Debian Codegraph @

src/monitorplayer.cpp

raw symbols SCIP
1 /*
2 Copyright (C) 2005-2019 Mario Stephan <[email protected]>
3 This library is free software; you can redistribute it and/or modify
4 it under the terms of the GNU Lesser General Public License as published
5 by the Free Software Foundation; either version 2.1 of the License, or
6 (at your option) any later version.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 GNU General Public License for more details.
11 You should have received a copy of the GNU Lesser General Public License
12 along with this program. If not, see <http://www.gnu.org/licenses/>.
13 */
14
15 #include <QtGui>
16 #if QT_VERSION >= 0x050000
17 #include <QtConcurrent/QtConcurrent>
18 #else
19 #include <QtConcurrentRun>
20 #endif
21
22 #if defined(Q_OS_DARWIN)
23 #include <CoreAudio/AudioHardware.h>
24 #include <CoreAudio/CoreAudio.h>
25 #elif defined(Q_OS_WIN32)
26 #include <dsound.h>
27 #elif defined(Q_OS_UNIX)
28 #include <alsa/asoundlib.h>
29 #endif
30
31 #include "monitorplayer.h"
32
33 void MonitorPlayer::sync_set_state(GstElement* element, GstState state)
34 {
35 GstStateChangeReturn res;
36 res = gst_element_set_state(GST_ELEMENT(element), state);
37 if (res == GST_STATE_CHANGE_FAILURE)
38 return;
39 if (res == GST_STATE_CHANGE_ASYNC) {
40 GstState state;
41 res = gst_element_get_state(GST_ELEMENT(element), &state, NULL, 1000000000 /*GST_CLOCK_TIME_NONE*/);
42 if (res == GST_STATE_CHANGE_FAILURE || res == GST_STATE_CHANGE_ASYNC)
43 return;
44 }
45 }
46
47 void cb_newpad_mp(GstElement* src,
48 GstPad* new_pad,
49 gpointer data)
50 {
51 MonitorPlayer* instance = (MonitorPlayer*)data;
52 instance->newpad(src, new_pad, data);
53 }
54
55 void MonitorPlayer::newpad(GstElement* src,
56 GstPad* new_pad,
57 gpointer data)
58 {
59 GstCaps* caps;
60 GstStructure* str;
61 GstPad* sink_pad;
62
63 /* only link once */
64 GstElement* bin = gst_bin_get_by_name(GST_BIN(pipeline), "convert");
65 sink_pad = gst_element_get_static_pad(bin, "sink");
66
67 gst_object_unref(bin);
68
69 if (GST_PAD_IS_LINKED(sink_pad)) {
70 g_object_unref(sink_pad);
71 return;
72 }
73
74 /* check media type */
75 #ifdef GST_API_VERSION_1
76 caps = gst_pad_query_caps(new_pad, nullptr);
77 #else
78 caps = gst_pad_get_caps(new_pad);
79 #endif
80 str = gst_caps_get_structure(caps, 0);
81 if (!g_strrstr(gst_structure_get_name(str), "audio")) {
82 gst_caps_unref(caps);
83 gst_object_unref(sink_pad);
84 return;
85 }
86 gst_caps_unref(caps);
87
88 /* link'n'play */
89 gst_pad_link(new_pad, sink_pad);
90 }
91
92 struct MonitorPlayerPrivate {
93 QFutureWatcher<void> watcher;
94 QMutex mutex;
95 bool isStarted;
96 bool isLoaded;
97 bool isDisabled;
98 QString error;
99 QString deviceName;
100 QString deviceID;
101 QMap<QString, QString> devices;
102 uint length;
103 uint position;
104 dsDevice dev;
105 double rms_l;
106 double rms_r;
107 };
108
109 MonitorPlayer::MonitorPlayer(QWidget* parent)
110 : QWidget(parent)
111 , p(new MonitorPlayerPrivate)
112 , pipeline(nullptr)
113 , bus(nullptr)
114 , Gstart(0)
115 , Glength(0)
116 {
117 p->isStarted = false;
118 p->isLoaded = false;
119 readDevices();
120 p->deviceID = defaultDeviceID();
121
122 connect(&p->watcher, SIGNAL(finished()), this, SLOT(loadThreadFinished()));
123 }
124
125 MonitorPlayer::~MonitorPlayer()
126 {
127 cleanup();
128 delete p;
129 p = nullptr;
130 }
131
132 GstBusSyncReply MonitorPlayer::bus_cb(GstBus* bus, GstMessage* msg, gpointer data)
133 {
134 Q_UNUSED(bus);
135
136 MonitorPlayer* instance = (MonitorPlayer*)data;
137 instance->messageReceived(msg);
138 return GST_BUS_PASS;
139 }
140
141 void MonitorPlayer::cleanup()
142 {
143 if (pipeline)
144 sync_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
145 if (bus)
146 gst_object_unref(bus);
147 if (pipeline)
148 gst_object_unref(G_OBJECT(pipeline));
149 }
150
151 bool MonitorPlayer::prepare()
152 {
153 // Init Gst
154 qDebug() << Q_FUNC_INFO << " "
155 << "START";
156 QString caps_value;
157
158 gst_init(nullptr, nullptr);
159
160 //prepare
161 GstElement *src, *conv, *resample, *sink, *level, *vol;
162 GstCaps* caps;
163 pipeline = gst_pipeline_new("pipeline");
164 bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
165 src = gst_element_factory_make("uridecodebin", "source");
166
167 #ifdef GST_API_VERSION_1
168 caps_value = "audio/x-raw";
169 #else
170 caps_value = "audio/x-raw-int";
171 #endif
172 caps = gst_caps_new_simple(caps_value.toLatin1().data(),
173 "channels", G_TYPE_INT, 2, NULL);
174 g_signal_connect(src, "pad-added", G_CALLBACK(cb_newpad_mp), this);
175
176 conv = gst_element_factory_make("audioconvert", "convert");
177 vol = gst_element_factory_make("volume", "volume");
178 resample = gst_element_factory_make("audioresample", "resample");
179 level = gst_element_factory_make("level", "level");
180
181 #if defined(Q_OS_DARWIN)
182 sink = gst_element_factory_make("osxaudiosink", "sink");
183 g_object_set(sink, "device", 0, NULL);
184 //g_object_set (sink, "volume", 9.5, NULL);
185 #elif defined(Q_OS_WIN32)
186 sink = gst_element_factory_make("directsoundsink", "sink");
187 g_object_set(sink, "device", NULL, NULL);
188 //g_object_set (sink, "volume", 99.5, NULL);
189 #elif defined(Q_OS_UNIX)
190 sink = gst_element_factory_make("alsasink", "sink");
191 g_object_set(sink, "device", "default", NULL);
192 //g_object_set (sink, "volume", 0.5, NULL);
193 #else
194 sink = gst_element_factory_make("fakesink", "sink");
195 g_object_set(sink, "device", NULL, NULL);
196 #endif
197
198 gst_bin_add_many(GST_BIN(pipeline), src, conv, resample, level, vol, sink, NULL);
199 gst_element_link(conv, resample);
200 gst_element_link_filtered(resample, level, caps);
201 gst_element_link(level, vol);
202 gst_element_link(vol, sink);
203
204 gst_element_set_state(src, GST_STATE_NULL);
205
206 #ifdef GST_API_VERSION_1
207 gst_bus_set_sync_handler(bus, bus_cb, this, nullptr);
208 #else
209 gst_bus_set_sync_handler(bus, bus_cb, this);
210 #endif
211
212 qDebug() << Q_FUNC_INFO << " "
213 << "END";
214
215 return pipeline;
216 }
217
218 bool MonitorPlayer::ready()
219 {
220 return pipeline;
221 }
222
223 void MonitorPlayer::open(QUrl url)
224 {
225 if (p->isDisabled) {
226 return;
227 }
228 // To avoid delays, load track in another thread
229 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName() << " url=" << url;
230 QFuture<void> future = QtConcurrent::run(this, &MonitorPlayer::asyncOpen, url);
231 p->watcher.setFuture(future);
232 }
233
234 void MonitorPlayer::asyncOpen(QUrl url)
235 {
236 p->mutex.lock();
237 p->length = 0;
238 p->isLoaded = false;
239 p->error = "";
240
241 sync_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
242
243 GstElement* src = gst_bin_get_by_name(GST_BIN(pipeline), "source");
244 g_object_set(G_OBJECT(src), "uri", (const char*)url.toString().toUtf8(), NULL);
245
246 sync_set_state(GST_ELEMENT(pipeline), GST_STATE_PAUSED);
247 setPosition(QTime(0, 0));
248
249 gst_object_unref(src);
250 p->mutex.unlock();
251 }
252
253 void MonitorPlayer::loadThreadFinished()
254 {
255 // async load in MonitorPlayerGst done
256 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName();
257 p->isLoaded = true;
258 if (p->isStarted) {
259 play();
260 }
261 emit loadFinished();
262 }
263
264 void MonitorPlayer::play()
265 {
266
267 p->isStarted = true;
268 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName();
269 if (p->isLoaded) {
270 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
271 }
272 }
273
274 void MonitorPlayer::stop()
275 {
276 p->isStarted = false;
277 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_READY);
278 }
279
280 void MonitorPlayer::pause()
281 {
282 if (isPlaying()) {
283 p->isStarted = false;
284 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PAUSED);
285 }
286 }
287
288 bool MonitorPlayer::close()
289 {
290 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
291 return true;
292 }
293
294 void MonitorPlayer::setPosition(QTime position)
295 {
296 int time_milliseconds = QTime(0, 0).msecsTo(position);
297 gint64 time_nanoseconds = (time_milliseconds * GST_MSECOND);
298 gst_element_seek(pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
299 GST_SEEK_TYPE_SET, time_nanoseconds,
300 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
301 p->position = time_milliseconds;
302 emit positionChanged();
303 }
304
305 QTime MonitorPlayer::position()
306 {
307 if (pipeline) {
308
309 gint64 value = 0;
310
311 #ifdef GST_API_VERSION_1
312 if (gst_element_query_position(pipeline, GST_FORMAT_TIME, &value)) {
313 #else
314 GstFormat fmt = GST_FORMAT_TIME;
315 if (gst_element_query_position(pipeline, &fmt, &value)) {
316 #endif
317 p->position = static_cast<uint>((value / GST_MSECOND));
318 return QTime(0, 0).addMSecs(p->position); // nanosec -> msec
319 }
320 return QTime(0, 0).addMSecs(p->position); // nanosec -> msec
321 }
322 return QTime(0, 0);
323 }
324
325 QTime MonitorPlayer::length()
326 {
327 gint64 value = 0;
328
329 if (p->length == 0 && pipeline) {
330
331 #ifdef GST_API_VERSION_1
332 if (gst_element_query_duration(pipeline, GST_FORMAT_TIME, &value)) {
333 #else
334 GstFormat fmt = GST_FORMAT_TIME;
335 if (gst_element_query_duration(pipeline, &fmt, &value)) {
336 #endif
337 p->length = static_cast<uint>((value / GST_MSECOND));
338 }
339 }
340 return QTime(0, 0).addMSecs(p->length); // nanosec -> msec
341 }
342
343 double MonitorPlayer::volume()
344 {
345 gdouble vol = 0;
346
347 GstElement* volume = gst_bin_get_by_name(GST_BIN(pipeline), "volume");
348 g_object_get(G_OBJECT(volume), "volume", &vol, NULL);
349 gst_object_unref(volume);
350
351 return vol;
352 }
353
354 void MonitorPlayer::setVolume(double v)
355 {
356 gdouble vol = 1.00 * v;
357 GstElement* volume = gst_bin_get_by_name(GST_BIN(pipeline), "volume");
358 g_object_set(G_OBJECT(volume), "volume", vol, NULL);
359 gst_object_unref(volume);
360 }
361
362 void MonitorPlayer::disable()
363 {
364 p->isDisabled = true;
365 }
366
367 void MonitorPlayer::enable()
368 {
369 p->isDisabled = false;
370 }
371
372 bool MonitorPlayer::isDisabled()
373 {
374 return p->isDisabled;
375 }
376
377 double MonitorPlayer::levelLeft()
378 {
379 return p->rms_l;
380 }
381
382 double MonitorPlayer::levelRight()
383 {
384 return p->rms_r;
385 }
386
387 bool MonitorPlayer::mediaPlayable()
388 {
389 GstState st;
390 gst_element_get_state(GST_ELEMENT(pipeline), &st, 0, 0);
391 //qDebug()<<gst_element_state_get_name(st);
392 return (st != GST_STATE_NULL);
393 }
394
395 bool MonitorPlayer::isPlaying()
396 {
397 GstState st;
398 gst_element_get_state(GST_ELEMENT(pipeline), &st, 0, 0);
399 return (st == GST_STATE_PLAYING);
400 }
401
402 QStringList MonitorPlayer::outputDevices()
403 {
404 QStringList outList;
405 QMapIterator<QString, QString> i(p->devices);
406 while (i.hasNext()) {
407 i.next();
408 outList << i.value();
409 }
410
411 return outList;
412 }
413
414 QString MonitorPlayer::outputDeviceName()
415 {
416 return p->deviceName;
417 }
418
419 QString MonitorPlayer::outputDeviceID()
420 {
421 return p->deviceID;
422 }
423
424 void MonitorPlayer::setOutputDevice(QString deviceName)
425 {
426 // for Mac device is DeviceID
427 QMapIterator<QString, QString> i(p->devices);
428 while (i.hasNext()) {
429 i.next();
430 if (i.value() == deviceName) {
431 p->deviceID = i.key();
432 p->deviceName = i.value();
433 }
434 }
435
436 qDebug() << "Monitor setDevice to DeviceID:" << p->deviceID << " DevicenName:" << p->deviceName;
437
438 GstElement* sink = gst_bin_get_by_name(GST_BIN(pipeline), "sink");
439 #if defined(Q_OS_WIN32)
440 g_object_set(sink, "device", p->deviceID.toLatin1().data(), NULL);
441 #elif defined(Q_OS_DARWIN)
442 g_object_set(sink, "device", p->deviceID.toInt(), NULL);
443 #elif defined(Q_OS_UNIX)
444 g_object_set(sink, "device", QString("hw:%1").arg(p->deviceID).toLatin1().data(), NULL);
445 #endif
446 gst_object_unref(sink);
447 }
448
449 #if defined(Q_OS_WIN32)
450 BOOL CALLBACK DSEnumProc(LPGUID lpGUID, const WCHAR* lpszDesc,
451 const WCHAR* lpszDrvName, void* ctx)
452 {
453 if (lpGUID) {
454 QList<dsDevice>* l = reinterpret_cast<QList<dsDevice>*>(ctx);
455 *l << dsDevice(QString::fromUtf16(reinterpret_cast<const ushort*>(lpszDesc)), QUuid(*lpGUID));
456 }
457
458 return (true);
459 }
460 #endif
461
462 QString MonitorPlayer::defaultDeviceID()
463 {
464 #if defined(Q_OS_WIN32)
465 GUID guid;
466 //DSDEVID_DefaultVoicePlayback="{DEF00000-9C6D-47ED-AAF1-4DDA8F2B5C03}"
467 const GUID defaultguid = QUuid("{DEF00000-9C6D-47ED-AAF1-4DDA8F2B5C03}");
468 if (GetDeviceID(&defaultguid, &guid) == DS_OK) {
469 return QUuid(guid).toString();
470 } else
471 return QString();
472 #elif defined(Q_OS_DARWIN)
473 return QString("0");
474 #elif defined(Q_OS_UNIX)
475 return QString("0");
476 #endif
477 }
478
479 void MonitorPlayer::readDevices()
480 {
481 #if defined(Q_OS_WIN32)
482 p->devices.clear();
483 QList<dsDevice> qlOutput;
484
485 DirectSoundEnumerate(DSEnumProc, reinterpret_cast<void*>(&qlOutput));
486
487 foreach (dev, qlOutput) {
488 p->devices.insert(dev.second.toString(), dev.first);
489 }
490
491 #elif defined(Q_OS_DARWIN)
492 UInt32 dataSize = 0;
493 AudioObjectPropertyAddress propertyAddress;
494 propertyAddress.mSelector = kAudioHardwarePropertyDevices;
495 propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
496 propertyAddress.mElement = kAudioObjectPropertyElementMaster;
497
498 OSStatus status = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize);
499 if (kAudioHardwareNoError != status) {
500 qDebug() << "Unable to get number of audio devices. Error: " << status;
501 }
502
503 UInt32 deviceCount = dataSize / sizeof(AudioDeviceID);
504
505 AudioDeviceID* audioDevices = (AudioDeviceID*)malloc(dataSize);
506
507 status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize, audioDevices);
508 if (kAudioHardwareNoError != status) {
509 qDebug() << "AudioObjectGetPropertyData failed when getting device IDs. Error:" << status;
510 free(audioDevices), audioDevices = NULL;
511 return;
512 }
513
514 p->devices.clear();
515
516 for (UInt32 i = 0; i < deviceCount; i++) {
517 CFStringRef deviceName = NULL;
518 propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; // probe for Inputstream
519 if (AudioObjectGetPropertyData(audioDevices[i], &propertyAddress, 0, NULL, &dataSize, &deviceName) != noErr) {
520 dataSize = sizeof(deviceName);
521 propertyAddress.mSelector = kAudioDevicePropertyDeviceNameCFString;
522 propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
523
524 status = AudioObjectGetPropertyData(audioDevices[i], &propertyAddress, 0, NULL, &dataSize, &deviceName);
525 QString devName = CFStringGetCStringPtr(deviceName, CFStringGetSystemEncoding());
526 p->devices.insert(QString::number(audioDevices[i]), devName.trimmed());
527 }
528 }
529
530 free(audioDevices);
531 #elif defined(Q_OS_UNIX)
532 int idx = 0;
533 char* name;
534
535 while (snd_card_get_name(idx, &name) == 0) {
536 p->devices.insert(QString::number(idx), QString(name));
537 idx++;
538 }
539 #endif
540 }
541
542 void MonitorPlayer::messageReceived(GstMessage* message)
543 {
544
545 switch (GST_MESSAGE_TYPE(message)) {
546 case GST_MESSAGE_ERROR: {
547 if (p->error == "") {
548 GError* err;
549 gchar* debug;
550 gst_message_parse_error(message, &err, &debug);
551 p->error = "Error #" + QString::number(err->code) + " in module " + QString::number(err->domain) + "\n" + QString::fromUtf8(err->message);
552 if (err->code == 6 && err->domain == 851) {
553 p->error += "\nMay be you should to install gstreamerX.XX-plugins-ugly or gstreamerX.XX-plugins-bad";
554 }
555 qDebug() << "Gstreamer error:" << p->error;
556 g_error_free(err);
557 g_free(debug);
558 Q_EMIT error();
559 }
560 break;
561 }
562 case GST_MESSAGE_EOS: {
563 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName() << " End of track reached";
564 Q_EMIT finish();
565 break;
566 }
567 case GST_MESSAGE_STATE_CHANGED: {
568 GstState old_state, new_state;
569 gst_message_parse_state_changed(message, &old_state, &new_state, NULL);
570 switch (new_state) {
571 case GST_STATE_PAUSED:
572 case GST_STATE_NULL:
573 p->rms_l = p->rms_r = 0;
574 default:
575 break;
576 }
577 break;
578 }
579
580 case GST_MESSAGE_ELEMENT: {
581 const GstStructure* s = gst_message_get_structure(message);
582 const gchar* src_name = GST_MESSAGE_SRC_NAME(message);
583
584 if (strcmp(src_name, "level") == 0) {
585 gint channels;
586 gdouble peak_dB;
587 gdouble rms;
588 gint i;
589
590 #ifdef GST_API_VERSION_1
591 const GValue* array_val;
592 GValueArray* peak_arr;
593
594 array_val = gst_structure_get_value(s, "peak");
595 peak_arr = (GValueArray*)g_value_get_boxed(array_val);
596 channels = peak_arr->n_values;
597
598 for (i = 0; i < channels; ++i) {
599 peak_dB = g_value_get_double(peak_arr->values + i);
600 #else
601 const GValue* list;
602 const GValue* value;
603
604 list = gst_structure_get_value(s, "peak");
605 channels = gst_value_list_get_size(list);
606
607 for (i = 0; i < channels; ++i) {
608 list = gst_structure_get_value(s, "peak");
609 value = gst_value_list_get_value(list, i);
610 peak_dB = g_value_get_double(value);
611 #endif
612 /* converting from dB to normal gives us a value between 0.0 and 1.0 */
613 rms = pow(10, peak_dB / 20);
614 if (i == 0)
615 p->rms_l = rms;
616 else
617 p->rms_r = rms;
618 }
619 }
620
621 } break;
622 default:
623 break;
624 }
625 }