1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_WEB_MEDIA_PLAYER_IMPL_H_
6 #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_WEB_MEDIA_PLAYER_IMPL_H_
14 #include "base/cancelable_callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/memory/raw_ptr.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_refptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/task/sequenced_task_runner.h"
21 #include "base/threading/thread.h"
22 #include "base/time/default_tick_clock.h"
23 #include "base/time/time.h"
24 #include "base/timer/elapsed_timer.h"
25 #include "base/timer/timer.h"
26 #include "build/build_config.h"
27 #include "media/base/cdm_config.h"
28 #include "media/base/data_source.h"
29 #include "media/base/demuxer.h"
30 #include "media/base/eme_constants.h"
31 #include "media/base/encryption_scheme.h"
32 #include "media/base/media_observer.h"
33 #include "media/base/media_tracks.h"
34 #include "media/base/overlay_info.h"
35 #include "media/base/pipeline_impl.h"
36 #include "media/base/renderer_factory_selector.h"
37 #include "media/base/routing_token_callback.h"
38 #include "media/base/simple_watch_timer.h"
39 #include "media/filters/demuxer_manager.h"
40 #include "media/mojo/mojom/media_metrics_provider.mojom.h"
41 #include "media/mojo/mojom/playback_events_recorder.mojom.h"
42 #include "media/renderers/paint_canvas_video_renderer.h"
43 #include "mojo/public/cpp/bindings/pending_remote.h"
44 #include "mojo/public/cpp/bindings/remote.h"
45 #include "services/media_session/public/cpp/media_position.h"
46 #include "third_party/abseil-cpp/absl/types/optional.h"
47 #include "third_party/blink/public/platform/media/video_frame_compositor.h"
48 #include "third_party/blink/public/platform/media/web_media_player_builder.h"
49 #include "third_party/blink/public/platform/media/webmediaplayer_delegate.h"
50 #include "third_party/blink/public/platform/web_audio_source_provider.h"
51 #include "third_party/blink/public/platform/web_content_decryption_module_result.h"
52 #include "third_party/blink/public/platform/web_media_player.h"
53 #include "third_party/blink/public/platform/web_surface_layer_bridge.h"
54 #include "third_party/blink/public/web/modules/media/webmediaplayer_util.h"
55 #include "third_party/blink/renderer/platform/allow_discouraged_type.h"
56 #include "third_party/blink/renderer/platform/media/learning_experiment_helper.h"
57 #include "third_party/blink/renderer/platform/media/multi_buffer_data_source.h"
58 #include "third_party/blink/renderer/platform/media/smoothness_helper.h"
59 #include "third_party/blink/renderer/platform/platform_export.h"
63 class SingleThreadTaskRunner;
76 class LearningTaskController;
84 class MemoryDumpProviderProxy;
85 class PipelineController;
86 class SwitchableAudioRendererSink;
90 class RasterContextProvider;
94 class BufferedDataSourceHostImpl;
95 class PowerStatusHelper;
96 class ThreadSafeBrowserInterfaceBrokerProxy;
98 class VideoDecodeStatsReporter;
99 class VideoFrameCompositor;
100 class WatchTimeReporter;
101 class WebAudioSourceProviderImpl;
102 class WebContentDecryptionModule;
104 class WebMediaPlayerClient;
105 class WebMediaPlayerEncryptedMediaClient;
107 // The canonical implementation of WebMediaPlayer that's backed by
108 // Pipeline. Handles normal resource loading, Media Source, and
110 class PLATFORM_EXPORT WebMediaPlayerImpl
111 : public WebMediaPlayer,
112 public WebMediaPlayerDelegate::Observer,
113 public media::Pipeline::Client,
114 public media::MediaObserverClient,
115 public media::DemuxerManager::Client,
116 public WebSurfaceLayerBridgeObserver,
117 public SmoothnessHelper::Client {
119 // Constructs a WebMediaPlayer implementation using Chromium's media stack.
120 // |delegate| and |renderer_factory_selector| must not be null.
122 WebLocalFrame* frame,
123 WebMediaPlayerClient* client,
124 WebMediaPlayerEncryptedMediaClient* encrypted_client,
125 WebMediaPlayerDelegate* delegate,
126 std::unique_ptr<media::RendererFactorySelector> renderer_factory_selector,
128 std::unique_ptr<VideoFrameCompositor> compositor,
129 std::unique_ptr<media::MediaLog> media_log,
130 media::MediaPlayerLoggingID player_id,
131 WebMediaPlayerBuilder::DeferLoadCB defer_load_cb,
132 scoped_refptr<media::SwitchableAudioRendererSink> audio_renderer_sink,
133 scoped_refptr<base::SequencedTaskRunner> media_task_runner,
134 scoped_refptr<base::TaskRunner> worker_task_runner,
135 scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner,
136 scoped_refptr<base::SingleThreadTaskRunner>
137 video_frame_compositor_task_runner,
138 WebMediaPlayerBuilder::AdjustAllocatedMemoryCB adjust_allocated_memory_cb,
139 WebContentDecryptionModule* initial_cdm,
140 media::RequestRoutingTokenCallback request_routing_token_cb,
141 base::WeakPtr<media::MediaObserver> media_observer,
142 bool enable_instant_source_buffer_gc,
143 bool embedded_media_experience_enabled,
144 mojo::PendingRemote<media::mojom::MediaMetricsProvider> metrics_provider,
145 CreateSurfaceLayerBridgeCB create_bridge_callback,
146 scoped_refptr<viz::RasterContextProvider> raster_context_provider,
147 #if defined(TIZEN_VIDEO_HOLE)
150 bool use_surface_layer,
151 bool is_background_suspend_enabled,
152 bool is_background_video_play_enabled,
153 bool is_background_video_track_optimization_supported,
154 std::unique_ptr<media::Demuxer> demuxer_override,
155 scoped_refptr<ThreadSafeBrowserInterfaceBrokerProxy> remote_interfaces);
156 WebMediaPlayerImpl(const WebMediaPlayerImpl&) = delete;
157 WebMediaPlayerImpl& operator=(const WebMediaPlayerImpl&) = delete;
158 ~WebMediaPlayerImpl() override;
160 // WebSurfaceLayerBridgeObserver implementation.
161 void OnWebLayerUpdated() override;
162 void RegisterContentsLayer(cc::Layer* layer) override;
163 void UnregisterContentsLayer(cc::Layer* layer) override;
164 void OnSurfaceIdUpdated(viz::SurfaceId surface_id) override;
166 WebMediaPlayer::LoadTiming Load(LoadType load_type,
167 const WebMediaPlayerSource& source,
169 bool is_cache_disabled) override;
171 // Playback controls.
172 void Play() override;
173 void Pause() override;
174 void Seek(double seconds) override;
175 void SetRate(double rate) override;
176 void SetVolume(double volume) override;
177 void SetLatencyHint(double seconds) override;
178 void SetPreservesPitch(bool preserves_pitch) override;
179 void SetWasPlayedWithUserActivation(
180 bool was_played_with_user_activation) override;
181 void OnRequestPictureInPicture() override;
182 void OnTimeUpdate() override;
183 bool SetSinkId(const WebString& sink_id,
184 WebSetSinkIdCompleteCallback completion_callback) override;
185 void SetPoster(const WebURL& poster) override;
186 void SetPreload(WebMediaPlayer::Preload preload) override;
187 WebTimeRanges Buffered() const override;
188 WebTimeRanges Seekable() const override;
189 #if defined(TIZEN_MULTIMEDIA)
190 void Suspend() override;
191 void Resume() override;
194 void OnFrozen() override;
196 // paint() the current video frame into |canvas|. This is used to support
197 // various APIs and functionalities, including but not limited to: <canvas>,
198 // ImageBitmap, printing and capturing capabilities.
199 void Paint(cc::PaintCanvas* canvas,
200 const gfx::Rect& rect,
201 cc::PaintFlags& flags) override;
202 scoped_refptr<media::VideoFrame> GetCurrentFrameThenUpdate() override;
203 absl::optional<media::VideoFrame::ID> CurrentFrameId() const override;
204 media::PaintCanvasVideoRenderer* GetPaintCanvasVideoRenderer() override;
206 // True if the loaded media has a playable video/audio track.
207 bool HasVideo() const override;
208 bool HasAudio() const override;
210 void EnabledAudioTracksChanged(
211 const WebVector<WebMediaPlayer::TrackId>& enabledTrackIds) override;
212 void SelectedVideoTrackChanged(
213 WebMediaPlayer::TrackId* selectedTrackId) override;
215 // Dimensions of the video.
216 gfx::Size NaturalSize() const override;
218 gfx::Size VisibleSize() const override;
220 // Getters of playback state.
221 bool Paused() const override;
222 bool Seeking() const override;
223 double Duration() const override;
224 virtual double timelineOffset() const;
225 bool IsEnded() const override;
227 // Shared between the WebMediaPlayer and DemuxerManager::Client interfaces.
228 double CurrentTime() const override;
230 bool PausedWhenHidden() const override;
232 // Internal states of loading and network.
233 // TODO(hclam): Ask the pipeline about the state rather than having reading
234 // them from members which would cause race conditions.
235 WebMediaPlayer::NetworkState GetNetworkState() const override;
236 WebMediaPlayer::ReadyState GetReadyState() const override;
238 WebString GetErrorMessage() const override;
239 bool DidLoadingProgress() override;
240 bool WouldTaintOrigin() const override;
242 double MediaTimeForTimeValue(double timeValue) const override;
244 unsigned DecodedFrameCount() const override;
245 unsigned DroppedFrameCount() const override;
246 uint64_t AudioDecodedByteCount() const override;
247 uint64_t VideoDecodedByteCount() const override;
249 bool PassedTimingAllowOriginCheck() const override;
251 void SetVolumeMultiplier(double multiplier) override;
252 void SetPersistentState(bool persistent) override;
253 void SetPowerExperimentState(bool state) override;
254 void SuspendForFrameClosed() override;
256 bool HasAvailableVideoFrame() const override;
257 bool HasReadableVideoFrame() const override;
259 scoped_refptr<WebAudioSourceProviderImpl> GetAudioSourceProvider() override;
261 void SetContentDecryptionModule(
262 WebContentDecryptionModule* cdm,
263 WebContentDecryptionModuleResult result) override;
265 void EnteredFullscreen() override;
266 void ExitedFullscreen() override;
267 void BecameDominantVisibleContent(bool is_dominant) override;
268 void SetIsEffectivelyFullscreen(
269 WebFullscreenVideoStatus fullscreen_video_status) override;
270 void OnHasNativeControlsChanged(bool) override;
271 void OnDisplayTypeChanged(DisplayType display_type) override;
273 // WebMediaPlayerDelegate::Observer implementation.
274 void OnFrameHidden() override;
275 void OnFrameShown() override;
276 void OnIdleTimeout() override;
278 void RequestRemotePlaybackDisabled(bool disabled) override;
279 void RequestMediaRemoting() override;
281 #if BUILDFLAG(IS_ANDROID)
282 // TODO(https://crbug.com/839651): Rename Flinging[Started/Stopped] to
283 // RemotePlayback[Started/Stopped] once the other RemotePlayback methods have
285 void FlingingStarted() override;
286 void FlingingStopped() override;
288 // Called when the play/pause state of media playing on a remote cast device
289 // changes, and WMPI wasn't the originator of that change (e.g. a phone on the
290 // same network paused the cast device via the casting notification).
291 // This is only used by the FlingingRenderer/FlingingRendererClient, when we
292 // are flinging media (a.k.a. RemotePlayback).
293 // The consistency between the WMPI state and the cast device state is not
294 // guaranteed, and it a best effort, which can always be fixed by the user by
295 // tapping play/pause once. Attempts to enfore stronger consistency guarantees
296 // have lead to unstable states, and a worse user experience.
297 void OnRemotePlayStateChange(media::MediaStatus::State state);
300 // media::MediaObserverClient implementation.
301 void SwitchToRemoteRenderer(
302 const std::string& remote_device_friendly_name) override;
303 void SwitchToLocalRenderer(
304 media::MediaObserverClient::ReasonToSwitchToLocal reason) override;
305 void UpdateRemotePlaybackCompatibility(bool is_compatible) override;
307 // Test helper methods for exercising media suspension. Once called, when
308 // |target_state| is reached or exceeded the stale flag will be set when
309 // computing the play state, which will trigger suspend if the player is
310 // paused; see UpdatePlayState_ComputePlayState() for the exact details.
311 void ForceStaleStateForTesting(ReadyState target_state) override;
312 bool IsSuspendedForTesting() override;
313 bool DidLazyLoad() const override;
314 void OnBecameVisible() override;
315 bool IsOpaque() const override;
316 int GetDelegateId() override;
317 absl::optional<viz::SurfaceId> GetSurfaceId() override;
318 GURL GetSrcAfterRedirects() override;
319 void RequestVideoFrameCallback() override;
320 std::unique_ptr<WebMediaPlayer::VideoFramePresentationMetadata>
321 GetVideoFramePresentationMetadata() override;
322 void UpdateFrameIfStale() override;
324 base::WeakPtr<WebMediaPlayer> AsWeakPtr() override;
325 void RegisterFrameSinkHierarchy() override;
326 void UnregisterFrameSinkHierarchy() override;
328 bool IsBackgroundMediaSuspendEnabled() const {
329 return is_background_suspend_enabled_;
332 // Distinct states that |delegate_| can be in. (Public for testing.)
333 enum class DelegateState {
339 // Playback state variables computed together in UpdatePlayState().
340 // (Public for testing.)
342 DelegateState delegate_state;
344 bool is_memory_reporting_enabled;
348 // Allow background video tracks with ~5 second keyframes (rounding down) to
349 // be disabled to save resources.
350 enum { kMaxKeyframeDistanceToDisableBackgroundVideoMs = 5500 };
353 friend class WebMediaPlayerImplTest;
354 friend class WebMediaPlayerImplBackgroundBehaviorTest;
356 // Helper function that can be used for generating different UMA records:
357 // |key| is the UMA prefix, such as "Media.TimeToPlayReady", for example.
358 // |UmaFunction| is some UMA function, like base::UmaHistogramMediumTimes
359 // which the record actually gets logged with
360 // |T...| are the arguments passed. Usually this is only one piece of data,
361 // such as a base::TimeDelta, in the case of UmaHistogramMediumTimes,
362 // but could also be a series of fields that customize bucket sizes
365 // Finally, the |Flags| template argument is used to determine which suffixes
366 // are logged - An integer enum is provided |SplitHistogramTypes| which is
367 // a bitmask, and can be used to require logging:
368 // PlaybackType: {".SRC", ".MSE", ".HLS" (in the future)} based on demuxer
370 // Encrypted: {".EME"} based on the value of |is_encrypted_|
371 // All: {".All"} all the time.
372 // |Flags| is provided as a template argument instead of a function argument
373 // in order to guard different components in "if constexpr" conditionals,
374 // so we won't even compile in strings such as "Media.TimeToPlayReady.All"
375 // if it's not specified.
376 template <uint32_t Flags, typename... T>
377 void WriteSplitHistogram(void (*UmaFunction)(const std::string&, T...),
378 const std::string& key,
381 void EnableOverlay();
382 void DisableOverlay();
384 // Do we have overlay information? For CVV, this is a surface id. For
385 // AndroidOverlay, this is the routing token.
386 bool HaveOverlayInfo();
388 // Send OverlayInfo to the decoder.
390 // If we've requested but not yet received the surface id or routing token, or
391 // if there's no decoder-provided callback to send the overlay info, then this
392 // call will do nothing.
393 void MaybeSendOverlayInfoToDecoder();
395 void OnPipelineSuspended();
396 void OnBeforePipelineResume();
397 void OnPipelineResumed();
398 void OnPipelineSeeked(bool time_updated);
400 // media::Pipeline::Client overrides.
401 void OnError(media::PipelineStatus status) override;
402 void OnFallback(media::PipelineStatus status) override;
403 void OnEnded() override;
404 void OnMetadata(const media::PipelineMetadata& metadata) override;
405 void OnBufferingStateChange(
406 media::BufferingState state,
407 media::BufferingStateChangeReason reason) override;
408 void OnDurationChange() override;
409 void OnWaiting(media::WaitingReason reason) override;
410 void OnAudioConfigChange(const media::AudioDecoderConfig& config) override;
411 void OnVideoConfigChange(const media::VideoDecoderConfig& config) override;
412 void OnVideoNaturalSizeChange(const gfx::Size& size) override;
413 void OnVideoOpacityChange(bool opaque) override;
414 void OnVideoFrameRateChange(absl::optional<int> fps) override;
415 void OnVideoAverageKeyframeDistanceUpdate() override;
416 void OnAudioPipelineInfoChange(const media::AudioPipelineInfo& info) override;
417 void OnVideoPipelineInfoChange(const media::VideoPipelineInfo& info) override;
418 #if defined(TIZEN_MULTIMEDIA)
419 // Called if a player in the browser process is suspended.
420 void OnRequestSuspend() override;
423 // media::DemuxerManager::Client overrides.
424 void OnChunkDemuxerOpened(media::ChunkDemuxer* demuxer) override;
425 void OnProgress() override;
426 void OnEncryptedMediaInitData(media::EmeInitDataType init_data_type,
427 const std::vector<uint8_t>& init_data) override;
428 void MakeDemuxerThreadDumper(media::Demuxer* demuxer) override;
429 bool CouldPlayIfEnoughData() override;
430 bool IsMediaPlayerRendererClient() override;
431 void StopForDemuxerReset() override;
432 void RestartForHls() override;
433 bool IsSecurityOriginCryptographic() const override;
434 void UpdateLoadedUrl(const GURL& url) override;
435 void DemuxerRequestsSeek(base::TimeDelta seek_time) override;
437 #if BUILDFLAG(ENABLE_FFMPEG)
438 void AddAudioTrack(const std::string& id,
439 const std::string& label,
440 const std::string& language,
441 bool is_first_track) override;
442 void AddVideoTrack(const std::string& id,
443 const std::string& label,
444 const std::string& language,
445 bool is_first_track) override;
446 #endif // BUILDFLAG(ENABLE_FFMPEG)
448 #if BUILDFLAG(ENABLE_HLS_DEMUXER)
449 void GetUrlData(const GURL& gurl,
450 base::OnceCallback<void(scoped_refptr<UrlData>)> cb);
451 base::SequenceBound<media::HlsDataSourceProvider> GetHlsDataSourceProvider()
453 #endif // BUILDFLAG(ENABLE_HLS_DEMUXER)
455 // Simplified watch time reporting.
456 void OnSimpleWatchTimerTick();
458 // Actually seek. Avoids causing |should_notify_time_changed_| to be set when
459 // |time_updated| is false.
460 void DoSeek(base::TimeDelta time, bool time_updated);
462 // Called after |defer_load_cb_| has decided to allow the load. If
463 // |defer_load_cb_| is null this is called immediately.
464 void DoLoad(LoadType load_type,
467 bool is_cache_disabled);
469 // Called after synchronous initialization of a data source completes.
470 void DataSourceInitialized(bool success);
472 // Called after asynchronous initialization of a multibuffer data source
474 void MultiBufferDataSourceInitialized(bool success);
476 // Called after synchronous or asynchronous MemoryDataSource initialization.
477 void MemoryDataSourceInitialized(bool success, size_t data_size);
479 // Called if the |MultiBufferDataSource| is redirected.
480 void OnDataSourceRedirected();
482 // Called when the data source is downloading or paused.
483 void NotifyDownloading(bool is_downloading);
485 // Called by RenderFrameImpl with the overlay routing token, if we request it.
486 void OnOverlayRoutingToken(const base::UnguessableToken& token);
488 // Called by GpuVideoDecoder on Android to request a surface to render to (if
490 void OnOverlayInfoRequested(
491 bool decoder_requires_restart_for_overlay,
492 media::ProvideOverlayInfoCB provide_overlay_info_cb);
494 // Creates a Renderer via the |renderer_factory_selector_|. If the
495 // |renderer_type| is absl::nullopt, create the base Renderer. Otherwise, set
496 // the base type to be |renderer_type| and create a Renderer of that type.
497 std::unique_ptr<media::Renderer> CreateRenderer(
498 absl::optional<media::RendererType> renderer_type);
500 // Finishes starting the pipeline due to a call to load().
501 void StartPipeline();
503 // Restart the player/pipeline as soon as possible. This will destroy the
504 // current renderer, if any, and create a new one via the RendererFactory; and
505 // then seek to resume playback at the current position.
506 void ScheduleRestart();
508 // Helpers that set the network/ready state and notifies the client if
510 void SetNetworkState(WebMediaPlayer::NetworkState state);
511 void SetReadyState(WebMediaPlayer::ReadyState state);
513 // Returns the current video frame from |compositor_|, and asks the compositor
514 // to update its frame if it is stale.
515 // Can return a nullptr.
516 scoped_refptr<media::VideoFrame> GetCurrentFrameFromCompositor() const;
518 // Sets CdmContext from |cdm| on the pipeline and calls OnCdmAttached()
520 void SetCdmInternal(WebContentDecryptionModule* cdm);
522 // Called when a CDM has been attached to the |pipeline_|.
523 void OnCdmAttached(bool success);
525 // Inspects the current playback state and:
526 // - notifies |delegate_|,
527 // - toggles the memory usage reporting timer, and
528 // - toggles suspend/resume as necessary.
530 // This method should be called any time its dependent values change. These
534 // - delegate_->IsHidden(),
535 // - network_state_, ready_state_,
536 // - is_idle_, must_suspend_,
537 // - paused_, ended_,
538 // - pending_suspend_resume_cycle_,
539 // - enter_pip_callback_,
540 void UpdatePlayState();
542 // Methods internal to UpdatePlayState().
543 PlayState UpdatePlayState_ComputePlayState(bool is_flinging,
544 bool can_auto_suspend,
546 bool is_backgrounded,
547 bool is_in_picture_in_picture);
548 void SetDelegateState(DelegateState new_state, bool is_idle);
549 void SetMemoryReportingState(bool is_memory_reporting_enabled);
550 void SetSuspendState(bool is_suspended);
552 // Called at low frequency to tell external observers how much memory we're
553 // using for video playback. Called by |memory_usage_reporting_timer_|.
554 // Memory usage reporting is done in two steps, because |demuxer_| must be
555 // accessed on the media thread.
556 void ReportMemoryUsage();
557 void FinishMemoryUsageReport(int64_t demuxer_memory_usage);
559 void OnMainThreadMemoryDump(int32_t id,
560 const base::trace_event::MemoryDumpArgs& args,
561 base::trace_event::ProcessMemoryDump* pmd);
562 static void OnMediaThreadMemoryDump(
564 media::Demuxer* demuxer,
565 const base::trace_event::MemoryDumpArgs& args,
566 base::trace_event::ProcessMemoryDump* pmd);
568 // Called during OnHidden() when we want a suspended player to enter the
569 // paused state after some idle timeout.
570 void ScheduleIdlePauseTimer();
572 // Returns |true| before HaveFutureData whenever there has been loading
573 // progress and we have not been resumed for at least kLoadingToIdleTimeout
576 // This is used to delay suspension long enough for preroll to complete, which
577 // is necessay because play() will not be called before HaveFutureData (and
578 // thus we think we are idle forever).
579 bool IsPrerollAttemptNeeded();
581 void CreateWatchTimeReporter();
582 void UpdateSecondaryProperties();
584 void CreateVideoDecodeStatsReporter();
586 // Returns true if the player is hidden.
587 bool IsHidden() const;
589 // Returns true if the player is in streaming mode, meaning that the source
590 // or the demuxer doesn't support timeline or seeking.
591 bool IsStreaming() const;
593 // Return whether |pipeline_metadata_| is compatible with an overlay. This
594 // is intended for android.
595 bool DoesOverlaySupportMetadata() const;
597 // Whether the playback should be paused when hidden. Uses metadata so has
598 // meaning only after the pipeline has started, otherwise returns false.
599 // Doesn't check if the playback can actually be paused depending on the
601 bool ShouldPausePlaybackWhenHidden() const;
603 // Whether the video track should be disabled when hidden. Uses metadata so
604 // has meaning only after the pipeline has started, otherwise returns false.
605 // Doesn't check if the video track can actually be disabled depending on the
607 bool ShouldDisableVideoWhenHidden() const;
609 // If enabling or disabling background video optimization has been delayed,
610 // because of the pipeline not running, seeking or resuming, this method
611 // needs to be called to update the optimization state.
612 void UpdateBackgroundVideoOptimizationState();
614 // Pauses a hidden video only player to save power if possible.
615 // Must be called when either of the following happens:
616 // - right after the video was hidden,
617 // - right ater the pipeline has resumed if the video is hidden.
618 void PauseVideoIfNeeded();
620 // Disables the video track to save power if possible.
621 // Must be called when either of the following happens:
622 // - right after the video was hidden,
623 // - right after the pipeline has started (|seeking_| is used to detect the
624 // when pipeline started) if the video is hidden,
625 // - right ater the pipeline has resumed if the video is hidden.
626 void DisableVideoTrackIfNeeded();
628 // Enables the video track if it was disabled before to save power.
629 // Must be called when either of the following happens:
630 // - right after the video was shown,
631 // - right before the pipeline is requested to resume
632 // (see https://crbug.com/678374),
633 // - right after the pipeline has resumed if the video is not hidden.
634 void EnableVideoTrackIfNeeded();
636 // Overrides the pipeline statistics returned by GetPiplineStatistics() for
638 void SetPipelineStatisticsForTest(const media::PipelineStatistics& stats);
640 // Returns the pipeline statistics or the value overridden by tests.
641 media::PipelineStatistics GetPipelineStatistics() const;
643 // Overrides the pipeline media duration returned by
644 // GetPipelineMediaDuration() for tests.
645 void SetPipelineMediaDurationForTest(base::TimeDelta duration);
647 // Returns the pipeline media duration or the value overridden by tests.
648 base::TimeDelta GetPipelineMediaDuration() const;
650 media::MediaContentType GetMediaContentType() const;
652 // Records |duration| to the appropriate metric based on whether we're
653 // handling a src= or MSE based playback.
654 void RecordUnderflowDuration(base::TimeDelta duration);
656 // Returns true when we estimate that we can play the rest of the media
657 // without buffering.
658 bool CanPlayThrough();
660 // Internal implementation of Pipeline::Client::OnBufferingStateChange(). When
661 // |for_suspended_start| is true, the given state will be set even if the
662 // pipeline is not currently stable.
663 void OnBufferingStateChangeInternal(media::BufferingState state,
664 media::BufferingStateChangeReason reason,
665 bool for_suspended_start = false);
667 // Records |natural_size| to MediaLog and video height to UMA.
668 void RecordVideoNaturalSize(const gfx::Size& natural_size);
670 void SetTickClockForTest(const base::TickClock* tick_clock);
672 // Returns the current time without clamping to Duration() as required by
673 // HTMLMediaElement for handling ended. This method will never return a
674 // negative or kInfiniteDuration value. See http://crbug.com/409280,
675 // http://crbug.com/645998, and http://crbug.com/751823 for reasons why.
676 base::TimeDelta GetCurrentTimeInternal() const;
678 // Called by the compositor the very first time a frame is received.
679 void OnFirstFrame(base::TimeTicks frame_time, bool is_frame_readable);
681 // Records the encryption scheme used by the stream |stream_name|. This is
682 // only recorded when metadata is available.
683 void RecordEncryptionScheme(const std::string& stream_name,
684 media::EncryptionScheme encryption_scheme);
686 // Returns whether the player is currently displayed in Picture-in-Picture.
687 // It will return true even if the player is in AutoPIP mode.
688 // The player MUST have a `client_` when this call happen.
689 bool IsInPictureInPicture() const;
691 // Sets the UKM container name if needed.
692 void MaybeSetContainerNameForMetrics();
694 // Switch to SurfaceLayer, either initially or from VideoLayer.
695 void ActivateSurfaceLayerForVideo();
697 // Called by |compositor_| upon presenting a frame, after
698 // RequestAnimationFrame() is called.
699 void OnNewFramePresentedCallback();
701 // Notifies |demuxer_manager_| of playback and rate changes which may increase
702 // the amount of data the DataSource buffers. Does nothing prior to reaching
703 // kReadyStateHaveEnoughData for the first time.
704 void MaybeUpdateBufferSizesForPlayback();
706 // Create / recreate |smoothness_helper_|, with current features. Will take
707 // no action if we already have a smoothness helper with the same features
708 // that we want now. Will destroy the helper if we shouldn't be measuring
709 // smoothness right now.
710 void UpdateSmoothnessHelper();
712 // Get the LearningTaskController for |task_name|.
713 std::unique_ptr<media::learning::LearningTaskController>
714 GetLearningTaskController(const char* task_name);
716 // Returns whether the player has an audio track and whether it should be
717 // allowed to play it.
718 bool HasUnmutedAudio() const;
720 // Returns true if the video frame from this player are being captured.
721 bool IsVideoBeingCaptured() const;
723 #if defined(TIZEN_VIDEO_HOLE)
724 bool ShouldUseVideoHole() const;
725 void CreateVideoHoleFrame();
726 void OnDrawableContentRectChanged(gfx::Rect rect, bool is_video);
727 bool UpdateBoundaryRectangle();
728 void StartLayerBoundUpdateTimer();
729 void StopLayerBoundUpdateTimer();
730 void OnLayerBoundUpdateTimerFired();
733 // Report UMAs when this object instance is destroyed.
734 void ReportSessionUMAs() const;
736 absl::optional<media::DemuxerType> GetDemuxerType() const;
738 // Useful to bind for a cb to be called when a demuxer is created.
739 media::PipelineStatus OnDemuxerCreated(media::Demuxer* demuxer,
740 media::Pipeline::StartType start_type,
744 // Notifies the `client_` and the `delegate_` about metadata change.
745 void DidMediaMetadataChange();
747 const raw_ptr<WebLocalFrame, ExperimentalRenderer> frame_;
749 WebMediaPlayer::NetworkState network_state_ =
750 WebMediaPlayer::kNetworkStateEmpty;
751 WebMediaPlayer::ReadyState ready_state_ =
752 WebMediaPlayer::kReadyStateHaveNothing;
753 WebMediaPlayer::ReadyState highest_ready_state_ =
754 WebMediaPlayer::kReadyStateHaveNothing;
756 // Preload state for when a DataSource is created after setPreload().
757 media::DataSource::Preload preload_ = media::DataSource::METADATA;
759 // Poster state (for UMA reporting).
760 bool has_poster_ = false;
762 // Task runner for posting tasks on Chrome's main thread. Also used
763 // for DCHECKs so methods calls won't execute in the wrong thread.
764 const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
765 const scoped_refptr<base::SequencedTaskRunner> media_task_runner_;
766 const scoped_refptr<base::TaskRunner> worker_task_runner_;
768 // This is the ID that is used within the internals of the media element
769 // primarily for correlating logs.
770 const media::MediaPlayerLoggingID media_player_id_;
772 std::unique_ptr<media::MediaLog> media_log_;
774 // |pipeline_controller_| owns an instance of Pipeline.
775 std::unique_ptr<media::PipelineController> pipeline_controller_;
777 // The LoadType passed in the |load_type| parameter of the load() call.
778 LoadType load_type_ = kLoadTypeURL;
780 // Cache of metadata for answering hasAudio(), hasVideo(), and naturalSize().
781 media::PipelineMetadata pipeline_metadata_;
783 // Whether the video is known to be opaque or not.
784 bool opaque_ = false;
788 // TODO(scherkus): we have these because Pipeline favours the simplicity of a
789 // single "playback rate" over worrying about paused/stopped etc... It forces
790 // all clients to manage the pause+playback rate externally, but is that
791 // really a bad thing?
793 // TODO(scherkus): since SetPlaybackRate(0) is asynchronous and we don't want
794 // to hang the render thread during pause(), we record the time at the same
795 // time we pause and then return that value in currentTime(). Otherwise our
796 // clock can creep forward a little bit while the asynchronous
797 // SetPlaybackRate(0) is being executed.
798 double playback_rate_ = 0.0;
800 // Counter that limits spam to |media_log_| of |playback_rate_| changes.
801 int num_playback_rate_logs_ = 0;
803 // Set while paused. |paused_time_| is only valid when |paused_| is true.
805 base::TimeDelta paused_time_;
807 // Set if paused automatically when hidden and need to resume when visible.
808 // Reset if paused for any other reason.
809 bool paused_when_hidden_ = false;
811 // Set when starting, seeking, and resuming (all of which require a Pipeline
812 // seek). |seek_time_| is only valid when |seeking_| is true.
813 bool seeking_ = false;
814 base::TimeDelta seek_time_;
816 // Set when doing a restart (a suspend and resume in sequence) of the pipeline
817 // in order to destruct and reinitialize the decoders. This is separate from
818 // |pending_resume_| and |pending_suspend_| because they can be elided in
819 // certain cases, whereas for a restart they must happen.
820 // TODO(sandersd,watk): Create a simpler interface for a pipeline restart.
821 bool pending_suspend_resume_cycle_ = false;
823 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
824 // see http://crbug.com/409280
827 // Tracks whether to issue time changed notifications during buffering state
829 bool should_notify_time_changed_ = false;
831 bool overlay_enabled_ = false;
833 // Cors and Caching flags set during `Load` and used while creating demuxers.
834 CorsMode cors_mode_ = kCorsModeUnspecified;
835 bool is_cache_disabled_ = false;
837 // Whether the current decoder requires a restart on overlay transitions.
838 bool decoder_requires_restart_for_overlay_ = false;
840 const raw_ptr<WebMediaPlayerClient, ExperimentalRenderer> client_;
841 const raw_ptr<WebMediaPlayerEncryptedMediaClient, ExperimentalRenderer>
844 // WebMediaPlayer notifies the |delegate_| of playback state changes using
845 // |delegate_id_|; an id provided after registering with the delegate. The
846 // WebMediaPlayer may also receive directives (play, pause) from the delegate
847 // via the WebMediaPlayerDelegate::Observer interface after registration.
849 // NOTE: HTMLMediaElement is a ExecutionContextLifecycleObserver, and
850 // will receive a call to contextDestroyed() when Document::shutdown()
851 // is called. Document::shutdown() is called before the frame detaches (and
852 // before the frame is destroyed). RenderFrameImpl owns |delegate_| and is
853 // guaranteed to outlive |this|; thus it is safe to store |delegate_| as a raw
855 raw_ptr<WebMediaPlayerDelegate, ExperimentalRenderer> delegate_;
856 int delegate_id_ = 0;
858 // The playback state last reported to |delegate_|, to avoid setting duplicate
860 // TODO(sandersd): The delegate should be implementing deduplication.
861 DelegateState delegate_state_ = DelegateState::GONE;
862 bool delegate_has_audio_ = false;
864 WebMediaPlayerBuilder::DeferLoadCB defer_load_cb_;
866 // Members for notifying upstream clients about internal memory usage. The
867 // |adjust_allocated_memory_cb_| must only be called on |main_task_runner_|.
868 base::RepeatingTimer memory_usage_reporting_timer_;
869 WebMediaPlayerBuilder::AdjustAllocatedMemoryCB adjust_allocated_memory_cb_;
870 int64_t last_reported_memory_usage_ = 0;
871 std::unique_ptr<media::MemoryDumpProviderProxy> main_thread_mem_dumper_;
872 std::unique_ptr<media::MemoryDumpProviderProxy> media_thread_mem_dumper_;
874 // Routes audio playback to either AudioRendererSink or WebAudio.
875 scoped_refptr<WebAudioSourceProviderImpl> audio_source_provider_;
877 // Manages the lifetime of the DataSource, and soon the Demuxer.
878 std::unique_ptr<media::DemuxerManager> demuxer_manager_;
880 raw_ptr<const base::TickClock, ExperimentalRenderer> tick_clock_ = nullptr;
882 std::unique_ptr<BufferedDataSourceHostImpl> buffered_data_source_host_;
883 const raw_ptr<UrlIndex, ExperimentalRenderer> url_index_;
884 scoped_refptr<viz::RasterContextProvider> raster_context_provider_;
886 // Video rendering members.
887 // The |compositor_| runs on the compositor thread, or if
888 // kEnableSurfaceLayerForVideo is enabled, the media thread. This task runner
889 // posts tasks for the |compositor_| on the correct thread.
890 scoped_refptr<base::SingleThreadTaskRunner> vfc_task_runner_;
891 std::unique_ptr<VideoFrameCompositor>
892 compositor_; // Deleted on |vfc_task_runner_|.
893 media::PaintCanvasVideoRenderer video_renderer_;
895 // The compositor layer for displaying the video content when using composited
897 scoped_refptr<cc::VideoLayer> video_layer_;
899 std::unique_ptr<WebContentDecryptionModuleResult> set_cdm_result_;
901 // If a CdmContext is attached keep a reference to the CdmContextRef, so that
902 // it is not destroyed until after the pipeline is done with it.
903 std::unique_ptr<media::CdmContextRef> cdm_context_ref_;
905 // Keep track of the CdmContextRef while it is in the process of attaching to
907 std::unique_ptr<media::CdmContextRef> pending_cdm_context_ref_;
909 // True when encryption is detected, either by demuxer or by presence of a
910 // ContentDecyprtionModule (CDM).
911 bool is_encrypted_ = false;
913 // Captured once the cdm is provided to SetCdmInternal(). Used in creation of
914 // |video_decode_stats_reporter_|.
915 absl::optional<media::CdmConfig> cdm_config_;
917 // Tracks if we are currently flinging a video (e.g. in a RemotePlayback
918 // session). Used to prevent videos from being paused when hidden.
919 // TODO(https://crbug.com/839651): remove or rename this flag, when removing
921 bool is_flinging_ = false;
923 // Tracks if we are currently using a remote renderer. See
924 // SwitchToRemoteRenderer().
925 bool is_remote_rendering_ = false;
927 // The last volume received by setVolume() and the last volume multiplier from
928 // SetVolumeMultiplier(). The multiplier is typical 1.0, but may be less
929 // if the WebMediaPlayerDelegate has requested a volume reduction (ducking)
930 // for a transient sound. Playout volume is derived by volume * multiplier.
931 double volume_ = 1.0;
932 double volume_multiplier_ = 1.0;
934 std::unique_ptr<media::RendererFactorySelector> renderer_factory_selector_;
936 // For canceling AndroidOverlay routing token requests.
937 base::CancelableOnceCallback<void(const base::UnguessableToken&)>
940 // If overlay info is requested before we have it, then the request is saved
941 // and satisfied once the overlay info is available. If the decoder does not
942 // require restart to change surfaces, this is callback is kept until cleared
944 media::ProvideOverlayInfoCB provide_overlay_info_cb_;
946 // On Android an overlay surface means using
947 // SurfaceView instead of SurfaceTexture.
949 // Allow overlays for all video on android.
950 bool always_enable_overlays_ = false;
952 // Suppresses calls to OnPipelineError() after destruction / shutdown has been
953 // started; prevents us from spuriously logging errors that are transient or
955 bool suppress_destruction_errors_ = false;
957 // NOTE: |using_media_player_renderer_| is set based on the usage of a
958 // MediaResource::Type::URL in StartPipeline(). This works because
959 // MediaPlayerRendererClientFactory is the only factory that uses
960 // MediaResource::Type::URL for now.
961 bool using_media_player_renderer_ = false;
963 #if BUILDFLAG(IS_ANDROID)
964 // Set during the initial DoLoad() call. Used to determine whether to allow
965 // credentials or not for MediaPlayerRenderer.
966 bool allow_media_player_renderer_credentials_ = false;
969 // Stores the current position state of the media.
970 media_session::MediaPosition media_position_state_;
972 // Called sometime after the media is suspended in a playing state in
973 // OnFrameHidden(), causing the state to change to paused.
974 base::OneShotTimer background_pause_timer_;
976 // Monitors the watch time of the played content.
977 std::unique_ptr<WatchTimeReporter> watch_time_reporter_;
978 media::AudioDecoderType audio_decoder_type_ =
979 media::AudioDecoderType::kUnknown;
980 media::VideoDecoderType video_decoder_type_ =
981 media::VideoDecoderType::kUnknown;
983 // The time at which DoLoad() is executed.
984 base::TimeTicks load_start_time_;
986 // Time elapsed time from |load_start_time_| to OnMetadata(). Used to later
987 // adjust |load_start_time_| if a suspended startup occurred.
988 base::TimeDelta time_to_metadata_;
989 bool skip_metrics_due_to_startup_suspend_ = false;
991 bool have_reported_time_to_play_ready_ = false;
993 // Records pipeline statistics for describing media capabilities.
994 std::unique_ptr<VideoDecodeStatsReporter> video_decode_stats_reporter_;
996 // Elapsed time since we've last reached BUFFERING_HAVE_NOTHING.
997 std::unique_ptr<base::ElapsedTimer> underflow_timer_;
999 // Used to track loading progress, used by IsPrerollAttemptNeeded().
1000 // |preroll_attempt_pending_| indicates that the clock has been reset
1001 // (awaiting a resume to start), while |preroll_attempt_start_time_| tracks
1002 // when a preroll attempt began.
1003 bool preroll_attempt_pending_ = false;
1004 base::TimeTicks preroll_attempt_start_time_;
1006 // Monitors the player events.
1007 base::WeakPtr<media::MediaObserver> observer_;
1009 // Owns the weblayer and obtains/maintains SurfaceIds.
1010 std::unique_ptr<WebSurfaceLayerBridge> bridge_;
1012 // The maximum video keyframe distance that allows triggering background
1013 // playback optimizations (non-MSE).
1014 base::TimeDelta max_keyframe_distance_to_disable_background_video_;
1016 // The maximum video keyframe distance that allows triggering background
1017 // playback optimizations (MSE).
1018 base::TimeDelta max_keyframe_distance_to_disable_background_video_mse_;
1020 // Whether disabled the video track as an optimization.
1021 bool video_track_disabled_ = false;
1023 // Whether the pipeline is being resumed at the moment.
1024 bool is_pipeline_resuming_ = false;
1026 // When this is true, pipeline will not be auto suspended.
1027 bool disable_pipeline_auto_suspend_ = false;
1029 // Pipeline statistics overridden by tests.
1030 absl::optional<media::PipelineStatistics> pipeline_statistics_for_test_;
1032 // Pipeline media duration overridden by tests.
1033 absl::optional<base::TimeDelta> pipeline_media_duration_for_test_;
1035 // Whether the video requires a user gesture to resume after it was paused in
1036 // the background. Affects the value of ShouldPausePlaybackWhenHidden().
1037 bool video_locked_when_paused_when_hidden_ = false;
1039 // Whether embedded media experience is currently enabled.
1040 bool embedded_media_experience_enabled_ = false;
1042 // When should we use SurfaceLayer for video?
1043 bool use_surface_layer_ = false;
1045 // Whether surface layer is currently in use to display frames.
1046 bool surface_layer_for_video_enabled_ = false;
1048 CreateSurfaceLayerBridgeCB create_bridge_callback_;
1050 bool initial_video_height_recorded_ = false;
1052 enum class OverlayMode {
1053 // All overlays are turned off.
1056 // Use AndroidOverlay for overlays.
1060 OverlayMode overlay_mode_ = OverlayMode::kNoOverlays;
1062 // Optional callback to request the routing token for AndroidOverlay.
1063 media::RequestRoutingTokenCallback request_routing_token_cb_;
1065 // If |overlay_routing_token_is_pending_| is false, then
1066 // |overlay_routing_token_| contains the routing token we should send, if any.
1067 // Otherwise, |overlay_routing_token_| is undefined. We set the flag while
1068 // we have a request for the token that hasn't been answered yet; i.e., it
1069 // means that we don't know what, if any, token we should be using.
1070 bool overlay_routing_token_is_pending_ = false;
1071 media::OverlayInfo::RoutingToken overlay_routing_token_;
1073 media::OverlayInfo overlay_info_;
1075 base::CancelableOnceClosure update_background_status_cb_;
1077 // We cannot use `update_background_status_cb_.IsCancelled()` as that changes
1078 // when the callback is run, even if not explicitly cancelled. This is
1079 // initialized to true to keep in line with the existing behavior of
1080 // base::CancellableOnceClosure.
1081 bool is_background_status_change_cancelled_ = true;
1083 mojo::Remote<media::mojom::MediaMetricsProvider> media_metrics_provider_;
1084 mojo::Remote<media::mojom::PlaybackEventsRecorder> playback_events_recorder_;
1086 absl::optional<ReadyState> stale_state_override_for_testing_;
1088 // True if we attempt to start the media pipeline in a suspended state for
1089 // preload=metadata. Cleared upon pipeline startup.
1090 bool attempting_suspended_start_ = false;
1092 // True if a frame has ever been rendered.
1093 bool has_first_frame_ = false;
1095 // True if we have not yet rendered a first frame, but one is needed. Set back
1096 // to false as soon as |has_first_frame_| is set to true.
1097 bool needs_first_frame_ = false;
1099 // Whether the rendered frame is readable, e.g. can be converted to image.
1100 bool is_frame_readable_ = false;
1102 // True if StartPipeline() completed a lazy load startup.
1103 bool did_lazy_load_ = false;
1105 // Whether the renderer should automatically suspend media playback in
1107 bool is_background_suspend_enabled_ = false;
1109 // If disabled, video will be auto paused when in background. Affects the
1110 // value of ShouldPausePlaybackWhenHidden().
1111 bool is_background_video_playback_enabled_ = true;
1113 // Whether background video optimization is supported on current platform.
1114 bool is_background_video_track_optimization_supported_ = true;
1116 const bool should_pause_background_muted_audio_;
1118 bool was_suspended_for_frame_closed_ = false;
1120 #if defined(TIZEN_MULTIMEDIA)
1121 bool was_suspended_by_player_ = false;
1124 // Request pipeline to suspend. It should not block other signals after
1126 bool pending_oneshot_suspend_ = false;
1128 base::CancelableOnceClosure have_enough_after_lazy_load_cb_;
1130 media::RendererType renderer_type_ = media::RendererType::kRendererImpl;
1131 media::SimpleWatchTimer simple_watch_timer_;
1133 LearningExperimentHelper will_play_helper_;
1135 #if defined(TIZEN_VIDEO_HOLE)
1136 bool is_video_hole_;
1137 gfx::RectF last_computed_rect_;
1138 base::RepeatingTimer layer_bound_update_timer_;
1141 std::unique_ptr<PowerStatusHelper> power_status_helper_;
1143 // Created while playing, deleted otherwise.
1144 std::unique_ptr<SmoothnessHelper> smoothness_helper_;
1145 absl::optional<int> last_reported_fps_;
1147 // Time of the last call to GetCurrentFrameFromCompositor(). Used to prevent
1148 // background optimizations from being applied when capturing is active.
1149 base::TimeTicks last_frame_request_time_;
1151 // Count the number of times a video frame is being readback.
1152 unsigned video_frame_readback_count_ = 0;
1154 base::WeakPtr<WebMediaPlayerImpl> weak_this_;
1155 base::WeakPtrFactory<WebMediaPlayerImpl> weak_factory_{this};
1158 } // namespace blink
1160 #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_WEB_MEDIA_PLAYER_IMPL_H_