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