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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
|
/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtCore/QVector>
#include <QtCore/QTimerEvent>
#include <QtCore/QTimer>
#include <QtCore/QTime>
#include <QtCore/QLibrary>
#ifndef Q_CC_MSVC
#include <dshow.h>
#endif //Q_CC_MSVC
#include <objbase.h>
#include <initguid.h>
#include <qnetwork.h>
#include <evcode.h>
#include "mediaobject.h"
#include "videowidget.h"
#include "audiooutput.h"
#include <QtCore/QDebug>
#define TIMER_INTERVAL 16 //... ms for the timer that polls the current state (we use the multimedia timer)
#define PRELOAD_TIME 2000 // 2 seconds to load a source
QT_BEGIN_NAMESPACE
namespace Phonon
{
namespace DS9
{
typedef BOOL (WINAPI* LPAMGETERRORTEXT)(HRESULT, WCHAR *, DWORD);
//first the definition of the WorkerThread class
WorkerThread::WorkerThread()
: QThread(), m_currentRenderId(0), m_finished(false), m_currentWorkId(1)
{
}
WorkerThread::~WorkerThread()
{
}
void WorkerThread::run()
{
while (m_finished == false) {
HANDLE handles[FILTER_COUNT +1];
handles[0] = m_waitCondition;
int count = 1;
for(int i = 0; i < FILTER_COUNT; ++i) {
if (m_graphHandle[i].graph) {
handles[count++] = m_graphHandle[i].handle;
}
}
DWORD result = ::WaitForMultipleObjects(count, handles, FALSE, INFINITE);
if (result == WAIT_OBJECT_0) {
handleTask();
} else {
//this is the event management
const Graph &graph = m_graphHandle[result - WAIT_OBJECT_0 - 1].graph;
long eventCode;
LONG_PTR param1, param2;
ComPointer<IMediaEvent> mediaEvent(graph, IID_IMediaEvent);
mediaEvent->GetEvent(&eventCode, ¶m1, ¶m2, 0);
emit eventReady(graph, eventCode, param1);
mediaEvent->FreeEventParams(eventCode, param1, param2);
}
}
}
//wants to know as soon as the state is set
void WorkerThread::addStateChangeRequest(Graph graph, OAFilterState state, QList<Filter> decoders)
{
QMutexLocker locker(&m_mutex);
bool found = false;
//we try to see if there is already an attempt to change the state and we remove it
for(int i = 0; !found && i < m_queue.size(); ++i) {
const Work &w = m_queue.at(i);
if (w.graph == graph && w.task == ChangeState) {
found = true;
m_queue.removeAt(i);
}
}
//now let's create the new task
Work w;
w.task = ChangeState;
w.id = m_currentWorkId++;
w.graph = graph;
w.state = state;
w.decoders = decoders;
m_queue.enqueue(w);
m_waitCondition.set();
}
quint16 WorkerThread::addSeekRequest(Graph graph, qint64 time)
{
QMutexLocker locker(&m_mutex);
bool found = false;
//we try to see if there is already an attempt to seek and we remove it
for(int i = 0; !found && i < m_queue.size(); ++i) {
const Work &w = m_queue.at(i);
if (w.graph == graph && w.task == Seek) {
found = true;
m_queue.removeAt(i);
}
}
Work w;
w.task = Seek;
//we create a new graph
w.graph = graph;
w.id = m_currentWorkId++;
w.time = time;
m_queue.enqueue(w);
m_waitCondition.set();
return w.id;
}
quint16 WorkerThread::addUrlToRender(const QString &url)
{
QMutexLocker locker(&m_mutex);
Work w;
w.task = Render;
//we create a new graph
w.graph = Graph(CLSID_FilterGraph, IID_IGraphBuilder);
w.url = url;
w.url.detach();
w.id = m_currentWorkId++;
m_queue.enqueue(w);
m_waitCondition.set();
return w.id;
}
quint16 WorkerThread::addFilterToRender(const Filter &filter)
{
QMutexLocker locker(&m_mutex);
Work w;
w.task = Render;
//we create a new graph
w.graph = Graph(CLSID_FilterGraph, IID_IGraphBuilder);
w.filter = filter;
w.id = m_currentWorkId++;
m_queue.enqueue(w);
m_waitCondition.set();
return w.id;
}
void WorkerThread::replaceGraphForEventManagement(Graph newGraph, Graph oldGraph)
{
QMutexLocker locker(&m_mutex);
Work w;
w.task = ReplaceGraph;
w.graph = newGraph;
w.oldGraph = oldGraph;
m_queue.enqueue(w);
m_waitCondition.set();
}
void WorkerThread::handleTask()
{
QMutexLocker locker(&m_mutex);
if (m_finished || m_queue.isEmpty()) {
return;
}
const Work w = m_queue.dequeue();
//we ensure to have the wait condition in the right state
if (m_queue.isEmpty()) {
m_waitCondition.reset();
} else {
m_waitCondition.set();
}
HRESULT hr = S_OK;
{
QMutexLocker locker(&m_currentMutex);
m_currentRender = w.graph;
m_currentRenderId = w.id;
}
if (w.task == ReplaceGraph) {
int index = -1;
for(int i = 0; i < FILTER_COUNT; ++i) {
if (m_graphHandle[i].graph == w.oldGraph) {
m_graphHandle[i].graph = Graph();
index = i;
break;
} else if (index == -1 && m_graphHandle[i].graph == 0) {
//this is the first available slot
index = i;
}
}
Q_ASSERT(index != -1);
//add the new graph
HANDLE h;
if (SUCCEEDED(ComPointer<IMediaEvent>(w.graph, IID_IMediaEvent)
->GetEventHandle(reinterpret_cast<OAEVENT*>(&h)))) {
m_graphHandle[index].graph = w.graph;
m_graphHandle[index].handle = h;
}
} else if (w.task == Render) {
if (w.filter) {
//let's render pins
w.graph->AddFilter(w.filter, 0);
const QList<OutputPin> outputs = BackendNode::pins(w.filter, PINDIR_OUTPUT);
for (int i = 0; i < outputs.count(); ++i) {
//blocking call
hr = w.graph->Render(outputs.at(i));
if (FAILED(hr)) {
break;
}
}
} else if (!w.url.isEmpty()) {
//let's render a url (blocking call)
hr = w.graph->RenderFile(reinterpret_cast<const wchar_t *>(w.url.utf16()), 0);
}
if (hr != E_ABORT) {
emit asyncRenderFinished(w.id, hr, w.graph);
}
} else if (w.task == Seek) {
//that's a seekrequest
ComPointer<IMediaSeeking> mediaSeeking(w.graph, IID_IMediaSeeking);
qint64 newtime = w.time * 10000;
hr = mediaSeeking->SetPositions(&newtime, AM_SEEKING_AbsolutePositioning,
0, AM_SEEKING_NoPositioning);
qint64 currentTime = -1;
if (SUCCEEDED(hr)) {
hr = mediaSeeking->GetCurrentPosition(¤tTime);
if (SUCCEEDED(hr)) {
currentTime /= 10000; //convert to ms
}
}
emit asyncSeekingFinished(w.id, currentTime);
hr = E_ABORT; //to avoid emitting asyncRenderFinished
} else if (w.task == ChangeState) {
//remove useless decoders
QList<Filter> unused;
for (int i = 0; i < w.decoders.count(); ++i) {
const Filter &filter = w.decoders.at(i);
bool used = false;
const QList<OutputPin> pins = BackendNode::pins(filter, PINDIR_OUTPUT);
for( int i = 0; i < pins.count(); ++i) {
InputPin input;
if (pins.at(i)->ConnectedTo(input.pparam()) == S_OK) {
used = true;
}
}
if (!used) {
unused += filter;
}
}
//we can get the state
for (int i = 0; i < unused.count(); ++i) {
//we should remove this filter from the graph
w.graph->RemoveFilter(unused.at(i));
}
//we can get the state
ComPointer<IMediaControl> mc(w.graph, IID_IMediaControl);
//we change the state here
switch(w.state)
{
case State_Stopped:
mc->Stop();
break;
case State_Paused:
mc->Pause();
break;
case State_Running:
mc->Run();
break;
}
OAFilterState s;
//blocking call
HRESULT hr = mc->GetState(INFINITE, &s);
if (SUCCEEDED(hr)) {
if (s == State_Stopped) {
emit stateReady(w.graph, Phonon::StoppedState);
} else if (s == State_Paused) {
emit stateReady(w.graph, Phonon::PausedState);
} else /*if (s == State_Running)*/ {
emit stateReady(w.graph, Phonon::PlayingState);
}
}
}
{
QMutexLocker locker(&m_currentMutex);
m_currentRender = Graph();
m_currentRenderId = 0;
}
}
void WorkerThread::abortCurrentRender(qint16 renderId)
{
{
QMutexLocker locker(&m_currentMutex);
if (m_currentRender && m_currentRenderId == renderId) {
m_currentRender->Abort();
}
}
QMutexLocker locker(&m_mutex);
bool found = false;
for(int i = 0; !found && i < m_queue.size(); ++i) {
const Work &w = m_queue.at(i);
if (w.id == renderId) {
found = true;
m_queue.removeAt(i);
if (m_queue.isEmpty()) {
m_waitCondition.reset();
}
}
}
}
//tells the thread to stop processing
void WorkerThread::signalStop()
{
QMutexLocker locker(&m_mutex);
m_queue.clear();
if (m_currentRender) {
//in case we're currently rendering something
m_currentRender->Abort();
}
m_finished = true;
m_waitCondition.set();
}
MediaObject::MediaObject(QObject *parent) : BackendNode(parent),
transactionState(Phonon::StoppedState),
m_errorType(Phonon::NoError),
m_state(Phonon::LoadingState),
m_nextState(Phonon::StoppedState),
m_prefinishMark(0),
m_tickInterval(0),
m_buffering(false),
m_oldHasVideo(false),
m_prefinishMarkSent(false),
m_aboutToFinishSent(false),
m_nextSourceReadyToStart(false),
#ifndef QT_NO_PHONON_MEDIACONTROLLER
m_autoplayTitles(true),
m_currentTitle(0),
#endif //QT_NO_PHONON_MEDIACONTROLLER
m_targetTick(INFINITE)
{
for(int i = 0; i < FILTER_COUNT; ++i) {
m_graphs[i] = new MediaGraph(this, i);
}
connect(&m_thread, SIGNAL(stateReady(Graph, Phonon::State)),
SLOT(slotStateReady(Graph, Phonon::State)));
connect(&m_thread, SIGNAL(eventReady(Graph, long, long)),
SLOT(handleEvents(Graph, long, long)));
connect(&m_thread, SIGNAL(asyncRenderFinished(quint16, HRESULT, Graph)),
SLOT(finishLoading(quint16, HRESULT, Graph)));
connect(&m_thread, SIGNAL(asyncSeekingFinished(quint16, qint64)),
SLOT(finishSeeking(quint16, qint64)));
//really special case
m_mediaObject = this;
m_thread.start();
}
MediaObject::~MediaObject()
{
//be sure to finish the timer first
m_tickTimer.stop();
//we finish the worker thread here
m_thread.signalStop();
m_thread.wait();
//and then we delete the graphs
for (int i = 0; i < FILTER_COUNT; ++i) {
delete m_graphs[i];
}
}
WorkerThread *MediaObject::workerThread()
{
return &m_thread;
}
MediaGraph *MediaObject::currentGraph() const
{
return m_graphs[0];
}
MediaGraph *MediaObject::nextGraph() const
{
return m_graphs[FILTER_COUNT - 1];
}
//utility function to save the graph to a file
void MediaObject::timerEvent(QTimerEvent *e)
{
if (e->timerId() == m_tickTimer.timerId()) {
const qint64 current = currentTime();
const qint64 total = totalTime();
if ( m_tickInterval != 0 && current > m_targetTick) {
updateTargetTick();
emit tick(current);
}
//check that the title hasn't changed
#ifndef QT_NO_PHONON_MEDIACONTROLLER
if (m_autoplayTitles && m_currentTitle < _iface_availableTitles() - 1) {
if (current >= total) {
//we go to the next title
_iface_setCurrentTitle(m_currentTitle + 1, false);
emit tick(current);
}
return;
}
#endif //QT_NO_PHONON_MEDIACONTROLLER
if (total) {
const qint64 remaining = total - current;
if (m_transitionTime < 0 && m_nextSourceReadyToStart) {
if (remaining < -m_transitionTime + TIMER_INTERVAL/2) {
//we need to switch graphs to run the next source in the queue (with cross-fading)
switchToNextSource();
return;
} else if (current < -m_transitionTime) {
//we are currently crossfading
for (int i = 0; i < m_audioOutputs.count(); ++i) {
m_audioOutputs.at(i)->setCrossFadingProgress( currentGraph()->index(), qMin( qreal(1.), qreal(current) / qreal(-m_transitionTime)));
}
}
}
if (m_prefinishMark > 0 && !m_prefinishMarkSent && remaining < m_prefinishMark + TIMER_INTERVAL/2) {
#ifdef GRAPH_DEBUG
qDebug() << "DS9: emit prefinishMarkReached" << remaining << QTime::currentTime().toString();
#endif
m_prefinishMarkSent = true;
emit prefinishMarkReached( remaining );
}
if (!m_aboutToFinishSent && remaining < PRELOAD_TIME - m_transitionTime + TIMER_INTERVAL/2) {
//let's take a 2 seconds time to actually load the next file
#ifdef GRAPH_DEBUG
qDebug() << "DS9: emit aboutToFinish" << remaining << QTime::currentTime().toString();
#endif
m_aboutToFinishSent = true;
emit aboutToFinish();
}
} else {
//total is 0: the stream is probably live (endless)
}
if (m_buffering) {
ComPointer<IAMNetworkStatus> status(currentGraph()->realSource(), IID_IAMNetworkStatus);
if (status) {
long l;
status->get_BufferingProgress(&l);
emit bufferStatus(l);
#ifdef GRAPH_DEBUG
qDebug() << "emit bufferStatus(" << l << ")";
#endif
}
}
}
}
void MediaObject::switchToNextSource()
{
m_prefinishMarkSent = false;
m_aboutToFinishSent = false;
m_nextSourceReadyToStart = false;
m_oldHasVideo = currentGraph()->hasVideo();
qSwap(m_graphs[0], m_graphs[1]); //swap the graphs
if (m_transitionTime >= 0)
m_graphs[1]->stop(); //make sure we stop the previous graph
if (currentGraph()->mediaSource().type() != Phonon::MediaSource::Invalid &&
catchComError(currentGraph()->renderResult())) {
setState(Phonon::ErrorState);
return;
}
//we need to play the next media
play();
//we tell the video widgets to switch now to the new source
#ifndef QT_NO_PHONON_VIDEO
for (int i = 0; i < m_videoWidgets.count(); ++i) {
m_videoWidgets.at(i)->setCurrentGraph(currentGraph()->index());
}
#endif //QT_NO_PHONON_VIDEO
emit currentSourceChanged(currentGraph()->mediaSource());
emit metaDataChanged(currentGraph()->metadata());
if (nextGraph()->hasVideo() != currentGraph()->hasVideo()) {
emit hasVideoChanged(currentGraph()->hasVideo());
}
emit tick(0);
emit totalTimeChanged(totalTime());
#ifndef QT_NO_PHONON_MEDIACONTROLLER
setTitles(currentGraph()->titles());
#endif //QT_NO_PHONON_MEDIACONTROLLER
}
Phonon::State MediaObject::state() const
{
if (m_buffering) {
return Phonon::BufferingState;
} else {
return m_state;
}
}
bool MediaObject::hasVideo() const
{
return currentGraph()->hasVideo();
}
bool MediaObject::isSeekable() const
{
return currentGraph()->isSeekable();
}
qint64 MediaObject::totalTime() const
{
#ifndef QT_NO_PHONON_MEDIACONTROLLER
//1st, check if there is more titles after
const qint64 ret = (m_currentTitle < _iface_availableTitles() - 1) ?
titleAbsolutePosition(m_currentTitle+1) : currentGraph()->absoluteTotalTime();
//this is the duration of the current title
return ret - titleAbsolutePosition(m_currentTitle);
#else
return currentGraph()->absoluteTotalTime();
#endif //QT_NO_PHONON_MEDIACONTROLLER
}
qint64 MediaObject::currentTime() const
{
//this handles inaccuracy when stopping on a title
return currentGraph()->absoluteCurrentTime()
#ifndef QT_NO_PHONON_MEDIACONTROLLER
- titleAbsolutePosition(m_currentTitle)
#endif //QT_NO_PHONON_MEDIACONTROLLER
;
}
qint32 MediaObject::tickInterval() const
{
return m_tickInterval;
}
void MediaObject::setTickInterval(qint32 newTickInterval)
{
m_tickInterval = newTickInterval;
updateTargetTick();
}
void MediaObject::pause()
{
if (currentGraph()->isLoading()) {
m_nextState = Phonon::PausedState;
} else {
currentGraph()->pause();
}
}
void MediaObject::stop()
{
if (currentGraph()->isLoading()) {
m_nextState = Phonon::StoppedState;
} else {
currentGraph()->stop();
}
}
void MediaObject::ensureStopped()
{
currentGraph()->ensureStopped();
if (m_state == Phonon::ErrorState) {
//we reset the state here
m_state = Phonon::StoppedState;
}
}
void MediaObject::play()
{
if (currentGraph()->isLoading()) {
m_nextState = Phonon::PlayingState;
} else {
currentGraph()->play();
}
}
QString MediaObject::errorString() const
{
return m_errorString;
}
Phonon::ErrorType MediaObject::errorType() const
{
return m_errorType;
}
void MediaObject::updateTargetTick()
{
if (m_tickInterval) {
const qint64 current = currentTime();
m_targetTick = current / m_tickInterval * m_tickInterval;
if (current == 0 || m_targetTick < current) {
m_targetTick += m_tickInterval;
}
}
}
void MediaObject::setState(Phonon::State newstate)
{
if (newstate == Phonon::PlayingState) {
updateTargetTick();
}
if (newstate == m_state) {
return;
}
//manage the timer
if (newstate == Phonon::PlayingState) {
m_tickTimer.start(TIMER_INTERVAL, this);
} else {
m_tickTimer.stop();
}
Phonon::State oldstate = state();
m_state = newstate;
emit stateChanged(newstate, oldstate);
}
qint32 MediaObject::prefinishMark() const
{
return m_prefinishMark;
}
void MediaObject::setPrefinishMark(qint32 newPrefinishMark)
{
m_prefinishMark = newPrefinishMark;
}
qint32 MediaObject::transitionTime() const
{
return m_transitionTime;
}
void MediaObject::setTransitionTime(qint32 time)
{
m_transitionTime = time;
}
qint64 MediaObject::remainingTime() const
{
return totalTime() - currentTime();
}
Phonon::MediaSource MediaObject::source() const
{
return currentGraph()->mediaSource();
}
void MediaObject::setNextSource(const Phonon::MediaSource &source)
{
m_nextSourceReadyToStart = true;
const bool shouldSwitch = (m_state == Phonon::StoppedState || m_state == Phonon::ErrorState);
nextGraph()->loadSource(source); //let's preload the source
if (shouldSwitch) {
switchToNextSource();
}
}
void MediaObject::setSource(const Phonon::MediaSource &source)
{
m_nextSourceReadyToStart = false;
m_prefinishMarkSent = false;
m_aboutToFinishSent = false;
m_oldHasVideo = currentGraph()->hasVideo();
setState(Phonon::LoadingState);
//After loading we go into stopped state
m_nextState = Phonon::StoppedState;
catchComError(currentGraph()->loadSource(source));
emit currentSourceChanged(source);
}
void MediaObject::slotStateReady(Graph graph, Phonon::State newState)
{
if (graph == currentGraph()->graph() && !currentGraph()->isLoading()) {
setState(newState);
}
}
void MediaObject::loadingFinished(MediaGraph *mg)
{
if (mg == currentGraph()) {
#ifndef QT_NO_PHONON_MEDIACONTROLLER
//Title interface
m_currentTitle = 0;
setTitles(currentGraph()->titles());
#endif //QT_NO_PHONON_MEDIACONTROLLER
HRESULT hr = mg->renderResult();
if (catchComError(hr)) {
return;
}
if (m_oldHasVideo != currentGraph()->hasVideo()) {
emit hasVideoChanged(currentGraph()->hasVideo());
}
#ifndef QT_NO_PHONON_VIDEO
if (currentGraph()->hasVideo()) {
updateVideoGeometry();
}
#endif //QT_NO_PHONON_VIDEO
emit metaDataChanged(currentGraph()->metadata());
emit totalTimeChanged(totalTime());
//let's put the next state
switch(m_nextState)
{
case Phonon::PausedState:
pause();
break;
case Phonon::PlayingState:
play();
break;
case Phonon::ErrorState:
setState(Phonon::ErrorState);
break;
case Phonon::StoppedState:
default:
stop();
break;
}
}
}
void MediaObject::seek(qint64 time)
{
//we seek into the current title
currentGraph()->absoluteSeek(time
#ifndef QT_NO_PHONON_MEDIACONTROLLER
+ titleAbsolutePosition(m_currentTitle)
#endif //QT_NO_PHONON_MEDIACONTROLLER
);
}
void MediaObject::seekingFinished(MediaGraph *mg)
{
if (mg == currentGraph()) {
updateTargetTick();
if (currentTime() < totalTime() - m_prefinishMark) {
m_prefinishMarkSent = false;
}
if (currentTime() < totalTime() - PRELOAD_TIME + m_transitionTime) {
m_aboutToFinishSent = false;
}
//this helps the update of the application (seekslider for example)
if (m_state == PausedState || m_state == PlayingState) {
emit tick(currentTime());
}
}
}
bool MediaObject::catchComError(HRESULT hr)
{
m_errorString.clear();
m_errorType = Phonon::NoError;
if (hr != S_OK) {
#ifdef GRAPH_DEBUG
qWarning("an error occurred 0x%x",hr);
#endif
LPAMGETERRORTEXT getErrorText = (LPAMGETERRORTEXT)QLibrary::resolve(QLatin1String("quartz"), "AMGetErrorTextW");
ushort buffer[MAX_ERROR_TEXT_LEN];
if (getErrorText && getErrorText(hr, (WCHAR*)buffer, MAX_ERROR_TEXT_LEN)) {
m_errorString = QString::fromUtf16(buffer);
} else {
m_errorString = QString::fromLatin1("Unknown error");
}
const QString comError = QString::number(uint(hr), 16);
if (!m_errorString.toLower().contains(comError.toLower())) {
m_errorString += QString::fromLatin1(" (0x%1)").arg(comError);
}
if (FAILED(hr)) {
m_errorType = Phonon::FatalError;
setState(Phonon::ErrorState);
} else {
m_errorType = Phonon::NormalError;
m_nextState = Phonon::ErrorState;
}
} else {
m_errorType = Phonon::NoError;
}
return m_errorType == Phonon::FatalError;
}
void MediaObject::grabNode(BackendNode *node)
{
for (int i = 0; i < FILTER_COUNT; ++i) {
m_graphs[i]->grabNode(node);
}
node->setMediaObject(this);
}
bool MediaObject::connectNodes(BackendNode *source, BackendNode *sink)
{
bool ret = true;
for (int i = 0; i < FILTER_COUNT; ++i) {
ret = ret && m_graphs[i]->connectNodes(source, sink);
}
if (ret) {
#ifndef QT_NO_PHONON_VIDEO
if (VideoWidget *video = qobject_cast<VideoWidget*>(sink)) {
m_videoWidgets += video;
} else
#endif //QT_NO_PHONON_VIDEO
if (AudioOutput *audio = qobject_cast<AudioOutput*>(sink)) {
m_audioOutputs += audio;
}
}
return ret;
}
bool MediaObject::disconnectNodes(BackendNode *source, BackendNode *sink)
{
bool ret = true;
for (int i = 0; i < FILTER_COUNT; ++i) {
ret = ret && m_graphs[i]->disconnectNodes(source, sink);
}
if (ret) {
#ifndef QT_NO_PHONON_VIDEO
if (VideoWidget *video = qobject_cast<VideoWidget*>(sink)) {
m_videoWidgets.removeOne(video);
} else
#endif //QT_NO_PHONON_VIDEO
if (AudioOutput *audio = qobject_cast<AudioOutput*>(sink)) {
m_audioOutputs.removeOne(audio);
}
}
return ret;
}
#ifndef QT_NO_PHONON_VIDEO
void MediaObject::updateVideoGeometry()
{
for (int i = 0; i < m_videoWidgets.count(); ++i) {
m_videoWidgets.at(i)->notifyVideoLoaded();
}
}
#endif //QT_NO_PHONON_VIDEO
void MediaObject::handleComplete(IGraphBuilder *graph)
{
if (graph == currentGraph()->graph()) {
if (m_transitionTime >= PRELOAD_TIME || m_aboutToFinishSent == false) {
emit aboutToFinish(); //give a chance to the frontend to give a next source
m_aboutToFinishSent = true;
}
if (!m_nextSourceReadyToStart) {
//this is the last source, we simply finish
const qint64 current = currentTime();
const OAFilterState currentState = currentGraph()->syncGetRealState();
emit tick(current); //this ensures that the end of the seek slider is reached
emit finished();
if (currentTime() == current && currentGraph()->syncGetRealState() == currentState) {
//no seek operation in-between
pause();
setState(Phonon::PausedState); //we set it here
}
} else if (m_transitionTime == 0) {
//gapless transition
switchToNextSource(); //let's call the function immediately
} else if (m_transitionTime > 0) {
//management of the transition (if it is >= 0)
QTimer::singleShot(m_transitionTime, this, SLOT(switchToNextSource()));
}
} else {
//it is just the end of the previous source (in case of cross-fading)
nextGraph()->cleanup();
}
for (int i = 0; i < m_audioOutputs.count(); ++i) {
m_audioOutputs.at(i)->setCrossFadingProgress( currentGraph()->index(), 1.); //cross-fading is in any case finished
}
}
void MediaObject::finishLoading(quint16 workId, HRESULT hr, Graph graph)
{
for(int i = 0; i < FILTER_COUNT; ++i) {
m_graphs[i]->finishLoading(workId, hr, graph);
}
}
void MediaObject::finishSeeking(quint16 workId, qint64 time)
{
for(int i = 0; i < FILTER_COUNT; ++i) {
m_graphs[i]->finishSeeking(workId, time);
}
}
void MediaObject::handleEvents(Graph graph, long eventCode, long param1)
{
QString eventDescription;
switch (eventCode)
{
case EC_BUFFERING_DATA:
if (graph == currentGraph()->graph()) {
m_buffering = param1;
emit stateChanged(state(), m_state);
}
break;
case EC_LENGTH_CHANGED:
if (graph == currentGraph()->graph()) {
emit totalTimeChanged( totalTime() );
}
break;
case EC_COMPLETE:
handleComplete(graph);
break;
#ifndef QT_NO_PHONON_VIDEO
case EC_VIDEO_SIZE_CHANGED:
if (graph == currentGraph()->graph()) {
updateVideoGeometry();
}
break;
#endif //QT_NO_PHONON_VIDEO
#ifdef GRAPH_DEBUG
case EC_ACTIVATE: qDebug() << "EC_ACTIVATE: A video window is being " << (param1 ? "ACTIVATED" : "DEACTIVATED"); break;
case EC_BUILT: qDebug() << "EC_BUILT: Send by the Video Control when a graph has been built. Not forwarded to applications."; break;
case EC_CLOCK_CHANGED: qDebug() << "EC_CLOCK_CHANGED"; break;
case EC_CLOCK_UNSET: qDebug() << "EC_CLOCK_UNSET: The clock provider was disconnected."; break;
case EC_CODECAPI_EVENT: qDebug() << "EC_CODECAPI_EVENT: Sent by an encoder to signal an encoding event."; break;
case EC_DEVICE_LOST: qDebug() << "EC_DEVICE_LOST: A Plug and Play device was removed or has become available again."; break;
case EC_DISPLAY_CHANGED: qDebug() << "EC_DISPLAY_CHANGED: The display mode has changed."; break;
case EC_END_OF_SEGMENT: qDebug() << "EC_END_OF_SEGMENT: The end of a segment has been reached."; break;
case EC_ERROR_STILLPLAYING: qDebug() << "EC_ERROR_STILLPLAYING: An asynchronous command to run the graph has failed."; break;
case EC_ERRORABORT: qDebug() << "EC_ERRORABORT: An operation was aborted because of an error."; break;
case EC_EXTDEVICE_MODE_CHANGE: qDebug() << "EC_EXTDEVICE_MODE_CHANGE: Not supported."; break;
case EC_FULLSCREEN_LOST: qDebug() << "EC_FULLSCREEN_LOST: The video renderer is switching out of full-screen mode."; break;
case EC_GRAPH_CHANGED: qDebug() << "EC_GRAPH_CHANGED: The filter graph has changed."; break;
case EC_NEED_RESTART: qDebug() << "EC_NEED_RESTART: A filter is requesting that the graph be restarted."; break;
case EC_NOTIFY_WINDOW: qDebug() << "EC_NOTIFY_WINDOW: Notifies a filter of the video renderer's window."; break;
case EC_OLE_EVENT: qDebug() << "EC_OLE_EVENT: A filter is passing a text string to the application."; break;
case EC_OPENING_FILE: qDebug() << "EC_OPENING_FILE: The graph is opening a file, or has finished opening a file."; break;
case EC_PALETTE_CHANGED: qDebug() << "EC_PALETTE_CHANGED: The video palette has changed."; break;
case EC_PAUSED: qDebug() << "EC_PAUSED: A pause request has completed."; break;
case EC_PREPROCESS_COMPLETE: qDebug() << "EC_PREPROCESS_COMPLETE: Sent by the WM ASF Writer filter when it completes the pre-processing for multipass encoding."; break;
case EC_QUALITY_CHANGE: qDebug() << "EC_QUALITY_CHANGE: The graph is dropping samples, for quality control."; break;
case EC_REPAINT: qDebug() << "EC_REPAINT: A video renderer requires a repaint."; break;
case EC_SEGMENT_STARTED: qDebug() << "EC_SEGMENT_STARTED: A new segment has started."; break;
case EC_SHUTTING_DOWN: qDebug() << "EC_SHUTTING_DOWN: The filter graph is shutting down, prior to being destroyed."; break;
case EC_SNDDEV_IN_ERROR: qDebug() << "EC_SNDDEV_IN_ERROR: A device error has occurred in an audio capture filter."; break;
case EC_SNDDEV_OUT_ERROR: qDebug() << "EC_SNDDEV_OUT_ERROR: A device error has occurred in an audio renderer filter."; break;
case EC_STARVATION: qDebug() << "EC_STARVATION: A filter is not receiving enough data."; break;
case EC_STATE_CHANGE: qDebug() << "EC_STATE_CHANGE: The filter graph has changed state."; break;
case EC_STEP_COMPLETE: qDebug() << "EC_STEP_COMPLETE: A filter performing frame stepping has stepped the specified number of frames."; break;
case EC_STREAM_CONTROL_STARTED: qDebug() << "EC_STREAM_CONTROL_STARTED: A stream-control start command has taken effect."; break;
case EC_STREAM_CONTROL_STOPPED: qDebug() << "EC_STREAM_CONTROL_STOPPED: A stream-control stop command has taken effect."; break;
case EC_STREAM_ERROR_STILLPLAYING: qDebug() << "EC_STREAM_ERROR_STILLPLAYING: An error has occurred in a stream. The stream is still playing."; break;
case EC_STREAM_ERROR_STOPPED: qDebug() << "EC_STREAM_ERROR_STOPPED: A stream has stopped because of an error."; break;
case EC_TIMECODE_AVAILABLE: qDebug() << "EC_TIMECODE_AVAILABLE: Not supported."; break;
case EC_UNBUILT: qDebug() << "Sent by the Video Control when a graph has been torn down. Not forwarded to applications."; break;
case EC_USERABORT: qDebug() << "EC_USERABORT: Send by the Video Control when a graph has been torn down. Not forwarded to applications."; break;
case EC_VMR_RECONNECTION_FAILED: qDebug() << "EC_VMR_RECONNECTION_FAILED: Sent by the VMR-7 and the VMR-9 when it was unable to accept a dynamic format change request from the upstream decoder."; break;
case EC_VMR_RENDERDEVICE_SET: qDebug() << "EC_VMR_RENDERDEVICE_SET: Sent when the VMR has selected its rendering mechanism."; break;
case EC_VMR_SURFACE_FLIPPED: qDebug() << "EC_VMR_SURFACE_FLIPPED: Sent when the VMR-7's allocator presenter has called the DirectDraw Flip method on the surface being presented."; break;
case EC_WINDOW_DESTROYED: qDebug() << "EC_WINDOW_DESTROYED: The video renderer was destroyed or removed from the graph"; break;
case EC_WMT_EVENT: qDebug() << "EC_WMT_EVENT: Sent by the Windows Media Format SDK when an application uses the ASF Reader filter to play ASF files protected by digital rights management (DRM)."; break;
case EC_WMT_INDEX_EVENT: qDebug() << "EC_WMT_INDEX_EVENT: Sent by the Windows Media Format SDK when an application uses the ASF Writer to index Windows Media Video files."; break;
//documented by Microsoft but not supported in the Platform SDK
// case EC_BANDWIDTHCHANGE : qDebug() << "EC_BANDWIDTHCHANGE: not supported"; break;
// case EC_CONTENTPROPERTY_CHANGED: qDebug() << "EC_CONTENTPROPERTY_CHANGED: not supported."; break;
// case EC_EOS_SOON: qDebug() << "EC_EOS_SOON: not supported"; break;
// case EC_ERRORABORTEX: qDebug() << "EC_ERRORABORTEX: An operation was aborted because of an error."; break;
// case EC_FILE_CLOSED: qDebug() << "EC_FILE_CLOSED: The source file was closed because of an unexpected event."; break;
// case EC_LOADSTATUS: qDebug() << "EC_LOADSTATUS: Notifies the application of progress when opening a network file."; break;
// case EC_MARKER_HIT: qDebug() << "EC_MARKER_HIT: not supported."; break;
// case EC_NEW_PIN: qDebug() << "EC_NEW_PIN: not supported."; break;
// case EC_PLEASE_REOPEN: qDebug() << "EC_PLEASE_REOPEN: The source file has changed."; break;
// case EC_PROCESSING_LATENCY: qDebug() << "EC_PROCESSING_LATENCY: Indicates the amount of time that a component is taking to process each sample."; break;
// case EC_RENDER_FINISHED: qDebug() << "EC_RENDER_FINISHED: Not supported."; break;
// case EC_SAMPLE_LATENCY: qDebug() << "EC_SAMPLE_LATENCY: Specifies how far behind schedule a component is for processing samples."; break;
// case EC_SAMPLE_NEEDED: qDebug() << "EC_SAMPLE_NEEDED: Requests a new input sample from the Enhanced Video Renderer (EVR) filter."; break;
// case EC_SCRUB_TIME: qDebug() << "EC_SCRUB_TIME: Specifies the time stamp for the most recent frame step."; break;
// case EC_STATUS: qDebug() << "EC_STATUS: Contains two arbitrary status strings."; break;
// case EC_VIDEOFRAMEREADY: qDebug() << "EC_VIDEOFRAMEREADY: A video frame is ready for display."; break;
default:
qDebug() << "Unknown event" << eventCode << "(" << param1 << ")";
break;
#else
default:
break;
#endif
}
}
#ifndef QT_NO_PHONON_MEDIACONTROLLER
//interface management
bool MediaObject::hasInterface(Interface iface) const
{
return iface == AddonInterface::TitleInterface;
}
QVariant MediaObject::interfaceCall(Interface iface, int command, const QList<QVariant> ¶ms)
{
if (hasInterface(iface)) {
switch (iface)
{
case TitleInterface:
switch (command)
{
case availableTitles:
return _iface_availableTitles();
case title:
return _iface_currentTitle();
case setTitle:
_iface_setCurrentTitle(params.first().toInt());
break;
case autoplayTitles:
return m_autoplayTitles;
case setAutoplayTitles:
m_autoplayTitles = params.first().toBool();
updateStopPosition();
break;
}
break;
default:
break;
}
}
return QVariant();
}
//TitleInterface
//this is called to set the time for the different titles
qint64 MediaObject::titleAbsolutePosition(int title) const
{
if (title >= 0 && title < m_titles.count()) {
return m_titles.at(title);
} else {
return 0;
}
}
void MediaObject::setTitles(const QList<qint64> &titles)
{
//this is called when the source is loaded
const bool emitSignal = m_titles.count() != titles.count();
m_titles = titles;
if (emitSignal) {
emit availableTitlesChanged(titles.count());
}
updateStopPosition();
}
int MediaObject::_iface_availableTitles() const
{
return m_titles.count() - 1;
}
int MediaObject::_iface_currentTitle() const
{
return m_currentTitle;
}
void MediaObject::_iface_setCurrentTitle(int title, bool bseek)
{
#ifdef GRAPH_DEBUG
qDebug() << "_iface_setCurrentTitle" << title;
#endif
const int oldTitle = m_currentTitle;
m_currentTitle = title;
updateStopPosition();
if (bseek) {
//let's seek to the beginning of the song
seek(0);
} else {
updateTargetTick();
}
if (oldTitle != title) {
emit titleChanged(title);
emit totalTimeChanged(totalTime());
}
}
void MediaObject::updateStopPosition()
{
if (!m_autoplayTitles && m_currentTitle < _iface_availableTitles() - 1) {
//stop position is set to the end of the track
currentGraph()->setStopPosition(titleAbsolutePosition(m_currentTitle+1));
} else {
//stop position is set to the end
currentGraph()->setStopPosition(-1);
}
}
#endif //QT_NO_PHONON_QT_NO_PHONON_MEDIACONTROLLER
void MediaObject::switchFilters(int index, Filter oldFilter, Filter newFilter)
{
if (currentGraph()->index() == index) {
currentGraph()->switchFilters(oldFilter, newFilter);
} else {
nextGraph()->switchFilters(oldFilter, newFilter);
}
}
}
}
QT_END_NAMESPACE
#include "moc_mediaobject.cpp"
|