annotate runner/FeatureExtractionManager.cpp @ 112:0c2d8c945bbf multiplex

Merge from default branch
author Chris Cannam
date Thu, 02 Oct 2014 15:23:25 +0100
parents ca565b18ba3e 74f7ad72fee6
children 297f9e415e39
rev   line source
Chris@0 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
Chris@0 2
Chris@0 3 /*
Chris@0 4 Sonic Annotator
Chris@0 5 A utility for batch feature extraction from audio files.
Chris@0 6 Mark Levy, Chris Sutton and Chris Cannam, Queen Mary, University of London.
Chris@0 7 Copyright 2007-2008 QMUL.
Chris@0 8
Chris@0 9 This program is free software; you can redistribute it and/or
Chris@0 10 modify it under the terms of the GNU General Public License as
Chris@0 11 published by the Free Software Foundation; either version 2 of the
Chris@0 12 License, or (at your option) any later version. See the file
Chris@0 13 COPYING included with this distribution for more information.
Chris@0 14 */
Chris@0 15
Chris@0 16 #include "FeatureExtractionManager.h"
Chris@106 17 #include "MultiplexedReader.h"
Chris@0 18
Chris@0 19 #include <vamp-hostsdk/PluginChannelAdapter.h>
Chris@0 20 #include <vamp-hostsdk/PluginBufferingAdapter.h>
Chris@0 21 #include <vamp-hostsdk/PluginInputDomainAdapter.h>
Chris@0 22 #include <vamp-hostsdk/PluginSummarisingAdapter.h>
Chris@8 23 #include <vamp-hostsdk/PluginWrapper.h>
Chris@0 24 #include <vamp-hostsdk/PluginLoader.h>
Chris@0 25
Chris@21 26 #include "base/Exceptions.h"
Chris@21 27
Chris@0 28 #include <iostream>
Chris@0 29
Chris@0 30 using namespace std;
Chris@0 31
Chris@0 32 using Vamp::Plugin;
Chris@0 33 using Vamp::PluginBase;
Chris@0 34 using Vamp::HostExt::PluginLoader;
Chris@0 35 using Vamp::HostExt::PluginChannelAdapter;
Chris@0 36 using Vamp::HostExt::PluginBufferingAdapter;
Chris@0 37 using Vamp::HostExt::PluginInputDomainAdapter;
Chris@0 38 using Vamp::HostExt::PluginSummarisingAdapter;
Chris@8 39 using Vamp::HostExt::PluginWrapper;
Chris@0 40
Chris@0 41 #include "data/fileio/FileSource.h"
Chris@0 42 #include "data/fileio/AudioFileReader.h"
Chris@0 43 #include "data/fileio/AudioFileReaderFactory.h"
Chris@0 44 #include "base/TempDirectory.h"
Chris@0 45 #include "base/ProgressPrinter.h"
Chris@0 46 #include "transform/TransformFactory.h"
Chris@0 47 #include "rdf/RDFTransformFactory.h"
Chris@0 48 #include "transform/FeatureWriter.h"
Chris@0 49
Chris@0 50 #include <QTextStream>
Chris@0 51 #include <QFile>
Chris@0 52 #include <QFileInfo>
Chris@0 53
Chris@0 54 FeatureExtractionManager::FeatureExtractionManager() :
Chris@0 55 m_summariesOnly(false),
Chris@0 56 // We can read using an arbitrary fixed block size --
Chris@0 57 // PluginBufferingAdapter handles this for us. It's likely to be
Chris@0 58 // quicker to use larger sizes than smallish ones like 1024
Chris@0 59 m_blockSize(16384),
Chris@0 60 m_defaultSampleRate(0),
Chris@0 61 m_sampleRate(0),
Chris@45 62 m_channels(0)
Chris@0 63 {
Chris@0 64 }
Chris@0 65
Chris@0 66 FeatureExtractionManager::~FeatureExtractionManager()
Chris@0 67 {
Chris@0 68 for (PluginMap::iterator pi = m_plugins.begin();
Chris@0 69 pi != m_plugins.end(); ++pi) {
Chris@0 70 delete pi->first;
Chris@0 71 }
Chris@45 72 foreach (AudioFileReader *r, m_readyReaders) {
Chris@45 73 delete r;
Chris@45 74 }
Chris@0 75 }
Chris@0 76
Chris@0 77 void FeatureExtractionManager::setChannels(int channels)
Chris@0 78 {
Chris@0 79 m_channels = channels;
Chris@0 80 }
Chris@0 81
Chris@0 82 void FeatureExtractionManager::setDefaultSampleRate(int sampleRate)
Chris@0 83 {
Chris@0 84 m_defaultSampleRate = sampleRate;
Chris@0 85 }
Chris@0 86
Chris@0 87 static PluginSummarisingAdapter::SummaryType
Chris@0 88 getSummaryType(string name)
Chris@0 89 {
Chris@0 90 if (name == "min") return PluginSummarisingAdapter::Minimum;
Chris@0 91 if (name == "max") return PluginSummarisingAdapter::Maximum;
Chris@0 92 if (name == "mean") return PluginSummarisingAdapter::Mean;
Chris@0 93 if (name == "median") return PluginSummarisingAdapter::Median;
Chris@0 94 if (name == "mode") return PluginSummarisingAdapter::Mode;
Chris@0 95 if (name == "sum") return PluginSummarisingAdapter::Sum;
Chris@0 96 if (name == "variance") return PluginSummarisingAdapter::Variance;
Chris@0 97 if (name == "sd") return PluginSummarisingAdapter::StandardDeviation;
Chris@0 98 if (name == "count") return PluginSummarisingAdapter::Count;
Chris@0 99 return PluginSummarisingAdapter::UnknownSummaryType;
Chris@0 100 }
Chris@0 101
Chris@102 102 bool
Chris@102 103 FeatureExtractionManager::setSummaryTypes(const set<string> &names,
Chris@102 104 const PluginSummarisingAdapter::SegmentBoundaries &boundaries)
Chris@0 105 {
Chris@0 106 for (SummaryNameSet::const_iterator i = names.begin();
Chris@0 107 i != names.end(); ++i) {
Chris@0 108 if (getSummaryType(*i) == PluginSummarisingAdapter::UnknownSummaryType) {
Chris@0 109 cerr << "ERROR: Unknown summary type \"" << *i << "\"" << endl;
Chris@0 110 return false;
Chris@0 111 }
Chris@0 112 }
Chris@0 113 m_summaries = names;
Chris@0 114 m_boundaries = boundaries;
Chris@0 115 return true;
Chris@0 116 }
Chris@0 117
Chris@102 118 void
Chris@102 119 FeatureExtractionManager::setSummariesOnly(bool summariesOnly)
Chris@102 120 {
Chris@102 121 m_summariesOnly = summariesOnly;
Chris@102 122 }
Chris@102 123
Chris@51 124 static PluginInputDomainAdapter::WindowType
Chris@51 125 convertWindowType(WindowType t)
Chris@51 126 {
Chris@51 127 switch (t) {
Chris@51 128 case RectangularWindow:
Chris@51 129 return PluginInputDomainAdapter::RectangularWindow;
Chris@51 130 case BartlettWindow:
Chris@51 131 return PluginInputDomainAdapter::BartlettWindow;
Chris@51 132 case HammingWindow:
Chris@51 133 return PluginInputDomainAdapter::HammingWindow;
Chris@51 134 case HanningWindow:
Chris@51 135 return PluginInputDomainAdapter::HanningWindow;
Chris@51 136 case BlackmanWindow:
Chris@51 137 return PluginInputDomainAdapter::BlackmanWindow;
Chris@51 138 case NuttallWindow:
Chris@51 139 return PluginInputDomainAdapter::NuttallWindow;
Chris@51 140 case BlackmanHarrisWindow:
Chris@51 141 return PluginInputDomainAdapter::BlackmanHarrisWindow;
Chris@51 142 default:
Chris@51 143 cerr << "ERROR: Unknown or unsupported window type \"" << t << "\", using Hann (\"" << HanningWindow << "\")" << endl;
Chris@51 144 return PluginInputDomainAdapter::HanningWindow;
Chris@51 145 }
Chris@51 146 }
Chris@51 147
Chris@0 148 bool FeatureExtractionManager::addFeatureExtractor
Chris@0 149 (Transform transform, const vector<FeatureWriter*> &writers)
Chris@0 150 {
Chris@0 151 //!!! exceptions rather than return values?
Chris@0 152
Chris@0 153 if (transform.getSampleRate() == 0) {
Chris@0 154 if (m_sampleRate == 0) {
Chris@0 155 cerr << "NOTE: Transform does not specify a sample rate, using default rate of " << m_defaultSampleRate << endl;
Chris@0 156 transform.setSampleRate(m_defaultSampleRate);
Chris@0 157 m_sampleRate = m_defaultSampleRate;
Chris@0 158 } else {
Chris@0 159 cerr << "NOTE: Transform does not specify a sample rate, using previous transform's rate of " << m_sampleRate << endl;
Chris@0 160 transform.setSampleRate(m_sampleRate);
Chris@0 161 }
Chris@0 162 }
Chris@0 163
Chris@0 164 if (m_sampleRate == 0) {
Chris@0 165 m_sampleRate = transform.getSampleRate();
Chris@0 166 }
Chris@0 167
Chris@0 168 if (transform.getSampleRate() != m_sampleRate) {
Chris@0 169 cerr << "WARNING: Transform sample rate " << transform.getSampleRate() << " does not match previously specified transform rate of " << m_sampleRate << " -- only a single rate is supported for each run" << endl;
Chris@0 170 cerr << "WARNING: Using previous rate of " << m_sampleRate << " for this transform as well" << endl;
Chris@0 171 transform.setSampleRate(m_sampleRate);
Chris@0 172 }
Chris@0 173
Chris@0 174 Plugin *plugin = 0;
Chris@0 175
Chris@0 176 // Remember what the original transform looked like, and index
Chris@0 177 // based on this -- because we may be about to fill in the zeros
Chris@0 178 // for step and block size, but we want any further copies with
Chris@0 179 // the same zeros to match this one
Chris@0 180 Transform originalTransform = transform;
Chris@0 181
Chris@0 182 if (m_transformPluginMap.find(transform) == m_transformPluginMap.end()) {
Chris@0 183
Chris@0 184 // Test whether we already have a transform that is identical
Chris@0 185 // to this, except for the output requested and/or the summary
Chris@0 186 // type -- if so, they should share plugin instances (a vital
Chris@0 187 // optimisation)
Chris@0 188
Chris@0 189 for (TransformPluginMap::iterator i = m_transformPluginMap.begin();
Chris@0 190 i != m_transformPluginMap.end(); ++i) {
Chris@0 191 Transform test = i->first;
Chris@0 192 test.setOutput(transform.getOutput());
Chris@0 193 test.setSummaryType(transform.getSummaryType());
Chris@0 194 if (transform == test) {
Chris@0 195 cerr << "NOTE: Already have transform identical to this one (for \""
Chris@0 196 << transform.getIdentifier().toStdString()
Chris@0 197 << "\") in every detail except output identifier and/or "
Chris@0 198 << "summary type; sharing its plugin instance" << endl;
Chris@0 199 plugin = i->second;
Chris@0 200 if (transform.getSummaryType() != Transform::NoSummary &&
Chris@0 201 !dynamic_cast<PluginSummarisingAdapter *>(plugin)) {
Chris@0 202 plugin = new PluginSummarisingAdapter(plugin);
Chris@0 203 i->second = plugin;
Chris@0 204 }
Chris@0 205 break;
Chris@0 206 }
Chris@0 207 }
Chris@0 208
Chris@0 209 if (!plugin) {
Chris@0 210
Chris@0 211 TransformFactory *tf = TransformFactory::getInstance();
Chris@0 212
Chris@0 213 PluginBase *pb = tf->instantiatePluginFor(transform);
Chris@0 214 plugin = tf->downcastVampPlugin(pb);
Chris@0 215 if (!plugin) {
Chris@0 216 //!!! todo: handle non-Vamp plugins too, or make the main --list
Chris@0 217 // option print out only Vamp transforms
Chris@0 218 cerr << "ERROR: Failed to load plugin for transform \""
Chris@0 219 << transform.getIdentifier().toStdString() << "\"" << endl;
Chris@0 220 delete pb;
Chris@0 221 return false;
Chris@0 222 }
Chris@0 223
Chris@0 224 // We will provide the plugin with arbitrary step and
Chris@0 225 // block sizes (so that we can use the same read/write
Chris@0 226 // block size for all transforms), and to that end we use
Chris@0 227 // a PluginBufferingAdapter. However, we need to know the
Chris@0 228 // underlying step size so that we can provide the right
Chris@0 229 // context for dense outputs. (Although, don't forget
Chris@0 230 // that the PluginBufferingAdapter rewrites
Chris@0 231 // OneSamplePerStep outputs so as to use FixedSampleRate
Chris@0 232 // -- so it supplies the sample rate in the output
Chris@0 233 // feature. I'm not sure whether we can easily use that.)
Chris@0 234
Chris@0 235 size_t pluginStepSize = plugin->getPreferredStepSize();
Chris@0 236 size_t pluginBlockSize = plugin->getPreferredBlockSize();
Chris@0 237
Chris@25 238 PluginInputDomainAdapter *pida = 0;
Chris@25 239
Chris@0 240 // adapt the plugin for buffering, channels, etc.
Chris@0 241 if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
Chris@51 242
Chris@25 243 pida = new PluginInputDomainAdapter(plugin);
Chris@26 244 pida->setProcessTimestampMethod(PluginInputDomainAdapter::ShiftData);
Chris@51 245
Chris@51 246 PluginInputDomainAdapter::WindowType wtype =
Chris@51 247 convertWindowType(transform.getWindowType());
Chris@51 248 pida->setWindowType(wtype);
Chris@25 249 plugin = pida;
Chris@0 250 }
Chris@0 251
Chris@0 252 PluginBufferingAdapter *pba = new PluginBufferingAdapter(plugin);
Chris@0 253 plugin = pba;
Chris@0 254
Chris@0 255 if (transform.getStepSize() != 0) {
Chris@0 256 pba->setPluginStepSize(transform.getStepSize());
Chris@0 257 } else {
Chris@0 258 transform.setStepSize(pluginStepSize);
Chris@0 259 }
Chris@0 260
Chris@0 261 if (transform.getBlockSize() != 0) {
Chris@0 262 pba->setPluginBlockSize(transform.getBlockSize());
Chris@0 263 } else {
Chris@0 264 transform.setBlockSize(pluginBlockSize);
Chris@0 265 }
Chris@0 266
Chris@0 267 plugin = new PluginChannelAdapter(plugin);
Chris@0 268
Chris@0 269 if (!m_summaries.empty() ||
Chris@0 270 transform.getSummaryType() != Transform::NoSummary) {
Chris@0 271 PluginSummarisingAdapter *adapter =
Chris@0 272 new PluginSummarisingAdapter(plugin);
Chris@0 273 adapter->setSummarySegmentBoundaries(m_boundaries);
Chris@0 274 plugin = adapter;
Chris@0 275 }
Chris@0 276
Chris@0 277 if (!plugin->initialise(m_channels, m_blockSize, m_blockSize)) {
Chris@0 278 cerr << "ERROR: Plugin initialise (channels = " << m_channels << ", stepSize = " << m_blockSize << ", blockSize = " << m_blockSize << ") failed." << endl;
Chris@0 279 delete plugin;
Chris@0 280 return false;
Chris@0 281 }
Chris@0 282
Chris@0 283 // cerr << "Initialised plugin" << endl;
Chris@0 284
Chris@0 285 size_t actualStepSize = 0;
Chris@0 286 size_t actualBlockSize = 0;
Chris@0 287 pba->getActualStepAndBlockSizes(actualStepSize, actualBlockSize);
Chris@0 288 transform.setStepSize(actualStepSize);
Chris@0 289 transform.setBlockSize(actualBlockSize);
Chris@0 290
Chris@0 291 Plugin::OutputList outputs = plugin->getOutputDescriptors();
Chris@0 292 for (int i = 0; i < (int)outputs.size(); ++i) {
Chris@0 293
Chris@0 294 // cerr << "Newly initialised plugin output " << i << " has bin count " << outputs[i].binCount << endl;
Chris@0 295
Chris@0 296 m_pluginOutputs[plugin][outputs[i].identifier] = outputs[i];
Chris@0 297 m_pluginOutputIndices[outputs[i].identifier] = i;
Chris@0 298 }
Chris@0 299
Chris@10 300 cerr << "NOTE: Loaded and initialised plugin for transform \""
Chris@25 301 << transform.getIdentifier().toStdString()
Chris@25 302 << "\" with plugin step size " << actualStepSize
Chris@25 303 << " and block size " << actualBlockSize
Chris@25 304 << " (adapter step and block size " << m_blockSize << ")"
Chris@25 305 << endl;
Chris@25 306
Chris@25 307 if (pida) {
Chris@25 308 cerr << "NOTE: PluginInputDomainAdapter timestamp adjustment is "
Chris@25 309
Chris@25 310 << pida->getTimestampAdjustment() << endl;
Chris@25 311 }
Chris@8 312
Chris@8 313 } else {
Chris@8 314
Chris@8 315 if (transform.getStepSize() == 0 || transform.getBlockSize() == 0) {
Chris@8 316
Chris@8 317 PluginWrapper *pw = dynamic_cast<PluginWrapper *>(plugin);
Chris@8 318 if (pw) {
Chris@8 319 PluginBufferingAdapter *pba =
Chris@8 320 pw->getWrapper<PluginBufferingAdapter>();
Chris@8 321 if (pba) {
Chris@8 322 size_t actualStepSize = 0;
Chris@8 323 size_t actualBlockSize = 0;
Chris@8 324 pba->getActualStepAndBlockSizes(actualStepSize,
Chris@8 325 actualBlockSize);
Chris@8 326 if (transform.getStepSize() == 0) {
Chris@8 327 transform.setStepSize(actualStepSize);
Chris@8 328 }
Chris@8 329 if (transform.getBlockSize() == 0) {
Chris@8 330 transform.setBlockSize(actualBlockSize);
Chris@8 331 }
Chris@8 332 }
Chris@8 333 }
Chris@8 334 }
Chris@0 335 }
Chris@0 336
Chris@0 337 if (transform.getOutput() == "") {
Chris@0 338 transform.setOutput
Chris@0 339 (plugin->getOutputDescriptors()[0].identifier.c_str());
Chris@0 340 }
Chris@0 341
Chris@0 342 m_transformPluginMap[transform] = plugin;
Chris@0 343
Chris@0 344 if (!(originalTransform == transform)) {
Chris@0 345 m_transformPluginMap[originalTransform] = plugin;
Chris@0 346 }
Chris@0 347
Chris@0 348 } else {
Chris@0 349
Chris@0 350 plugin = m_transformPluginMap[transform];
Chris@0 351 }
Chris@0 352
Chris@109 353 if (m_plugins.find(plugin) == m_plugins.end()) {
Chris@109 354 m_orderedPlugins.push_back(plugin);
Chris@109 355 }
Chris@109 356
Chris@0 357 m_plugins[plugin][transform] = writers;
Chris@0 358
Chris@0 359 return true;
Chris@0 360 }
Chris@0 361
Chris@0 362 bool FeatureExtractionManager::addDefaultFeatureExtractor
Chris@0 363 (TransformId transformId, const vector<FeatureWriter*> &writers)
Chris@0 364 {
Chris@0 365 TransformFactory *tf = TransformFactory::getInstance();
Chris@0 366
Chris@0 367 if (m_sampleRate == 0) {
Chris@0 368 if (m_defaultSampleRate == 0) {
Chris@0 369 cerr << "ERROR: Default transform requested, but no default sample rate available" << endl;
Chris@0 370 return false;
Chris@0 371 } else {
Chris@0 372 cerr << "NOTE: Using default sample rate of " << m_defaultSampleRate << " for default transform" << endl;
Chris@0 373 m_sampleRate = m_defaultSampleRate;
Chris@0 374 }
Chris@0 375 }
Chris@0 376
Chris@0 377 Transform transform = tf->getDefaultTransformFor(transformId, m_sampleRate);
Chris@0 378
Chris@0 379 return addFeatureExtractor(transform, writers);
Chris@0 380 }
Chris@0 381
Chris@0 382 bool FeatureExtractionManager::addFeatureExtractorFromFile
Chris@0 383 (QString transformXmlFile, const vector<FeatureWriter*> &writers)
Chris@0 384 {
Chris@99 385 bool tryRdf = true;
Chris@99 386
Chris@99 387 if (transformXmlFile.endsWith(".xml") || transformXmlFile.endsWith(".XML")) {
Chris@99 388 // We don't support RDF-XML (and nor does the underlying
Chris@99 389 // parser library) so skip the RDF parse if the filename
Chris@99 390 // suggests XML, to avoid puking out a load of errors from
Chris@99 391 // feeding XML to a Turtle parser
Chris@99 392 tryRdf = false;
Chris@0 393 }
Chris@99 394
Chris@99 395 if (tryRdf) {
Chris@99 396 RDFTransformFactory factory
Chris@99 397 (QUrl::fromLocalFile(QFileInfo(transformXmlFile).absoluteFilePath())
Chris@99 398 .toString());
Chris@99 399 ProgressPrinter printer("Parsing transforms RDF file");
Chris@99 400 std::vector<Transform> transforms = factory.getTransforms(&printer);
Chris@99 401 if (!factory.isOK()) {
Chris@99 402 cerr << "WARNING: FeatureExtractionManager::addFeatureExtractorFromFile: Failed to parse transforms file: " << factory.getErrorString().toStdString() << endl;
Chris@99 403 if (factory.isRDF()) {
Chris@99 404 return false; // no point trying it as XML
Chris@0 405 }
Chris@0 406 }
Chris@99 407 if (!transforms.empty()) {
Chris@99 408 bool success = true;
Chris@99 409 for (int i = 0; i < (int)transforms.size(); ++i) {
Chris@99 410 if (!addFeatureExtractor(transforms[i], writers)) {
Chris@99 411 success = false;
Chris@99 412 }
Chris@99 413 }
Chris@99 414 return success;
Chris@99 415 }
Chris@0 416 }
Chris@0 417
Chris@0 418 QFile file(transformXmlFile);
Chris@0 419 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
Chris@0 420 cerr << "ERROR: Failed to open transform XML file \""
Chris@0 421 << transformXmlFile.toStdString() << "\" for reading" << endl;
Chris@0 422 return false;
Chris@0 423 }
Chris@0 424
Chris@0 425 QTextStream *qts = new QTextStream(&file);
Chris@0 426 QString qs = qts->readAll();
Chris@0 427 delete qts;
Chris@0 428 file.close();
Chris@0 429
Chris@0 430 Transform transform(qs);
Chris@0 431
Chris@0 432 return addFeatureExtractor(transform, writers);
Chris@0 433 }
Chris@0 434
Chris@106 435 void FeatureExtractionManager::addSource(QString audioSource, bool willMultiplex)
Chris@0 436 {
Chris@45 437 std::cerr << "Have audio source: \"" << audioSource.toStdString() << "\"" << std::endl;
Chris@45 438
Chris@45 439 // We don't actually do anything with it here, unless it's the
Chris@45 440 // first audio source and we need it to establish default channel
Chris@45 441 // count and sample rate
Chris@45 442
Chris@45 443 if (m_channels == 0 || m_defaultSampleRate == 0) {
Chris@45 444
Chris@45 445 ProgressPrinter retrievalProgress("Determining default rate and channel count from first input file...");
Chris@45 446
Chris@45 447 FileSource source(audioSource, &retrievalProgress);
Chris@45 448 if (!source.isAvailable()) {
Chris@45 449 cerr << "ERROR: File or URL \"" << audioSource.toStdString()
Chris@45 450 << "\" could not be located" << endl;
Chris@45 451 throw FileNotFound(audioSource);
Chris@45 452 }
Chris@45 453
Chris@45 454 source.waitForData();
Chris@45 455
Chris@45 456 // Open to determine validity, channel count, sample rate only
Chris@45 457 // (then close, and open again later with actual desired rate &c)
Chris@45 458
Chris@45 459 AudioFileReader *reader =
Chris@95 460 AudioFileReaderFactory::createReader(source, 0, false,
Chris@95 461 &retrievalProgress);
Chris@45 462
Chris@45 463 if (!reader) {
Chris@45 464 throw FailedToOpenFile(audioSource);
Chris@45 465 }
Chris@45 466
Chris@45 467 retrievalProgress.done();
Chris@45 468
Chris@45 469 cerr << "File or URL \"" << audioSource.toStdString() << "\" opened successfully" << endl;
Chris@45 470
Chris@106 471 if (willMultiplex) {
Chris@106 472 ++m_channels; // channel count is simply number of sources
Chris@106 473 } else {
Chris@106 474 if (m_channels == 0) {
Chris@106 475 m_channels = reader->getChannelCount();
Chris@106 476 cerr << "Taking default channel count of "
Chris@106 477 << reader->getChannelCount() << " from file" << endl;
Chris@106 478 }
Chris@45 479 }
Chris@45 480
Chris@45 481 if (m_defaultSampleRate == 0) {
Chris@45 482 m_defaultSampleRate = reader->getNativeRate();
Chris@45 483 cerr << "Taking default sample rate of "
Chris@45 484 << reader->getNativeRate() << "Hz from file" << endl;
Chris@45 485 cerr << "(Note: Default may be overridden by transforms)" << endl;
Chris@45 486 }
Chris@45 487
Chris@45 488 m_readyReaders[audioSource] = reader;
Chris@45 489 }
Chris@45 490 }
Chris@45 491
Chris@112 492 void FeatureExtractionManager::extractFeatures(QString audioSource)
Chris@45 493 {
Chris@45 494 if (m_plugins.empty()) return;
Chris@45 495
Chris@45 496 testOutputFiles(audioSource);
Chris@45 497
Chris@0 498 if (m_sampleRate == 0) {
Chris@45 499 throw FileOperationFailed
Chris@45 500 (audioSource, "internal error: have sources and plugins, but no sample rate");
Chris@45 501 }
Chris@45 502 if (m_channels == 0) {
Chris@45 503 throw FileOperationFailed
Chris@45 504 (audioSource, "internal error: have sources and plugins, but no channel count");
Chris@0 505 }
Chris@0 506
Chris@106 507 AudioFileReader *reader = prepareReader(audioSource);
Chris@106 508 extractFeaturesFor(reader, audioSource); // Note this also deletes reader
Chris@106 509 }
Chris@102 510
Chris@106 511 void FeatureExtractionManager::extractFeaturesMultiplexed(QStringList sources)
Chris@106 512 {
Chris@106 513 if (m_plugins.empty() || sources.empty()) return;
Chris@106 514
Chris@106 515 QString nominalSource = sources[0];
Chris@106 516
Chris@106 517 testOutputFiles(nominalSource);
Chris@106 518
Chris@106 519 if (m_sampleRate == 0) {
Chris@106 520 throw FileOperationFailed
Chris@106 521 (nominalSource, "internal error: have sources and plugins, but no sample rate");
Chris@106 522 }
Chris@106 523 if (m_channels == 0) {
Chris@106 524 throw FileOperationFailed
Chris@106 525 (nominalSource, "internal error: have sources and plugins, but no channel count");
Chris@106 526 }
Chris@106 527
Chris@106 528 QList<AudioFileReader *> readers;
Chris@106 529 foreach (QString source, sources) {
Chris@106 530 AudioFileReader *reader = prepareReader(source);
Chris@106 531 readers.push_back(reader);
Chris@106 532 }
Chris@106 533
Chris@106 534 AudioFileReader *reader = new MultiplexedReader(readers);
Chris@106 535 extractFeaturesFor(reader, nominalSource); // Note this also deletes reader
Chris@106 536 }
Chris@106 537
Chris@106 538 AudioFileReader *
Chris@106 539 FeatureExtractionManager::prepareReader(QString source)
Chris@106 540 {
Chris@45 541 AudioFileReader *reader = 0;
Chris@106 542 if (m_readyReaders.contains(source)) {
Chris@106 543 reader = m_readyReaders[source];
Chris@106 544 m_readyReaders.remove(source);
Chris@106 545 if (reader->getSampleRate() != m_sampleRate) {
Chris@45 546 // can't use this; open it again
Chris@45 547 delete reader;
Chris@45 548 reader = 0;
Chris@45 549 }
Chris@45 550 }
Chris@45 551 if (!reader) {
Chris@45 552 ProgressPrinter retrievalProgress("Retrieving audio data...");
Chris@106 553 FileSource fs(source, &retrievalProgress);
Chris@106 554 fs.waitForData();
Chris@45 555 reader = AudioFileReaderFactory::createReader
Chris@106 556 (fs, m_sampleRate, false, &retrievalProgress);
Chris@45 557 retrievalProgress.done();
Chris@45 558 }
Chris@102 559 if (!reader) {
Chris@107 560 throw FailedToOpenFile(source);
Chris@102 561 }
Chris@106 562 return reader;
Chris@106 563 }
Chris@45 564
Chris@106 565 void
Chris@106 566 FeatureExtractionManager::extractFeaturesFor(AudioFileReader *reader,
Chris@106 567 QString audioSource)
Chris@106 568 {
Chris@106 569 // Note: This also deletes reader
Chris@0 570
Chris@45 571 cerr << "Audio file \"" << audioSource.toStdString() << "\": "
Chris@45 572 << reader->getChannelCount() << "ch at "
Chris@45 573 << reader->getNativeRate() << "Hz" << endl;
Chris@45 574 if (reader->getChannelCount() != m_channels ||
Chris@45 575 reader->getNativeRate() != m_sampleRate) {
Chris@45 576 cerr << "NOTE: File will be mixed or resampled for processing: "
Chris@45 577 << m_channels << "ch at "
Chris@45 578 << m_sampleRate << "Hz" << endl;
Chris@45 579 }
Chris@11 580
Chris@0 581 // allocate audio buffers
Chris@0 582 float **data = new float *[m_channels];
Chris@0 583 for (int c = 0; c < m_channels; ++c) {
Chris@0 584 data[c] = new float[m_blockSize];
Chris@0 585 }
Chris@31 586
Chris@31 587 struct LifespanMgr { // unintrusive hack introduced to ensure
Chris@31 588 // destruction on exceptions
Chris@31 589 AudioFileReader *m_r;
Chris@31 590 int m_c;
Chris@31 591 float **m_d;
Chris@31 592 LifespanMgr(AudioFileReader *r, int c, float **d) :
Chris@31 593 m_r(r), m_c(c), m_d(d) { }
Chris@31 594 ~LifespanMgr() { destroy(); }
Chris@31 595 void destroy() {
Chris@31 596 if (!m_r) return;
Chris@31 597 delete m_r;
Chris@31 598 for (int i = 0; i < m_c; ++i) delete[] m_d[i];
Chris@31 599 delete[] m_d;
Chris@31 600 m_r = 0;
Chris@31 601 }
Chris@31 602 };
Chris@31 603 LifespanMgr lifemgr(reader, m_channels, data);
Chris@0 604
Chris@0 605 size_t frameCount = reader->getFrameCount();
Chris@0 606
Chris@0 607 // cerr << "file has " << frameCount << " frames" << endl;
Chris@0 608
Chris@99 609 int earliestStartFrame = 0;
Chris@99 610 int latestEndFrame = frameCount;
Chris@99 611 bool haveExtents = false;
Chris@99 612
Chris@109 613 foreach (Plugin *plugin, m_orderedPlugins) {
Chris@0 614
Chris@109 615 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 616
Chris@109 617 std::cerr << "Calling reset on " << plugin << std::endl;
Chris@0 618 plugin->reset();
Chris@0 619
Chris@0 620 for (TransformWriterMap::iterator ti = pi->second.begin();
Chris@0 621 ti != pi->second.end(); ++ti) {
Chris@0 622
Chris@0 623 const Transform &transform = ti->first;
Chris@0 624
Chris@99 625 int startFrame = RealTime::realTime2Frame
Chris@99 626 (transform.getStartTime(), m_sampleRate);
Chris@99 627 int duration = RealTime::realTime2Frame
Chris@99 628 (transform.getDuration(), m_sampleRate);
Chris@99 629 if (duration == 0) {
Chris@99 630 duration = frameCount - startFrame;
Chris@99 631 }
Chris@99 632
Chris@99 633 if (!haveExtents || startFrame < earliestStartFrame) {
Chris@99 634 earliestStartFrame = startFrame;
Chris@99 635 }
Chris@99 636 if (!haveExtents || startFrame + duration > latestEndFrame) {
Chris@99 637 latestEndFrame = startFrame + duration;
Chris@99 638 }
Chris@99 639
Chris@109 640 cerr << "startFrame for transform " << startFrame << endl;
Chris@109 641 cerr << "duration for transform " << duration << endl;
Chris@109 642 cerr << "earliestStartFrame becomes " << earliestStartFrame << endl;
Chris@109 643 cerr << "latestEndFrame becomes " << latestEndFrame << endl;
Chris@109 644
Chris@99 645 haveExtents = true;
Chris@0 646
Chris@0 647 string outputId = transform.getOutput().toStdString();
Chris@0 648 if (m_pluginOutputs[plugin].find(outputId) ==
Chris@0 649 m_pluginOutputs[plugin].end()) {
Chris@0 650 //!!! throw?
Chris@0 651 cerr << "WARNING: Nonexistent plugin output \"" << outputId << "\" requested for transform \""
Chris@0 652 << transform.getIdentifier().toStdString() << "\", ignoring this transform"
Chris@0 653 << endl;
Chris@0 654 /*
Chris@0 655 cerr << "Known outputs for all plugins are as follows:" << endl;
Chris@0 656 for (PluginOutputMap::const_iterator k = m_pluginOutputs.begin();
Chris@0 657 k != m_pluginOutputs.end(); ++k) {
Chris@0 658 cerr << "Plugin " << k->first << ": ";
Chris@0 659 if (k->second.empty()) {
Chris@0 660 cerr << "(none)";
Chris@0 661 }
Chris@0 662 for (OutputMap::const_iterator i = k->second.begin();
Chris@0 663 i != k->second.end(); ++i) {
Chris@0 664 cerr << "\"" << i->first << "\" ";
Chris@0 665 }
Chris@0 666 cerr << endl;
Chris@0 667 }
Chris@0 668 */
Chris@0 669 }
Chris@0 670 }
Chris@0 671 }
Chris@0 672
Chris@99 673 int startFrame = earliestStartFrame;
Chris@99 674 int endFrame = latestEndFrame;
Chris@0 675
Chris@109 676 foreach (Plugin *plugin, m_orderedPlugins) {
Chris@109 677
Chris@109 678 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 679
Chris@0 680 for (TransformWriterMap::const_iterator ti = pi->second.begin();
Chris@0 681 ti != pi->second.end(); ++ti) {
Chris@0 682
Chris@0 683 const vector<FeatureWriter *> &writers = ti->second;
Chris@0 684
Chris@0 685 for (int j = 0; j < (int)writers.size(); ++j) {
Chris@0 686 FeatureWriter::TrackMetadata m;
Chris@0 687 m.title = reader->getTitle();
Chris@0 688 m.maker = reader->getMaker();
Chris@19 689 if (m.title != "" && m.maker != "") {
Chris@19 690 writers[j]->setTrackMetadata(audioSource, m);
Chris@19 691 }
Chris@0 692 }
Chris@0 693 }
Chris@0 694 }
Chris@0 695
Chris@0 696 ProgressPrinter extractionProgress("Extracting and writing features...");
Chris@0 697 int progress = 0;
Chris@0 698
Chris@99 699 for (int i = startFrame; i < endFrame; i += m_blockSize) {
Chris@0 700
Chris@0 701 //!!! inefficient, although much of the inefficiency may be
Chris@99 702 // susceptible to compiler optimisation
Chris@0 703
Chris@0 704 SampleBlock frames;
Chris@0 705 reader->getInterleavedFrames(i, m_blockSize, frames);
Chris@0 706
Chris@0 707 // We have to do our own channel handling here; we can't just
Chris@0 708 // leave it to the plugin adapter because the same plugin
Chris@0 709 // adapter may have to serve for input files with various
Chris@0 710 // numbers of channels (so the adapter is simply configured
Chris@34 711 // with a fixed channel count).
Chris@0 712
Chris@0 713 int rc = reader->getChannelCount();
Chris@0 714
Chris@34 715 // m_channels is the number of channels we need for the plugin
Chris@34 716
Chris@34 717 int index;
Chris@34 718 int fc = (int)frames.size();
Chris@46 719
Chris@34 720 if (m_channels == 1) { // only case in which we can sensibly mix down
Chris@34 721 for (int j = 0; j < m_blockSize; ++j) {
Chris@34 722 data[0][j] = 0.f;
Chris@34 723 }
Chris@34 724 for (int c = 0; c < rc; ++c) {
Chris@34 725 for (int j = 0; j < m_blockSize; ++j) {
Chris@0 726 index = j * rc + c;
Chris@34 727 if (index < fc) data[0][j] += frames[index];
Chris@0 728 }
Chris@0 729 }
Chris@34 730 for (int j = 0; j < m_blockSize; ++j) {
Chris@34 731 data[0][j] /= rc;
Chris@34 732 }
Chris@34 733 } else {
Chris@34 734 for (int c = 0; c < m_channels; ++c) {
Chris@34 735 for (int j = 0; j < m_blockSize; ++j) {
Chris@34 736 data[c][j] = 0.f;
Chris@34 737 }
Chris@34 738 if (c < rc) {
Chris@34 739 for (int j = 0; j < m_blockSize; ++j) {
Chris@34 740 index = j * rc + c;
Chris@34 741 if (index < fc) data[c][j] += frames[index];
Chris@34 742 }
Chris@34 743 }
Chris@34 744 }
Chris@34 745 }
Chris@0 746
Chris@0 747 Vamp::RealTime timestamp = Vamp::RealTime::frame2RealTime
Chris@0 748 (i, m_sampleRate);
Chris@0 749
Chris@109 750 foreach (Plugin *plugin, m_orderedPlugins) {
Chris@0 751
Chris@109 752 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 753 Plugin::FeatureSet featureSet = plugin->process(data, timestamp);
Chris@0 754
Chris@0 755 if (!m_summariesOnly) {
Chris@0 756 writeFeatures(audioSource, plugin, featureSet);
Chris@0 757 }
Chris@0 758 }
Chris@0 759
Chris@0 760 int pp = progress;
Chris@6 761 progress = int(((i - startFrame) * 100.0) / (endFrame - startFrame) + 0.1);
Chris@0 762 if (progress > pp) extractionProgress.setProgress(progress);
Chris@0 763 }
Chris@10 764
Chris@22 765 // std::cerr << "FeatureExtractionManager: deleting audio file reader" << std::endl;
Chris@12 766
Chris@31 767 lifemgr.destroy(); // deletes reader, data
Chris@57 768
Chris@109 769 foreach (Plugin *plugin, m_orderedPlugins) {
Chris@57 770
Chris@109 771 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 772 Plugin::FeatureSet featureSet = plugin->getRemainingFeatures();
Chris@0 773
Chris@0 774 if (!m_summariesOnly) {
Chris@0 775 writeFeatures(audioSource, plugin, featureSet);
Chris@0 776 }
Chris@0 777
Chris@0 778 if (!m_summaries.empty()) {
Chris@0 779 PluginSummarisingAdapter *adapter =
Chris@0 780 dynamic_cast<PluginSummarisingAdapter *>(plugin);
Chris@0 781 if (!adapter) {
Chris@0 782 cerr << "WARNING: Summaries requested, but plugin is not a summarising adapter" << endl;
Chris@0 783 } else {
Chris@0 784 for (SummaryNameSet::const_iterator sni = m_summaries.begin();
Chris@0 785 sni != m_summaries.end(); ++sni) {
Chris@0 786 featureSet.clear();
Chris@0 787 //!!! problem here -- we are requesting summaries
Chris@0 788 //!!! for all outputs, but they in principle have
Chris@0 789 //!!! different averaging requirements depending
Chris@0 790 //!!! on whether their features have duration or
Chris@0 791 //!!! not
Chris@0 792 featureSet = adapter->getSummaryForAllOutputs
Chris@0 793 (getSummaryType(*sni),
Chris@0 794 PluginSummarisingAdapter::ContinuousTimeAverage);
Chris@0 795 writeFeatures(audioSource, plugin, featureSet,//!!! *sni);
Chris@0 796 Transform::stringToSummaryType(sni->c_str()));
Chris@0 797 }
Chris@0 798 }
Chris@0 799 }
Chris@0 800
Chris@0 801 writeSummaries(audioSource, plugin);
Chris@0 802 }
Chris@0 803
Chris@3 804 extractionProgress.done();
Chris@3 805
Chris@0 806 finish();
Chris@0 807
Chris@0 808 TempDirectory::getInstance()->cleanup();
Chris@0 809 }
Chris@0 810
Chris@0 811 void
Chris@0 812 FeatureExtractionManager::writeSummaries(QString audioSource, Plugin *plugin)
Chris@0 813 {
Chris@0 814 // caller should have ensured plugin is in m_plugins
Chris@0 815 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 816
Chris@0 817 for (TransformWriterMap::const_iterator ti = pi->second.begin();
Chris@0 818 ti != pi->second.end(); ++ti) {
Chris@0 819
Chris@0 820 const Transform &transform = ti->first;
Chris@0 821 const vector<FeatureWriter *> &writers = ti->second;
Chris@0 822
Chris@0 823 Transform::SummaryType summaryType = transform.getSummaryType();
Chris@0 824 PluginSummarisingAdapter::SummaryType pType =
Chris@0 825 (PluginSummarisingAdapter::SummaryType)summaryType;
Chris@0 826
Chris@0 827 if (transform.getSummaryType() == Transform::NoSummary) {
Chris@0 828 continue;
Chris@0 829 }
Chris@0 830
Chris@0 831 PluginSummarisingAdapter *adapter =
Chris@0 832 dynamic_cast<PluginSummarisingAdapter *>(plugin);
Chris@0 833 if (!adapter) {
Chris@0 834 cerr << "FeatureExtractionManager::writeSummaries: INTERNAL ERROR: Summary requested for transform, but plugin is not a summarising adapter" << endl;
Chris@0 835 continue;
Chris@0 836 }
Chris@0 837
Chris@0 838 Plugin::FeatureSet featureSet = adapter->getSummaryForAllOutputs
Chris@0 839 (pType, PluginSummarisingAdapter::ContinuousTimeAverage);
Chris@0 840
Chris@0 841 // cout << "summary type " << int(pType) << " for transform:" << endl << transform.toXmlString().toStdString()<< endl << "... feature set with " << featureSet.size() << " elts" << endl;
Chris@0 842
Chris@0 843 writeFeatures(audioSource, plugin, featureSet, summaryType);
Chris@0 844 }
Chris@0 845 }
Chris@0 846
Chris@0 847 void FeatureExtractionManager::writeFeatures(QString audioSource,
Chris@0 848 Plugin *plugin,
Chris@0 849 const Plugin::FeatureSet &features,
Chris@0 850 Transform::SummaryType summaryType)
Chris@0 851 {
Chris@0 852 // caller should have ensured plugin is in m_plugins
Chris@0 853 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 854
Chris@0 855 for (TransformWriterMap::const_iterator ti = pi->second.begin();
Chris@0 856 ti != pi->second.end(); ++ti) {
Chris@0 857
Chris@0 858 const Transform &transform = ti->first;
Chris@0 859 const vector<FeatureWriter *> &writers = ti->second;
Chris@0 860
Chris@0 861 if (transform.getSummaryType() != Transform::NoSummary &&
Chris@0 862 m_summaries.empty() &&
Chris@0 863 summaryType == Transform::NoSummary) {
Chris@0 864 continue;
Chris@0 865 }
Chris@0 866
Chris@0 867 if (transform.getSummaryType() != Transform::NoSummary &&
Chris@0 868 summaryType != Transform::NoSummary &&
Chris@0 869 transform.getSummaryType() != summaryType) {
Chris@0 870 continue;
Chris@0 871 }
Chris@0 872
Chris@0 873 string outputId = transform.getOutput().toStdString();
Chris@0 874
Chris@0 875 if (m_pluginOutputs[plugin].find(outputId) ==
Chris@0 876 m_pluginOutputs[plugin].end()) {
Chris@0 877 continue;
Chris@0 878 }
Chris@0 879
Chris@0 880 const Plugin::OutputDescriptor &desc =
Chris@0 881 m_pluginOutputs[plugin][outputId];
Chris@0 882
Chris@0 883 int outputIndex = m_pluginOutputIndices[outputId];
Chris@0 884 Plugin::FeatureSet::const_iterator fsi = features.find(outputIndex);
Chris@0 885 if (fsi == features.end()) continue;
Chris@0 886
Chris@0 887 for (int j = 0; j < (int)writers.size(); ++j) {
Chris@0 888 writers[j]->write
Chris@0 889 (audioSource, transform, desc, fsi->second,
Chris@0 890 Transform::summaryTypeToString(summaryType).toStdString());
Chris@0 891 }
Chris@0 892 }
Chris@0 893 }
Chris@0 894
Chris@31 895 void FeatureExtractionManager::testOutputFiles(QString audioSource)
Chris@31 896 {
Chris@31 897 for (PluginMap::iterator pi = m_plugins.begin();
Chris@31 898 pi != m_plugins.end(); ++pi) {
Chris@31 899
Chris@31 900 for (TransformWriterMap::iterator ti = pi->second.begin();
Chris@31 901 ti != pi->second.end(); ++ti) {
Chris@31 902
Chris@31 903 vector<FeatureWriter *> &writers = ti->second;
Chris@31 904
Chris@31 905 for (int i = 0; i < (int)writers.size(); ++i) {
Chris@31 906 writers[i]->testOutputFile(audioSource, ti->first.getIdentifier());
Chris@31 907 }
Chris@31 908 }
Chris@31 909 }
Chris@31 910 }
Chris@31 911
Chris@0 912 void FeatureExtractionManager::finish()
Chris@0 913 {
Chris@109 914 foreach (Plugin *plugin, m_orderedPlugins) {
Chris@109 915
Chris@109 916 PluginMap::iterator pi = m_plugins.find(plugin);
Chris@0 917
Chris@0 918 for (TransformWriterMap::iterator ti = pi->second.begin();
Chris@0 919 ti != pi->second.end(); ++ti) {
Chris@0 920
Chris@0 921 vector<FeatureWriter *> &writers = ti->second;
Chris@0 922
Chris@0 923 for (int i = 0; i < (int)writers.size(); ++i) {
Chris@0 924 writers[i]->flush();
Chris@0 925 writers[i]->finish();
Chris@0 926 }
Chris@0 927 }
Chris@0 928 }
Chris@0 929 }
Chris@0 930
Chris@0 931 void FeatureExtractionManager::print(Transform transform) const
Chris@0 932 {
Chris@0 933 QString qs;
Chris@0 934 QTextStream qts(&qs);
Chris@0 935 transform.toXml(qts);
Chris@0 936 cerr << qs.toStdString() << endl;
Chris@0 937 }