annotate plugins/SimilarityPlugin.cpp @ 130:c655fa61884f

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