% FUNCTION FRAMESEG = TIMESEG2FRAMESEG( TIMESEG, FRAMELENGTH, FRAMESHIFT )
%
% Version 1 - 030910
% lathoud@idiap.ch
%
% Function that maps a segmentation of concurrent speakers in time domain
% (i.e. expressed in seconds) to a binary matrix of nChannels - by - nFrames.
%
%%%% Input values:
%
% TIMESEG: an object defining segmentation of concurrent speakers,
% as read by READ_TIMESEG. Fields are:
% - TIMESEG.nChannels:  an integer defining the number of speakers
% - TIMESEG.startTime:  a float, in seconds, beginning of the segmentation.
% - TIMESEG.endTime:    a float, in seconds, end of the segmentation.
% - TIMESEG.seg:        a list of nChannels matrices. Each matrix defines
% the speech/non-speech segmentation for one speaker: each column is a segment.
%   - row 1 is start of the segment in seconds.
%   - row 2 is end of the segment in seconds.
%   - row 3 is 0 or 1. 0 means non-speech, 1 means speech.
%
% FRAMELENGTH:  in seconds (e.g. 0.032).
%
% FRAMESHIFT: in seconds (e.g. 0.016). By default FRAMELENGTH / 2.
%
%%%% Output value:
%
% FRAMESEG: nChannels - by - nFrames matrix of zeroes and ones.
% - if FRAMESEG( i, j ) == 0: speaker i is silent at frame j.
% - if FRAMESEG( i, j ) == 1: speaker i is speaking at frame j.

function frameseg = timeseg2frameseg( timeseg, framelength, frameshift )
  
  if nargin < 2
    error( 'timeseg2frameseg needs at least 2 parameters' );
  end
  
  if nargin < 3
    frameshift = [];
  end
  if isempty( frameshift )
    frameshift = framelength / 2;
  end
  
  % Define frames
  nFrames = 1 + floor( ( timeseg.endTime - timeseg.startTime - framelength ) / frameshift );
  frameCenter = timeseg.startTime + framelength / 2 + frameshift * (0:nFrames-1);
  
  % Map time-domain segmentation to frame-domain segmentation
  frameseg = zeros( timeseg.nChannels, nFrames );
  for a = 1:timeseg.nChannels
    m = timeseg.seg{ a };
    speechSegments = find( m(3,:) );

    for b = 1:length( speechSegments )
      iSegment = speechSegments( b );
      start = m( 1, iSegment );
      finish = m( 2, iSegment );
      frameseg( a, find( ( frameCenter >= start ) & ( frameCenter <= finish ) ) ) = 1;
    end
  
  end
  