1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
6 Centre for Digital Music, Queen Mary, University of London.
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2 of the
11 License, or (at your option) any later version. See the file
12 COPYING included with this distribution for more information.
15 #include "BeatTrack.h"
17 #include <dsp/onsets/DetectionFunction.h>
18 #include <dsp/onsets/PeakPicking.h>
19 #include <dsp/tempotracking/TempoTrack.h>
20 #include <dsp/tempotracking/TempoTrackV2.h>
27 float BeatTracker::m_stepSecs = 0.01161; // 512 samples at 44100
35 BeatTrackerData(const DFConfig &config) : dfConfig(config) {
36 df = new DetectionFunction(config);
43 df = new DetectionFunction(dfConfig);
45 origin = Vamp::RealTime::zeroTime;
49 DetectionFunction *df;
50 vector<double> dfOutput;
51 Vamp::RealTime origin;
55 BeatTracker::BeatTracker(float inputSampleRate) :
56 Vamp::Plugin(inputSampleRate),
59 m_dfType(DF_COMPLEXSD),
60 m_alpha(0.9), // MEPD new exposed parameter for beat tracker, default value = 0.9 (as old version)
62 m_inputtempo(120.), // MEPD new exposed parameter for beat tracker, default value = 120. (as old version)
63 m_constraintempo(false), // MEPD new exposed parameter for beat tracker, default value = false (as old version)
64 // calling the beat tracker with these default parameters will give the same output as the previous existing version
70 BeatTracker::~BeatTracker()
76 BeatTracker::getIdentifier() const
78 return "qm-tempotracker";
82 BeatTracker::getName() const
84 return "Tempo and Beat Tracker";
88 BeatTracker::getDescription() const
90 return "Estimate beat locations and tempo";
94 BeatTracker::getMaker() const
96 return "Queen Mary, University of London";
100 BeatTracker::getPluginVersion() const
106 BeatTracker::getCopyright() const
108 return "Plugin by Christian Landone and Matthew Davies. Copyright (c) 2006-2013 QMUL - All Rights Reserved";
111 BeatTracker::ParameterList
112 BeatTracker::getParameterDescriptors() const
116 ParameterDescriptor desc;
118 desc.identifier = "method";
119 desc.name = "Beat Tracking Method";
120 desc.description = "Basic method to use ";
123 desc.defaultValue = METHOD_NEW;
124 desc.isQuantized = true;
125 desc.quantizeStep = 1;
126 desc.valueNames.push_back("Old");
127 desc.valueNames.push_back("New");
128 list.push_back(desc);
130 desc.identifier = "dftype";
131 desc.name = "Onset Detection Function Type";
132 desc.description = "Method used to calculate the onset detection function";
135 desc.defaultValue = 3;
136 desc.valueNames.clear();
137 desc.valueNames.push_back("High-Frequency Content");
138 desc.valueNames.push_back("Spectral Difference");
139 desc.valueNames.push_back("Phase Deviation");
140 desc.valueNames.push_back("Complex Domain");
141 desc.valueNames.push_back("Broadband Energy Rise");
142 list.push_back(desc);
144 desc.identifier = "whiten";
145 desc.name = "Adaptive Whitening";
146 desc.description = "Normalize frequency bin magnitudes relative to recent peak levels";
149 desc.defaultValue = 0;
150 desc.isQuantized = true;
151 desc.quantizeStep = 1;
153 desc.valueNames.clear();
154 list.push_back(desc);
156 // MEPD new exposed parameter - used in the dynamic programming part of the beat tracker
157 //Alpha Parameter of Beat Tracker
158 desc.identifier = "alpha";
160 desc.description = "Inertia - Flexibility Trade Off";
162 desc.maxValue = 0.99;
163 desc.defaultValue = 0.90;
165 desc.isQuantized = false;
166 list.push_back(desc);
168 // We aren't exposing tightness as a parameter, it's fixed at 4
170 // MEPD new exposed parameter - used in the periodicity estimation
172 desc.identifier = "inputtempo";
173 desc.name = "Tempo Hint";
174 desc.description = "User-defined tempo on which to centre the tempo preference function";
177 desc.defaultValue = 120;
179 desc.isQuantized = true;
180 list.push_back(desc);
182 // MEPD new exposed parameter - used in periodicity estimation
183 desc.identifier = "constraintempo";
184 desc.name = "Constrain Tempo";
185 desc.description = "Constrain more tightly around the tempo hint, using a Gaussian weighting instead of Rayleigh";
188 desc.defaultValue = 0;
189 desc.isQuantized = true;
190 desc.quantizeStep = 1;
192 desc.valueNames.clear();
193 list.push_back(desc);
201 BeatTracker::getParameter(std::string name) const
203 if (name == "dftype") {
205 case DF_HFC: return 0;
206 case DF_SPECDIFF: return 1;
207 case DF_PHASEDEV: return 2;
208 default: case DF_COMPLEXSD: return 3;
209 case DF_BROADBAND: return 4;
211 } else if (name == "method") {
213 } else if (name == "whiten") {
214 return m_whiten ? 1.0 : 0.0;
215 } else if (name == "alpha") {
217 } else if (name == "inputtempo") {
219 } else if (name == "constraintempo") {
220 return m_constraintempo ? 1.0 : 0.0;
226 BeatTracker::setParameter(std::string name, float value)
228 if (name == "dftype") {
229 switch (lrintf(value)) {
230 case 0: m_dfType = DF_HFC; break;
231 case 1: m_dfType = DF_SPECDIFF; break;
232 case 2: m_dfType = DF_PHASEDEV; break;
233 default: case 3: m_dfType = DF_COMPLEXSD; break;
234 case 4: m_dfType = DF_BROADBAND; break;
236 } else if (name == "method") {
237 m_method = lrintf(value);
238 } else if (name == "whiten") {
239 m_whiten = (value > 0.5);
240 } else if (name == "alpha") {
242 } else if (name == "inputtempo") {
243 m_inputtempo = value;
244 } else if (name == "constraintempo") {
245 m_constraintempo = (value > 0.5);
250 BeatTracker::initialise(size_t channels, size_t stepSize, size_t blockSize)
257 if (channels < getMinChannelCount() ||
258 channels > getMaxChannelCount()) {
259 std::cerr << "BeatTracker::initialise: Unsupported channel count: "
260 << channels << std::endl;
264 if (stepSize != getPreferredStepSize()) {
265 std::cerr << "ERROR: BeatTracker::initialise: Unsupported step size for this sample rate: "
266 << stepSize << " (wanted " << (getPreferredStepSize()) << ")" << std::endl;
270 if (blockSize != getPreferredBlockSize()) {
271 std::cerr << "WARNING: BeatTracker::initialise: Sub-optimal block size for this sample rate: "
272 << blockSize << " (wanted " << getPreferredBlockSize() << ")" << std::endl;
277 dfConfig.DFType = m_dfType;
278 dfConfig.stepSize = stepSize;
279 dfConfig.frameLength = blockSize;
281 dfConfig.adaptiveWhitening = m_whiten;
282 dfConfig.whiteningRelaxCoeff = -1;
283 dfConfig.whiteningFloor = -1;
285 m_d = new BeatTrackerData(dfConfig);
292 if (m_d) m_d->reset();
296 BeatTracker::getPreferredStepSize() const
298 size_t step = size_t(m_inputSampleRate * m_stepSecs + 0.0001);
299 // std::cerr << "BeatTracker::getPreferredStepSize: input sample rate is " << m_inputSampleRate << ", step size is " << step << std::endl;
304 BeatTracker::getPreferredBlockSize() const
306 size_t theoretical = getPreferredStepSize() * 2;
308 // I think this is not necessarily going to be a power of two, and
309 // the host might have a problem with that, but I'm not sure we
310 // can do much about it here
314 BeatTracker::OutputList
315 BeatTracker::getOutputDescriptors() const
319 OutputDescriptor beat;
320 beat.identifier = "beats";
322 beat.description = "Estimated metrical beat locations";
324 beat.hasFixedBinCount = true;
326 beat.sampleType = OutputDescriptor::VariableSampleRate;
327 beat.sampleRate = 1.0 / m_stepSecs;
330 df.identifier = "detection_fn";
331 df.name = "Onset Detection Function";
332 df.description = "Probability function of note onset likelihood";
334 df.hasFixedBinCount = true;
336 df.hasKnownExtents = false;
337 df.isQuantized = false;
338 df.sampleType = OutputDescriptor::OneSamplePerStep;
340 OutputDescriptor tempo;
341 tempo.identifier = "tempo";
342 tempo.name = "Tempo";
343 tempo.description = "Locked tempo estimates";
345 tempo.hasFixedBinCount = true;
347 tempo.hasKnownExtents = false;
348 tempo.isQuantized = false;
349 tempo.sampleType = OutputDescriptor::VariableSampleRate;
350 tempo.sampleRate = 1.0 / m_stepSecs;
352 list.push_back(beat);
354 list.push_back(tempo);
359 BeatTracker::FeatureSet
360 BeatTracker::process(const float *const *inputBuffers,
361 Vamp::RealTime timestamp)
364 cerr << "ERROR: BeatTracker::process: "
365 << "BeatTracker has not been initialised"
370 size_t len = m_d->dfConfig.frameLength / 2 + 1;
372 double *reals = new double[len];
373 double *imags = new double[len];
375 // We only support a single input channel
377 for (size_t i = 0; i < len; ++i) {
378 reals[i] = inputBuffers[0][i*2];
379 imags[i] = inputBuffers[0][i*2+1];
382 double output = m_d->df->processFrequencyDomain(reals, imags);
387 if (m_d->dfOutput.empty()) m_d->origin = timestamp;
389 m_d->dfOutput.push_back(output);
391 FeatureSet returnFeatures;
394 feature.hasTimestamp = false;
395 feature.values.push_back(output);
397 returnFeatures[1].push_back(feature); // detection function is output 1
398 return returnFeatures;
401 BeatTracker::FeatureSet
402 BeatTracker::getRemainingFeatures()
405 cerr << "ERROR: BeatTracker::getRemainingFeatures: "
406 << "BeatTracker has not been initialised"
411 if (m_method == METHOD_OLD) return beatTrackOld();
412 else return beatTrackNew();
415 BeatTracker::FeatureSet
416 BeatTracker::beatTrackOld()
418 double aCoeffs[] = { 1.0000, -0.5949, 0.2348 };
419 double bCoeffs[] = { 0.1600, 0.3200, 0.1600 };
422 ttParams.winLength = 512;
423 ttParams.lagLength = 128;
425 ttParams.LPACoeffs = aCoeffs;
426 ttParams.LPBCoeffs = bCoeffs;
428 ttParams.WinT.post = 8;
429 ttParams.WinT.pre = 7;
431 TempoTrack tempoTracker(ttParams);
433 vector<double> tempi;
434 vector<int> beats = tempoTracker.process(m_d->dfOutput, &tempi);
436 FeatureSet returnFeatures;
440 for (size_t i = 0; i < beats.size(); ++i) {
442 size_t frame = beats[i] * m_d->dfConfig.stepSize;
445 feature.hasTimestamp = true;
446 feature.timestamp = m_d->origin + Vamp::RealTime::frame2RealTime
447 (frame, lrintf(m_inputSampleRate));
450 int frameIncrement = 0;
452 if (i < beats.size() - 1) {
454 frameIncrement = (beats[i+1] - beats[i]) * m_d->dfConfig.stepSize;
456 // one beat is frameIncrement frames, so there are
457 // samplerate/frameIncrement bps, so
458 // 60*samplerate/frameIncrement bpm
460 if (frameIncrement > 0) {
461 bpm = (60.0 * m_inputSampleRate) / frameIncrement;
462 bpm = int(bpm * 100.0 + 0.5) / 100.0;
463 sprintf(label, "%.2f bpm", bpm);
464 feature.label = label;
468 returnFeatures[0].push_back(feature); // beats are output 0
471 double prevTempo = 0.0;
473 for (size_t i = 0; i < tempi.size(); ++i) {
475 size_t frame = i * m_d->dfConfig.stepSize * ttParams.lagLength;
477 // std::cerr << "unit " << i << ", step size " << m_d->dfConfig.stepSize << ", hop " << ttParams.lagLength << ", frame = " << frame << std::endl;
479 if (tempi[i] > 1 && int(tempi[i] * 100) != int(prevTempo * 100)) {
481 feature.hasTimestamp = true;
482 feature.timestamp = m_d->origin + Vamp::RealTime::frame2RealTime
483 (frame, lrintf(m_inputSampleRate));
484 feature.values.push_back(tempi[i]);
485 sprintf(label, "%.2f bpm", tempi[i]);
486 feature.label = label;
487 returnFeatures[2].push_back(feature); // tempo is output 2
488 prevTempo = tempi[i];
492 return returnFeatures;
495 BeatTracker::FeatureSet
496 BeatTracker::beatTrackNew()
499 vector<double> beatPeriod;
500 vector<double> tempi;
502 size_t nonZeroCount = m_d->dfOutput.size();
503 while (nonZeroCount > 0) {
504 if (m_d->dfOutput[nonZeroCount-1] > 0.0) {
510 // std::cerr << "Note: nonZeroCount was " << m_d->dfOutput.size() << ", is now " << nonZeroCount << std::endl;
512 for (size_t i = 2; i < nonZeroCount; ++i) { // discard first two elts
513 df.push_back(m_d->dfOutput[i]);
514 beatPeriod.push_back(0.0);
516 if (df.empty()) return FeatureSet();
518 TempoTrackV2 tt(m_inputSampleRate, m_d->dfConfig.stepSize);
521 // MEPD - note this function is now passed 2 new parameters, m_inputtempo and m_constraintempo
522 tt.calculateBeatPeriod(df, beatPeriod, tempi, m_inputtempo, m_constraintempo);
524 vector<double> beats;
526 // MEPD - note this function is now passed 2 new parameters, m_alpha and m_tightness
527 tt.calculateBeats(df, beatPeriod, beats, m_alpha, m_tightness);
529 FeatureSet returnFeatures;
533 for (size_t i = 0; i < beats.size(); ++i) {
535 size_t frame = beats[i] * m_d->dfConfig.stepSize;
538 feature.hasTimestamp = true;
539 feature.timestamp = m_d->origin + Vamp::RealTime::frame2RealTime
540 (frame, lrintf(m_inputSampleRate));
543 int frameIncrement = 0;
545 if (i+1 < beats.size()) {
547 frameIncrement = (beats[i+1] - beats[i]) * m_d->dfConfig.stepSize;
549 // one beat is frameIncrement frames, so there are
550 // samplerate/frameIncrement bps, so
551 // 60*samplerate/frameIncrement bpm
553 if (frameIncrement > 0) {
554 bpm = (60.0 * m_inputSampleRate) / frameIncrement;
555 bpm = int(bpm * 100.0 + 0.5) / 100.0;
556 sprintf(label, "%.2f bpm", bpm);
557 feature.label = label;
561 returnFeatures[0].push_back(feature); // beats are output 0
564 double prevTempo = 0.0;
566 for (size_t i = 0; i < tempi.size(); ++i) {
568 size_t frame = i * m_d->dfConfig.stepSize;
570 if (tempi[i] > 1 && int(tempi[i] * 100) != int(prevTempo * 100)) {
572 feature.hasTimestamp = true;
573 feature.timestamp = m_d->origin + Vamp::RealTime::frame2RealTime
574 (frame, lrintf(m_inputSampleRate));
575 feature.values.push_back(tempi[i]);
576 sprintf(label, "%.2f bpm", tempi[i]);
577 feature.label = label;
578 returnFeatures[2].push_back(feature); // tempo is output 2
579 prevTempo = tempi[i];
583 return returnFeatures;