function [t,f0,pvx] = ptrack_yin(d,sr)
% [t,f0,pvx] = ptrack_yin(d,sr)
%    Run the yin pitch tracker on the waveform d (at sampling
%    frequency sr).
%    Returns three 1D vectors.  
%      t is the sample times at which pitches are estimated 
%          (typically uniformly spaced every 0.010 sec).  
%      f0 is the corresponding pitch value in Hz (which can be 
%          zero for unvoiced frames). 
%      pvx is the corresponding probability of voicing for each
%          frame (between 0 and 1).  Generally, a threshold of 0.5
%          is the best guess for actual voiced-unvoiced threshold.
%    This is supposed to be a generic framework for pitch trackers,
%    but in this case we'll run YIN.
% 2013-01-31 Dan Ellis dpwe@ee.columbia.edu

if ~isdeployed() && exist('yin','file') ~= 2
  addpath('yin')
end

R = yin(d,sr);

% Yin uses 32 sample hops
t = [0:32:(32*length(R.f0)-1)]/sr;

% this is the pitch in f0
f0 = 440*exp(R.f0*log(2));

% Use aperiodicity proportion to approximate P(vx)
% this gives p = 1.0 when ap = 0, and p = 0.5 when ap = 0.3
%pvx = 1 ./ (1 + (R.ap/0.3));
% ap0 better than ap?
pvx = 1 ./ (1 + (R.ap0/0.3));

% Set implausible pitches to zero?
f0(find(pvx < 0.5)) = 0;
