function y = PLIIencode(x)
% PLIIencode Version 1.0.1
% Programmed by Drew Weymouth
%
% Encodes discrete 5-channel surround-sound signal into stereo matrix-encoded
% signal based on the Dolby Pro-Logic II matrix. When played back on
% home theater receivers with Pro-Logic II decoding, the stereo signal will
% be upmixed to an approximation of the original 5-channel signal. A sixth
% subwoofer channel may be included in the input, but if present it will be
% mixed into the center channel.
%
% The input x should be as follows:
% x(:,1) = FRONT LEFT
% x(:,2) = FRONT RIGHT
% x(:,3) = CENTER
% x(:,4) = REAR LEFT
% x(:,5) = REAR RIGHT
% x(:,6) = SUBWOOFER (optional)
%
% This function requires that the Signal Processing Toolbox be installed as
% it makes use of the function hilbert.
%
% NOTE: Pro-Logic is a registered trademark of Dolby Laboratories.
% The matrix encoding coefficients are obtained from Wikipedia:
% http://en.wikipedia.org/wiki/Pro-Logic#Dolby_encoding_matrices
%
% check validity of input and initialize the output
[nr,nc] = size(x);
if nc < 5 || nc > 6
error('Input signal must contain five or six (5.0/5.1) channels.')
end
if ~isreal(x), error('Input signal must be real-valued.'); end
if nc == 6
x(:,3) = x(:,3) + x(:,6);
x = x(:,1:5);
end
y = zeros(nr,2);
% take Hilbert transform of rear channels to provide a -j (-90 degrees)
% phase shift at all frequencies
x(:,4:5) = imag(hilbert(x(:,4:5)));
% Sum up all the contributions to the L and R channels of y, using the
% Pro-Logic II matrix coefficients
y(:,1) = x(:,1) + sqrt(.5)*x(:,3) + sqrt(19/25)*x(:,4) + sqrt(6/25)*x(:,5);
y(:,2) = x(:,2) + sqrt(.5)*x(:,3) - sqrt(6/25)*x(:,4) - sqrt(19/25)*x(:,5);
% ...and normalize to [-1,1]
y = y/max(max(abs(y)));