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