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
qmediaplayer.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
5
6#include <private/qmultimediautils_p.h>
7#include <private/qplatformmediaintegration_p.h>
8#include <private/qaudiobufferoutput_p.h>
9#include <qvideosink.h>
10#include <qaudiooutput.h>
11
12#include <QtCore/qcoreevent.h>
13#include <QtCore/qmetaobject.h>
14#include <QtCore/qtimer.h>
15#include <QtCore/qdebug.h>
16#include <QtCore/qdir.h>
17#include <QtCore/qpointer.h>
18#include <QtCore/qfileinfo.h>
19#include <QtCore/qtemporaryfile.h>
20#include <QtCore/qcoreapplication.h>
21
22#if defined(Q_OS_ANDROID)
23# include <QtCore/qjniobject.h>
24#endif
25
27
28/*!
29 \class QMediaPlayer
30 \brief The QMediaPlayer class allows the playing of a media files.
31 \inmodule QtMultimedia
32 \ingroup multimedia
33 \ingroup multimedia_playback
34 \ingroup multimedia_video
35
36 The QMediaPlayer class is a high level media playback class. It can be used
37 to playback audio of video media files. The content
38 to playback is specified as a QUrl object.
39
40 \snippet multimedia-snippets/media.cpp Player
41
42 QVideoWidget can be used with QMediaPlayer for video rendering.
43
44 \sa QVideoWidget
45*/
46
47/*!
48 \qmltype MediaPlayer
49 \nativetype QMediaPlayer
50 \brief Adds media playback to a scene.
51
52 \inqmlmodule QtMultimedia
53 \ingroup multimedia_qml
54 \ingroup multimedia_audio_qml
55 \ingroup multimedia_video_qml
56
57 \qml
58 Text {
59 text: "Click Me!";
60 font.pointSize: 24;
61 width: 150; height: 50;
62
63 MediaPlayer {
64 id: playMusic
65 source: "music.wav"
66 audioOutput: AudioOutput {}
67 }
68 MouseArea {
69 anchors.fill: parent
70 onPressed: { playMusic.play() }
71 }
72 }
73 \endqml
74
75 You can use MediaPlayer together with a MultiMedia::AudioOutput to play audio content, or you can use it
76 in conjunction with a Multimedia::VideoOutput for rendering video.
77
78 \qml
79 Item {
80 MediaPlayer {
81 id: mediaplayer
82 source: "groovy_video.mp4"
83 audioOutput: AudioOutput {}
84 videoOutput: videoOutput
85 }
86
87 VideoOutput {
88 id: videoOutput
89 anchors.fill: parent
90 }
91
92 MouseArea {
93 anchors.fill: parent
94 onPressed: mediaplayer.play();
95 }
96 }
97 \endqml
98
99 \sa AudioOutput, VideoOutput
100*/
101
102void QMediaPlayerPrivate::setState(QMediaPlayer::PlaybackState toState)
103{
104 Q_Q(QMediaPlayer);
105
106 if (toState != state) {
107 const auto fromState = std::exchange(state, toState);
108 if (toState == QMediaPlayer::PlayingState || fromState == QMediaPlayer::PlayingState)
109 emit q->playingChanged(toState == QMediaPlayer::PlayingState);
110 emit q->playbackStateChanged(toState);
111 }
112}
113
114void QMediaPlayerPrivate::setStatus(QMediaPlayer::MediaStatus s)
115{
116 Q_Q(QMediaPlayer);
117
118 emit q->mediaStatusChanged(s);
119}
120
121void QMediaPlayerPrivate::setError(QMediaPlayer::Error error, const QString &errorString)
122{
123 Q_Q(QMediaPlayer);
124
125 this->error.setAndNotify(error, errorString, *q);
126}
127
128void QMediaPlayerPrivate::setMedia(const QUrl &media, QIODevice *stream)
129{
130 setError(QMediaPlayer::NoError, {});
131
132 if (!control)
133 return;
134
135 auto setErrorFn = [&](
136 QMediaPlayer::MediaStatus status,
137 QMediaPlayer::Error err,
138 const QString &errString)
139 {
140 control->setMedia(QUrl(), nullptr);
141 control->mediaStatusChanged(status);
142 control->error(err, errString);
143 };
144
145 std::unique_ptr<QFile> file;
146
147 // Back ends can't play qrc files directly.
148 // If the back end supports StreamPlayback, we pass a QFile for that resource.
149 // If it doesn't, we copy the data to a temporary file and pass its path.
150 if (!media.isEmpty() && !stream && media.scheme() == QLatin1String("qrc")
151 && !control->canPlayQrc()) {
152 qrcMedia = media;
153
154 file.reset(new QFile(QLatin1Char(':') + media.path()));
155 if (!file->open(QFile::ReadOnly)) {
156 file.reset();
157 setErrorFn(
158 QMediaPlayer::InvalidMedia,
159 QMediaPlayer::ResourceError,
160 QMediaPlayer::tr("Attempting to play invalid Qt resource"));
161
162 } else if (control->streamPlaybackSupported()) {
163 control->setMedia(media, file.get());
164 } else {
165#if QT_CONFIG(temporaryfile)
166#if defined(Q_OS_ANDROID)
167 QString tempFileName = QDir::tempPath() + media.path();
168 QDir().mkpath(QFileInfo(tempFileName).path());
169 std::unique_ptr<QTemporaryFile> tempFile { QTemporaryFile::createNativeFile(*file) };
170 if (tempFile.get() == nullptr) {
171 setErrorFn(
172 QMediaPlayer::InvalidMedia,
173 QMediaPlayer::ResourceError,
174 QMediaPlayer::tr("Failed to establish temporary file during playback"));
175 return;
176 }
177 if (!tempFile->rename(tempFileName)) {
178 setErrorFn(
179 QMediaPlayer::InvalidMedia,
180 QMediaPlayer::ResourceError,
181 QStringLiteral("Could not rename temporary file to: %1").arg(tempFileName));
182 return;
183 }
184#else
185 std::unique_ptr<QTemporaryFile> tempFile = std::make_unique<QTemporaryFile>();
186
187 // Preserve original file extension, some back ends might not load the file if it doesn't
188 // have an extension.
189 const QString suffix = QFileInfo(*file).suffix();
190 if (!suffix.isEmpty())
191 tempFile->setFileTemplate(tempFile->fileTemplate() + QLatin1Char('.') + suffix);
192
193 // Copy the qrc data into the temporary file
194 if (!tempFile->open()) {
195 setErrorFn(
196 QMediaPlayer::InvalidMedia,
197 QMediaPlayer::ResourceError,
198 tempFile->errorString());
199 qrcFile.reset();
200 return;
201 }
202 char buffer[4096];
203 while (true) {
204 qint64 len = file->read(buffer, sizeof(buffer));
205 if (len < 1)
206 break;
207 tempFile->write(buffer, len);
208 }
209 tempFile->close();
210#endif
211 file = std::move(tempFile);
212 control->setMedia(QUrl(QUrl::fromLocalFile(file->fileName())), nullptr);
213#else
214 qWarning("Qt was built with -no-feature-temporaryfile: playback from resource file is not supported!");
215#endif
216 }
217 } else {
218 qrcMedia = QUrl();
219 QUrl url = qMediaFromUserInput(media);
220 if (url.scheme() == QLatin1String("content") && !stream) {
221 file.reset(new QFile(media.url()));
222 stream = file.get();
223 }
224
225 control->setMedia(url, stream);
226 }
227
228 qrcFile.swap(file); // Cleans up any previous file
229}
230
231QList<QMediaMetaData> QMediaPlayerPrivate::trackMetaData(QPlatformMediaPlayer::TrackType s) const
232{
233 QList<QMediaMetaData> tracks;
234 if (control) {
235 int count = control->trackCount(s);
236 for (int i = 0; i < count; ++i) {
237 tracks.append(control->trackMetaData(s, i));
238 }
239 }
240 return tracks;
241}
242
243/*!
244 Constructs a QMediaPlayer instance as a child of \a{parent}.
245*/
246
247QMediaPlayer::QMediaPlayer(QObject *parent)
248 : QObject(*new QMediaPlayerPrivate, parent)
249{
250 Q_D(QMediaPlayer);
251
252 auto maybeControl = QPlatformMediaIntegration::instance()->createPlayer(this);
253 if (maybeControl) {
254 d->control = maybeControl.value();
255 d->state = d->control->state();
256 } else {
257 qWarning() << "Failed to initialize QMediaPlayer" << maybeControl.error();
258 d->setError(QMediaPlayer::ResourceError, maybeControl.error());
259 }
260}
261
262
263/*!
264 Destroys the player object.
265*/
266
267QMediaPlayer::~QMediaPlayer()
268{
269 Q_D(QMediaPlayer);
270
271 // prevents emitting audioOutputChanged and videoOutputChanged.
272 QSignalBlocker blocker(this);
273
274 // Reset audio output and video sink to ensure proper unregistering of the source
275 // To be investigated: registering of the source might be removed after switching on the ffmpeg
276 // backend;
277
278 // Workaround to prevent freeze in GStreamer when setting audioOutput while stopped
279 if (d->control)
280 d->control->qmediaplayerDestructorCalled = true;
281 setAudioOutput(nullptr);
282
283 d->setVideoSink(nullptr);
284 delete d->control;
285}
286
287QUrl QMediaPlayer::source() const
288{
289 Q_D(const QMediaPlayer);
290
291 return d->source;
292}
293
294/*!
295 Returns the stream source of media data.
296
297 This is only valid if a stream was passed to setSource().
298
299 \sa setSource()
300*/
301
302const QIODevice *QMediaPlayer::sourceDevice() const
303{
304 Q_D(const QMediaPlayer);
305
306 return d->stream;
307}
308
309/*!
310 \property QMediaPlayer::playbackState
311
312 Returns the \l{QMediaPlayer::}{PlaybackState}.
313
314 \sa playing
315*/
316QMediaPlayer::PlaybackState QMediaPlayer::playbackState() const
317{
318 Q_D(const QMediaPlayer);
319
320 // In case if EndOfMedia status is already received
321 // but state is not.
322 if (d->control
323 && d->control->mediaStatus() == QMediaPlayer::EndOfMedia
324 && d->state != d->control->state()) {
325 return d->control->state();
326 }
327
328 return d->state;
329}
330
331QMediaPlayer::MediaStatus QMediaPlayer::mediaStatus() const
332{
333 Q_D(const QMediaPlayer);
334 return d->control ? d->control->mediaStatus() : NoMedia;
335}
336
337/*!
338 Returns the duration of the current media in ms.
339
340 Returns 0 if the media player doesn't have a valid media file or stream.
341 For live streams, the duration usually changes during playback as more
342 data becomes available.
343*/
344qint64 QMediaPlayer::duration() const
345{
346 Q_D(const QMediaPlayer);
347 return d->control ? d->control->duration() : 0;
348}
349
350/*!
351 Returns the current position inside the media being played back in ms.
352
353 Returns 0 if the media player doesn't have a valid media file or stream.
354 For live streams, the duration usually changes during playback as more
355 data becomes available.
356*/
357qint64 QMediaPlayer::position() const
358{
359 Q_D(const QMediaPlayer);
360 return d->control ? d->control->position() : 0;
361}
362
363/*!
364 Returns a number between 0 and 1 when buffering data.
365
366 0 means that there is no buffered data available, playback is usually
367 stalled in this case. Playback will resume once the buffer reaches 1,
368 meaning enough data has been buffered to be able to resume playback.
369
370 bufferProgress() will always return 1 for local files.
371*/
372float QMediaPlayer::bufferProgress() const
373{
374 Q_D(const QMediaPlayer);
375 return d->control ? d->control->bufferProgress() : 0;
376}
377
378/*!
379 Returns a QMediaTimeRange describing the currently buffered data.
380
381 When streaming media from a remote source, different parts of the media
382 file can be available locally. The returned QMediaTimeRange object describes
383 the time ranges that are buffered and available for immediate playback.
384
385 \sa QMediaTimeRange
386*/
387QMediaTimeRange QMediaPlayer::bufferedTimeRange() const
388{
389 Q_D(const QMediaPlayer);
390 return d->control ? d->control->availablePlaybackRanges() : QMediaTimeRange{};
391}
392
393/*!
394 \qmlproperty bool QtMultimedia::MediaPlayer::hasAudio
395
396 This property holds whether the media contains audio.
397*/
398
399/*!
400 \property QMediaPlayer::hasAudio
401 \brief This property holds whether the media contains audio.
402*/
403bool QMediaPlayer::hasAudio() const
404{
405 Q_D(const QMediaPlayer);
406 return d->control && d->control->isAudioAvailable();
407}
408
409/*!
410 \qmlproperty bool QtMultimedia::MediaPlayer::hasVideo
411
412 This property holds whether the media contains video.
413*/
414
415/*!
416 \property QMediaPlayer::hasVideo
417 \brief This property holds whether the media contains video.
418*/
419bool QMediaPlayer::hasVideo() const
420{
421 Q_D(const QMediaPlayer);
422 return d->control && d->control->isVideoAvailable();
423}
424
425/*!
426 Returns true if the media is seekable. Most file based media files are seekable,
427 but live streams usually are not.
428
429 \sa position
430*/
431bool QMediaPlayer::isSeekable() const
432{
433 Q_D(const QMediaPlayer);
434 return d->control && d->control->isSeekable();
435}
436
437bool QMediaPlayer::isPlaying() const
438{
439 Q_D(const QMediaPlayer);
440 return d->state == QMediaPlayer::PlayingState;
441}
442
443/*!
444 Returns the current playback rate.
445*/
446qreal QMediaPlayer::playbackRate() const
447{
448 Q_D(const QMediaPlayer);
449 return d->control ? d->control->playbackRate() : 0.;
450}
451
452/*!
453 \enum QMediaPlayer::Loops
454
455 Some predefined constants for the \l loops property.
456
457 \value Infinite Loop forever.
458 \value Once Play the media once (the default).
459*/
460
461/*!
462 \property QMediaPlayer::loops
463
464 Determines how often the media is played before the player stops.
465 Set to QMediaPlayer::Infinite to loop the current media file forever.
466
467 The default value is \c 1. Setting this property to \c 0 has no effect.
468*/
469
470/*!
471 \qmlproperty int QtMultimedia::MediaPlayer::loops
472
473 Determines how often the media is played before the player stops.
474 Set to MediaPlayer::Infinite to loop the current media file forever.
475
476 The default value is \c 1. Setting this property to \c 0 has no effect.
477*/
478int QMediaPlayer::loops() const
479{
480 Q_D(const QMediaPlayer);
481 return d->control ? d->control->loops() : 1;
482}
483
484void QMediaPlayer::setLoops(int loops)
485{
486 Q_D(QMediaPlayer);
487 if (loops == 0)
488 return;
489 if (d->control)
490 d->control->setLoops(loops);
491}
492
493/*!
494 Returns the current error state.
495*/
496QMediaPlayer::Error QMediaPlayer::error() const
497{
498 return d_func()->error.code();
499}
500
501/*!
502 \qmlproperty string QtMultimedia::MediaPlayer::errorString
503
504 This property holds a string describing the current error condition in more
505 detail.
506*/
507
508/*!
509 \property QMediaPlayer::errorString
510 \brief This property holds a string describing the current error condition in
511 more detail.
512*/
513QString QMediaPlayer::errorString() const
514{
515 return d_func()->error.description();
516}
517
518/*!
519 \qmlmethod QtMultimedia::MediaPlayer::play()
520
521 Starts or resumes playback of the media.
522
523 Sets the \l playbackState property to PlayingState, and changes
524 \l playing to \c true.
525*/
526
527/*!
528 Start or resume playing the current source.
529
530 \sa pause(), stop()
531*/
532void QMediaPlayer::play()
533{
534 Q_D(QMediaPlayer);
535
536 if (!d->control)
537 return;
538
539 d->control->play();
540}
541
542/*!
543 \qmlmethod QtMultimedia::MediaPlayer::pause()
544
545 Pauses playback of the media.
546
547 Sets the \l playbackState property to PausedState,
548 and changes \l playing to \c false.
549*/
550
551/*!
552 Pause playing the current source.
553
554 \sa play(), stop()
555*/
556void QMediaPlayer::pause()
557{
558 Q_D(QMediaPlayer);
559
560 if (d->control)
561 d->control->pause();
562}
563
564/*!
565 \qmlmethod QtMultimedia::MediaPlayer::stop()
566
567 Stops playback of the media.
568
569 Sets the \l playbackState property to StoppedState,
570 and changes \l playing to \c false.
571*/
572
573/*!
574 Stop playing, and reset the play position to the beginning.
575
576 \sa play(), pause()
577*/
578void QMediaPlayer::stop()
579{
580 Q_D(QMediaPlayer);
581
582 if (d->control)
583 d->control->stop();
584}
585
586void QMediaPlayer::setPosition(qint64 position)
587{
588 Q_D(QMediaPlayer);
589
590 if (!d->control)
591 return;
592 if (!d->control->isSeekable())
593 return;
594 d->control->setPosition(qMax(position, 0ll));
595}
596
597void QMediaPlayer::setPlaybackRate(qreal rate)
598{
599 Q_D(QMediaPlayer);
600
601 if (d->control)
602 d->control->setPlaybackRate(rate);
603}
604
605/*!
606 \qmlproperty url QtMultimedia::MediaPlayer::source
607
608 This property holds the source URL of the media.
609
610 \snippet multimedia-snippets/qtvideosink.qml complete
611
612 \sa QMediaPlayer::setSource()
613*/
614
615/*!
616 Sets the current \a source.
617
618 Setting the media to a null QUrl will cause the player to discard all
619 information relating to the current media source and to cease all I/O operations related
620 to that media. Setting the media will stop the playback.
621
622 \note This function returns immediately after recording the specified source of the media.
623 It does not wait for the media to finish loading and does not check for errors. Listen for
624 the mediaStatusChanged() and error() signals to be notified when the media is loaded and
625 when an error occurs during loading.
626
627 \note FFmpeg, used by the FFmpeg media backend, restricts use of nested protocols for
628 security reasons. In controlled environments where all inputs are trusted, the list of
629 approved protocols can be overridden using the QT_FFMPEG_PROTOCOL_WHITELIST environment
630 variable. This environment variable is Qt's private API and can change between patch
631 releases without notice.
632*/
633
634void QMediaPlayer::setSource(const QUrl &source)
635{
636 Q_D(QMediaPlayer);
637 stop();
638
639 if (d->source == source && d->stream == nullptr)
640 return;
641
642 d->source = source;
643 d->stream = nullptr;
644
645 d->setMedia(source, nullptr);
646 emit sourceChanged(d->source);
647}
648
649/*!
650 Sets the current source \a device.
651
652 The media data will be read from \a device. The \a sourceUrl can be provided
653 to resolve additional information about the media, mime type etc. The
654 \a device must be open and readable.
655
656 For macOS the \a device should also be seek-able.
657
658 \note This function returns immediately after recording the specified source
659 of the media. It does not wait for the media to finish loading and does not
660 check for errors. Listen for the mediaStatusChanged() and error() signals to
661 be notified when the media is loaded, and if an error occurs during loading.
662*/
663void QMediaPlayer::setSourceDevice(QIODevice *device, const QUrl &sourceUrl)
664{
665 Q_D(QMediaPlayer);
666 stop();
667
668 if (d->source == sourceUrl && d->stream == device)
669 return;
670
671 d->source = sourceUrl;
672 d->stream = device;
673
674 d->setMedia(d->source, device);
675 emit sourceChanged(d->source);
676}
677
678/*!
679 \qmlproperty QAudioBufferOutput QtMultimedia::MediaPlayer::audioBufferOutput
680 \since 6.8
681
682 This property holds the target audio buffer output.
683
684 Normal usage of MediaPlayer from QML should not require using this property.
685
686 \sa QMediaPlayer::audioBufferOutput()
687*/
688
689/*!
690 \property QMediaPlayer::audioBufferOutput
691 \since 6.8
692 \brief The output audio buffer used by the media player.
693
694 Sets an audio buffer \a output to the media player.
695
696 If \l QAudioBufferOutput is specified and the media source
697 contains an audio stream, the media player, it will emit
698 the signal \l{QAudioBufferOutput::audioBufferReceived} with
699 audio buffers containing decoded audio data. At the end of
700 the audio stream, \c QMediaPlayer emits an empty \l QAudioBuffer.
701
702 \c QMediaPlayer emits outputs audio buffers at the same time as it
703 pushes the matching data to the audio output if it's specified.
704 However, the sound can be played with a small delay due to
705 audio bufferization.
706
707 The format of emitted audio buffers is taken from the
708 specified \a output or from the matching audio stream
709 if the \a output returns an invalid format. Emitted
710 audio data is not scaled depending on the current playback rate.
711
712 Potential use cases of utilizing \c QAudioBufferOutput
713 with \c QMediaPlayer might be:
714 \list
715 \li Audio visualization. If the playback rate of the media player
716 is not \c 1, you may scale the output image dimensions,
717 or image update interval according to the requirements
718 of the visualizer.
719 \li Any AI sound processing, e.g. voice recognition.
720 \li Sending the data to external audio output.
721 Playback rate changing, synchronization with video, and manual
722 flushing on stoping and seeking should be considered.
723 We don't recommend using the audio buffer output
724 for this purpose unless you have a strong reason for this.
725 \endlist
726
727*/
728void QMediaPlayer::setAudioBufferOutput(QAudioBufferOutput *output)
729{
730 Q_D(QMediaPlayer);
731
732 QAudioBufferOutput *oldOutput = d->audioBufferOutput;
733 if (oldOutput == output)
734 return;
735
736 d->audioBufferOutput = output;
737
738 if (oldOutput) {
739 auto oldPlayer = QAudioBufferOutputPrivate::exchangeMediaPlayer(*oldOutput, this);
740 if (oldPlayer)
741 oldPlayer->setAudioBufferOutput(nullptr);
742 }
743
744 if (d->control)
745 d->control->setAudioBufferOutput(output);
746
747 emit audioBufferOutputChanged();
748}
749
750QAudioBufferOutput *QMediaPlayer::audioBufferOutput() const
751{
752 Q_D(const QMediaPlayer);
753 return d->audioBufferOutput;
754}
755
756/*!
757 \qmlproperty AudioOutput QtMultimedia::MediaPlayer::audioOutput
758
759 This property holds the target audio output.
760 Accepts one AudioOutput elements.
761
762 \sa QMediaPlayer::setAudioOutput()
763*/
764
765
766/*!
767 \property QMediaPlayer::audioOutput
768 \brief The audio output device used by the media player.
769
770 The current audio output to be used when playing back media. Setting
771 a new audio output will replace the currently used output.
772
773 Setting this property to \c nullptr will disable any audio output.
774*/
775void QMediaPlayer::setAudioOutput(QAudioOutput *output)
776{
777 Q_D(QMediaPlayer);
778 auto oldOutput = d->audioOutput;
779 if (oldOutput == output)
780 return;
781 d->audioOutput = output;
782 if (d->control)
783 d->control->setAudioOutput(nullptr);
784 if (oldOutput)
785 oldOutput->setDisconnectFunction({});
786 if (output) {
787 output->setDisconnectFunction([this](){ setAudioOutput(nullptr); });
788 if (d->control)
789 d->control->setAudioOutput(output->handle());
790 }
791 emit audioOutputChanged();
792}
793
794QAudioOutput *QMediaPlayer::audioOutput() const
795{
796 Q_D(const QMediaPlayer);
797 return d->audioOutput;
798}
799
800/*!
801 \qmlproperty list<mediaMetaData> QtMultimedia::MediaPlayer::audioTracks
802
803 This property holds a list of metadata.
804 Each index refers to an audio track.
805
806 The metadata holds properties describing the individual tracks. For
807 audio tracks the \l{QMediaMetaData}{Language} is usually the most
808 important property.
809
810 \sa mediaMetaData
811*/
812
813/*!
814 \property QMediaPlayer::audioTracks
815
816 Lists the set of available audio tracks inside the media.
817
818 The QMediaMetaData returned describes the properties of individual
819 tracks.
820
821 Different audio tracks can for example contain audio in different languages.
822*/
823QList<QMediaMetaData> QMediaPlayer::audioTracks() const
824{
825 Q_D(const QMediaPlayer);
826 return d->trackMetaData(QPlatformMediaPlayer::AudioStream);
827}
828
829/*!
830 \qmlproperty list<mediaMetaData> QtMultimedia::MediaPlayer::videoTracks
831
832 This property holds a list of metadata.
833 Each index refers to a video track.
834
835 The metadata holds properties describing the individual tracks.
836
837 \sa mediaMetaData
838*/
839
840/*!
841 \property QMediaPlayer::videoTracks
842
843 Lists the set of available video tracks inside the media.
844
845 The QMediaMetaData returned describes the properties of individual
846 tracks.
847*/
848QList<QMediaMetaData> QMediaPlayer::videoTracks() const
849{
850 Q_D(const QMediaPlayer);
851 return d->trackMetaData(QPlatformMediaPlayer::VideoStream);
852}
853
854/*!
855 \qmlproperty list<mediaMetaData> QtMultimedia::MediaPlayer::subtitleTracks
856
857 This property holds a list of metadata.
858 Each index refers to a subtitle track.
859
860 The metadata holds properties describing the individual tracks. For
861 subtitle tracks the \l{QMediaMetaData}{Language} is usually the most
862 important property.
863
864 \sa mediaMetaData
865*/
866
867/*!
868 \property QMediaPlayer::subtitleTracks
869
870 Lists the set of available subtitle tracks inside the media.
871
872 The QMediaMetaData returned describes the properties of individual
873 tracks.
874*/
875QList<QMediaMetaData> QMediaPlayer::subtitleTracks() const
876{
877 Q_D(const QMediaPlayer);
878 return d->trackMetaData(QPlatformMediaPlayer::SubtitleStream);
879}
880
881/*!
882 \qmlproperty int QtMultimedia::MediaPlayer::activeAudioTrack
883
884 This property holds the track number of the currently active audio track.
885 Set to \c{-1} to disable audio track.
886
887 The default property value is \c{0}: the first audio track.
888*/
889
890/*!
891 \property QMediaPlayer::activeAudioTrack
892 \brief Returns the currently active audio track.
893
894 By default, the first available audio track will be chosen.
895
896 Set \a index to \c -1 to disable all audio tracks.
897*/
898int QMediaPlayer::activeAudioTrack() const
899{
900 Q_D(const QMediaPlayer);
901 return d->control ? d->control->activeTrack(QPlatformMediaPlayer::AudioStream) : 0;
902}
903
904/*!
905 \since 6.2
906 \qmlproperty int QtMultimedia::MediaPlayer::activeVideoTrack
907
908 This property holds the track number of the currently active video audio track.
909 Set to \c{-1} to disable video track.
910
911 The default property value is \c{0}: the first video track.
912*/
913
914/*!
915 \property QMediaPlayer::activeVideoTrack
916 \brief Returns the currently active video track.
917
918 By default, the first available audio track will be chosen.
919
920 Set \a index to \c -1 to disable all video tracks.
921*/
922int QMediaPlayer::activeVideoTrack() const
923{
924 Q_D(const QMediaPlayer);
925 return d->control ? d->control->activeTrack(QPlatformMediaPlayer::VideoStream) : -1;
926}
927
928/*!
929 \since 6.2
930 \qmlproperty int QtMultimedia::MediaPlayer::activeSubtitleTrack
931
932 This property holds the track number of the currently active subtitle track.
933 Set to \c{-1} to disable subtitle track.
934
935 The default property value is \c{-1}: no subtitles active.
936*/
937
938/*!
939 \property QMediaPlayer::activeSubtitleTrack
940 \brief Returns the currently active subtitle track.
941
942 Set \a index to \c -1 to disable subtitles.
943
944 Subtitles are disabled by default.
945*/
946int QMediaPlayer::activeSubtitleTrack() const
947{
948 Q_D(const QMediaPlayer);
949 return d->control ? d->control->activeTrack(QPlatformMediaPlayer::SubtitleStream) : -1;
950}
951
952void QMediaPlayer::setActiveAudioTrack(int index)
953{
954 Q_D(QMediaPlayer);
955 if (!d->control)
956 return;
957
958 if (activeAudioTrack() == index)
959 return;
960 d->control->setActiveTrack(QPlatformMediaPlayer::AudioStream, index);
961}
962
963void QMediaPlayer::setActiveVideoTrack(int index)
964{
965 Q_D(QMediaPlayer);
966 if (!d->control)
967 return;
968
969 if (activeVideoTrack() == index)
970 return;
971 d->control->setActiveTrack(QPlatformMediaPlayer::VideoStream, index);
972}
973
974void QMediaPlayer::setActiveSubtitleTrack(int index)
975{
976 Q_D(QMediaPlayer);
977 if (!d->control)
978 return;
979
980 if (activeSubtitleTrack() == index)
981 return;
982 d->control->setActiveTrack(QPlatformMediaPlayer::SubtitleStream, index);
983}
984
985/*!
986 \qmlproperty VideoOutput QtMultimedia::MediaPlayer::videoOutput
987
988 This property holds the target video output.
989 Accepts one VideoOutput elements.
990
991 \sa QMediaPlayer::setVideoOutput()
992*/
993
994/*!
995 \property QMediaPlayer::videoOutput
996 \brief The video output to be used by the media player.
997
998 A media player can only have one video output attached, so
999 setting this property will replace the previously connected
1000 video output.
1001
1002 Setting this property to \c nullptr will disable video output.
1003*/
1004QObject *QMediaPlayer::videoOutput() const
1005{
1006 Q_D(const QMediaPlayer);
1007 return d->videoOutput;
1008}
1009
1010void QMediaPlayer::setVideoOutput(QObject *output)
1011{
1012 Q_D(QMediaPlayer);
1013 if (d->videoOutput == output)
1014 return;
1015
1016 auto *sink = qobject_cast<QVideoSink *>(output);
1017 if (!sink && output) {
1018 auto *mo = output->metaObject();
1019 mo->invokeMethod(output, "videoSink", Q_RETURN_ARG(QVideoSink *, sink));
1020 }
1021 d->videoOutput = output;
1022 d->setVideoSink(sink);
1023}
1024
1025/*!
1026 Sets \a sink to be the QVideoSink instance to
1027 retrieve video data.
1028*/
1029void QMediaPlayer::setVideoSink(QVideoSink *sink)
1030{
1031 Q_D(QMediaPlayer);
1032 d->videoOutput = nullptr;
1033 d->setVideoSink(sink);
1034}
1035
1036/*!
1037 Returns the QVideoSink instance.
1038*/
1039QVideoSink *QMediaPlayer::videoSink() const
1040{
1041 Q_D(const QMediaPlayer);
1042 return d->videoSink;
1043}
1044
1045
1046#if 0
1047/*
1048 \since 5.15
1049 Sets multiple video sinks as the video output of a media player.
1050 This allows the media player to render video frames on several outputs.
1051
1052 If a video output has already been set on the media player the new surfaces
1053 will replace it.
1054*/
1055void QMediaPlayer::setVideoOutput(const QList<QVideoSink *> &sinks)
1056{
1057 // ### IMPLEMENT ME
1058 Q_UNUSED(sinks);
1059// setVideoOutput(!surfaces.empty() ? new QVideoSurfaces(surfaces, this) : nullptr);
1060}
1061#endif
1062
1063/*!
1064 Returns true if the media player is supported on this platform.
1065*/
1066bool QMediaPlayer::isAvailable() const
1067{
1068 Q_D(const QMediaPlayer);
1069 return bool(d->control);
1070}
1071
1072/*!
1073 \qmlproperty mediaMetaData QtMultimedia::MediaPlayer::metaData
1074
1075 Returns meta data for the current media used by the media player.
1076
1077 Meta data can contain information such as the title of the video or its creation date.
1078
1079 \note The Windows implementation provides metadata only for media located on the local file
1080 system.
1081*/
1082
1083/*!
1084 \property QMediaPlayer::metaData
1085
1086 Returns meta data for the current media used by the media player.
1087
1088 Meta data can contain information such as the title of the video or its creation date.
1089
1090 \note The Windows implementation provides metadata only for media located on the local file
1091 system.
1092*/
1093QMediaMetaData QMediaPlayer::metaData() const
1094{
1095 Q_D(const QMediaPlayer);
1096 return d->control ? d->control->metaData() : QMediaMetaData{};
1097}
1098
1099/*!
1100 \qmlproperty bool QtMultimedia::MediaPlayer::pitchCompensation
1101 \since 6.10
1102
1103 This property holds whether pitch compensation is enabled.
1104*/
1105
1106/*!
1107 \property QMediaPlayer::pitchCompensation
1108 \brief The pitch compensation status of the media player.
1109 \since 6.10
1110
1111 Indicates whether pitch compensation is enabled. When enabled, changing the playback rate
1112 will not affect the pitch of the audio signal.
1113
1114 \note The pitch compensation will increase the CPU load of the QMediaPlayer.
1115
1116 By default is \c{true} if pitch compensation, is available, else \c{false}.
1117*/
1118
1119/*!
1120 Returns the state of pitch compensation.
1121 \since 6.10
1122*/
1123bool QMediaPlayer::pitchCompensation() const
1124{
1125 Q_D(const QMediaPlayer);
1126 return d->control ? d->control->pitchCompensation() : false;
1127}
1128
1129/*!
1130 Sets the state (\a enabled or disabled) of pitch compensation. This only
1131 has an effect if the audio pitch compensation can be configured on the
1132 backend at runtime.
1133 \since 6.10
1134*/
1135void QMediaPlayer::setPitchCompensation(bool enabled) const
1136{
1137 Q_D(const QMediaPlayer);
1138 if (d->control)
1139 d->control->setPitchCompensation(enabled);
1140}
1141
1142/*!
1143 \enum QMediaPlayer::PitchCompensationAvailability
1144 \since 6.10
1145
1146 Availablility of pitch compensation.
1147
1148 Different backends have different behavior regarding pitch compensation when changing
1149 playback rate.
1150
1151 \value AlwaysOn The media player is always performing pitch compensation.
1152 \value Available The media player can be configured to use pitch compensation.
1153 If pitch compensation is available on the current platform, it will be enabled by default,
1154 but users can disable if needed.
1155 \value Unavailable The media player is not able to perform pitch compensation
1156 on the current platform.
1157*/
1158
1159/*!
1160 \qmlproperty enumeration QtMultimedia::MediaPlayer::pitchCompensationAvailability
1161 \since 6.10
1162
1163 Indicates the availability of pitch compensation of the \c MediaPlayer on the current backend.
1164 The enumeration \c PitchCompensationAvailability is scoped.
1165
1166 \qmlenumeratorsfrom QMediaPlayer::PitchCompensationAvailability
1167*/
1168
1169/*!
1170 \property QMediaPlayer::pitchCompensationAvailability
1171 \brief The pitch compensation availability of the current QtMultimedia backend.
1172 \since 6.10
1173
1174 Indicates the availability of pitch compensation of the QMediaPlayer on the current backend.
1175
1176 \note Different backends may have different behavior.
1177
1178 For more information, see \l{QMediaPlayer::PitchCompensationAvailability}.
1179*/
1180
1181/*!
1182 Returns availability of pitch compensation of the current backend.
1183 \since 6.10
1184*/
1185
1186QMediaPlayer::PitchCompensationAvailability QMediaPlayer::pitchCompensationAvailability() const
1187{
1188 Q_D(const QMediaPlayer);
1189 return d->control->pitchCompensationAvailability();
1190}
1191
1192/*!
1193 \qmlproperty playbackOptions MediaPlayer::playbackOptions
1194 \since 6.10
1195
1196 This property exposes the \l playbackOptions API that gives low-level control of media playback
1197 options. Although we strongly recommend to rely on the default settings of \l MediaPlayer,
1198 this API can be used to optimize media playback for specific use cases where the default
1199 options are not ideal.
1200
1201 Playback options take effect the next time \l MediaPlayer::source is changed.
1202*/
1203
1204/*!
1205 \property QMediaPlayer::playbackOptions
1206 \brief Advanced playback options used to configure media playback and decoding.
1207 \since 6.10
1208
1209 This property exposes the \l QPlaybackOptions API that gives low-level control of media
1210 playback options. Although we strongly recommend to rely on the default settings of
1211 \l QMediaPlayer, this API can be used to optimize media playback for specific use cases where
1212 the default options are not ideal.
1213
1214 Playback options take effect the next time \l QMediaPlayer::setSource() is called.
1215*/
1216
1217QPlaybackOptions QMediaPlayer::playbackOptions() const
1218{
1219 Q_D(const QMediaPlayer);
1220 return d->playbackOptions;
1221}
1222
1223void QMediaPlayer::setPlaybackOptions(const QPlaybackOptions &options)
1224{
1225 Q_D(QMediaPlayer);
1226 if (std::exchange(d->playbackOptions, options) != options)
1227 emit playbackOptionsChanged();
1228}
1229
1230void QMediaPlayer::resetPlaybackOptions()
1231{
1232 Q_D(QMediaPlayer);
1233 QPlaybackOptions defaultOptions{ };
1234 if (std::exchange(d->playbackOptions, defaultOptions) != defaultOptions)
1235 emit playbackOptionsChanged();
1236}
1237
1238// Enums
1239/*!
1240 \enum QMediaPlayer::PlaybackState
1241
1242 Defines the current state of a media player.
1243
1244 \value StoppedState The media player is not playing content, playback will begin from the start
1245 of the current track.
1246 \value PlayingState The media player is currently playing content. This indicates the same as the \l playing property.
1247 \value PausedState The media player has paused playback, playback of the current track will
1248 resume from the position the player was paused at.
1249*/
1250
1251/*!
1252 \qmlproperty enumeration QtMultimedia::MediaPlayer::playbackState
1253
1254 This property holds the state of media playback. It can be one of the following:
1255
1256 \table
1257 \header \li Property value
1258 \li Description
1259 \row \li PlayingState
1260 \li The media is currently playing. This indicates the same as the \l playing property.
1261 \row \li PausedState
1262 \li Playback of the media has been suspended.
1263 \row \li StoppedState
1264 \li Playback of the media is yet to begin.
1265 \endtable
1266*/
1267
1268/*!
1269 \qmlsignal QtMultimedia::MediaPlayer::playbackStateChanged()
1270
1271 This signal is emitted when the \l playbackState property is altered.
1272*/
1273
1274/*!
1275 \qmlsignal QtMultimedia::MediaPlayer::playingChanged()
1276
1277 This signal is emitted when the \l playing property changes.
1278*/
1279
1280/*!
1281 \enum QMediaPlayer::MediaStatus
1282
1283 Defines the status of a media player's current media.
1284
1285 \value NoMedia The is no current media. The player is in the StoppedState.
1286 \value LoadingMedia The current media is being loaded. The player may be in any state.
1287 \value LoadedMedia The current media has been loaded. The player is in the StoppedState.
1288 \value StalledMedia Playback of the current media has stalled due to insufficient buffering or
1289 some other temporary interruption. The player is in the PlayingState or PausedState.
1290 \value BufferingMedia The player is buffering data but has enough data buffered for playback to
1291 continue for the immediate future. The player is in the PlayingState or PausedState.
1292 \value BufferedMedia The player has fully buffered the current media. The player is in the
1293 PlayingState or PausedState.
1294 \value EndOfMedia Playback has reached the end of the current media. The player is in the
1295 StoppedState.
1296 \value InvalidMedia The current media cannot be played. The player is in the StoppedState.
1297*/
1298
1299/*!
1300 \qmlproperty enumeration QtMultimedia::MediaPlayer::mediaStatus
1301
1302 This property holds the status of media loading. It can be one of the following:
1303
1304 \table
1305 \header
1306 \li Property value
1307 \li Description
1308 \row \li NoMedia
1309 \li No media has been set.
1310 \row \li LoadingMedia
1311 \li The media is currently being loaded.
1312 \row \li LoadedMedia
1313 \li The media has been loaded.
1314 \row \li BufferingMedia
1315 \li The media is buffering data.
1316 \row \li StalledMedia
1317 \li Playback has been interrupted while the media is buffering data.
1318 \row \li BufferedMedia
1319 \li The media has buffered data.
1320 \row \li EndOfMedia
1321 \li The media has played to the end.
1322 \row \li InvalidMedia
1323 \li The media cannot be played.
1324 \endtable
1325*/
1326
1327/*!
1328 \qmlproperty enumeration QtMultimedia::MediaPlayer::error
1329
1330 This property holds the error state of the audio. It can be one of the following.
1331
1332 \table
1333 \header \li Value \li Description
1334 \row \li NoError
1335 \li There is no current error.
1336 \row \li ResourceError
1337 \li The audio cannot be played due to a problem allocating resources.
1338 \row \li FormatError
1339 \li The audio format is not supported.
1340 \row \li NetworkError
1341 \li The audio cannot be played due to network issues.
1342 \row \li AccessDeniedError
1343 \li The audio cannot be played due to insufficient permissions.
1344 \endtable
1345*/
1346
1347/*!
1348 \enum QMediaPlayer::Error
1349
1350 Defines a media player error condition.
1351
1352 \value NoError No error has occurred.
1353 \value ResourceError A media resource couldn't be resolved.
1354 \value FormatError The format of a media resource isn't (fully) supported. Playback may still
1355 be possible, but without an audio or video component.
1356 \value NetworkError A network error occurred.
1357 \value AccessDeniedError There are not the appropriate permissions to play a media resource.
1358*/
1359
1360/*!
1361 \qmlsignal QtMultimedia::MediaPlayer::errorOccurred(error, errorString)
1362
1363 This signal is emitted when an \a error has occurred. The \a errorString
1364 parameter may contain more detailed information about the error.
1365
1366 \sa QMediaPlayer::Error
1367*/
1368
1369/*!
1370 \fn QMediaPlayer::errorOccurred(QMediaPlayer::Error error, const QString &errorString)
1371
1372 Signals that an \a error condition has occurred, with \a errorString
1373 containing a description of the error.
1374
1375 \sa errorString()
1376*/
1377
1378/*!
1379 \fn QMediaPlayer::mediaStatusChanged(QMediaPlayer::MediaStatus status)
1380
1381 Signals that the \a status of the current media has changed.
1382
1383 \sa mediaStatus()
1384*/
1385
1386/*!
1387 \fn void QMediaPlayer::sourceChanged(const QUrl &media);
1388
1389 Signals that the media source has been changed to \a media.
1390*/
1391
1392/*!
1393 \fn void QMediaPlayer::playbackRateChanged(qreal rate);
1394
1395 Signals the playbackRate has changed to \a rate.
1396*/
1397
1398/*!
1399 \fn void QMediaPlayer::seekableChanged(bool seekable);
1400
1401 Signals the \a seekable status of the player object has changed.
1402*/
1403
1404// Properties
1405/*!
1406 \property QMediaPlayer::error
1407 \brief a string describing the last error condition.
1408
1409 \sa error()
1410*/
1411
1412/*!
1413 \property QMediaPlayer::source
1414 \brief the active media source being used by the player object.
1415
1416 The player object will use the QUrl for selection of the content to
1417 be played.
1418
1419 By default this property has a null QUrl.
1420
1421 Setting this property to a null QUrl will cause the player to discard all
1422 information relating to the current media source and to cease all I/O operations related
1423 to that media.
1424
1425 \sa QUrl
1426*/
1427
1428/*!
1429 \property QMediaPlayer::mediaStatus
1430 \brief the status of the current media stream.
1431
1432 The stream status describes how the playback of the current stream is
1433 progressing.
1434
1435 By default this property is QMediaPlayer::NoMedia
1436
1437*/
1438
1439/*!
1440 \qmlproperty int QtMultimedia::MediaPlayer::duration
1441
1442 This property holds the duration of the media in milliseconds.
1443
1444 If the media doesn't have a fixed duration (a live stream for example) this
1445 will be set to \c{0}.
1446*/
1447
1448/*!
1449 \property QMediaPlayer::duration
1450 \brief the duration of the current media.
1451
1452 The value is the total playback time in milliseconds of the current media.
1453 The value may change across the life time of the QMediaPlayer object and
1454 may not be available when initial playback begins, connect to the
1455 durationChanged() signal to receive status notifications.
1456*/
1457
1458/*!
1459 \qmlproperty int QtMultimedia::MediaPlayer::position
1460
1461 The value is the current playback position, expressed in milliseconds since
1462 the beginning of the media. Periodically changes in the position will be
1463 indicated with the positionChanged() signal.
1464
1465 If the \l seekable property is true, this property can be set to milliseconds.
1466*/
1467
1468/*!
1469 \property QMediaPlayer::position
1470 \brief the playback position of the current media.
1471
1472 The value is the current playback position, expressed in milliseconds since
1473 the beginning of the media. Periodically changes in the position will be
1474 indicated with the positionChanged() signal.
1475
1476 If the \l seekable property is true, this property can be set to milliseconds.
1477*/
1478
1479/*!
1480 \qmlproperty real QtMultimedia::MediaPlayer::bufferProgress
1481
1482 This property holds how much of the data buffer is currently filled,
1483 from \c 0.0 (empty) to \c 1.0 (full).
1484
1485 Playback can start or resume only when the buffer is entirely filled.
1486 When the buffer is filled, \c MediaPlayer.Buffered is true.
1487 When buffer progress is between \c 0.0 and \c 1.0, \c MediaPlayer.Buffering
1488 is set to \c{true}.
1489
1490 A value lower than \c 1.0 implies that the property \c MediaPlayer.StalledMedia
1491 is \c{true}.
1492
1493 \sa mediaStatus
1494 */
1495
1496/*!
1497 \property QMediaPlayer::bufferProgress
1498 \brief the percentage of the temporary buffer filled before playback begins or resumes, from
1499 \c 0. (empty) to \c 1. (full).
1500
1501 When the player object is buffering; this property holds the percentage of
1502 the temporary buffer that is filled. The buffer will need to reach 100%
1503 filled before playback can start or resume, at which time mediaStatus() will return
1504 BufferedMedia or BufferingMedia. If the value is anything lower than \c 100, mediaStatus() will
1505 return StalledMedia.
1506
1507 \sa mediaStatus()
1508*/
1509
1510/*!
1511 \qmlproperty bool QtMultimedia::MediaPlayer::seekable
1512
1513 This property holds whether the \l position of the media can be changed.
1514*/
1515
1516/*!
1517 \property QMediaPlayer::seekable
1518 \brief the seek-able status of the current media
1519
1520 If seeking is supported this property will be true; false otherwise. The
1521 status of this property may change across the life time of the QMediaPlayer
1522 object, use the seekableChanged signal to monitor changes.
1523*/
1524
1525/*!
1526 \qmlproperty bool QtMultimedia::MediaPlayer::playing
1527 \since 6.5
1528
1529 Indicates whether the media is currently playing.
1530
1531 \sa playbackState
1532*/
1533
1534/*!
1535 \property QMediaPlayer::playing
1536 \brief Whether the media is playing.
1537 \since 6.5
1538
1539 \sa playbackState, PlayingState
1540*/
1541
1542/*!
1543 \qmlproperty real QtMultimedia::MediaPlayer::playbackRate
1544
1545 This property holds the rate at which media is played at as a multiple of
1546 the normal rate.
1547
1548 For more information, see \l{QMediaPlayer::playbackRate}.
1549
1550 Defaults to \c{1.0}.
1551*/
1552
1553/*!
1554 \property QMediaPlayer::playbackRate
1555 \brief the playback rate of the current media.
1556
1557 This value is a multiplier applied to the media's standard playback
1558 rate. By default this value is 1.0, indicating that the media is
1559 playing at the standard speed. Values higher than 1.0 will increase
1560 the playback speed, while values between 0.0 and 1.0 results in
1561 slower playback. Negative playback rates are not supported.
1562
1563 Not all playback services support change of the playback rate. It is
1564 framework defined as to the status and quality of audio and video
1565 while fast forwarding or rewinding.
1566*/
1567
1568/*!
1569 \fn void QMediaPlayer::durationChanged(qint64 duration)
1570
1571 Signals the duration of the content has changed to \a duration, expressed in milliseconds.
1572*/
1573
1574/*!
1575 \fn void QMediaPlayer::positionChanged(qint64 position)
1576
1577 Signals the position of the content has changed to \a position, expressed in
1578 milliseconds.
1579*/
1580
1581/*!
1582 \fn void QMediaPlayer::hasVideoChanged(bool videoAvailable)
1583
1584 Signals the availability of visual content has changed to \a videoAvailable.
1585*/
1586
1587/*!
1588 \fn void QMediaPlayer::hasAudioChanged(bool available)
1589
1590 Signals the availability of audio content has changed to \a available.
1591*/
1592
1593/*!
1594 \fn void QMediaPlayer::bufferProgressChanged(float filled)
1595
1596 Signals the amount of the local buffer \a filled as a number between 0 and 1.
1597*/
1598
1599QT_END_NAMESPACE
1600
1601#include "moc_qmediaplayer.cpp"
QPlatformMediaPlayer * control
void setState(QMediaPlayer::PlaybackState state)
\qmltype MediaPlayer \nativetype QMediaPlayer
QList< QMediaMetaData > trackMetaData(QPlatformMediaPlayer::TrackType s) const
void setMedia(const QUrl &media, QIODevice *stream=nullptr)
void setStatus(QMediaPlayer::MediaStatus status)