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/ref_counted.h"
17 #include "base/memory/scoped_refptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/task/sequenced_task_runner.h"
20 #include "base/threading/thread.h"
21 #include "base/time/default_tick_clock.h"
22 #include "base/time/time.h"
23 #include "base/timer/elapsed_timer.h"
24 #include "base/timer/timer.h"
25 #include "build/build_config.h"
26 #include "media/base/cdm_config.h"
27 #include "media/base/data_source.h"
28 #include "media/base/demuxer.h"
29 #include "media/base/eme_constants.h"
30 #include "media/base/encryption_scheme.h"
31 #include "media/base/media_observer.h"
32 #include "media/base/media_tracks.h"
33 #include "media/base/overlay_info.h"
34 #include "media/base/pipeline_impl.h"
35 #include "media/base/renderer_factory_selector.h"
36 #include "media/base/routing_token_callback.h"
37 #include "media/base/simple_watch_timer.h"
38 #include "media/base/text_track.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;
258 scoped_refptr<WebAudioSourceProviderImpl> GetAudioSourceProvider() override;
260 void SetContentDecryptionModule(
261 WebContentDecryptionModule* cdm,
262 WebContentDecryptionModuleResult result) override;
264 void EnteredFullscreen() override;
265 void ExitedFullscreen() override;
266 void BecameDominantVisibleContent(bool is_dominant) override;
267 void SetIsEffectivelyFullscreen(
268 WebFullscreenVideoStatus fullscreen_video_status) override;
269 void OnHasNativeControlsChanged(bool) override;
270 void OnDisplayTypeChanged(DisplayType display_type) override;
272 // WebMediaPlayerDelegate::Observer implementation.
273 void OnFrameHidden() override;
274 void OnFrameShown() override;
275 void OnIdleTimeout() override;
277 void RequestRemotePlaybackDisabled(bool disabled) override;
278 void RequestMediaRemoting() override;
280 #if BUILDFLAG(IS_ANDROID)
281 // TODO(https://crbug.com/839651): Rename Flinging[Started/Stopped] to
282 // RemotePlayback[Started/Stopped] once the other RemotePlayback methods have
284 void FlingingStarted() override;
285 void FlingingStopped() override;
287 // Called when the play/pause state of media playing on a remote cast device
288 // changes, and WMPI wasn't the originator of that change (e.g. a phone on the
289 // same network paused the cast device via the casting notification).
290 // This is only used by the FlingingRenderer/FlingingRendererClient, when we
291 // are flinging media (a.k.a. RemotePlayback).
292 // The consistency between the WMPI state and the cast device state is not
293 // guaranteed, and it a best effort, which can always be fixed by the user by
294 // tapping play/pause once. Attempts to enfore stronger consistency guarantees
295 // have lead to unstable states, and a worse user experience.
296 void OnRemotePlayStateChange(media::MediaStatus::State state);
299 // media::MediaObserverClient implementation.
300 void SwitchToRemoteRenderer(
301 const std::string& remote_device_friendly_name) override;
302 void SwitchToLocalRenderer(
303 media::MediaObserverClient::ReasonToSwitchToLocal reason) override;
304 void UpdateRemotePlaybackCompatibility(bool is_compatible) override;
306 // Test helper methods for exercising media suspension. Once called, when
307 // |target_state| is reached or exceeded the stale flag will be set when
308 // computing the play state, which will trigger suspend if the player is
309 // paused; see UpdatePlayState_ComputePlayState() for the exact details.
310 void ForceStaleStateForTesting(ReadyState target_state) override;
311 bool IsSuspendedForTesting() override;
312 bool DidLazyLoad() const override;
313 void OnBecameVisible() override;
314 bool IsOpaque() const override;
315 int GetDelegateId() override;
316 absl::optional<viz::SurfaceId> GetSurfaceId() override;
317 GURL GetSrcAfterRedirects() override;
318 void RequestVideoFrameCallback() override;
319 std::unique_ptr<WebMediaPlayer::VideoFramePresentationMetadata>
320 GetVideoFramePresentationMetadata() override;
321 void UpdateFrameIfStale() override;
323 base::WeakPtr<WebMediaPlayer> AsWeakPtr() override;
324 void RegisterFrameSinkHierarchy() override;
325 void UnregisterFrameSinkHierarchy() override;
327 bool IsBackgroundMediaSuspendEnabled() const {
328 return is_background_suspend_enabled_;
331 // Distinct states that |delegate_| can be in. (Public for testing.)
332 enum class DelegateState {
338 // Playback state variables computed together in UpdatePlayState().
339 // (Public for testing.)
341 DelegateState delegate_state;
343 bool is_memory_reporting_enabled;
347 // Allow background video tracks with ~5 second keyframes (rounding down) to
348 // be disabled to save resources.
349 enum { kMaxKeyframeDistanceToDisableBackgroundVideoMs = 5500 };
352 friend class WebMediaPlayerImplTest;
353 friend class WebMediaPlayerImplBackgroundBehaviorTest;
355 // Helper function that can be used for generating different UMA records:
356 // |key| is the UMA prefix, such as "Media.TimeToPlayReady", for example.
357 // |UmaFunction| is some UMA function, like base::UmaHistogramMediumTimes
358 // which the record actually gets logged with
359 // |T...| are the arguments passed. Usually this is only one piece of data,
360 // such as a base::TimeDelta, in the case of UmaHistogramMediumTimes,
361 // but could also be a series of fields that customize bucket sizes
364 // Finally, the |Flags| template argument is used to determine which suffixes
365 // are logged - An integer enum is provided |SplitHistogramTypes| which is
366 // a bitmask, and can be used to require logging:
367 // PlaybackType: {".SRC", ".MSE", ".HLS" (in the future)} based on demuxer
369 // Encrypted: {".EME"} based on the value of |is_encrypted_|
370 // All: {".All"} all the time.
371 // |Flags| is provided as a template argument instead of a function argument
372 // in order to guard different components in "if constexpr" conditionals,
373 // so we won't even compile in strings such as "Media.TimeToPlayReady.All"
374 // if it's not specified.
375 template <uint32_t Flags, typename... T>
376 void WriteSplitHistogram(void (*UmaFunction)(const std::string&, T...),
377 const std::string& key,
380 void EnableOverlay();
381 void DisableOverlay();
383 // Do we have overlay information? For CVV, this is a surface id. For
384 // AndroidOverlay, this is the routing token.
385 bool HaveOverlayInfo();
387 // Send OverlayInfo to the decoder.
389 // If we've requested but not yet received the surface id or routing token, or
390 // if there's no decoder-provided callback to send the overlay info, then this
391 // call will do nothing.
392 void MaybeSendOverlayInfoToDecoder();
394 void OnPipelineSuspended();
395 void OnBeforePipelineResume();
396 void OnPipelineResumed();
397 void OnPipelineSeeked(bool time_updated);
399 // media::Pipeline::Client overrides.
400 void OnError(media::PipelineStatus status) override;
401 void OnFallback(media::PipelineStatus status) override;
402 void OnEnded() override;
403 void OnMetadata(const media::PipelineMetadata& metadata) override;
404 void OnBufferingStateChange(
405 media::BufferingState state,
406 media::BufferingStateChangeReason reason) override;
407 void OnDurationChange() override;
408 void OnAddTextTrack(const media::TextTrackConfig& config,
409 media::AddTextTrackDoneCB done_cb) override;
410 void OnWaiting(media::WaitingReason reason) override;
411 void OnAudioConfigChange(const media::AudioDecoderConfig& config) override;
412 void OnVideoConfigChange(const media::VideoDecoderConfig& config) override;
413 void OnVideoNaturalSizeChange(const gfx::Size& size) override;
414 void OnVideoOpacityChange(bool opaque) override;
415 void OnVideoFrameRateChange(absl::optional<int> fps) override;
416 void OnVideoAverageKeyframeDistanceUpdate() override;
417 void OnAudioPipelineInfoChange(const media::AudioPipelineInfo& info) override;
418 void OnVideoPipelineInfoChange(const media::VideoPipelineInfo& info) override;
419 #if defined(TIZEN_MULTIMEDIA)
420 // Called if a player in the browser process is suspended.
421 void OnRequestSuspend() override;
424 // media::DemuxerManager::Client overrides.
425 void OnChunkDemuxerOpened(media::ChunkDemuxer* demuxer) override;
426 void OnProgress() override;
427 void OnEncryptedMediaInitData(media::EmeInitDataType init_data_type,
428 const std::vector<uint8_t>& init_data) override;
429 void MakeDemuxerThreadDumper(media::Demuxer* demuxer) override;
430 bool CouldPlayIfEnoughData() override;
431 bool IsMediaPlayerRendererClient() override;
432 void StopForDemuxerReset() override;
433 void RestartForHls() override;
434 bool IsSecurityOriginCryptographic() const override;
435 void UpdateLoadedUrl(const GURL& url) 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 base::SequenceBound<media::HlsDataSourceProvider> GetHlsDataSourceProvider()
451 #endif // BUILDFLAG(ENABLE_HLS_DEMUXER)
453 // Simplified watch time reporting.
454 void OnSimpleWatchTimerTick();
456 // Actually seek. Avoids causing |should_notify_time_changed_| to be set when
457 // |time_updated| is false.
458 void DoSeek(base::TimeDelta time, bool time_updated);
460 // Called after |defer_load_cb_| has decided to allow the load. If
461 // |defer_load_cb_| is null this is called immediately.
462 void DoLoad(LoadType load_type,
465 bool is_cache_disabled);
467 // Called after synchronous initialization of a data source completes.
468 void DataSourceInitialized(bool success);
470 // Called after asynchronous initialization of a multibuffer data source
472 void MultiBufferDataSourceInitialized(bool success);
474 // Called after synchronous or asynchronous MemoryDataSource initialization.
475 void MemoryDataSourceInitialized(bool success, size_t data_size);
477 // Called if the |MultiBufferDataSource| is redirected.
478 void OnDataSourceRedirected();
480 // Called when the data source is downloading or paused.
481 void NotifyDownloading(bool is_downloading);
483 // Called by RenderFrameImpl with the overlay routing token, if we request it.
484 void OnOverlayRoutingToken(const base::UnguessableToken& token);
486 // Called by GpuVideoDecoder on Android to request a surface to render to (if
488 void OnOverlayInfoRequested(
489 bool decoder_requires_restart_for_overlay,
490 media::ProvideOverlayInfoCB provide_overlay_info_cb);
492 // Creates a Renderer via the |renderer_factory_selector_|. If the
493 // |renderer_type| is absl::nullopt, create the base Renderer. Otherwise, set
494 // the base type to be |renderer_type| and create a Renderer of that type.
495 std::unique_ptr<media::Renderer> CreateRenderer(
496 absl::optional<media::RendererType> renderer_type);
498 // Finishes starting the pipeline due to a call to load().
499 void StartPipeline();
501 // Restart the player/pipeline as soon as possible. This will destroy the
502 // current renderer, if any, and create a new one via the RendererFactory; and
503 // then seek to resume playback at the current position.
504 void ScheduleRestart();
506 // Helpers that set the network/ready state and notifies the client if
508 void SetNetworkState(WebMediaPlayer::NetworkState state);
509 void SetReadyState(WebMediaPlayer::ReadyState state);
511 // Returns the current video frame from |compositor_|, and asks the compositor
512 // to update its frame if it is stale.
513 // Can return a nullptr.
514 scoped_refptr<media::VideoFrame> GetCurrentFrameFromCompositor() const;
516 // Sets CdmContext from |cdm| on the pipeline and calls OnCdmAttached()
518 void SetCdmInternal(WebContentDecryptionModule* cdm);
520 // Called when a CDM has been attached to the |pipeline_|.
521 void OnCdmAttached(bool success);
523 // Inspects the current playback state and:
524 // - notifies |delegate_|,
525 // - toggles the memory usage reporting timer, and
526 // - toggles suspend/resume as necessary.
528 // This method should be called any time its dependent values change. These
532 // - delegate_->IsHidden(),
533 // - network_state_, ready_state_,
534 // - is_idle_, must_suspend_,
535 // - paused_, ended_,
536 // - pending_suspend_resume_cycle_,
537 // - enter_pip_callback_,
538 void UpdatePlayState();
540 // Methods internal to UpdatePlayState().
541 PlayState UpdatePlayState_ComputePlayState(bool is_flinging,
542 bool can_auto_suspend,
544 bool is_backgrounded,
545 bool is_in_picture_in_picture);
546 void SetDelegateState(DelegateState new_state, bool is_idle);
547 void SetMemoryReportingState(bool is_memory_reporting_enabled);
548 void SetSuspendState(bool is_suspended);
550 // Called at low frequency to tell external observers how much memory we're
551 // using for video playback. Called by |memory_usage_reporting_timer_|.
552 // Memory usage reporting is done in two steps, because |demuxer_| must be
553 // accessed on the media thread.
554 void ReportMemoryUsage();
555 void FinishMemoryUsageReport(int64_t demuxer_memory_usage);
557 void OnMainThreadMemoryDump(int32_t id,
558 const base::trace_event::MemoryDumpArgs& args,
559 base::trace_event::ProcessMemoryDump* pmd);
560 static void OnMediaThreadMemoryDump(
562 media::Demuxer* demuxer,
563 const base::trace_event::MemoryDumpArgs& args,
564 base::trace_event::ProcessMemoryDump* pmd);
566 // Called during OnHidden() when we want a suspended player to enter the
567 // paused state after some idle timeout.
568 void ScheduleIdlePauseTimer();
570 // Returns |true| before HaveFutureData whenever there has been loading
571 // progress and we have not been resumed for at least kLoadingToIdleTimeout
574 // This is used to delay suspension long enough for preroll to complete, which
575 // is necessay because play() will not be called before HaveFutureData (and
576 // thus we think we are idle forever).
577 bool IsPrerollAttemptNeeded();
579 void CreateWatchTimeReporter();
580 void UpdateSecondaryProperties();
582 void CreateVideoDecodeStatsReporter();
584 // Returns true if the player is hidden.
585 bool IsHidden() const;
587 // Returns true if the player is in streaming mode, meaning that the source
588 // or the demuxer doesn't support timeline or seeking.
589 bool IsStreaming() const;
591 // Return whether |pipeline_metadata_| is compatible with an overlay. This
592 // is intended for android.
593 bool DoesOverlaySupportMetadata() const;
595 // Whether the playback should be paused when hidden. Uses metadata so has
596 // meaning only after the pipeline has started, otherwise returns false.
597 // Doesn't check if the playback can actually be paused depending on the
599 bool ShouldPausePlaybackWhenHidden() const;
601 // Whether the video track should be disabled when hidden. Uses metadata so
602 // has meaning only after the pipeline has started, otherwise returns false.
603 // Doesn't check if the video track can actually be disabled depending on the
605 bool ShouldDisableVideoWhenHidden() const;
607 // If enabling or disabling background video optimization has been delayed,
608 // because of the pipeline not running, seeking or resuming, this method
609 // needs to be called to update the optimization state.
610 void UpdateBackgroundVideoOptimizationState();
612 // Pauses a hidden video only player to save power if possible.
613 // Must be called when either of the following happens:
614 // - right after the video was hidden,
615 // - right ater the pipeline has resumed if the video is hidden.
616 void PauseVideoIfNeeded();
618 // Disables the video track to save power if possible.
619 // Must be called when either of the following happens:
620 // - right after the video was hidden,
621 // - right after the pipeline has started (|seeking_| is used to detect the
622 // when pipeline started) if the video is hidden,
623 // - right ater the pipeline has resumed if the video is hidden.
624 void DisableVideoTrackIfNeeded();
626 // Enables the video track if it was disabled before to save power.
627 // Must be called when either of the following happens:
628 // - right after the video was shown,
629 // - right before the pipeline is requested to resume
630 // (see https://crbug.com/678374),
631 // - right after the pipeline has resumed if the video is not hidden.
632 void EnableVideoTrackIfNeeded();
634 // Overrides the pipeline statistics returned by GetPiplineStatistics() for
636 void SetPipelineStatisticsForTest(const media::PipelineStatistics& stats);
638 // Returns the pipeline statistics or the value overridden by tests.
639 media::PipelineStatistics GetPipelineStatistics() const;
641 // Overrides the pipeline media duration returned by
642 // GetPipelineMediaDuration() for tests.
643 void SetPipelineMediaDurationForTest(base::TimeDelta duration);
645 // Returns the pipeline media duration or the value overridden by tests.
646 base::TimeDelta GetPipelineMediaDuration() const;
648 media::MediaContentType GetMediaContentType() const;
650 // Records |duration| to the appropriate metric based on whether we're
651 // handling a src= or MSE based playback.
652 void RecordUnderflowDuration(base::TimeDelta duration);
654 // Returns true when we estimate that we can play the rest of the media
655 // without buffering.
656 bool CanPlayThrough();
658 // Internal implementation of Pipeline::Client::OnBufferingStateChange(). When
659 // |for_suspended_start| is true, the given state will be set even if the
660 // pipeline is not currently stable.
661 void OnBufferingStateChangeInternal(media::BufferingState state,
662 media::BufferingStateChangeReason reason,
663 bool for_suspended_start = false);
665 // Records |natural_size| to MediaLog and video height to UMA.
666 void RecordVideoNaturalSize(const gfx::Size& natural_size);
668 void SetTickClockForTest(const base::TickClock* tick_clock);
670 // Returns the current time without clamping to Duration() as required by
671 // HTMLMediaElement for handling ended. This method will never return a
672 // negative or kInfiniteDuration value. See http://crbug.com/409280,
673 // http://crbug.com/645998, and http://crbug.com/751823 for reasons why.
674 base::TimeDelta GetCurrentTimeInternal() const;
676 // Called by the compositor the very first time a frame is received.
677 void OnFirstFrame(base::TimeTicks frame_time);
679 // Records the encryption scheme used by the stream |stream_name|. This is
680 // only recorded when metadata is available.
681 void RecordEncryptionScheme(const std::string& stream_name,
682 media::EncryptionScheme encryption_scheme);
684 // Returns whether the player is currently displayed in Picture-in-Picture.
685 // It will return true even if the player is in AutoPIP mode.
686 // The player MUST have a `client_` when this call happen.
687 bool IsInPictureInPicture() const;
689 // Sets the UKM container name if needed.
690 void MaybeSetContainerNameForMetrics();
692 // Switch to SurfaceLayer, either initially or from VideoLayer.
693 void ActivateSurfaceLayerForVideo();
695 // Called by |compositor_| upon presenting a frame, after
696 // RequestAnimationFrame() is called.
697 void OnNewFramePresentedCallback();
699 // Notifies |demuxer_manager_| of playback and rate changes which may increase
700 // the amount of data the DataSource buffers. Does nothing prior to reaching
701 // kReadyStateHaveEnoughData for the first time.
702 void MaybeUpdateBufferSizesForPlayback();
704 // Create / recreate |smoothness_helper_|, with current features. Will take
705 // no action if we already have a smoothness helper with the same features
706 // that we want now. Will destroy the helper if we shouldn't be measuring
707 // smoothness right now.
708 void UpdateSmoothnessHelper();
710 // Get the LearningTaskController for |task_name|.
711 std::unique_ptr<media::learning::LearningTaskController>
712 GetLearningTaskController(const char* task_name);
714 // Returns whether the player has an audio track and whether it should be
715 // allowed to play it.
716 bool HasUnmutedAudio() const;
718 // Returns true if the video frame from this player are being captured.
719 bool IsVideoBeingCaptured() const;
721 #if defined(TIZEN_VIDEO_HOLE)
722 bool ShouldUseVideoHole() const;
723 void CreateVideoHoleFrame();
724 void OnDrawableContentRectChanged(gfx::Rect rect, bool is_video);
725 bool UpdateBoundaryRectangle();
726 void StartLayerBoundUpdateTimer();
727 void StopLayerBoundUpdateTimer();
728 void OnLayerBoundUpdateTimerFired();
731 // Report UMAs when this object instance is destroyed.
732 void ReportSessionUMAs() const;
734 absl::optional<media::DemuxerType> GetDemuxerType() const;
736 // Useful to bind for a cb to be called when a demuxer is created.
737 media::PipelineStatus OnDemuxerCreated(media::Demuxer* demuxer,
738 media::Pipeline::StartType start_type,
742 WebLocalFrame* const frame_;
744 WebMediaPlayer::NetworkState network_state_ =
745 WebMediaPlayer::kNetworkStateEmpty;
746 WebMediaPlayer::ReadyState ready_state_ =
747 WebMediaPlayer::kReadyStateHaveNothing;
748 WebMediaPlayer::ReadyState highest_ready_state_ =
749 WebMediaPlayer::kReadyStateHaveNothing;
751 // Preload state for when a DataSource is created after setPreload().
752 media::DataSource::Preload preload_ = media::DataSource::METADATA;
754 // Poster state (for UMA reporting).
755 bool has_poster_ = false;
757 // Task runner for posting tasks on Chrome's main thread. Also used
758 // for DCHECKs so methods calls won't execute in the wrong thread.
759 const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
760 const scoped_refptr<base::SequencedTaskRunner> media_task_runner_;
761 const scoped_refptr<base::TaskRunner> worker_task_runner_;
763 // This is the ID that is used within the internals of the media element
764 // primarily for correlating logs.
765 const media::MediaPlayerLoggingID media_player_id_;
767 std::unique_ptr<media::MediaLog> media_log_;
769 // |pipeline_controller_| owns an instance of Pipeline.
770 std::unique_ptr<media::PipelineController> pipeline_controller_;
772 // The LoadType passed in the |load_type| parameter of the load() call.
773 LoadType load_type_ = kLoadTypeURL;
775 // Cache of metadata for answering hasAudio(), hasVideo(), and naturalSize().
776 media::PipelineMetadata pipeline_metadata_;
778 // Whether the video is known to be opaque or not.
779 bool opaque_ = false;
783 // TODO(scherkus): we have these because Pipeline favours the simplicity of a
784 // single "playback rate" over worrying about paused/stopped etc... It forces
785 // all clients to manage the pause+playback rate externally, but is that
786 // really a bad thing?
788 // TODO(scherkus): since SetPlaybackRate(0) is asynchronous and we don't want
789 // to hang the render thread during pause(), we record the time at the same
790 // time we pause and then return that value in currentTime(). Otherwise our
791 // clock can creep forward a little bit while the asynchronous
792 // SetPlaybackRate(0) is being executed.
793 double playback_rate_ = 0.0;
795 // Counter that limits spam to |media_log_| of |playback_rate_| changes.
796 int num_playback_rate_logs_ = 0;
798 // Set while paused. |paused_time_| is only valid when |paused_| is true.
800 base::TimeDelta paused_time_;
802 // Set if paused automatically when hidden and need to resume when visible.
803 // Reset if paused for any other reason.
804 bool paused_when_hidden_ = false;
806 // Set when starting, seeking, and resuming (all of which require a Pipeline
807 // seek). |seek_time_| is only valid when |seeking_| is true.
808 bool seeking_ = false;
809 base::TimeDelta seek_time_;
811 // Set when doing a restart (a suspend and resume in sequence) of the pipeline
812 // in order to destruct and reinitialize the decoders. This is separate from
813 // |pending_resume_| and |pending_suspend_| because they can be elided in
814 // certain cases, whereas for a restart they must happen.
815 // TODO(sandersd,watk): Create a simpler interface for a pipeline restart.
816 bool pending_suspend_resume_cycle_ = false;
818 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
819 // see http://crbug.com/409280
822 // Tracks whether to issue time changed notifications during buffering state
824 bool should_notify_time_changed_ = false;
826 bool overlay_enabled_ = false;
828 // Whether the current decoder requires a restart on overlay transitions.
829 bool decoder_requires_restart_for_overlay_ = false;
831 WebMediaPlayerClient* const client_;
832 WebMediaPlayerEncryptedMediaClient* const encrypted_client_;
834 // WebMediaPlayer notifies the |delegate_| of playback state changes using
835 // |delegate_id_|; an id provided after registering with the delegate. The
836 // WebMediaPlayer may also receive directives (play, pause) from the delegate
837 // via the WebMediaPlayerDelegate::Observer interface after registration.
839 // NOTE: HTMLMediaElement is a ExecutionContextLifecycleObserver, and
840 // will receive a call to contextDestroyed() when Document::shutdown()
841 // is called. Document::shutdown() is called before the frame detaches (and
842 // before the frame is destroyed). RenderFrameImpl owns |delegate_| and is
843 // guaranteed to outlive |this|; thus it is safe to store |delegate_| as a raw
845 WebMediaPlayerDelegate* delegate_;
846 int delegate_id_ = 0;
848 // The playback state last reported to |delegate_|, to avoid setting duplicate
850 // TODO(sandersd): The delegate should be implementing deduplication.
851 DelegateState delegate_state_ = DelegateState::GONE;
852 bool delegate_has_audio_ = false;
854 WebMediaPlayerBuilder::DeferLoadCB defer_load_cb_;
856 // Members for notifying upstream clients about internal memory usage. The
857 // |adjust_allocated_memory_cb_| must only be called on |main_task_runner_|.
858 base::RepeatingTimer memory_usage_reporting_timer_;
859 WebMediaPlayerBuilder::AdjustAllocatedMemoryCB adjust_allocated_memory_cb_;
860 int64_t last_reported_memory_usage_ = 0;
861 std::unique_ptr<media::MemoryDumpProviderProxy> main_thread_mem_dumper_;
862 std::unique_ptr<media::MemoryDumpProviderProxy> media_thread_mem_dumper_;
864 // Routes audio playback to either AudioRendererSink or WebAudio.
865 scoped_refptr<WebAudioSourceProviderImpl> audio_source_provider_;
867 // Manages the lifetime of the DataSource, and soon the Demuxer.
868 std::unique_ptr<media::DemuxerManager> demuxer_manager_;
870 const base::TickClock* tick_clock_ = nullptr;
872 std::unique_ptr<BufferedDataSourceHostImpl> buffered_data_source_host_;
873 UrlIndex* const url_index_;
874 scoped_refptr<viz::RasterContextProvider> raster_context_provider_;
876 // Video rendering members.
877 // The |compositor_| runs on the compositor thread, or if
878 // kEnableSurfaceLayerForVideo is enabled, the media thread. This task runner
879 // posts tasks for the |compositor_| on the correct thread.
880 scoped_refptr<base::SingleThreadTaskRunner> vfc_task_runner_;
881 std::unique_ptr<VideoFrameCompositor>
882 compositor_; // Deleted on |vfc_task_runner_|.
883 media::PaintCanvasVideoRenderer video_renderer_;
885 // The compositor layer for displaying the video content when using composited
887 scoped_refptr<cc::VideoLayer> video_layer_;
889 std::unique_ptr<WebContentDecryptionModuleResult> set_cdm_result_;
891 // If a CdmContext is attached keep a reference to the CdmContextRef, so that
892 // it is not destroyed until after the pipeline is done with it.
893 std::unique_ptr<media::CdmContextRef> cdm_context_ref_;
895 // Keep track of the CdmContextRef while it is in the process of attaching to
897 std::unique_ptr<media::CdmContextRef> pending_cdm_context_ref_;
899 // True when encryption is detected, either by demuxer or by presence of a
900 // ContentDecyprtionModule (CDM).
901 bool is_encrypted_ = false;
903 // Captured once the cdm is provided to SetCdmInternal(). Used in creation of
904 // |video_decode_stats_reporter_|.
905 absl::optional<media::CdmConfig> cdm_config_;
907 // Tracks if we are currently flinging a video (e.g. in a RemotePlayback
908 // session). Used to prevent videos from being paused when hidden.
909 // TODO(https://crbug.com/839651): remove or rename this flag, when removing
911 bool is_flinging_ = false;
913 // Tracks if we are currently using a remote renderer. See
914 // SwitchToRemoteRenderer().
915 bool is_remote_rendering_ = false;
917 // The last volume received by setVolume() and the last volume multiplier from
918 // SetVolumeMultiplier(). The multiplier is typical 1.0, but may be less
919 // if the WebMediaPlayerDelegate has requested a volume reduction (ducking)
920 // for a transient sound. Playout volume is derived by volume * multiplier.
921 double volume_ = 1.0;
922 double volume_multiplier_ = 1.0;
924 std::unique_ptr<media::RendererFactorySelector> renderer_factory_selector_;
926 // For canceling AndroidOverlay routing token requests.
927 base::CancelableOnceCallback<void(const base::UnguessableToken&)>
930 // If overlay info is requested before we have it, then the request is saved
931 // and satisfied once the overlay info is available. If the decoder does not
932 // require restart to change surfaces, this is callback is kept until cleared
934 media::ProvideOverlayInfoCB provide_overlay_info_cb_;
936 // On Android an overlay surface means using
937 // SurfaceView instead of SurfaceTexture.
939 // Allow overlays for all video on android.
940 bool always_enable_overlays_ = false;
942 // Suppresses calls to OnPipelineError() after destruction / shutdown has been
943 // started; prevents us from spuriously logging errors that are transient or
945 bool suppress_destruction_errors_ = false;
947 // TODO(dalecurtis): The following comment is inaccurate as this value is also
948 // used for, for example, data URLs.
949 // Used for HLS playback and in certain fallback paths (e.g. on older devices
950 // that can't support the unified media pipeline).
951 GURL loaded_url_ ALLOW_DISCOURAGED_TYPE("Avoids conversion in media code");
953 // NOTE: |using_media_player_renderer_| is set based on the usage of a
954 // MediaResource::Type::URL in StartPipeline(). This works because
955 // MediaPlayerRendererClientFactory is the only factory that uses
956 // MediaResource::Type::URL for now.
957 bool using_media_player_renderer_ = false;
959 #if BUILDFLAG(IS_ANDROID)
960 // Set during the initial DoLoad() call. Used to determine whether to allow
961 // credentials or not for MediaPlayerRenderer.
962 bool allow_media_player_renderer_credentials_ = false;
965 // Stores the current position state of the media.
966 media_session::MediaPosition media_position_state_;
968 // Called sometime after the media is suspended in a playing state in
969 // OnFrameHidden(), causing the state to change to paused.
970 base::OneShotTimer background_pause_timer_;
972 // Monitors the watch time of the played content.
973 std::unique_ptr<WatchTimeReporter> watch_time_reporter_;
974 media::AudioDecoderType audio_decoder_type_ =
975 media::AudioDecoderType::kUnknown;
976 media::VideoDecoderType video_decoder_type_ =
977 media::VideoDecoderType::kUnknown;
979 // The time at which DoLoad() is executed.
980 base::TimeTicks load_start_time_;
982 // Time elapsed time from |load_start_time_| to OnMetadata(). Used to later
983 // adjust |load_start_time_| if a suspended startup occurred.
984 base::TimeDelta time_to_metadata_;
985 bool skip_metrics_due_to_startup_suspend_ = false;
987 bool have_reported_time_to_play_ready_ = false;
989 // Records pipeline statistics for describing media capabilities.
990 std::unique_ptr<VideoDecodeStatsReporter> video_decode_stats_reporter_;
992 // Elapsed time since we've last reached BUFFERING_HAVE_NOTHING.
993 std::unique_ptr<base::ElapsedTimer> underflow_timer_;
995 // Used to track loading progress, used by IsPrerollAttemptNeeded().
996 // |preroll_attempt_pending_| indicates that the clock has been reset
997 // (awaiting a resume to start), while |preroll_attempt_start_time_| tracks
998 // when a preroll attempt began.
999 bool preroll_attempt_pending_ = false;
1000 base::TimeTicks preroll_attempt_start_time_;
1002 // Monitors the player events.
1003 base::WeakPtr<media::MediaObserver> observer_;
1005 // Owns the weblayer and obtains/maintains SurfaceIds.
1006 std::unique_ptr<WebSurfaceLayerBridge> bridge_;
1008 // The maximum video keyframe distance that allows triggering background
1009 // playback optimizations (non-MSE).
1010 base::TimeDelta max_keyframe_distance_to_disable_background_video_;
1012 // The maximum video keyframe distance that allows triggering background
1013 // playback optimizations (MSE).
1014 base::TimeDelta max_keyframe_distance_to_disable_background_video_mse_;
1016 // Whether disabled the video track as an optimization.
1017 bool video_track_disabled_ = false;
1019 // Whether the pipeline is being resumed at the moment.
1020 bool is_pipeline_resuming_ = false;
1022 // When this is true, pipeline will not be auto suspended.
1023 bool disable_pipeline_auto_suspend_ = false;
1025 // Pipeline statistics overridden by tests.
1026 absl::optional<media::PipelineStatistics> pipeline_statistics_for_test_;
1028 // Pipeline media duration overridden by tests.
1029 absl::optional<base::TimeDelta> pipeline_media_duration_for_test_;
1031 // Whether the video requires a user gesture to resume after it was paused in
1032 // the background. Affects the value of ShouldPausePlaybackWhenHidden().
1033 bool video_locked_when_paused_when_hidden_ = false;
1035 // Whether embedded media experience is currently enabled.
1036 bool embedded_media_experience_enabled_ = false;
1038 // When should we use SurfaceLayer for video?
1039 bool use_surface_layer_ = false;
1041 // Whether surface layer is currently in use to display frames.
1042 bool surface_layer_for_video_enabled_ = false;
1044 CreateSurfaceLayerBridgeCB create_bridge_callback_;
1046 bool initial_video_height_recorded_ = false;
1048 enum class OverlayMode {
1049 // All overlays are turned off.
1052 // Use AndroidOverlay for overlays.
1056 OverlayMode overlay_mode_ = OverlayMode::kNoOverlays;
1058 // Optional callback to request the routing token for AndroidOverlay.
1059 media::RequestRoutingTokenCallback request_routing_token_cb_;
1061 // If |overlay_routing_token_is_pending_| is false, then
1062 // |overlay_routing_token_| contains the routing token we should send, if any.
1063 // Otherwise, |overlay_routing_token_| is undefined. We set the flag while
1064 // we have a request for the token that hasn't been answered yet; i.e., it
1065 // means that we don't know what, if any, token we should be using.
1066 bool overlay_routing_token_is_pending_ = false;
1067 media::OverlayInfo::RoutingToken overlay_routing_token_;
1069 media::OverlayInfo overlay_info_;
1071 base::CancelableOnceClosure update_background_status_cb_;
1073 // We cannot use `update_background_status_cb_.IsCancelled()` as that changes
1074 // when the callback is run, even if not explicitly cancelled. This is
1075 // initialized to true to keep in line with the existing behavior of
1076 // base::CancellableOnceClosure.
1077 bool is_background_status_change_cancelled_ = true;
1079 mojo::Remote<media::mojom::MediaMetricsProvider> media_metrics_provider_;
1080 mojo::Remote<media::mojom::PlaybackEventsRecorder> playback_events_recorder_;
1082 absl::optional<ReadyState> stale_state_override_for_testing_;
1084 // True if we attempt to start the media pipeline in a suspended state for
1085 // preload=metadata. Cleared upon pipeline startup.
1086 bool attempting_suspended_start_ = false;
1088 // True if a frame has ever been rendered.
1089 bool has_first_frame_ = false;
1091 // True if we have not yet rendered a first frame, but one is needed. Set back
1092 // to false as soon as |has_first_frame_| is set to true.
1093 bool needs_first_frame_ = false;
1095 // True if StartPipeline() completed a lazy load startup.
1096 bool did_lazy_load_ = false;
1098 // Whether the renderer should automatically suspend media playback in
1100 bool is_background_suspend_enabled_ = false;
1102 // If disabled, video will be auto paused when in background. Affects the
1103 // value of ShouldPausePlaybackWhenHidden().
1104 bool is_background_video_playback_enabled_ = true;
1106 // Whether background video optimization is supported on current platform.
1107 bool is_background_video_track_optimization_supported_ = true;
1109 const bool should_pause_background_muted_audio_;
1111 bool was_suspended_for_frame_closed_ = false;
1113 #if defined(TIZEN_MULTIMEDIA)
1114 bool was_suspended_by_player_ = false;
1117 // Request pipeline to suspend. It should not block other signals after
1119 bool pending_oneshot_suspend_ = false;
1121 base::CancelableOnceClosure have_enough_after_lazy_load_cb_;
1123 media::RendererType renderer_type_ = media::RendererType::kRendererImpl;
1124 media::SimpleWatchTimer simple_watch_timer_;
1126 LearningExperimentHelper will_play_helper_;
1128 #if defined(TIZEN_VIDEO_HOLE)
1129 bool is_video_hole_;
1130 gfx::RectF last_computed_rect_;
1131 base::RepeatingTimer layer_bound_update_timer_;
1134 std::unique_ptr<PowerStatusHelper> power_status_helper_;
1136 // Created while playing, deleted otherwise.
1137 std::unique_ptr<SmoothnessHelper> smoothness_helper_;
1138 absl::optional<int> last_reported_fps_;
1140 // Time of the last call to GetCurrentFrameFromCompositor(). Used to prevent
1141 // background optimizations from being applied when capturing is active.
1142 base::TimeTicks last_frame_request_time_;
1144 // Count the number of times a video frame is being readback.
1145 unsigned video_frame_readback_count_ = 0;
1147 base::WeakPtr<WebMediaPlayerImpl> weak_this_;
1148 base::WeakPtrFactory<WebMediaPlayerImpl> weak_factory_{this};
1151 } // namespace blink
1153 #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_WEB_MEDIA_PLAYER_IMPL_H_