Debian Codegraph @

src/player.cpp

raw symbols SCIP
1 /*
2 Copyright (C) 2005-2019 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 "player.h"
19
20 #include <QtGui>
21 #if QT_VERSION >= 0x050000
22 #include <QtConcurrent/QtConcurrent>
23 #else
24 #include <QtConcurrentRun>
25 #endif
26
27 void Player::sync_set_state(GstElement* element, GstState state)
28 {
29 GstStateChangeReturn res;
30 res = gst_element_set_state(GST_ELEMENT(element), state);
31 if (res == GST_STATE_CHANGE_FAILURE)
32 return;
33 if (res == GST_STATE_CHANGE_ASYNC) {
34 GstState state;
35 res = gst_element_get_state(GST_ELEMENT(element), &state, NULL, GST_CLOCK_TIME_NONE);
36 if (res == GST_STATE_CHANGE_FAILURE || res == GST_STATE_CHANGE_ASYNC)
37 return;
38 }
39 }
40
41 void cb_newpad(GstElement* src,
42 GstPad* new_pad,
43 gpointer data)
44 {
45 Player* instance = (Player*)data;
46 instance->newpad(src, new_pad, data);
47 }
48
49 void Player::newpad(GstElement* src,
50 GstPad* new_pad,
51 gpointer data)
52 {
53 Q_UNUSED(src);
54 Q_UNUSED(data);
55
56 GstCaps* caps;
57 GstStructure* str;
58 GstPad* sink_pad;
59
60 /* only link once */
61 GstElement* bin = gst_bin_get_by_name(GST_BIN(pipeline), "convert");
62 sink_pad = gst_element_get_static_pad(bin, "sink");
63 gst_object_unref(bin);
64
65 if (GST_PAD_IS_LINKED(sink_pad)) {
66 g_object_unref(sink_pad);
67 return;
68 }
69
70 /* check media type */
71 #ifdef GST_API_VERSION_1
72 caps = gst_pad_query_caps(new_pad, nullptr);
73 #else
74 caps = gst_pad_get_caps(new_pad);
75 #endif
76 str = gst_caps_get_structure(caps, 0);
77 if (!g_strrstr(gst_structure_get_name(str), "audio")) {
78 gst_caps_unref(caps);
79 gst_object_unref(sink_pad);
80 return;
81 }
82 gst_caps_unref(caps);
83
84 /* link'n'play */
85 gst_pad_link(new_pad, sink_pad);
86
87 qDebug() << Q_FUNC_INFO << " "
88 << "END";
89 }
90
91 struct PlayerPrivate {
92 QFutureWatcher<void> watcher;
93 QMutex mutex;
94 bool isStarted;
95 bool isLoaded;
96 QString error;
97 int length;
98 int position;
99 double volume;
100 double rms_l;
101 double rms_r;
102 double rmsout_l;
103 double rmsout_r;
104 };
105
106 Player::Player(QWidget* parent)
107 : QWidget(parent)
108 , p(new PlayerPrivate)
109 , pipeline(nullptr)
110 , bus(nullptr)
111 , Gstart(0)
112 , Glength(0)
113 {
114 p->isStarted = false;
115 p->isLoaded = false;
116
117 connect(&p->watcher, SIGNAL(finished()), this, SLOT(loadThreadFinished()));
118 }
119
120 Player::~Player()
121 {
122 cleanup();
123 delete p;
124 p = nullptr;
125 }
126
127 GstBusSyncReply Player::bus_cb(GstBus* bus, GstMessage* msg, gpointer data)
128 {
129 Q_UNUSED(bus);
130 Player* instance = (Player*)data;
131 instance->messageReceived(msg);
132 return GST_BUS_PASS;
133 }
134
135 void Player::cleanup()
136 {
137 if (pipeline)
138 sync_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
139 if (bus)
140 gst_object_unref(bus);
141 if (pipeline)
142 gst_object_unref(G_OBJECT(pipeline));
143 }
144
145 bool Player::prepare()
146 {
147 // Init Gst
148 qDebug() << Q_FUNC_INFO << " "
149 << "START";
150 QString caps_value;
151
152 // On mac we bundle the gstreamer plugins with knowthelist
153 #if defined(Q_OS_DARWIN)
154 QString scanner_path;
155 QString plugin_path;
156 QString registry_filename;
157
158 QDir pd(QCoreApplication::applicationDirPath() + "/../plugins");
159 scanner_path = QCoreApplication::applicationDirPath() + "/../plugins/gst-plugin-scanner";
160 plugin_path = QCoreApplication::applicationDirPath() + "/../plugins/gstreamer";
161 registry_filename = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QString("/gst-registry-%1-bin").arg(QCoreApplication::applicationVersion());
162
163 if (pd.exists())
164 setenv("GST_PLUGIN_SCANNER", scanner_path.toLocal8Bit().constData(), 1);
165
166 if (pd.exists()) {
167 setenv("GST_PLUGIN_PATH", plugin_path.toLocal8Bit().constData(), 1);
168 // Never load plugins from anywhere else.
169 setenv("GST_PLUGIN_SYSTEM_PATH", plugin_path.toLocal8Bit().constData(), 1);
170 }
171
172 if (!registry_filename.isEmpty()) {
173 setenv("GST_REGISTRY", registry_filename.toLocal8Bit().constData(), 1);
174 }
175 #elif defined(Q_OS_WIN32)
176 QString plugin_path = QCoreApplication::applicationDirPath() + "/plugins";
177 QDir pluginDir(plugin_path);
178 if (pluginDir.exists())
179 _putenv_s("GST_PLUGIN_PATH", plugin_path.toLocal8Bit());
180
181 #endif
182
183 //_putenv_s("GST_DEBUG", "*:4"); // win
184 //setenv("GST_DEBUG", "*:4", 1); // unix, mac
185
186 gst_init(nullptr, nullptr);
187
188 //prepare
189 GstElement *src, *conv, *resample, *sink, *gain, *vol, *level, *equalizer;
190 GstElement* levelout;
191 GstCaps* caps;
192 pipeline = gst_pipeline_new("pipeline");
193 bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
194
195 #ifdef GST_API_VERSION_1
196 caps_value = "audio/x-raw";
197 #else
198 caps_value = "audio/x-raw-int";
199 #endif
200 caps = gst_caps_new_simple(caps_value.toLatin1().data(),
201 "channels", G_TYPE_INT, 2, NULL);
202
203 src = gst_element_factory_make("uridecodebin", "source");
204 g_signal_connect(src, "pad-added", G_CALLBACK(cb_newpad), this);
205
206 conv = gst_element_factory_make("audioconvert", "convert");
207 resample = gst_element_factory_make("audioresample", "resample");
208 gain = gst_element_factory_make("audioamplify", "gain");
209 level = gst_element_factory_make("level", "levelintern");
210 vol = gst_element_factory_make("volume", "volume");
211 levelout = gst_element_factory_make("level", "levelout");
212 equalizer = gst_element_factory_make("equalizer-3bands", "equalizer");
213 sink = gst_element_factory_make("autoaudiosink", "sink");
214
215 g_object_set(level, "message", TRUE, NULL);
216 g_object_set(levelout, "message", TRUE, NULL);
217 g_object_set(level, "peak-ttl", 300000000000, NULL);
218
219 gst_bin_add_many(GST_BIN(pipeline), src, conv, resample, level, gain, equalizer, levelout, vol, sink, NULL);
220
221 gst_element_link(conv, resample);
222 gst_element_link_filtered(resample, level, caps);
223 gst_element_link(level, gain);
224 gst_element_link(gain, equalizer);
225 gst_element_link(equalizer, vol);
226 gst_element_link_filtered(vol, levelout, caps);
227 gst_element_link(levelout, sink);
228
229 #ifdef GST_API_VERSION_1
230 gst_bus_set_sync_handler(bus, bus_cb, this, nullptr);
231 #else
232 gst_bus_set_sync_handler(bus, bus_cb, this);
233 #endif
234
235 qDebug() << Q_FUNC_INFO << " "
236 << "END";
237
238 return pipeline;
239 }
240
241 bool Player::ready()
242 {
243 return pipeline;
244 }
245
246 void Player::setGain(double g)
247 {
248 gdouble gain_value = 1.00 * g;
249
250 GstElement* gain = gst_bin_get_by_name(GST_BIN(pipeline), "gain");
251 g_object_set(G_OBJECT(gain), "amplification", gain_value, NULL);
252 gst_object_unref(gain);
253 }
254
255 void Player::setEqualizer(QString band, double gain)
256 {
257 gdouble gain_value = 1.00 * gain;
258
259 GstElement* equalizer = gst_bin_get_by_name(GST_BIN(pipeline), "equalizer");
260 g_object_set(G_OBJECT(equalizer), band.toLatin1().data(), gain_value, NULL);
261 gst_object_unref(equalizer);
262 }
263
264 void Player::open(QUrl url)
265 {
266 //To avoid delays load track in another thread
267 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName() << " url=" << url;
268 QFuture<void> future = QtConcurrent::run(this, &Player::asyncOpen, url);
269 p->watcher.setFuture(future);
270 }
271
272 void Player::asyncOpen(QUrl url)
273 {
274 p->mutex.lock();
275 p->length = 0;
276 p->position = 0;
277 p->isLoaded = false;
278 p->error = "";
279 lastError = "";
280
281 sync_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
282
283 GstElement* src = gst_bin_get_by_name(GST_BIN(pipeline), "source");
284 g_object_set(G_OBJECT(src), "uri", (const char*)url.toString().toUtf8(), NULL);
285
286 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName();
287
288 sync_set_state(GST_ELEMENT(pipeline), GST_STATE_PAUSED);
289 setPosition(QTime(0, 0));
290
291 gst_object_unref(src);
292 p->mutex.unlock();
293 }
294
295 void Player::loadThreadFinished()
296 {
297 // async load in player done
298 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName();
299
300 p->isLoaded = true;
301 emit loadFinished();
302
303 if (p->isStarted) {
304 play();
305 }
306 }
307
308 void Player::play()
309 {
310 p->isStarted = true;
311 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName();
312 if (p->isLoaded) {
313 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName() << " call GST_STATE_PLAYING";
314 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
315 } else {
316 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName() << " is not loaded";
317 }
318 }
319 void Player::stop()
320 {
321 p->isStarted = false;
322 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_READY);
323 }
324
325 void Player::pause()
326 {
327 if (isPlaying()) {
328 p->isStarted = false;
329 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PAUSED);
330 }
331 }
332
333 bool Player::close()
334 {
335 gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
336 return true;
337 }
338
339 void Player::setPosition(QTime position)
340 {
341 int time_milliseconds = QTime(0, 0).msecsTo(position);
342 gint64 time_nanoseconds = (time_milliseconds * GST_MSECOND);
343 gst_element_seek(pipeline, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
344 GST_SEEK_TYPE_SET, time_nanoseconds,
345 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
346 p->position = time_milliseconds;
347 emit positionChanged();
348 }
349
350 QTime Player::position()
351 {
352 if (pipeline) {
353
354 gint64 value = 0;
355
356 #ifdef GST_API_VERSION_1
357 if (gst_element_query_position(pipeline, GST_FORMAT_TIME, &value)) {
358 #else
359 GstFormat fmt = GST_FORMAT_TIME;
360 if (gst_element_query_position(pipeline, &fmt, &value)) {
361 #endif
362 p->position = static_cast<int>((value / GST_MSECOND));
363 return QTime(0, 0).addMSecs(p->position); // nanosec -> msec
364 }
365 return QTime(0, 0).addMSecs(p->position); // nanosec -> msec
366 }
367 return QTime(0, 0);
368 }
369
370 QTime Player::length()
371 {
372 gint64 value = 0;
373
374 if (p->length == 0 && pipeline) {
375
376 #ifdef GST_API_VERSION_1
377 if (gst_element_query_duration(pipeline, GST_FORMAT_TIME, &value)) {
378 #else
379 GstFormat fmt = GST_FORMAT_TIME;
380 if (gst_element_query_duration(pipeline, &fmt, &value)) {
381 #endif
382 p->length = static_cast<int>((value / GST_MSECOND));
383 } else
384 qDebug() << Q_FUNC_INFO << ": Can not get duration";
385 }
386 return QTime(0, 0).addMSecs(p->length); // nanosec -> msec
387 }
388
389 double Player::volume()
390 {
391 gdouble vol = 0;
392
393 GstElement* volume = gst_bin_get_by_name(GST_BIN(pipeline), "volume");
394 g_object_get(G_OBJECT(volume), "volume", &vol, nullptr);
395 gst_object_unref(volume);
396
397 return static_cast<double>(vol);
398 }
399
400 void Player::setVolume(double v)
401 {
402 gdouble vol = static_cast<gdouble>(v);
403 if (vol < 0.001) {
404 vol = 0.001;
405 }
406
407 GstElement* volume = gst_bin_get_by_name(GST_BIN(pipeline), "volume");
408 g_object_set(G_OBJECT(volume), "volume", vol, nullptr);
409 gst_object_unref(volume);
410 }
411
412 bool Player::mediaPlayable()
413 {
414 GstState st;
415 gst_element_get_state(GST_ELEMENT(pipeline), &st, nullptr, 0);
416 //qDebug()<<gst_element_state_get_name(st);
417 return (st != GST_STATE_NULL);
418 }
419
420 bool Player::isPlaying()
421 {
422 GstState st;
423 gst_element_get_state(GST_ELEMENT(pipeline), &st, nullptr, 0);
424 return (st == GST_STATE_PLAYING);
425 }
426
427 double Player::levelLeft() { return p->rms_l; }
428 double Player::levelRight() { return p->rms_r; }
429 double Player::levelOutLeft() { return p->rmsout_l; }
430 double Player::levelOutRight() { return p->rmsout_r; }
431
432 void Player::messageReceived(GstMessage* message)
433 {
434
435 switch (GST_MESSAGE_TYPE(message)) {
436 case GST_STATE_CHANGE_FAILURE: {
437 qDebug() << Q_FUNC_INFO << ": Gstreamer error:" << p->error;
438 }
439 case GST_MESSAGE_ERROR: {
440 if (p->error == "") {
441 GError* err;
442 gchar* debug;
443 gst_message_parse_error(message, &err, &debug);
444 p->error = "Error #" + QString::number(err->code) + " in module " + QString::number(err->domain) + "\n" + QString::fromUtf8(err->message);
445 if (err->domain != GST_STREAM_ERROR && err->code != GST_STREAM_ERROR_FAILED) {
446 p->error += "\nMay be you should install more of gstreamer plugins";
447 lastError = QString::fromUtf8(err->message);
448 }
449 qDebug() << Q_FUNC_INFO << ": Gstreamer error:" << p->error;
450 g_error_free(err);
451 g_free(debug);
452 Q_EMIT error();
453 }
454 break;
455 }
456 case GST_MESSAGE_EOS: {
457 qDebug() << Q_FUNC_INFO << ":" << parentWidget()->objectName() << " End of track reached";
458 Q_EMIT finish();
459 break;
460 }
461 case GST_MESSAGE_STATE_CHANGED: {
462 GstState old_state, new_state;
463 gst_message_parse_state_changed(message, &old_state, &new_state, nullptr);
464 switch (new_state) {
465 case GST_STATE_PAUSED:
466 case GST_STATE_NULL:
467 p->rms_l = p->rms_r = 0;
468 p->rmsout_l = p->rmsout_r = 0;
469 default:
470 break;
471 }
472 break;
473 }
474
475 case GST_MESSAGE_ELEMENT: {
476 const GstStructure* s = gst_message_get_structure(message);
477 const gchar* src_name = GST_MESSAGE_SRC_NAME(message);
478
479 if (strcmp(src_name, "levelintern") == 0) {
480 gint channels;
481 gdouble peak_dB;
482 gdouble rms;
483 gint i;
484
485 #ifdef GST_API_VERSION_1
486 const GValue* array_val;
487 GValueArray* peak_arr;
488
489 array_val = gst_structure_get_value(s, "peak");
490 peak_arr = (GValueArray*)g_value_get_boxed(array_val);
491 channels = peak_arr->n_values;
492
493 for (i = 0; i < channels; ++i) {
494 peak_dB = g_value_get_double(peak_arr->values + i);
495 #else
496 const GValue* list;
497 const GValue* value;
498
499 list = gst_structure_get_value(s, "peak");
500 channels = gst_value_list_get_size(list);
501
502 for (i = 0; i < channels; ++i) {
503 list = gst_structure_get_value(s, "peak");
504 value = gst_value_list_get_value(list, i);
505 peak_dB = g_value_get_double(value);
506 #endif
507 /* converting from dB to normal gives us a value between 0.0 and 1.0 */
508 rms = pow(10, peak_dB / 20);
509 if (i == 0)
510 p->rms_l = rms;
511 else
512 p->rms_r = rms;
513 }
514 }
515 if (strcmp(src_name, "levelout") == 0) {
516 gint channels;
517 gdouble peak_dB;
518 gdouble rms;
519 gint i;
520
521 #ifdef GST_API_VERSION_1
522 const GValue* array_val;
523 GValueArray* peak_arr;
524
525 array_val = gst_structure_get_value(s, "peak");
526 peak_arr = (GValueArray*)g_value_get_boxed(array_val);
527 channels = peak_arr->n_values;
528
529 for (i = 0; i < channels; ++i) {
530 peak_dB = g_value_get_double(peak_arr->values + i);
531 #else
532 const GValue* list;
533 const GValue* value;
534
535 list = gst_structure_get_value(s, "peak");
536 channels = gst_value_list_get_size(list);
537
538 for (i = 0; i < channels; ++i) {
539 list = gst_structure_get_value(s, "peak");
540 value = gst_value_list_get_value(list, i);
541 peak_dB = g_value_get_double(value);
542 #endif
543
544 /* converting from dB to normal gives us a value between 0.0 and 1.0 */
545 rms = pow(10, peak_dB / 20);
546 if (i == 0)
547 p->rmsout_l = rms;
548 else
549 p->rmsout_r = rms;
550 }
551 }
552 } break;
553 default:
554 break;
555 }
556 }