/
MediaPlayerPrivateGStreamer.cpp
4193 lines (3518 loc) · 164 KB
/
MediaPlayerPrivateGStreamer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2007, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2007 Collabora Ltd. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2009 Gustavo Noronha Silva <gns@gnome.org>
* Copyright (C) 2014 Cable Television Laboratories, Inc.
* Copyright (C) 2009, 2019 Igalia S.L
* Copyright (C) 2015, 2019 Metrological Group B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* aint with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "MediaPlayerPrivateGStreamer.h"
#include "VideoFrameGStreamer.h"
#if ENABLE(VIDEO) && USE(GSTREAMER)
#include "GraphicsContext.h"
#include "GStreamerAudioMixer.h"
#include "GStreamerCommon.h"
#include "GStreamerRegistryScanner.h"
#include "HTTPHeaderNames.h"
#include "ImageGStreamer.h"
#include "ImageOrientation.h"
#include "IntRect.h"
#include "Logging.h"
#include "MediaPlayer.h"
#include "MediaPlayerRequestInstallMissingPluginsCallback.h"
#include "MIMETypeRegistry.h"
#include "NotImplemented.h"
#include "SecurityOrigin.h"
#include "TimeRanges.h"
#include "VideoSinkGStreamer.h"
#include "WebKitAudioSinkGStreamer.h"
#include "WebKitWebSourceGStreamer.h"
#include "AudioTrackPrivateGStreamer.h"
#include "InbandMetadataTextTrackPrivateGStreamer.h"
#include "InbandTextTrackPrivateGStreamer.h"
#include "TextCombinerGStreamer.h"
#include "TextSinkGStreamer.h"
#include "VideoFrameMetadataGStreamer.h"
#include "VideoTrackPrivateGStreamer.h"
#if ENABLE(MEDIA_STREAM)
#include "GStreamerMediaStreamSource.h"
#include "MediaStreamPrivate.h"
#endif
#if ENABLE(MEDIA_SOURCE)
#include "MediaSource.h"
#include "WebKitMediaSourceGStreamer.h"
#endif
#if ENABLE(ENCRYPTED_MEDIA)
#include "CDMInstance.h"
#include "GStreamerEMEUtilities.h"
#include "SharedBuffer.h"
#include "WebKitCommonEncryptionDecryptorGStreamer.h"
#endif
#if ENABLE(WEB_AUDIO)
#include "AudioSourceProviderGStreamer.h"
#endif
#include <cstring>
#include <glib.h>
#include <gst/audio/streamvolume.h>
#include <gst/gst.h>
#include <gst/pbutils/missing-plugins.h>
#include <gst/video/gstvideometa.h>
#include <limits>
#include <wtf/FileSystem.h>
#include <wtf/glib/GUniquePtr.h>
#include <wtf/glib/RunLoopSourcePriority.h>
#include <wtf/MathExtras.h>
#include <wtf/MediaTime.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/Scope.h>
#include <wtf/StdLibExtras.h>
#include <wtf/StringPrintStream.h>
#include <wtf/text/AtomString.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringConcatenateNumbers.h>
#include <wtf/UniStdExtras.h>
#include <wtf/URL.h>
#include <wtf/WallTime.h>
#if USE(GSTREAMER_MPEGTS)
#define GST_USE_UNSTABLE_API
#include <gst/mpegts/mpegts.h>
#undef GST_USE_UNSTABLE_API
#endif // ENABLE(VIDEO) && USE(GSTREAMER_MPEGTS)
#if USE(GSTREAMER_GL)
#include "GLVideoSinkGStreamer.h"
#include "VideoTextureCopierGStreamer.h"
#define TEXTURE_COPIER_COLOR_CONVERT_FLAG VideoTextureCopierGStreamer::ColorConversion::NoConvert
#endif // USE(GSTREAMER_GL)
#if USE(TEXTURE_MAPPER_GL)
#include "BitmapTextureGL.h"
#include "BitmapTexturePool.h"
#include "GStreamerVideoFrameHolder.h"
#include "TextureMapperContextAttributes.h"
#include "TextureMapperPlatformLayerBuffer.h"
#include "TextureMapperPlatformLayerProxyGL.h"
#endif // USE(TEXTURE_MAPPER_GL)
#if USE(TEXTURE_MAPPER_DMABUF)
#include "DMABufFormat.h"
#include "DMABufObject.h"
#include "DMABufVideoSinkGStreamer.h"
#include "GBMBufferSwapchain.h"
#include "GBMDevice.h"
#include "TextureMapperPlatformLayerProxyDMABuf.h"
#include <gbm.h>
#include <gst/allocators/gstdmabuf.h>
#endif // USE(TEXTURE_MAPPER_DMABUF)
#if USE(WPE_VIDEO_PLANE_DISPLAY_DMABUF)
#include "PlatformDisplayLibWPE.h"
#include <gst/gl/egl/gsteglimage.h>
#include <gst/gl/egl/gstglmemoryegl.h>
#include <wpe/extensions/video-plane-display-dmabuf.h>
#endif
GST_DEBUG_CATEGORY(webkit_media_player_debug);
#define GST_CAT_DEFAULT webkit_media_player_debug
namespace WebCore {
using namespace std;
#if USE(GSTREAMER_HOLEPUNCH)
static const FloatSize s_holePunchDefaultFrameSize(1280, 720);
#endif
static void initializeDebugCategory()
{
static std::once_flag onceFlag;
std::call_once(onceFlag, [] {
GST_DEBUG_CATEGORY_INIT(webkit_media_player_debug, "webkitmediaplayer", 0, "WebKit media player");
});
}
MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
: m_notifier(MainThreadNotifier<MainThreadNotification>::create())
, m_player(player)
, m_referrer(player->referrer())
, m_cachedDuration(MediaTime::invalidTime())
, m_seekTime(MediaTime::invalidTime())
, m_timeOfOverlappingSeek(MediaTime::invalidTime())
, m_fillTimer(*this, &MediaPlayerPrivateGStreamer::fillTimerFired)
, m_maxTimeLoaded(MediaTime::zeroTime())
, m_preload(player->preload())
, m_maxTimeLoadedAtLastDidLoadingProgress(MediaTime::zeroTime())
, m_drawTimer(RunLoop::main(), this, &MediaPlayerPrivateGStreamer::repaint)
, m_readyTimerHandler(RunLoop::main(), this, &MediaPlayerPrivateGStreamer::readyTimerFired)
#if USE(TEXTURE_MAPPER_GL) && !USE(NICOSIA)
, m_platformLayerProxy(adoptRef(new TextureMapperPlatformLayerProxyGL))
#endif
#if !RELEASE_LOG_DISABLED
, m_logger(player->mediaPlayerLogger())
, m_logIdentifier(player->mediaPlayerLogIdentifier())
#endif
#if USE(TEXTURE_MAPPER_DMABUF)
, m_swapchain(adoptRef(new GBMBufferSwapchain(GBMBufferSwapchain::BufferSwapchainSize::Eight)))
#endif
{
#if USE(GLIB)
m_readyTimerHandler.setPriority(G_PRIORITY_DEFAULT_IDLE);
#endif
m_isPlayerShuttingDown.store(false);
#if USE(TEXTURE_MAPPER_GL) && USE(NICOSIA)
m_nicosiaLayer = Nicosia::ContentLayer::create(Nicosia::ContentLayerTextureMapperImpl::createFactory(*this,
[&]() -> Ref<TextureMapperPlatformLayerProxy> {
#if USE(TEXTURE_MAPPER_DMABUF)
if (webKitDMABufVideoSinkIsEnabled() && webKitDMABufVideoSinkProbePlatform())
return adoptRef(*new TextureMapperPlatformLayerProxyDMABuf);
#endif
return adoptRef(*new TextureMapperPlatformLayerProxyGL);
}()));
#endif
ensureGStreamerInitialized();
m_audioSink = createAudioSink();
#if USE(WPE_VIDEO_PLANE_DISPLAY_DMABUF)
auto& sharedDisplay = PlatformDisplay::sharedDisplay();
if (is<PlatformDisplayLibWPE>(sharedDisplay))
m_wpeVideoPlaneDisplayDmaBuf.reset(wpe_video_plane_display_dmabuf_source_create(downcast<PlatformDisplayLibWPE>(sharedDisplay).backend()));
#endif
}
MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
{
GST_DEBUG_OBJECT(pipeline(), "Disposing player");
m_isPlayerShuttingDown.store(true);
m_sinkTaskQueue.startAborting();
for (auto& track : m_audioTracks.values())
track->disconnect();
for (auto& track : m_textTracks.values())
track->disconnect();
for (auto& track : m_videoTracks.values())
track->disconnect();
if (m_fillTimer.isActive())
m_fillTimer.stop();
m_readyTimerHandler.stop();
for (auto& missingPluginCallback : m_missingPluginCallbacks) {
if (missingPluginCallback)
missingPluginCallback->invalidate();
}
m_missingPluginCallbacks.clear();
if (m_videoSink) {
GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_videoSink.get(), "sink"));
g_signal_handlers_disconnect_matched(videoSinkPad.get(), G_SIGNAL_MATCH_DATA, 0, 0, nullptr, nullptr, this);
}
if (m_pipeline) {
disconnectSimpleBusMessageCallback(m_pipeline.get());
g_signal_handlers_disconnect_matched(m_pipeline.get(), G_SIGNAL_MATCH_DATA, 0, 0, nullptr, nullptr, this);
}
#if USE(GSTREAMER_GL)
if (m_videoDecoderPlatform == GstVideoDecoderPlatform::Video4Linux)
flushCurrentBuffer();
#endif
#if USE(TEXTURE_MAPPER_GL) && USE(NICOSIA)
downcast<Nicosia::ContentLayerTextureMapperImpl>(m_nicosiaLayer->impl()).invalidateClient();
#endif
if (m_videoSink)
g_signal_handlers_disconnect_matched(m_videoSink.get(), G_SIGNAL_MATCH_DATA, 0, 0, nullptr, nullptr, this);
if (m_volumeElement)
g_signal_handlers_disconnect_matched(m_volumeElement.get(), G_SIGNAL_MATCH_DATA, 0, 0, nullptr, nullptr, this);
// This will release the GStreamer thread from m_drawCondition in non AC mode in case there's an ongoing triggerRepaint call
// waiting there, and ensure that any triggerRepaint call reaching the lock won't wait on m_drawCondition.
cancelRepaint(true);
#if ENABLE(ENCRYPTED_MEDIA)
{
Locker cdmAttachmentLocker { m_cdmAttachmentLock };
m_cdmAttachmentCondition.notifyAll();
}
#endif
// The change to GST_STATE_NULL state is always synchronous. So after this gets executed we don't need to worry
// about handlers running in the GStreamer thread.
if (m_pipeline)
gst_element_set_state(m_pipeline.get(), GST_STATE_NULL);
m_player = nullptr;
m_notifier->invalidate();
}
bool MediaPlayerPrivateGStreamer::isAvailable()
{
return true;
}
class MediaPlayerFactoryGStreamer final : public MediaPlayerFactory {
private:
MediaPlayerEnums::MediaEngineIdentifier identifier() const final { return MediaPlayerEnums::MediaEngineIdentifier::GStreamer; };
std::unique_ptr<MediaPlayerPrivateInterface> createMediaEnginePlayer(MediaPlayer* player) const final
{
return makeUnique<MediaPlayerPrivateGStreamer>(player);
}
void getSupportedTypes(HashSet<String, ASCIICaseInsensitiveHash>& types) const final
{
return MediaPlayerPrivateGStreamer::getSupportedTypes(types);
}
MediaPlayer::SupportsType supportsTypeAndCodecs(const MediaEngineSupportParameters& parameters) const final
{
return MediaPlayerPrivateGStreamer::supportsType(parameters);
}
bool supportsKeySystem(const String& keySystem, const String& mimeType) const final
{
return MediaPlayerPrivateGStreamer::supportsKeySystem(keySystem, mimeType);
}
};
void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
{
initializeDebugCategory();
registrar(makeUnique<MediaPlayerFactoryGStreamer>());
}
void MediaPlayerPrivateGStreamer::load(const String& urlString)
{
URL url { urlString };
if (url.protocolIsAbout()) {
loadingFailed(MediaPlayer::NetworkState::FormatError, MediaPlayer::ReadyState::HaveNothing, true);
return;
}
if (!ensureGStreamerInitialized()) {
loadingFailed(MediaPlayer::NetworkState::FormatError, MediaPlayer::ReadyState::HaveNothing, true);
return;
}
registerWebKitGStreamerElements();
if (!m_pipeline)
createGSTPlayBin(url);
syncOnClock(true);
if (m_fillTimer.isActive())
m_fillTimer.stop();
ASSERT(m_pipeline);
setPlaybinURL(url);
GST_DEBUG_OBJECT(pipeline(), "preload: %s", convertEnumerationToString(m_preload).utf8().data());
if (m_preload == MediaPlayer::Preload::None && !isMediaSource()) {
GST_INFO_OBJECT(pipeline(), "Delaying load.");
m_isDelayingLoad = true;
}
// Reset network and ready states. Those will be set properly once
// the pipeline pre-rolled.
m_networkState = MediaPlayer::NetworkState::Loading;
m_player->networkStateChanged();
m_readyState = MediaPlayer::ReadyState::HaveNothing;
m_player->readyStateChanged();
m_areVolumeAndMuteInitialized = false;
m_hasTaintedOrigin = std::nullopt;
if (!m_isDelayingLoad)
commitLoad();
}
#if ENABLE(MEDIA_SOURCE)
void MediaPlayerPrivateGStreamer::load(const URL&, const ContentType&, MediaSourcePrivateClient&)
{
// Properly fail so the global MediaPlayer tries to fallback to the next MediaPlayerPrivate.
m_networkState = MediaPlayer::NetworkState::FormatError;
m_player->networkStateChanged();
}
#endif
#if ENABLE(MEDIA_STREAM)
void MediaPlayerPrivateGStreamer::load(MediaStreamPrivate& stream)
{
m_streamPrivate = &stream;
load(makeString("mediastream://", stream.id()));
syncOnClock(false);
m_player->play();
}
#endif
void MediaPlayerPrivateGStreamer::cancelLoad()
{
if (m_networkState < MediaPlayer::NetworkState::Loading || m_networkState == MediaPlayer::NetworkState::Loaded)
return;
if (m_pipeline)
changePipelineState(GST_STATE_READY);
}
void MediaPlayerPrivateGStreamer::prepareToPlay()
{
GST_DEBUG_OBJECT(pipeline(), "Prepare to play");
m_preload = MediaPlayer::Preload::Auto;
if (m_isDelayingLoad) {
m_isDelayingLoad = false;
commitLoad();
}
}
void MediaPlayerPrivateGStreamer::play()
{
if (!m_playbackRate) {
m_isPlaybackRatePaused = true;
return;
}
if (changePipelineState(GST_STATE_PLAYING)) {
m_isEndReached = false;
m_isDelayingLoad = false;
m_preload = MediaPlayer::Preload::Auto;
updateDownloadBufferingFlag();
GST_INFO_OBJECT(pipeline(), "Play");
} else
loadingFailed(MediaPlayer::NetworkState::Empty);
}
void MediaPlayerPrivateGStreamer::pause()
{
m_isPlaybackRatePaused = false;
GstState currentState, pendingState;
gst_element_get_state(m_pipeline.get(), ¤tState, &pendingState, 0);
if (currentState < GST_STATE_PAUSED && pendingState <= GST_STATE_PAUSED)
return;
if (changePipelineState(GST_STATE_PAUSED))
GST_INFO_OBJECT(pipeline(), "Pause");
else
loadingFailed(MediaPlayer::NetworkState::Empty);
}
bool MediaPlayerPrivateGStreamer::paused() const
{
if (!m_pipeline)
return true;
if (m_isEndReached) {
GST_DEBUG_OBJECT(pipeline(), "Ignoring pause at EOS");
return true;
}
if (m_isPlaybackRatePaused) {
GST_DEBUG_OBJECT(pipeline(), "Playback rate is 0, simulating PAUSED state");
return false;
}
GstState state;
gst_element_get_state(m_pipeline.get(), &state, nullptr, 0);
bool paused = state <= GST_STATE_PAUSED;
GST_LOG_OBJECT(pipeline(), "Paused: %s", toString(paused).utf8().data());
return paused;
}
bool MediaPlayerPrivateGStreamer::doSeek(const MediaTime& position, float rate, GstSeekFlags seekFlags)
{
// Default values for rate >= 0.
MediaTime startTime = position, endTime = MediaTime::invalidTime();
if (rate < 0) {
startTime = MediaTime::zeroTime();
// If we are at beginning of media, start from the end to avoid immediate EOS.
endTime = position < MediaTime::zeroTime() ? durationMediaTime() : position;
}
if (!rate)
rate = 1.0;
if (m_hasWebKitWebSrcSentEOS && m_downloadBuffer) {
GST_DEBUG_OBJECT(pipeline(), "Setting high-percent=0 on GstDownloadBuffer to force 100%% buffered reporting");
g_object_set(m_downloadBuffer.get(), "high-percent", 0, nullptr);
}
GST_DEBUG_OBJECT(pipeline(), "[Seek] Performing actual seek to %" GST_TIME_FORMAT " (endTime: %" GST_TIME_FORMAT ") at rate %f", GST_TIME_ARGS(toGstClockTime(startTime)), GST_TIME_ARGS(toGstClockTime(endTime)), rate);
return gst_element_seek(m_pipeline.get(), rate, GST_FORMAT_TIME, seekFlags,
GST_SEEK_TYPE_SET, toGstClockTime(startTime), GST_SEEK_TYPE_SET, toGstClockTime(endTime));
}
void MediaPlayerPrivateGStreamer::seek(const MediaTime& mediaTime)
{
if (!m_pipeline || m_didErrorOccur || isMediaStreamPlayer())
return;
GST_INFO_OBJECT(pipeline(), "[Seek] seek attempt to %s", toString(mediaTime).utf8().data());
// Avoid useless seeking.
if (mediaTime == currentMediaTime()) {
GST_DEBUG_OBJECT(pipeline(), "[Seek] Already at requested position. Aborting.");
return;
}
if (m_isLiveStream.value_or(false)) {
GST_DEBUG_OBJECT(pipeline(), "[Seek] Live stream seek unhandled");
return;
}
MediaTime time = std::min(mediaTime, durationMediaTime());
GST_INFO_OBJECT(pipeline(), "[Seek] seeking to %s", toString(time).utf8().data());
if (m_isSeeking) {
m_timeOfOverlappingSeek = time;
if (m_isSeekPending) {
m_seekTime = time;
return;
}
}
GstState state;
GstStateChangeReturn getStateResult = gst_element_get_state(m_pipeline.get(), &state, nullptr, 0);
if (getStateResult == GST_STATE_CHANGE_FAILURE || getStateResult == GST_STATE_CHANGE_NO_PREROLL) {
GST_DEBUG_OBJECT(pipeline(), "[Seek] cannot seek, current state change is %s", gst_element_state_change_return_get_name(getStateResult));
return;
}
if (getStateResult == GST_STATE_CHANGE_ASYNC || state < GST_STATE_PAUSED || m_isEndReached) {
m_isSeekPending = true;
if (m_isEndReached) {
GST_DEBUG_OBJECT(pipeline(), "[Seek] reset pipeline");
m_shouldResetPipeline = true;
if (!changePipelineState(GST_STATE_PAUSED))
loadingFailed(MediaPlayer::NetworkState::Empty);
}
} else {
// We can seek now.
if (!doSeek(time, m_player->rate(), static_cast<GstSeekFlags>(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE))) {
GST_DEBUG_OBJECT(pipeline(), "[Seek] seeking to %s failed", toString(time).utf8().data());
return;
}
}
m_isSeeking = true;
m_seekTime = time;
m_isEndReached = false;
}
void MediaPlayerPrivateGStreamer::updatePlaybackRate()
{
if (isMediaStreamPlayer() || !m_isChangingRate)
return;
GST_INFO_OBJECT(pipeline(), "Set playback rate to %f", m_playbackRate);
// Mute the sound if the playback rate is negative or too extreme and audio pitch is not adjusted.
bool mute = m_playbackRate <= 0 || (!m_shouldPreservePitch && (m_playbackRate < 0.8 || m_playbackRate > 2));
GST_INFO_OBJECT(pipeline(), mute ? "Need to mute audio" : "Do not need to mute audio");
if (m_lastPlaybackRate != m_playbackRate) {
if (doSeek(playbackPosition(), m_playbackRate, static_cast<GstSeekFlags>(GST_SEEK_FLAG_FLUSH))) {
g_object_set(m_pipeline.get(), "mute", mute, nullptr);
m_lastPlaybackRate = m_playbackRate;
} else {
GST_ERROR_OBJECT(pipeline(), "Set rate to %f failed", m_playbackRate);
m_playbackRate = m_lastPlaybackRate;
}
}
if (m_isPlaybackRatePaused) {
GstState state, pending;
gst_element_get_state(m_pipeline.get(), &state, &pending, 0);
if (state != GST_STATE_PLAYING && pending != GST_STATE_PLAYING)
changePipelineState(GST_STATE_PLAYING);
m_isPlaybackRatePaused = false;
}
m_isChangingRate = false;
m_player->rateChanged();
}
MediaTime MediaPlayerPrivateGStreamer::durationMediaTime() const
{
GST_TRACE_OBJECT(pipeline(), "Cached duration: %s", m_cachedDuration.toString().utf8().data());
if (m_cachedDuration.isValid())
return m_cachedDuration;
MediaTime duration = platformDuration();
if (!duration || duration.isInvalid())
return MediaTime::zeroTime();
m_cachedDuration = duration;
return m_cachedDuration;
}
MediaTime MediaPlayerPrivateGStreamer::currentMediaTime() const
{
if (!m_pipeline || m_didErrorOccur)
return MediaTime::invalidTime();
GST_TRACE_OBJECT(pipeline(), "seeking: %s, seekTime: %s", boolForPrinting(m_isSeeking), m_seekTime.toString().utf8().data());
if (m_isSeeking)
return m_seekTime;
return playbackPosition();
}
void MediaPlayerPrivateGStreamer::setRate(float rate)
{
float rateClamped = clampTo(rate, -20.0, 20.0);
if (rateClamped != rate)
GST_WARNING_OBJECT(pipeline(), "Clamping original rate (%f) to [-20, 20] (%f), higher rates cause crashes", rate, rateClamped);
GST_DEBUG_OBJECT(pipeline(), "Setting playback rate to %f", rateClamped);
// Avoid useless playback rate update.
if (m_playbackRate == rateClamped) {
// And make sure that upper layers were notified if rate was set.
if (!m_isChangingRate && m_player->rate() != m_playbackRate)
m_player->rateChanged();
return;
}
if (m_isLiveStream.value_or(false)) {
// Notify upper layers that we cannot handle passed rate.
m_isChangingRate = false;
m_player->rateChanged();
return;
}
GstState state, pending;
m_playbackRate = rateClamped;
m_isChangingRate = true;
gst_element_get_state(m_pipeline.get(), &state, &pending, 0);
if (!rateClamped) {
m_isChangingRate = false;
m_isPlaybackRatePaused = true;
if (state != GST_STATE_PAUSED && pending != GST_STATE_PAUSED)
changePipelineState(GST_STATE_PAUSED);
return;
}
if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
|| (pending == GST_STATE_PAUSED))
return;
updatePlaybackRate();
}
double MediaPlayerPrivateGStreamer::rate() const
{
return m_playbackRate;
}
void MediaPlayerPrivateGStreamer::setPreservesPitch(bool preservesPitch)
{
GST_DEBUG_OBJECT(pipeline(), "Preserving audio pitch: %s", boolForPrinting(preservesPitch));
m_shouldPreservePitch = preservesPitch;
}
void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
{
if (isMediaStreamPlayer())
return;
GST_DEBUG_OBJECT(pipeline(), "Setting preload to %s", convertEnumerationToString(preload).utf8().data());
if (preload == MediaPlayer::Preload::Auto && m_isLiveStream.value_or(false))
return;
m_preload = preload;
updateDownloadBufferingFlag();
if (m_isDelayingLoad && m_preload != MediaPlayer::Preload::None) {
m_isDelayingLoad = false;
commitLoad();
}
}
std::unique_ptr<PlatformTimeRanges> MediaPlayerPrivateGStreamer::buffered() const
{
auto timeRanges = makeUnique<PlatformTimeRanges>();
if (m_didErrorOccur || m_isLiveStream.value_or(false))
return timeRanges;
MediaTime mediaDuration = durationMediaTime();
if (!mediaDuration || mediaDuration.isPositiveInfinite())
return timeRanges;
GRefPtr<GstQuery> query = adoptGRef(gst_query_new_buffering(GST_FORMAT_PERCENT));
if (!gst_element_query(m_pipeline.get(), query.get()))
return timeRanges;
unsigned numBufferingRanges = gst_query_get_n_buffering_ranges(query.get());
for (unsigned index = 0; index < numBufferingRanges; index++) {
gint64 rangeStart = 0, rangeStop = 0;
if (gst_query_parse_nth_buffering_range(query.get(), index, &rangeStart, &rangeStop)) {
uint64_t startTime = gst_util_uint64_scale_int_round(toGstUnsigned64Time(mediaDuration), rangeStart, GST_FORMAT_PERCENT_MAX);
uint64_t stopTime = gst_util_uint64_scale_int_round(toGstUnsigned64Time(mediaDuration), rangeStop, GST_FORMAT_PERCENT_MAX);
timeRanges->add(MediaTime(startTime, GST_SECOND), MediaTime(stopTime, GST_SECOND));
}
}
// Fallback to the more general maxTimeLoaded() if no range has been found.
if (!timeRanges->length()) {
MediaTime loaded = maxTimeLoaded();
if (loaded.isValid() && loaded)
timeRanges->add(MediaTime::zeroTime(), loaded);
}
return timeRanges;
}
MediaTime MediaPlayerPrivateGStreamer::maxMediaTimeSeekable() const
{
GST_TRACE_OBJECT(pipeline(), "errorOccured: %s, isLiveStream: %s", boolForPrinting(m_didErrorOccur), boolForPrinting(m_isLiveStream));
if (m_didErrorOccur)
return MediaTime::zeroTime();
if (m_isLiveStream.value_or(false))
return MediaTime::zeroTime();
if (isMediaStreamPlayer())
return MediaTime::zeroTime();
MediaTime duration = durationMediaTime();
GST_DEBUG_OBJECT(pipeline(), "maxMediaTimeSeekable, duration: %s", toString(duration).utf8().data());
// Infinite duration means live stream.
if (duration.isPositiveInfinite())
return MediaTime::zeroTime();
return duration;
}
MediaTime MediaPlayerPrivateGStreamer::maxTimeLoaded() const
{
if (m_didErrorOccur)
return MediaTime::zeroTime();
MediaTime loaded = m_maxTimeLoaded;
if (m_isEndReached)
loaded = durationMediaTime();
GST_LOG_OBJECT(pipeline(), "maxTimeLoaded: %s", toString(loaded).utf8().data());
return loaded;
}
bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
{
if (m_didErrorOccur || m_loadingStalled)
return false;
if (WEBKIT_IS_WEB_SRC(m_source.get())) {
GST_LOG_OBJECT(pipeline(), "Last network read position: %" G_GUINT64_FORMAT ", current: %" G_GUINT64_FORMAT, m_readPositionAtLastDidLoadingProgress, m_networkReadPosition);
bool didLoadingProgress = m_readPositionAtLastDidLoadingProgress < m_networkReadPosition;
m_readPositionAtLastDidLoadingProgress = m_networkReadPosition;
GST_LOG_OBJECT(pipeline(), "didLoadingProgress: %s", boolForPrinting(didLoadingProgress));
return didLoadingProgress;
}
if (UNLIKELY(!m_pipeline || !durationMediaTime() || (!isMediaSource() && !totalBytes())))
return false;
MediaTime currentMaxTimeLoaded = maxTimeLoaded();
bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
GST_LOG_OBJECT(pipeline(), "didLoadingProgress: %s", boolForPrinting(didLoadingProgress));
return didLoadingProgress;
}
unsigned long long MediaPlayerPrivateGStreamer::totalBytes() const
{
if (m_didErrorOccur || !m_source || m_isLiveStream.value_or(false) || isMediaStreamPlayer())
return 0;
if (m_totalBytes)
return m_totalBytes;
GstFormat fmt = GST_FORMAT_BYTES;
gint64 length = 0;
if (gst_element_query_duration(m_source.get(), fmt, &length)) {
GST_INFO_OBJECT(pipeline(), "totalBytes %" G_GINT64_FORMAT, length);
m_totalBytes = static_cast<unsigned long long>(length);
m_isLiveStream = !length;
return m_totalBytes;
}
// Fall back to querying the source pads manually. See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
bool done = false;
while (!done) {
GValue item = G_VALUE_INIT;
switch (gst_iterator_next(iter, &item)) {
case GST_ITERATOR_OK: {
GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
gint64 padLength = 0;
if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
length = padLength;
break;
}
case GST_ITERATOR_RESYNC:
gst_iterator_resync(iter);
break;
case GST_ITERATOR_ERROR:
FALLTHROUGH;
case GST_ITERATOR_DONE:
done = true;
break;
}
g_value_unset(&item);
}
gst_iterator_free(iter);
GST_INFO_OBJECT(pipeline(), "totalBytes %" G_GINT64_FORMAT, length);
m_totalBytes = static_cast<unsigned long long>(length);
m_isLiveStream = !length;
return m_totalBytes;
}
bool MediaPlayerPrivateGStreamer::hasSingleSecurityOrigin() const
{
if (!m_source)
return false;
if (!WEBKIT_IS_WEB_SRC(m_source.get()))
return true;
GUniqueOutPtr<char> originalURI, resolvedURI;
g_object_get(m_source.get(), "location", &originalURI.outPtr(), "resolved-location", &resolvedURI.outPtr(), nullptr);
if (!originalURI || !resolvedURI)
return false;
if (!g_strcmp0(originalURI.get(), resolvedURI.get()))
return true;
Ref<SecurityOrigin> resolvedOrigin(SecurityOrigin::createFromString(String::fromUTF8(resolvedURI.get())));
Ref<SecurityOrigin> requestedOrigin(SecurityOrigin::createFromString(String::fromUTF8(originalURI.get())));
return resolvedOrigin->isSameSchemeHostPort(requestedOrigin.get());
}
std::optional<bool> MediaPlayerPrivateGStreamer::wouldTaintOrigin(const SecurityOrigin& origin) const
{
GST_TRACE_OBJECT(pipeline(), "Checking %u origins", m_origins.size());
for (auto& responseOrigin : m_origins) {
if (!origin.isSameOriginDomain(*responseOrigin)) {
GST_DEBUG_OBJECT(pipeline(), "Found reachable response origin");
return true;
}
}
GST_DEBUG_OBJECT(pipeline(), "No valid response origin found");
return false;
}
void MediaPlayerPrivateGStreamer::simulateAudioInterruption()
{
GstMessage* message = gst_message_new_request_state(GST_OBJECT(m_pipeline.get()), GST_STATE_PAUSED);
gst_element_post_message(m_pipeline.get(), message);
}
#if ENABLE(WEB_AUDIO)
void MediaPlayerPrivateGStreamer::ensureAudioSourceProvider()
{
if (!m_audioSourceProvider)
m_audioSourceProvider = makeUnique<AudioSourceProviderGStreamer>();
}
AudioSourceProvider* MediaPlayerPrivateGStreamer::audioSourceProvider()
{
ensureAudioSourceProvider();
return m_audioSourceProvider.get();
}
#endif
void MediaPlayerPrivateGStreamer::durationChanged()
{
MediaTime previousDuration = durationMediaTime();
m_cachedDuration = MediaTime::invalidTime();
// Avoid emitting durationChanged in the case where the previous
// duration was 0 because that case is already handled by the
// HTMLMediaElement.
if (previousDuration && durationMediaTime() != previousDuration)
m_player->durationChanged();
}
void MediaPlayerPrivateGStreamer::sourceSetup(GstElement* sourceElement)
{
GST_DEBUG_OBJECT(pipeline(), "Source element set-up for %s", GST_ELEMENT_NAME(sourceElement));
m_source = sourceElement;
if (WEBKIT_IS_WEB_SRC(m_source.get())) {
webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC_CAST(m_source.get()), m_player, m_referrer);
#if ENABLE(MEDIA_STREAM)
} else if (WEBKIT_IS_MEDIA_STREAM_SRC(sourceElement)) {
auto stream = m_streamPrivate.get();
ASSERT(stream);
webkitMediaStreamSrcSetStream(WEBKIT_MEDIA_STREAM_SRC(sourceElement), stream, m_player->isVideoPlayer());
#endif
}
}
void MediaPlayerPrivateGStreamer::sourceSetupCallback(MediaPlayerPrivateGStreamer* player, GstElement* sourceElement)
{
player->sourceSetup(sourceElement);
}
bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
{
ASSERT(m_pipeline);
GstState currentState, pending;
gst_element_get_state(m_pipeline.get(), ¤tState, &pending, 0);
if (currentState == newState || pending == newState) {
GST_DEBUG_OBJECT(pipeline(), "Rejected state change to %s from %s with %s pending", gst_element_state_get_name(newState),
gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
return true;
}
GST_DEBUG_OBJECT(pipeline(), "Changing state change to %s from %s with %s pending", gst_element_state_get_name(newState),
gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
GstStateChangeReturn setStateResult = gst_element_set_state(m_pipeline.get(), newState);
GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE)
return false;
// Create a timer when entering the READY state so that we can free resources if we stay for too long on READY.
// Also lets remove the timer if we request a state change for any state other than READY. See also https://bugs.webkit.org/show_bug.cgi?id=117354
if (newState == GST_STATE_READY && !m_readyTimerHandler.isActive()) {
// Max interval in seconds to stay in the READY state on manual state change requests.
static const Seconds readyStateTimerDelay { 1_min };
m_readyTimerHandler.startOneShot(readyStateTimerDelay);
} else if (newState != GST_STATE_READY)
m_readyTimerHandler.stop();
return true;
}
void MediaPlayerPrivateGStreamer::setPlaybinURL(const URL& url)
{
// Clean out everything after file:// url path.
String cleanURLString(url.string());
if (url.isLocalFile())
cleanURLString = cleanURLString.left(url.pathEnd());
m_url = URL { cleanURLString };
GST_INFO_OBJECT(pipeline(), "Load %s", m_url.string().utf8().data());
g_object_set(m_pipeline.get(), "uri", m_url.string().utf8().data(), nullptr);
}
static void setSyncOnClock(GstElement *element, bool sync)
{
if (!element)
return;
if (!GST_IS_BIN(element)) {
g_object_set(element, "sync", sync, nullptr);
return;
}
GUniquePtr<GstIterator> iterator(gst_bin_iterate_sinks(GST_BIN_CAST(element)));
while (gst_iterator_foreach(iterator.get(), static_cast<GstIteratorForeachFunction>([](const GValue* item, void* syncPtr) {
bool* sync = static_cast<bool*>(syncPtr);
setSyncOnClock(GST_ELEMENT_CAST(g_value_get_object(item)), *sync);
}), &sync) == GST_ITERATOR_RESYNC)
gst_iterator_resync(iterator.get());
}
void MediaPlayerPrivateGStreamer::syncOnClock(bool sync)
{
setSyncOnClock(videoSink(), sync);
setSyncOnClock(audioSink(), sync);
}
template <typename TrackPrivateType>
void MediaPlayerPrivateGStreamer::notifyPlayerOfTrack()
{
if (UNLIKELY(!m_pipeline || !m_source))
return;
ASSERT(m_isLegacyPlaybin);
using TrackType = TrackPrivateBaseGStreamer::TrackType;
std::variant<HashMap<AtomString, Ref<AudioTrackPrivateGStreamer>>*, HashMap<AtomString, Ref<VideoTrackPrivateGStreamer>>*, HashMap<AtomString, Ref<InbandTextTrackPrivateGStreamer>>*> variantTracks = static_cast<HashMap<AtomString, Ref<TrackPrivateType>>*>(0);
auto type(static_cast<TrackType>(variantTracks.index()));
const char* typeName;
bool* hasType;
switch (type) {
case TrackType::Audio:
typeName = "audio";
hasType = &m_hasAudio;
variantTracks = &m_audioTracks;
break;
case TrackType::Video:
typeName = "video";
hasType = &m_hasVideo;
variantTracks = &m_videoTracks;
break;
case TrackType::Text:
typeName = "text";
hasType = nullptr;
variantTracks = &m_textTracks;
break;
default:
ASSERT_NOT_REACHED();
}
auto& tracks = *std::get<HashMap<AtomString, Ref<TrackPrivateType>>*>(variantTracks);
// Ignore notifications after a EOS. We don't want the tracks to disappear when the video is finished.