annotate dsp/tempotracking/TempoTrackV2.cpp @ 327:8252d055bd00

Now includes latest changes from MEPD: * TempoTrackV2::calculatebeats method - exposes "alpha" and "tightness" parameters * TempoTrackV2::calculateBeatPeriod - user can specify an inputtempo (in BPM) and "constraintempo" (bool)
author luisf <luis.figueira@eecs.qmul.ac.uk>
date Wed, 12 Dec 2012 15:10:38 +0000
parents d5014ab8b0e5
children 1e433aaa44ad
rev   line source
c@277 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
c@277 2
c@277 3 /*
c@277 4 QM DSP Library
c@277 5
c@277 6 Centre for Digital Music, Queen Mary, University of London.
c@277 7 This file copyright 2008-2009 Matthew Davies and QMUL.
c@309 8
c@309 9 This program is free software; you can redistribute it and/or
c@309 10 modify it under the terms of the GNU General Public License as
c@309 11 published by the Free Software Foundation; either version 2 of the
c@309 12 License, or (at your option) any later version. See the file
c@309 13 COPYING included with this distribution for more information.
c@277 14 */
c@277 15
c@277 16 #include "TempoTrackV2.h"
c@277 17
c@277 18 #include <cmath>
c@277 19 #include <cstdlib>
c@278 20 #include <iostream>
c@277 21
c@279 22 #include "maths/MathUtilities.h"
c@277 23
c@277 24 #define EPS 0.0000008 // just some arbitrary small number
c@277 25
c@279 26 TempoTrackV2::TempoTrackV2(float rate, size_t increment) :
c@279 27 m_rate(rate), m_increment(increment) { }
c@277 28 TempoTrackV2::~TempoTrackV2() { }
c@277 29
c@277 30 void
c@277 31 TempoTrackV2::filter_df(d_vec_t &df)
c@277 32 {
c@278 33 d_vec_t a(3);
c@278 34 d_vec_t b(3);
c@278 35 d_vec_t lp_df(df.size());
c@277 36
c@278 37 //equivalent in matlab to [b,a] = butter(2,0.4);
c@278 38 a[0] = 1.0000;
c@278 39 a[1] = -0.3695;
c@278 40 a[2] = 0.1958;
c@278 41 b[0] = 0.2066;
c@278 42 b[1] = 0.4131;
c@278 43 b[2] = 0.2066;
luis@327 44
c@278 45 double inp1 = 0.;
c@278 46 double inp2 = 0.;
c@278 47 double out1 = 0.;
c@278 48 double out2 = 0.;
c@277 49
c@277 50
c@278 51 // forwards filtering
c@295 52 for (unsigned int i = 0;i < df.size();i++)
c@278 53 {
c@278 54 lp_df[i] = b[0]*df[i] + b[1]*inp1 + b[2]*inp2 - a[1]*out1 - a[2]*out2;
c@278 55 inp2 = inp1;
c@278 56 inp1 = df[i];
c@278 57 out2 = out1;
c@278 58 out1 = lp_df[i];
c@278 59 }
c@277 60
c@278 61 // copy forwards filtering to df...
c@278 62 // but, time-reversed, ready for backwards filtering
c@295 63 for (unsigned int i = 0;i < df.size();i++)
c@278 64 {
c@278 65 df[i] = lp_df[df.size()-i-1];
c@278 66 }
c@277 67
c@295 68 for (unsigned int i = 0;i < df.size();i++)
c@278 69 {
luis@327 70 lp_df[i] = 0.;
c@278 71 }
c@277 72
c@278 73 inp1 = 0.; inp2 = 0.;
c@278 74 out1 = 0.; out2 = 0.;
c@277 75
c@277 76 // backwards filetering on time-reversed df
c@295 77 for (unsigned int i = 0;i < df.size();i++)
c@278 78 {
c@278 79 lp_df[i] = b[0]*df[i] + b[1]*inp1 + b[2]*inp2 - a[1]*out1 - a[2]*out2;
c@278 80 inp2 = inp1;
c@278 81 inp1 = df[i];
c@278 82 out2 = out1;
c@278 83 out1 = lp_df[i];
c@278 84 }
c@277 85
c@277 86 // write the re-reversed (i.e. forward) version back to df
c@295 87 for (unsigned int i = 0;i < df.size();i++)
c@278 88 {
c@278 89 df[i] = lp_df[df.size()-i-1];
c@278 90 }
c@277 91 }
c@277 92
c@277 93
luis@327 94 // MEPD 28/11/12
luis@327 95 // This function now allows for a user to specify an inputtempo (in BPM)
luis@327 96 // and a flag "constraintempo" which replaces the general rayleigh weighting for periodicities
luis@327 97 // with a gaussian which is centered around the input tempo
luis@327 98 // Note, if inputtempo = 120 and constraintempo = false, then functionality is
luis@327 99 // as it was before
c@277 100 void
c@304 101 TempoTrackV2::calculateBeatPeriod(const vector<double> &df,
c@304 102 vector<double> &beat_period,
luis@327 103 vector<double> &tempi,
luis@327 104 double inputtempo, bool constraintempo)
c@277 105 {
c@278 106 // to follow matlab.. split into 512 sample frames with a 128 hop size
c@278 107 // calculate the acf,
c@278 108 // then the rcf.. and then stick the rcfs as columns of a matrix
c@278 109 // then call viterbi decoding with weight vector and transition matrix
c@278 110 // and get best path
c@277 111
c@295 112 unsigned int wv_len = 128;
luis@327 113
luis@327 114 // MEPD 28/11/12
luis@327 115 // the default value of inputtempo in the beat tracking plugin is 120
luis@327 116 // so if the user specifies a different inputtempo, the rayparam will be updated
luis@327 117 // accordingly.
luis@327 118 // note: 60*44100/512 is a magic number
luis@327 119 // this might (will?) break if a user specifies a different frame rate for the onset detection function
luis@327 120 double rayparam = (60*44100/512)/inputtempo;
luis@327 121
luis@327 122 // these debug statements can be removed.
luis@327 123 std::cout << "inputtempo" << inputtempo << std::endl;
luis@327 124 std::cout << "rayparam" << rayparam << std::endl;
luis@327 125 std::cout << "constraintempo" << constraintempo << std::endl;
c@277 126
c@278 127 // make rayleigh weighting curve
c@278 128 d_vec_t wv(wv_len);
luis@327 129
luis@327 130 // check whether or not to use rayleigh weighting (if constraintempo is false)
luis@327 131 // or use gaussian weighting it (constraintempo is true)
luis@327 132 if (constraintempo)
c@277 133 {
luis@327 134 for (unsigned int i=0; i<wv.size(); i++)
luis@327 135 {
luis@327 136 // MEPD 28/11/12
luis@327 137 // do a gaussian weighting instead of rayleigh
luis@327 138 wv[i] = exp( (-1.*pow((static_cast<double> (i)-rayparam),2.)) / (2.*pow(rayparam/4.,2.)) );
luis@327 139 }
luis@327 140 }
luis@327 141 else
luis@327 142 {
luis@327 143 for (unsigned int i=0; i<wv.size(); i++)
luis@327 144 {
luis@327 145 // MEPD 28/11/12
luis@327 146 // standard rayleigh weighting over periodicities
luis@327 147 wv[i] = (static_cast<double> (i) / pow(rayparam,2.)) * exp((-1.*pow(-static_cast<double> (i),2.)) / (2.*pow(rayparam,2.)));
luis@327 148 }
c@277 149 }
c@277 150
c@278 151 // beat tracking frame size (roughly 6 seconds) and hop (1.5 seconds)
c@295 152 unsigned int winlen = 512;
c@295 153 unsigned int step = 128;
c@278 154
c@278 155 // matrix to store output of comb filter bank, increment column of matrix at each frame
c@278 156 d_mat_t rcfmat;
c@278 157 int col_counter = -1;
c@278 158
c@278 159 // main loop for beat period calculation
c@295 160 for (unsigned int i=0; i+winlen<df.size(); i+=step)
c@278 161 {
c@278 162 // get dfframe
c@278 163 d_vec_t dfframe(winlen);
c@295 164 for (unsigned int k=0; k<winlen; k++)
c@278 165 {
c@278 166 dfframe[k] = df[i+k];
c@278 167 }
c@278 168 // get rcf vector for current frame
luis@327 169 d_vec_t rcf(wv_len);
c@278 170 get_rcf(dfframe,wv,rcf);
luis@327 171
c@278 172 rcfmat.push_back( d_vec_t() ); // adds a new column
c@278 173 col_counter++;
c@295 174 for (unsigned int j=0; j<rcf.size(); j++)
c@278 175 {
c@278 176 rcfmat[col_counter].push_back( rcf[j] );
c@278 177 }
c@278 178 }
luis@327 179
c@278 180 // now call viterbi decoding function
c@278 181 viterbi_decode(rcfmat,wv,beat_period,tempi);
c@277 182 }
c@277 183
c@277 184
c@277 185 void
c@277 186 TempoTrackV2::get_rcf(const d_vec_t &dfframe_in, const d_vec_t &wv, d_vec_t &rcf)
c@277 187 {
c@278 188 // calculate autocorrelation function
c@278 189 // then rcf
c@278 190 // just hard code for now... don't really need separate functions to do this
c@277 191
c@278 192 // make acf
c@277 193
c@278 194 d_vec_t dfframe(dfframe_in);
c@277 195
c@279 196 MathUtilities::adaptiveThreshold(dfframe);
c@277 197
c@278 198 d_vec_t acf(dfframe.size());
c@277 199
luis@327 200
c@295 201 for (unsigned int lag=0; lag<dfframe.size(); lag++)
c@278 202 {
c@278 203 double sum = 0.;
c@278 204 double tmp = 0.;
c@277 205
c@295 206 for (unsigned int n=0; n<(dfframe.size()-lag); n++)
c@278 207 {
luis@327 208 tmp = dfframe[n] * dfframe[n+lag];
c@278 209 sum += tmp;
c@278 210 }
c@278 211 acf[lag] = static_cast<double> (sum/ (dfframe.size()-lag));
c@278 212 }
c@277 213
c@278 214 // now apply comb filtering
c@278 215 int numelem = 4;
luis@327 216
c@295 217 for (unsigned int i = 2;i < rcf.size();i++) // max beat period
c@278 218 {
c@278 219 for (int a = 1;a <= numelem;a++) // number of comb elements
c@278 220 {
c@278 221 for (int b = 1-a;b <= a-1;b++) // general state using normalisation of comb elements
c@278 222 {
c@278 223 rcf[i-1] += ( acf[(a*i+b)-1]*wv[i-1] ) / (2.*a-1.); // calculate value for comb filter row
c@278 224 }
c@278 225 }
c@278 226 }
luis@327 227
c@278 228 // apply adaptive threshold to rcf
c@279 229 MathUtilities::adaptiveThreshold(rcf);
luis@327 230
c@278 231 double rcfsum =0.;
c@295 232 for (unsigned int i=0; i<rcf.size(); i++)
c@278 233 {
c@278 234 rcf[i] += EPS ;
c@278 235 rcfsum += rcf[i];
c@278 236 }
c@277 237
c@278 238 // normalise rcf to sum to unity
c@295 239 for (unsigned int i=0; i<rcf.size(); i++)
c@277 240 {
c@278 241 rcf[i] /= (rcfsum + EPS);
c@277 242 }
c@277 243 }
c@277 244
c@277 245 void
c@278 246 TempoTrackV2::viterbi_decode(const d_mat_t &rcfmat, const d_vec_t &wv, d_vec_t &beat_period, d_vec_t &tempi)
c@277 247 {
c@278 248 // following Kevin Murphy's Viterbi decoding to get best path of
c@278 249 // beat periods through rfcmat
c@277 250
c@278 251 // make transition matrix
c@278 252 d_mat_t tmat;
c@295 253 for (unsigned int i=0;i<wv.size();i++)
c@278 254 {
c@278 255 tmat.push_back ( d_vec_t() ); // adds a new column
c@295 256 for (unsigned int j=0; j<wv.size(); j++)
luis@327 257 {
c@278 258 tmat[i].push_back(0.); // fill with zeros initially
c@278 259 }
c@278 260 }
luis@327 261
c@278 262 // variance of Gaussians in transition matrix
c@278 263 // formed of Gaussians on diagonal - implies slow tempo change
c@278 264 double sigma = 8.;
c@278 265 // don't want really short beat periods, or really long ones
c@295 266 for (unsigned int i=20;i <wv.size()-20; i++)
c@278 267 {
c@295 268 for (unsigned int j=20; j<wv.size()-20; j++)
luis@327 269 {
c@278 270 double mu = static_cast<double>(i);
c@278 271 tmat[i][j] = exp( (-1.*pow((j-mu),2.)) / (2.*pow(sigma,2.)) );
c@278 272 }
c@278 273 }
c@277 274
c@278 275 // parameters for Viterbi decoding... this part is taken from
c@278 276 // Murphy's matlab
c@277 277
c@278 278 d_mat_t delta;
c@278 279 i_mat_t psi;
c@295 280 for (unsigned int i=0;i <rcfmat.size(); i++)
c@278 281 {
c@278 282 delta.push_back( d_vec_t());
c@278 283 psi.push_back( i_vec_t());
c@295 284 for (unsigned int j=0; j<rcfmat[i].size(); j++)
luis@327 285 {
c@278 286 delta[i].push_back(0.); // fill with zeros initially
c@278 287 psi[i].push_back(0); // fill with zeros initially
c@278 288 }
c@278 289 }
c@277 290
c@277 291
c@295 292 unsigned int T = delta.size();
c@281 293
c@281 294 if (T < 2) return; // can't do anything at all meaningful
c@281 295
c@295 296 unsigned int Q = delta[0].size();
c@277 297
c@278 298 // initialize first column of delta
c@295 299 for (unsigned int j=0; j<Q; j++)
c@277 300 {
c@278 301 delta[0][j] = wv[j] * rcfmat[0][j];
c@278 302 psi[0][j] = 0;
c@277 303 }
luis@327 304
c@277 305 double deltasum = 0.;
c@295 306 for (unsigned int i=0; i<Q; i++)
c@277 307 {
c@278 308 deltasum += delta[0][i];
luis@327 309 }
c@295 310 for (unsigned int i=0; i<Q; i++)
c@277 311 {
c@278 312 delta[0][i] /= (deltasum + EPS);
luis@327 313 }
c@277 314
c@277 315
c@295 316 for (unsigned int t=1; t<T; t++)
c@278 317 {
c@278 318 d_vec_t tmp_vec(Q);
c@277 319
c@295 320 for (unsigned int j=0; j<Q; j++)
c@278 321 {
c@295 322 for (unsigned int i=0; i<Q; i++)
c@278 323 {
c@278 324 tmp_vec[i] = delta[t-1][i] * tmat[j][i];
luis@327 325 }
luis@327 326
luis@327 327 delta[t][j] = get_max_val(tmp_vec);
c@277 328
c@278 329 psi[t][j] = get_max_ind(tmp_vec);
luis@327 330
c@278 331 delta[t][j] *= rcfmat[t][j];
c@278 332 }
c@277 333
c@278 334 // normalise current delta column
c@278 335 double deltasum = 0.;
c@295 336 for (unsigned int i=0; i<Q; i++)
c@278 337 {
c@278 338 deltasum += delta[t][i];
luis@327 339 }
c@295 340 for (unsigned int i=0; i<Q; i++)
c@278 341 {
c@278 342 delta[t][i] /= (deltasum + EPS);
luis@327 343 }
c@278 344 }
c@277 345
c@278 346 i_vec_t bestpath(T);
c@278 347 d_vec_t tmp_vec(Q);
c@295 348 for (unsigned int i=0; i<Q; i++)
luis@327 349 {
c@278 350 tmp_vec[i] = delta[T-1][i];
c@278 351 }
c@277 352
c@278 353 // find starting point - best beat period for "last" frame
c@278 354 bestpath[T-1] = get_max_ind(tmp_vec);
luis@327 355
c@278 356 // backtrace through index of maximum values in psi
c@295 357 for (unsigned int t=T-2; t>0 ;t--)
c@278 358 {
c@278 359 bestpath[t] = psi[t+1][bestpath[t+1]];
c@278 360 }
c@277 361
c@278 362 // weird but necessary hack -- couldn't get above loop to terminate at t >= 0
c@278 363 bestpath[0] = psi[1][bestpath[1]];
c@277 364
c@295 365 unsigned int lastind = 0;
c@295 366 for (unsigned int i=0; i<T; i++)
luis@327 367 {
c@295 368 unsigned int step = 128;
c@295 369 for (unsigned int j=0; j<step; j++)
c@278 370 {
c@278 371 lastind = i*step+j;
c@278 372 beat_period[lastind] = bestpath[i];
c@278 373 }
c@282 374 // std::cerr << "bestpath[" << i << "] = " << bestpath[i] << " (used for beat_periods " << i*step << " to " << i*step+step-1 << ")" << std::endl;
c@278 375 }
c@277 376
c@278 377 //fill in the last values...
c@295 378 for (unsigned int i=lastind; i<beat_period.size(); i++)
c@278 379 {
c@278 380 beat_period[i] = beat_period[lastind];
c@278 381 }
c@277 382
c@295 383 for (unsigned int i = 0; i < beat_period.size(); i++)
c@277 384 {
c@279 385 tempi.push_back((60. * m_rate / m_increment)/beat_period[i]);
c@277 386 }
c@277 387 }
c@277 388
c@277 389 double
c@277 390 TempoTrackV2::get_max_val(const d_vec_t &df)
c@277 391 {
c@278 392 double maxval = 0.;
c@295 393 for (unsigned int i=0; i<df.size(); i++)
c@277 394 {
c@278 395 if (maxval < df[i])
c@278 396 {
c@278 397 maxval = df[i];
c@278 398 }
c@277 399 }
luis@327 400
c@278 401 return maxval;
c@277 402 }
c@277 403
c@277 404 int
c@277 405 TempoTrackV2::get_max_ind(const d_vec_t &df)
c@277 406 {
c@278 407 double maxval = 0.;
c@278 408 int ind = 0;
c@295 409 for (unsigned int i=0; i<df.size(); i++)
c@277 410 {
c@278 411 if (maxval < df[i])
c@278 412 {
c@278 413 maxval = df[i];
c@278 414 ind = i;
c@278 415 }
c@277 416 }
luis@327 417
c@278 418 return ind;
c@277 419 }
c@277 420
c@277 421 void
c@277 422 TempoTrackV2::normalise_vec(d_vec_t &df)
c@277 423 {
c@278 424 double sum = 0.;
c@295 425 for (unsigned int i=0; i<df.size(); i++)
c@278 426 {
c@278 427 sum += df[i];
c@278 428 }
luis@327 429
c@295 430 for (unsigned int i=0; i<df.size(); i++)
c@278 431 {
c@278 432 df[i]/= (sum + EPS);
c@278 433 }
c@277 434 }
c@277 435
luis@327 436 // MEPD 28/11/12
luis@327 437 // this function has been updated to allow the "alpha" and "tightness" parameters
luis@327 438 // of the dynamic program to be set by the user
luis@327 439 // the default value of alpha = 0.9 and tightness = 4
c@277 440 void
c@304 441 TempoTrackV2::calculateBeats(const vector<double> &df,
c@304 442 const vector<double> &beat_period,
luis@327 443 vector<double> &beats, double alpha, double tightness)
c@277 444 {
c@281 445 if (df.empty() || beat_period.empty()) return;
c@281 446
c@278 447 d_vec_t cumscore(df.size()); // store cumulative score
c@278 448 i_vec_t backlink(df.size()); // backlink (stores best beat locations at each time instant)
c@278 449 d_vec_t localscore(df.size()); // localscore, for now this is the same as the detection function
c@277 450
c@295 451 for (unsigned int i=0; i<df.size(); i++)
c@277 452 {
c@278 453 localscore[i] = df[i];
c@278 454 backlink[i] = -1;
c@277 455 }
c@277 456
luis@327 457 //double tightness = 4.;
luis@327 458 //double alpha = 0.9;
luis@327 459 // MEPD 28/11/12
luis@327 460 // debug statements that can be removed.
luis@327 461 std::cout << "alpha" << alpha << std::endl;
luis@327 462 std::cout << "tightness" << tightness << std::endl;
c@277 463
c@278 464 // main loop
c@295 465 for (unsigned int i=0; i<localscore.size(); i++)
c@278 466 {
c@278 467 int prange_min = -2*beat_period[i];
c@278 468 int prange_max = round(-0.5*beat_period[i]);
c@277 469
c@278 470 // transition range
c@278 471 d_vec_t txwt (prange_max - prange_min + 1);
c@278 472 d_vec_t scorecands (txwt.size());
c@277 473
c@295 474 for (unsigned int j=0;j<txwt.size();j++)
c@278 475 {
c@278 476 double mu = static_cast<double> (beat_period[i]);
c@278 477 txwt[j] = exp( -0.5*pow(tightness * log((round(2*mu)-j)/mu),2));
c@277 478
c@278 479 // IF IN THE ALLOWED RANGE, THEN LOOK AT CUMSCORE[I+PRANGE_MIN+J
c@278 480 // ELSE LEAVE AT DEFAULT VALUE FROM INITIALISATION: D_VEC_T SCORECANDS (TXWT.SIZE());
c@277 481
c@278 482 int cscore_ind = i+prange_min+j;
luis@327 483 if (cscore_ind >= 0)
c@278 484 {
c@278 485 scorecands[j] = txwt[j] * cumscore[cscore_ind];
c@278 486 }
c@278 487 }
c@277 488
c@278 489 // find max value and index of maximum value
c@278 490 double vv = get_max_val(scorecands);
c@278 491 int xx = get_max_ind(scorecands);
c@277 492
c@278 493 cumscore[i] = alpha*vv + (1.-alpha)*localscore[i];
c@278 494 backlink[i] = i+prange_min+xx;
c@280 495
c@282 496 // std::cerr << "backlink[" << i << "] <= " << backlink[i] << std::endl;
c@278 497 }
c@278 498
c@278 499 // STARTING POINT, I.E. LAST BEAT.. PICK A STRONG POINT IN cumscore VECTOR
c@278 500 d_vec_t tmp_vec;
c@295 501 for (unsigned int i=cumscore.size() - beat_period[beat_period.size()-1] ; i<cumscore.size(); i++)
c@278 502 {
c@278 503 tmp_vec.push_back(cumscore[i]);
luis@327 504 }
c@278 505
c@278 506 int startpoint = get_max_ind(tmp_vec) + cumscore.size() - beat_period[beat_period.size()-1] ;
c@278 507
c@281 508 // can happen if no results obtained earlier (e.g. input too short)
c@281 509 if (startpoint >= backlink.size()) startpoint = backlink.size()-1;
c@281 510
c@278 511 // USE BACKLINK TO GET EACH NEW BEAT (TOWARDS THE BEGINNING OF THE FILE)
c@278 512 // BACKTRACKING FROM THE END TO THE BEGINNING.. MAKING SURE NOT TO GO BEFORE SAMPLE 0
c@278 513 i_vec_t ibeats;
c@278 514 ibeats.push_back(startpoint);
c@282 515 // std::cerr << "startpoint = " << startpoint << std::endl;
c@278 516 while (backlink[ibeats.back()] > 0)
c@278 517 {
c@282 518 // std::cerr << "backlink[" << ibeats.back() << "] = " << backlink[ibeats.back()] << std::endl;
c@281 519 int b = ibeats.back();
c@281 520 if (backlink[b] == b) break; // shouldn't happen... haha
c@281 521 ibeats.push_back(backlink[b]);
c@278 522 }
luis@327 523
c@278 524 // REVERSE SEQUENCE OF IBEATS AND STORE AS BEATS
c@295 525 for (unsigned int i=0; i<ibeats.size(); i++)
luis@327 526 {
c@278 527 beats.push_back( static_cast<double>(ibeats[ibeats.size()-i-1]) );
c@278 528 }
c@277 529 }
c@277 530
c@277 531