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