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 if (m_pendingState != NoPending) {
810 m_request.setCommand(CmdPause);
811 } else {
812 if (m_state.command == CmdPause)
813 return;
814
815 if (SUCCEEDED(m_session->Pause())) {
816 m_state.setCommand(CmdPause);
817 m_pendingState = CmdPending;
818 } else {
819 error(QMediaPlayer::ResourceError, tr("Failed to pause."), false);
820 }
821 if (status() == QMediaPlayer::EndOfMedia) {
822 setPosition(0);
823 positionChanged(0);
824 }
825 }
826}
827
828void MFPlayerSession::changeStatus(QMediaPlayer::MediaStatus newStatus)
829{
830 if (!m_playerControl)
831 return;
832#ifdef DEBUG_MEDIAFOUNDATION
833 qDebug() << "MFPlayerSession::changeStatus" << newStatus;
834#endif
835 // notify the control to run its session-specific handling
836 statusChanged(newStatus);
837}
838
839QMediaPlayer::MediaStatus MFPlayerSession::status() const
840{
841 if (!m_playerControl)
842 return QMediaPlayer::NoMedia;
843 return m_playerControl->mediaStatus();
844}
845
846bool MFPlayerSession::createSession()
847{
848 close();
849
850 Q_ASSERT(m_session == NULL);
851
852 HRESULT hr = MFCreateMediaSession(NULL, &m_session);
853 if (FAILED(hr)) {
854 changeStatus(QMediaPlayer::InvalidMedia);
855 error(QMediaPlayer::ResourceError, tr("Unable to create mediasession."), true);
856 return false;
857 }
858
859 m_hCloseEvent = EventHandle{ CreateEvent(NULL, FALSE, FALSE, NULL) };
860
861 hr = m_session->BeginGetEvent(this, m_session.Get());
862 if (FAILED(hr)) {
863 changeStatus(QMediaPlayer::InvalidMedia);
864 error(QMediaPlayer::ResourceError, tr("Unable to pull session events."), false);
865 close();
866 return false;
867 }
868
869 m_sourceResolver = makeComObject<SourceResolver>();
870 QObject::connect(m_sourceResolver.Get(), &SourceResolver::mediaSourceReady, this,
871 &MFPlayerSession::handleMediaSourceReady);
872 QObject::connect(m_sourceResolver.Get(), &SourceResolver::error, this,
873 &MFPlayerSession::handleSourceError);
874
875 m_position = 0;
876 return true;
877}
878
880{
881 if (m_request.command == CmdSeek || m_request.command == CmdSeekResume)
882 return m_request.start;
883
884 if (m_pendingState == SeekPending)
885 return m_state.start;
886
887 if (m_state.command == CmdStop)
888 return m_position / 10000;
889
890 if (m_presentationClock) {
891 MFTIME time, sysTime;
892 if (FAILED(m_presentationClock->GetCorrelatedTime(0, &time, &sysTime)))
893 return m_position / 10000;
894 return qint64(time / 10000);
895 }
896 return m_position / 10000;
897}
898
899void MFPlayerSession::setPosition(qint64 position)
900{
901#ifdef DEBUG_MEDIAFOUNDATION
902 qDebug() << "setPosition";
903#endif
904 if (m_pendingState != NoPending) {
905 m_request.setCommand(CmdSeek);
906 m_request.start = position;
907 } else {
908 setPositionInternal(position, CmdNone);
909 }
910}
911
912void MFPlayerSession::setPositionInternal(qint64 position, Command requestCmd)
913{
914 if (status() == QMediaPlayer::EndOfMedia)
915 changeStatus(QMediaPlayer::LoadedMedia);
916 if (m_state.command == CmdStop && requestCmd != CmdSeekResume) {
917 m_position = position * 10000;
918 // Even though the position is not actually set on the session yet,
919 // report it to have changed anyway for UI controls to be updated
920 positionChanged(this->position());
921 return;
922 }
923
924 if (m_state.command == CmdPause)
925 scrub(true);
926
927#ifdef DEBUG_MEDIAFOUNDATION
928 qDebug() << "setPositionInternal";
929#endif
930
931 PROPVARIANT varStart;
932 varStart.vt = VT_I8;
933 varStart.hVal.QuadPart = LONGLONG(position * 10000);
934 if (SUCCEEDED(m_session->Start(NULL, &varStart))) {
935 PropVariantClear(&varStart);
936 // Store the pending state.
937 m_state.setCommand(CmdStart);
938 m_state.start = position;
939 m_pendingState = SeekPending;
940 } else {
941 error(QMediaPlayer::ResourceError, tr("Failed to seek."), true);
942 }
943}
944
946{
947 if (m_scrubbing)
948 return m_restoreRate;
949 return m_state.rate;
950}
951
953{
954 if (m_scrubbing) {
955 m_restoreRate = rate;
956 playbackRateChanged(rate);
957 return;
958 }
959 setPlaybackRateInternal(rate);
960}
961
962void MFPlayerSession::setPlaybackRateInternal(qreal rate)
963{
964 if (rate == m_request.rate)
965 return;
966
967 m_pendingRate = rate;
968 if (!m_rateSupport)
969 return;
970
971#ifdef DEBUG_MEDIAFOUNDATION
972 qDebug() << "setPlaybackRate";
973#endif
974 BOOL isThin = FALSE;
975
976 //from MSDN http://msdn.microsoft.com/en-us/library/aa965220%28v=vs.85%29.aspx
977 //Thinning applies primarily to video streams.
978 //In thinned mode, the source drops delta frames and deliver only key frames.
979 //At very high playback rates, the source might skip some key frames (for example, deliver every other key frame).
980
981 if (FAILED(m_rateSupport->IsRateSupported(FALSE, rate, NULL))) {
982 isThin = TRUE;
983 if (FAILED(m_rateSupport->IsRateSupported(isThin, rate, NULL))) {
984 qWarning() << "unable to set playbackrate = " << rate;
985 m_pendingRate = m_request.rate = m_state.rate;
986 return;
987 }
988 }
989 if (m_pendingState != NoPending) {
990 m_request.rate = rate;
991 m_request.isThin = isThin;
992 // Remember the current transport state (play, paused, etc), so that we
993 // can restore it after the rate change, if necessary. However, if
994 // anothercommand is already pending, that one takes precedent.
995 if (m_request.command == CmdNone)
996 m_request.setCommand(m_state.command);
997 } else {
998 //No pending operation. Commit the new rate.
999 commitRateChange(rate, isThin);
1000 }
1001}
1002
1003void MFPlayerSession::commitRateChange(qreal rate, BOOL isThin)
1004{
1005#ifdef DEBUG_MEDIAFOUNDATION
1006 qDebug() << "commitRateChange";
1007#endif
1008 Q_ASSERT(m_pendingState == NoPending);
1009 MFTIME hnsSystemTime = 0;
1010 MFTIME hnsClockTime = 0;
1011 Command cmdNow = m_state.command;
1012 bool resetPosition = false;
1013 // Allowed rate transitions:
1014 // Positive <-> negative: Stopped
1015 // Negative <-> zero: Stopped
1016 // Postive <-> zero: Paused or stopped
1017 if ((rate > 0 && m_state.rate <= 0) || (rate < 0 && m_state.rate >= 0)) {
1018 if (cmdNow == CmdStart) {
1019 // Get the current clock position. This will be the restart time.
1020 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1021 Q_ASSERT(hnsSystemTime != 0);
1022
1023 if (rate < 0 || m_state.rate < 0)
1024 m_request.setCommand(CmdSeekResume);
1025 else if (isThin || m_state.isThin)
1026 m_request.setCommand(CmdStartAndSeek);
1027 else
1028 m_request.setCommand(CmdStart);
1029
1030 // We need to stop only when dealing with negative rates
1031 if (rate >= 0 && m_state.rate >= 0)
1032 pause();
1033 else
1034 stop();
1035
1036 // If we deal with negative rates, we stopped the session and consequently
1037 // reset the position to zero. We then need to resume to the current position.
1038 m_request.start = hnsClockTime / 10000;
1039 } else if (cmdNow == CmdPause) {
1040 if (rate < 0 || m_state.rate < 0) {
1041 // The current state is paused.
1042 // For this rate change, the session must be stopped. However, the
1043 // session cannot transition back from stopped to paused.
1044 // Therefore, this rate transition is not supported while paused.
1045 qWarning() << "Unable to change rate from positive to negative or vice versa in paused state";
1046 rate = m_state.rate;
1047 isThin = m_state.isThin;
1048 goto done;
1049 }
1050
1051 // This happens when resuming playback after scrubbing in pause mode.
1052 // This transition requires the session to be paused. Even though our
1053 // internal state is set to paused, the session might not be so we need
1054 // to enforce it
1055 if (rate > 0 && m_state.rate == 0) {
1056 m_state.setCommand(CmdNone);
1057 pause();
1058 }
1059 }
1060 } else if (rate == 0 && m_state.rate > 0) {
1061 if (cmdNow != CmdPause) {
1062 // Transition to paused.
1063 // This transisition requires the paused state.
1064 // Pause and set the rate.
1065 pause();
1066
1067 // Request: Switch back to current state.
1068 m_request.setCommand(cmdNow);
1069 }
1070 } else if (rate == 0 && m_state.rate < 0) {
1071 // Changing rate from negative to zero requires to stop the session
1072 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1073
1074 m_request.setCommand(CmdSeekResume);
1075
1076 stop();
1077
1078 // Resume to the current position (stop() will reset the position to 0)
1079 m_request.start = hnsClockTime / 10000;
1080 } else if (!isThin && m_state.isThin) {
1081 if (cmdNow == CmdStart) {
1082 // When thinning, only key frames are read and presented. Going back
1083 // to normal playback requires to reset the current position to force
1084 // the pipeline to decode the actual frame at the current position
1085 // (which might be earlier than the last decoded key frame)
1086 resetPosition = true;
1087 } else if (cmdNow == CmdPause) {
1088 // If paused, don't reset the position until we resume, otherwise
1089 // a new frame will be rendered
1090 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1091 m_request.setCommand(CmdSeekResume);
1092 m_request.start = hnsClockTime / 10000;
1093 }
1094
1095 }
1096
1097 // Set the rate.
1098 if (FAILED(m_rateControl->SetRate(isThin, rate))) {
1099 qWarning() << "failed to set playbackrate = " << rate;
1100 rate = m_state.rate;
1101 isThin = m_state.isThin;
1102 goto done;
1103 }
1104
1105 if (resetPosition) {
1106 m_presentationClock->GetCorrelatedTime(0, &hnsClockTime, &hnsSystemTime);
1107 setPosition(hnsClockTime / 10000);
1108 }
1109
1110done:
1111 // Adjust our current rate and requested rate.
1112 m_pendingRate = m_request.rate = m_state.rate = rate;
1113 if (rate != 0)
1114 m_state.isThin = isThin;
1115 playbackRateChanged(rate);
1116}
1117
1118void MFPlayerSession::scrub(bool enableScrub)
1119{
1120 if (m_scrubbing == enableScrub)
1121 return;
1122
1123 m_scrubbing = enableScrub;
1124
1125 if (!canScrub()) {
1126 if (!enableScrub)
1127 m_pendingRate = m_restoreRate;
1128 return;
1129 }
1130
1131 if (enableScrub) {
1132 // Enter scrubbing mode. Cache the rate.
1133 m_restoreRate = m_request.rate;
1134 setPlaybackRateInternal(0.0f);
1135 } else {
1136 // Leaving scrubbing mode. Restore the old rate.
1137 setPlaybackRateInternal(m_restoreRate);
1138 }
1139}
1140
1141void MFPlayerSession::setVolume(float volume)
1142{
1143 if (m_volume == volume)
1144 return;
1145 m_volume = volume;
1146
1147 if (!m_muted)
1148 setVolumeInternal(volume);
1149}
1150
1151void MFPlayerSession::setMuted(bool muted)
1152{
1153 if (m_muted == muted)
1154 return;
1155 m_muted = muted;
1156
1157 setVolumeInternal(muted ? 0 : m_volume);
1158}
1159
1160void MFPlayerSession::setVolumeInternal(float volume)
1161{
1162 if (m_volumeControl) {
1163 quint32 channelCount = 0;
1164 if (!SUCCEEDED(m_volumeControl->GetChannelCount(&channelCount))
1165 || channelCount == 0)
1166 return;
1167
1168 for (quint32 i = 0; i < channelCount; ++i)
1169 m_volumeControl->SetChannelVolume(i, volume);
1170 }
1171}
1172
1174{
1175 if (!m_netsourceStatistics)
1176 return 0;
1177 PROPVARIANT var;
1178 PropVariantInit(&var);
1179 PROPERTYKEY key;
1180 key.fmtid = MFNETSOURCE_STATISTICS;
1181 key.pid = MFNETSOURCE_BUFFERPROGRESS_ID;
1182 int progress = -1;
1183 // GetValue returns S_FALSE if the property is not available, which has
1184 // a value > 0. We therefore can't use the SUCCEEDED macro here.
1185 if (m_netsourceStatistics->GetValue(key, &var) == S_OK) {
1186 progress = var.lVal;
1187 PropVariantClear(&var);
1188 }
1189
1190#ifdef DEBUG_MEDIAFOUNDATION
1191 qDebug() << "bufferProgress: progress = " << progress;
1192#endif
1193
1194 return progress/100.;
1195}
1196
1198{
1199 // defaults to the whole media
1200 qint64 start = 0;
1201 qint64 end = qint64(m_duration / 10000);
1202
1203 if (m_netsourceStatistics) {
1204 PROPVARIANT var;
1205 PropVariantInit(&var);
1206 PROPERTYKEY key;
1207 key.fmtid = MFNETSOURCE_STATISTICS;
1208 key.pid = MFNETSOURCE_SEEKRANGESTART_ID;
1209 // GetValue returns S_FALSE if the property is not available, which has
1210 // a value > 0. We therefore can't use the SUCCEEDED macro here.
1211 if (m_netsourceStatistics->GetValue(key, &var) == S_OK) {
1212 start = qint64(var.uhVal.QuadPart / 10000);
1213 PropVariantClear(&var);
1214 PropVariantInit(&var);
1215 key.pid = MFNETSOURCE_SEEKRANGEEND_ID;
1216 if (m_netsourceStatistics->GetValue(key, &var) == S_OK) {
1217 end = qint64(var.uhVal.QuadPart / 10000);
1218 PropVariantClear(&var);
1219 }
1220 }
1221 }
1222
1223 return QMediaTimeRange(start, end);
1224}
1225
1226HRESULT MFPlayerSession::QueryInterface(REFIID riid, void** ppvObject)
1227{
1228 if (!ppvObject)
1229 return E_POINTER;
1230 if (riid == IID_IMFAsyncCallback) {
1231 *ppvObject = static_cast<IMFAsyncCallback*>(this);
1232 } else if (riid == IID_IUnknown) {
1233 *ppvObject = static_cast<IUnknown*>(this);
1234 } else {
1235 *ppvObject = NULL;
1236 return E_NOINTERFACE;
1237 }
1238 return S_OK;
1239}
1240
1241ULONG MFPlayerSession::AddRef(void)
1242{
1243 return InterlockedIncrement(&m_cRef);
1244}
1245
1246ULONG MFPlayerSession::Release(void)
1247{
1248 LONG cRef = InterlockedDecrement(&m_cRef);
1249 if (cRef == 0) {
1250 deleteLater();
1251
1252 // In rare cases the session has queued events to be run between deleteLater and deleting,
1253 // so we set the parent control to nullptr in order to prevent crashes in the cases.
1254 m_playerControl = nullptr;
1255 }
1256 return cRef;
1257}
1258
1259HRESULT MFPlayerSession::Invoke(IMFAsyncResult *pResult)
1260{
1261 if (pResult->GetStateNoAddRef() != m_session.Get())
1262 return S_OK;
1263
1264 ComPtr<IMFMediaEvent> pEvent;
1265 // Get the event from the event queue.
1266 HRESULT hr = m_session->EndGetEvent(pResult, &pEvent);
1267 if (FAILED(hr)) {
1268 return S_OK;
1269 }
1270
1271 MediaEventType meType = MEUnknown;
1272 hr = pEvent->GetType(&meType);
1273 if (FAILED(hr)) {
1274 return S_OK;
1275 }
1276
1277 if (meType == MESessionClosed) {
1278 SetEvent(m_hCloseEvent.get());
1279 return S_OK;
1280 } else {
1281 hr = m_session->BeginGetEvent(this, m_session.Get());
1282 if (FAILED(hr)) {
1283 return S_OK;
1284 }
1285 }
1286
1287 if (!m_closing) {
1288 emit sessionEvent(pEvent);
1289 }
1290 return S_OK;
1291}
1292
1293void MFPlayerSession::handleSessionEvent(const ComPtr<IMFMediaEvent> &sessionEvent)
1294{
1295 HRESULT hrStatus = S_OK;
1296 HRESULT hr = sessionEvent->GetStatus(&hrStatus);
1297 if (FAILED(hr) || !m_session) {
1298 return;
1299 }
1300
1301 MediaEventType meType = MEUnknown;
1302 hr = sessionEvent->GetType(&meType);
1303#ifdef DEBUG_MEDIAFOUNDATION
1304 if (FAILED(hrStatus))
1305 qDebug() << "handleSessionEvent: MediaEventType = " << meType << "Failed";
1306 else
1307 qDebug() << "handleSessionEvent: MediaEventType = " << meType;
1308#endif
1309
1310 switch (meType) {
1311 case MENonFatalError: {
1312 PROPVARIANT var;
1313 PropVariantInit(&var);
1314 sessionEvent->GetValue(&var);
1315 qWarning() << "handleSessionEvent: non fatal error = " << var.ulVal;
1316 PropVariantClear(&var);
1317 error(QMediaPlayer::ResourceError, tr("Media session non-fatal error."), false);
1318 }
1319 break;
1320 case MESourceUnknown:
1321 changeStatus(QMediaPlayer::InvalidMedia);
1322 break;
1323 case MEError:
1324 if (hrStatus == MF_E_ALREADY_INITIALIZED) {
1325 // Workaround for a possible WMF issue that causes an error
1326 // with some specific videos, which play fine otherwise.
1327#ifdef DEBUG_MEDIAFOUNDATION
1328 qDebug() << "handleSessionEvent: ignoring MF_E_ALREADY_INITIALIZED";
1329#endif
1330 break;
1331 }
1332 changeStatus(QMediaPlayer::InvalidMedia);
1333 qWarning() << "handleSessionEvent: serious error = "
1334 << Qt::showbase << Qt::hex << Qt::uppercasedigits << static_cast<quint32>(hrStatus);
1335 switch (hrStatus) {
1336 case MF_E_NET_READ:
1337 error(QMediaPlayer::NetworkError, tr("Error reading from the network."), true);
1338 break;
1339 case MF_E_NET_WRITE:
1340 error(QMediaPlayer::NetworkError, tr("Error writing to the network."), true);
1341 break;
1342 case NS_E_FIREWALL:
1343 error(QMediaPlayer::NetworkError, tr("Network packets might be blocked by a firewall."), true);
1344 break;
1345 case MF_E_MEDIAPROC_WRONGSTATE:
1346 error(QMediaPlayer::ResourceError, tr("Media session state error."), true);
1347 break;
1348 case MF_E_INVALID_STREAM_DATA:
1349 error(QMediaPlayer::ResourceError, tr("Invalid stream data."), true);
1350 break;
1351 default:
1352 error(QMediaPlayer::ResourceError, tr("Media session serious error."), true);
1353 break;
1354 }
1355 break;
1356 case MESessionRateChanged:
1357 // If the rate change succeeded, we've already got the rate
1358 // cached. If it failed, try to get the actual rate.
1359 if (FAILED(hrStatus)) {
1360 PROPVARIANT var;
1361 PropVariantInit(&var);
1362 if (SUCCEEDED(sessionEvent->GetValue(&var)) && (var.vt == VT_R4)) {
1363 m_state.rate = var.fltVal;
1364 }
1365 playbackRateChanged(playbackRate());
1366 }
1367 break;
1368 case MESessionScrubSampleComplete :
1369 if (m_scrubbing)
1370 updatePendingCommands(CmdStart);
1371 break;
1372 case MESessionStarted:
1373 if (status() == QMediaPlayer::EndOfMedia
1374 || status() == QMediaPlayer::LoadedMedia) {
1375 // If the session started, then enough data is buffered to play
1376 changeStatus(QMediaPlayer::BufferedMedia);
1377 }
1378
1379 updatePendingCommands(CmdStart);
1380 // playback started, we can now set again the procAmpValues if they have been
1381 // changed previously (these are lost when loading a new media)
1382// if (m_playerService->videoWindowControl()) {
1383// m_playerService->videoWindowControl()->applyImageControls();
1384// }
1385 m_signalPositionChangeTimer.start();
1386 break;
1387 case MESessionStopped:
1388 if (status() != QMediaPlayer::EndOfMedia) {
1389 m_position = 0;
1390
1391 // Reset to Loaded status unless we are loading a new media
1392 // or changing the playback rate to negative values (stop required)
1393 if (status() != QMediaPlayer::LoadingMedia && m_request.command != CmdSeekResume)
1394 changeStatus(QMediaPlayer::LoadedMedia);
1395 }
1396 updatePendingCommands(CmdStop);
1397 m_signalPositionChangeTimer.stop();
1398 break;
1399 case MESessionPaused:
1400 m_position = position() * 10000;
1401 updatePendingCommands(CmdPause);
1402 m_signalPositionChangeTimer.stop();
1403 if (status() == QMediaPlayer::LoadedMedia)
1404 setPosition(position());
1405 break;
1406 case MEReconnectStart:
1407#ifdef DEBUG_MEDIAFOUNDATION
1408 qDebug() << "MEReconnectStart" << ((hrStatus == S_OK) ? "OK" : "Failed");
1409#endif
1410 break;
1411 case MEReconnectEnd:
1412#ifdef DEBUG_MEDIAFOUNDATION
1413 qDebug() << "MEReconnectEnd" << ((hrStatus == S_OK) ? "OK" : "Failed");
1414#endif
1415 break;
1416 case MESessionTopologySet:
1417 if (FAILED(hrStatus)) {
1418 changeStatus(QMediaPlayer::InvalidMedia);
1419 error(QMediaPlayer::FormatError, tr("Unsupported media, a codec is missing."), true);
1420 } else {
1421 // Topology is resolved and successfuly set, this happens only after loading a new media.
1422 // Make sure we always start the media from the beginning
1423 m_lastPosition = -1;
1424 m_position = 0;
1425 positionChanged(0);
1426 changeStatus(QMediaPlayer::LoadedMedia);
1427 }
1428 break;
1429 }
1430
1431 if (FAILED(hrStatus)) {
1432 return;
1433 }
1434
1435 switch (meType) {
1436 case MEBufferingStarted:
1437 changeStatus(QMediaPlayer::StalledMedia);
1439 break;
1440 case MEBufferingStopped:
1441 changeStatus(QMediaPlayer::BufferedMedia);
1443 break;
1444 case MESessionEnded:
1445 m_pendingState = NoPending;
1446 m_state.command = CmdStop;
1447 m_state.prevCmd = CmdNone;
1448 m_request.command = CmdNone;
1449 m_request.prevCmd = CmdNone;
1450
1451 //keep reporting the final position after end of media
1452 m_position = qint64(m_duration);
1453 positionChanged(position());
1454
1455 changeStatus(QMediaPlayer::EndOfMedia);
1456 break;
1457 case MEEndOfPresentationSegment:
1458 break;
1459 case MESessionTopologyStatus: {
1460 UINT32 status;
1461 if (SUCCEEDED(sessionEvent->GetUINT32(MF_EVENT_TOPOLOGY_STATUS, &status))) {
1462 if (status == MF_TOPOSTATUS_READY) {
1463 ComPtr<IMFClock> clock;
1464 if (SUCCEEDED(m_session->GetClock(&clock))) {
1465 clock->QueryInterface(IID_IMFPresentationClock, &m_presentationClock);
1466 }
1467
1468 if (SUCCEEDED(MFGetService(m_session.Get(), MF_RATE_CONTROL_SERVICE,
1469 IID_PPV_ARGS(&m_rateControl)))) {
1470 if (SUCCEEDED(MFGetService(m_session.Get(), MF_RATE_CONTROL_SERVICE,
1471 IID_PPV_ARGS(&m_rateSupport)))) {
1472 if (SUCCEEDED(m_rateSupport->IsRateSupported(TRUE, 0, NULL)))
1473 m_canScrub = true;
1474 }
1475 BOOL isThin = FALSE;
1476 float rate = 1;
1477 if (SUCCEEDED(m_rateControl->GetRate(&isThin, &rate))) {
1478 if (m_pendingRate != rate) {
1479 m_state.rate = m_request.rate = rate;
1480 setPlaybackRate(m_pendingRate);
1481 }
1482 }
1483 }
1484 MFGetService(m_session.Get(), MFNETSOURCE_STATISTICS_SERVICE,
1485 IID_PPV_ARGS(&m_netsourceStatistics));
1486
1487 if (SUCCEEDED(MFGetService(m_session.Get(), MR_STREAM_VOLUME_SERVICE,
1488 IID_PPV_ARGS(&m_volumeControl))))
1489 setVolumeInternal(m_muted ? 0 : m_volume);
1490
1491 m_updatingTopology = false;
1492 stop();
1493 }
1494 }
1495 }
1496 break;
1497 default:
1498 break;
1499 }
1500}
1501
1502void MFPlayerSession::updatePendingCommands(Command command)
1503{
1504 positionChanged(position());
1505 if (m_state.command != command || m_pendingState == NoPending)
1506 return;
1507
1508 // Seek while paused completed
1509 if (m_pendingState == SeekPending && m_state.prevCmd == CmdPause) {
1510 m_pendingState = NoPending;
1511 // A seek operation actually restarts playback. If scrubbing is possible, playback rate
1512 // is set to 0.0 at this point and we just need to reset the current state to Pause.
1513 // If scrubbing is not possible, the playback rate was not changed and we explicitly need
1514 // to re-pause playback.
1515 if (!canScrub())
1516 pause();
1517 else
1518 m_state.setCommand(CmdPause);
1519 }
1520
1521 m_pendingState = NoPending;
1522
1523 //First look for rate changes.
1524 if (m_request.rate != m_state.rate) {
1525 commitRateChange(m_request.rate, m_request.isThin);
1526 }
1527
1528 // Now look for new requests.
1529 if (m_pendingState == NoPending) {
1530 switch (m_request.command) {
1531 case CmdStart:
1532 start();
1533 break;
1534 case CmdPause:
1535 pause();
1536 break;
1537 case CmdStop:
1538 stop();
1539 break;
1540 case CmdSeek:
1541 case CmdSeekResume:
1542 setPositionInternal(m_request.start, m_request.command);
1543 break;
1544 case CmdStartAndSeek:
1545 start();
1546 setPositionInternal(m_request.start, m_request.command);
1547 break;
1548 default:
1549 break;
1550 }
1551 m_request.setCommand(CmdNone);
1552 }
1553
1554}
1555
1556bool MFPlayerSession::canScrub() const
1557{
1558 return m_canScrub && m_rateSupport && m_rateControl;
1559}
1560
1561void MFPlayerSession::clear()
1562{
1563#ifdef DEBUG_MEDIAFOUNDATION
1564 qDebug() << "MFPlayerSession::clear";
1565#endif
1566 m_mediaTypes = 0;
1567 m_canScrub = false;
1568
1569 m_pendingState = NoPending;
1570 m_state.command = CmdStop;
1571 m_state.prevCmd = CmdNone;
1572 m_request.command = CmdNone;
1573 m_request.prevCmd = CmdNone;
1574
1575 for (int i = 0; i < QPlatformMediaPlayer::NTrackTypes; ++i) {
1576 m_trackInfo[i].metaData.clear();
1577 m_trackInfo[i].nativeIndexes.clear();
1578 m_trackInfo[i].currentIndex = -1;
1579 m_trackInfo[i].sourceNodeId = TOPOID(-1);
1580 m_trackInfo[i].outputNodeId = TOPOID(-1);
1581 m_trackInfo[i].format = GUID_NULL;
1582 }
1583
1584 if (!m_metaData.isEmpty()) {
1585 m_metaData.clear();
1587 }
1588
1589 m_presentationClock.Reset();
1590 m_rateControl.Reset();
1591 m_rateSupport.Reset();
1592 m_volumeControl.Reset();
1593 m_netsourceStatistics.Reset();
1594}
1595
1596void MFPlayerSession::setAudioOutput(QPlatformAudioOutput *device)
1597{
1598 if (m_audioOutput == device)
1599 return;
1600
1601 if (m_audioOutput)
1602 m_audioOutput->q->disconnect(this);
1603
1604 m_audioOutput = device;
1605 if (m_audioOutput) {
1606 setMuted(m_audioOutput->q->isMuted());
1607 setVolume(m_audioOutput->q->volume());
1609 connect(m_audioOutput->q, &QAudioOutput::deviceChanged, this, &MFPlayerSession::updateOutputRouting);
1610 connect(m_audioOutput->q, &QAudioOutput::volumeChanged, this, &MFPlayerSession::setVolume);
1611 connect(m_audioOutput->q, &QAudioOutput::mutedChanged, this, &MFPlayerSession::setMuted);
1612 }
1613}
1614
1616{
1617 int currentAudioTrack = m_trackInfo[QPlatformMediaPlayer::AudioStream].currentIndex;
1618 if (currentAudioTrack > -1)
1619 setActiveTrack(QPlatformMediaPlayer::AudioStream, currentAudioTrack);
1620}
1621
1622void MFPlayerSession::setVideoSink(QVideoSink *sink)
1623{
1624 m_videoRendererControl->setSink(sink);
1625}
1626
1627void MFPlayerSession::setActiveTrack(QPlatformMediaPlayer::TrackType type, int index)
1628{
1629 if (!m_session)
1630 return;
1631
1632 // Only audio track selection is currently supported.
1633 if (type != QPlatformMediaPlayer::AudioStream)
1634 return;
1635
1636 const auto &nativeIndexes = m_trackInfo[type].nativeIndexes;
1637
1638 if (index < -1 || index >= nativeIndexes.count())
1639 return;
1640
1641 // Updating the topology fails if there is a HEVC video stream,
1642 // which causes other issues. Ignoring the change, for now.
1643 if (m_trackInfo[QPlatformMediaPlayer::VideoStream].format == MFVideoFormat_HEVC)
1644 return;
1645
1646 ComPtr<IMFTopology> topology;
1647
1648 if (SUCCEEDED(m_session->GetFullTopology(MFSESSION_GETFULLTOPOLOGY_CURRENT, 0, &topology))) {
1649
1650 m_restorePosition = position() * 10000;
1651
1652 if (m_state.command == CmdStart)
1653 stop();
1654
1655 if (m_trackInfo[type].outputNodeId != TOPOID(-1)) {
1656 ComPtr<IMFTopologyNode> node;
1657 if (SUCCEEDED(topology->GetNodeByID(m_trackInfo[type].outputNodeId, &node))) {
1658 topology->RemoveNode(node.Get());
1659 m_trackInfo[type].outputNodeId = TOPOID(-1);
1660 }
1661 }
1662 if (m_trackInfo[type].sourceNodeId != TOPOID(-1)) {
1663 ComPtr<IMFTopologyNode> node;
1664 if (SUCCEEDED(topology->GetNodeByID(m_trackInfo[type].sourceNodeId, &node))) {
1665 topology->RemoveNode(node.Get());
1666 m_trackInfo[type].sourceNodeId = TOPOID(-1);
1667 }
1668 }
1669
1670 IMFMediaSource *mediaSource = m_sourceResolver->mediaSource();
1671
1672 ComPtr<IMFPresentationDescriptor> sourcePD;
1673 if (SUCCEEDED(mediaSource->CreatePresentationDescriptor(&sourcePD))) {
1674
1675 if (m_trackInfo[type].currentIndex >= 0 && m_trackInfo[type].currentIndex < nativeIndexes.count())
1676 sourcePD->DeselectStream(nativeIndexes.at(m_trackInfo[type].currentIndex));
1677
1678 m_trackInfo[type].currentIndex = index;
1679
1680 if (index == -1) {
1681 m_session->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE, topology.Get());
1682 } else {
1683 int nativeIndex = nativeIndexes.at(index);
1684 sourcePD->SelectStream(nativeIndex);
1685
1686 ComPtr<IMFStreamDescriptor> streamDesc;
1687 BOOL selected = FALSE;
1688
1689 if (SUCCEEDED(sourcePD->GetStreamDescriptorByIndex(nativeIndex, &selected, &streamDesc))) {
1690 ComPtr<IMFTopologyNode> sourceNode = addSourceNode(
1691 topology.Get(), mediaSource, sourcePD.Get(), streamDesc.Get());
1692 if (sourceNode) {
1693 ComPtr<IMFTopologyNode> outputNode =
1694 addOutputNode(MFPlayerSession::Audio, topology.Get(), 0);
1695 if (outputNode) {
1696 if (SUCCEEDED(sourceNode->ConnectOutput(0, outputNode.Get(), 0))) {
1697 sourceNode->GetTopoNodeID(&m_trackInfo[type].sourceNodeId);
1698 outputNode->GetTopoNodeID(&m_trackInfo[type].outputNodeId);
1699 m_session->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE,
1700 topology.Get());
1701 }
1702 }
1703 }
1704 }
1705 }
1706 m_updatingTopology = true;
1707 }
1708 }
1709}
1710
1711int MFPlayerSession::activeTrack(QPlatformMediaPlayer::TrackType type)
1712{
1713 if (type >= QPlatformMediaPlayer::NTrackTypes)
1714 return -1;
1715 return m_trackInfo[type].currentIndex;
1716}
1717
1718int MFPlayerSession::trackCount(QPlatformMediaPlayer::TrackType type)
1719{
1720 if (type >= QPlatformMediaPlayer::NTrackTypes)
1721 return -1;
1722 return m_trackInfo[type].metaData.count();
1723}
1724
1725QMediaMetaData MFPlayerSession::trackMetaData(QPlatformMediaPlayer::TrackType type, int trackNumber)
1726{
1727 if (type >= QPlatformMediaPlayer::NTrackTypes)
1728 return {};
1729
1730 if (trackNumber < 0 || trackNumber >= m_trackInfo[type].metaData.count())
1731 return {};
1732
1733 return m_trackInfo[type].metaData.at(trackNumber);
1734}
1735
1736QT_END_NAMESPACE
1737
1738#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.