% AAB and FG 10/2018
% 
% Running this script will load an audio file, vocode it, and play it back.
%
% 2018 CBU Matlab Course

%% Initialization

clear
close all

%% Parameters

% Parameters of the vocoder
audio_in_filename = 'audio_example_1.wav'; % Audio sample to be vocoded
freq_range_Hz = [250 8000]; % Frequency range for vocoder from low cutoff
                            % of lowest channel to high cutoff of highest channel (in Hz)
num_chan = 8; % Number of frequency channels
env_freq_Hz = 30; % Cutoff frequency for lowpass envelope smoothing filter
filt_ord = 6; % Filter order
noiseband_rms = 0.1;

% Visualisation parameters
freq_range_to_show_Hz = [0 8000]; % Which range of frequencies to show in the plots

% Parameters from above constants
low_freq_Hz = freq_range_Hz(1); % Lowest channel frequency lower cutoff
high_freq_Hz = freq_range_Hz(2); % Highest channel frequency upper cutoff


%% Load input speech signal

[input_no_DC, samp_freq_Hz, len_sig_samp, len_sig_sec, nyquist_freq_Hz] = ...
    load_signal(audio_in_filename);

%% Visualize signal

title_string = 'Original signal';

% Time and Frequency analysis
visualize_signal(input_no_DC, samp_freq_Hz, freq_range_to_show_Hz, title_string)

% Spectrogram analysis 
spectrogram_analysis(input_no_DC, samp_freq_Hz, freq_range_to_show_Hz, title_string)

%% Define filterbank (make it equal log-spaced for now)

[lower_freq, upper_freq, center_freq, filterbank] = make_filterbank(num_chan, filt_ord, low_freq_Hz, high_freq_Hz, nyquist_freq_Hz); % Function to create filterbank

%% Create carriers (sine, 1 sine tone, complex (rand phase) - (possibly noise))

sine_tones = zeros(num_chan,len_sig_samp);
noise_bands = zeros(num_chan,len_sig_samp);

for ii = 1:num_chan
    
    sine_tones(ii,:) = make_sine(center_freq(ii), 0, len_sig_sec, samp_freq_Hz);
    [noise_bands(ii,:), ~] = make_noise(noiseband_rms, lower_freq(ii), upper_freq(ii), len_sig_samp, samp_freq_Hz);

end

%% Define lowpass envelope filter

[env_filt(2,:), env_filt(1,:)] = butter(2, env_freq_Hz/nyquist_freq_Hz);

%% Analysis, smoothing, and envelope modulation (this can probably be split up into more loops for clarity...)

[filt_output, smth_filt_output, chan_level] = analysis_and_smoothing(input_no_DC, len_sig_samp, num_chan, filterbank, env_filt);

%% Visualize oscillations

visualize_oscillations(input_no_DC, filt_output, num_chan, samp_freq_Hz)
% visualize_oscillations(input_no_DC, smth_filt_output, num_chan, samp_freq_Hz)

%% Synthesis

 [output] = sine_synthesis(sine_tones, smth_filt_output, chan_level, len_sig_samp, num_chan);
%[output] = sine_synthesis(noise_bands, smth_filt_output, chan_level, len_sig_samp, num_chan);


%% Play input and output

sound(output,samp_freq_Hz);

%% Visualize output

title_string = 'Vocoded signal';

visualize_signal(output, samp_freq_Hz, freq_range_to_show_Hz, title_string)

