Upload upstream chromium 108.0.5359.1
[platform/framework/web/chromium-efl.git] / third_party / blink / renderer / platform / media / web_media_player_impl.h
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.
4
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_
7
8 #include <stdint.h>
9
10 #include <memory>
11 #include <string>
12 #include <vector>
13
14 #include "base/cancelable_callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/memory/memory_pressure_listener.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/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/encryption_scheme.h"
28 #include "media/base/media_observer.h"
29 #include "media/base/media_tracks.h"
30 #include "media/base/overlay_info.h"
31 #include "media/base/pipeline_impl.h"
32 #include "media/base/renderer_factory_selector.h"
33 #include "media/base/routing_token_callback.h"
34 #include "media/base/simple_watch_timer.h"
35 #include "media/base/text_track.h"
36 #include "media/mojo/mojom/media_metrics_provider.mojom.h"
37 #include "media/mojo/mojom/playback_events_recorder.mojom.h"
38 #include "media/renderers/paint_canvas_video_renderer.h"
39 #include "mojo/public/cpp/bindings/pending_remote.h"
40 #include "mojo/public/cpp/bindings/remote.h"
41 #include "services/media_session/public/cpp/media_position.h"
42 #include "third_party/abseil-cpp/absl/types/optional.h"
43 #include "third_party/blink/public/platform/media/video_frame_compositor.h"
44 #include "third_party/blink/public/platform/media/web_media_player_builder.h"
45 #include "third_party/blink/public/platform/media/webmediaplayer_delegate.h"
46 #include "third_party/blink/public/platform/web_audio_source_provider.h"
47 #include "third_party/blink/public/platform/web_content_decryption_module_result.h"
48 #include "third_party/blink/public/platform/web_media_player.h"
49 #include "third_party/blink/public/platform/web_surface_layer_bridge.h"
50 #include "third_party/blink/public/web/modules/media/webmediaplayer_util.h"
51 #include "third_party/blink/renderer/platform/media/learning_experiment_helper.h"
52 #include "third_party/blink/renderer/platform/media/multi_buffer_data_source.h"
53 #include "third_party/blink/renderer/platform/media/smoothness_helper.h"
54 #include "third_party/blink/renderer/platform/platform_export.h"
55 #include "url/gurl.h"
56
57 namespace base {
58 class SingleThreadTaskRunner;
59 class TaskRunner;
60 }  // namespace base
61
62 namespace cc {
63 class VideoLayer;
64 }
65
66 namespace gfx {
67 class Size;
68 }
69
70 namespace learning {
71 class LearningTaskController;
72 }
73
74 namespace media {
75 class CdmContextRef;
76 class ChunkDemuxer;
77 class DataSource;
78 class Demuxer;
79 class MediaLog;
80 class MemoryDumpProviderProxy;
81 class PipelineController;
82 class SwitchableAudioRendererSink;
83 }  // namespace media
84
85 namespace viz {
86 class RasterContextProvider;
87 }
88
89 namespace blink {
90 class BufferedDataSourceHostImpl;
91 class PowerStatusHelper;
92 class ThreadSafeBrowserInterfaceBrokerProxy;
93 class UrlIndex;
94 class VideoDecodeStatsReporter;
95 class VideoFrameCompositor;
96 class WatchTimeReporter;
97 class WebAudioSourceProviderImpl;
98 class WebContentDecryptionModule;
99 class WebLocalFrame;
100 class WebMediaPlayerClient;
101 class WebMediaPlayerEncryptedMediaClient;
102
103 // The canonical implementation of WebMediaPlayer that's backed by
104 // Pipeline. Handles normal resource loading, Media Source, and
105 // Encrypted Media.
106 class PLATFORM_EXPORT WebMediaPlayerImpl
107     : public WebMediaPlayer,
108       public WebMediaPlayerDelegate::Observer,
109       public media::Pipeline::Client,
110       public media::MediaObserverClient,
111       public WebSurfaceLayerBridgeObserver,
112       public SmoothnessHelper::Client {
113  public:
114   // Constructs a WebMediaPlayer implementation using Chromium's media stack.
115   // |delegate| and |renderer_factory_selector| must not be null.
116   WebMediaPlayerImpl(
117       WebLocalFrame* frame,
118       WebMediaPlayerClient* client,
119       WebMediaPlayerEncryptedMediaClient* encrypted_client,
120       WebMediaPlayerDelegate* delegate,
121       std::unique_ptr<media::RendererFactorySelector> renderer_factory_selector,
122       UrlIndex* url_index,
123       std::unique_ptr<VideoFrameCompositor> compositor,
124       std::unique_ptr<media::MediaLog> media_log,
125       media::MediaPlayerLoggingID player_id,
126       WebMediaPlayerBuilder::DeferLoadCB defer_load_cb,
127       scoped_refptr<media::SwitchableAudioRendererSink> audio_renderer_sink,
128       scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
129       scoped_refptr<base::TaskRunner> worker_task_runner,
130       scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner,
131       scoped_refptr<base::SingleThreadTaskRunner>
132           video_frame_compositor_task_runner,
133       WebMediaPlayerBuilder::AdjustAllocatedMemoryCB adjust_allocated_memory_cb,
134       WebContentDecryptionModule* initial_cdm,
135       media::RequestRoutingTokenCallback request_routing_token_cb,
136       base::WeakPtr<media::MediaObserver> media_observer,
137       bool enable_instant_source_buffer_gc,
138       bool embedded_media_experience_enabled,
139       mojo::PendingRemote<media::mojom::MediaMetricsProvider> metrics_provider,
140       CreateSurfaceLayerBridgeCB create_bridge_callback,
141       scoped_refptr<viz::RasterContextProvider> raster_context_provider,
142       bool use_surface_layer,
143       bool is_background_suspend_enabled,
144       bool is_background_video_play_enabled,
145       bool is_background_video_track_optimization_supported,
146       std::unique_ptr<media::Demuxer> demuxer_override,
147       scoped_refptr<ThreadSafeBrowserInterfaceBrokerProxy> remote_interfaces);
148   WebMediaPlayerImpl(const WebMediaPlayerImpl&) = delete;
149   WebMediaPlayerImpl& operator=(const WebMediaPlayerImpl&) = delete;
150   ~WebMediaPlayerImpl() override;
151
152   // WebSurfaceLayerBridgeObserver implementation.
153   void OnWebLayerUpdated() override;
154   void RegisterContentsLayer(cc::Layer* layer) override;
155   void UnregisterContentsLayer(cc::Layer* layer) override;
156   void OnSurfaceIdUpdated(viz::SurfaceId surface_id) override;
157
158   WebMediaPlayer::LoadTiming Load(LoadType load_type,
159                                   const WebMediaPlayerSource& source,
160                                   CorsMode cors_mode,
161                                   bool is_cache_disabled) override;
162
163   // Playback controls.
164   void Play() override;
165   void Pause() override;
166   void Seek(double seconds) override;
167   void SetRate(double rate) override;
168   void SetVolume(double volume) override;
169   void SetLatencyHint(double seconds) override;
170   void SetPreservesPitch(bool preserves_pitch) override;
171   void SetWasPlayedWithUserActivation(
172       bool was_played_with_user_activation) override;
173   void OnRequestPictureInPicture() override;
174   void OnTimeUpdate() override;
175   bool SetSinkId(const WebString& sink_id,
176                  WebSetSinkIdCompleteCallback completion_callback) override;
177   void SetPoster(const WebURL& poster) override;
178   void SetPreload(WebMediaPlayer::Preload preload) override;
179   WebTimeRanges Buffered() const override;
180   WebTimeRanges Seekable() const override;
181
182   void OnFrozen() override;
183
184   // paint() the current video frame into |canvas|. This is used to support
185   // various APIs and functionalities, including but not limited to: <canvas>,
186   // ImageBitmap, printing and capturing capabilities.
187   void Paint(cc::PaintCanvas* canvas,
188              const gfx::Rect& rect,
189              cc::PaintFlags& flags) override;
190   scoped_refptr<media::VideoFrame> GetCurrentFrameThenUpdate() override;
191   absl::optional<int> CurrentFrameId() const override;
192   media::PaintCanvasVideoRenderer* GetPaintCanvasVideoRenderer() override;
193
194   // True if the loaded media has a playable video/audio track.
195   bool HasVideo() const override;
196   bool HasAudio() const override;
197
198   void EnabledAudioTracksChanged(
199       const WebVector<WebMediaPlayer::TrackId>& enabledTrackIds) override;
200   void SelectedVideoTrackChanged(
201       WebMediaPlayer::TrackId* selectedTrackId) override;
202
203   // Dimensions of the video.
204   gfx::Size NaturalSize() const override;
205
206   gfx::Size VisibleSize() const override;
207
208   // Getters of playback state.
209   bool Paused() const override;
210   bool Seeking() const override;
211   double Duration() const override;
212   virtual double timelineOffset() const;
213   double CurrentTime() const override;
214   bool IsEnded() const override;
215
216   bool PausedWhenHidden() const override;
217
218   // Internal states of loading and network.
219   // TODO(hclam): Ask the pipeline about the state rather than having reading
220   // them from members which would cause race conditions.
221   WebMediaPlayer::NetworkState GetNetworkState() const override;
222   WebMediaPlayer::ReadyState GetReadyState() const override;
223
224   WebString GetErrorMessage() const override;
225   bool DidLoadingProgress() override;
226   bool WouldTaintOrigin() const override;
227
228   double MediaTimeForTimeValue(double timeValue) const override;
229
230   unsigned DecodedFrameCount() const override;
231   unsigned DroppedFrameCount() const override;
232   uint64_t AudioDecodedByteCount() const override;
233   uint64_t VideoDecodedByteCount() const override;
234
235   bool PassedTimingAllowOriginCheck() const override;
236
237   void SetVolumeMultiplier(double multiplier) override;
238   void SetPersistentState(bool persistent) override;
239   void SetPowerExperimentState(bool state) override;
240   void SuspendForFrameClosed() override;
241
242   bool HasAvailableVideoFrame() const override;
243
244   scoped_refptr<WebAudioSourceProviderImpl> GetAudioSourceProvider() override;
245
246   void SetContentDecryptionModule(
247       WebContentDecryptionModule* cdm,
248       WebContentDecryptionModuleResult result) override;
249
250   void EnteredFullscreen() override;
251   void ExitedFullscreen() override;
252   void BecameDominantVisibleContent(bool is_dominant) override;
253   void SetIsEffectivelyFullscreen(
254       WebFullscreenVideoStatus fullscreen_video_status) override;
255   void OnHasNativeControlsChanged(bool) override;
256   void OnDisplayTypeChanged(DisplayType display_type) override;
257
258   // WebMediaPlayerDelegate::Observer implementation.
259   void OnFrameHidden() override;
260   void OnFrameShown() override;
261   void OnIdleTimeout() override;
262   void RequestRemotePlaybackDisabled(bool disabled) override;
263
264 #if BUILDFLAG(IS_ANDROID)
265   // TODO(https://crbug.com/839651): Rename Flinging[Started/Stopped] to
266   // RemotePlayback[Started/Stopped] once the other RemotePlayback methods have
267   // been removed
268   void FlingingStarted() override;
269   void FlingingStopped() override;
270
271   // Called when the play/pause state of media playing on a remote cast device
272   // changes, and WMPI wasn't the originator of that change (e.g. a phone on the
273   // same network paused the cast device via the casting notification).
274   // This is only used by the FlingingRenderer/FlingingRendererClient, when we
275   // are flinging media (a.k.a. RemotePlayback).
276   // The consistency between the WMPI state and the cast device state is not
277   // guaranteed, and it a best effort, which can always be fixed by the user by
278   // tapping play/pause once. Attempts to enfore stronger consistency guarantees
279   // have lead to unstable states, and a worse user experience.
280   void OnRemotePlayStateChange(media::MediaStatus::State state);
281 #endif
282
283   // media::MediaObserverClient implementation.
284   void SwitchToRemoteRenderer(
285       const std::string& remote_device_friendly_name) override;
286   void SwitchToLocalRenderer(
287       media::MediaObserverClient::ReasonToSwitchToLocal reason) override;
288   void UpdateRemotePlaybackCompatibility(bool is_compatible) override;
289
290   // Test helper methods for exercising media suspension. Once called, when
291   // |target_state| is reached or exceeded the stale flag will be set when
292   // computing the play state, which will trigger suspend if the player is
293   // paused; see UpdatePlayState_ComputePlayState() for the exact details.
294   void ForceStaleStateForTesting(ReadyState target_state) override;
295   bool IsSuspendedForTesting() override;
296   bool DidLazyLoad() const override;
297   void OnBecameVisible() override;
298   bool IsOpaque() const override;
299   int GetDelegateId() override;
300   absl::optional<viz::SurfaceId> GetSurfaceId() override;
301   GURL GetSrcAfterRedirects() override;
302   void RequestVideoFrameCallback() override;
303   std::unique_ptr<WebMediaPlayer::VideoFramePresentationMetadata>
304   GetVideoFramePresentationMetadata() override;
305   void UpdateFrameIfStale() override;
306
307   base::WeakPtr<WebMediaPlayer> AsWeakPtr() override;
308   void RegisterFrameSinkHierarchy() override;
309   void UnregisterFrameSinkHierarchy() override;
310
311   bool IsBackgroundMediaSuspendEnabled() const {
312     return is_background_suspend_enabled_;
313   }
314
315   // Distinct states that |delegate_| can be in. (Public for testing.)
316   enum class DelegateState {
317     GONE,
318     PLAYING,
319     PAUSED,
320   };
321
322   // Playback state variables computed together in UpdatePlayState().
323   // (Public for testing.)
324   struct PlayState {
325     DelegateState delegate_state;
326     bool is_idle;
327     bool is_memory_reporting_enabled;
328     bool is_suspended;
329   };
330
331   // Allow background video tracks with ~5 second keyframes (rounding down) to
332   // be disabled to save resources.
333   enum { kMaxKeyframeDistanceToDisableBackgroundVideoMs = 5500 };
334
335  private:
336   friend class WebMediaPlayerImplTest;
337   friend class WebMediaPlayerImplBackgroundBehaviorTest;
338
339   void EnableOverlay();
340   void DisableOverlay();
341
342   // Do we have overlay information?  For CVV, this is a surface id.  For
343   // AndroidOverlay, this is the routing token.
344   bool HaveOverlayInfo();
345
346   // Send OverlayInfo to the decoder.
347   //
348   // If we've requested but not yet received the surface id or routing token, or
349   // if there's no decoder-provided callback to send the overlay info, then this
350   // call will do nothing.
351   void MaybeSendOverlayInfoToDecoder();
352
353   void OnPipelineSuspended();
354   void OnBeforePipelineResume();
355   void OnPipelineResumed();
356   void OnPipelineSeeked(bool time_updated);
357   void OnDemuxerOpened();
358
359   // media::Pipeline::Client overrides.
360   void OnError(media::PipelineStatus status) override;
361   void OnFallback(media::PipelineStatus status) override;
362   void OnEnded() override;
363   void OnMetadata(const media::PipelineMetadata& metadata) override;
364   void OnBufferingStateChange(
365       media::BufferingState state,
366       media::BufferingStateChangeReason reason) override;
367   void OnDurationChange() override;
368   void OnAddTextTrack(const media::TextTrackConfig& config,
369                       media::AddTextTrackDoneCB done_cb) override;
370   void OnWaiting(media::WaitingReason reason) override;
371   void OnAudioConfigChange(const media::AudioDecoderConfig& config) override;
372   void OnVideoConfigChange(const media::VideoDecoderConfig& config) override;
373   void OnVideoNaturalSizeChange(const gfx::Size& size) override;
374   void OnVideoOpacityChange(bool opaque) override;
375   void OnVideoFrameRateChange(absl::optional<int> fps) override;
376   void OnVideoAverageKeyframeDistanceUpdate() override;
377   void OnAudioPipelineInfoChange(const media::AudioPipelineInfo& info) override;
378   void OnVideoPipelineInfoChange(const media::VideoPipelineInfo& info) override;
379
380   // Simplified watch time reporting.
381   void OnSimpleWatchTimerTick();
382
383   // Actually seek. Avoids causing |should_notify_time_changed_| to be set when
384   // |time_updated| is false.
385   void DoSeek(base::TimeDelta time, bool time_updated);
386
387   // Called after |defer_load_cb_| has decided to allow the load. If
388   // |defer_load_cb_| is null this is called immediately.
389   void DoLoad(LoadType load_type,
390               const WebURL& url,
391               CorsMode cors_mode,
392               bool is_cache_disabled);
393
394   // Called after asynchronous initialization of a data source completed.
395   void DataSourceInitialized(bool success);
396
397   // Called if the |MultiBufferDataSource| is redirected.
398   void OnDataSourceRedirected();
399
400   // Called when the data source is downloading or paused.
401   void NotifyDownloading(bool is_downloading);
402
403   // Called by RenderFrameImpl with the overlay routing token, if we request it.
404   void OnOverlayRoutingToken(const base::UnguessableToken& token);
405
406   // Called by GpuVideoDecoder on Android to request a surface to render to (if
407   // necessary).
408   void OnOverlayInfoRequested(
409       bool decoder_requires_restart_for_overlay,
410       media::ProvideOverlayInfoCB provide_overlay_info_cb);
411
412   // Creates a Renderer via the |renderer_factory_selector_|. If the
413   // |renderer_type| is absl::nullopt, create the base Renderer. Otherwise, set
414   // the base type to be |renderer_type| and create a Renderer of that type.
415   std::unique_ptr<media::Renderer> CreateRenderer(
416       absl::optional<media::RendererType> renderer_type);
417
418   // Finishes starting the pipeline due to a call to load().
419   void StartPipeline();
420
421   // Restart the player/pipeline as soon as possible. This will destroy the
422   // current renderer, if any, and create a new one via the RendererFactory; and
423   // then seek to resume playback at the current position.
424   void ScheduleRestart();
425
426   // Helpers that set the network/ready state and notifies the client if
427   // they've changed.
428   void SetNetworkState(WebMediaPlayer::NetworkState state);
429   void SetReadyState(WebMediaPlayer::ReadyState state);
430
431   // Returns the current video frame from |compositor_|, and asks the compositor
432   // to update its frame if it is stale.
433   // Can return a nullptr.
434   scoped_refptr<media::VideoFrame> GetCurrentFrameFromCompositor() const;
435
436   // Called when the demuxer encounters encrypted streams.
437   void OnEncryptedMediaInitData(media::EmeInitDataType init_data_type,
438                                 const std::vector<uint8_t>& init_data);
439
440   // Called when the FFmpegDemuxer encounters new media tracks. This is only
441   // invoked when using FFmpegDemuxer, since MSE/ChunkDemuxer handle media
442   // tracks separately in WebSourceBufferImpl.
443   void OnFFmpegMediaTracksUpdated(std::unique_ptr<media::MediaTracks> tracks);
444
445   // Sets CdmContext from |cdm| on the pipeline and calls OnCdmAttached()
446   // when done.
447   void SetCdmInternal(WebContentDecryptionModule* cdm);
448
449   // Called when a CDM has been attached to the |pipeline_|.
450   void OnCdmAttached(bool success);
451
452   // Inspects the current playback state and:
453   //   - notifies |delegate_|,
454   //   - toggles the memory usage reporting timer, and
455   //   - toggles suspend/resume as necessary.
456   //
457   // This method should be called any time its dependent values change. These
458   // are:
459   //   - is_flinging_,
460   //   - hasVideo(),
461   //   - delegate_->IsHidden(),
462   //   - network_state_, ready_state_,
463   //   - is_idle_, must_suspend_,
464   //   - paused_, ended_,
465   //   - pending_suspend_resume_cycle_,
466   //   - enter_pip_callback_,
467   void UpdatePlayState();
468
469   // Methods internal to UpdatePlayState().
470   PlayState UpdatePlayState_ComputePlayState(bool is_flinging,
471                                              bool can_auto_suspend,
472                                              bool is_suspended,
473                                              bool is_backgrounded,
474                                              bool is_in_picture_in_picture);
475   void SetDelegateState(DelegateState new_state, bool is_idle);
476   void SetMemoryReportingState(bool is_memory_reporting_enabled);
477   void SetSuspendState(bool is_suspended);
478
479   void SetDemuxer(std::unique_ptr<media::Demuxer> demuxer);
480
481   // Called at low frequency to tell external observers how much memory we're
482   // using for video playback.  Called by |memory_usage_reporting_timer_|.
483   // Memory usage reporting is done in two steps, because |demuxer_| must be
484   // accessed on the media thread.
485   void ReportMemoryUsage();
486   void FinishMemoryUsageReport(int64_t demuxer_memory_usage);
487
488   void OnMainThreadMemoryDump(int32_t id,
489                               const base::trace_event::MemoryDumpArgs& args,
490                               base::trace_event::ProcessMemoryDump* pmd);
491   static void OnMediaThreadMemoryDump(
492       int32_t id,
493       media::Demuxer* demuxer,
494       const base::trace_event::MemoryDumpArgs& args,
495       base::trace_event::ProcessMemoryDump* pmd);
496
497   void OnMemoryPressure(
498       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
499
500   // Called during OnHidden() when we want a suspended player to enter the
501   // paused state after some idle timeout.
502   void ScheduleIdlePauseTimer();
503
504   // Returns |true| before HaveFutureData whenever there has been loading
505   // progress and we have not been resumed for at least kLoadingToIdleTimeout
506   // since then.
507   //
508   // This is used to delay suspension long enough for preroll to complete, which
509   // is necessay because play() will not be called before HaveFutureData (and
510   // thus we think we are idle forever).
511   bool IsPrerollAttemptNeeded();
512
513   void CreateWatchTimeReporter();
514   void UpdateSecondaryProperties();
515
516   void CreateVideoDecodeStatsReporter();
517
518   // Returns true if the player is hidden.
519   bool IsHidden() const;
520
521   // Returns true if the player's source is streaming.
522   bool IsStreaming() const;
523
524   // Return whether |pipeline_metadata_| is compatible with an overlay. This
525   // is intended for android.
526   bool DoesOverlaySupportMetadata() const;
527
528   // Whether the playback should be paused when hidden. Uses metadata so has
529   // meaning only after the pipeline has started, otherwise returns false.
530   // Doesn't check if the playback can actually be paused depending on the
531   // pipeline's state.
532   bool ShouldPausePlaybackWhenHidden() const;
533
534   // Whether the video track should be disabled when hidden. Uses metadata so
535   // has meaning only after the pipeline has started, otherwise returns false.
536   // Doesn't check if the video track can actually be disabled depending on the
537   // pipeline's state.
538   bool ShouldDisableVideoWhenHidden() const;
539
540   // Whether the video is suitable for background playback optimizations (either
541   // pausing it or disabling the video track). Uses metadata so has meaning only
542   // after the pipeline has started, otherwise returns false.
543   // The logical OR between the two methods above that is also used as their
544   // common implementation.
545   bool IsBackgroundOptimizationCandidate() const;
546
547   // If enabling or disabling background video optimization has been delayed,
548   // because of the pipeline not running, seeking or resuming, this method
549   // needs to be called to update the optimization state.
550   void UpdateBackgroundVideoOptimizationState();
551
552   // Pauses a hidden video only player to save power if possible.
553   // Must be called when either of the following happens:
554   // - right after the video was hidden,
555   // - right ater the pipeline has resumed if the video is hidden.
556   void PauseVideoIfNeeded();
557
558   // Disables the video track to save power if possible.
559   // Must be called when either of the following happens:
560   // - right after the video was hidden,
561   // - right after the pipeline has started (|seeking_| is used to detect the
562   //   when pipeline started) if the video is hidden,
563   // - right ater the pipeline has resumed if the video is hidden.
564   void DisableVideoTrackIfNeeded();
565
566   // Enables the video track if it was disabled before to save power.
567   // Must be called when either of the following happens:
568   // - right after the video was shown,
569   // - right before the pipeline is requested to resume
570   //   (see https://crbug.com/678374),
571   // - right after the pipeline has resumed if the video is not hidden.
572   void EnableVideoTrackIfNeeded();
573
574   // Overrides the pipeline statistics returned by GetPiplineStatistics() for
575   // tests.
576   void SetPipelineStatisticsForTest(const media::PipelineStatistics& stats);
577
578   // Returns the pipeline statistics or the value overridden by tests.
579   media::PipelineStatistics GetPipelineStatistics() const;
580
581   // Overrides the pipeline media duration returned by
582   // GetPipelineMediaDuration() for tests.
583   void SetPipelineMediaDurationForTest(base::TimeDelta duration);
584
585   // Returns the pipeline media duration or the value overridden by tests.
586   base::TimeDelta GetPipelineMediaDuration() const;
587
588   media::MediaContentType GetMediaContentType() const;
589
590   // Records |duration| to the appropriate metric based on whether we're
591   // handling a src= or MSE based playback.
592   void RecordUnderflowDuration(base::TimeDelta duration);
593
594   // Called by the data source (for src=) or demuxer (for mse) when loading
595   // progresses.
596   // Can be called quite often.
597   void OnProgress();
598
599   // Returns true when we estimate that we can play the rest of the media
600   // without buffering.
601   bool CanPlayThrough();
602
603   // Internal implementation of Pipeline::Client::OnBufferingStateChange(). When
604   // |for_suspended_start| is true, the given state will be set even if the
605   // pipeline is not currently stable.
606   void OnBufferingStateChangeInternal(media::BufferingState state,
607                                       media::BufferingStateChangeReason reason,
608                                       bool for_suspended_start = false);
609
610   // Records |natural_size| to MediaLog and video height to UMA.
611   void RecordVideoNaturalSize(const gfx::Size& natural_size);
612
613   void SetTickClockForTest(const base::TickClock* tick_clock);
614
615   // Returns the current time without clamping to Duration() as required by
616   // HTMLMediaElement for handling ended. This method will never return a
617   // negative or kInfiniteDuration value. See http://crbug.com/409280,
618   // http://crbug.com/645998, and http://crbug.com/751823 for reasons why.
619   base::TimeDelta GetCurrentTimeInternal() const;
620
621   // Called by the compositor the very first time a frame is received.
622   void OnFirstFrame(base::TimeTicks frame_time);
623
624   // Records timing metrics for three UMA metrics: #key.SRC, #key.MSE, and
625   // #key.EME. The SRC and MSE ones are mutually exclusive based on the presence
626   // of |chunk_demuxer_|, while the EME one is only recorded if |is_encrypted_|.
627   void RecordTimingUMA(const std::string& key, base::TimeDelta elapsed);
628
629   // Records the encryption scheme used by the stream |stream_name|. This is
630   // only recorded when metadata is available.
631   void RecordEncryptionScheme(const std::string& stream_name,
632                               media::EncryptionScheme encryption_scheme);
633
634   // Returns whether the player is currently displayed in Picture-in-Picture.
635   // It will return true even if the player is in AutoPIP mode.
636   // The player MUST have a `client_` when this call happen.
637   bool IsInPictureInPicture() const;
638
639   // Sets the UKM container name if needed.
640   void MaybeSetContainerNameForMetrics();
641
642   // Switch to SurfaceLayer, either initially or from VideoLayer.
643   void ActivateSurfaceLayerForVideo();
644
645   // Called by |compositor_| upon presenting a frame, after
646   // RequestAnimationFrame() is called.
647   void OnNewFramePresentedCallback();
648
649   // Notifies |mb_data_source_| of playback and rate changes which may increase
650   // the amount of data the DataSource buffers. Does nothing prior to reaching
651   // kReadyStateHaveEnoughData for the first time.
652   void MaybeUpdateBufferSizesForPlayback();
653
654   // Create / recreate |smoothness_helper_|, with current features.  Will take
655   // no action if we already have a smoothness helper with the same features
656   // that we want now.  Will destroy the helper if we shouldn't be measuring
657   // smoothness right now.
658   void UpdateSmoothnessHelper();
659
660   // Get the LearningTaskController for |task_name|.
661   std::unique_ptr<media::learning::LearningTaskController>
662   GetLearningTaskController(const char* task_name);
663
664   // Returns whether the player has an audio track and whether it should be
665   // allowed to play it.
666   bool HasUnmutedAudio() const;
667
668   // Returns true if the video frame from this player are being captured.
669   bool IsVideoBeingCaptured() const;
670
671   // Report UMAs when this object instance is destroyed.
672   void ReportSessionUMAs() const;
673
674   WebLocalFrame* const frame_;
675
676   WebMediaPlayer::NetworkState network_state_ =
677       WebMediaPlayer::kNetworkStateEmpty;
678   WebMediaPlayer::ReadyState ready_state_ =
679       WebMediaPlayer::kReadyStateHaveNothing;
680   WebMediaPlayer::ReadyState highest_ready_state_ =
681       WebMediaPlayer::kReadyStateHaveNothing;
682
683   // Preload state for when |data_source_| is created after setPreload().
684   MultiBufferDataSource::Preload preload_ = MultiBufferDataSource::METADATA;
685
686   // Poster state (for UMA reporting).
687   bool has_poster_ = false;
688
689   // Task runner for posting tasks on Chrome's main thread. Also used
690   // for DCHECKs so methods calls won't execute in the wrong thread.
691   const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
692   const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
693   const scoped_refptr<base::TaskRunner> worker_task_runner_;
694
695   // This is the ID that is used within the internals of the media element
696   // primarily for correlating logs.
697   const media::MediaPlayerLoggingID media_player_id_;
698
699   std::unique_ptr<media::MediaLog> media_log_;
700
701   // |pipeline_controller_| owns an instance of Pipeline.
702   std::unique_ptr<media::PipelineController> pipeline_controller_;
703
704   // The LoadType passed in the |load_type| parameter of the load() call.
705   LoadType load_type_ = kLoadTypeURL;
706
707   // Cache of metadata for answering hasAudio(), hasVideo(), and naturalSize().
708   media::PipelineMetadata pipeline_metadata_;
709
710   // Whether the video is known to be opaque or not.
711   bool opaque_ = false;
712
713   // Playback state.
714   //
715   // TODO(scherkus): we have these because Pipeline favours the simplicity of a
716   // single "playback rate" over worrying about paused/stopped etc...  It forces
717   // all clients to manage the pause+playback rate externally, but is that
718   // really a bad thing?
719   //
720   // TODO(scherkus): since SetPlaybackRate(0) is asynchronous and we don't want
721   // to hang the render thread during pause(), we record the time at the same
722   // time we pause and then return that value in currentTime().  Otherwise our
723   // clock can creep forward a little bit while the asynchronous
724   // SetPlaybackRate(0) is being executed.
725   double playback_rate_ = 0.0;
726
727   // Counter that limits spam to |media_log_| of |playback_rate_| changes.
728   int num_playback_rate_logs_ = 0;
729
730   // Set while paused. |paused_time_| is only valid when |paused_| is true.
731   bool paused_ = true;
732   base::TimeDelta paused_time_;
733
734   // Set if paused automatically when hidden and need to resume when visible.
735   // Reset if paused for any other reason.
736   bool paused_when_hidden_ = false;
737
738   // Set when starting, seeking, and resuming (all of which require a Pipeline
739   // seek). |seek_time_| is only valid when |seeking_| is true.
740   bool seeking_ = false;
741   base::TimeDelta seek_time_;
742
743   // Set when doing a restart (a suspend and resume in sequence) of the pipeline
744   // in order to destruct and reinitialize the decoders. This is separate from
745   // |pending_resume_| and |pending_suspend_| because they can be elided in
746   // certain cases, whereas for a restart they must happen.
747   // TODO(sandersd,watk): Create a simpler interface for a pipeline restart.
748   bool pending_suspend_resume_cycle_ = false;
749
750   // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
751   // see http://crbug.com/409280
752   bool ended_ = false;
753
754   // Tracks whether to issue time changed notifications during buffering state
755   // changes.
756   bool should_notify_time_changed_ = false;
757
758   bool overlay_enabled_ = false;
759
760   // Whether the current decoder requires a restart on overlay transitions.
761   bool decoder_requires_restart_for_overlay_ = false;
762
763   WebMediaPlayerClient* const client_;
764   WebMediaPlayerEncryptedMediaClient* const encrypted_client_;
765
766   // WebMediaPlayer notifies the |delegate_| of playback state changes using
767   // |delegate_id_|; an id provided after registering with the delegate.  The
768   // WebMediaPlayer may also receive directives (play, pause) from the delegate
769   // via the WebMediaPlayerDelegate::Observer interface after registration.
770   //
771   // NOTE: HTMLMediaElement is a ExecutionContextLifecycleObserver, and
772   // will receive a call to contextDestroyed() when Document::shutdown()
773   // is called. Document::shutdown() is called before the frame detaches (and
774   // before the frame is destroyed). RenderFrameImpl owns |delegate_| and is
775   // guaranteed to outlive |this|; thus it is safe to store |delegate_| as a raw
776   // pointer.
777   WebMediaPlayerDelegate* delegate_;
778   int delegate_id_ = 0;
779
780   // The playback state last reported to |delegate_|, to avoid setting duplicate
781   // states.
782   // TODO(sandersd): The delegate should be implementing deduplication.
783   DelegateState delegate_state_ = DelegateState::GONE;
784   bool delegate_has_audio_ = false;
785
786   WebMediaPlayerBuilder::DeferLoadCB defer_load_cb_;
787
788   // Members for notifying upstream clients about internal memory usage.  The
789   // |adjust_allocated_memory_cb_| must only be called on |main_task_runner_|.
790   base::RepeatingTimer memory_usage_reporting_timer_;
791   WebMediaPlayerBuilder::AdjustAllocatedMemoryCB adjust_allocated_memory_cb_;
792   int64_t last_reported_memory_usage_ = 0;
793   std::unique_ptr<media::MemoryDumpProviderProxy> main_thread_mem_dumper_;
794   std::unique_ptr<media::MemoryDumpProviderProxy> media_thread_mem_dumper_;
795
796   // Routes audio playback to either AudioRendererSink or WebAudio.
797   scoped_refptr<WebAudioSourceProviderImpl> audio_source_provider_;
798
799   // These two are mutually exclusive:
800   //   |data_source_| is used for regular resource loads.
801   //   |chunk_demuxer_| is used for Media Source resource loads.
802   //
803   // |demuxer_| will contain the appropriate demuxer based on which resource
804   // load strategy we're using.
805   MultiBufferDataSource* mb_data_source_ = nullptr;
806   std::unique_ptr<media::DataSource> data_source_;
807   std::unique_ptr<media::Demuxer> demuxer_;
808   media::ChunkDemuxer* chunk_demuxer_ = nullptr;
809
810   std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
811
812   const base::TickClock* tick_clock_ = nullptr;
813
814   std::unique_ptr<BufferedDataSourceHostImpl> buffered_data_source_host_;
815   UrlIndex* const url_index_;
816   scoped_refptr<viz::RasterContextProvider> raster_context_provider_;
817
818   // Video rendering members.
819   // The |compositor_| runs on the compositor thread, or if
820   // kEnableSurfaceLayerForVideo is enabled, the media thread. This task runner
821   // posts tasks for the |compositor_| on the correct thread.
822   scoped_refptr<base::SingleThreadTaskRunner> vfc_task_runner_;
823   std::unique_ptr<VideoFrameCompositor>
824       compositor_;  // Deleted on |vfc_task_runner_|.
825   media::PaintCanvasVideoRenderer video_renderer_;
826
827   // The compositor layer for displaying the video content when using composited
828   // playback.
829   scoped_refptr<cc::VideoLayer> video_layer_;
830
831   std::unique_ptr<WebContentDecryptionModuleResult> set_cdm_result_;
832
833   // If a CdmContext is attached keep a reference to the CdmContextRef, so that
834   // it is not destroyed until after the pipeline is done with it.
835   std::unique_ptr<media::CdmContextRef> cdm_context_ref_;
836
837   // Keep track of the CdmContextRef while it is in the process of attaching to
838   // the pipeline.
839   std::unique_ptr<media::CdmContextRef> pending_cdm_context_ref_;
840
841   // True when encryption is detected, either by demuxer or by presence of a
842   // ContentDecyprtionModule (CDM).
843   bool is_encrypted_ = false;
844
845   // Captured once the cdm is provided to SetCdmInternal(). Used in creation of
846   // |video_decode_stats_reporter_|.
847   absl::optional<media::CdmConfig> cdm_config_;
848
849   // Tracks if we are currently flinging a video (e.g. in a RemotePlayback
850   // session). Used to prevent videos from being paused when hidden.
851   // TODO(https://crbug.com/839651): remove or rename this flag, when removing
852   // IsRemote().
853   bool is_flinging_ = false;
854
855   // Tracks if we are currently using a remote renderer. See
856   // SwitchToRemoteRenderer().
857   bool is_remote_rendering_ = false;
858
859   // The last volume received by setVolume() and the last volume multiplier from
860   // SetVolumeMultiplier().  The multiplier is typical 1.0, but may be less
861   // if the WebMediaPlayerDelegate has requested a volume reduction (ducking)
862   // for a transient sound.  Playout volume is derived by volume * multiplier.
863   double volume_ = 1.0;
864   double volume_multiplier_ = 1.0;
865
866   std::unique_ptr<media::RendererFactorySelector> renderer_factory_selector_;
867
868   // For canceling AndroidOverlay routing token requests.
869   base::CancelableOnceCallback<void(const base::UnguessableToken&)>
870       token_available_cb_;
871
872   // If overlay info is requested before we have it, then the request is saved
873   // and satisfied once the overlay info is available. If the decoder does not
874   // require restart to change surfaces, this is callback is kept until cleared
875   // by the decoder.
876   media::ProvideOverlayInfoCB provide_overlay_info_cb_;
877
878   // On Android an overlay surface means using
879   // SurfaceView instead of SurfaceTexture.
880
881   // Allow overlays for all video on android.
882   bool always_enable_overlays_ = false;
883
884   // Suppresses calls to OnPipelineError() after destruction / shutdown has been
885   // started; prevents us from spuriously logging errors that are transient or
886   // unimportant.
887   bool suppress_destruction_errors_ = false;
888
889   // TODO(dalecurtis): The following comment is inaccurate as this value is also
890   // used for, for example, data URLs.
891   // Used for HLS playback and in certain fallback paths (e.g. on older devices
892   // that can't support the unified media pipeline).
893   GURL loaded_url_;
894
895   // NOTE: |using_media_player_renderer_| is set based on the usage of a
896   // MediaResource::Type::URL in StartPipeline(). This works because
897   // MediaPlayerRendererClientFactory is the only factory that uses
898   // MediaResource::Type::URL for now.
899   bool using_media_player_renderer_ = false;
900
901 #if BUILDFLAG(IS_ANDROID)
902   // Set during the initial DoLoad() call. Used to determine whether to allow
903   // credentials or not for MediaPlayerRenderer.
904   bool allow_media_player_renderer_credentials_ = false;
905 #endif
906
907   // Stores the current position state of the media.
908   media_session::MediaPosition media_position_state_;
909
910   // Set whenever the demuxer encounters an HLS file.
911   // This flag is distinct from |using_media_player_renderer_|, because on older
912   // devices we might use MediaPlayerRenderer for non HLS playback.
913   bool demuxer_found_hls_ = false;
914
915   // Called sometime after the media is suspended in a playing state in
916   // OnFrameHidden(), causing the state to change to paused.
917   base::OneShotTimer background_pause_timer_;
918
919   // Monitors the watch time of the played content.
920   std::unique_ptr<WatchTimeReporter> watch_time_reporter_;
921   media::AudioDecoderType audio_decoder_type_ =
922       media::AudioDecoderType::kUnknown;
923   media::VideoDecoderType video_decoder_type_ =
924       media::VideoDecoderType::kUnknown;
925
926   // The time at which DoLoad() is executed.
927   base::TimeTicks load_start_time_;
928
929   // Time elapsed time from |load_start_time_| to OnMetadata(). Used to later
930   // adjust |load_start_time_| if a suspended startup occurred.
931   base::TimeDelta time_to_metadata_;
932   bool skip_metrics_due_to_startup_suspend_ = false;
933
934   bool have_reported_time_to_play_ready_ = false;
935
936   // Records pipeline statistics for describing media capabilities.
937   std::unique_ptr<VideoDecodeStatsReporter> video_decode_stats_reporter_;
938
939   // Elapsed time since we've last reached BUFFERING_HAVE_NOTHING.
940   std::unique_ptr<base::ElapsedTimer> underflow_timer_;
941
942   // Used to track loading progress, used by IsPrerollAttemptNeeded().
943   // |preroll_attempt_pending_| indicates that the clock has been reset
944   // (awaiting a resume to start), while |preroll_attempt_start_time_| tracks
945   // when a preroll attempt began.
946   bool preroll_attempt_pending_ = false;
947   base::TimeTicks preroll_attempt_start_time_;
948
949   // Monitors the player events.
950   base::WeakPtr<media::MediaObserver> observer_;
951
952   // Owns the weblayer and obtains/maintains SurfaceIds.
953   std::unique_ptr<WebSurfaceLayerBridge> bridge_;
954
955   // The maximum video keyframe distance that allows triggering background
956   // playback optimizations (non-MSE).
957   base::TimeDelta max_keyframe_distance_to_disable_background_video_;
958
959   // The maximum video keyframe distance that allows triggering background
960   // playback optimizations (MSE).
961   base::TimeDelta max_keyframe_distance_to_disable_background_video_mse_;
962
963   // When MSE memory pressure based garbage collection is enabled, the
964   // |enable_instant_source_buffer_gc| controls whether the GC is done
965   // immediately on memory pressure notification or during the next SourceBuffer
966   // append (slower, but MSE spec compliant).
967   bool enable_instant_source_buffer_gc_ = false;
968
969   // Whether disabled the video track as an optimization.
970   bool video_track_disabled_ = false;
971
972   // Whether the pipeline is being resumed at the moment.
973   bool is_pipeline_resuming_ = false;
974
975   // When this is true, pipeline will not be auto suspended.
976   bool disable_pipeline_auto_suspend_ = false;
977
978   // Pipeline statistics overridden by tests.
979   absl::optional<media::PipelineStatistics> pipeline_statistics_for_test_;
980
981   // Pipeline media duration overridden by tests.
982   absl::optional<base::TimeDelta> pipeline_media_duration_for_test_;
983
984   // Whether the video requires a user gesture to resume after it was paused in
985   // the background. Affects the value of ShouldPausePlaybackWhenHidden().
986   bool video_locked_when_paused_when_hidden_ = false;
987
988   // Whether embedded media experience is currently enabled.
989   bool embedded_media_experience_enabled_ = false;
990
991   // When should we use SurfaceLayer for video?
992   bool use_surface_layer_ = false;
993
994   // Whether surface layer is currently in use to display frames.
995   bool surface_layer_for_video_enabled_ = false;
996
997   CreateSurfaceLayerBridgeCB create_bridge_callback_;
998
999   bool initial_video_height_recorded_ = false;
1000
1001   enum class OverlayMode {
1002     // All overlays are turned off.
1003     kNoOverlays,
1004
1005     // Use AndroidOverlay for overlays.
1006     kUseAndroidOverlay,
1007   };
1008
1009   OverlayMode overlay_mode_ = OverlayMode::kNoOverlays;
1010
1011   // Optional callback to request the routing token for AndroidOverlay.
1012   media::RequestRoutingTokenCallback request_routing_token_cb_;
1013
1014   // If |overlay_routing_token_is_pending_| is false, then
1015   // |overlay_routing_token_| contains the routing token we should send, if any.
1016   // Otherwise, |overlay_routing_token_| is undefined.  We set the flag while
1017   // we have a request for the token that hasn't been answered yet; i.e., it
1018   // means that we don't know what, if any, token we should be using.
1019   bool overlay_routing_token_is_pending_ = false;
1020   media::OverlayInfo::RoutingToken overlay_routing_token_;
1021
1022   media::OverlayInfo overlay_info_;
1023
1024   base::CancelableOnceClosure update_background_status_cb_;
1025
1026   // We cannot use `update_background_status_cb_.IsCancelled()` as that changes
1027   // when the callback is run, even if not explicitly cancelled. This is
1028   // initialized to true to keep in line with the existing behavior of
1029   // base::CancellableOnceClosure.
1030   bool is_background_status_change_cancelled_ = true;
1031
1032   mojo::Remote<media::mojom::MediaMetricsProvider> media_metrics_provider_;
1033   mojo::Remote<media::mojom::PlaybackEventsRecorder> playback_events_recorder_;
1034
1035   absl::optional<ReadyState> stale_state_override_for_testing_;
1036
1037   // True if we attempt to start the media pipeline in a suspended state for
1038   // preload=metadata. Cleared upon pipeline startup.
1039   bool attempting_suspended_start_ = false;
1040
1041   // True if a frame has ever been rendered.
1042   bool has_first_frame_ = false;
1043
1044   // True if we have not yet rendered a first frame, but one is needed. Set back
1045   // to false as soon as |has_first_frame_| is set to true.
1046   bool needs_first_frame_ = false;
1047
1048   // True if StartPipeline() completed a lazy load startup.
1049   bool did_lazy_load_ = false;
1050
1051   // Whether the renderer should automatically suspend media playback in
1052   // background tabs.
1053   bool is_background_suspend_enabled_ = false;
1054
1055   // If disabled, video will be auto paused when in background. Affects the
1056   // value of ShouldPausePlaybackWhenHidden().
1057   bool is_background_video_playback_enabled_ = true;
1058
1059   // Whether background video optimization is supported on current platform.
1060   bool is_background_video_track_optimization_supported_ = true;
1061
1062   bool was_suspended_for_frame_closed_ = false;
1063
1064   base::CancelableOnceClosure have_enough_after_lazy_load_cb_;
1065
1066   media::RendererType renderer_type_ = media::RendererType::kDefault;
1067   media::SimpleWatchTimer simple_watch_timer_;
1068
1069   LearningExperimentHelper will_play_helper_;
1070
1071   // Stores the optional override Demuxer until it is used in DoLoad().
1072   std::unique_ptr<media::Demuxer> demuxer_override_;
1073
1074   std::unique_ptr<PowerStatusHelper> power_status_helper_;
1075
1076   // Created while playing, deleted otherwise.
1077   std::unique_ptr<SmoothnessHelper> smoothness_helper_;
1078   absl::optional<int> last_reported_fps_;
1079
1080   // Time of the last call to GetCurrentFrameFromCompositor(). Used to prevent
1081   // background optimizations from being applied when capturing is active.
1082   base::TimeTicks last_frame_request_time_;
1083
1084   // Count the number of times a video frame is being readback.
1085   unsigned video_frame_readback_count_ = 0;
1086
1087   base::WeakPtr<WebMediaPlayerImpl> weak_this_;
1088   base::WeakPtrFactory<WebMediaPlayerImpl> weak_factory_{this};
1089 };
1090
1091 }  // namespace blink
1092
1093 #endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_WEB_MEDIA_PLAYER_IMPL_H_