annotate segmentino/Segmentino.cpp @ 60:b536a23b8523

added comment to weird beat-deletion code
author matthiasm
date Thu, 13 Jun 2013 16:38:04 +0100
parents 6be9479ad11f
children 8bd9b79c9e83
rev   line source
max@1 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
max@1 2
max@1 3 /*
Chris@48 4 Segmentino
max@1 5
Chris@48 6 Code by Massimiliano Zanoni and Matthias Mauch
Chris@48 7 Centre for Digital Music, Queen Mary, University of London
Chris@48 8
Chris@48 9 Copyright 2009-2013 Queen Mary, University of London.
max@1 10
max@1 11 This program is free software; you can redistribute it and/or
max@1 12 modify it under the terms of the GNU General Public License as
max@1 13 published by the Free Software Foundation; either version 2 of the
max@1 14 License, or (at your option) any later version. See the file
max@1 15 COPYING included with this distribution for more information.
max@1 16 */
max@1 17
Chris@48 18 #include "Segmentino.h"
max@1 19
Chris@49 20 #include <qm-dsp/base/Window.h>
Chris@49 21 #include <qm-dsp/dsp/onsets/DetectionFunction.h>
Chris@49 22 #include <qm-dsp/dsp/onsets/PeakPicking.h>
Chris@49 23 #include <qm-dsp/dsp/transforms/FFT.h>
Chris@49 24 #include <qm-dsp/dsp/tempotracking/TempoTrackV2.h>
Chris@49 25 #include <qm-dsp/dsp/tempotracking/DownBeat.h>
Chris@49 26 #include <qm-dsp/maths/MathUtilities.h>
Chris@49 27
Chris@49 28 #include <nnls-chroma/chromamethods.h>
Chris@49 29
Chris@49 30 #include <armadillo>
Chris@49 31
max@1 32 #include <fstream>
max@1 33 #include <sstream>
max@1 34 #include <cmath>
max@1 35 #include <vector>
max@1 36
max@1 37 #include <vamp-sdk/Plugin.h>
max@1 38
Chris@56 39 using arma::colvec;
Chris@56 40 using arma::conv;
Chris@56 41 using arma::cor;
Chris@56 42 using arma::cube;
Chris@56 43 using arma::eye;
Chris@56 44 using arma::imat;
Chris@56 45 using arma::irowvec;
Chris@56 46 using arma::linspace;
Chris@56 47 using arma::mat;
Chris@56 48 using arma::max;
Chris@56 49 using arma::ones;
Chris@56 50 using arma::rowvec;
Chris@56 51 using arma::sort;
Chris@56 52 using arma::span;
Chris@56 53 using arma::sum;
Chris@56 54 using arma::trans;
Chris@56 55 using arma::uvec;
Chris@56 56 using arma::uword;
Chris@56 57 using arma::vec;
Chris@56 58 using arma::zeros;
Chris@56 59
max@1 60 using std::string;
max@1 61 using std::vector;
max@1 62 using std::cerr;
max@1 63 using std::cout;
max@1 64 using std::endl;
max@1 65
max@1 66 #ifndef __GNUC__
max@1 67 #include <alloca.h>
max@1 68 #endif
max@1 69
max@1 70
max@1 71 // Result Struct
max@1 72 typedef struct Part {
max@1 73 int n;
Chris@21 74 vector<int> indices;
max@1 75 string letter;
Chris@21 76 int value;
max@1 77 int level;
max@1 78 int nInd;
max@1 79 }Part;
max@1 80
max@1 81
max@8 82
max@1 83 /* ------------------------------------ */
max@1 84 /* ----- BEAT DETECTOR CLASS ---------- */
max@1 85 /* ------------------------------------ */
max@1 86
max@1 87 class BeatTrackerData
max@1 88 {
max@1 89 /* --- ATTRIBUTES --- */
max@1 90 public:
max@1 91 DFConfig dfConfig;
max@1 92 DetectionFunction *df;
max@1 93 DownBeat *downBeat;
max@1 94 vector<double> dfOutput;
max@1 95 Vamp::RealTime origin;
max@1 96
max@1 97
max@1 98 /* --- METHODS --- */
max@1 99
max@1 100 /* --- Constructor --- */
max@1 101 public:
max@1 102 BeatTrackerData(float rate, const DFConfig &config) : dfConfig(config) {
Chris@22 103
max@1 104 df = new DetectionFunction(config);
max@1 105 // decimation factor aims at resampling to c. 3KHz; must be power of 2
max@1 106 int factor = MathUtilities::nextPowerOfTwo(rate / 3000);
max@1 107 // std::cerr << "BeatTrackerData: factor = " << factor << std::endl;
max@1 108 downBeat = new DownBeat(rate, factor, config.stepSize);
max@1 109 }
max@1 110
max@1 111 /* --- Desctructor --- */
max@1 112 ~BeatTrackerData() {
Chris@22 113 delete df;
max@1 114 delete downBeat;
max@1 115 }
max@1 116
max@1 117 void reset() {
max@1 118 delete df;
max@1 119 df = new DetectionFunction(dfConfig);
max@1 120 dfOutput.clear();
max@1 121 downBeat->resetAudioBuffer();
max@1 122 origin = Vamp::RealTime::zeroTime;
max@1 123 }
max@1 124 };
max@1 125
max@1 126
max@1 127 /* --------------------------------------- */
max@1 128 /* ----- CHROMA EXTRACTOR CLASS ---------- */
max@1 129 /* --------------------------------------- */
max@1 130
max@1 131 class ChromaData
max@1 132 {
max@1 133
max@1 134 /* --- ATTRIBUTES --- */
max@1 135
max@1 136 public:
max@1 137 int frameCount;
max@1 138 int nBPS;
max@1 139 Vamp::Plugin::FeatureList logSpectrum;
Chris@37 140 int blockSize;
max@1 141 int lengthOfNoteIndex;
max@1 142 vector<float> meanTunings;
max@1 143 vector<float> localTunings;
max@1 144 float whitening;
max@1 145 float preset;
max@1 146 float useNNLS;
max@1 147 vector<float> localTuning;
max@1 148 vector<float> kernelValue;
max@1 149 vector<int> kernelFftIndex;
max@1 150 vector<int> kernelNoteIndex;
max@1 151 float *dict;
max@1 152 bool tuneLocal;
max@1 153 float doNormalizeChroma;
max@1 154 float rollon;
max@1 155 float s;
max@1 156 vector<float> hw;
max@1 157 vector<float> sinvalues;
max@1 158 vector<float> cosvalues;
max@1 159 Window<float> window;
max@1 160 FFTReal fft;
Chris@37 161 int inputSampleRate;
max@1 162
max@1 163 /* --- METHODS --- */
max@1 164
max@1 165 /* --- Constructor --- */
max@1 166
max@1 167 public:
max@1 168 ChromaData(float inputSampleRate, size_t block_size) :
max@1 169 frameCount(0),
max@1 170 nBPS(3),
max@1 171 logSpectrum(0),
max@1 172 blockSize(0),
max@1 173 lengthOfNoteIndex(0),
max@1 174 meanTunings(0),
max@1 175 localTunings(0),
max@1 176 whitening(1.0),
max@1 177 preset(0.0),
max@1 178 useNNLS(1.0),
max@1 179 localTuning(0.0),
max@1 180 kernelValue(0),
max@1 181 kernelFftIndex(0),
max@1 182 kernelNoteIndex(0),
max@1 183 dict(0),
max@1 184 tuneLocal(0.0),
max@1 185 doNormalizeChroma(0),
max@1 186 rollon(0.0),
Chris@35 187 s(0.7),
Chris@35 188 sinvalues(0),
Chris@35 189 cosvalues(0),
Chris@35 190 window(HanningWindow, block_size),
Chris@35 191 fft(block_size),
Chris@35 192 inputSampleRate(inputSampleRate)
max@1 193 {
max@1 194 // make the *note* dictionary matrix
max@1 195 dict = new float[nNote * 84];
max@1 196 for (int i = 0; i < nNote * 84; ++i) dict[i] = 0.0;
max@1 197 blockSize = block_size;
max@1 198 }
max@1 199
max@1 200
max@1 201 /* --- Desctructor --- */
max@1 202
max@1 203 ~ChromaData() {
max@1 204 delete [] dict;
max@1 205 }
max@1 206
max@1 207 /* --- Public Methods --- */
max@1 208
max@1 209 void reset() {
max@1 210 frameCount = 0;
max@1 211 logSpectrum.clear();
max@1 212 for (int iBPS = 0; iBPS < 3; ++iBPS) {
max@1 213 meanTunings[iBPS] = 0;
max@1 214 localTunings[iBPS] = 0;
max@1 215 }
max@1 216 localTuning.clear();
max@1 217 }
max@1 218
max@1 219 void baseProcess(float *inputBuffers, Vamp::RealTime timestamp)
max@1 220 {
Chris@22 221
max@1 222 frameCount++;
max@1 223 float *magnitude = new float[blockSize/2];
max@1 224 double *fftReal = new double[blockSize];
max@1 225 double *fftImag = new double[blockSize];
max@1 226
max@1 227 // FFTReal wants doubles, so we need to make a local copy of inputBuffers
max@1 228 double *inputBuffersDouble = new double[blockSize];
Chris@37 229 for (int i = 0; i < blockSize; i++) inputBuffersDouble[i] = inputBuffers[i];
max@1 230
max@1 231 fft.process(false, inputBuffersDouble, fftReal, fftImag);
max@1 232
max@1 233 float energysum = 0;
max@1 234 // make magnitude
max@1 235 float maxmag = -10000;
max@1 236 for (int iBin = 0; iBin < static_cast<int>(blockSize/2); iBin++) {
max@1 237 magnitude[iBin] = sqrt(fftReal[iBin] * fftReal[iBin] +
max@1 238 fftImag[iBin] * fftImag[iBin]);
max@1 239 if (magnitude[iBin]>blockSize*1.0) magnitude[iBin] = blockSize;
max@1 240 // a valid audio signal (between -1 and 1) should not be limited here.
max@1 241 if (maxmag < magnitude[iBin]) maxmag = magnitude[iBin];
max@1 242 if (rollon > 0) {
max@1 243 energysum += pow(magnitude[iBin],2);
max@1 244 }
max@1 245 }
max@1 246
max@1 247 float cumenergy = 0;
max@1 248 if (rollon > 0) {
max@1 249 for (int iBin = 2; iBin < static_cast<int>(blockSize/2); iBin++) {
max@1 250 cumenergy += pow(magnitude[iBin],2);
max@1 251 if (cumenergy < energysum * rollon / 100) magnitude[iBin-2] = 0;
max@1 252 else break;
max@1 253 }
max@1 254 }
max@1 255
max@1 256 if (maxmag < 2) {
max@1 257 // cerr << "timestamp " << timestamp << ": very low magnitude, setting magnitude to all zeros" << endl;
max@1 258 for (int iBin = 0; iBin < static_cast<int>(blockSize/2); iBin++) {
max@1 259 magnitude[iBin] = 0;
max@1 260 }
max@1 261 }
max@1 262
max@1 263 // cerr << magnitude[200] << endl;
max@1 264
max@1 265 // note magnitude mapping using pre-calculated matrix
max@1 266 float *nm = new float[nNote]; // note magnitude
max@1 267 for (int iNote = 0; iNote < nNote; iNote++) {
max@1 268 nm[iNote] = 0; // initialise as 0
max@1 269 }
max@1 270 int binCount = 0;
max@1 271 for (vector<float>::iterator it = kernelValue.begin(); it != kernelValue.end(); ++it) {
max@1 272 nm[kernelNoteIndex[binCount]] += magnitude[kernelFftIndex[binCount]] * kernelValue[binCount];
max@1 273 binCount++;
max@1 274 }
max@1 275
max@1 276 float one_over_N = 1.0/frameCount;
max@1 277 // update means of complex tuning variables
max@1 278 for (int iBPS = 0; iBPS < nBPS; ++iBPS) meanTunings[iBPS] *= float(frameCount-1)*one_over_N;
max@1 279
max@1 280 for (int iTone = 0; iTone < round(nNote*0.62/nBPS)*nBPS+1; iTone = iTone + nBPS) {
max@1 281 for (int iBPS = 0; iBPS < nBPS; ++iBPS) meanTunings[iBPS] += nm[iTone + iBPS]*one_over_N;
max@1 282 float ratioOld = 0.997;
max@1 283 for (int iBPS = 0; iBPS < nBPS; ++iBPS) {
max@1 284 localTunings[iBPS] *= ratioOld;
max@1 285 localTunings[iBPS] += nm[iTone + iBPS] * (1 - ratioOld);
max@1 286 }
max@1 287 }
max@1 288
max@1 289 float localTuningImag = 0;
max@1 290 float localTuningReal = 0;
max@1 291 for (int iBPS = 0; iBPS < nBPS; ++iBPS) {
max@1 292 localTuningReal += localTunings[iBPS] * cosvalues[iBPS];
max@1 293 localTuningImag += localTunings[iBPS] * sinvalues[iBPS];
max@1 294 }
max@1 295
max@1 296 float normalisedtuning = atan2(localTuningImag, localTuningReal)/(2*M_PI);
max@1 297 localTuning.push_back(normalisedtuning);
max@1 298
max@1 299 Vamp::Plugin::Feature f1; // logfreqspec
max@1 300 f1.hasTimestamp = true;
max@1 301 f1.timestamp = timestamp;
max@1 302 for (int iNote = 0; iNote < nNote; iNote++) {
max@1 303 f1.values.push_back(nm[iNote]);
max@1 304 }
max@1 305
max@1 306 // deletes
max@1 307 delete[] inputBuffersDouble;
max@1 308 delete[] magnitude;
max@1 309 delete[] fftReal;
max@1 310 delete[] fftImag;
max@1 311 delete[] nm;
max@1 312
max@1 313 logSpectrum.push_back(f1); // remember note magnitude
max@1 314 }
max@1 315
max@1 316 bool initialise()
max@1 317 {
max@1 318 dictionaryMatrix(dict, s);
Chris@22 319
Chris@37 320 // make things for tuning estimation
Chris@37 321 for (int iBPS = 0; iBPS < nBPS; ++iBPS) {
max@1 322 sinvalues.push_back(sin(2*M_PI*(iBPS*1.0/nBPS)));
max@1 323 cosvalues.push_back(cos(2*M_PI*(iBPS*1.0/nBPS)));
max@1 324 }
max@1 325
Chris@22 326
Chris@37 327 // make hamming window of length 1/2 octave
Chris@37 328 int hamwinlength = nBPS * 6 + 1;
max@1 329 float hamwinsum = 0;
max@1 330 for (int i = 0; i < hamwinlength; ++i) {
max@1 331 hw.push_back(0.54 - 0.46 * cos((2*M_PI*i)/(hamwinlength-1)));
max@1 332 hamwinsum += 0.54 - 0.46 * cos((2*M_PI*i)/(hamwinlength-1));
max@1 333 }
max@1 334 for (int i = 0; i < hamwinlength; ++i) hw[i] = hw[i] / hamwinsum;
max@1 335
max@1 336
max@1 337 // initialise the tuning
max@1 338 for (int iBPS = 0; iBPS < nBPS; ++iBPS) {
max@1 339 meanTunings.push_back(0);
max@1 340 localTunings.push_back(0);
max@1 341 }
Chris@22 342
max@1 343 blockSize = blockSize;
max@1 344 frameCount = 0;
max@1 345 int tempn = nNote * blockSize/2;
max@1 346 // cerr << "length of tempkernel : " << tempn << endl;
max@1 347 float *tempkernel;
max@1 348
max@1 349 tempkernel = new float[tempn];
max@1 350
max@1 351 logFreqMatrix(inputSampleRate, blockSize, tempkernel);
max@1 352 kernelValue.clear();
max@1 353 kernelFftIndex.clear();
max@1 354 kernelNoteIndex.clear();
max@1 355 int countNonzero = 0;
max@1 356 for (int iNote = 0; iNote < nNote; ++iNote) {
max@1 357 // I don't know if this is wise: manually making a sparse matrix
max@1 358 for (int iFFT = 0; iFFT < static_cast<int>(blockSize/2); ++iFFT) {
max@1 359 if (tempkernel[iFFT + blockSize/2 * iNote] > 0) {
max@1 360 kernelValue.push_back(tempkernel[iFFT + blockSize/2 * iNote]);
max@1 361 if (tempkernel[iFFT + blockSize/2 * iNote] > 0) {
max@1 362 countNonzero++;
max@1 363 }
max@1 364 kernelFftIndex.push_back(iFFT);
Chris@23 365 kernelNoteIndex.push_back(iNote);
max@1 366 }
max@1 367 }
max@1 368 }
max@1 369 delete [] tempkernel;
Chris@37 370
Chris@37 371 return true;
max@1 372 }
max@1 373 };
max@1 374
max@1 375
max@1 376 /* --------------------------------- */
max@1 377 /* ----- SONG PARTITIONER ---------- */
max@1 378 /* --------------------------------- */
max@1 379
max@1 380
max@1 381 /* --- ATTRIBUTES --- */
max@1 382
Chris@48 383 float Segmentino::m_stepSecs = 0.01161; // 512 samples at 44100
Chris@48 384 int Segmentino::m_chromaFramesizeFactor = 16; // 16 times as long as beat tracker's
Chris@48 385 int Segmentino::m_chromaStepsizeFactor = 4; // 4 times as long as beat tracker's
max@1 386
max@1 387
max@1 388 /* --- METHODS --- */
max@1 389
max@1 390 /* --- Constructor --- */
Chris@48 391 Segmentino::Segmentino(float inputSampleRate) :
max@1 392 Vamp::Plugin(inputSampleRate),
max@1 393 m_d(0),
Chris@35 394 m_chromadata(0),
max@1 395 m_bpb(4),
max@1 396 m_pluginFrameCount(0)
max@1 397 {
max@1 398 }
max@1 399
max@1 400
max@1 401 /* --- Desctructor --- */
Chris@48 402 Segmentino::~Segmentino()
max@1 403 {
max@1 404 delete m_d;
Chris@35 405 delete m_chromadata;
max@1 406 }
max@1 407
max@1 408
max@1 409 /* --- Methods --- */
Chris@48 410 string Segmentino::getIdentifier() const
max@1 411 {
Chris@54 412 return "segmentino";
max@1 413 }
max@1 414
Chris@48 415 string Segmentino::getName() const
max@1 416 {
Chris@54 417 return "Segmentino";
max@1 418 }
max@1 419
Chris@48 420 string Segmentino::getDescription() const
max@1 421 {
max@1 422 return "Estimate contiguous segments pertaining to song parts such as verse and chorus.";
max@1 423 }
max@1 424
Chris@48 425 string Segmentino::getMaker() const
max@1 426 {
max@1 427 return "Queen Mary, University of London";
max@1 428 }
max@1 429
Chris@48 430 int Segmentino::getPluginVersion() const
max@1 431 {
max@1 432 return 2;
max@1 433 }
max@1 434
Chris@48 435 string Segmentino::getCopyright() const
max@1 436 {
max@1 437 return "Plugin by Matthew Davies, Christian Landone, Chris Cannam, Matthias Mauch and Massimiliano Zanoni Copyright (c) 2006-2012 QMUL - All Rights Reserved";
max@1 438 }
max@1 439
Chris@48 440 Segmentino::ParameterList Segmentino::getParameterDescriptors() const
max@1 441 {
max@1 442 ParameterList list;
max@1 443
max@1 444 ParameterDescriptor desc;
max@1 445
matthiasm@46 446 // desc.identifier = "bpb";
matthiasm@46 447 // desc.name = "Beats per Bar";
matthiasm@46 448 // desc.description = "The number of beats in each bar";
matthiasm@46 449 // desc.minValue = 2;
matthiasm@46 450 // desc.maxValue = 16;
matthiasm@46 451 // desc.defaultValue = 4;
matthiasm@46 452 // desc.isQuantized = true;
matthiasm@46 453 // desc.quantizeStep = 1;
matthiasm@46 454 // list.push_back(desc);
max@1 455
max@1 456 return list;
max@1 457 }
max@1 458
Chris@48 459 float Segmentino::getParameter(std::string name) const
max@1 460 {
max@1 461 if (name == "bpb") return m_bpb;
max@1 462 return 0.0;
max@1 463 }
max@1 464
Chris@48 465 void Segmentino::setParameter(std::string name, float value)
max@1 466 {
max@1 467 if (name == "bpb") m_bpb = lrintf(value);
max@1 468 }
max@1 469
max@1 470
max@1 471 // Return the StepSize for Chroma Extractor
Chris@48 472 size_t Segmentino::getPreferredStepSize() const
max@1 473 {
max@1 474 size_t step = size_t(m_inputSampleRate * m_stepSecs + 0.0001);
max@1 475 if (step < 1) step = 1;
max@1 476
max@1 477 return step;
max@1 478 }
max@1 479
max@1 480 // Return the BlockSize for Chroma Extractor
Chris@48 481 size_t Segmentino::getPreferredBlockSize() const
max@1 482 {
Chris@50 483 int theoretical = getPreferredStepSize() * 2;
max@1 484 theoretical *= m_chromaFramesizeFactor;
Chris@50 485 return MathUtilities::nextPowerOfTwo(theoretical);
max@1 486 }
max@1 487
max@1 488
max@1 489 // Initialize the plugin and define Beat Tracker and Chroma Extractor Objects
Chris@48 490 bool Segmentino::initialise(size_t channels, size_t stepSize, size_t blockSize)
max@1 491 {
max@1 492 if (m_d) {
Chris@22 493 delete m_d;
Chris@22 494 m_d = 0;
max@1 495 }
Chris@35 496 if (m_chromadata) {
Chris@35 497 delete m_chromadata;
Chris@35 498 m_chromadata = 0;
Chris@35 499 }
max@1 500
max@1 501 if (channels < getMinChannelCount() ||
Chris@22 502 channels > getMaxChannelCount()) {
Chris@48 503 std::cerr << "Segmentino::initialise: Unsupported channel count: "
max@1 504 << channels << std::endl;
max@1 505 return false;
max@1 506 }
max@1 507
max@1 508 if (stepSize != getPreferredStepSize()) {
Chris@48 509 std::cerr << "ERROR: Segmentino::initialise: Unsupported step size for this sample rate: "
max@1 510 << stepSize << " (wanted " << (getPreferredStepSize()) << ")" << std::endl;
max@1 511 return false;
max@1 512 }
max@1 513
max@1 514 if (blockSize != getPreferredBlockSize()) {
Chris@48 515 std::cerr << "WARNING: Segmentino::initialise: Sub-optimal block size for this sample rate: "
max@1 516 << blockSize << " (wanted " << getPreferredBlockSize() << ")" << std::endl;
max@1 517 }
max@1 518
max@1 519 // Beat tracker and Chroma extractor has two different configuration parameters
max@1 520
max@1 521 // Configuration Parameters for Beat Tracker
max@1 522 DFConfig dfConfig;
max@1 523 dfConfig.DFType = DF_COMPLEXSD;
max@1 524 dfConfig.stepSize = stepSize;
max@1 525 dfConfig.frameLength = blockSize / m_chromaFramesizeFactor;
max@1 526 dfConfig.dbRise = 3;
max@1 527 dfConfig.adaptiveWhitening = false;
max@1 528 dfConfig.whiteningRelaxCoeff = -1;
max@1 529 dfConfig.whiteningFloor = -1;
max@1 530
max@1 531 // Initialise Beat Tracker
max@1 532 m_d = new BeatTrackerData(m_inputSampleRate, dfConfig);
max@1 533 m_d->downBeat->setBeatsPerBar(m_bpb);
max@1 534
max@1 535 // Initialise Chroma Extractor
max@1 536 m_chromadata = new ChromaData(m_inputSampleRate, blockSize);
max@1 537 m_chromadata->initialise();
max@1 538
matthiasm@59 539 // definition of outputs numbers used internally
matthiasm@59 540 int outputCounter = 1;
matthiasm@59 541 m_beatOutputNumber = outputCounter++;
matthiasm@59 542 m_barsOutputNumber = outputCounter++;
matthiasm@59 543 m_beatcountsOutputNumber = outputCounter++;
matthiasm@59 544 m_beatsdOutputNumber = outputCounter++;
matthiasm@59 545 m_logscalespecOutputNumber = outputCounter++;
matthiasm@59 546 m_bothchromaOutputNumber = outputCounter++;
matthiasm@59 547 m_qchromafwOutputNumber = outputCounter++;
matthiasm@59 548 m_qchromaOutputNumber = outputCounter++;
matthiasm@59 549
max@1 550 return true;
max@1 551 }
max@1 552
Chris@48 553 void Segmentino::reset()
max@1 554 {
max@1 555 if (m_d) m_d->reset();
Chris@38 556 if (m_chromadata) m_chromadata->reset();
max@1 557 m_pluginFrameCount = 0;
max@1 558 }
max@1 559
Chris@48 560 Segmentino::OutputList Segmentino::getOutputDescriptors() const
max@1 561 {
matthiasm@59 562
max@1 563 OutputList list;
max@1 564
max@1 565 OutputDescriptor segm;
Chris@15 566 segm.identifier = "segmentation";
max@1 567 segm.name = "Segmentation";
max@1 568 segm.description = "Segmentation";
max@1 569 segm.unit = "segment-type";
max@1 570 segm.hasFixedBinCount = true;
max@1 571 //segm.binCount = 24;
max@1 572 segm.binCount = 1;
max@1 573 segm.hasKnownExtents = true;
max@1 574 segm.minValue = 1;
max@1 575 segm.maxValue = 5;
max@1 576 segm.isQuantized = true;
max@1 577 segm.quantizeStep = 1;
max@1 578 segm.sampleType = OutputDescriptor::VariableSampleRate;
Chris@17 579 segm.sampleRate = 1.0 / m_stepSecs;
max@1 580 segm.hasDuration = true;
matthiasm@59 581 m_segmOutputNumber = 0;
matthiasm@59 582
max@1 583 list.push_back(segm);
max@1 584
max@1 585 return list;
max@1 586 }
max@1 587
max@1 588 // Executed for each frame - called from the host
max@1 589
max@1 590 // We use time domain input, because DownBeat requires it -- so we
max@1 591 // use the time-domain version of DetectionFunction::process which
max@1 592 // does its own FFT. It requires doubles as input, so we need to
max@1 593 // make a temporary copy
max@1 594
max@1 595 // We only support a single input channel
Chris@48 596 Segmentino::FeatureSet Segmentino::process(const float *const *inputBuffers,Vamp::RealTime timestamp)
max@1 597 {
max@1 598 if (!m_d) {
Chris@48 599 cerr << "ERROR: Segmentino::process: "
Chris@48 600 << "Segmentino has not been initialised"
Chris@22 601 << endl;
Chris@22 602 return FeatureSet();
max@1 603 }
max@1 604
max@1 605 const int fl = m_d->dfConfig.frameLength;
max@1 606 #ifndef __GNUC__
max@1 607 double *dfinput = (double *)alloca(fl * sizeof(double));
max@1 608 #else
max@1 609 double dfinput[fl];
max@1 610 #endif
max@1 611 int sampleOffset = ((m_chromaFramesizeFactor-1) * fl) / 2;
max@1 612
max@1 613 // Since chroma needs a much longer frame size, we only ever use the very
max@1 614 // beginning of the frame for beat tracking.
max@1 615 for (int i = 0; i < fl; ++i) dfinput[i] = inputBuffers[0][i];
max@1 616 double output = m_d->df->process(dfinput);
max@1 617
max@1 618 if (m_d->dfOutput.empty()) m_d->origin = timestamp;
max@1 619
max@1 620 // std::cerr << "df[" << m_d->dfOutput.size() << "] is " << output << std::endl;
max@1 621 m_d->dfOutput.push_back(output);
max@1 622
max@1 623 // Downsample and store the incoming audio block.
max@1 624 // We have an overlap on the incoming audio stream (step size is
max@1 625 // half block size) -- this function is configured to take only a
max@1 626 // step size's worth, so effectively ignoring the overlap. Note
max@1 627 // however that this means we omit the last blocksize - stepsize
max@1 628 // samples completely for the purposes of barline detection
max@1 629 // (hopefully not a problem)
max@1 630 m_d->downBeat->pushAudioBlock(inputBuffers[0]);
max@1 631
max@1 632 // The following is not done every time, but only every m_chromaFramesizeFactor times,
max@1 633 // because the chroma does not need dense time frames.
max@1 634
max@1 635 if (m_pluginFrameCount % m_chromaStepsizeFactor == 0)
max@1 636 {
max@1 637
max@1 638 // Window the full time domain, data, FFT it and process chroma stuff.
max@1 639
max@1 640 #ifndef __GNUC__
max@1 641 float *windowedBuffers = (float *)alloca(m_chromadata->blockSize * sizeof(float));
max@1 642 #else
max@1 643 float windowedBuffers[m_chromadata->blockSize];
max@1 644 #endif
max@1 645 m_chromadata->window.cut(&inputBuffers[0][0], &windowedBuffers[0]);
max@1 646
max@1 647 // adjust timestamp (we want the middle of the frame)
max@1 648 timestamp = timestamp + Vamp::RealTime::frame2RealTime(sampleOffset, lrintf(m_inputSampleRate));
max@1 649
max@1 650 m_chromadata->baseProcess(&windowedBuffers[0], timestamp);
max@1 651
max@1 652 }
max@1 653 m_pluginFrameCount++;
max@1 654
max@1 655 FeatureSet fs;
max@1 656 fs[m_logscalespecOutputNumber].push_back(
max@1 657 m_chromadata->logSpectrum.back());
max@1 658 return fs;
max@1 659 }
max@1 660
Chris@48 661 Segmentino::FeatureSet Segmentino::getRemainingFeatures()
max@1 662 {
max@1 663 if (!m_d) {
Chris@48 664 cerr << "ERROR: Segmentino::getRemainingFeatures: "
Chris@48 665 << "Segmentino has not been initialised"
Chris@22 666 << endl;
Chris@22 667 return FeatureSet();
max@1 668 }
max@1 669
matthiasm@59 670 FeatureSet masterFeatureset;
matthiasm@59 671 FeatureSet internalFeatureset = beatTrack();
matthiasm@59 672
matthiasm@59 673 int beatcount = internalFeatureset[m_beatOutputNumber].size();
Chris@49 674 if (beatcount == 0) return Segmentino::FeatureSet();
matthiasm@59 675 Vamp::RealTime last_beattime = internalFeatureset[m_beatOutputNumber][beatcount-1].timestamp;
matthiasm@59 676
matthiasm@60 677 // // THIS FOLLOWING BIT IS WEIRD! REPLACES BEAT-TRACKED BEATS WITH
matthiasm@60 678 // // UNIFORM 0.5 SEC BEATS
matthiasm@59 679 // internalFeatureset[m_beatOutputNumber].clear();
matthiasm@59 680 // Vamp::RealTime beattime = Vamp::RealTime::fromSeconds(1.0);
matthiasm@59 681 // while (beattime < last_beattime)
matthiasm@59 682 // {
matthiasm@59 683 // Feature beatfeature;
matthiasm@59 684 // beatfeature.hasTimestamp = true;
matthiasm@59 685 // beatfeature.timestamp = beattime;
matthiasm@59 686 // masterFeatureset[m_beatOutputNumber].push_back(beatfeature);
matthiasm@59 687 // beattime = beattime + Vamp::RealTime::fromSeconds(0.5);
matthiasm@59 688 // }
matthiasm@46 689
Chris@16 690 FeatureList chromaList = chromaFeatures();
max@1 691
Chris@37 692 for (int i = 0; i < (int)chromaList.size(); ++i)
max@1 693 {
matthiasm@59 694 internalFeatureset[m_bothchromaOutputNumber].push_back(chromaList[i]);
max@1 695 }
max@1 696
max@1 697 // quantised and pseudo-quantised (beat-wise) chroma
matthiasm@59 698 std::vector<FeatureList> quantisedChroma = beatQuantiser(chromaList, internalFeatureset[m_beatOutputNumber]);
Chris@32 699
Chris@32 700 if (quantisedChroma.empty()) return masterFeatureset;
max@1 701
matthiasm@59 702 internalFeatureset[m_qchromafwOutputNumber] = quantisedChroma[0];
matthiasm@59 703 internalFeatureset[m_qchromaOutputNumber] = quantisedChroma[1];
max@1 704
max@1 705 // Segmentation
Chris@39 706 try {
Chris@39 707 masterFeatureset[m_segmOutputNumber] = runSegmenter(quantisedChroma[1]);
Chris@39 708 } catch (std::bad_alloc &a) {
Chris@48 709 cerr << "ERROR: Segmentino::getRemainingFeatures: Failed to run segmenter, not enough memory (song too long?)" << endl;
Chris@39 710 }
max@1 711
max@1 712 return(masterFeatureset);
max@1 713 }
max@1 714
max@1 715 /* ------ Beat Tracker ------ */
max@1 716
Chris@48 717 Segmentino::FeatureSet Segmentino::beatTrack()
max@1 718 {
max@1 719 vector<double> df;
max@1 720 vector<double> beatPeriod;
max@1 721 vector<double> tempi;
max@1 722
Chris@37 723 for (int i = 2; i < (int)m_d->dfOutput.size(); ++i) { // discard first two elts
max@1 724 df.push_back(m_d->dfOutput[i]);
max@1 725 beatPeriod.push_back(0.0);
max@1 726 }
max@1 727 if (df.empty()) return FeatureSet();
max@1 728
max@1 729 TempoTrackV2 tt(m_inputSampleRate, m_d->dfConfig.stepSize);
max@1 730 tt.calculateBeatPeriod(df, beatPeriod, tempi);
max@1 731
max@1 732 vector<double> beats;
max@1 733 tt.calculateBeats(df, beatPeriod, beats);
max@1 734
max@1 735 vector<int> downbeats;
max@1 736 size_t downLength = 0;
max@1 737 const float *downsampled = m_d->downBeat->getBufferedAudio(downLength);
max@1 738 m_d->downBeat->findDownBeats(downsampled, downLength, beats, downbeats);
max@1 739
max@1 740 vector<double> beatsd;
max@1 741 m_d->downBeat->getBeatSD(beatsd);
max@1 742
max@1 743 /*std::cout << "BeatTracker: found downbeats at: ";
max@1 744 for (int i = 0; i < downbeats.size(); ++i) std::cout << downbeats[i] << " " << std::endl;*/
max@1 745
max@1 746 FeatureSet returnFeatures;
max@1 747
max@1 748 char label[20];
max@1 749
max@1 750 int dbi = 0;
max@1 751 int beat = 0;
max@1 752 int bar = 0;
max@1 753
max@1 754 if (!downbeats.empty()) {
max@1 755 // get the right number for the first beat; this will be
max@1 756 // incremented before use (at top of the following loop)
max@1 757 int firstDown = downbeats[0];
max@1 758 beat = m_bpb - firstDown - 1;
max@1 759 if (beat == m_bpb) beat = 0;
max@1 760 }
max@1 761
Chris@37 762 for (int i = 0; i < (int)beats.size(); ++i) {
max@1 763
Chris@37 764 int frame = beats[i] * m_d->dfConfig.stepSize;
max@1 765
Chris@37 766 if (dbi < (int)downbeats.size() && i == downbeats[dbi]) {
max@1 767 beat = 0;
max@1 768 ++bar;
max@1 769 ++dbi;
max@1 770 } else {
max@1 771 ++beat;
max@1 772 }
max@1 773
max@1 774 /* Ooutput Section */
max@1 775
max@1 776 // outputs are:
max@1 777 //
max@1 778 // 0 -> beats
max@1 779 // 1 -> bars
max@1 780 // 2 -> beat counter function
max@1 781
max@1 782 Feature feature;
max@1 783 feature.hasTimestamp = true;
max@1 784 feature.timestamp = m_d->origin + Vamp::RealTime::frame2RealTime (frame, lrintf(m_inputSampleRate));
max@1 785
max@1 786 sprintf(label, "%d", beat + 1);
max@1 787 feature.label = label;
max@1 788 returnFeatures[m_beatOutputNumber].push_back(feature); // labelled beats
max@1 789
max@1 790 feature.values.push_back(beat + 1);
max@1 791 returnFeatures[m_beatcountsOutputNumber].push_back(feature); // beat function
max@1 792
Chris@37 793 if (i > 0 && i <= (int)beatsd.size()) {
max@1 794 feature.values.clear();
max@1 795 feature.values.push_back(beatsd[i-1]);
max@1 796 feature.label = "";
max@1 797 returnFeatures[m_beatsdOutputNumber].push_back(feature); // beat spectral difference
max@1 798 }
max@1 799
max@1 800 if (beat == 0) {
max@1 801 feature.values.clear();
max@1 802 sprintf(label, "%d", bar);
max@1 803 feature.label = label;
max@1 804 returnFeatures[m_barsOutputNumber].push_back(feature); // bars
max@1 805 }
max@1 806 }
max@1 807
max@1 808 return returnFeatures;
max@1 809 }
max@1 810
max@1 811
max@1 812 /* ------ Chroma Extractor ------ */
max@1 813
Chris@48 814 Segmentino::FeatureList Segmentino::chromaFeatures()
max@1 815 {
max@1 816
max@1 817 FeatureList returnFeatureList;
max@1 818 FeatureList tunedlogfreqspec;
max@1 819
max@1 820 if (m_chromadata->logSpectrum.size() == 0) return returnFeatureList;
max@1 821
max@1 822 /** Calculate Tuning
max@1 823 calculate tuning from (using the angle of the complex number defined by the
max@1 824 cumulative mean real and imag values)
max@1 825 **/
max@1 826 float meanTuningImag = 0;
max@1 827 float meanTuningReal = 0;
max@1 828 for (int iBPS = 0; iBPS < nBPS; ++iBPS) {
max@1 829 meanTuningReal += m_chromadata->meanTunings[iBPS] * m_chromadata->cosvalues[iBPS];
max@1 830 meanTuningImag += m_chromadata->meanTunings[iBPS] * m_chromadata->sinvalues[iBPS];
max@1 831 }
max@1 832 float cumulativetuning = 440 * pow(2,atan2(meanTuningImag, meanTuningReal)/(24*M_PI));
max@1 833 float normalisedtuning = atan2(meanTuningImag, meanTuningReal)/(2*M_PI);
max@1 834 int intShift = floor(normalisedtuning * 3);
max@1 835 float floatShift = normalisedtuning * 3 - intShift; // floatShift is a really bad name for this
max@1 836
max@1 837 char buffer0 [50];
max@1 838
max@1 839 sprintf(buffer0, "estimated tuning: %0.1f Hz", cumulativetuning);
max@1 840
max@1 841 /** Tune Log-Frequency Spectrogram
max@1 842 calculate a tuned log-frequency spectrogram (f2): use the tuning estimated above (kinda f0) to
max@1 843 perform linear interpolation on the existing log-frequency spectrogram (kinda f1).
max@1 844 **/
Chris@50 845 // cerr << endl << "[NNLS Chroma Plugin] Tuning Log-Frequency Spectrogram ... ";
max@1 846
max@1 847 float tempValue = 0;
max@1 848
max@1 849 int count = 0;
max@1 850
max@1 851 for (FeatureList::iterator i = m_chromadata->logSpectrum.begin(); i != m_chromadata->logSpectrum.end(); ++i)
max@1 852 {
max@1 853
max@1 854 Feature f1 = *i;
max@1 855 Feature f2; // tuned log-frequency spectrum
max@1 856
max@1 857 f2.hasTimestamp = true;
max@1 858 f2.timestamp = f1.timestamp;
max@1 859
max@1 860 f2.values.push_back(0.0);
max@1 861 f2.values.push_back(0.0); // set lower edge to zero
max@1 862
max@1 863 if (m_chromadata->tuneLocal) {
max@1 864 intShift = floor(m_chromadata->localTuning[count] * 3);
max@1 865 floatShift = m_chromadata->localTuning[count] * 3 - intShift;
max@1 866 // floatShift is a really bad name for this
max@1 867 }
max@1 868
max@1 869 for (int k = 2; k < (int)f1.values.size() - 3; ++k)
max@1 870 { // interpolate all inner bins
max@1 871 tempValue = f1.values[k + intShift] * (1-floatShift) + f1.values[k+intShift+1] * floatShift;
max@1 872 f2.values.push_back(tempValue);
max@1 873 }
max@1 874
max@1 875 f2.values.push_back(0.0);
max@1 876 f2.values.push_back(0.0);
max@1 877 f2.values.push_back(0.0); // upper edge
max@1 878
max@1 879 vector<float> runningmean = SpecialConvolution(f2.values,m_chromadata->hw);
max@1 880 vector<float> runningstd;
max@1 881 for (int i = 0; i < nNote; i++) { // first step: squared values into vector (variance)
max@1 882 runningstd.push_back((f2.values[i] - runningmean[i]) * (f2.values[i] - runningmean[i]));
max@1 883 }
max@1 884 runningstd = SpecialConvolution(runningstd,m_chromadata->hw); // second step convolve
max@1 885 for (int i = 0; i < nNote; i++)
max@1 886 {
max@1 887
max@1 888 runningstd[i] = sqrt(runningstd[i]);
max@1 889 // square root to finally have running std
max@1 890
max@1 891 if (runningstd[i] > 0)
max@1 892 {
max@1 893 f2.values[i] = (f2.values[i] - runningmean[i]) > 0 ?
max@1 894 (f2.values[i] - runningmean[i]) / pow(runningstd[i],m_chromadata->whitening) : 0;
max@1 895 }
max@1 896
max@1 897 if (f2.values[i] < 0) {
max@1 898
max@1 899 cerr << "ERROR: negative value in logfreq spectrum" << endl;
max@1 900
max@1 901 }
max@1 902 }
max@1 903 tunedlogfreqspec.push_back(f2);
max@1 904 count++;
max@1 905 }
Chris@50 906 // cerr << "done." << endl;
max@1 907 /** Semitone spectrum and chromagrams
max@1 908 Semitone-spaced log-frequency spectrum derived
max@1 909 from the tuned log-freq spectrum above. the spectrum
max@1 910 is inferred using a non-negative least squares algorithm.
max@1 911 Three different kinds of chromagram are calculated, "treble", "bass", and "both" (which means
max@1 912 bass and treble stacked onto each other).
max@1 913 **/
Chris@50 914 /*
max@1 915 if (m_chromadata->useNNLS == 0) {
max@1 916 cerr << "[NNLS Chroma Plugin] Mapping to semitone spectrum and chroma ... ";
max@1 917 } else {
max@1 918 cerr << "[NNLS Chroma Plugin] Performing NNLS and mapping to chroma ... ";
max@1 919 }
Chris@50 920 */
max@1 921 vector<float> oldchroma = vector<float>(12,0);
max@1 922 vector<float> oldbasschroma = vector<float>(12,0);
max@1 923 count = 0;
max@1 924
max@1 925 for (FeatureList::iterator it = tunedlogfreqspec.begin(); it != tunedlogfreqspec.end(); ++it) {
max@1 926 Feature logfreqsp = *it; // logfreq spectrum
max@1 927 Feature bothchroma; // treble and bass chromagram
max@1 928
max@1 929 bothchroma.hasTimestamp = true;
max@1 930 bothchroma.timestamp = logfreqsp.timestamp;
max@1 931
max@1 932 float b[nNote];
max@1 933
max@1 934 bool some_b_greater_zero = false;
max@1 935 float sumb = 0;
max@1 936 for (int i = 0; i < nNote; i++) {
max@1 937 b[i] = logfreqsp.values[i];
max@1 938 sumb += b[i];
max@1 939 if (b[i] > 0) {
max@1 940 some_b_greater_zero = true;
max@1 941 }
max@1 942 }
max@1 943
max@1 944 // here's where the non-negative least squares algorithm calculates the note activation x
max@1 945
max@1 946 vector<float> chroma = vector<float>(12, 0);
max@1 947 vector<float> basschroma = vector<float>(12, 0);
max@1 948 float currval;
max@1 949 int iSemitone = 0;
max@1 950
max@1 951 if (some_b_greater_zero) {
max@1 952 if (m_chromadata->useNNLS == 0) {
max@1 953 for (int iNote = nBPS/2 + 2; iNote < nNote - nBPS/2; iNote += nBPS) {
max@1 954 currval = 0;
max@1 955 for (int iBPS = -nBPS/2; iBPS < nBPS/2+1; ++iBPS) {
max@1 956 currval += b[iNote + iBPS] * (1-abs(iBPS*1.0/(nBPS/2+1)));
max@1 957 }
max@1 958 chroma[iSemitone % 12] += currval * treblewindow[iSemitone];
max@1 959 basschroma[iSemitone % 12] += currval * basswindow[iSemitone];
max@1 960 iSemitone++;
max@1 961 }
max@1 962
max@1 963 } else {
max@1 964 float x[84+1000];
max@1 965 for (int i = 1; i < 1084; ++i) x[i] = 1.0;
max@1 966 vector<int> signifIndex;
max@1 967 int index=0;
max@1 968 sumb /= 84.0;
max@1 969 for (int iNote = nBPS/2 + 2; iNote < nNote - nBPS/2; iNote += nBPS) {
max@1 970 float currval = 0;
max@1 971 for (int iBPS = -nBPS/2; iBPS < nBPS/2+1; ++iBPS) {
max@1 972 currval += b[iNote + iBPS];
max@1 973 }
max@1 974 if (currval > 0) signifIndex.push_back(index);
max@1 975 index++;
max@1 976 }
max@1 977 float rnorm;
max@1 978 float w[84+1000];
max@1 979 float zz[84+1000];
max@1 980 int indx[84+1000];
max@1 981 int mode;
max@1 982 int dictsize = nNote*signifIndex.size();
max@1 983
max@1 984 float *curr_dict = new float[dictsize];
max@1 985 for (int iNote = 0; iNote < (int)signifIndex.size(); ++iNote) {
max@1 986 for (int iBin = 0; iBin < nNote; iBin++) {
max@1 987 curr_dict[iNote * nNote + iBin] =
max@1 988 1.0 * m_chromadata->dict[signifIndex[iNote] * nNote + iBin];
max@1 989 }
max@1 990 }
max@1 991 nnls(curr_dict, nNote, nNote, signifIndex.size(), b, x, &rnorm, w, zz, indx, &mode);
max@1 992 delete [] curr_dict;
max@1 993 for (int iNote = 0; iNote < (int)signifIndex.size(); ++iNote) {
max@1 994 // cerr << mode << endl;
max@1 995 chroma[signifIndex[iNote] % 12] += x[iNote] * treblewindow[signifIndex[iNote]];
max@1 996 basschroma[signifIndex[iNote] % 12] += x[iNote] * basswindow[signifIndex[iNote]];
max@1 997 }
max@1 998 }
max@1 999 }
max@1 1000
max@1 1001 chroma.insert(chroma.begin(), basschroma.begin(), basschroma.end());
max@1 1002 // just stack the both chromas
max@1 1003
max@1 1004 bothchroma.values = chroma;
max@1 1005 returnFeatureList.push_back(bothchroma);
max@1 1006 count++;
max@1 1007 }
Chris@50 1008 // cerr << "done." << endl;
max@1 1009
max@1 1010 return returnFeatureList;
max@1 1011 }
max@1 1012
max@1 1013 /* ------ Beat Quantizer ------ */
max@1 1014
max@4 1015 std::vector<Vamp::Plugin::FeatureList>
Chris@48 1016 Segmentino::beatQuantiser(Vamp::Plugin::FeatureList chromagram, Vamp::Plugin::FeatureList beats)
max@1 1017 {
max@1 1018 std::vector<FeatureList> returnVector;
max@1 1019
max@1 1020 FeatureList fwQchromagram; // frame-wise beat-quantised chroma
max@1 1021 FeatureList bwQchromagram; // beat-wise beat-quantised chroma
matthiasm@43 1022
matthiasm@43 1023
matthiasm@43 1024 size_t nChromaFrame = chromagram.size();
matthiasm@43 1025 size_t nBeat = beats.size();
max@1 1026
max@1 1027 if (nBeat == 0 && nChromaFrame == 0) return returnVector;
max@1 1028
Chris@37 1029 int nBin = chromagram[0].values.size();
max@1 1030
max@1 1031 vector<float> tempChroma = vector<float>(nBin);
max@1 1032
max@1 1033 Vamp::RealTime beatTimestamp = Vamp::RealTime::zeroTime;
max@1 1034 int currBeatCount = -1; // start before first beat
max@1 1035 int framesInBeat = 0;
max@1 1036
matthiasm@43 1037 for (size_t iChroma = 0; iChroma < nChromaFrame; ++iChroma)
max@1 1038 {
max@4 1039 Vamp::RealTime frameTimestamp = chromagram[iChroma].timestamp;
Chris@24 1040 Vamp::RealTime newBeatTimestamp;
Chris@22 1041
Chris@37 1042 if (currBeatCount != (int)beats.size() - 1) {
Chris@37 1043 newBeatTimestamp = beats[currBeatCount+1].timestamp;
Chris@37 1044 } else {
Chris@37 1045 newBeatTimestamp = chromagram[nChromaFrame-1].timestamp;
Chris@37 1046 }
Chris@22 1047
Chris@24 1048 if (frameTimestamp > newBeatTimestamp ||
max@1 1049 iChroma == nChromaFrame-1)
max@1 1050 {
max@1 1051 // new beat (or last chroma frame)
max@1 1052 // 1. finish all the old beat processing
Chris@23 1053 if (framesInBeat > 0)
Chris@23 1054 {
Chris@23 1055 for (int i = 0; i < nBin; ++i) tempChroma[i] /= framesInBeat; // average
Chris@23 1056 }
max@1 1057
max@1 1058 Feature bwQchromaFrame;
max@1 1059 bwQchromaFrame.hasTimestamp = true;
max@1 1060 bwQchromaFrame.timestamp = beatTimestamp;
max@1 1061 bwQchromaFrame.values = tempChroma;
Chris@24 1062 bwQchromaFrame.duration = newBeatTimestamp - beatTimestamp;
max@1 1063 bwQchromagram.push_back(bwQchromaFrame);
max@1 1064
max@1 1065 for (int iFrame = -framesInBeat; iFrame < 0; ++iFrame)
max@1 1066 {
max@1 1067 Feature fwQchromaFrame;
max@1 1068 fwQchromaFrame.hasTimestamp = true;
max@1 1069 fwQchromaFrame.timestamp = chromagram[iChroma+iFrame].timestamp;
max@1 1070 fwQchromaFrame.values = tempChroma; // all between two beats get the same
max@1 1071 fwQchromagram.push_back(fwQchromaFrame);
max@1 1072 }
max@1 1073
max@1 1074 // 2. increments / resets for current (new) beat
max@1 1075 currBeatCount++;
Chris@24 1076 beatTimestamp = newBeatTimestamp;
Chris@37 1077 for (int i = 0; i < nBin; ++i) tempChroma[i] = 0; // average
max@1 1078 framesInBeat = 0;
max@1 1079 }
max@1 1080 framesInBeat++;
Chris@37 1081 for (int i = 0; i < nBin; ++i) tempChroma[i] += chromagram[iChroma].values[i];
max@1 1082 }
max@1 1083 returnVector.push_back(fwQchromagram);
max@1 1084 returnVector.push_back(bwQchromagram);
Chris@30 1085 return returnVector;
max@1 1086 }
max@1 1087
matthiasm@43 1088
matthiasm@43 1089
max@1 1090 /* -------------------------------- */
max@1 1091 /* ------ Support Functions ------ */
max@1 1092 /* -------------------------------- */
max@1 1093
max@1 1094 // one-dimesion median filter
Chris@56 1095 vec medfilt1(vec v, int medfilt_length)
max@1 1096 {
matthiasm@46 1097 // TODO: check if this works with odd and even medfilt_length !!!
max@1 1098 int halfWin = medfilt_length/2;
max@1 1099
max@1 1100 // result vector
Chris@56 1101 vec res = zeros<vec>(v.size());
max@1 1102
max@1 1103 // padding
Chris@56 1104 vec padV = zeros<vec>(v.size()+medfilt_length-1);
max@1 1105
Chris@37 1106 for (int i=medfilt_length/2; i < medfilt_length/2+(int)v.size(); ++ i)
max@1 1107 {
max@1 1108 padV(i) = v(i-medfilt_length/2);
matthiasm@46 1109 }
matthiasm@46 1110
matthiasm@46 1111 // the above loop leaves the boundaries at 0,
matthiasm@46 1112 // the two loops below fill them with the start or end values of v at start and end
matthiasm@46 1113 for (int i = 0; i < halfWin; ++i) padV(i) = v(0);
matthiasm@46 1114 for (int i = halfWin+(int)v.size(); i < (int)v.size()+2*halfWin; ++i) padV(i) = v(v.size()-1);
matthiasm@46 1115
matthiasm@46 1116
max@1 1117
max@1 1118 // Median filter
Chris@56 1119 vec win = zeros<vec>(medfilt_length);
max@1 1120
Chris@37 1121 for (int i=0; i < (int)v.size(); ++i)
max@1 1122 {
max@1 1123 win = padV.subvec(i,i+halfWin*2);
max@1 1124 win = sort(win);
max@1 1125 res(i) = win(halfWin);
max@1 1126 }
max@1 1127
max@1 1128 return res;
max@1 1129 }
max@1 1130
max@1 1131
max@1 1132 // Quantile
Chris@56 1133 double quantile(vec v, double p)
max@1 1134 {
Chris@56 1135 vec sortV = sort(v);
max@1 1136 int n = sortV.size();
Chris@56 1137 vec x = zeros<vec>(n+2);
Chris@56 1138 vec y = zeros<vec>(n+2);
max@1 1139
max@1 1140 x(0) = 0;
max@1 1141 x(n+1) = 100;
max@1 1142
Chris@21 1143 for (int i=1; i<n+1; ++i)
max@1 1144 x(i) = 100*(0.5+(i-1))/n;
max@1 1145
max@1 1146 y(0) = sortV(0);
max@1 1147 y.subvec(1,n) = sortV;
max@1 1148 y(n+1) = sortV(n-1);
max@1 1149
Chris@56 1150 uvec x2index = find(x>=p*100);
max@1 1151
max@1 1152 // Interpolation
max@1 1153 double x1 = x(x2index(0)-1);
max@1 1154 double x2 = x(x2index(0));
max@1 1155 double y1 = y(x2index(0)-1);
max@1 1156 double y2 = y(x2index(0));
max@1 1157
max@1 1158 double res = (y2-y1)/(x2-x1)*(p*100-x1)+y1;
max@1 1159
max@1 1160 return res;
max@1 1161 }
max@1 1162
max@1 1163 // Max Filtering
Chris@56 1164 mat maxfilt1(mat inmat, int len)
max@1 1165 {
Chris@56 1166 mat outmat = inmat;
max@1 1167
Chris@37 1168 for (int i=0; i < (int)inmat.n_rows; ++i)
max@1 1169 {
Chris@56 1170 if (sum(inmat.row(i)) > 0)
max@1 1171 {
max@1 1172 // Take a window of rows
max@1 1173 int startWin;
max@1 1174 int endWin;
max@1 1175
max@1 1176 if (0 > i-len)
max@1 1177 startWin = 0;
max@1 1178 else
max@1 1179 startWin = i-len;
max@1 1180
Chris@37 1181 if ((int)inmat.n_rows-1 < i+len-1)
max@1 1182 endWin = inmat.n_rows-1;
max@1 1183 else
max@1 1184 endWin = i+len-1;
max@1 1185
Chris@56 1186 outmat(i,span::all) =
Chris@56 1187 max(inmat(span(startWin,endWin),span::all));
max@1 1188 }
max@1 1189 }
max@1 1190
max@1 1191 return outmat;
Chris@56 1192
max@1 1193 }
max@1 1194
max@1 1195 // Null Parts
Chris@56 1196 Part nullpart(vector<Part> parts, vec barline)
max@1 1197 {
Chris@56 1198 uvec nullindices = ones<uvec>(barline.size());
Chris@37 1199 for (int iPart=0; iPart<(int)parts.size(); ++iPart)
max@1 1200 {
Chris@21 1201 //for (int iIndex=0; iIndex < parts[0].indices.size(); ++iIndex)
Chris@37 1202 for (int iIndex=0; iIndex < (int)parts[iPart].indices.size(); ++iIndex)
Chris@21 1203 for (int i=0; i<parts[iPart].n; ++i)
max@1 1204 {
Chris@21 1205 int ind = parts[iPart].indices[iIndex]+i;
max@1 1206 nullindices(ind) = 0;
max@1 1207 }
max@1 1208 }
max@7 1209
max@1 1210 Part newPart;
max@1 1211 newPart.n = 1;
Chris@56 1212 uvec q = find(nullindices > 0);
max@1 1213
Chris@37 1214 for (int i=0; i<(int)q.size();++i)
max@1 1215 newPart.indices.push_back(q(i));
max@7 1216
max@1 1217 newPart.letter = '-';
max@1 1218 newPart.value = 0;
max@1 1219 newPart.level = 0;
max@1 1220
max@1 1221 return newPart;
max@1 1222 }
max@1 1223
max@1 1224
max@1 1225 // Merge Nulls
max@1 1226 void mergenulls(vector<Part> &parts)
max@1 1227 {
Chris@37 1228 for (int iPart=0; iPart<(int)parts.size(); ++iPart)
max@1 1229 {
max@1 1230
max@1 1231 vector<Part> newVectorPart;
max@1 1232
max@1 1233 if (parts[iPart].letter.compare("-")==0)
max@1 1234 {
max@1 1235 sort (parts[iPart].indices.begin(), parts[iPart].indices.end());
Chris@21 1236 int newpartind = -1;
max@1 1237
max@1 1238 vector<int> indices;
max@1 1239 indices.push_back(-2);
max@1 1240
Chris@37 1241 for (int iIndex=0; iIndex<(int)parts[iPart].indices.size(); ++iIndex)
max@1 1242 indices.push_back(parts[iPart].indices[iIndex]);
max@1 1243
Chris@37 1244 for (int iInd=1; iInd < (int)indices.size(); ++iInd)
max@1 1245 {
max@1 1246 if (indices[iInd] - indices[iInd-1] > 1)
max@1 1247 {
max@1 1248 newpartind++;
max@1 1249
max@1 1250 Part newPart;
matthiasm@46 1251 newPart.letter = 'N';
max@1 1252 std::stringstream out;
max@1 1253 out << newpartind+1;
max@1 1254 newPart.letter.append(out.str());
matthiasm@44 1255 // newPart.value = 20+newpartind+1;
matthiasm@44 1256 newPart.value = 0;
max@1 1257 newPart.n = 1;
max@1 1258 newPart.indices.push_back(indices[iInd]);
max@1 1259 newPart.level = 0;
max@1 1260
max@1 1261 newVectorPart.push_back(newPart);
max@1 1262 }
max@1 1263 else
max@1 1264 {
max@1 1265 newVectorPart[newpartind].n = newVectorPart[newpartind].n+1;
max@1 1266 }
max@1 1267 }
max@1 1268 parts.erase (parts.end());
max@1 1269
Chris@37 1270 for (int i=0; i<(int)newVectorPart.size(); ++i)
max@1 1271 parts.push_back(newVectorPart[i]);
max@1 1272 }
max@1 1273 }
max@1 1274 }
max@1 1275
max@1 1276 /* ------ Segmentation ------ */
max@1 1277
Chris@19 1278 vector<Part> songSegment(Vamp::Plugin::FeatureList quantisedChromagram)
max@1 1279 {
max@1 1280
max@1 1281
max@1 1282 /* ------ Parameters ------ */
max@1 1283 double thresh_beat = 0.85;
max@1 1284 double thresh_seg = 0.80;
matthiasm@46 1285 int medfilt_length = 5;
max@1 1286 int minlength = 28;
matthiasm@46 1287 int maxlength = 2*128;
max@1 1288 double quantilePerc = 0.1;
max@1 1289 /* ------------------------ */
max@1 1290
max@1 1291
max@1 1292 // Collect Info
Chris@19 1293 int nBeat = quantisedChromagram.size(); // Number of feature vector
Chris@19 1294 int nFeatValues = quantisedChromagram[0].values.size(); // Number of values for each feature vector
max@1 1295
Chris@27 1296 if (nBeat < minlength) {
Chris@27 1297 // return a single part
Chris@27 1298 vector<Part> parts;
Chris@27 1299 Part newPart;
Chris@27 1300 newPart.n = 1;
Chris@27 1301 newPart.indices.push_back(0);
Chris@27 1302 newPart.letter = "n1";
Chris@27 1303 newPart.value = 20;
Chris@27 1304 newPart.level = 0;
Chris@27 1305 parts.push_back(newPart);
Chris@27 1306 return parts;
Chris@27 1307 }
Chris@27 1308
Chris@56 1309 irowvec timeStamp = zeros<imat>(1,nBeat); // Vector of Time Stamps
max@1 1310
Chris@22 1311 // Save time stamp as a Vector
Chris@19 1312 if (quantisedChromagram[0].hasTimestamp)
max@1 1313 {
Chris@21 1314 for (int i = 0; i < nBeat; ++ i)
Chris@19 1315 timeStamp[i] = quantisedChromagram[i].timestamp.nsec;
max@1 1316 }
max@1 1317
max@1 1318
max@1 1319 // Build a ObservationTOFeatures Matrix
Chris@56 1320 mat featVal = zeros<mat>(nBeat,nFeatValues/2);
max@1 1321
Chris@21 1322 for (int i = 0; i < nBeat; ++ i)
Chris@21 1323 for (int j = 0; j < nFeatValues/2; ++ j)
max@1 1324 {
matthiasm@44 1325 featVal(i,j) = 0.8 * quantisedChromagram[i].values[j] + quantisedChromagram[i].values[j+12]; // bass attenuated
max@1 1326 }
max@1 1327
max@1 1328 // Set to arbitrary value to feature vectors with low std
Chris@56 1329 mat a = stddev(featVal,1,1);
max@1 1330
matthiasm@44 1331 // Feature Correlation Matrix
Chris@56 1332 mat simmat0 = 1-cor(trans(featVal));
max@1 1333
max@1 1334
Chris@21 1335 for (int i = 0; i < nBeat; ++ i)
max@1 1336 {
max@1 1337 if (a(i)<0.000001)
max@1 1338 {
max@1 1339 featVal(i,1) = 1000; // arbitrary
max@1 1340
Chris@21 1341 for (int j = 0; j < nFeatValues/2; ++j)
max@1 1342 {
max@1 1343 simmat0(i,j) = 1;
max@1 1344 simmat0(j,i) = 1;
max@1 1345 }
max@1 1346 }
max@1 1347 }
max@1 1348
Chris@56 1349 mat simmat = 1-simmat0/2;
max@1 1350
max@1 1351 // -------- To delate when the proble with the add of beat will be solved -------
matthiasm@45 1352 for (int i = 0; i < nBeat; ++ i)
matthiasm@45 1353 for (int j = 0; j < nBeat; ++ j)
matthiasm@45 1354 if (!std::isfinite(simmat(i,j)))
matthiasm@45 1355 simmat(i,j)=0;
max@1 1356 // ------------------------------------------------------------------------------
max@1 1357
max@1 1358 // Median Filtering applied to the Correlation Matrix
max@1 1359 // The median filter is for each diagonal of the Matrix
Chris@56 1360 mat median_simmat = zeros<mat>(nBeat,nBeat);
max@1 1361
Chris@21 1362 for (int i = 0; i < nBeat; ++ i)
max@1 1363 {
Chris@56 1364 vec temp = medfilt1(simmat.diag(i),medfilt_length);
max@1 1365 median_simmat.diag(i) = temp;
max@1 1366 median_simmat.diag(-i) = temp;
max@1 1367 }
max@1 1368
Chris@21 1369 for (int i = 0; i < nBeat; ++ i)
Chris@21 1370 for (int j = 0; j < nBeat; ++ j)
max@1 1371 if (!std::isfinite(median_simmat(i,j)))
max@1 1372 median_simmat(i,j) = 0;
max@1 1373
max@1 1374 // -------------- NOT CONVERTED -------------------------------------
max@1 1375 // if param.seg.standardise
max@1 1376 // med_median_simmat = repmat(median(median_simmat),nBeat,1);
max@1 1377 // std_median_simmat = repmat(std(median_simmat),nBeat,1);
max@1 1378 // median_simmat = (median_simmat - med_median_simmat) ./ std_median_simmat;
max@1 1379 // end
max@1 1380 // --------------------------------------------------------
max@1 1381
max@1 1382 // Retrieve Bar Bounderies
Chris@56 1383 uvec dup = find(median_simmat > thresh_beat);
Chris@56 1384 mat potential_duplicates = zeros<mat>(nBeat,nBeat);
Chris@56 1385 potential_duplicates.elem(dup) = ones<vec>(dup.size());
max@1 1386 potential_duplicates = trimatu(potential_duplicates);
max@1 1387
Chris@21 1388 int nPartlengths = round((maxlength-minlength)/4)+1;
Chris@56 1389 vec partlengths = zeros<vec>(nPartlengths);
max@1 1390
Chris@21 1391 for (int i = 0; i < nPartlengths; ++ i)
matthiasm@46 1392 partlengths(i) = (i*4) + minlength;
max@1 1393
max@1 1394 // initialise arrays
Chris@56 1395 cube simArray = zeros<cube>(nBeat,nBeat,nPartlengths);
Chris@56 1396 cube decisionArray2 = zeros<cube>(nBeat,nBeat,nPartlengths);
max@1 1397
matthiasm@46 1398 for (int iLength = 0; iLength < nPartlengths; ++ iLength)
matthiasm@46 1399 // for (int iLength = 0; iLength < 20; ++ iLength)
max@1 1400 {
Chris@21 1401 int len = partlengths(iLength);
Chris@21 1402 int nUsedBeat = nBeat - len + 1; // number of potential rep beginnings: they can't overlap at the end of the song
Chris@33 1403
Chris@33 1404 if (nUsedBeat < 1) continue;
max@1 1405
Chris@21 1406 for (int iBeat = 0; iBeat < nUsedBeat; ++ iBeat) // looping over all columns (arbitrarily chosen columns)
max@1 1407 {
Chris@56 1408 uvec help2 = find(potential_duplicates(span(0,nUsedBeat-1),iBeat)==1);
max@1 1409
Chris@37 1410 for (int i=0; i < (int)help2.size(); ++i)
max@1 1411 {
max@1 1412
max@1 1413 // measure how well two length len segments go together
max@1 1414 int kBeat = help2(i);
Chris@56 1415 vec distrib = median_simmat(span(iBeat,iBeat+len-1), span(kBeat,kBeat+len-1)).diag(0);
max@1 1416 simArray(iBeat,kBeat,iLength) = quantile(distrib,quantilePerc);
max@1 1417 }
max@1 1418 }
max@1 1419
Chris@56 1420 mat tempM = simArray(span(0,nUsedBeat-1), span(0,nUsedBeat-1), span(iLength,iLength));
Chris@56 1421 simArray.slice(iLength)(span(0,nUsedBeat-1), span(0,nUsedBeat-1)) = tempM + trans(tempM) - (eye<mat>(nUsedBeat,nUsedBeat)%tempM);
max@1 1422
max@1 1423 // convolution
Chris@56 1424 vec K = zeros<vec>(3);
max@1 1425 K << 0.01 << 0.98 << 0.01;
max@1 1426
max@1 1427
Chris@37 1428 for (int i=0; i < (int)simArray.n_rows; ++i)
max@1 1429 {
Chris@56 1430 rowvec t = conv((rowvec)simArray.slice(iLength).row(i),K);
Chris@56 1431 simArray.slice(iLength)(i, span::all) = t.subvec(1,t.size()-2);
max@1 1432 }
max@1 1433
max@1 1434 // take only over-average bars that do not overlap
max@1 1435
Chris@56 1436 mat temp = zeros<mat>(simArray.n_rows, simArray.n_cols);
Chris@56 1437 temp(span::all, span(0,nUsedBeat-1)) = simArray.slice(iLength)(span::all, span(0,nUsedBeat-1));
max@1 1438
Chris@37 1439 for (int i=0; i < (int)temp.n_rows; ++i)
Chris@37 1440 for (int j=0; j < nUsedBeat; ++j)
max@1 1441 if (temp(i,j) < thresh_seg)
max@1 1442 temp(i,j) = 0;
max@1 1443
max@1 1444 decisionArray2.slice(iLength) = temp;
max@1 1445
Chris@56 1446 mat maxMat = maxfilt1(decisionArray2.slice(iLength),len-1);
max@1 1447
Chris@37 1448 for (int i=0; i < (int)decisionArray2.n_rows; ++i)
Chris@37 1449 for (int j=0; j < (int)decisionArray2.n_cols; ++j)
max@1 1450 if (decisionArray2.slice(iLength)(i,j) < maxMat(i,j))
max@1 1451 decisionArray2.slice(iLength)(i,j) = 0;
max@1 1452
Chris@56 1453 decisionArray2.slice(iLength) = decisionArray2.slice(iLength) % trans(decisionArray2.slice(iLength));
max@1 1454
Chris@37 1455 for (int i=0; i < (int)simArray.n_rows; ++i)
Chris@37 1456 for (int j=0; j < (int)simArray.n_cols; ++j)
max@1 1457 if (simArray.slice(iLength)(i,j) < thresh_seg)
max@1 1458 potential_duplicates(i,j) = 0;
max@1 1459 }
max@1 1460
max@1 1461 // Milk the data
max@1 1462
Chris@56 1463 mat bestval;
max@1 1464
Chris@21 1465 for (int iLength=0; iLength<nPartlengths; ++iLength)
max@1 1466 {
Chris@56 1467 mat temp = zeros<mat>(decisionArray2.n_rows,decisionArray2.n_cols);
max@1 1468
Chris@37 1469 for (int rows=0; rows < (int)decisionArray2.n_rows; ++rows)
Chris@37 1470 for (int cols=0; cols < (int)decisionArray2.n_cols; ++cols)
max@1 1471 if (decisionArray2.slice(iLength)(rows,cols) > 0)
max@1 1472 temp(rows,cols) = 1;
max@1 1473
Chris@56 1474 vec currLogicSum = sum(temp,1);
max@1 1475
Chris@37 1476 for (int iBeat=0; iBeat < nBeat; ++iBeat)
max@1 1477 if (currLogicSum(iBeat) > 1)
max@1 1478 {
Chris@56 1479 vec t = decisionArray2.slice(iLength)(span::all,iBeat);
max@1 1480 double currSum = sum(t);
max@1 1481
Chris@21 1482 int count = 0;
Chris@37 1483 for (int i=0; i < (int)t.size(); ++i)
max@1 1484 if (t(i)>0)
max@1 1485 count++;
max@1 1486
max@1 1487 currSum = (currSum/count)/2;
max@1 1488
Chris@56 1489 rowvec t1;
max@1 1490 t1 << (currLogicSum(iBeat)-1) * partlengths(iLength) << currSum << iLength << iBeat << currLogicSum(iBeat);
max@1 1491
max@1 1492 bestval = join_cols(bestval,t1);
max@1 1493 }
max@1 1494 }
max@1 1495
max@1 1496 // Definition of the resulting vector
max@1 1497 vector<Part> parts;
max@1 1498
max@1 1499 // make a table of all valid sets of parts
max@1 1500
max@1 1501 char partletters[] = {'A','B','C','D','E','F','G', 'H','I','J','K','L','M','N','O','P','Q','R','S'};
Chris@21 1502 int partvalues[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
Chris@56 1503 vec valid_sets = ones<vec>(bestval.n_rows);
max@1 1504
max@1 1505 if (!bestval.is_empty())
max@1 1506 {
max@1 1507
max@1 1508 // In questo punto viene introdotto un errore alla 3 cifra decimale
max@1 1509
Chris@56 1510 colvec t = zeros<colvec>(bestval.n_rows);
Chris@37 1511 for (int i=0; i < (int)bestval.n_rows; ++i)
max@1 1512 {
max@1 1513 t(i) = bestval(i,1)*2;
max@1 1514 }
max@1 1515
max@1 1516 double m = t.max();
max@1 1517
Chris@56 1518 bestval(span::all,1) = bestval(span::all,1) / m;
Chris@56 1519 bestval(span::all,0) = bestval(span::all,0) + bestval(span::all,1);
max@1 1520
Chris@56 1521 mat bestval2;
Chris@37 1522 for (int i=0; i < (int)bestval.n_cols; ++i)
max@1 1523 if (i!=1)
max@1 1524 bestval2 = join_rows(bestval2,bestval.col(i));
max@1 1525
Chris@21 1526 for (int kSeg=0; kSeg<6; ++kSeg)
max@1 1527 {
Chris@56 1528 mat currbestvals = zeros<mat>(bestval2.n_rows, bestval2.n_cols);
Chris@37 1529 for (int i=0; i < (int)bestval2.n_rows; ++i)
Chris@37 1530 for (int j=0; j < (int)bestval2.n_cols; ++j)
max@1 1531 if (valid_sets(i))
max@1 1532 currbestvals(i,j) = bestval2(i,j);
max@1 1533
Chris@56 1534 vec t1 = currbestvals.col(0);
max@1 1535 double ma;
Chris@56 1536 uword maIdx;
max@1 1537 ma = t1.max(maIdx);
max@6 1538
max@6 1539 if ((maIdx == 0)&&(ma == 0))
max@6 1540 break;
max@1 1541
Chris@28 1542 int bestLength = lrint(partlengths(currbestvals(maIdx,1)));
Chris@56 1543 rowvec bestIndices = decisionArray2.slice(currbestvals(maIdx,1))(currbestvals(maIdx,2), span::all);
max@1 1544
Chris@56 1545 rowvec bestIndicesMap = zeros<rowvec>(bestIndices.size());
Chris@37 1546 for (int i=0; i < (int)bestIndices.size(); ++i)
max@1 1547 if (bestIndices(i)>0)
max@1 1548 bestIndicesMap(i) = 1;
max@1 1549
Chris@56 1550 rowvec mask = zeros<rowvec>(bestLength*2-1);
Chris@21 1551 for (int i=0; i<bestLength; ++i)
max@1 1552 mask(i+bestLength-1) = 1;
max@1 1553
Chris@56 1554 rowvec t2 = conv(bestIndicesMap,mask);
Chris@56 1555 rowvec island = t2.subvec(mask.size()/2,t2.size()-1-mask.size()/2);
max@1 1556
max@1 1557 // Save results in the structure
max@1 1558 Part newPart;
max@1 1559 newPart.n = bestLength;
Chris@56 1560 uvec q1 = find(bestIndices > 0);
max@1 1561
Chris@37 1562 for (int i=0; i < (int)q1.size();++i)
max@1 1563 newPart.indices.push_back(q1(i));
max@1 1564
max@1 1565 newPart.letter = partletters[kSeg];
max@1 1566 newPart.value = partvalues[kSeg];
max@1 1567 newPart.level = kSeg+1;
max@1 1568 parts.push_back(newPart);
max@1 1569
Chris@56 1570 uvec q2 = find(valid_sets==1);
max@1 1571
Chris@37 1572 for (int i=0; i < (int)q2.size(); ++i)
max@1 1573 {
Chris@21 1574 int iSet = q2(i);
Chris@21 1575 int s = partlengths(bestval2(iSet,1));
max@1 1576
Chris@56 1577 rowvec mask1 = zeros<rowvec>(s*2-1);
Chris@21 1578 for (int i=0; i<s; ++i)
max@1 1579 mask1(i+s-1) = 1;
max@1 1580
Chris@56 1581 rowvec Ind = decisionArray2.slice(bestval2(iSet,1))(bestval2(iSet,2), span::all);
Chris@56 1582 rowvec IndMap = zeros<rowvec>(Ind.size());
Chris@37 1583 for (int i=0; i < (int)Ind.size(); ++i)
max@1 1584 if (Ind(i)>0)
max@1 1585 IndMap(i) = 2;
max@1 1586
Chris@56 1587 rowvec t3 = conv(IndMap,mask1);
Chris@56 1588 rowvec currislands = t3.subvec(mask1.size()/2,t3.size()-1-mask1.size()/2);
Chris@56 1589 rowvec islandsdMult = currislands%island;
max@6 1590
Chris@56 1591 uvec islandsIndex = find(islandsdMult > 0);
max@1 1592
max@6 1593 if (islandsIndex.size() > 0)
max@1 1594 valid_sets(iSet) = 0;
max@1 1595 }
max@1 1596 }
max@1 1597 }
max@1 1598 else
max@1 1599 {
max@1 1600 Part newPart;
max@1 1601 newPart.n = nBeat;
Chris@33 1602 newPart.indices.push_back(0);
max@1 1603 newPart.letter = 'A';
max@1 1604 newPart.value = 1;
max@1 1605 newPart.level = 1;
max@1 1606 parts.push_back(newPart);
max@1 1607 }
max@6 1608
Chris@56 1609 vec bar = linspace(1,nBeat,nBeat);
max@1 1610 Part np = nullpart(parts,bar);
max@7 1611
max@1 1612 parts.push_back(np);
max@1 1613
max@1 1614 // -------------- NOT CONVERTED -------------------------------------
max@1 1615 // if param.seg.editor
max@1 1616 // [pa, ta] = partarray(parts);
max@1 1617 // parts = editorssearch(pa, ta, parts);
max@1 1618 // parts = [parts, nullpart(parts,1:nBeat)];
max@1 1619 // end
max@1 1620 // ------------------------------------------------------------------
max@1 1621
max@1 1622
max@1 1623 mergenulls(parts);
max@1 1624
max@1 1625
max@1 1626 // -------------- NOT CONVERTED -------------------------------------
max@1 1627 // if param.seg.editor
max@1 1628 // [pa, ta] = partarray(parts);
max@1 1629 // parts = editorssearch(pa, ta, parts);
max@1 1630 // parts = [parts, nullpart(parts,1:nBeat)];
max@1 1631 // end
max@1 1632 // ------------------------------------------------------------------
max@1 1633
max@1 1634 return parts;
max@1 1635 }
max@1 1636
max@1 1637
max@1 1638
Chris@19 1639 void songSegmentChroma(Vamp::Plugin::FeatureList quantisedChromagram, vector<Part> &parts)
max@1 1640 {
max@1 1641 // Collect Info
Chris@19 1642 int nBeat = quantisedChromagram.size(); // Number of feature vector
Chris@19 1643 int nFeatValues = quantisedChromagram[0].values.size(); // Number of values for each feature vector
max@1 1644
Chris@56 1645 mat synchTreble = zeros<mat>(nBeat,nFeatValues/2);
max@1 1646
Chris@21 1647 for (int i = 0; i < nBeat; ++ i)
Chris@21 1648 for (int j = 0; j < nFeatValues/2; ++ j)
max@1 1649 {
Chris@19 1650 synchTreble(i,j) = quantisedChromagram[i].values[j];
max@1 1651 }
max@1 1652
Chris@56 1653 mat synchBass = zeros<mat>(nBeat,nFeatValues/2);
max@1 1654
Chris@21 1655 for (int i = 0; i < nBeat; ++ i)
Chris@21 1656 for (int j = 0; j < nFeatValues/2; ++ j)
max@1 1657 {
Chris@19 1658 synchBass(i,j) = quantisedChromagram[i].values[j+12];
max@1 1659 }
max@1 1660
max@1 1661 // Process
max@1 1662
Chris@56 1663 mat segTreble = zeros<mat>(quantisedChromagram.size(),quantisedChromagram[0].values.size()/2);
Chris@56 1664 mat segBass = zeros<mat>(quantisedChromagram.size(),quantisedChromagram[0].values.size()/2);
max@1 1665
Chris@37 1666 for (int iPart=0; iPart < (int)parts.size(); ++iPart)
max@1 1667 {
max@1 1668 parts[iPart].nInd = parts[iPart].indices.size();
max@1 1669
Chris@21 1670 for (int kOccur=0; kOccur<parts[iPart].nInd; ++kOccur)
max@1 1671 {
max@1 1672 int kStartIndex = parts[iPart].indices[kOccur];
max@1 1673 int kEndIndex = kStartIndex + parts[iPart].n-1;
max@1 1674
max@1 1675 segTreble.rows(kStartIndex,kEndIndex) = segTreble.rows(kStartIndex,kEndIndex) + synchTreble.rows(kStartIndex,kEndIndex);
max@1 1676 segBass.rows(kStartIndex,kEndIndex) = segBass.rows(kStartIndex,kEndIndex) + synchBass.rows(kStartIndex,kEndIndex);
max@1 1677 }
max@1 1678 }
max@1 1679 }
max@1 1680
max@1 1681
max@1 1682 // Segment Integration
max@1 1683 vector<Part> songSegmentIntegration(vector<Part> &parts)
max@1 1684 {
max@1 1685 // Break up parts (every part will have one instance)
max@1 1686 vector<Part> newPartVector;
max@1 1687 vector<int> partindices;
max@1 1688
Chris@37 1689 for (int iPart=0; iPart < (int)parts.size(); ++iPart)
max@1 1690 {
max@1 1691 parts[iPart].nInd = parts[iPart].indices.size();
Chris@21 1692 for (int iInstance=0; iInstance<parts[iPart].nInd; ++iInstance)
max@1 1693 {
max@1 1694 Part newPart;
max@1 1695 newPart.n = parts[iPart].n;
max@1 1696 newPart.letter = parts[iPart].letter;
max@1 1697 newPart.value = parts[iPart].value;
max@1 1698 newPart.level = parts[iPart].level;
max@1 1699 newPart.indices.push_back(parts[iPart].indices[iInstance]);
max@1 1700 newPart.nInd = 1;
max@1 1701 partindices.push_back(parts[iPart].indices[iInstance]);
max@1 1702
max@1 1703 newPartVector.push_back(newPart);
max@1 1704 }
max@1 1705 }
max@1 1706
max@1 1707
max@1 1708 // Sort the parts in order of occurrence
max@1 1709 sort (partindices.begin(), partindices.end());
max@1 1710
Chris@37 1711 for (int i=0; i < (int)partindices.size(); ++i)
max@1 1712 {
max@1 1713 bool found = false;
max@1 1714 int in=0;
max@1 1715 while (!found)
max@1 1716 {
max@1 1717 if (newPartVector[in].indices[0] == partindices[i])
max@1 1718 {
max@1 1719 newPartVector.push_back(newPartVector[in]);
max@1 1720 newPartVector.erase(newPartVector.begin()+in);
max@1 1721 found = true;
max@1 1722 }
max@1 1723 else
max@1 1724 in++;
max@1 1725 }
max@1 1726 }
max@1 1727
max@1 1728 // Clear the vector
Chris@37 1729 for (int iNewpart=1; iNewpart < (int)newPartVector.size(); ++iNewpart)
max@1 1730 {
max@1 1731 if (newPartVector[iNewpart].n < 12)
max@1 1732 {
max@1 1733 newPartVector[iNewpart-1].n = newPartVector[iNewpart-1].n + newPartVector[iNewpart].n;
max@1 1734 newPartVector.erase(newPartVector.begin()+iNewpart);
max@1 1735 }
max@1 1736 }
max@1 1737
max@1 1738 return newPartVector;
max@1 1739 }
max@1 1740
max@1 1741 // Segmenter
Chris@48 1742 Vamp::Plugin::FeatureList Segmentino::runSegmenter(Vamp::Plugin::FeatureList quantisedChromagram)
max@1 1743 {
max@1 1744 /* --- Display Information --- */
Chris@37 1745 // int numBeat = quantisedChromagram.size();
Chris@37 1746 // int numFeats = quantisedChromagram[0].values.size();
max@1 1747
max@1 1748 vector<Part> parts;
max@1 1749 vector<Part> finalParts;
max@1 1750
Chris@19 1751 parts = songSegment(quantisedChromagram);
Chris@19 1752 songSegmentChroma(quantisedChromagram,parts);
max@7 1753
max@1 1754 finalParts = songSegmentIntegration(parts);
max@1 1755
max@1 1756
max@1 1757 // TEMP ----
Chris@21 1758 /*for (int i=0;i<finalParts.size(); ++i)
max@1 1759 {
max@6 1760 std::cout << "Parts n° " << i << std::endl;
max@6 1761 std::cout << "n°: " << finalParts[i].n << std::endl;
max@6 1762 std::cout << "letter: " << finalParts[i].letter << std::endl;
max@1 1763
max@6 1764 std::cout << "indices: ";
Chris@21 1765 for (int j=0;j<finalParts[i].indices.size(); ++j)
max@6 1766 std::cout << finalParts[i].indices[j] << " ";
max@6 1767
max@6 1768 std::cout << std::endl;
max@6 1769 std::cout << "level: " << finalParts[i].level << std::endl;
max@1 1770 }*/
max@1 1771
max@1 1772 // ---------
max@1 1773
max@1 1774
max@1 1775 // Output
max@1 1776
max@1 1777 Vamp::Plugin::FeatureList results;
max@1 1778
max@1 1779
max@1 1780 Feature seg;
max@1 1781
Chris@56 1782 vec indices;
Chris@37 1783 // int idx=0;
max@1 1784 vector<int> values;
max@1 1785 vector<string> letters;
max@1 1786
Chris@37 1787 for (int iPart=0; iPart < (int)finalParts.size()-1; ++iPart)
max@1 1788 {
Chris@21 1789 int iInstance=0;
max@1 1790 seg.hasTimestamp = true;
max@1 1791
max@1 1792 int ind = finalParts[iPart].indices[iInstance];
max@1 1793 int ind1 = finalParts[iPart+1].indices[iInstance];
max@1 1794
Chris@19 1795 seg.timestamp = quantisedChromagram[ind].timestamp;
max@1 1796 seg.hasDuration = true;
Chris@19 1797 seg.duration = quantisedChromagram[ind1].timestamp-quantisedChromagram[ind].timestamp;
max@1 1798 seg.values.clear();
max@1 1799 seg.values.push_back(finalParts[iPart].value);
max@1 1800 seg.label = finalParts[iPart].letter;
max@1 1801
max@1 1802 results.push_back(seg);
max@1 1803 }
max@1 1804
Chris@37 1805 if (finalParts.size() > 0) {
Chris@37 1806 int ind = finalParts[finalParts.size()-1].indices[0];
Chris@37 1807 seg.hasTimestamp = true;
Chris@37 1808 seg.timestamp = quantisedChromagram[ind].timestamp;
Chris@37 1809 seg.hasDuration = true;
Chris@37 1810 seg.duration = quantisedChromagram[quantisedChromagram.size()-1].timestamp-quantisedChromagram[ind].timestamp;
Chris@37 1811 seg.values.clear();
Chris@37 1812 seg.values.push_back(finalParts[finalParts.size()-1].value);
Chris@37 1813 seg.label = finalParts[finalParts.size()-1].letter;
max@1 1814
Chris@37 1815 results.push_back(seg);
Chris@37 1816 }
max@1 1817
max@1 1818 return results;
max@1 1819 }
max@1 1820
max@1 1821
max@1 1822
max@1 1823
max@1 1824
max@1 1825
max@1 1826
max@1 1827
max@1 1828
max@1 1829
max@1 1830
max@1 1831
max@1 1832
max@1 1833
max@1 1834
max@1 1835
max@1 1836