annotate plugins/SimilarityPlugin.cpp @ 135:dcf5800f0f00

* Add GPL
author Chris Cannam <c.cannam@qmul.ac.uk>
date Mon, 13 Dec 2010 14:03:46 +0000
parents c655fa61884f
children f96ea0e4b475
rev   line source
c@41 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
c@41 2
c@41 3 /*
c@67 4 * SimilarityPlugin.cpp
c@41 5 *
c@118 6 * Copyright 2009 Centre for Digital Music, Queen Mary, University of London.
c@135 7
c@135 8 This program is free software; you can redistribute it and/or
c@135 9 modify it under the terms of the GNU General Public License as
c@135 10 published by the Free Software Foundation; either version 2 of the
c@135 11 License, or (at your option) any later version. See the file
c@135 12 COPYING included with this distribution for more information.
c@41 13 */
c@41 14
c@41 15 #include <iostream>
c@44 16 #include <cstdio>
c@41 17
c@41 18 #include "SimilarityPlugin.h"
c@42 19 #include "base/Pitch.h"
c@41 20 #include "dsp/mfcc/MFCC.h"
c@42 21 #include "dsp/chromagram/Chromagram.h"
c@41 22 #include "dsp/rateconversion/Decimator.h"
c@47 23 #include "dsp/rhythm/BeatSpectrum.h"
c@47 24 #include "maths/KLDivergence.h"
c@47 25 #include "maths/CosineDistance.h"
c@49 26 #include "maths/MathUtilities.h"
c@41 27
c@41 28 using std::string;
c@41 29 using std::vector;
c@41 30 using std::cerr;
c@41 31 using std::endl;
c@41 32 using std::ostringstream;
c@41 33
c@47 34 const float
c@47 35 SimilarityPlugin::m_noRhythm = 0.009;
c@47 36
c@47 37 const float
c@47 38 SimilarityPlugin::m_allRhythm = 0.991;
c@47 39
c@41 40 SimilarityPlugin::SimilarityPlugin(float inputSampleRate) :
c@41 41 Plugin(inputSampleRate),
c@42 42 m_type(TypeMFCC),
c@41 43 m_mfcc(0),
c@47 44 m_rhythmfcc(0),
c@42 45 m_chromagram(0),
c@41 46 m_decimator(0),
c@42 47 m_featureColumnSize(20),
c@48 48 m_rhythmWeighting(0.5f),
c@47 49 m_rhythmClipDuration(4.f), // seconds
c@47 50 m_rhythmClipOrigin(40.f), // seconds
c@47 51 m_rhythmClipFrameSize(0),
c@47 52 m_rhythmClipFrames(0),
c@47 53 m_rhythmColumnSize(20),
c@41 54 m_blockSize(0),
c@47 55 m_channels(0),
c@47 56 m_processRate(0),
c@47 57 m_frameNo(0),
c@47 58 m_done(false)
c@41 59 {
c@47 60 int rate = lrintf(m_inputSampleRate);
c@47 61 int internalRate = 22050;
c@47 62 int decimationFactor = rate / internalRate;
c@47 63 if (decimationFactor < 1) decimationFactor = 1;
c@47 64
c@47 65 // must be a power of two
c@47 66 while (decimationFactor & (decimationFactor - 1)) ++decimationFactor;
c@47 67
c@47 68 m_processRate = rate / decimationFactor; // may be 22050, 24000 etc
c@41 69 }
c@41 70
c@41 71 SimilarityPlugin::~SimilarityPlugin()
c@41 72 {
c@41 73 delete m_mfcc;
c@47 74 delete m_rhythmfcc;
c@42 75 delete m_chromagram;
c@41 76 delete m_decimator;
c@41 77 }
c@41 78
c@41 79 string
c@41 80 SimilarityPlugin::getIdentifier() const
c@41 81 {
c@41 82 return "qm-similarity";
c@41 83 }
c@41 84
c@41 85 string
c@41 86 SimilarityPlugin::getName() const
c@41 87 {
c@41 88 return "Similarity";
c@41 89 }
c@41 90
c@41 91 string
c@41 92 SimilarityPlugin::getDescription() const
c@41 93 {
c@42 94 return "Return a distance matrix for similarity between the input audio channels";
c@41 95 }
c@41 96
c@41 97 string
c@41 98 SimilarityPlugin::getMaker() const
c@41 99 {
c@50 100 return "Queen Mary, University of London";
c@41 101 }
c@41 102
c@41 103 int
c@41 104 SimilarityPlugin::getPluginVersion() const
c@41 105 {
c@41 106 return 1;
c@41 107 }
c@41 108
c@41 109 string
c@41 110 SimilarityPlugin::getCopyright() const
c@41 111 {
c@118 112 return "Plugin by Mark Levy, Kurt Jacobson and Chris Cannam. Copyright (c) 2009 QMUL - All Rights Reserved";
c@41 113 }
c@41 114
c@41 115 size_t
c@41 116 SimilarityPlugin::getMinChannelCount() const
c@41 117 {
c@43 118 return 1;
c@41 119 }
c@41 120
c@41 121 size_t
c@41 122 SimilarityPlugin::getMaxChannelCount() const
c@41 123 {
c@41 124 return 1024;
c@41 125 }
c@41 126
c@41 127 int
c@41 128 SimilarityPlugin::getDecimationFactor() const
c@41 129 {
c@41 130 int rate = lrintf(m_inputSampleRate);
c@47 131 return rate / m_processRate;
c@41 132 }
c@41 133
c@41 134 size_t
c@41 135 SimilarityPlugin::getPreferredStepSize() const
c@41 136 {
c@42 137 if (m_blockSize == 0) calculateBlockSize();
c@47 138
c@47 139 // there is also an assumption to this effect in process()
c@47 140 // (referring to m_fftSize/2 instead of a literal post-decimation
c@47 141 // step size):
c@45 142 return m_blockSize/2;
c@41 143 }
c@41 144
c@41 145 size_t
c@41 146 SimilarityPlugin::getPreferredBlockSize() const
c@41 147 {
c@42 148 if (m_blockSize == 0) calculateBlockSize();
c@42 149 return m_blockSize;
c@42 150 }
c@42 151
c@42 152 void
c@42 153 SimilarityPlugin::calculateBlockSize() const
c@42 154 {
c@42 155 if (m_blockSize != 0) return;
c@42 156 int decimationFactor = getDecimationFactor();
c@66 157 m_blockSize = 2048 * decimationFactor;
c@41 158 }
c@41 159
c@41 160 SimilarityPlugin::ParameterList SimilarityPlugin::getParameterDescriptors() const
c@41 161 {
c@41 162 ParameterList list;
c@42 163
c@42 164 ParameterDescriptor desc;
c@42 165 desc.identifier = "featureType";
c@42 166 desc.name = "Feature Type";
c@48 167 desc.description = "Audio feature used for similarity measure. Timbral: use the first 20 MFCCs (19 plus C0). Chromatic: use 12 bin-per-octave chroma. Rhythmic: compare beat spectra of short regions.";
c@42 168 desc.unit = "";
c@42 169 desc.minValue = 0;
c@48 170 desc.maxValue = 4;
c@48 171 desc.defaultValue = 1;
c@42 172 desc.isQuantized = true;
c@42 173 desc.quantizeStep = 1;
c@48 174 desc.valueNames.push_back("Timbre");
c@48 175 desc.valueNames.push_back("Timbre and Rhythm");
c@48 176 desc.valueNames.push_back("Chroma");
c@48 177 desc.valueNames.push_back("Chroma and Rhythm");
c@48 178 desc.valueNames.push_back("Rhythm only");
c@42 179 list.push_back(desc);
c@48 180 /*
c@47 181 desc.identifier = "rhythmWeighting";
c@47 182 desc.name = "Influence of Rhythm";
c@47 183 desc.description = "Proportion of similarity measure made up from rhythmic similarity component, from 0 (entirely timbral or chromatic) to 100 (entirely rhythmic).";
c@47 184 desc.unit = "%";
c@47 185 desc.minValue = 0;
c@47 186 desc.maxValue = 100;
c@47 187 desc.defaultValue = 0;
c@48 188 desc.isQuantized = false;
c@47 189 desc.valueNames.clear();
c@47 190 list.push_back(desc);
c@48 191 */
c@41 192 return list;
c@41 193 }
c@41 194
c@41 195 float
c@41 196 SimilarityPlugin::getParameter(std::string param) const
c@41 197 {
c@42 198 if (param == "featureType") {
c@48 199
c@48 200 if (m_rhythmWeighting > m_allRhythm) {
c@48 201 return 4;
c@48 202 }
c@48 203
c@48 204 switch (m_type) {
c@48 205
c@48 206 case TypeMFCC:
c@48 207 if (m_rhythmWeighting < m_noRhythm) return 0;
c@48 208 else return 1;
c@48 209 break;
c@48 210
c@48 211 case TypeChroma:
c@48 212 if (m_rhythmWeighting < m_noRhythm) return 2;
c@48 213 else return 3;
c@48 214 break;
c@48 215 }
c@48 216
c@48 217 return 1;
c@48 218
c@48 219 // } else if (param == "rhythmWeighting") {
c@48 220 // return nearbyint(m_rhythmWeighting * 100.0);
c@42 221 }
c@42 222
c@41 223 std::cerr << "WARNING: SimilarityPlugin::getParameter: unknown parameter \""
c@41 224 << param << "\"" << std::endl;
c@41 225 return 0.0;
c@41 226 }
c@41 227
c@41 228 void
c@41 229 SimilarityPlugin::setParameter(std::string param, float value)
c@41 230 {
c@42 231 if (param == "featureType") {
c@48 232
c@42 233 int v = int(value + 0.1);
c@48 234
c@48 235 Type newType = m_type;
c@48 236
c@48 237 switch (v) {
c@48 238 case 0: newType = TypeMFCC; m_rhythmWeighting = 0.0f; break;
c@48 239 case 1: newType = TypeMFCC; m_rhythmWeighting = 0.5f; break;
c@48 240 case 2: newType = TypeChroma; m_rhythmWeighting = 0.0f; break;
c@48 241 case 3: newType = TypeChroma; m_rhythmWeighting = 0.5f; break;
c@48 242 case 4: newType = TypeMFCC; m_rhythmWeighting = 1.f; break;
c@48 243 }
c@48 244
c@48 245 if (newType != m_type) m_blockSize = 0;
c@48 246
c@48 247 m_type = newType;
c@42 248 return;
c@48 249
c@48 250 // } else if (param == "rhythmWeighting") {
c@48 251 // m_rhythmWeighting = value / 100;
c@48 252 // return;
c@42 253 }
c@42 254
c@41 255 std::cerr << "WARNING: SimilarityPlugin::setParameter: unknown parameter \""
c@41 256 << param << "\"" << std::endl;
c@41 257 }
c@41 258
c@41 259 SimilarityPlugin::OutputList
c@41 260 SimilarityPlugin::getOutputDescriptors() const
c@41 261 {
c@41 262 OutputList list;
c@41 263
c@41 264 OutputDescriptor similarity;
c@43 265 similarity.identifier = "distancematrix";
c@43 266 similarity.name = "Distance Matrix";
c@43 267 similarity.description = "Distance matrix for similarity metric. Smaller = more similar. Should be symmetrical.";
c@41 268 similarity.unit = "";
c@41 269 similarity.hasFixedBinCount = true;
c@41 270 similarity.binCount = m_channels;
c@41 271 similarity.hasKnownExtents = false;
c@41 272 similarity.isQuantized = false;
c@41 273 similarity.sampleType = OutputDescriptor::FixedSampleRate;
c@41 274 similarity.sampleRate = 1;
c@41 275
c@43 276 m_distanceMatrixOutput = list.size();
c@41 277 list.push_back(similarity);
c@41 278
c@43 279 OutputDescriptor simvec;
c@43 280 simvec.identifier = "distancevector";
c@43 281 simvec.name = "Distance from First Channel";
c@43 282 simvec.description = "Distance vector for similarity of each channel to the first channel. Smaller = more similar.";
c@43 283 simvec.unit = "";
c@43 284 simvec.hasFixedBinCount = true;
c@43 285 simvec.binCount = m_channels;
c@43 286 simvec.hasKnownExtents = false;
c@43 287 simvec.isQuantized = false;
c@43 288 simvec.sampleType = OutputDescriptor::FixedSampleRate;
c@43 289 simvec.sampleRate = 1;
c@43 290
c@43 291 m_distanceVectorOutput = list.size();
c@43 292 list.push_back(simvec);
c@43 293
c@44 294 OutputDescriptor sortvec;
c@44 295 sortvec.identifier = "sorteddistancevector";
c@44 296 sortvec.name = "Ordered Distances from First Channel";
c@44 297 sortvec.description = "Vector of the order of other channels in similarity to the first, followed by distance vector for similarity of each to the first. Smaller = more similar.";
c@44 298 sortvec.unit = "";
c@44 299 sortvec.hasFixedBinCount = true;
c@44 300 sortvec.binCount = m_channels;
c@44 301 sortvec.hasKnownExtents = false;
c@44 302 sortvec.isQuantized = false;
c@44 303 sortvec.sampleType = OutputDescriptor::FixedSampleRate;
c@44 304 sortvec.sampleRate = 1;
c@44 305
c@44 306 m_sortedVectorOutput = list.size();
c@44 307 list.push_back(sortvec);
c@44 308
c@41 309 OutputDescriptor means;
c@41 310 means.identifier = "means";
c@42 311 means.name = "Feature Means";
c@43 312 means.description = "Means of the feature bins. Feature time (sec) corresponds to input channel. Number of bins depends on selected feature type.";
c@41 313 means.unit = "";
c@41 314 means.hasFixedBinCount = true;
c@43 315 means.binCount = m_featureColumnSize;
c@41 316 means.hasKnownExtents = false;
c@41 317 means.isQuantized = false;
c@43 318 means.sampleType = OutputDescriptor::FixedSampleRate;
c@43 319 means.sampleRate = 1;
c@41 320
c@43 321 m_meansOutput = list.size();
c@41 322 list.push_back(means);
c@41 323
c@41 324 OutputDescriptor variances;
c@41 325 variances.identifier = "variances";
c@42 326 variances.name = "Feature Variances";
c@43 327 variances.description = "Variances of the feature bins. Feature time (sec) corresponds to input channel. Number of bins depends on selected feature type.";
c@41 328 variances.unit = "";
c@41 329 variances.hasFixedBinCount = true;
c@43 330 variances.binCount = m_featureColumnSize;
c@41 331 variances.hasKnownExtents = false;
c@41 332 variances.isQuantized = false;
c@43 333 variances.sampleType = OutputDescriptor::FixedSampleRate;
c@43 334 variances.sampleRate = 1;
c@41 335
c@43 336 m_variancesOutput = list.size();
c@41 337 list.push_back(variances);
c@41 338
c@47 339 OutputDescriptor beatspectrum;
c@47 340 beatspectrum.identifier = "beatspectrum";
c@47 341 beatspectrum.name = "Beat Spectra";
c@47 342 beatspectrum.description = "Rhythmic self-similarity vectors (beat spectra) for the input channels. Feature time (sec) corresponds to input channel. Not returned if rhythm weighting is zero.";
c@47 343 beatspectrum.unit = "";
c@47 344 if (m_rhythmClipFrames > 0) {
c@47 345 beatspectrum.hasFixedBinCount = true;
c@47 346 beatspectrum.binCount = m_rhythmClipFrames / 2;
c@47 347 } else {
c@47 348 beatspectrum.hasFixedBinCount = false;
c@47 349 }
c@47 350 beatspectrum.hasKnownExtents = false;
c@47 351 beatspectrum.isQuantized = false;
c@47 352 beatspectrum.sampleType = OutputDescriptor::FixedSampleRate;
c@47 353 beatspectrum.sampleRate = 1;
c@47 354
c@47 355 m_beatSpectraOutput = list.size();
c@47 356 list.push_back(beatspectrum);
c@47 357
c@41 358 return list;
c@41 359 }
c@41 360
c@68 361 bool
c@68 362 SimilarityPlugin::initialise(size_t channels, size_t stepSize, size_t blockSize)
c@68 363 {
c@68 364 if (channels < getMinChannelCount()) return false;
c@68 365
c@68 366 // Using more than getMaxChannelCount is not actually a problem
c@68 367 // for us. Using "incorrect" step and block sizes would be fine
c@68 368 // for timbral or chroma similarity, but will break rhythmic
c@68 369 // similarity, so we'd better enforce these.
c@68 370
c@68 371 if (stepSize != getPreferredStepSize()) {
c@68 372 std::cerr << "SimilarityPlugin::initialise: supplied step size "
c@68 373 << stepSize << " differs from required step size "
c@68 374 << getPreferredStepSize() << std::endl;
c@68 375 return false;
c@68 376 }
c@68 377
c@68 378 if (blockSize != getPreferredBlockSize()) {
c@68 379 std::cerr << "SimilarityPlugin::initialise: supplied block size "
c@68 380 << blockSize << " differs from required block size "
c@68 381 << getPreferredBlockSize() << std::endl;
c@68 382 return false;
c@68 383 }
c@68 384
c@68 385 m_blockSize = blockSize;
c@68 386 m_channels = channels;
c@68 387
c@68 388 m_lastNonEmptyFrame = std::vector<int>(m_channels);
c@68 389 for (int i = 0; i < m_channels; ++i) m_lastNonEmptyFrame[i] = -1;
c@68 390
c@68 391 m_emptyFrameCount = std::vector<int>(m_channels);
c@68 392 for (int i = 0; i < m_channels; ++i) m_emptyFrameCount[i] = 0;
c@68 393
c@68 394 m_frameNo = 0;
c@68 395
c@68 396 int decimationFactor = getDecimationFactor();
c@68 397 if (decimationFactor > 1) {
c@68 398 m_decimator = new Decimator(m_blockSize, decimationFactor);
c@68 399 }
c@68 400
c@68 401 if (m_type == TypeMFCC) {
c@68 402
c@68 403 m_featureColumnSize = 20;
c@68 404
c@68 405 MFCCConfig config(m_processRate);
c@68 406 config.fftsize = 2048;
c@68 407 config.nceps = m_featureColumnSize - 1;
c@68 408 config.want_c0 = true;
c@68 409 config.logpower = 1;
c@68 410 m_mfcc = new MFCC(config);
c@68 411 m_fftSize = m_mfcc->getfftlength();
c@68 412 m_rhythmClipFrameSize = m_fftSize / 4;
c@68 413
c@68 414 // std::cerr << "MFCC FS = " << config.FS << ", FFT size = " << m_fftSize<< std::endl;
c@68 415
c@68 416 } else if (m_type == TypeChroma) {
c@68 417
c@68 418 m_featureColumnSize = 12;
c@68 419
c@68 420 // For simplicity, aim to have the chroma fft size equal to
c@68 421 // 2048, the same as the mfcc fft size (so the input block
c@68 422 // size does not depend on the feature type and we can use the
c@68 423 // same processing parameters for rhythm etc). This is also
c@68 424 // why getPreferredBlockSize can confidently return 2048 * the
c@68 425 // decimation factor.
c@68 426
c@68 427 // The fft size for a chromagram is the filterbank Q value
c@68 428 // times the sample rate, divided by the minimum frequency,
c@68 429 // rounded up to the nearest power of two.
c@68 430
c@68 431 double q = 1.0 / (pow(2.0, (1.0 / 12.0)) - 1.0);
c@68 432 double fmin = (q * m_processRate) / 2048.0;
c@68 433
c@68 434 // Round fmin up to the nearest MIDI pitch multiple of 12.
c@68 435 // So long as fmin is greater than 12 to start with, this
c@68 436 // should not change the resulting fft size.
c@68 437
c@68 438 int pmin = Pitch::getPitchForFrequency(float(fmin));
c@68 439 pmin = ((pmin / 12) + 1) * 12;
c@68 440 fmin = Pitch::getFrequencyForPitch(pmin);
c@68 441
c@68 442 float fmax = Pitch::getFrequencyForPitch(pmin + 36);
c@68 443
c@68 444 ChromaConfig config;
c@68 445 config.FS = m_processRate;
c@68 446 config.min = fmin;
c@68 447 config.max = fmax;
c@68 448 config.BPO = 12;
c@68 449 config.CQThresh = 0.0054;
c@68 450 // We don't normalise the chromagram's columns individually;
c@68 451 // we normalise the mean at the end instead
c@68 452 config.normalise = MathUtilities::NormaliseNone;
c@68 453 m_chromagram = new Chromagram(config);
c@68 454 m_fftSize = m_chromagram->getFrameSize();
c@68 455
c@68 456 if (m_fftSize != 2048) {
c@68 457 std::cerr << "WARNING: SimilarityPlugin::initialise: Internal processing FFT size " << m_fftSize << " != expected size 2048 in chroma mode" << std::endl;
c@68 458 }
c@68 459
c@68 460 // std::cerr << "fftsize = " << m_fftSize << std::endl;
c@68 461
c@68 462 m_rhythmClipFrameSize = m_fftSize / 4;
c@68 463
c@68 464 // std::cerr << "m_rhythmClipFrameSize = " << m_rhythmClipFrameSize << std::endl;
c@68 465 // std::cerr << "min = "<< config.min << ", max = " << config.max << std::endl;
c@68 466
c@68 467 } else {
c@68 468
c@68 469 std::cerr << "SimilarityPlugin::initialise: internal error: unknown type " << m_type << std::endl;
c@68 470 return false;
c@68 471 }
c@68 472
c@68 473 if (needRhythm()) {
c@68 474 m_rhythmClipFrames =
c@68 475 int(ceil((m_rhythmClipDuration * m_processRate)
c@68 476 / m_rhythmClipFrameSize));
c@68 477 // std::cerr << "SimilarityPlugin::initialise: rhythm clip requires "
c@68 478 // << m_rhythmClipFrames << " frames of size "
c@68 479 // << m_rhythmClipFrameSize << " at process rate "
c@68 480 // << m_processRate << " ( = "
c@68 481 // << (float(m_rhythmClipFrames * m_rhythmClipFrameSize) / m_processRate) << " sec )"
c@68 482 // << std::endl;
c@68 483
c@68 484 MFCCConfig config(m_processRate);
c@68 485 config.fftsize = m_rhythmClipFrameSize;
c@68 486 config.nceps = m_rhythmColumnSize - 1;
c@68 487 config.want_c0 = true;
c@68 488 config.logpower = 1;
c@68 489 config.window = RectangularWindow; // because no overlap
c@68 490 m_rhythmfcc = new MFCC(config);
c@68 491 }
c@68 492
c@68 493 for (int i = 0; i < m_channels; ++i) {
c@68 494
c@68 495 m_values.push_back(FeatureMatrix());
c@68 496
c@68 497 if (needRhythm()) {
c@68 498 m_rhythmValues.push_back(FeatureColumnQueue());
c@68 499 }
c@68 500 }
c@68 501
c@68 502 m_done = false;
c@68 503
c@68 504 return true;
c@68 505 }
c@68 506
c@68 507 void
c@68 508 SimilarityPlugin::reset()
c@68 509 {
c@68 510 for (int i = 0; i < m_values.size(); ++i) {
c@68 511 m_values[i].clear();
c@68 512 }
c@68 513
c@68 514 for (int i = 0; i < m_rhythmValues.size(); ++i) {
c@68 515 m_rhythmValues[i].clear();
c@68 516 }
c@68 517
c@68 518 for (int i = 0; i < m_lastNonEmptyFrame.size(); ++i) {
c@68 519 m_lastNonEmptyFrame[i] = -1;
c@68 520 }
c@68 521
c@68 522 for (int i = 0; i < m_emptyFrameCount.size(); ++i) {
c@68 523 m_emptyFrameCount[i] = 0;
c@68 524 }
c@68 525
c@68 526 m_done = false;
c@68 527 }
c@68 528
c@41 529 SimilarityPlugin::FeatureSet
c@41 530 SimilarityPlugin::process(const float *const *inputBuffers, Vamp::RealTime /* timestamp */)
c@41 531 {
c@47 532 if (m_done) {
c@47 533 return FeatureSet();
c@47 534 }
c@47 535
c@41 536 double *dblbuf = new double[m_blockSize];
c@41 537 double *decbuf = dblbuf;
c@42 538 if (m_decimator) decbuf = new double[m_fftSize];
c@42 539
c@47 540 double *raw = new double[std::max(m_featureColumnSize,
c@47 541 m_rhythmColumnSize)];
c@41 542
c@43 543 float threshold = 1e-10;
c@43 544
c@47 545 bool someRhythmFrameNeeded = false;
c@47 546
c@41 547 for (size_t c = 0; c < m_channels; ++c) {
c@41 548
c@43 549 bool empty = true;
c@43 550
c@41 551 for (int i = 0; i < m_blockSize; ++i) {
c@43 552 float val = inputBuffers[c][i];
c@43 553 if (fabs(val) > threshold) empty = false;
c@43 554 dblbuf[i] = val;
c@41 555 }
c@41 556
c@47 557 if (empty) {
c@47 558 if (needRhythm() && ((m_frameNo % 2) == 0)) {
c@47 559 for (int i = 0; i < m_fftSize / m_rhythmClipFrameSize; ++i) {
c@47 560 if (m_rhythmValues[c].size() < m_rhythmClipFrames) {
c@47 561 FeatureColumn mf(m_rhythmColumnSize);
c@47 562 for (int i = 0; i < m_rhythmColumnSize; ++i) {
c@47 563 mf[i] = 0.0;
c@47 564 }
c@47 565 m_rhythmValues[c].push_back(mf);
c@47 566 }
c@47 567 }
c@47 568 }
c@60 569 m_emptyFrameCount[c]++;
c@47 570 continue;
c@47 571 }
c@47 572
c@44 573 m_lastNonEmptyFrame[c] = m_frameNo;
c@43 574
c@41 575 if (m_decimator) {
c@41 576 m_decimator->process(dblbuf, decbuf);
c@41 577 }
c@42 578
c@47 579 if (needTimbre()) {
c@47 580
c@66 581 FeatureColumn mf(m_featureColumnSize);
c@66 582
c@47 583 if (m_type == TypeMFCC) {
c@47 584 m_mfcc->process(decbuf, raw);
c@66 585 for (int i = 0; i < m_featureColumnSize; ++i) {
c@66 586 mf[i] = raw[i];
c@66 587 }
c@47 588 } else if (m_type == TypeChroma) {
c@66 589 double *chroma = m_chromagram->process(decbuf);
c@66 590 for (int i = 0; i < m_featureColumnSize; ++i) {
c@66 591 mf[i] = chroma[i];
c@66 592 }
c@47 593 }
c@41 594
c@47 595 m_values[c].push_back(mf);
c@44 596 }
c@41 597
c@47 598 // std::cerr << "needRhythm = " << needRhythm() << ", frame = " << m_frameNo << std::endl;
c@47 599
c@47 600 if (needRhythm() && ((m_frameNo % 2) == 0)) {
c@47 601
c@47 602 // The incoming frames are overlapping; we only use every
c@47 603 // other one, because we don't want the overlap (it would
c@47 604 // screw up the rhythm)
c@47 605
c@47 606 int frameOffset = 0;
c@47 607
c@47 608 while (frameOffset + m_rhythmClipFrameSize <= m_fftSize) {
c@47 609
c@47 610 bool needRhythmFrame = true;
c@47 611
c@47 612 if (m_rhythmValues[c].size() >= m_rhythmClipFrames) {
c@47 613
c@47 614 needRhythmFrame = false;
c@47 615
c@47 616 // assumes hopsize = framesize/2
c@47 617 float current = m_frameNo * (m_fftSize/2) + frameOffset;
c@47 618 current = current / m_processRate;
c@47 619 if (current - m_rhythmClipDuration < m_rhythmClipOrigin) {
c@47 620 needRhythmFrame = true;
c@47 621 m_rhythmValues[c].pop_front();
c@47 622 }
c@47 623
c@53 624 // if (needRhythmFrame) {
c@53 625 // std::cerr << "at current = " <<current << " (frame = " << m_frameNo << "), have " << m_rhythmValues[c].size() << ", need rhythm = " << needRhythmFrame << std::endl;
c@53 626 // }
c@47 627
c@47 628 }
c@47 629
c@47 630 if (needRhythmFrame) {
c@47 631
c@47 632 someRhythmFrameNeeded = true;
c@47 633
c@47 634 m_rhythmfcc->process(decbuf + frameOffset, raw);
c@47 635
c@47 636 FeatureColumn mf(m_rhythmColumnSize);
c@47 637 for (int i = 0; i < m_rhythmColumnSize; ++i) {
c@47 638 mf[i] = raw[i];
c@47 639 }
c@47 640
c@47 641 m_rhythmValues[c].push_back(mf);
c@47 642 }
c@47 643
c@47 644 frameOffset += m_rhythmClipFrameSize;
c@47 645 }
c@47 646 }
c@47 647 }
c@47 648
c@47 649 if (!needTimbre() && !someRhythmFrameNeeded && ((m_frameNo % 2) == 0)) {
c@53 650 // std::cerr << "done!" << std::endl;
c@47 651 m_done = true;
c@41 652 }
c@41 653
c@41 654 if (m_decimator) delete[] decbuf;
c@41 655 delete[] dblbuf;
c@47 656 delete[] raw;
c@41 657
c@44 658 ++m_frameNo;
c@44 659
c@41 660 return FeatureSet();
c@41 661 }
c@41 662
c@47 663 SimilarityPlugin::FeatureMatrix
c@47 664 SimilarityPlugin::calculateTimbral(FeatureSet &returnFeatures)
c@41 665 {
c@47 666 FeatureMatrix m(m_channels); // means
c@47 667 FeatureMatrix v(m_channels); // variances
c@41 668
c@41 669 for (int i = 0; i < m_channels; ++i) {
c@41 670
c@42 671 FeatureColumn mean(m_featureColumnSize), variance(m_featureColumnSize);
c@41 672
c@42 673 for (int j = 0; j < m_featureColumnSize; ++j) {
c@41 674
c@43 675 mean[j] = 0.0;
c@43 676 variance[j] = 0.0;
c@41 677 int count;
c@41 678
c@44 679 // We want to take values up to, but not including, the
c@44 680 // last non-empty frame (which may be partial)
c@43 681
c@60 682 int sz = m_lastNonEmptyFrame[i] - m_emptyFrameCount[i];
c@44 683 if (sz < 0) sz = 0;
c@60 684 if (sz >= m_values[i].size()) sz = m_values[i].size()-1;
c@43 685
c@41 686 count = 0;
c@43 687 for (int k = 0; k < sz; ++k) {
c@42 688 double val = m_values[i][k][j];
c@130 689 if (ISNAN(val) || ISINF(val)) continue;
c@41 690 mean[j] += val;
c@41 691 ++count;
c@41 692 }
c@41 693 if (count > 0) mean[j] /= count;
c@41 694
c@41 695 count = 0;
c@43 696 for (int k = 0; k < sz; ++k) {
c@42 697 double val = ((m_values[i][k][j] - mean[j]) *
c@42 698 (m_values[i][k][j] - mean[j]));
c@130 699 if (ISNAN(val) || ISINF(val)) continue;
c@41 700 variance[j] += val;
c@41 701 ++count;
c@41 702 }
c@41 703 if (count > 0) variance[j] /= count;
c@41 704 }
c@41 705
c@41 706 m[i] = mean;
c@41 707 v[i] = variance;
c@41 708 }
c@41 709
c@47 710 FeatureMatrix distances(m_channels);
c@42 711
c@48 712 if (m_type == TypeMFCC) {
c@48 713
c@48 714 // "Despite the fact that MFCCs extracted from music are
c@48 715 // clearly not Gaussian, [14] showed, somewhat surprisingly,
c@48 716 // that a similarity function comparing single Gaussians
c@48 717 // modelling MFCCs for each track can perform as well as
c@48 718 // mixture models. A great advantage of using single
c@48 719 // Gaussians is that a simple closed form exists for the KL
c@48 720 // divergence." -- Mark Levy, "Lightweight measures for
c@48 721 // timbral similarity of musical audio"
c@48 722 // (http://www.elec.qmul.ac.uk/easaier/papers/mlevytimbralsimilarity.pdf)
c@48 723
c@48 724 KLDivergence kld;
c@48 725
c@48 726 for (int i = 0; i < m_channels; ++i) {
c@48 727 for (int j = 0; j < m_channels; ++j) {
c@48 728 double d = kld.distanceGaussian(m[i], v[i], m[j], v[j]);
c@48 729 distances[i].push_back(d);
c@48 730 }
c@48 731 }
c@48 732
c@48 733 } else {
c@48 734
c@49 735 // We use the KL divergence for distributions of discrete
c@49 736 // variables, as chroma are histograms already. Or at least,
c@49 737 // they will be when we've normalised them like this:
c@49 738 for (int i = 0; i < m_channels; ++i) {
c@49 739 MathUtilities::normalise(m[i], MathUtilities::NormaliseUnitSum);
c@49 740 }
c@48 741
c@48 742 KLDivergence kld;
c@48 743
c@48 744 for (int i = 0; i < m_channels; ++i) {
c@48 745 for (int j = 0; j < m_channels; ++j) {
c@48 746 double d = kld.distanceDistribution(m[i], m[j], true);
c@48 747 distances[i].push_back(d);
c@48 748 }
c@41 749 }
c@41 750 }
c@47 751
c@44 752 Feature feature;
c@44 753 feature.hasTimestamp = true;
c@44 754
c@44 755 char labelBuffer[100];
c@43 756
c@41 757 for (int i = 0; i < m_channels; ++i) {
c@41 758
c@41 759 feature.timestamp = Vamp::RealTime(i, 0);
c@41 760
c@44 761 sprintf(labelBuffer, "Means for channel %d", i+1);
c@44 762 feature.label = labelBuffer;
c@44 763
c@41 764 feature.values.clear();
c@42 765 for (int k = 0; k < m_featureColumnSize; ++k) {
c@41 766 feature.values.push_back(m[i][k]);
c@41 767 }
c@41 768
c@43 769 returnFeatures[m_meansOutput].push_back(feature);
c@41 770
c@44 771 sprintf(labelBuffer, "Variances for channel %d", i+1);
c@44 772 feature.label = labelBuffer;
c@44 773
c@41 774 feature.values.clear();
c@42 775 for (int k = 0; k < m_featureColumnSize; ++k) {
c@41 776 feature.values.push_back(v[i][k]);
c@41 777 }
c@41 778
c@43 779 returnFeatures[m_variancesOutput].push_back(feature);
c@47 780 }
c@47 781
c@47 782 return distances;
c@47 783 }
c@47 784
c@47 785 SimilarityPlugin::FeatureMatrix
c@47 786 SimilarityPlugin::calculateRhythmic(FeatureSet &returnFeatures)
c@47 787 {
c@47 788 if (!needRhythm()) return FeatureMatrix();
c@47 789
c@60 790 // std::cerr << "SimilarityPlugin::initialise: rhythm clip for channel 0 contains "
c@60 791 // << m_rhythmValues[0].size() << " frames of size "
c@60 792 // << m_rhythmClipFrameSize << " at process rate "
c@60 793 // << m_processRate << " ( = "
c@60 794 // << (float(m_rhythmValues[0].size() * m_rhythmClipFrameSize) / m_processRate) << " sec )"
c@60 795 // << std::endl;
c@60 796
c@47 797 BeatSpectrum bscalc;
c@47 798 CosineDistance cd;
c@47 799
c@47 800 // Our rhythm feature matrix is a deque of vectors for practical
c@47 801 // reasons, but BeatSpectrum::process wants a vector of vectors
c@47 802 // (which is what FeatureMatrix happens to be).
c@47 803
c@47 804 FeatureMatrixSet bsinput(m_channels);
c@47 805 for (int i = 0; i < m_channels; ++i) {
c@47 806 for (int j = 0; j < m_rhythmValues[i].size(); ++j) {
c@47 807 bsinput[i].push_back(m_rhythmValues[i][j]);
c@47 808 }
c@47 809 }
c@47 810
c@47 811 FeatureMatrix bs(m_channels);
c@47 812 for (int i = 0; i < m_channels; ++i) {
c@47 813 bs[i] = bscalc.process(bsinput[i]);
c@47 814 }
c@47 815
c@47 816 FeatureMatrix distances(m_channels);
c@47 817 for (int i = 0; i < m_channels; ++i) {
c@47 818 for (int j = 0; j < m_channels; ++j) {
c@47 819 double d = cd.distance(bs[i], bs[j]);
c@47 820 distances[i].push_back(d);
c@47 821 }
c@47 822 }
c@47 823
c@47 824 Feature feature;
c@47 825 feature.hasTimestamp = true;
c@47 826
c@47 827 char labelBuffer[100];
c@47 828
c@47 829 for (int i = 0; i < m_channels; ++i) {
c@47 830
c@47 831 feature.timestamp = Vamp::RealTime(i, 0);
c@47 832
c@47 833 sprintf(labelBuffer, "Beat spectrum for channel %d", i+1);
c@47 834 feature.label = labelBuffer;
c@47 835
c@47 836 feature.values.clear();
c@47 837 for (int j = 0; j < bs[i].size(); ++j) {
c@47 838 feature.values.push_back(bs[i][j]);
c@47 839 }
c@47 840
c@47 841 returnFeatures[m_beatSpectraOutput].push_back(feature);
c@47 842 }
c@47 843
c@47 844 return distances;
c@47 845 }
c@47 846
c@47 847 double
c@47 848 SimilarityPlugin::getDistance(const FeatureMatrix &timbral,
c@47 849 const FeatureMatrix &rhythmic,
c@47 850 int i, int j)
c@47 851 {
c@47 852 double distance = 1.0;
c@47 853 if (needTimbre()) distance *= timbral[i][j];
c@47 854 if (needRhythm()) distance *= rhythmic[i][j];
c@47 855 return distance;
c@47 856 }
c@47 857
c@47 858 SimilarityPlugin::FeatureSet
c@47 859 SimilarityPlugin::getRemainingFeatures()
c@47 860 {
c@47 861 FeatureSet returnFeatures;
c@47 862
c@47 863 // We want to return a matrix of the distances between channels,
c@47 864 // but Vamp doesn't have a matrix return type so we will actually
c@47 865 // return a series of vectors
c@47 866
c@47 867 FeatureMatrix timbralDistances, rhythmicDistances;
c@47 868
c@47 869 if (needTimbre()) {
c@47 870 timbralDistances = calculateTimbral(returnFeatures);
c@47 871 }
c@47 872
c@47 873 if (needRhythm()) {
c@47 874 rhythmicDistances = calculateRhythmic(returnFeatures);
c@47 875 }
c@47 876
c@47 877 // We give all features a timestamp, otherwise hosts will tend to
c@47 878 // stamp them at the end of the file, which is annoying
c@47 879
c@47 880 Feature feature;
c@47 881 feature.hasTimestamp = true;
c@47 882
c@47 883 Feature distanceVectorFeature;
c@47 884 distanceVectorFeature.label = "Distance from first channel";
c@47 885 distanceVectorFeature.hasTimestamp = true;
c@47 886 distanceVectorFeature.timestamp = Vamp::RealTime::zeroTime;
c@47 887
c@47 888 std::map<double, int> sorted;
c@47 889
c@47 890 char labelBuffer[100];
c@47 891
c@47 892 for (int i = 0; i < m_channels; ++i) {
c@47 893
c@47 894 feature.timestamp = Vamp::RealTime(i, 0);
c@41 895
c@41 896 feature.values.clear();
c@41 897 for (int j = 0; j < m_channels; ++j) {
c@47 898 double dist = getDistance(timbralDistances, rhythmicDistances, i, j);
c@47 899 feature.values.push_back(dist);
c@41 900 }
c@43 901
c@44 902 sprintf(labelBuffer, "Distances from channel %d", i+1);
c@44 903 feature.label = labelBuffer;
c@41 904
c@43 905 returnFeatures[m_distanceMatrixOutput].push_back(feature);
c@43 906
c@47 907 double fromFirst =
c@47 908 getDistance(timbralDistances, rhythmicDistances, 0, i);
c@44 909
c@47 910 distanceVectorFeature.values.push_back(fromFirst);
c@47 911 sorted[fromFirst] = i;
c@41 912 }
c@41 913
c@43 914 returnFeatures[m_distanceVectorOutput].push_back(distanceVectorFeature);
c@43 915
c@44 916 feature.label = "Order of channels by similarity to first channel";
c@44 917 feature.values.clear();
c@44 918 feature.timestamp = Vamp::RealTime(0, 0);
c@44 919
c@44 920 for (std::map<double, int>::iterator i = sorted.begin();
c@44 921 i != sorted.end(); ++i) {
c@45 922 feature.values.push_back(i->second + 1);
c@44 923 }
c@44 924
c@44 925 returnFeatures[m_sortedVectorOutput].push_back(feature);
c@44 926
c@44 927 feature.label = "Ordered distances of channels from first channel";
c@44 928 feature.values.clear();
c@44 929 feature.timestamp = Vamp::RealTime(1, 0);
c@44 930
c@44 931 for (std::map<double, int>::iterator i = sorted.begin();
c@44 932 i != sorted.end(); ++i) {
c@44 933 feature.values.push_back(i->first);
c@44 934 }
c@44 935
c@44 936 returnFeatures[m_sortedVectorOutput].push_back(feature);
c@44 937
c@41 938 return returnFeatures;
c@41 939 }