Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
mfplayersession.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "private/qplatformmediaplayer_p.h"
5
6#include <QtCore/qcoreapplication.h>
7#include <QtCore/qdatetime.h>
8#include <QtCore/qthread.h>
9#include <QtCore/qvarlengtharray.h>
10#include <QtCore/qdebug.h>
11#include <QtCore/qfile.h>
12#include <QtCore/qbuffer.h>
13
14#include "private/qplatformaudiooutput_p.h"
15#include "qaudiooutput.h"
16
19#include <mfmetadata_p.h>
20#include <private/qwindowsaudioutils_p.h>
21
23#include <mferror.h>
24#include <nserror.h>
25#include <winerror.h>
27#include <wmcodecdsp.h>
28
29#include <mfidl.h>
30#include <mmdeviceapi.h>
31#include <propvarutil.h>
32#include <wininet.h>
33#include <functiondiscoverykeys_devpkey.h>
34
35//#define DEBUG_MEDIAFOUNDATION
36
38
39MFPlayerSession::MFPlayerSession(MFPlayerControl *playerControl)
40 : m_cRef(1),
41 m_playerControl(playerControl),
42 m_scrubbing(false),
43 m_restoreRate(1),
44 m_closing(false),
45 m_mediaTypes(0),
46 m_pendingRate(1),
47 m_status(QMediaPlayer::NoMedia)
48
49{
50 connect(this, &MFPlayerSession::sessionEvent, this, &MFPlayerSession::handleSessionEvent);
51
52 m_signalPositionChangeTimer.setInterval(10);
53 m_signalPositionChangeTimer.setTimerType(Qt::PreciseTimer);
54 m_signalPositionChangeTimer.callOnTimeout(this, &MFPlayerSession::timeout);
55
56 m_pendingState = NoPending;
57 ZeroMemory(&m_state, sizeof(m_state));
58 m_state.command = CmdStop;
59 m_state.prevCmd = CmdNone;
60 m_state.rate = 1.0f;
61 ZeroMemory(&m_request, sizeof(m_request));
62 m_request.command = CmdNone;
63 m_request.prevCmd = CmdNone;
64 m_request.rate = 1.0f;
65
66 m_videoRendererControl = new MFVideoRendererControl(this);
67}
68
69void MFPlayerSession::timeout()
70{
71 const qint64 pos = position();
72
73 if (pos != m_lastPosition) {
74 const bool updatePos = m_timeCounter++ % 10 == 0;
75 if (pos >= qint64(m_duration / 10000 - 20)) {
76 if (m_playerControl->doLoop()) {
77 m_session->Pause();
78 setPosition(0);
79 positionChanged(0);
80 } else {
81 if (updatePos)
82 positionChanged(pos);
83 }
84 } else {
85 if (updatePos)
86 positionChanged(pos);
87 }
88 m_lastPosition = pos;
89 }
90}
91
93{
94#ifdef DEBUG_MEDIAFOUNDATION
95 qDebug() << "close";
96#endif
97
98 m_signalPositionChangeTimer.stop();
99 clear();
100 if (!m_session)
101 return;
102
103 HRESULT hr = S_OK;
104 if (m_session) {
105 m_closing = true;
106 hr = m_session->Close();
107 if (SUCCEEDED(hr)) {
108 DWORD dwWaitResult = WaitForSingleObject(m_hCloseEvent.get(), 2000);
109 if (dwWaitResult == WAIT_TIMEOUT) {
110 qWarning() << "session close time out!";
111 }
112 }
113 m_closing = false;
114 }
115
116 if (SUCCEEDED(hr)) {
117 if (m_session)
118 m_session->Shutdown();
119 if (m_sourceResolver)
120 m_sourceResolver->shutdown();
121 }
122 m_sourceResolver.Reset();
123
124 m_videoRendererControl->releaseActivate();
125// } else if (m_playerService->videoWindowControl()) {
126// m_playerService->videoWindowControl()->releaseActivate();
127// }
128
129 m_session.Reset();
130 m_hCloseEvent = {};
131 m_lastPosition = -1;
132 m_position = 0;
133}
134
135void MFPlayerSession::load(const QUrl &url, QIODevice *stream)
136{
137#ifdef DEBUG_MEDIAFOUNDATION
138 qDebug() << "load";
139#endif
140 clear();
141
142 if (m_status == QMediaPlayer::LoadingMedia && m_sourceResolver)
143 m_sourceResolver->cancel();
144
145 if (url.isEmpty() && !stream) {
146 close();
147 changeStatus(QMediaPlayer::NoMedia);
148 } else if (stream && (!stream->isReadable())) {
149 close();
150 changeStatus(QMediaPlayer::InvalidMedia);
151 error(QMediaPlayer::ResourceError, tr("Invalid stream source."), true);
152 } else if (createSession()) {
153 changeStatus(QMediaPlayer::LoadingMedia);
154 m_sourceResolver->load(url, stream);
155 if (url.isLocalFile())
156 m_updateRoutingOnStart = true;
157 }
158 positionChanged(position());
159}
160
161void MFPlayerSession::handleSourceError(long hr)
162{
163 QString errorString;
164 QMediaPlayer::Error errorCode = QMediaPlayer::ResourceError;
165 switch (hr) {
166 case QMediaPlayer::FormatError:
167 errorCode = QMediaPlayer::FormatError;
168 errorString = tr("Attempting to play invalid Qt resource.");
169 break;
170 case NS_E_FILE_NOT_FOUND:
171 errorString = tr("The system cannot find the file specified.");
172 break;
173 case NS_E_SERVER_NOT_FOUND:
174 errorString = tr("The specified server could not be found.");
175 break;
176 case MF_E_UNSUPPORTED_BYTESTREAM_TYPE:
177 errorCode = QMediaPlayer::FormatError;
178 errorString = tr("Unsupported media type.");
179 break;
180 case MF_E_UNSUPPORTED_SCHEME:
181 errorCode = QMediaPlayer::ResourceError;
182 errorString = tr("Unsupported URL scheme.");
183 break;
184 case INET_E_CANNOT_CONNECT:
185 errorCode = QMediaPlayer::NetworkError;
186 errorString = tr("Connection to server could not be established.");
187 break;
188 default:
189 qWarning() << "handleSourceError:"
190 << Qt::showbase << Qt::hex << Qt::uppercasedigits << static_cast<quint32>(hr);
191 errorString = tr("Failed to load source.");
192 break;
193 }
194 changeStatus(QMediaPlayer::InvalidMedia);
195 error(errorCode, errorString, true);
196}
197
198void MFPlayerSession::handleMediaSourceReady()
199{
200 if (QMediaPlayer::LoadingMedia != m_status || !m_sourceResolver
201 || m_sourceResolver.Get() != sender())
202 return;
203#ifdef DEBUG_MEDIAFOUNDATION
204 qDebug() << "handleMediaSourceReady";
205#endif
206 HRESULT hr = S_OK;
207 IMFMediaSource* mediaSource = m_sourceResolver->mediaSource();
208
209 DWORD dwCharacteristics = 0;
210 mediaSource->GetCharacteristics(&dwCharacteristics);
211 seekableUpdate(MFMEDIASOURCE_CAN_SEEK & dwCharacteristics);
212
213 ComPtr<IMFPresentationDescriptor> sourcePD;
214 hr = mediaSource->CreatePresentationDescriptor(&sourcePD);
215 if (SUCCEEDED(hr)) {
216 m_duration = 0;
217 m_metaData = MFMetaData::fromNative(mediaSource);
219 sourcePD->GetUINT64(MF_PD_DURATION, &m_duration);
220 //convert from 100 nanosecond to milisecond
221 durationUpdate(qint64(m_duration / 10000));
222 setupPlaybackTopology(mediaSource, sourcePD.Get());
224 } else {
225 changeStatus(QMediaPlayer::InvalidMedia);
226 error(QMediaPlayer::ResourceError, tr("Cannot create presentation descriptor."), true);
227 }
228}
229
230bool MFPlayerSession::getStreamInfo(IMFStreamDescriptor *stream,
231 MFPlayerSession::MediaType *type,
232 QString *name,
233 QString *language,
234 GUID *format) const
235{
236 if (!stream || !type || !name || !language || !format)
237 return false;
238
239 *type = Unknown;
240 *name = QString();
241 *language = QString();
242
243 ComPtr<IMFMediaTypeHandler> typeHandler;
244
245 if (SUCCEEDED(stream->GetMediaTypeHandler(&typeHandler))) {
246
247 UINT32 len = 0;
248 if (SUCCEEDED(stream->GetStringLength(MF_SD_STREAM_NAME, &len)) && len > 0) {
249 WCHAR *wstr = new WCHAR[len+1];
250 if (SUCCEEDED(stream->GetString(MF_SD_STREAM_NAME, wstr, len + 1, &len))) {
251 *name = QString::fromUtf16(reinterpret_cast<const char16_t *>(wstr));
252 }
253 delete []wstr;
254 }
255 if (SUCCEEDED(stream->GetStringLength(MF_SD_LANGUAGE, &len)) && len > 0) {
256 WCHAR *wstr = new WCHAR[len+1];
257 if (SUCCEEDED(stream->GetString(MF_SD_LANGUAGE, wstr, len + 1, &len))) {
258 *language = QString::fromUtf16(reinterpret_cast<const char16_t *>(wstr));
259 }
260 delete []wstr;
261 }
262
263 GUID guidMajorType;
264 if (SUCCEEDED(typeHandler->GetMajorType(&guidMajorType))) {
265 if (guidMajorType == MFMediaType_Audio)
266 *type = Audio;
267 else if (guidMajorType == MFMediaType_Video)
268 *type = Video;
269 }
270
271 ComPtr<IMFMediaType> mediaType;
272 if (SUCCEEDED(typeHandler->GetCurrentMediaType(&mediaType))) {
273 mediaType->GetGUID(MF_MT_SUBTYPE, format);
274 }
275 }
276
277 return *type != Unknown;
278}
279
280void MFPlayerSession::setupPlaybackTopology(IMFMediaSource *source, IMFPresentationDescriptor *sourcePD)
281{
282 HRESULT hr = S_OK;
283 // Get the number of streams in the media source.
284 DWORD cSourceStreams = 0;
285 hr = sourcePD->GetStreamDescriptorCount(&cSourceStreams);
286 if (FAILED(hr)) {
287 changeStatus(QMediaPlayer::InvalidMedia);
288 error(QMediaPlayer::ResourceError, tr("Failed to get stream count."), true);
289 return;
290 }
291
292 ComPtr<IMFTopology> topology;
293 hr = MFCreateTopology(&topology);
294 if (FAILED(hr)) {
295 changeStatus(QMediaPlayer::InvalidMedia);
296 error(QMediaPlayer::ResourceError, tr("Failed to create topology."), true);
297 return;
298 }
299
300 // For each stream, create the topology nodes and add them to the topology.
301 DWORD succeededCount = 0;
302 for (DWORD i = 0; i < cSourceStreams; i++) {
303 BOOL selected = FALSE;
304 bool streamAdded = false;
305 ComPtr<IMFStreamDescriptor> streamDesc;
306
307 HRESULT hr = sourcePD->GetStreamDescriptorByIndex(i, &selected, &streamDesc);
308 if (SUCCEEDED(hr)) {
309 // The media might have multiple audio and video streams,
310 // only use one of each kind, and only if it is selected by default.
311 MediaType mediaType = Unknown;
312 QString streamName;
313 QString streamLanguage;
314 GUID format = GUID_NULL;
315
316 if (getStreamInfo(streamDesc.Get(), &mediaType, &streamName, &streamLanguage,
317 &format)) {
318
319 QPlatformMediaPlayer::TrackType trackType = (mediaType == Audio) ?
320 QPlatformMediaPlayer::AudioStream : QPlatformMediaPlayer::VideoStream;
321
322 QLocale::Language lang = streamLanguage.isEmpty() ?
323 QLocale::Language::AnyLanguage : QLocale(streamLanguage).language();
324
325 QMediaMetaData metaData;
326 metaData.insert(QMediaMetaData::Title, streamName);
327 metaData.insert(QMediaMetaData::Language, lang);
328
329 m_trackInfo[trackType].metaData.append(metaData);
330 m_trackInfo[trackType].nativeIndexes.append(i);
331 m_trackInfo[trackType].format = format;
332
333 if (((m_mediaTypes & mediaType) == 0) && selected) { // Check if this type isn't already added
334 ComPtr<IMFTopologyNode> sourceNode =
335 addSourceNode(topology.Get(), source, sourcePD, streamDesc.Get());
336 if (sourceNode) {
337 ComPtr<IMFTopologyNode> outputNode =
338 addOutputNode(mediaType, topology.Get(), 0);
339 if (outputNode) {
340 sourceNode->GetTopoNodeID(&m_trackInfo[trackType].sourceNodeId);
341 outputNode->GetTopoNodeID(&m_trackInfo[trackType].outputNodeId);
342
343 hr = sourceNode->ConnectOutput(0, outputNode.Get(), 0);
344
345 if (FAILED(hr)) {
346 error(QMediaPlayer::FormatError, tr("Unable to play any stream."), false);
347 } else {
348 m_trackInfo[trackType].currentIndex = m_trackInfo[trackType].nativeIndexes.count() - 1;
349 streamAdded = true;
350 succeededCount++;
351 m_mediaTypes |= mediaType;
352 switch (mediaType) {
353 case Audio:
355 break;
356 case Video:
358 break;
359 default:
360 break;
361 }
362 }
363 } else {
364 // remove the source node if the output node cannot be created
365 topology->RemoveNode(sourceNode.Get());
366 }
367 }
368 }
369 }
370
371 if (selected && !streamAdded)
372 sourcePD->DeselectStream(i);
373 }
374 }
375
376 if (succeededCount == 0) {
377 changeStatus(QMediaPlayer::InvalidMedia);
378 error(QMediaPlayer::ResourceError, tr("Unable to play."), true);
379 } else {
380 if (m_trackInfo[QPlatformMediaPlayer::VideoStream].outputNodeId != TOPOID(-1))
381 topology = insertMFT(topology, m_trackInfo[QPlatformMediaPlayer::VideoStream].outputNodeId);
382
383 hr = m_session->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE, topology.Get());
384 if (SUCCEEDED(hr)) {
385 m_updatingTopology = true;
386 } else {
387 changeStatus(QMediaPlayer::InvalidMedia);
388 error(QMediaPlayer::ResourceError, tr("Failed to set topology."), true);
389 }
390 }
391}
392
393ComPtr<IMFTopologyNode> MFPlayerSession::addSourceNode(IMFTopology *topology,
394 IMFMediaSource *source,
395 IMFPresentationDescriptor *presentationDesc,
396 IMFStreamDescriptor *streamDesc)
397{
398 ComPtr<IMFTopologyNode> node;
399 HRESULT hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &node);
400 if (SUCCEEDED(hr)) {
401 hr = node->SetUnknown(MF_TOPONODE_SOURCE, source);
402 if (SUCCEEDED(hr)) {
403 hr = node->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, presentationDesc);
404 if (SUCCEEDED(hr)) {
405 hr = node->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, streamDesc);
406 if (SUCCEEDED(hr)) {
407 hr = topology->AddNode(node.Get());
408 if (SUCCEEDED(hr))
409 return node;
410 }
411 }
412 }
413 }
414 return NULL;
415}
416
417ComPtr<IMFTopologyNode> MFPlayerSession::addOutputNode(MediaType mediaType, IMFTopology *topology,
418 DWORD sinkID)
419{
420 ComPtr<IMFTopologyNode> node;
421 if (FAILED(MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &node)))
422 return NULL;
423
424 ComPtr<IMFActivate> activate;
425 if (mediaType == Audio) {
426 if (m_audioOutput) {
427 auto id = m_audioOutput->device.id();
428 if (id.isEmpty()) {
429 qInfo() << "No audio output";
430 return NULL;
431 }
432
433 HRESULT hr = MFCreateAudioRendererActivate(&activate);
434 if (FAILED(hr)) {
435 qWarning() << "Failed to create audio renderer activate";
436 return NULL;
437 }
438
439 QString s = QString::fromUtf8(id);
440 hr = activate->SetString(MF_AUDIO_RENDERER_ATTRIBUTE_ENDPOINT_ID, (LPCWSTR)s.utf16());
441 if (FAILED(hr)) {
442 qWarning() << "Failed to set attribute for audio device"
443 << m_audioOutput->device.description();
444 return NULL;
445 }
446 }
447 } else if (mediaType == Video) {
448 activate = m_videoRendererControl->createActivate();
449
450 QSize resolution = m_metaData.value(QMediaMetaData::Resolution).toSize();
451
452 if (resolution.isValid())
453 m_videoRendererControl->setCropRect(QRect(QPoint(), resolution));
454
455 } else {
456 // Unknown stream type.
457 error(QMediaPlayer::FormatError, tr("Unknown stream type."), false);
458 }
459
460 if (!activate || FAILED(node->SetObject(activate.Get()))
461 || FAILED(node->SetUINT32(MF_TOPONODE_STREAMID, sinkID))
462 || FAILED(node->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE))
463 || FAILED(topology->AddNode(node.Get()))) {
464 node.Reset();
465 }
466
467 if (activate && mediaType == Audio)
468 activate.Reset();
469
470 return node;
471}
472
473// BindOutputNode
474// Sets the IMFStreamSink pointer on an output node.
475// IMFActivate pointer in the output node must be converted to an
476// IMFStreamSink pointer before the topology loader resolves the topology.
477HRESULT BindOutputNode(IMFTopologyNode *pNode)
478{
479 ComPtr<IUnknown> nodeObject;
480 ComPtr<IMFActivate> activate;
481 ComPtr<IMFStreamSink> stream;
482 ComPtr<IMFMediaSink> sink;
483
484 HRESULT hr = pNode->GetObject(&nodeObject);
485 if (FAILED(hr))
486 return hr;
487
488 hr = nodeObject->QueryInterface(IID_PPV_ARGS(&activate));
489 if (SUCCEEDED(hr)) {
490 DWORD dwStreamID = 0;
491
492 // Try to create the media sink.
493 hr = activate->ActivateObject(IID_PPV_ARGS(&sink));
494 if (SUCCEEDED(hr))
495 dwStreamID = MFGetAttributeUINT32(pNode, MF_TOPONODE_STREAMID, 0);
496
497 if (SUCCEEDED(hr)) {
498 // First check if the media sink already has a stream sink with the requested ID.
499 hr = sink->GetStreamSinkById(dwStreamID, &stream);
500 if (FAILED(hr)) {
501 // Create the stream sink.
502 hr = sink->AddStreamSink(dwStreamID, NULL, &stream);
503 }
504 }
505
506 // Replace the node's object pointer with the stream sink.
507 if (SUCCEEDED(hr)) {
508 hr = pNode->SetObject(stream.Get());
509 }
510 } else {
511 hr = nodeObject->QueryInterface(IID_PPV_ARGS(&stream));
512 }
513
514 return hr;
515}
516
517// BindOutputNodes
518// Sets the IMFStreamSink pointers on all of the output nodes in a topology.
519HRESULT BindOutputNodes(IMFTopology *pTopology)
520{
521 ComPtr<IMFCollection> collection;
522
523 // Get the collection of output nodes.
524 HRESULT hr = pTopology->GetOutputNodeCollection(&collection);
525
526 // Enumerate all of the nodes in the collection.
527 if (SUCCEEDED(hr)) {
528 DWORD cNodes;
529 hr = collection->GetElementCount(&cNodes);
530
531 if (SUCCEEDED(hr)) {
532 for (DWORD i = 0; i < cNodes; i++) {
533 ComPtr<IUnknown> element;
534 hr = collection->GetElement(i, &element);
535 if (FAILED(hr))
536 break;
537
538 ComPtr<IMFTopologyNode> node;
539 hr = element->QueryInterface(IID_IMFTopologyNode, &node);
540 if (FAILED(hr))
541 break;
542
543 // Bind this node.
544 hr = BindOutputNode(node.Get());
545 if (FAILED(hr))
546 break;
547 }
548 }
549 }
550
551 return hr;
552}
553
554// This method binds output nodes to complete the topology,
555// then loads the topology and inserts MFT between the output node
556// and a filter connected to the output node.
557ComPtr<IMFTopology> MFPlayerSession::insertMFT(const ComPtr<IMFTopology> &topology,
558 TOPOID outputNodeId)
559{
560 bool isNewTopology = false;
561
562 ComPtr<IMFTopoLoader> topoLoader;
563 ComPtr<IMFTopology> resolvedTopology;
564 ComPtr<IMFCollection> outputNodes;
565
566 do {
567 if (FAILED(BindOutputNodes(topology.Get())))
568 break;
569
570 if (FAILED(MFCreateTopoLoader(&topoLoader)))
571 break;
572
573 if (FAILED(topoLoader->Load(topology.Get(), &resolvedTopology, NULL))) {
574 // Topology could not be resolved, adding ourselves a color converter
575 // to the topology might solve the problem
576 insertColorConverter(topology.Get(), outputNodeId);
577 if (FAILED(topoLoader->Load(topology.Get(), &resolvedTopology, NULL)))
578 break;
579 }
580
581 if (insertResizer(resolvedTopology.Get()))
582 isNewTopology = true;
583 } while (false);
584
585 if (isNewTopology) {
586 return resolvedTopology;
587 }
588
589 return topology;
590}
591
592// This method checks if the topology contains a color converter transform (CColorConvertDMO),
593// if it does it inserts a resizer transform (CResizerDMO) to handle dynamic frame size change
594// of the video stream.
595// Returns true if it inserted a resizer
596bool MFPlayerSession::insertResizer(IMFTopology *topology)
597{
598 bool inserted = false;
599 WORD elementCount = 0;
600 ComPtr<IMFTopologyNode> node;
601 ComPtr<IUnknown> object;
602 ComPtr<IWMColorConvProps> colorConv;
603 ComPtr<IMFTransform> resizer;
604 ComPtr<IMFTopologyNode> resizerNode;
605 ComPtr<IMFTopologyNode> inputNode;
606
607 HRESULT hr = topology->GetNodeCount(&elementCount);
608 if (FAILED(hr))
609 return false;
610
611 for (WORD i = 0; i < elementCount; ++i) {
612 node.Reset();
613 object.Reset();
614
615 if (FAILED(topology->GetNode(i, &node)))
616 break;
617
618 MF_TOPOLOGY_TYPE nodeType;
619 if (FAILED(node->GetNodeType(&nodeType)))
620 break;
621
622 if (nodeType != MF_TOPOLOGY_TRANSFORM_NODE)
623 continue;
624
625 if (FAILED(node->GetObject(&object)))
626 break;
627
628 if (FAILED(object->QueryInterface(IID_PPV_ARGS(&colorConv))))
629 continue;
630
631 if (FAILED(CoCreateInstance(CLSID_CResizerDMO, NULL, CLSCTX_INPROC_SERVER, IID_IMFTransform,
632 &resizer)))
633 break;
634
635 if (FAILED(MFCreateTopologyNode(MF_TOPOLOGY_TRANSFORM_NODE, &resizerNode)))
636 break;
637
638 if (FAILED(resizerNode->SetObject(resizer.Get())))
639 break;
640
641 if (FAILED(topology->AddNode(resizerNode.Get())))
642 break;
643
644 DWORD outputIndex = 0;
645 if (FAILED(node->GetInput(0, &inputNode, &outputIndex))) {
646 topology->RemoveNode(resizerNode.Get());
647 break;
648 }
649
650 if (FAILED(inputNode->ConnectOutput(0, resizerNode.Get(), 0))) {
651 topology->RemoveNode(resizerNode.Get());
652 break;
653 }
654
655 if (FAILED(resizerNode->ConnectOutput(0, node.Get(), 0))) {
656 inputNode->ConnectOutput(0, node.Get(), 0);
657 topology->RemoveNode(resizerNode.Get());
658 break;
659 }
660
661 inserted = true;
662 break;
663 }
664
665 return inserted;
666}
667
668// This method inserts a color converter (CColorConvertDMO) in the topology,
669// typically to convert to RGB format.
670// Usually this converter is automatically inserted when the topology is resolved but
671// for some reason it fails to do so in some cases, we then do it ourselves.
672void MFPlayerSession::insertColorConverter(IMFTopology *topology, TOPOID outputNodeId)
673{
674 ComPtr<IMFCollection> outputNodes;
675
676 if (FAILED(topology->GetOutputNodeCollection(&outputNodes)))
677 return;
678
679 DWORD elementCount = 0;
680 if (FAILED(outputNodes->GetElementCount(&elementCount)))
681 return;
682
683 for (DWORD n = 0; n < elementCount; n++) {
684 ComPtr<IUnknown> element;
685 ComPtr<IMFTopologyNode> node;
686 ComPtr<IMFTopologyNode> inputNode;
687 ComPtr<IMFTopologyNode> mftNode;
688 ComPtr<IMFTransform> converter;
689
690 do {
691 if (FAILED(outputNodes->GetElement(n, &element)))
692 break;
693
694 if (FAILED(element->QueryInterface(IID_IMFTopologyNode, &node)))
695 break;
696
697 TOPOID id;
698 if (FAILED(node->GetTopoNodeID(&id)))
699 break;
700
701 if (id != outputNodeId)
702 break;
703
704 DWORD outputIndex = 0;
705 if (FAILED(node->GetInput(0, &inputNode, &outputIndex)))
706 break;
707
708 if (FAILED(MFCreateTopologyNode(MF_TOPOLOGY_TRANSFORM_NODE, &mftNode)))
709 break;
710
711 if (FAILED(CoCreateInstance(CLSID_CColorConvertDMO, NULL, CLSCTX_INPROC_SERVER,
712 IID_IMFTransform, &converter)))
713 break;
714
715 if (FAILED(mftNode->SetObject(converter.Get())))
716 break;
717
718 if (FAILED(topology->AddNode(mftNode.Get())))
719 break;
720
721 if (FAILED(inputNode->ConnectOutput(0, mftNode.Get(), 0)))
722 break;
723
724 if (FAILED(mftNode->ConnectOutput(0, node.Get(), 0)))
725 break;
726
727 } while (false);
728 }
729}
730
731void MFPlayerSession::stop(bool immediate)
732{
733#ifdef DEBUG_MEDIAFOUNDATION
734 qDebug() << "stop";
735#endif
736 if (!immediate && m_pendingState != NoPending) {
737 m_request.setCommand(CmdStop);
738 } else {
739 if (m_state.command == CmdStop)
740 return;
741
742 if (m_scrubbing)
743 scrub(false);
744
745 if (SUCCEEDED(m_session->Stop())) {
746
747 m_state.setCommand(CmdStop);
748 m_pendingState = CmdPending;
749 if (m_status != QMediaPlayer::EndOfMedia) {
750 m_position = 0;
751 positionChanged(0);
752 }
753 } else {
754 error(QMediaPlayer::ResourceError, tr("Failed to stop."), true);
755 }
756 }
757}
758
760{
761 if (status() == QMediaPlayer::LoadedMedia && m_updateRoutingOnStart) {
762 m_updateRoutingOnStart = false;
764 }
765
766 if (m_status == QMediaPlayer::EndOfMedia) {
767 m_position = 0; // restart from the beginning
768 positionChanged(0);
769 }
770
771#ifdef DEBUG_MEDIAFOUNDATION
772 qDebug() << "start";
773#endif
774
775 if (m_pendingState != NoPending) {
776 m_request.setCommand(CmdStart);
777 } else {
778 if (m_state.command == CmdStart)
779 return;
780
781 if (m_scrubbing) {
782 scrub(false);
783 m_position = position() * 10000;
784 }
785
786 if (m_restorePosition >= 0) {
787 m_position = m_restorePosition;
788 if (!m_updatingTopology)
789 m_restorePosition = -1;
790 }
791
792 PROPVARIANT varStart;
793 InitPropVariantFromInt64(m_position, &varStart);
794
795 if (SUCCEEDED(m_session->Start(&GUID_NULL, &varStart))) {
796 m_state.setCommand(CmdStart);
797 m_pendingState = CmdPending;
798 } else {
799 error(QMediaPlayer::ResourceError, tr("failed to start playback"), true);
800 }
801 PropVariantClear(&varStart);
802 }
803}
804
806{
807#ifdef DEBUG_MEDIAFOUNDATION
808 qDebug() << "pause";
809#endif
810 if (m_pendingState != NoPending) {
811 m_request.setCommand(CmdPause);
812 } else {
813 if (m_state.command == CmdPause)
814 return;
815
816 if (SUCCEEDED(m_session->Pause())) {
817 m_state.setCommand(CmdPause);
818 m_pendingState = CmdPending;
819 } else {
820 error(QMediaPlayer::ResourceError, tr("Failed to pause."), false);
821 }
822 if (m_status == QMediaPlayer::EndOfMedia) {
823 setPosition(0);
824 positionChanged(0);
825 }
826 }
827}
828
829void MFPlayerSession::changeStatus(QMediaPlayer::MediaStatus newStatus)
830{
831 if (m_status == newStatus)
832 return;
833#ifdef DEBUG_MEDIAFOUNDATION
834 qDebug() << "MFPlayerSession::changeStatus" << newStatus;
835#endif
836 m_status = newStatus;
838}
839
840QMediaPlayer::MediaStatus MFPlayerSession::status() const
841{
842 return m_status;
843}
844
845bool MFPlayerSession::createSession()
846{
847 close();
848
849 Q_ASSERT(m_session == NULL);
850
851 HRESULT hr = MFCreateMediaSession(NULL, &m_session);
852 if (FAILED(hr)) {
853 changeStatus(QMediaPlayer::InvalidMedia);
854 error(QMediaPlayer::ResourceError, tr("Unable to create mediasession."), true);
855 return false;
856 }
857
858 m_hCloseEvent = EventHandle{ CreateEvent(NULL, FALSE, FALSE, NULL) };
859
860 hr = m_session->BeginGetEvent(this, m_session.Get());
861 if (FAILED(hr)) {
862 changeStatus(QMediaPlayer::InvalidMedia);
863 error(QMediaPlayer::ResourceError, tr("Unable to pull session events."), false);
864 close();
865 return false;
866 }
867
868 m_sourceResolver = makeComObject<SourceResolver>();
869 QObject::connect(m_sourceResolver.Get(), &SourceResolver::mediaSourceReady, this,
870 &MFPlayerSession::handleMediaSourceReady);
871 QObject::connect(m_sourceResolver.Get(), &SourceResolver::error, this,
872 &MFPlayerSession::handleSourceError);
873
874 m_position = 0;
875 return true;
876}
877
879{
880 if (m_request.command == CmdSeek || m_request.command == CmdSeekResume)
881 return m_request.start;
882
883 if (m_pendingState == SeekPending)
884 return m_state.start;
885
886 if (m_state.command == CmdStop)
887 return m_position / 10000;
888
889 if (m_presentationClock) {
890 MFTIME time, sysTime;
891 if (FAILED(m_presentationClock->GetCorrelatedTime(0, &time, &sysTime)))
892 return m_position / 10000;
893 return qint64(time / 10000);
894 }
895 return m_position / 10000;
896}
897
898void MFPlayerSession::setPosition(qint64 position)
899{
900#ifdef DEBUG_MEDIAFOUNDATION
901 qDebug() << "setPosition";
902#endif
903 if (m_pendingState != NoPending) {
904 m_request.setCommand(CmdSeek);
905 m_request.start = position;
906 } else {
907 setPositionInternal(position, CmdNone);
908 }
909}
910
911void MFPlayerSession::setPositionInternal(qint64 position, Command requestCmd)
912{
913 if (m_status == QMediaPlayer::EndOfMedia)
914 changeStatus(QMediaPlayer::LoadedMedia);
915 if (m_state.command == CmdStop && requestCmd != CmdSeekResume) {
916 m_position = position * 10000;
917 // Even though the position is not actually set on the session yet,
918 // report it to have changed anyway for UI controls to be updated
919 positionChanged(this->position());
920 return;
921 }
922
923 if (m_state.command == CmdPause)
924 scrub(true);
925
926#ifdef DEBUG_MEDIAFOUNDATION
927 qDebug() << "setPositionInternal";
928#endif
929
930 PROPVARIANT varStart;
931 varStart.vt = VT_I8;
932 varStart.hVal.QuadPart = LONGLONG(position * 10000);
933 if (SUCCEEDED(m_session->Start(NULL, &varStart))) {
934 PropVariantClear(&varStart);
935 // Store the pending state.
936 m_state.setCommand(CmdStart);
937 m_state.start = position;
938 m_pendingState = SeekPending;
939 } else {
940 error(QMediaPlayer::ResourceError, tr("Failed to seek."), true);
941 }
942}
943
945{
946 if (m_scrubbing)
947 return m_restoreRate;
948 return m_state.rate;
949}
950
952{
953 if (m_scrubbing) {
954 m_restoreRate = rate;
955 playbackRateChanged(rate);
956 return;
957 }
958 setPlaybackRateInternal(rate);
959}
960
961void MFPlayerSession::setPlaybackRateInternal(qreal rate)
962{
963 if (rate == m_request.rate)
964 return;
965
966 m_pendingRate = rate;
967 if (!m_rateSupport)
968 return;
969
970#ifdef DEBUG_MEDIAFOUNDATION
971 qDebug() << "setPlaybackRate";
972#endif
973 BOOL isThin = FALSE;
974
975 //from MSDN http://msdn.microsoft.com/en-us/library/aa965220%28v=vs.85%29.aspx
976 //Thinning applies primarily to video streams.
977 //In thinned mode, the source drops delta frames and deliver only key frames.
978 //At very high playback rates, the source might skip some key frames (for example, deliver every other key frame).
979
980 if (FAILED(m_rateSupport->IsRateSupported(FALSE, rate, NULL))) {
981 isThin = TRUE;
982 if (FAILED(m_rateSupport->IsRateSupported(isThin, rate, NULL))) {
983 qWarning() << "unable to set playbackrate = " << rate;
984 m_pendingRate = m_request.rate = m_state.rate;
985 return;
986 }
987 }
988 if (m_pendingState != NoPending) {
989 m_request.rate = rate;
990 m_request.isThin = isThin;
991 // Remember the current transport state (play, paused, etc), so that we
992 // can restore it after the rate change, if necessary. However, if
993 // anothercommand is already pending, that one takes precedent.
994 if (m_request.command == CmdNone)
995 m_request.setCommand(m_state.command);
996 } else {
997 //No pending operation. Commit the new rate.
998 commitRateChange(rate, isThin);
999 }
1000}
1001
1002void MFPlayerSession::commitRateChange(qreal rate, BOOL isThin)
1003{
1004#ifdef DEBUG_MEDIAFOUNDATION
1005 qDebug() << "commitRateChange";
1006#endif
1007 Q_ASSERT(m_pendingState == NoPending);
1008 MFTIME hnsSystemTime = 0;
1009 MFTIME hnsClockTime = 0;
1010 Command cmdNow = m_state.command;
1011 bool resetPosition = false;
1012 // Allowed rate transitions:
1013 // Positive <-> negative: Stopped
1014 // Negative <-> zero: Stopped
1015 // Postive <-> zero: Paused or stopped
1016 if ((rate > 0 && m_state.rate <= 0) || (rate < 0 && m_state.rate >= 0)) {
1017 if (cmdNow == CmdStart) {
1018 // Get the current clock position. This will be the restart time.
1019 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1020 Q_ASSERT(hnsSystemTime != 0);
1021
1022 if (rate < 0 || m_state.rate < 0)
1023 m_request.setCommand(CmdSeekResume);
1024 else if (isThin || m_state.isThin)
1025 m_request.setCommand(CmdStartAndSeek);
1026 else
1027 m_request.setCommand(CmdStart);
1028
1029 // We need to stop only when dealing with negative rates
1030 if (rate >= 0 && m_state.rate >= 0)
1031 pause();
1032 else
1033 stop();
1034
1035 // If we deal with negative rates, we stopped the session and consequently
1036 // reset the position to zero. We then need to resume to the current position.
1037 m_request.start = hnsClockTime / 10000;
1038 } else if (cmdNow == CmdPause) {
1039 if (rate < 0 || m_state.rate < 0) {
1040 // The current state is paused.
1041 // For this rate change, the session must be stopped. However, the
1042 // session cannot transition back from stopped to paused.
1043 // Therefore, this rate transition is not supported while paused.
1044 qWarning() << "Unable to change rate from positive to negative or vice versa in paused state";
1045 rate = m_state.rate;
1046 isThin = m_state.isThin;
1047 goto done;
1048 }
1049
1050 // This happens when resuming playback after scrubbing in pause mode.
1051 // This transition requires the session to be paused. Even though our
1052 // internal state is set to paused, the session might not be so we need
1053 // to enforce it
1054 if (rate > 0 && m_state.rate == 0) {
1055 m_state.setCommand(CmdNone);
1056 pause();
1057 }
1058 }
1059 } else if (rate == 0 && m_state.rate > 0) {
1060 if (cmdNow != CmdPause) {
1061 // Transition to paused.
1062 // This transisition requires the paused state.
1063 // Pause and set the rate.
1064 pause();
1065
1066 // Request: Switch back to current state.
1067 m_request.setCommand(cmdNow);
1068 }
1069 } else if (rate == 0 && m_state.rate < 0) {
1070 // Changing rate from negative to zero requires to stop the session
1071 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1072
1073 m_request.setCommand(CmdSeekResume);
1074
1075 stop();
1076
1077 // Resume to the current position (stop() will reset the position to 0)
1078 m_request.start = hnsClockTime / 10000;
1079 } else if (!isThin && m_state.isThin) {
1080 if (cmdNow == CmdStart) {
1081 // When thinning, only key frames are read and presented. Going back
1082 // to normal playback requires to reset the current position to force
1083 // the pipeline to decode the actual frame at the current position
1084 // (which might be earlier than the last decoded key frame)
1085 resetPosition = true;
1086 } else if (cmdNow == CmdPause) {
1087 // If paused, don't reset the position until we resume, otherwise
1088 // a new frame will be rendered
1089 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1090 m_request.setCommand(CmdSeekResume);
1091 m_request.start = hnsClockTime / 10000;
1092 }
1093
1094 }
1095
1096 // Set the rate.
1097 if (FAILED(m_rateControl->SetRate(isThin, rate))) {
1098 qWarning() << "failed to set playbackrate = " << rate;
1099 rate = m_state.rate;
1100 isThin = m_state.isThin;
1101 goto done;
1102 }
1103
1104 if (resetPosition) {
1105 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1106 setPosition(hnsClockTime / 10000);
1107 }
1108
1109done:
1110 // Adjust our current rate and requested rate.
1111 m_pendingRate = m_request.rate = m_state.rate = rate;
1112 if (rate != 0)
1113 m_state.isThin = isThin;
1114 playbackRateChanged(rate);
1115}
1116
1117void MFPlayerSession::scrub(bool enableScrub)
1118{
1119 if (m_scrubbing == enableScrub)
1120 return;
1121
1122 m_scrubbing = enableScrub;
1123
1124 if (!canScrub()) {
1125 if (!enableScrub)
1126 m_pendingRate = m_restoreRate;
1127 return;
1128 }
1129
1130 if (enableScrub) {
1131 // Enter scrubbing mode. Cache the rate.
1132 m_restoreRate = m_request.rate;
1133 setPlaybackRateInternal(0.0f);
1134 } else {
1135 // Leaving scrubbing mode. Restore the old rate.
1136 setPlaybackRateInternal(m_restoreRate);
1137 }
1138}
1139
1140void MFPlayerSession::setVolume(float volume)
1141{
1142 if (m_volume == volume)
1143 return;
1144 m_volume = volume;
1145
1146 if (!m_muted)
1147 setVolumeInternal(volume);
1148}
1149
1150void MFPlayerSession::setMuted(bool muted)
1151{
1152 if (m_muted == muted)
1153 return;
1154 m_muted = muted;
1155
1156 setVolumeInternal(muted ? 0 : m_volume);
1157}
1158
1159void MFPlayerSession::setVolumeInternal(float volume)
1160{
1161 if (m_volumeControl) {
1162 quint32 channelCount = 0;
1163 if (!SUCCEEDED(m_volumeControl->GetChannelCount(&channelCount))
1164 || channelCount == 0)
1165 return;
1166
1167 for (quint32 i = 0; i < channelCount; ++i)
1168 m_volumeControl->SetChannelVolume(i, volume);
1169 }
1170}
1171
1173{
1174 if (!m_netsourceStatistics)
1175 return 0;
1176 PROPVARIANT var;
1177 PropVariantInit(&var);
1178 PROPERTYKEY key;
1179 key.fmtid = MFNETSOURCE_STATISTICS;
1180 key.pid = MFNETSOURCE_BUFFERPROGRESS_ID;
1181 int progress = -1;
1182 // GetValue returns S_FALSE if the property is not available, which has
1183 // a value > 0. We therefore can't use the SUCCEEDED macro here.
1184 if (m_netsourceStatistics->GetValue(key, &var) == S_OK) {
1185 progress = var.lVal;
1186 PropVariantClear(&var);
1187 }
1188
1189#ifdef DEBUG_MEDIAFOUNDATION
1190 qDebug() << "bufferProgress: progress = " << progress;
1191#endif
1192
1193 return progress/100.;
1194}
1195
1197{
1198 // defaults to the whole media
1199 qint64 start = 0;
1200 qint64 end = qint64(m_duration / 10000);
1201
1202 if (m_netsourceStatistics) {
1203 PROPVARIANT var;
1204 PropVariantInit(&var);
1205 PROPERTYKEY key;
1206 key.fmtid = MFNETSOURCE_STATISTICS;
1207 key.pid = MFNETSOURCE_SEEKRANGESTART_ID;
1208 // GetValue returns S_FALSE if the property is not available, which has
1209 // a value > 0. We therefore can't use the SUCCEEDED macro here.
1210 if (m_netsourceStatistics->GetValue(key, &var) == S_OK) {
1211 start = qint64(var.uhVal.QuadPart / 10000);
1212 PropVariantClear(&var);
1213 PropVariantInit(&var);
1214 key.pid = MFNETSOURCE_SEEKRANGEEND_ID;
1215 if (m_netsourceStatistics->GetValue(key, &var) == S_OK) {
1216 end = qint64(var.uhVal.QuadPart / 10000);
1217 PropVariantClear(&var);
1218 }
1219 }
1220 }
1221
1222 return QMediaTimeRange(start, end);
1223}
1224
1225HRESULT MFPlayerSession::QueryInterface(REFIID riid, void** ppvObject)
1226{
1227 if (!ppvObject)
1228 return E_POINTER;
1229 if (riid == IID_IMFAsyncCallback) {
1230 *ppvObject = static_cast<IMFAsyncCallback*>(this);
1231 } else if (riid == IID_IUnknown) {
1232 *ppvObject = static_cast<IUnknown*>(this);
1233 } else {
1234 *ppvObject = NULL;
1235 return E_NOINTERFACE;
1236 }
1237 return S_OK;
1238}
1239
1240ULONG MFPlayerSession::AddRef(void)
1241{
1242 return InterlockedIncrement(&m_cRef);
1243}
1244
1245ULONG MFPlayerSession::Release(void)
1246{
1247 LONG cRef = InterlockedDecrement(&m_cRef);
1248 if (cRef == 0) {
1249 deleteLater();
1250
1251 // In rare cases the session has queued events to be run between deleteLater and deleting,
1252 // so we set the parent control to nullptr in order to prevent crashes in the cases.
1253 m_playerControl = nullptr;
1254 }
1255 return cRef;
1256}
1257
1258HRESULT MFPlayerSession::Invoke(IMFAsyncResult *pResult)
1259{
1260 if (pResult->GetStateNoAddRef() != m_session.Get())
1261 return S_OK;
1262
1263 ComPtr<IMFMediaEvent> pEvent;
1264 // Get the event from the event queue.
1265 HRESULT hr = m_session->EndGetEvent(pResult, &pEvent);
1266 if (FAILED(hr)) {
1267 return S_OK;
1268 }
1269
1270 MediaEventType meType = MEUnknown;
1271 hr = pEvent->GetType(&meType);
1272 if (FAILED(hr)) {
1273 return S_OK;
1274 }
1275
1276 if (meType == MESessionClosed) {
1277 SetEvent(m_hCloseEvent.get());
1278 return S_OK;
1279 } else {
1280 hr = m_session->BeginGetEvent(this, m_session.Get());
1281 if (FAILED(hr)) {
1282 return S_OK;
1283 }
1284 }
1285
1286 if (!m_closing) {
1287 emit sessionEvent(pEvent);
1288 }
1289 return S_OK;
1290}
1291
1292void MFPlayerSession::handleSessionEvent(const ComPtr<IMFMediaEvent> &sessionEvent)
1293{
1294 HRESULT hrStatus = S_OK;
1295 HRESULT hr = sessionEvent->GetStatus(&hrStatus);
1296 if (FAILED(hr) || !m_session) {
1297 return;
1298 }
1299
1300 MediaEventType meType = MEUnknown;
1301 hr = sessionEvent->GetType(&meType);
1302#ifdef DEBUG_MEDIAFOUNDATION
1303 if (FAILED(hrStatus))
1304 qDebug() << "handleSessionEvent: MediaEventType = " << meType << "Failed";
1305 else
1306 qDebug() << "handleSessionEvent: MediaEventType = " << meType;
1307#endif
1308
1309 switch (meType) {
1310 case MENonFatalError: {
1311 PROPVARIANT var;
1312 PropVariantInit(&var);
1313 sessionEvent->GetValue(&var);
1314 qWarning() << "handleSessionEvent: non fatal error = " << var.ulVal;
1315 PropVariantClear(&var);
1316 error(QMediaPlayer::ResourceError, tr("Media session non-fatal error."), false);
1317 }
1318 break;
1319 case MESourceUnknown:
1320 changeStatus(QMediaPlayer::InvalidMedia);
1321 break;
1322 case MEError:
1323 if (hrStatus == MF_E_ALREADY_INITIALIZED) {
1324 // Workaround for a possible WMF issue that causes an error
1325 // with some specific videos, which play fine otherwise.
1326#ifdef DEBUG_MEDIAFOUNDATION
1327 qDebug() << "handleSessionEvent: ignoring MF_E_ALREADY_INITIALIZED";
1328#endif
1329 break;
1330 }
1331 changeStatus(QMediaPlayer::InvalidMedia);
1332 qWarning() << "handleSessionEvent: serious error = "
1333 << Qt::showbase << Qt::hex << Qt::uppercasedigits << static_cast<quint32>(hrStatus);
1334 switch (hrStatus) {
1335 case MF_E_NET_READ:
1336 error(QMediaPlayer::NetworkError, tr("Error reading from the network."), true);
1337 break;
1338 case MF_E_NET_WRITE:
1339 error(QMediaPlayer::NetworkError, tr("Error writing to the network."), true);
1340 break;
1341 case NS_E_FIREWALL:
1342 error(QMediaPlayer::NetworkError, tr("Network packets might be blocked by a firewall."), true);
1343 break;
1344 case MF_E_MEDIAPROC_WRONGSTATE:
1345 error(QMediaPlayer::ResourceError, tr("Media session state error."), true);
1346 break;
1347 case MF_E_INVALID_STREAM_DATA:
1348 error(QMediaPlayer::ResourceError, tr("Invalid stream data."), true);
1349 break;
1350 default:
1351 error(QMediaPlayer::ResourceError, tr("Media session serious error."), true);
1352 break;
1353 }
1354 break;
1355 case MESessionRateChanged:
1356 // If the rate change succeeded, we've already got the rate
1357 // cached. If it failed, try to get the actual rate.
1358 if (FAILED(hrStatus)) {
1359 PROPVARIANT var;
1360 PropVariantInit(&var);
1361 if (SUCCEEDED(sessionEvent->GetValue(&var)) && (var.vt == VT_R4)) {
1362 m_state.rate = var.fltVal;
1363 }
1364 playbackRateChanged(playbackRate());
1365 }
1366 break;
1367 case MESessionScrubSampleComplete :
1368 if (m_scrubbing)
1369 updatePendingCommands(CmdStart);
1370 break;
1371 case MESessionStarted:
1372 if (m_status == QMediaPlayer::EndOfMedia
1373 || m_status == QMediaPlayer::LoadedMedia) {
1374 // If the session started, then enough data is buffered to play
1375 changeStatus(QMediaPlayer::BufferedMedia);
1376 }
1377
1378 updatePendingCommands(CmdStart);
1379 // playback started, we can now set again the procAmpValues if they have been
1380 // changed previously (these are lost when loading a new media)
1381// if (m_playerService->videoWindowControl()) {
1382// m_playerService->videoWindowControl()->applyImageControls();
1383// }
1384 m_signalPositionChangeTimer.start();
1385 break;
1386 case MESessionStopped:
1387 if (m_status != QMediaPlayer::EndOfMedia) {
1388 m_position = 0;
1389
1390 // Reset to Loaded status unless we are loading a new media
1391 // or changing the playback rate to negative values (stop required)
1392 if (m_status != QMediaPlayer::LoadingMedia && m_request.command != CmdSeekResume)
1393 changeStatus(QMediaPlayer::LoadedMedia);
1394 }
1395 updatePendingCommands(CmdStop);
1396 m_signalPositionChangeTimer.stop();
1397 break;
1398 case MESessionPaused:
1399 m_position = position() * 10000;
1400 updatePendingCommands(CmdPause);
1401 m_signalPositionChangeTimer.stop();
1402 if (m_status == QMediaPlayer::LoadedMedia)
1403 setPosition(position());
1404 break;
1405 case MEReconnectStart:
1406#ifdef DEBUG_MEDIAFOUNDATION
1407 qDebug() << "MEReconnectStart" << ((hrStatus == S_OK) ? "OK" : "Failed");
1408#endif
1409 break;
1410 case MEReconnectEnd:
1411#ifdef DEBUG_MEDIAFOUNDATION
1412 qDebug() << "MEReconnectEnd" << ((hrStatus == S_OK) ? "OK" : "Failed");
1413#endif
1414 break;
1415 case MESessionTopologySet:
1416 if (FAILED(hrStatus)) {
1417 changeStatus(QMediaPlayer::InvalidMedia);
1418 error(QMediaPlayer::FormatError, tr("Unsupported media, a codec is missing."), true);
1419 } else {
1420 // Topology is resolved and successfuly set, this happens only after loading a new media.
1421 // Make sure we always start the media from the beginning
1422 m_lastPosition = -1;
1423 m_position = 0;
1424 positionChanged(0);
1425 changeStatus(QMediaPlayer::LoadedMedia);
1426 }
1427 break;
1428 }
1429
1430 if (FAILED(hrStatus)) {
1431 return;
1432 }
1433
1434 switch (meType) {
1435 case MEBufferingStarted:
1436 changeStatus(QMediaPlayer::StalledMedia);
1438 break;
1439 case MEBufferingStopped:
1440 changeStatus(QMediaPlayer::BufferedMedia);
1442 break;
1443 case MESessionEnded:
1444 m_pendingState = NoPending;
1445 m_state.command = CmdStop;
1446 m_state.prevCmd = CmdNone;
1447 m_request.command = CmdNone;
1448 m_request.prevCmd = CmdNone;
1449
1450 //keep reporting the final position after end of media
1451 m_position = qint64(m_duration);
1452 positionChanged(position());
1453
1454 changeStatus(QMediaPlayer::EndOfMedia);
1455 break;
1456 case MEEndOfPresentationSegment:
1457 break;
1458 case MESessionTopologyStatus: {
1459 UINT32 status;
1460 if (SUCCEEDED(sessionEvent->GetUINT32(MF_EVENT_TOPOLOGY_STATUS, &status))) {
1461 if (status == MF_TOPOSTATUS_READY) {
1462 ComPtr<IMFClock> clock;
1463 if (SUCCEEDED(m_session->GetClock(&clock))) {
1464 clock->QueryInterface(IID_IMFPresentationClock, &m_presentationClock);
1465 }
1466
1467 if (SUCCEEDED(MFGetService(m_session.Get(), MF_RATE_CONTROL_SERVICE,
1468 IID_PPV_ARGS(&m_rateControl)))) {
1469 if (SUCCEEDED(MFGetService(m_session.Get(), MF_RATE_CONTROL_SERVICE,
1470 IID_PPV_ARGS(&m_rateSupport)))) {
1471 if (SUCCEEDED(m_rateSupport->IsRateSupported(TRUE, 0, NULL)))
1472 m_canScrub = true;
1473 }
1474 BOOL isThin = FALSE;
1475 float rate = 1;
1476 if (SUCCEEDED(m_rateControl->GetRate(&isThin, &rate))) {
1477 if (m_pendingRate != rate) {
1478 m_state.rate = m_request.rate = rate;
1479 setPlaybackRate(m_pendingRate);
1480 }
1481 }
1482 }
1483 MFGetService(m_session.Get(), MFNETSOURCE_STATISTICS_SERVICE,
1484 IID_PPV_ARGS(&m_netsourceStatistics));
1485
1486 if (SUCCEEDED(MFGetService(m_session.Get(), MR_STREAM_VOLUME_SERVICE,
1487 IID_PPV_ARGS(&m_volumeControl))))
1488 setVolumeInternal(m_muted ? 0 : m_volume);
1489
1490 m_updatingTopology = false;
1491 stop();
1492 }
1493 }
1494 }
1495 break;
1496 default:
1497 break;
1498 }
1499}
1500
1501void MFPlayerSession::updatePendingCommands(Command command)
1502{
1503 positionChanged(position());
1504 if (m_state.command != command || m_pendingState == NoPending)
1505 return;
1506
1507 // Seek while paused completed
1508 if (m_pendingState == SeekPending && m_state.prevCmd == CmdPause) {
1509 m_pendingState = NoPending;
1510 // A seek operation actually restarts playback. If scrubbing is possible, playback rate
1511 // is set to 0.0 at this point and we just need to reset the current state to Pause.
1512 // If scrubbing is not possible, the playback rate was not changed and we explicitly need
1513 // to re-pause playback.
1514 if (!canScrub())
1515 pause();
1516 else
1517 m_state.setCommand(CmdPause);
1518 }
1519
1520 m_pendingState = NoPending;
1521
1522 //First look for rate changes.
1523 if (m_request.rate != m_state.rate) {
1524 commitRateChange(m_request.rate, m_request.isThin);
1525 }
1526
1527 // Now look for new requests.
1528 if (m_pendingState == NoPending) {
1529 switch (m_request.command) {
1530 case CmdStart:
1531 start();
1532 break;
1533 case CmdPause:
1534 pause();
1535 break;
1536 case CmdStop:
1537 stop();
1538 break;
1539 case CmdSeek:
1540 case CmdSeekResume:
1541 setPositionInternal(m_request.start, m_request.command);
1542 break;
1543 case CmdStartAndSeek:
1544 start();
1545 setPositionInternal(m_request.start, m_request.command);
1546 break;
1547 default:
1548 break;
1549 }
1550 m_request.setCommand(CmdNone);
1551 }
1552
1553}
1554
1555bool MFPlayerSession::canScrub() const
1556{
1557 return m_canScrub && m_rateSupport && m_rateControl;
1558}
1559
1560void MFPlayerSession::clear()
1561{
1562#ifdef DEBUG_MEDIAFOUNDATION
1563 qDebug() << "MFPlayerSession::clear";
1564#endif
1565 m_mediaTypes = 0;
1566 m_canScrub = false;
1567
1568 m_pendingState = NoPending;
1569 m_state.command = CmdStop;
1570 m_state.prevCmd = CmdNone;
1571 m_request.command = CmdNone;
1572 m_request.prevCmd = CmdNone;
1573
1574 for (int i = 0; i < QPlatformMediaPlayer::NTrackTypes; ++i) {
1575 m_trackInfo[i].metaData.clear();
1576 m_trackInfo[i].nativeIndexes.clear();
1577 m_trackInfo[i].currentIndex = -1;
1578 m_trackInfo[i].sourceNodeId = TOPOID(-1);
1579 m_trackInfo[i].outputNodeId = TOPOID(-1);
1580 m_trackInfo[i].format = GUID_NULL;
1581 }
1582
1583 if (!m_metaData.isEmpty()) {
1584 m_metaData.clear();
1586 }
1587
1588 m_presentationClock.Reset();
1589 m_rateControl.Reset();
1590 m_rateSupport.Reset();
1591 m_volumeControl.Reset();
1592 m_netsourceStatistics.Reset();
1593}
1594
1595void MFPlayerSession::setAudioOutput(QPlatformAudioOutput *device)
1596{
1597 if (m_audioOutput == device)
1598 return;
1599
1600 if (m_audioOutput)
1601 m_audioOutput->q->disconnect(this);
1602
1603 m_audioOutput = device;
1604 if (m_audioOutput) {
1605 setMuted(m_audioOutput->q->isMuted());
1606 setVolume(m_audioOutput->q->volume());
1608 connect(m_audioOutput->q, &QAudioOutput::deviceChanged, this, &MFPlayerSession::updateOutputRouting);
1609 connect(m_audioOutput->q, &QAudioOutput::volumeChanged, this, &MFPlayerSession::setVolume);
1610 connect(m_audioOutput->q, &QAudioOutput::mutedChanged, this, &MFPlayerSession::setMuted);
1611 }
1612}
1613
1615{
1616 int currentAudioTrack = m_trackInfo[QPlatformMediaPlayer::AudioStream].currentIndex;
1617 if (currentAudioTrack > -1)
1618 setActiveTrack(QPlatformMediaPlayer::AudioStream, currentAudioTrack);
1619}
1620
1621void MFPlayerSession::setVideoSink(QVideoSink *sink)
1622{
1623 m_videoRendererControl->setSink(sink);
1624}
1625
1626void MFPlayerSession::setActiveTrack(QPlatformMediaPlayer::TrackType type, int index)
1627{
1628 if (!m_session)
1629 return;
1630
1631 // Only audio track selection is currently supported.
1632 if (type != QPlatformMediaPlayer::AudioStream)
1633 return;
1634
1635 const auto &nativeIndexes = m_trackInfo[type].nativeIndexes;
1636
1637 if (index < -1 || index >= nativeIndexes.count())
1638 return;
1639
1640 // Updating the topology fails if there is a HEVC video stream,
1641 // which causes other issues. Ignoring the change, for now.
1642 if (m_trackInfo[QPlatformMediaPlayer::VideoStream].format == MFVideoFormat_HEVC)
1643 return;
1644
1645 ComPtr<IMFTopology> topology;
1646
1647 if (SUCCEEDED(m_session->GetFullTopology(MFSESSION_GETFULLTOPOLOGY_CURRENT, 0, &topology))) {
1648
1649 m_restorePosition = position() * 10000;
1650
1651 if (m_state.command == CmdStart)
1652 stop();
1653
1654 if (m_trackInfo[type].outputNodeId != TOPOID(-1)) {
1655 ComPtr<IMFTopologyNode> node;
1656 if (SUCCEEDED(topology->GetNodeByID(m_trackInfo[type].outputNodeId, &node))) {
1657 topology->RemoveNode(node.Get());
1658 m_trackInfo[type].outputNodeId = TOPOID(-1);
1659 }
1660 }
1661 if (m_trackInfo[type].sourceNodeId != TOPOID(-1)) {
1662 ComPtr<IMFTopologyNode> node;
1663 if (SUCCEEDED(topology->GetNodeByID(m_trackInfo[type].sourceNodeId, &node))) {
1664 topology->RemoveNode(node.Get());
1665 m_trackInfo[type].sourceNodeId = TOPOID(-1);
1666 }
1667 }
1668
1669 IMFMediaSource *mediaSource = m_sourceResolver->mediaSource();
1670
1671 ComPtr<IMFPresentationDescriptor> sourcePD;
1672 if (SUCCEEDED(mediaSource->CreatePresentationDescriptor(&sourcePD))) {
1673
1674 if (m_trackInfo[type].currentIndex >= 0 && m_trackInfo[type].currentIndex < nativeIndexes.count())
1675 sourcePD->DeselectStream(nativeIndexes.at(m_trackInfo[type].currentIndex));
1676
1677 m_trackInfo[type].currentIndex = index;
1678
1679 if (index == -1) {
1680 m_session->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE, topology.Get());
1681 } else {
1682 int nativeIndex = nativeIndexes.at(index);
1683 sourcePD->SelectStream(nativeIndex);
1684
1685 ComPtr<IMFStreamDescriptor> streamDesc;
1686 BOOL selected = FALSE;
1687
1688 if (SUCCEEDED(sourcePD->GetStreamDescriptorByIndex(nativeIndex, &selected, &streamDesc))) {
1689 ComPtr<IMFTopologyNode> sourceNode = addSourceNode(
1690 topology.Get(), mediaSource, sourcePD.Get(), streamDesc.Get());
1691 if (sourceNode) {
1692 ComPtr<IMFTopologyNode> outputNode =
1693 addOutputNode(MFPlayerSession::Audio, topology.Get(), 0);
1694 if (outputNode) {
1695 if (SUCCEEDED(sourceNode->ConnectOutput(0, outputNode.Get(), 0))) {
1696 sourceNode->GetTopoNodeID(&m_trackInfo[type].sourceNodeId);
1697 outputNode->GetTopoNodeID(&m_trackInfo[type].outputNodeId);
1698 m_session->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE,
1699 topology.Get());
1700 }
1701 }
1702 }
1703 }
1704 }
1705 m_updatingTopology = true;
1706 }
1707 }
1708}
1709
1710int MFPlayerSession::activeTrack(QPlatformMediaPlayer::TrackType type)
1711{
1712 if (type >= QPlatformMediaPlayer::NTrackTypes)
1713 return -1;
1714 return m_trackInfo[type].currentIndex;
1715}
1716
1717int MFPlayerSession::trackCount(QPlatformMediaPlayer::TrackType type)
1718{
1719 if (type >= QPlatformMediaPlayer::NTrackTypes)
1720 return -1;
1721 return m_trackInfo[type].metaData.count();
1722}
1723
1724QMediaMetaData MFPlayerSession::trackMetaData(QPlatformMediaPlayer::TrackType type, int trackNumber)
1725{
1726 if (type >= QPlatformMediaPlayer::NTrackTypes)
1727 return {};
1728
1729 if (trackNumber < 0 || trackNumber >= m_trackInfo[type].metaData.count())
1730 return {};
1731
1732 return m_trackInfo[type].metaData.at(trackNumber);
1733}
1734
1735QT_END_NAMESPACE
1736
1737#include "moc_mfplayersession_p.cpp"
void setPlaybackRate(qreal rate)
void setPosition(qint64 position)
void setAudioOutput(QPlatformAudioOutput *device)
void setVideoSink(QVideoSink *sink)
void bufferProgressChanged(float percentFilled)
qreal playbackRate() const
void stop(bool immediate=false)
STDMETHODIMP Invoke(IMFAsyncResult *pResult) override
void load(const QUrl &media, QIODevice *stream)
void changeStatus(QMediaPlayer::MediaStatus newStatus)
QMediaTimeRange availablePlaybackRanges()
void setMuted(bool muted)
void setSink(QVideoSink *surface)
HRESULT BindOutputNode(IMFTopologyNode *pNode)
HRESULT BindOutputNodes(IMFTopology *pTopology)