clear
close all

system('ffmpeg -i Eli.mp4 -c copy audio.aac')
system('ffmpeg -i Eli.mp4 -an -c copy video.mp4')

[in,fs] = audioread('audio.aac');
% Original channel order:  L R C lfe sL sR
in = in(:,[1 2 3 5 6 4]);   % Rearrange channel order to: L R C sL sR lfe

SOFAstart;
hrtf = SOFAload('FABIAN_HRIR_measured_HATO_0.sofa');
fs_hrtf = hrtf.Data.SamplingRate;
hrtfData = hrtf.Data.IR;
sourcePosition = hrtf.SourcePosition;
%%
LS_pos  = [  30 ,0;     % L
            330 ,0;     % R
             0  ,0;     % C
            110 ,0;     % SL
            250 ,0];    % SR
       
indz = zeros(size(LS_pos,1),1);
for n = 1 : size(LS_pos,1)
    [~,ind] = min( sum(  (bsxfun(@minus, sourcePosition(:,1:2) ,mod(LS_pos(n,:),360))).^2,2  ) );
    indz(n) = ind;
end
HRTFs = hrtfData(indz,:,:);
%%
if (fs-fs_hrtf)>1e-6
    HRTF_res = zeros(size(HRTFs,1),size(HRTFs,2),ceil(size(HRTFs,3)*fs/fs_hrtf));
    for n = 1 : size(HRTFs,1)
        for m = 1 : size(HRTFs,2)
            HRTF_res(n,m,:) = resample(HRTFs(n,m,:),fs,fs_hrtf);
        end
    end
    HRTFs = HRTF_res;
end

%%
output = zeros( size(in,1), 2);
for n = 1 : size(LS_pos,1)
    output(:,1) = output(:,1) + conv( in(:,n), squeeze(HRTFs(n,1,:)) ,'same');
    output(:,2) = output(:,2) + conv( in(:,n), squeeze(HRTFs(n,2,:)) ,'same');
end
output = bsxfun( @plus, output, 2*in(:,6));
output = output/max(max(abs(output)));
%%
audiowrite('Eli_binaural.wav',output,fs);
system('ffmpeg -i video.mp4 -i Eli_binaural.wav -vcodec copy output.mp4')
dos(['"' 'C:\Program Files\VideoLAN\VLC\vlc.exe' '" "' 'output.mp4' '" &']);