-
Notifications
You must be signed in to change notification settings - Fork 3
/
mpvdeclarativeobject.cpp
1266 lines (1128 loc) · 41.6 KB
/
mpvdeclarativeobject.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "mpvdeclarativeobject.h"
#include <QDebug>
#include <QOpenGLContext>
#include <QOpenGLFramebufferObject>
#include <QQuickWindow>
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
#include <QX11Info>
#include <QGuiApplication>
#endif
namespace {
void wakeup(void *ctx) {
// This callback is invoked from any mpv thread (but possibly also
// recursively from a thread that is calling the mpv API). Just notify
// the Qt GUI thread to wake up (so that it can process events with
// mpv_wait_event()), and return as quickly as possible.
QMetaObject::invokeMethod(static_cast<MpvDeclarativeObject *>(ctx),
"hasMpvEvents", Qt::QueuedConnection);
}
void on_mpv_redraw(void *ctx) { MpvDeclarativeObject::on_update(ctx); }
void *get_proc_address_mpv(void *ctx, const char *name) {
Q_UNUSED(ctx)
QOpenGLContext *glctx = QOpenGLContext::currentContext();
if (glctx == nullptr) {
return nullptr;
}
return reinterpret_cast<void *>(glctx->getProcAddress(QByteArray(name)));
}
} // namespace
class MpvRenderer : public QQuickFramebufferObject::Renderer {
Q_DISABLE_COPY_MOVE(MpvRenderer)
public:
MpvRenderer(MpvDeclarativeObject *mpvDeclarativeObject)
: m_mpvDeclarativeObject(mpvDeclarativeObject) {
Q_ASSERT(m_mpvDeclarativeObject != nullptr);
}
~MpvRenderer() override = default;
// This function is called when a new FBO is needed.
// This happens on the initial frame.
QOpenGLFramebufferObject *
createFramebufferObject(const QSize &size) override {
// init mpv_gl:
if (m_mpvDeclarativeObject->mpv_gl == nullptr) {
mpv_opengl_init_params gl_init_params{get_proc_address_mpv, nullptr,
nullptr};
mpv_render_param params[]{
{MPV_RENDER_PARAM_API_TYPE,
const_cast<char *>(MPV_RENDER_API_TYPE_OPENGL)},
{MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params},
{MPV_RENDER_PARAM_INVALID, nullptr},
{MPV_RENDER_PARAM_INVALID, nullptr}};
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
if (QGuiApplication::platformName().contains("xcb")) {
params[2].type = MPV_RENDER_PARAM_X11_DISPLAY;
params[2].data = QX11Info::display();
}
#endif
const int mpvGLInitResult =
mpv_render_context_create(&m_mpvDeclarativeObject->mpv_gl,
m_mpvDeclarativeObject->mpv, params);
Q_ASSERT(mpvGLInitResult >= 0);
mpv_render_context_set_update_callback(
m_mpvDeclarativeObject->mpv_gl, on_mpv_redraw,
m_mpvDeclarativeObject);
QMetaObject::invokeMethod(m_mpvDeclarativeObject, "initFinished");
}
return QQuickFramebufferObject::Renderer::createFramebufferObject(size);
}
void render() override {
m_mpvDeclarativeObject->window()->resetOpenGLState();
QOpenGLFramebufferObject *fbo = framebufferObject();
mpv_opengl_fbo mpfbo{0, 0, 0, 0};
mpfbo.fbo = static_cast<int>(fbo->handle());
mpfbo.w = fbo->width();
mpfbo.h = fbo->height();
int flip_y{0};
mpv_render_param params[] = {
// Specify the default framebuffer (0) as target. This will
// render onto the entire screen. If you want to show the video
// in a smaller rectangle or apply fancy transformations, you'll
// need to render into a separate FBO and draw it manually.
{MPV_RENDER_PARAM_OPENGL_FBO, &mpfbo},
// Flip rendering (needed due to flipped GL coordinate system).
{MPV_RENDER_PARAM_FLIP_Y, &flip_y},
{MPV_RENDER_PARAM_INVALID, nullptr}};
// See render_gl.h on what OpenGL environment mpv expects, and
// other API details.
mpv_render_context_render(m_mpvDeclarativeObject->mpv_gl, params);
m_mpvDeclarativeObject->window()->resetOpenGLState();
}
private:
MpvDeclarativeObject *m_mpvDeclarativeObject = nullptr;
};
MpvDeclarativeObject::MpvDeclarativeObject(QQuickItem *parent)
: QQuickFramebufferObject(parent),
mpv(mpv::qt::Handle::FromRawHandle(mpv_create())) {
Q_ASSERT(mpv != nullptr);
mpvSetProperty(QLatin1String("input-default-bindings"), false);
mpvSetProperty(QLatin1String("input-vo-keyboard"), false);
mpvSetProperty(QLatin1String("input-cursor"), false);
mpvSetProperty(QLatin1String("cursor-autohide"), false);
auto iterator = properties.constBegin();
while (iterator != properties.constEnd()) {
mpvObserveProperty(QLatin1String(iterator.key()));
++iterator;
}
// From this point on, the wakeup function will be called. The callback
// can come from any thread, so we use the QueuedConnection mechanism to
// relay the wakeup in a thread-safe way.
connect(this, &MpvDeclarativeObject::hasMpvEvents, this,
&MpvDeclarativeObject::handleMpvEvents, Qt::QueuedConnection);
mpv_set_wakeup_callback(mpv, wakeup, this);
const int mpvInitResult = mpv_initialize(mpv);
Q_ASSERT(mpvInitResult >= 0);
connect(this, &MpvDeclarativeObject::onUpdate, this,
&MpvDeclarativeObject::doUpdate, Qt::QueuedConnection);
}
MpvDeclarativeObject::~MpvDeclarativeObject() {
// only initialized if something got drawn
if (mpv_gl != nullptr) {
mpv_render_context_free(mpv_gl);
}
// We don't need to destroy mpv handle in our own because we are using
// mpv::qt::Handle, which is a shared pointer.
// mpv_terminate_destroy(mpv);
}
void MpvDeclarativeObject::on_update(void *ctx) {
Q_EMIT static_cast<MpvDeclarativeObject *>(ctx)->onUpdate();
}
// connected to onUpdate() signal makes sure it runs on the GUI thread
void MpvDeclarativeObject::doUpdate() { update(); }
void MpvDeclarativeObject::processMpvLogMessage(mpv_event_log_message *event) {
const QString logMessage =
QStringLiteral("[libmpv] %1: %2")
.arg(QString::fromUtf8(event->prefix),
QString::fromUtf8(event->text).trimmed());
switch (event->log_level) {
case MPV_LOG_LEVEL_V:
case MPV_LOG_LEVEL_DEBUG:
case MPV_LOG_LEVEL_TRACE:
qDebug().noquote() << logMessage;
break;
case MPV_LOG_LEVEL_WARN:
qWarning().noquote() << logMessage;
break;
case MPV_LOG_LEVEL_ERROR:
qCritical().noquote() << logMessage;
break;
case MPV_LOG_LEVEL_FATAL:
// qFatal() doesn't support the "<<" operator.
qFatal("%ls", qUtf16Printable(logMessage));
break;
case MPV_LOG_LEVEL_INFO:
qInfo().noquote() << logMessage;
break;
default:
qDebug().noquote() << logMessage;
break;
}
}
void MpvDeclarativeObject::processMpvPropertyChange(mpv_event_property *event) {
const char *eventName = event->name;
if (!propertyBlackList.contains(QString::fromUtf8(eventName),
Qt::CaseInsensitive)) {
qDebug().noquote() << "[libmpv] Property changed from mpv:"
<< eventName;
}
if (properties.contains(eventName)) {
const auto signalName = properties.value(eventName);
if (signalName != nullptr) {
QMetaObject::invokeMethod(this, signalName);
}
}
}
bool MpvDeclarativeObject::isLoaded() const {
return ((mediaStatus() == MediaStatus::Loaded) ||
(mediaStatus() == MediaStatus::Buffering) ||
(mediaStatus() == MediaStatus::Buffered));
}
bool MpvDeclarativeObject::isPlaying() const {
return playbackState() == PlaybackState::Playing;
}
bool MpvDeclarativeObject::isPaused() const {
return playbackState() == PlaybackState::Paused;
}
bool MpvDeclarativeObject::isStopped() const {
return playbackState() == PlaybackState::Stopped;
}
void MpvDeclarativeObject::setMediaStatus(
MpvDeclarativeObject::MediaStatus mediaStatus) {
if (this->mediaStatus() == mediaStatus) {
return;
}
currentMediaStatus = mediaStatus;
Q_EMIT mediaStatusChanged();
}
void MpvDeclarativeObject::videoReconfig() { Q_EMIT videoSizeChanged(); }
void MpvDeclarativeObject::audioReconfig() {}
void MpvDeclarativeObject::playbackStateChangeEvent() {
if (isPlaying()) {
Q_EMIT playing();
}
if (isPaused()) {
Q_EMIT paused();
}
if (isStopped()) {
Q_EMIT stopped();
}
Q_EMIT playbackStateChanged();
}
bool MpvDeclarativeObject::mpvSendCommand(const QVariant &arguments) {
if (arguments.isNull() || !arguments.isValid()) {
return false;
}
qDebug().noquote() << "Sending a command to mpv:" << arguments;
int errorCode = 0;
if (mpvCallType() == MpvCallType::Asynchronous) {
errorCode = mpv::qt::command_async(mpv, arguments, 0);
} else {
errorCode = mpv::qt::get_error(mpv::qt::command(mpv, arguments));
}
if (errorCode < 0) {
qWarning().noquote()
<< "Failed to execute a command for mpv:" << arguments;
}
return (errorCode >= 0);
}
bool MpvDeclarativeObject::mpvSetProperty(const QString &name,
const QVariant &value) {
if (name.isEmpty() || value.isNull() || !value.isValid()) {
return false;
}
qDebug().noquote() << "Setting a property for mpv:" << name
<< "to:" << value;
int errorCode = 0;
if (mpvCallType() == MpvCallType::Asynchronous) {
errorCode = mpv::qt::set_property_async(mpv, name, value, 0);
} else {
errorCode = mpv::qt::get_error(mpv::qt::set_property(mpv, name, value));
}
if (errorCode < 0) {
qWarning().noquote() << "Failed to set a property for mpv:" << name;
}
return (errorCode >= 0);
}
QVariant MpvDeclarativeObject::mpvGetProperty(const QString &name,
bool *ok) const {
if (ok != nullptr) {
*ok = false;
}
if (name.isEmpty()) {
return QVariant();
}
const QVariant result = mpv::qt::get_property(mpv, name);
if (result.isNull() || !result.isValid()) {
qWarning().noquote() << "Failed to query a property from mpv:" << name;
} else {
if (ok != nullptr) {
*ok = true;
}
/*if ((name != QLatin1String("time-pos")) &&
(name != QLatin1String("duration"))) {
qDebug().noquote() << "Querying a property from mpv:"
<< name << "result:" << result;
}*/
}
return result;
}
bool MpvDeclarativeObject::mpvObserveProperty(const QString &name) {
if (name.isEmpty()) {
return false;
}
qDebug().noquote() << "Observing a property from mpv:" << name;
const int errorCode = mpv_observe_property(
mpv, 0, name.toUtf8().constData(), MPV_FORMAT_NONE);
if (errorCode < 0) {
qWarning().noquote()
<< "Failed to observe a property from mpv:" << name;
}
return (errorCode >= 0);
}
QQuickFramebufferObject::Renderer *
MpvDeclarativeObject::createRenderer() const {
window()->setPersistentOpenGLContext(true);
window()->setPersistentSceneGraph(true);
return new MpvRenderer(const_cast<MpvDeclarativeObject *>(this));
}
QUrl MpvDeclarativeObject::source() const {
return isStopped() ? QUrl() : currentSource;
}
QString MpvDeclarativeObject::fileName() const {
return isStopped() ? QString()
: mpvGetProperty(QLatin1String("filename")).toString();
}
QSize MpvDeclarativeObject::videoSize() const {
if (isStopped()) {
return QSize();
}
QSize size(
qMax(mpvGetProperty(QLatin1String("video-out-params/dw")).toInt(), 0),
qMax(mpvGetProperty(QLatin1String("video-out-params/dh")).toInt(), 0));
const int rotate = videoRotate();
if ((rotate == 90) || (rotate == 270)) {
size.transpose();
}
return size;
}
MpvDeclarativeObject::PlaybackState
MpvDeclarativeObject::playbackState() const {
const bool stopped = mpvGetProperty(QLatin1String("idle-active")).toBool();
const bool paused = mpvGetProperty(QLatin1String("pause")).toBool();
return stopped ? PlaybackState::Stopped
: (paused ? PlaybackState::Paused : PlaybackState::Playing);
}
MpvDeclarativeObject::MediaStatus MpvDeclarativeObject::mediaStatus() const {
return currentMediaStatus;
}
MpvDeclarativeObject::LogLevel MpvDeclarativeObject::logLevel() const {
const QString level = mpvGetProperty(QLatin1String("msg-level")).toString();
if (level.isEmpty() || (level == QLatin1String("no")) ||
(level == QLatin1String("off"))) {
return LogLevel::Off;
}
const QString actualLevel =
level.right(level.length() - level.lastIndexOf(QLatin1Char('=')) - 1);
if (actualLevel.isEmpty() || (actualLevel == QLatin1String("no")) ||
(actualLevel == QLatin1String("off"))) {
return LogLevel::Off;
}
if ((actualLevel == QLatin1String("v")) ||
(actualLevel == QLatin1String("debug")) ||
(actualLevel == QLatin1String("trace"))) {
return LogLevel::Debug;
}
if (actualLevel == QLatin1String("warn")) {
return LogLevel::Warning;
}
if (actualLevel == QLatin1String("error")) {
return LogLevel::Critical;
}
if (actualLevel == QLatin1String("fatal")) {
return LogLevel::Fatal;
}
if (actualLevel == QLatin1String("info")) {
return LogLevel::Info;
}
return LogLevel::Debug;
}
qint64 MpvDeclarativeObject::duration() const {
return isStopped()
? 0
: qMax(mpvGetProperty(QLatin1String("duration")).toLongLong(),
qint64(0));
}
qint64 MpvDeclarativeObject::position() const {
return isStopped()
? 0
: qMin(qMax(mpvGetProperty(QLatin1String("time-pos")).toLongLong(),
qint64(0)),
duration());
}
int MpvDeclarativeObject::volume() const {
return qMin(qMax(mpvGetProperty(QLatin1String("volume")).toInt(), 0), 100);
}
bool MpvDeclarativeObject::mute() const {
return mpvGetProperty(QLatin1String("mute")).toBool();
}
bool MpvDeclarativeObject::seekable() const {
return isStopped() ? false
: mpvGetProperty(QLatin1String("seekable")).toBool();
}
QString MpvDeclarativeObject::mediaTitle() const {
return isStopped()
? QString()
: mpvGetProperty(QLatin1String("media-title")).toString();
}
QString MpvDeclarativeObject::hwdec() const {
// Querying "hwdec" itself will return empty string.
return mpvGetProperty(QLatin1String("hwdec-current")).toString();
}
QString MpvDeclarativeObject::mpvVersion() const {
return mpvGetProperty(QLatin1String("mpv-version")).toString();
}
QString MpvDeclarativeObject::mpvConfiguration() const {
return mpvGetProperty(QLatin1String("mpv-configuration")).toString();
}
QString MpvDeclarativeObject::ffmpegVersion() const {
return mpvGetProperty(QLatin1String("ffmpeg-version")).toString();
}
QString MpvDeclarativeObject::qtVersion() const {
// qVersion(): run-time Qt version
// QT_VERSION_STR: Qt version against which the application is compiled
return QLatin1String(qVersion());
}
int MpvDeclarativeObject::vid() const {
return isStopped() ? 0 : mpvGetProperty(QLatin1String("vid")).toInt();
}
int MpvDeclarativeObject::aid() const {
return isStopped() ? 0 : mpvGetProperty(QLatin1String("aid")).toInt();
}
int MpvDeclarativeObject::sid() const {
return isStopped() ? 0 : mpvGetProperty(QLatin1String("sid")).toInt();
}
int MpvDeclarativeObject::videoRotate() const {
return isStopped()
? 0
: qMin((qMax(mpvGetProperty(QLatin1String("video-out-params/rotate"))
.toInt(),
0) +
360) %
360,
359);
}
qreal MpvDeclarativeObject::videoAspect() const {
return isStopped()
? 1.7777
: qMax(
mpvGetProperty(QLatin1String("video-out-params/aspect")).toReal(),
0.0);
}
qreal MpvDeclarativeObject::speed() const {
return qMax(mpvGetProperty(QLatin1String("speed")).toReal(), 0.0);
}
bool MpvDeclarativeObject::deinterlace() const {
return mpvGetProperty(QLatin1String("deinterlace")).toBool();
}
bool MpvDeclarativeObject::audioExclusive() const {
return mpvGetProperty(QLatin1String("audio-exclusive")).toBool();
}
QString MpvDeclarativeObject::audioFileAuto() const {
return mpvGetProperty(QLatin1String("audio-file-auto")).toString();
}
QString MpvDeclarativeObject::subAuto() const {
return mpvGetProperty(QLatin1String("sub-auto")).toString();
}
QString MpvDeclarativeObject::subCodepage() const {
QString codePage = mpvGetProperty(QLatin1String("sub-codepage")).toString();
if (codePage.startsWith(QLatin1Char('+'))) {
codePage.remove(0, 1);
}
return codePage;
}
QString MpvDeclarativeObject::vo() const {
return mpvGetProperty(QLatin1String("vo")).toString();
}
QString MpvDeclarativeObject::ao() const {
return mpvGetProperty(QLatin1String("ao")).toString();
}
QString MpvDeclarativeObject::screenshotFormat() const {
return mpvGetProperty(QLatin1String("screenshot-format")).toString();
}
bool MpvDeclarativeObject::screenshotTagColorspace() const {
return mpvGetProperty(QLatin1String("screenshot-tag-colorspace")).toBool();
}
int MpvDeclarativeObject::screenshotPngCompression() const {
return qMin(
qMax(
mpvGetProperty(QLatin1String("screenshot-png-compression")).toInt(),
0),
9);
}
int MpvDeclarativeObject::screenshotJpegQuality() const {
return qMin(
qMax(mpvGetProperty(QLatin1String("screenshot-jpeg-quality")).toInt(),
0),
100);
}
QString MpvDeclarativeObject::screenshotTemplate() const {
return mpvGetProperty(QLatin1String("screenshot-template")).toString();
}
QString MpvDeclarativeObject::screenshotDirectory() const {
return mpvGetProperty(QLatin1String("screenshot-directory")).toString();
}
QString MpvDeclarativeObject::profile() const {
return mpvGetProperty(QLatin1String("profile")).toString();
}
bool MpvDeclarativeObject::hrSeek() const {
return mpvGetProperty(QLatin1String("hr-seek")).toBool();
}
bool MpvDeclarativeObject::ytdl() const {
return mpvGetProperty(QLatin1String("ytdl")).toBool();
}
bool MpvDeclarativeObject::loadScripts() const {
return mpvGetProperty(QLatin1String("load-scripts")).toBool();
}
QString MpvDeclarativeObject::path() const {
return isStopped() ? QString()
: mpvGetProperty(QLatin1String("path")).toString();
}
QString MpvDeclarativeObject::fileFormat() const {
return isStopped()
? QString()
: mpvGetProperty(QLatin1String("file-format")).toString();
}
qint64 MpvDeclarativeObject::fileSize() const {
return isStopped()
? 0
: qMax(mpvGetProperty(QLatin1String("file-size")).toLongLong(),
qint64(0));
}
qreal MpvDeclarativeObject::videoBitrate() const {
return isStopped()
? 0.0
: qMax(mpvGetProperty(QLatin1String("video-bitrate")).toReal(), 0.0);
}
qreal MpvDeclarativeObject::audioBitrate() const {
return isStopped()
? 0.0
: qMax(mpvGetProperty(QLatin1String("audio-bitrate")).toReal(), 0.0);
}
MpvDeclarativeObject::AudioDevices
MpvDeclarativeObject::audioDeviceList() const {
AudioDevices audioDevices;
QVariantList deviceList =
mpvGetProperty(QLatin1String("audio-device-list")).toList();
for (const auto &device : deviceList) {
const auto &deviceInfo = device.toMap();
SingleTrackInfo singleTrackInfo;
singleTrackInfo["name"] = deviceInfo["name"];
singleTrackInfo["description"] = deviceInfo["description"];
audioDevices.append(singleTrackInfo);
}
return audioDevices;
}
QString MpvDeclarativeObject::videoFormat() const {
return isStopped()
? QString()
: mpvGetProperty(QLatin1String("video-format")).toString();
}
MpvDeclarativeObject::MpvCallType MpvDeclarativeObject::mpvCallType() const {
return currentMpvCallType;
}
MpvDeclarativeObject::MediaTracks MpvDeclarativeObject::mediaTracks() const {
MediaTracks mediaTracks;
QVariantList trackList =
mpvGetProperty(QLatin1String("track-list")).toList();
for (const auto &track : trackList) {
const auto &trackInfo = track.toMap();
if ((trackInfo["type"] != QLatin1String("video")) &&
(trackInfo["type"] != QLatin1String("audio")) &&
(trackInfo["type"] != QLatin1String("sub"))) {
continue;
}
SingleTrackInfo singleTrackInfo;
singleTrackInfo["id"] = trackInfo["id"];
singleTrackInfo["type"] = trackInfo["type"];
singleTrackInfo["src-id"] = trackInfo["src-id"];
if (trackInfo["title"].toString().isEmpty()) {
if (trackInfo["lang"].toString() != QLatin1String("und")) {
singleTrackInfo["title"] = trackInfo["lang"];
} else if (!trackInfo["external"].toBool()) {
singleTrackInfo["title"] = "[internal]";
} else {
singleTrackInfo["title"] = "[untitled]";
}
} else {
singleTrackInfo["title"] = trackInfo["title"];
}
singleTrackInfo["lang"] = trackInfo["lang"];
singleTrackInfo["default"] = trackInfo["default"];
singleTrackInfo["forced"] = trackInfo["forced"];
singleTrackInfo["codec"] = trackInfo["codec"];
singleTrackInfo["external"] = trackInfo["external"];
singleTrackInfo["external-filename"] = trackInfo["external-filename"];
singleTrackInfo["selected"] = trackInfo["selected"];
singleTrackInfo["decoder-desc"] = trackInfo["decoder-desc"];
if (trackInfo["type"] == QLatin1String("video")) {
singleTrackInfo["albumart"] = trackInfo["albumart"];
singleTrackInfo["demux-w"] = trackInfo["demux-w"];
singleTrackInfo["demux-h"] = trackInfo["demux-h"];
singleTrackInfo["demux-fps"] = trackInfo["demux-fps"];
mediaTracks.videoChannels.append(singleTrackInfo);
} else if (trackInfo["type"] == QLatin1String("audio")) {
singleTrackInfo["demux-channel-count"] =
trackInfo["demux-channel-count"];
singleTrackInfo["demux-channels"] = trackInfo["demux-channels"];
singleTrackInfo["demux-samplerate"] = trackInfo["demux-samplerate"];
mediaTracks.audioTracks.append(singleTrackInfo);
} else if (trackInfo["type"] == QLatin1String("sub")) {
mediaTracks.subtitleStreams.append(singleTrackInfo);
}
}
return mediaTracks;
}
MpvDeclarativeObject::Chapters MpvDeclarativeObject::chapters() const {
Chapters chapters;
QVariantList chapterList =
mpvGetProperty(QLatin1String("chapter-list")).toList();
for (const auto &chapter : chapterList) {
const auto &chapterInfo = chapter.toMap();
SingleTrackInfo singleTrackInfo;
singleTrackInfo["title"] = chapterInfo["title"];
singleTrackInfo["time"] = chapterInfo["time"];
chapters.append(singleTrackInfo);
}
return chapters;
}
MpvDeclarativeObject::Metadata MpvDeclarativeObject::metadata() const {
Metadata metadata;
QVariantMap metadataMap = mpvGetProperty(QLatin1String("metadata")).toMap();
auto iterator = metadataMap.constBegin();
while (iterator != metadataMap.constEnd()) {
metadata[iterator.key()] = iterator.value();
++iterator;
}
return metadata;
}
qreal MpvDeclarativeObject::avsync() const {
return isStopped()
? 0.0
: qMax(mpvGetProperty(QLatin1String("avsync")).toReal(), 0.0);
}
int MpvDeclarativeObject::percentPos() const {
return isStopped()
? 0
: qMin(qMax(mpvGetProperty(QLatin1String("percent-pos")).toInt(), 0),
100);
}
qreal MpvDeclarativeObject::estimatedVfFps() const {
return isStopped()
? 0.0
: qMax(mpvGetProperty(QLatin1String("estimated-vf-fps")).toReal(), 0.0);
}
bool MpvDeclarativeObject::open(const QUrl &url) {
if (!url.isValid()) {
return false;
}
if (url != currentSource) {
setSource(url);
}
if (!isPlaying()) {
play();
}
return true;
}
bool MpvDeclarativeObject::play() {
if (!isPaused() || !currentSource.isValid()) {
return false;
}
const bool result = mpvSetProperty(QLatin1String("pause"), false);
if (result) {
Q_EMIT playing();
}
return result;
}
bool MpvDeclarativeObject::play(const QUrl &url) {
if (!url.isValid()) {
return false;
}
bool result = false;
if ((url == currentSource) && !isPlaying()) {
result = play();
} else {
result = open(url);
}
return result;
}
bool MpvDeclarativeObject::pause() {
if (!isPlaying()) {
return false;
}
const bool result = mpvSetProperty(QLatin1String("pause"), true);
if (result) {
Q_EMIT paused();
}
return result;
}
bool MpvDeclarativeObject::stop() {
if (isStopped()) {
return false;
}
const bool result = mpvSendCommand(QVariantList{"stop"});
if (result) {
Q_EMIT stopped();
}
currentSource.clear();
return result;
}
bool MpvDeclarativeObject::seek(qint64 value, bool absolute, bool percent) {
if (isStopped()) {
return false;
}
QStringList arguments;
arguments.append(percent ? "absolute-percent"
: (absolute ? "absolute" : "relative"));
const qint64 min = (absolute || percent) ? 0 : -position();
const qint64 max =
percent ? 100 : (absolute ? duration() : duration() - position());
return mpvSendCommand(
QVariantList{"seek", qMin(qMax(value, min), max), arguments});
}
bool MpvDeclarativeObject::seekAbsolute(qint64 position) {
if (isStopped() || position == this->position()) {
return false;
}
return seek(qMin(qMax(position, qint64(0)), duration()), true);
}
bool MpvDeclarativeObject::seekRelative(qint64 offset) {
if (isStopped() || offset == 0) {
return false;
}
return seek(qMin(qMax(offset, -position()), duration() - position()));
}
bool MpvDeclarativeObject::seekPercent(int percent) {
if (isStopped() || percent == this->percentPos()) {
return false;
}
return seek(qMin(qMax(percent, 0), 100), true, true);
}
bool MpvDeclarativeObject::screenshot() {
if (isStopped()) {
return false;
}
// Replace "subtitles" with "video" if you don't want to include subtitles
// when screenshotting.
return mpvSendCommand(QVariantList{"screenshot", "subtitles"});
}
bool MpvDeclarativeObject::screenshotToFile(const QString &filePath) {
if (isStopped() || filePath.isEmpty()) {
return false;
}
// libmpv's default: including subtitles when making a screenshot.
return mpvSendCommand(
QVariantList{"screenshot-to-file", filePath, "subtitles"});
}
void MpvDeclarativeObject::setSource(const QUrl &source) {
if (!source.isValid() || (source == currentSource)) {
return;
}
const bool result = mpvSendCommand(QVariantList{
"loadfile",
source.isLocalFile() ? source.toLocalFile() : source.url()});
if (result) {
currentSource = source;
Q_EMIT sourceChanged();
}
}
void MpvDeclarativeObject::setMute(bool mute) {
if (mute == this->mute()) {
return;
}
mpvSetProperty(QLatin1String("mute"), mute);
}
void MpvDeclarativeObject::setPlaybackState(
MpvDeclarativeObject::PlaybackState playbackState) {
if (isStopped() || (this->playbackState() == playbackState)) {
return;
}
bool result = false;
switch (playbackState) {
case PlaybackState::Stopped:
result = stop();
break;
case PlaybackState::Paused:
result = pause();
break;
case PlaybackState::Playing:
result = play();
break;
}
if (result) {
Q_EMIT playbackStateChanged();
}
}
void MpvDeclarativeObject::setLogLevel(
MpvDeclarativeObject::LogLevel logLevel) {
if (logLevel == this->logLevel()) {
return;
}
QString level(QLatin1String("debug"));
switch (logLevel) {
case LogLevel::Off:
level = QLatin1String("no");
break;
case LogLevel::Debug:
// libmpv's log level: v (verbose) < debug < trace (print all messages)
// Use "v" to avoid noisy message floods.
level = QLatin1String("v");
break;
case LogLevel::Warning:
level = QLatin1String("warn");
break;
case LogLevel::Critical:
level = QLatin1String("error");
break;
case LogLevel::Fatal:
level = QLatin1String("fatal");
break;
case LogLevel::Info:
level = QLatin1String("info");
break;
}
const bool result1 =
mpvSetProperty(QLatin1String("terminal"), level != QLatin1String("no"));
const bool result2 = mpvSetProperty(QLatin1String("msg-level"),
QStringLiteral("all=%1").arg(level));
const int result3 =
mpv_request_log_messages(mpv, level.toUtf8().constData());
if (result1 && result2 && (result3 >= 0)) {
Q_EMIT logLevelChanged();
} else {
qWarning().noquote() << "Failed to set log level.";
}
}
void MpvDeclarativeObject::setPosition(qint64 position) {
if (isStopped() || position == this->position()) {
return;
}
seek(qMin(qMax(position, qint64(0)), duration()));
}
void MpvDeclarativeObject::setVolume(int volume) {
if (volume == this->volume()) {
return;
}
mpvSetProperty(QLatin1String("volume"), qMin(qMax(volume, 0), 100));
}
void MpvDeclarativeObject::setHwdec(const QString &hwdec) {
if (hwdec.isEmpty() || hwdec == this->hwdec()) {
return;
}
mpvSetProperty(QLatin1String("hwdec"), hwdec);
}
void MpvDeclarativeObject::setVid(int vid) {
if (isStopped() || vid == this->vid()) {
return;
}
mpvSetProperty(QLatin1String("vid"), qMax(vid, 0));
}
void MpvDeclarativeObject::setAid(int aid) {
if (isStopped() || aid == this->aid()) {
return;
}
mpvSetProperty(QLatin1String("aid"), qMax(aid, 0));
}
void MpvDeclarativeObject::setSid(int sid) {
if (isStopped() || sid == this->sid()) {
return;
}
mpvSetProperty(QLatin1String("sid"), qMax(sid, 0));
}
void MpvDeclarativeObject::setVideoRotate(int videoRotate) {
if (isStopped() || videoRotate == this->videoRotate()) {
return;
}
mpvSetProperty(QLatin1String("video-rotate"),
qMin(qMax(videoRotate, 0), 359));
}
void MpvDeclarativeObject::setVideoAspect(qreal videoAspect) {
if (isStopped() || videoAspect == this->videoAspect()) {
return;
}
mpvSetProperty(QLatin1String("video-aspect"), qMax(videoAspect, 0.0));
}
void MpvDeclarativeObject::setSpeed(qreal speed) {
if (isStopped() || speed == this->speed()) {
return;
}
mpvSetProperty(QLatin1String("speed"), qMax(speed, 0.0));
}
void MpvDeclarativeObject::setDeinterlace(bool deinterlace) {
if (deinterlace == this->deinterlace()) {
return;
}
mpvSetProperty(QLatin1String("deinterlace"), deinterlace);
}
void MpvDeclarativeObject::setAudioExclusive(bool audioExclusive) {
if (audioExclusive == this->audioExclusive()) {
return;
}
mpvSetProperty(QLatin1String("audio-exclusive"), audioExclusive);
}
void MpvDeclarativeObject::setAudioFileAuto(const QString &audioFileAuto) {
if (audioFileAuto.isEmpty() || audioFileAuto == this->audioFileAuto()) {
return;
}
mpvSetProperty(QLatin1String("audio-file-auto"), audioFileAuto);
}
void MpvDeclarativeObject::setSubAuto(const QString &subAuto) {
if (subAuto.isEmpty() || subAuto == this->subAuto()) {