%Funciton THR_ADAPT_DYN - Adaptive threshold for general VAD criterial function.
%
%Usage: [out,Dv,Dpv]=thr_adapt_dyn(Dv,[perc,Dynmin,qmax1,qmax2,qmin1,qmin2]);              
%Input parameters:
%  Dv     - vector with dsitance function (criterial function)
%Optional input parameters:                                    <Default values>
%  perc   - placement of threshold in dynamic range                        <20>
%  Dynmin - Minimal dynamics (default value for energy)                  <1e-4>
%  qmax1  - forgetting parameter for increase of maximum                  <0.8>
%  qmax2  - forgetting parameter for decrease of maximum                <0.995>
%  qmin1  - forgetting parameter for increase of minimum                  <0.8>
%  qmin2  - forgetting parameter for decrease of minimum               <0.9999>
%Output parameters:
%  out    - output vector with values 0 or 1 for pause or speech
%  Dv     - vector with current distance (input)
%  Dpv    - vector with current thresholds 

%                              Made by PP
%                             CVUT FEL K331
%                         Last change 20/3/2012

function [out,Dv,Dpv,Dmaxv,Dminv]=thr_adapt_dyn(Dv,perc,Dynmin,qmax1,qmax2,qmin1,qmin2);

if nargin<2,
  perc=10;
end;
if nargin<3,
  Dynmin=1e-4;  
end;
if nargin<4,
  qmax1=0.8;  
end;
if nargin<5,
  qmax2=0.995;  
end;
if nargin<6,
  qmin1=0.8;  
end;
if nargin<7,
  qmin2=0.9999;  
end;


out=[];
Dpv=[];
Dmaxv=[];
Dminv=[];

wnum=length(Dv);

Dmax=max(Dv(1:2))+Dynmin/10;
Dmin=min(Dv(1:2))-Dynmin/10;
Dyn=Dmax-Dmin;

 
for i=1:wnum,

  D=Dv(i);


  if ( D > Dmax )
    Dmax = qmax1*Dmax + (1-qmax1)*D ; 
  else
    Dmax = qmax2*Dmax + (1-qmax2)*D ;
  end

  if ( D < Dmin )
    Dmin = qmin1*Dmin + (1-qmin1)*D ;
  else
    Dmin = qmin2*Dmin + (1-qmin2)*D ;
  end

  Dyn=Dmax-Dmin ;

  Dp=Dmin+perc/100*(Dmax-Dmin);

  Dpv=[Dpv Dp];
  Dmaxv=[Dmaxv Dmax];
  Dminv=[Dminv Dmin];

  if ( D>Dp & Dyn > Dynmin),
    out=[out 1];
  else
    out=[out 0];
  end;

end;


out=out(:);
Dv=Dv(:);
Dpv=Dpv(:);  
Dmaxv=Dmaxv(:);  
Dminv=Dminv(:);  

if nargout < 1,
  figure(gcf); clf;
  x=1:length(out);
  subplot(211);
  plot(x,Dv,'r-',x,Dpv,'b--',x,Dmaxv,'b--',x,Dminv,'--');
  title('Distance and adaptive threshold');
  xlabel('Frame No.');
  ylabel('Dv');
  
  subplot(212)
  plot(x,out,'g.-');
  title('Final detection');
  xlabel('Frame No.');
  ylabel('out');
end;

