%%% interpdemo.m
%%%
%%% Demonstrates interpolation
%%%
%%% by Prof. Brian L. Evans, bevans@ece.utexas.edu
%%% The University of Texas at Austin
%%%
%%% Version: 10/22/16	@(#)interpdemo.m	1.2
%%% Created: October 23, 2015
%%%
%%% This Matlab script will play three sounds:
%%% (1) low-frequency signal (baseband signal)
%%% (2) upsampled signal
%%% (3) interpolation using rectangular pulse
%%% (4) interpolation using triangular pulse
%%% (5) interpolation using truncated sinc pulse

fs = 8000;           %%% Sampling rate
Ts = 1/fs;           %%% Sampling time
tmax = 4;            %%% Signals last tmax seconds
nmax = tmax*fs;
n = 1 : nmax; 

%%% Generate baseband signal
f1 = 600;
basebandInput = cos(2*pi*(f1/fs)*n);

%%% Upsampled signal
upsampleFactor = 6;
upsampledSignal = zeros(length(basebandInput)*upsampleFactor, 1);
upsampledSignal(1 : upsampleFactor : nmax*upsampleFactor) = basebandInput;
fs2 = upsampleFactor * fs;

%%% Interpolation using a rectangular pulse
%%% Normalize rectangular pulse to have unit area.
rectPulse = ones(upsampleFactor, 1);
rectPulse = rectPulse / sum(abs(rectPulse));
interpolationByRect = conv(rectPulse, upsampledSignal);

%%% Interpolation using a triangular pulse
%%% Triangular pulse spans two periods
%%% Normalize triangular pulse to have unit area.
triWidth = 2*upsampleFactor + 1;
triPulse = tripuls( linspace(-upsampleFactor,upsampleFactor,triWidth), triWidth-2 );
triPulse = triPulse / sum(abs(triPulse));
interpolationByTri = conv(triPulse, upsampledSignal);

%%% Interpolation using a truncated sinc pulse
%%% Normalize sinc pulse to have unit area.
numberPeriods = 4;
sincWidth = numberPeriods*upsampleFactor + 1;
leftIndex = -(numberPeriods/2)*upsampleFactor;
rightIndex = (numberPeriods/2)*upsampleFactor;
indexVector = linspace(leftIndex, rightIndex, sincWidth);
sincPulse = sinc( indexVector / upsampleFactor );
sincPulse = (5/3) * sincPulse / sum(abs(sincPulse));
interpolationBySinc = conv(sincPulse, upsampledSignal);

%%% Playback signals
figure;
plotspec(basebandInput, 1/fs);
title(num2str(f1, 'Cosine at %d Hz'));
sound(basebandInput, fs);

pause(tmax+1);

figure;
plotspec(upsampledSignal, 1/fs2);
title(num2str(upsampleFactor, 'Cosine Upsampled by %d'));
sound(basebandInput, fs);

pause(tmax+1);

figure;
plotspec(interpolationByRect, 1/fs2);
title('Interpolation Using a Rectangular Pulse');
sound(interpolationByRect, fs2);

pause(tmax+1);

figure;
plotspec(interpolationByTri, 1/fs2);
title('Interpolation Using a Triangular Pulse');
sound(interpolationByTri, fs2);

pause(tmax+1);

figure;
plotspec(interpolationBySinc, 1/fs2);
title('Interpolation Using a Truncated Sinc');
sound(interpolationBySinc, fs2);
