| 1 | /* |
| 2 | Copyright (C) 2011 Mario Stephan <[email protected]> |
| 3 | |
| 4 | This library is free software; you can redistribute it and/or modify |
| 5 | it under the terms of the GNU Lesser General Public License as published |
| 6 | by the Free Software Foundation; either version 2.1 of the License, or |
| 7 | (at your option) any later version. |
| 8 | |
| 9 | This program is distributed in the hope that it will be useful, |
| 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | GNU General Public License for more details. |
| 13 | |
| 14 | You should have received a copy of the GNU Lesser General Public License |
| 15 | along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | */ |
| 17 | |
| 18 | #include "trackanalyser.h" |
| 19 | |
| 20 | #include <QtGui> |
| 21 | #if QT_VERSION >= 0x050000 |
| 22 | #include <QtConcurrent/QtConcurrent> |
| 23 | #else |
| 24 | #include <QtConcurrentRun> |
| 25 | #endif |
| 26 | |
| 27 | #define AUDIOFREQ 32000 |
| 28 | #define SCAN_DURATION 60 |
| 29 | static const guint spect_bands = 8; |
| 30 | |
| 31 | struct TrackAnalyser_Private |
| 32 | { |
| 33 | QFutureWatcher<void> watcher; |
| 34 | QMutex mutex; |
| 35 | guint64 fft_res; |
| 36 | float lastSpectrum[spect_bands]; |
| 37 | QList<float> spectralFlux; |
| 38 | int bpm; |
| 39 | GstElement *src, *conv, *sink, *cutter, *audio, *analysis, *spectrum; |
| 40 | TrackAnalyser::modeType analysisMode; |
| 41 | }; |
| 42 | |
| 43 | TrackAnalyser::TrackAnalyser(QWidget *parent) : |
| 44 | QWidget(parent), |
| 45 | pipeline(nullptr), m_finished(false) |
| 46 | , p( new TrackAnalyser_Private ) |
| 47 | { |
| 48 | p->fft_res = 435; //sample rate for fft samples in Hz |
| 49 | for (int i=0;i<spect_bands;i++) |
| 50 | p->lastSpectrum[i]=0.0; |
| 51 | |
| 52 | gst_init (nullptr, nullptr); |
| 53 | prepare(); |
| 54 | connect(&p->watcher, SIGNAL(finished()), this, SLOT(loadThreadFinished())); |
| 55 | |
| 56 | } |
| 57 | |
| 58 | void TrackAnalyser::sync_set_state(GstElement* element, GstState state) |
| 59 | { GstStateChangeReturn res; \ |
| 60 | res = gst_element_set_state (GST_ELEMENT (element), state); \ |
| 61 | if(res == GST_STATE_CHANGE_FAILURE) return; \ |
| 62 | if(res == GST_STATE_CHANGE_ASYNC) { \ |
| 63 | GstState state; \ |
| 64 | res = gst_element_get_state(GST_ELEMENT (element), &state, NULL, 1000000000/*GST_CLOCK_TIME_NONE*/); \ |
| 65 | if(res == GST_STATE_CHANGE_FAILURE || res == GST_STATE_CHANGE_ASYNC) return; \ |
| 66 | } } |
| 67 | |
| 68 | TrackAnalyser::~TrackAnalyser() |
| 69 | { |
| 70 | cleanup(); |
| 71 | delete p; |
| 72 | p = nullptr; |
| 73 | } |
| 74 | |
| 75 | |
| 76 | void cb_newpad_ta (GstElement *src, |
| 77 | GstPad *new_pad, |
| 78 | gpointer data) |
| 79 | { |
| 80 | TrackAnalyser* instance = (TrackAnalyser*)data; |
| 81 | instance->newpad(src, new_pad, data); |
| 82 | } |
| 83 | |
| 84 | |
| 85 | void TrackAnalyser::newpad (GstElement *src, |
| 86 | GstPad *new_pad, |
| 87 | gpointer data) |
| 88 | { |
| 89 | GstCaps *caps; |
| 90 | GstStructure *str; |
| 91 | GstPad *sink_pad; |
| 92 | |
| 93 | /* only link once */ |
| 94 | GstElement *bin = gst_bin_get_by_name(GST_BIN(pipeline), "convert"); |
| 95 | sink_pad = gst_element_get_static_pad (bin, "sink"); |
| 96 | |
| 97 | if (GST_PAD_IS_LINKED (sink_pad)) { |
| 98 | g_object_unref (sink_pad); |
| 99 | return; |
| 100 | } |
| 101 | |
| 102 | /* check media type */ |
| 103 | #ifdef GST_API_VERSION_1 |
| 104 | caps = gst_pad_query_caps (new_pad, nullptr); |
| 105 | #else |
| 106 | caps = gst_pad_get_caps (new_pad); |
| 107 | #endif |
| 108 | str = gst_caps_get_structure (caps, 0); |
| 109 | if (!g_strrstr (gst_structure_get_name (str), "audio")) { |
| 110 | gst_caps_unref (caps); |
| 111 | gst_object_unref (sink_pad); |
| 112 | return; |
| 113 | } |
| 114 | gst_caps_unref (caps); |
| 115 | |
| 116 | /* link'n'play */ |
| 117 | gst_pad_link (new_pad, sink_pad); |
| 118 | } |
| 119 | |
| 120 | GstBusSyncReply TrackAnalyser::bus_cb (GstBus *bus, GstMessage *msg, gpointer data) |
| 121 | { |
| 122 | TrackAnalyser* instance = (TrackAnalyser*)data; |
| 123 | instance->messageReceived(msg); |
| 124 | return GST_BUS_PASS; |
| 125 | } |
| 126 | |
| 127 | void TrackAnalyser::cleanup() |
| 128 | { |
| 129 | if(pipeline) sync_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL); |
| 130 | if(bus) gst_object_unref (bus); |
| 131 | if(pipeline) gst_object_unref(G_OBJECT(pipeline)); |
| 132 | } |
| 133 | |
| 134 | bool TrackAnalyser::prepare() |
| 135 | { |
| 136 | pipeline = gst_pipeline_new ("pipeline"); |
| 137 | bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); |
| 138 | p->src = gst_element_factory_make ("uridecodebin", "source"); |
| 139 | |
| 140 | g_signal_connect (p->src, "pad-added", G_CALLBACK (cb_newpad_ta), this); |
| 141 | |
| 142 | p->conv = gst_element_factory_make ("audioconvert", "convert"); |
| 143 | p->spectrum = gst_element_factory_make ("spectrum", "spectrum"); |
| 144 | p->analysis = gst_element_factory_make ("rganalysis", "analysis"); |
| 145 | p->cutter = gst_element_factory_make ("cutter", "cutter"); |
| 146 | p->sink = gst_element_factory_make ("fakesink", "sink"); |
| 147 | |
| 148 | g_object_set (p->analysis, "message", TRUE, NULL); |
| 149 | g_object_set (p->analysis, "num-tracks", 1, NULL); |
| 150 | g_object_set (p->cutter, "threshold-dB", -25.0, NULL); |
| 151 | |
| 152 | g_object_set (G_OBJECT (p->spectrum), "bands", spect_bands, "threshold", -80, |
| 153 | "post-messages", TRUE, "interval", GST_SECOND / p->fft_res, NULL); |
| 154 | |
| 155 | |
| 156 | gst_bin_add_many (GST_BIN (pipeline), p->src, p->conv, p->analysis, p->cutter, p->spectrum, p->sink, NULL); |
| 157 | gst_element_link (p->conv, p->analysis); |
| 158 | gst_element_link (p->analysis, p->cutter); |
| 159 | gst_element_link (p->cutter, p->sink); |
| 160 | |
| 161 | #ifdef GST_API_VERSION_1 |
| 162 | gst_bus_set_sync_handler (bus, bus_cb, this, nullptr); |
| 163 | #else |
| 164 | gst_bus_set_sync_handler (bus, bus_cb, this); |
| 165 | #endif |
| 166 | |
| 167 | return pipeline; |
| 168 | } |
| 169 | |
| 170 | int TrackAnalyser::bpm() |
| 171 | { |
| 172 | return p->bpm; |
| 173 | } |
| 174 | |
| 175 | double TrackAnalyser::gainDB() |
| 176 | { |
| 177 | return m_GainDB; |
| 178 | } |
| 179 | |
| 180 | double TrackAnalyser::gainFactor() |
| 181 | { |
| 182 | return pow (10, m_GainDB / 20); |
| 183 | } |
| 184 | |
| 185 | QTime TrackAnalyser::startPosition() |
| 186 | { |
| 187 | return m_StartPosition; |
| 188 | } |
| 189 | |
| 190 | QTime TrackAnalyser::endPosition() |
| 191 | { |
| 192 | return m_EndPosition; |
| 193 | } |
| 194 | |
| 195 | void TrackAnalyser::setPosition(QTime position) |
| 196 | { |
| 197 | int time_milliseconds=QTime(0,0).msecsTo(position); |
| 198 | gint64 time_nanoseconds=( time_milliseconds * GST_MSECOND ); |
| 199 | gst_element_seek (pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH, |
| 200 | GST_SEEK_TYPE_SET, time_nanoseconds, |
| 201 | GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE); |
| 202 | qDebug() << Q_FUNC_INFO <<":"<<" position="<<position; |
| 203 | } |
| 204 | |
| 205 | void TrackAnalyser::setMode(modeType mode) |
| 206 | { |
| 207 | p->analysisMode = mode; |
| 208 | sync_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL); |
| 209 | |
| 210 | //divide in multiple analyser due to different running times |
| 211 | switch (p->analysisMode) |
| 212 | { |
| 213 | case TEMPO: |
| 214 | gst_element_unlink (p->conv, p->analysis); |
| 215 | gst_element_unlink (p->analysis, p->cutter); |
| 216 | gst_element_unlink (p->cutter, p->sink); |
| 217 | |
| 218 | gst_element_link (p->conv, p->spectrum);//spectrum take too much time |
| 219 | gst_element_link (p->spectrum, p->sink); |
| 220 | break; |
| 221 | default: |
| 222 | gst_element_unlink (p->conv, p->spectrum); |
| 223 | gst_element_unlink (p->spectrum, p->sink); |
| 224 | |
| 225 | gst_element_link (p->conv, p->analysis); |
| 226 | gst_element_link (p->analysis, p->cutter); |
| 227 | gst_element_link (p->cutter, p->sink); |
| 228 | m_StartPosition = m_MaxPosition = QTime(0,0); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | void TrackAnalyser::open(QUrl url) |
| 233 | { |
| 234 | //To avoid delays load track in another thread |
| 235 | qDebug() << Q_FUNC_INFO <<":"<<parentWidget()->objectName()<<" url="<<url; |
| 236 | QFuture<void> future = QtConcurrent::run( this, &TrackAnalyser::asyncOpen,url); |
| 237 | p->watcher.setFuture(future); |
| 238 | } |
| 239 | |
| 240 | void TrackAnalyser::asyncOpen(QUrl url) |
| 241 | { |
| 242 | p->mutex.lock(); |
| 243 | m_GainDB = GAIN_INVALID; |
| 244 | //m_StartPosition = QTime(0,0); |
| 245 | p->spectralFlux.clear(); |
| 246 | |
| 247 | sync_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL); |
| 248 | |
| 249 | |
| 250 | GstElement *src = gst_bin_get_by_name(GST_BIN(pipeline), "source"); |
| 251 | g_object_set (G_OBJECT (src), "uri", (const char*)url.toString().toUtf8(), nullptr); |
| 252 | |
| 253 | sync_set_state (GST_ELEMENT (pipeline), GST_STATE_PAUSED); |
| 254 | |
| 255 | m_finished=false; |
| 256 | |
| 257 | gst_object_unref(src); |
| 258 | p->mutex.unlock(); |
| 259 | } |
| 260 | |
| 261 | void TrackAnalyser::loadThreadFinished() |
| 262 | { |
| 263 | // async load in player done |
| 264 | qDebug() << Q_FUNC_INFO <<":"<<parentWidget()->objectName()<<" analysisMode="<<p->analysisMode; |
| 265 | |
| 266 | if ( p->analysisMode == TrackAnalyser::TEMPO ){ |
| 267 | //setPosition( m_EndPosition.addSecs(-SCAN_DURATION) ); |
| 268 | setPosition(m_StartPosition); |
| 269 | } |
| 270 | else { |
| 271 | m_EndPosition=length(); |
| 272 | } |
| 273 | start(); |
| 274 | } |
| 275 | |
| 276 | void TrackAnalyser::start() |
| 277 | { |
| 278 | qDebug() << Q_FUNC_INFO <<":"<<parentWidget()->objectName(); |
| 279 | gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING); |
| 280 | } |
| 281 | |
| 282 | |
| 283 | bool TrackAnalyser::close() |
| 284 | { |
| 285 | gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL); |
| 286 | return true; |
| 287 | } |
| 288 | |
| 289 | |
| 290 | QTime TrackAnalyser::length() |
| 291 | { |
| 292 | if (pipeline) { |
| 293 | |
| 294 | gint64 value=0; |
| 295 | |
| 296 | #ifdef GST_API_VERSION_1 |
| 297 | if(gst_element_query_duration(pipeline, GST_FORMAT_TIME, &value)) { |
| 298 | #else |
| 299 | GstFormat fmt = GST_FORMAT_TIME; |
| 300 | if(gst_element_query_duration(pipeline, &fmt, &value)) { |
| 301 | #endif |
| 302 | //qDebug() << Q_FUNC_INFO << " new value:" <<value; |
| 303 | m_MaxPosition = QTime(0,0).addMSecs( static_cast<uint>( ( value / GST_MSECOND ) )); // nanosec -> msec |
| 304 | } |
| 305 | } |
| 306 | //qDebug() << Q_FUNC_INFO << " return:" <<m_MaxPosition; |
| 307 | return m_MaxPosition; |
| 308 | } |
| 309 | |
| 310 | |
| 311 | void TrackAnalyser::messageReceived(GstMessage *message) |
| 312 | { |
| 313 | switch (GST_MESSAGE_TYPE (message)) { |
| 314 | case GST_MESSAGE_ERROR: { |
| 315 | GError *err; |
| 316 | gchar *debug; |
| 317 | gst_message_parse_error (message, &err, &debug); |
| 318 | QString str; |
| 319 | str = "Error #"+QString::number(err->code)+" in module "+QString::number(err->domain)+"\n"+QString::fromUtf8(err->message); |
| 320 | if(err->code == 6 && err->domain == 851) { |
| 321 | str += "\nMay be you should to install gstreamer0.10-plugins-ugly or gstreamer0.10-plugins-bad"; |
| 322 | } |
| 323 | qDebug()<< "Gstreamer error:"<< str; |
| 324 | g_error_free (err); |
| 325 | g_free (debug); |
| 326 | need_finish(); |
| 327 | break; |
| 328 | } |
| 329 | case GST_MESSAGE_EOS:{ |
| 330 | qDebug() << Q_FUNC_INFO <<":"<<parentWidget()->objectName()<<" End of track reached"; |
| 331 | need_finish(); |
| 332 | break; |
| 333 | } |
| 334 | case GST_MESSAGE_ELEMENT:{ |
| 335 | |
| 336 | const GstStructure *s = gst_message_get_structure (message); |
| 337 | const gchar *name = gst_structure_get_name (s); |
| 338 | GstClockTime timestamp; |
| 339 | gst_structure_get_clock_time (s, "timestamp", ×tamp); |
| 340 | |
| 341 | // data for tempo detection |
| 342 | if (strcmp (name, "spectrum") == 0) { |
| 343 | const GValue *magnitudes; |
| 344 | const GValue *mag; |
| 345 | float mag_value; |
| 346 | guint i; |
| 347 | |
| 348 | magnitudes = gst_structure_get_value (s, "magnitude"); |
| 349 | |
| 350 | float flux = 0; |
| 351 | for (i = 0; i < spect_bands; ++i) { |
| 352 | //gdouble freq = (gdouble) ((AUDIOFREQ / 2) * i + AUDIOFREQ / 4) / spect_bands; |
| 353 | mag = gst_value_list_get_value (magnitudes, i); |
| 354 | mag_value = pow (10.0, g_value_get_float (mag)/ 20.0); |
| 355 | float value = (mag_value - p->lastSpectrum[i]); |
| 356 | p->lastSpectrum[i] = mag_value; |
| 357 | flux += value < 0? 0: value; |
| 358 | //qDebug() << Q_FUNC_INFO <<"freq:"<<freq<<" flux:"<<flux; |
| 359 | } |
| 360 | //Spectral flux (comparing the power spectrum for one frame against the previous frame) |
| 361 | //for onset detection |
| 362 | p->spectralFlux.append( flux ); |
| 363 | |
| 364 | } |
| 365 | // data for Start and End time detection |
| 366 | if (strcmp (name, "cutter") == 0) { |
| 367 | |
| 368 | const GValue *value; |
| 369 | value=gst_structure_get_value (s, "above"); |
| 370 | bool isSilent=!g_value_get_boolean(value); |
| 371 | |
| 372 | //if we detect a falling edge, set EndPostion to this |
| 373 | if (isSilent) |
| 374 | m_EndPosition=QTime(0,0).addMSecs( static_cast<uint>( ( timestamp / GST_MSECOND ) )); // nanosec -> msec |
| 375 | else |
| 376 | { |
| 377 | //if this is the first rising edge, set StartPosition |
| 378 | if (m_StartPosition==QTime(0,0) && m_EndPosition==m_MaxPosition) |
| 379 | m_StartPosition=QTime(0,0).addMSecs( static_cast<uint>( ( timestamp / GST_MSECOND ) )); // nanosec -> msec |
| 380 | |
| 381 | //if we detect a rising edge, set EndPostion to track end |
| 382 | m_EndPosition=length(); |
| 383 | } |
| 384 | //qDebug() << Q_FUNC_INFO <<QTime(0,0).addMSecs( static_cast<uint>( ( timestamp / GST_MSECOND ) ))<< " silent:" << isSilent; |
| 385 | } |
| 386 | break; |
| 387 | } |
| 388 | |
| 389 | case GST_MESSAGE_TAG:{ |
| 390 | |
| 391 | GstTagList *tags = NULL; |
| 392 | gst_message_parse_tag (message, &tags); |
| 393 | if (gst_tag_list_get_double (tags, GST_TAG_TRACK_GAIN, &m_GainDB)) |
| 394 | { |
| 395 | qDebug() << Q_FUNC_INFO << ": Gain-db:" << m_GainDB; |
| 396 | qDebug() << Q_FUNC_INFO << ": Gain-norm:" << pow (10, m_GainDB / 20); |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | default: |
| 401 | break; |
| 402 | } |
| 403 | |
| 404 | } |
| 405 | |
| 406 | void TrackAnalyser::need_finish() |
| 407 | { |
| 408 | m_finished=true; |
| 409 | switch (p->analysisMode) |
| 410 | { |
| 411 | case TEMPO: |
| 412 | detectTempo(); |
| 413 | Q_EMIT finishTempo(); |
| 414 | break; |
| 415 | default: |
| 416 | Q_EMIT finishGain(); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | void TrackAnalyser::detectTempo() |
| 421 | { |
| 422 | int THRESHOLD_WINDOW_SIZE = 10; |
| 423 | float MULTIPLIER = 1.5f; |
| 424 | QList<float> prunedSpectralFlux; |
| 425 | QList<float> threshold; |
| 426 | QList<float> peaks; |
| 427 | |
| 428 | //calculate the running average for spectral flux. |
| 429 | for( int i = 0; i < p->spectralFlux.size(); i++ ) |
| 430 | { |
| 431 | int start = qMax( 0, i - THRESHOLD_WINDOW_SIZE ); |
| 432 | int end = qMin( p->spectralFlux.size() - 1, i + THRESHOLD_WINDOW_SIZE ); |
| 433 | float mean = 0; |
| 434 | for( int j = start; j <= end; j++ ) |
| 435 | mean += p->spectralFlux.at(j); |
| 436 | mean /= (end - start); |
| 437 | threshold.append( mean * MULTIPLIER ); |
| 438 | } |
| 439 | |
| 440 | //take only the signifikat onsets above threshold |
| 441 | for( int i = 0; i < threshold.size(); i++ ) |
| 442 | { |
| 443 | if( threshold.at(i) <= p->spectralFlux.at(i) ) |
| 444 | prunedSpectralFlux.append( p->spectralFlux.at(i) - threshold.at(i) ); |
| 445 | else |
| 446 | prunedSpectralFlux.append( (float)0 ); |
| 447 | } |
| 448 | |
| 449 | //peak detection |
| 450 | for( int i = 0; i < prunedSpectralFlux.size() - 1; i++ ) |
| 451 | { |
| 452 | if( prunedSpectralFlux.at(i) > prunedSpectralFlux.at(i+1) ) |
| 453 | peaks.append( prunedSpectralFlux.at(i) ); |
| 454 | else |
| 455 | peaks.append( (float)0 ); |
| 456 | } |
| 457 | |
| 458 | //use autocorrelation to retrieve time periode of peaks |
| 459 | float bpm = AutoCorrelation(peaks, peaks.count(), 60, 240, p->fft_res); |
| 460 | qDebug() << Q_FUNC_INFO << "autocorrelation bpm:"<<bpm; |
| 461 | |
| 462 | //tempo-harmonics issue |
| 463 | //if ( bpm < 72.0 ) { |
| 464 | // bpm *= 2; |
| 465 | // qDebug() << Q_FUNC_INFO << "guess bpm:"<<bpm; |
| 466 | //} //We dont care about tempo-harmonics issue -> music fits anyway -> factor: 2x or 0.5x |
| 467 | p->bpm = qRound(bpm); |
| 468 | } |
| 469 | |
| 470 | float TrackAnalyser::AutoCorrelation( QList<float> buffer, int frames, int minBpm, int maxBpm, int sampleRate) |
| 471 | { |
| 472 | |
| 473 | float maxCorr = 0; |
| 474 | int maxLag = 0; |
| 475 | float std_bpm = 120.0f; |
| 476 | float std_dev = 0.8f; |
| 477 | |
| 478 | int maxOffset = sampleRate * 60 / minBpm; |
| 479 | int minOffset = sampleRate * 60 / maxBpm; |
| 480 | if (frames > buffer.count()) frames=buffer.count(); |
| 481 | |
| 482 | for (int lag = minOffset; lag < maxOffset; lag++) |
| 483 | { |
| 484 | float corr = 0; |
| 485 | for (int i = 0; i < frames-lag; i++) |
| 486 | { |
| 487 | corr += (buffer.at(i+lag) * buffer.at(i)); |
| 488 | } |
| 489 | |
| 490 | //float bpm = sampleRate * 60.0 / lag; |
| 491 | |
| 492 | //calculate rating according then common bpm of 120 (log normal distribution) |
| 493 | //float rate = (float) qExp( -0.5 * qPow(( log( bpm / std_bpm ) / log(2) / std_dev),2.0)); |
| 494 | //corr = corr * rate; |
| 495 | //We dont care about tempo-harmonics issue -> music fits anyway -> factor: 2x or 0.5x |
| 496 | |
| 497 | if (corr > maxCorr) |
| 498 | { |
| 499 | //qDebug() << Q_FUNC_INFO << "corr: "<<corr<<" bpm:"<<bpm; |
| 500 | maxCorr = corr; |
| 501 | maxLag = lag; |
| 502 | } |
| 503 | |
| 504 | } |
| 505 | if (maxLag>0) |
| 506 | return sampleRate * 60.0 / maxLag; |
| 507 | else |
| 508 | return 0.0; |
| 509 | } |