blob: 9d72af0afe84ffc7c9736d4d1b58939b896da28e [file] [log] [blame]
[email protected]85a37afd2013-05-30 22:51:151// Copyright 2013 The Chromium Authors. All rights reserved.
[email protected]891acc92009-04-27 19:56:412// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]ec9212f2008-12-18 21:40:364
acolwell9e0840d2014-09-06 19:01:325#include "media/blink/webmediaplayer_impl.h"
[email protected]8931c41a2009-07-07 17:31:496
[email protected]c2a45e242013-02-15 20:24:587#include <algorithm>
mateuszs3371ab02015-04-24 13:20:238#include <cmath>
[email protected]47b06ceb2010-08-04 22:41:119#include <limits>
Gyuyoung Kim62a5de42018-01-10 09:48:4210#include <memory>
guidouc7babef2015-10-22 00:42:3511#include <string>
dcheng652f5ff2015-12-27 08:54:0012#include <utility>
[email protected]47b06ceb2010-08-04 22:41:1113
[email protected]08273c7b2011-09-17 00:33:5114#include "base/bind.h"
sandersd1c0bba02016-03-04 23:14:0815#include "base/bind_helpers.h"
[email protected]2041cf342010-02-19 03:15:5916#include "base/callback.h"
[email protected]7502ef12014-01-25 01:19:2717#include "base/callback_helpers.h"
sandersd1e49fb62015-12-12 01:18:0618#include "base/command_line.h"
[email protected]ca04095f2014-02-07 10:23:5619#include "base/debug/alias.h"
[email protected]926f8fd2013-04-12 20:27:5320#include "base/debug/crash_logging.h"
fdoraydb3ef7d2016-06-09 15:42:3821#include "base/location.h"
Dale Curtis3899090ea2018-01-12 00:10:3522#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0823#include "base/metrics/histogram_macros.h"
acolwellb4034942014-08-28 15:42:4324#include "base/single_thread_task_runner.h"
servolka233f832016-06-10 20:39:0425#include "base/strings/string_number_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3326#include "base/task/post_task.h"
wdzierzanowskifd4cd91c52015-12-02 23:50:2027#include "base/task_runner_util.h"
gabba14a442016-05-11 20:10:2028#include "base/threading/thread_task_runner_handle.h"
ssid9525f4672015-01-28 12:13:1529#include "base/trace_event/trace_event.h"
sandersd1e49fb62015-12-12 01:18:0630#include "build/build_config.h"
[email protected]21c3f7502013-03-23 03:29:5131#include "cc/layers/video_layer.h"
CJ DiMeglioc60a5cf2017-09-27 20:08:4132#include "components/viz/common/gpu/context_provider.h"
[email protected]e4fc09e2012-04-06 03:17:4433#include "media/audio/null_audio_sink.h"
[email protected]2eccbed2014-01-10 05:15:5334#include "media/base/bind_to_current_loop.h"
xhwang0ad11e512014-11-25 23:43:0935#include "media/base/cdm_context.h"
John Rummelldb5a7ef2018-05-16 00:28:0136#include "media/base/encryption_scheme.h"
[email protected]32da1002010-03-03 21:57:3537#include "media/base/limits.h"
zqzhang5d8eab72016-08-26 20:34:3038#include "media/base/media_content_type.h"
[email protected]090f7312011-08-05 23:26:4039#include "media/base/media_log.h"
sandersd1e49fb62015-12-12 01:18:0640#include "media/base/media_switches.h"
tguilbert25a4d112016-10-13 21:56:5141#include "media/base/media_url_demuxer.h"
[email protected]8a561062013-11-22 01:19:3142#include "media/base/text_renderer.h"
watk9f9dfdc92015-09-04 21:33:2943#include "media/base/timestamp_constants.h"
[email protected]e81283bb2010-08-31 18:01:2144#include "media/base/video_frame.h"
acolwell9e0840d2014-09-06 19:01:3245#include "media/blink/texttrack_impl.h"
John Delaneyb933391602018-10-17 21:50:4746#include "media/blink/url_index.h"
Chris Cunninghamd9df58e2017-08-29 00:04:2347#include "media/blink/video_decode_stats_reporter.h"
dalecurtis04bdb582016-08-17 22:15:2348#include "media/blink/watch_time_reporter.h"
xhwang97de4202014-11-25 08:44:0149#include "media/blink/webcontentdecryptionmodule_impl.h"
acolwell9e0840d2014-09-06 19:01:3250#include "media/blink/webinbandtexttrack_impl.h"
acolwell9e0840d2014-09-06 19:01:3251#include "media/blink/webmediasource_impl.h"
[email protected]efe7cd22012-09-12 23:55:0152#include "media/filters/chunk_demuxer.h"
[email protected]ddbc6ff2013-04-19 15:28:3353#include "media/filters/ffmpeg_demuxer.h"
Dale Curtis4841c712018-12-13 18:14:0554#include "media/filters/memory_data_source.h"
Scott Violeta35f9a42018-03-22 22:00:4455#include "media/media_buildflags.h"
Gyuyoung Kima040bc52019-10-30 01:14:3556#include "mojo/public/cpp/bindings/pending_remote.h"
Dale Curtis4841c712018-12-13 18:14:0557#include "net/base/data_url.h"
Blink Reformata30d4232018-04-07 15:31:0658#include "third_party/blink/public/platform/web_encrypted_media_types.h"
Blink Reformata30d4232018-04-07 15:31:0659#include "third_party/blink/public/platform/web_media_player_client.h"
60#include "third_party/blink/public/platform/web_media_player_encrypted_media_client.h"
61#include "third_party/blink/public/platform/web_media_player_source.h"
62#include "third_party/blink/public/platform/web_media_source.h"
63#include "third_party/blink/public/platform/web_rect.h"
64#include "third_party/blink/public/platform/web_runtime_features.h"
65#include "third_party/blink/public/platform/web_security_origin.h"
66#include "third_party/blink/public/platform/web_size.h"
67#include "third_party/blink/public/platform/web_string.h"
68#include "third_party/blink/public/platform/web_surface_layer_bridge.h"
69#include "third_party/blink/public/platform/web_url.h"
Antonio Gomes3a858b52019-05-31 02:47:5270#include "third_party/blink/public/platform/webaudiosourceprovider_impl.h"
Gyuyoung Kimf99f5f32019-09-26 03:45:1571#include "third_party/blink/public/strings/grit/blink_strings.h"
Antonio Gomesf01cfbd2019-07-12 08:53:1172#include "third_party/blink/public/web/modules/media/webmediaplayer_util.h"
Blink Reformata30d4232018-04-07 15:31:0673#include "third_party/blink/public/web/web_document.h"
74#include "third_party/blink/public/web/web_frame.h"
75#include "third_party/blink/public/web/web_local_frame.h"
76#include "third_party/blink/public/web/web_user_gesture_indicator.h"
77#include "third_party/blink/public/web/web_view.h"
[email protected]b3f2b912009-04-09 16:18:5278
dalecurtisea27a3ed2016-06-24 01:41:3079#if defined(OS_ANDROID)
80#include "media/base/android/media_codec_util.h"
81#endif
82
[email protected]180ef242013-11-07 06:50:4683using blink::WebMediaPlayer;
84using blink::WebRect;
85using blink::WebSize;
86using blink::WebString;
hubbed5f36882016-01-15 22:40:3787using gpu::gles2::GLES2Interface;
88
danakj365175c2016-02-06 00:37:3789#define STATIC_ASSERT_ENUM(a, b) \
90 static_assert(static_cast<int>(a) == static_cast<int>(b), \
91 "mismatching enums: " #a)
92
hubbed5f36882016-01-15 22:40:3793namespace media {
[email protected]ec9212f2008-12-18 21:40:3694
[email protected]8931c41a2009-07-07 17:31:4995namespace {
96
Dan Sanders6edfd782019-08-13 00:13:1897const char kWatchTimeHistogram[] = "Media.WebMediaPlayerImpl.WatchTime";
98
Xiaohan Wang48aaa192019-12-05 01:29:0099void RecordSimpleWatchTimeUMA(RendererFactoryType type) {
100 UMA_HISTOGRAM_ENUMERATION(kWatchTimeHistogram, type);
Dan Sanders6edfd782019-08-13 00:13:18101}
102
Antonio Gomes3a858b52019-05-31 02:47:52103void SetSinkIdOnMediaThread(
104 scoped_refptr<blink::WebAudioSourceProviderImpl> sink,
105 const std::string& device_id,
106 OutputDeviceStatusCB callback) {
Daniel Chengc1710b52018-10-24 03:12:28107 sink->SwitchOutputDevice(device_id, std::move(callback));
guidouc7babef2015-10-22 00:42:35108}
109
Sergey Volk8b09c2c52018-12-12 23:20:40110bool IsBackgroundSuspendEnabled(const WebMediaPlayerImpl* wmpi) {
Luke Halliwell7a8a8982018-07-25 01:07:05111 // TODO(crbug.com/867146): remove these switches.
112 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
113 switches::kDisableMediaSuspend))
114 return false;
115 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
116 switches::kEnableMediaSuspend))
117 return true;
118
Sergey Volk8b09c2c52018-12-12 23:20:40119 return wmpi->IsBackgroundMediaSuspendEnabled();
dalecurtis0431cbf2016-03-12 01:19:43120}
121
avayvod48a8be52016-08-04 19:52:50122bool IsResumeBackgroundVideosEnabled() {
123 return base::FeatureList::IsEnabled(kResumeBackgroundVideo);
124}
125
avayvod01201332017-04-14 00:27:15126bool IsBackgroundVideoPauseOptimizationEnabled() {
127 return base::FeatureList::IsEnabled(kBackgroundVideoPauseOptimization);
128}
129
sandersd50a635e2016-04-04 22:50:09130bool IsNetworkStateError(blink::WebMediaPlayer::NetworkState state) {
Blink Reformat1c4d759e2017-04-09 16:34:54131 bool result = state == blink::WebMediaPlayer::kNetworkStateFormatError ||
132 state == blink::WebMediaPlayer::kNetworkStateNetworkError ||
133 state == blink::WebMediaPlayer::kNetworkStateDecodeError;
134 DCHECK_EQ(state > blink::WebMediaPlayer::kNetworkStateLoaded, result);
sandersd50a635e2016-04-04 22:50:09135 return result;
136}
137
sandersd2c478422016-08-02 01:19:25138gfx::Size GetRotatedVideoSize(VideoRotation rotation, gfx::Size natural_size) {
139 if (rotation == VIDEO_ROTATION_90 || rotation == VIDEO_ROTATION_270)
140 return gfx::Size(natural_size.height(), natural_size.width());
141 return natural_size;
142}
143
Xiaohan Wangf63505d2017-10-21 08:00:53144void RecordEncryptedEvent(bool encrypted_event_fired) {
145 UMA_HISTOGRAM_BOOLEAN("Media.EME.EncryptedEvent", encrypted_event_fired);
146}
147
sandersd35d2c3f2017-01-14 02:04:42148// How much time must have elapsed since loading last progressed before we
149// assume that the decoder will have had time to complete preroll.
150constexpr base::TimeDelta kPrerollAttemptTimeout =
watkd026f792016-11-05 00:28:51151 base::TimeDelta::FromSeconds(3);
152
Matt Wolenetz6010f6c2017-10-18 00:44:36153// Maximum number, per-WMPI, of media logs of playback rate changes.
154constexpr int kMaxNumPlaybackRateLogs = 10;
155
Gyuyoung Kimf99f5f32019-09-26 03:45:15156int GetSwitchToLocalMessage(MediaObserverClient::ReasonToSwitchToLocal reason) {
Xiangjun Zhang5e20cba42018-01-10 19:54:56157 switch (reason) {
158 case MediaObserverClient::ReasonToSwitchToLocal::NORMAL:
Gyuyoung Kimf99f5f32019-09-26 03:45:15159 return IDS_MEDIA_REMOTING_STOP_TEXT;
Xiangjun Zhang5e20cba42018-01-10 19:54:56160 case MediaObserverClient::ReasonToSwitchToLocal::POOR_PLAYBACK_QUALITY:
Gyuyoung Kimf99f5f32019-09-26 03:45:15161 return IDS_MEDIA_REMOTING_STOP_BY_PLAYBACK_QUALITY_TEXT;
Xiangjun Zhang5e20cba42018-01-10 19:54:56162 case MediaObserverClient::ReasonToSwitchToLocal::PIPELINE_ERROR:
Gyuyoung Kimf99f5f32019-09-26 03:45:15163 return IDS_MEDIA_REMOTING_STOP_BY_ERROR_TEXT;
Xiangjun Zhang5e20cba42018-01-10 19:54:56164 case MediaObserverClient::ReasonToSwitchToLocal::ROUTE_TERMINATED:
Gyuyoung Kimf99f5f32019-09-26 03:45:15165 return blink::WebMediaPlayerClient::kMediaRemotingStopNoText;
Xiangjun Zhang5e20cba42018-01-10 19:54:56166 }
167 NOTREACHED();
168 // To suppress compiler warning on Windows.
Gyuyoung Kimf99f5f32019-09-26 03:45:15169 return blink::WebMediaPlayerClient::kMediaRemotingStopNoText;
Xiangjun Zhang5e20cba42018-01-10 19:54:56170}
171
John Rummelldb5a7ef2018-05-16 00:28:01172// These values are persisted to UMA. Entries should not be renumbered and
173// numeric values should never be reused.
Yuchen Liub33bfc12019-11-08 20:16:12174// TODO(crbug.com/825041): This should use EncryptionScheme when kUnencrypted
John Rummelldb5a7ef2018-05-16 00:28:01175// removed.
176enum class EncryptionSchemeUMA { kCenc = 0, kCbcs = 1, kCount };
177
178EncryptionSchemeUMA DetermineEncryptionSchemeUMAValue(
Yuchen Liub33bfc12019-11-08 20:16:12179 EncryptionScheme encryption_scheme) {
180 if (encryption_scheme == EncryptionScheme::kCbcs)
John Rummelldb5a7ef2018-05-16 00:28:01181 return EncryptionSchemeUMA::kCbcs;
182
Yuchen Liub33bfc12019-11-08 20:16:12183 DCHECK_EQ(encryption_scheme, EncryptionScheme::kCenc);
John Rummelldb5a7ef2018-05-16 00:28:01184 return EncryptionSchemeUMA::kCenc;
185}
186
Pavel Feldman023c3e62018-08-28 17:59:47187#if BUILDFLAG(ENABLE_FFMPEG)
Dale Curtisb8139f72018-08-27 23:28:48188// Returns true if |url| represents (or is likely to) a local file.
189bool IsLocalFile(const GURL& url) {
190 return url.SchemeIsFile() || url.SchemeIsFileSystem() ||
191 url.SchemeIs(url::kContentScheme) ||
192 url.SchemeIs(url::kContentIDScheme) ||
193 url.SchemeIs("chrome-extension");
194}
Pavel Feldman023c3e62018-08-28 17:59:47195#endif
Dale Curtisb8139f72018-08-27 23:28:48196
Dale Curtisf273f8f2018-12-13 23:40:33197// Handles destruction of media::Renderer dependent components after the
198// renderer has been destructed on the media thread.
199void DestructionHelper(
200 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
201 scoped_refptr<base::SingleThreadTaskRunner> vfc_task_runner,
202 std::unique_ptr<Demuxer> demuxer,
203 std::unique_ptr<DataSource> data_source,
204 std::unique_ptr<VideoFrameCompositor> compositor,
205 std::unique_ptr<CdmContextRef> cdm_context_1,
206 std::unique_ptr<CdmContextRef> cdm_context_2,
207 std::unique_ptr<MediaLog> media_log,
208 std::unique_ptr<RendererFactorySelector> renderer_factory_selector,
209 std::unique_ptr<blink::WebSurfaceLayerBridge> bridge,
210 bool is_chunk_demuxer) {
211 // We release |bridge| after pipeline stop to ensure layout tests receive
212 // painted video frames before test harness exit.
213 main_task_runner->DeleteSoon(FROM_HERE, std::move(bridge));
214
215 // Since the media::Renderer is gone we can now destroy the compositor and
216 // renderer factory selector.
217 vfc_task_runner->DeleteSoon(FROM_HERE, std::move(compositor));
218 main_task_runner->DeleteSoon(FROM_HERE, std::move(renderer_factory_selector));
219
220 // ChunkDemuxer can be deleted on any thread, but other demuxers are bound to
221 // the main thread and must be deleted there now that the renderer is gone.
222 if (!is_chunk_demuxer) {
223 main_task_runner->DeleteSoon(FROM_HERE, std::move(demuxer));
224 main_task_runner->DeleteSoon(FROM_HERE, std::move(data_source));
225 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_1));
226 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_2));
227 main_task_runner->DeleteSoon(FROM_HERE, std::move(media_log));
228 return;
229 }
230
231 // ChunkDemuxer's streams may contain much buffered, compressed media that
232 // may need to be paged back in during destruction. Paging delay may exceed
233 // the renderer hang monitor's threshold on at least Windows while also
234 // blocking other work on the renderer main thread, so we do the actual
235 // destruction in the background without blocking WMPI destruction or
236 // |task_runner|. On advice of task_scheduler OWNERS, MayBlock() is not
237 // used because virtual memory overhead is not considered blocking I/O; and
238 // CONTINUE_ON_SHUTDOWN is used to allow process termination to not block on
239 // completing the task.
Sami Kyostila127d6632019-08-06 21:32:25240 base::PostTask(
Dale Curtisf273f8f2018-12-13 23:40:33241 FROM_HERE,
Sami Kyostila127d6632019-08-06 21:32:25242 {base::ThreadPool(), base::TaskPriority::BEST_EFFORT,
Dale Curtisf273f8f2018-12-13 23:40:33243 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
244 base::BindOnce(
245 [](scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
246 std::unique_ptr<Demuxer> demuxer_to_destroy,
247 std::unique_ptr<CdmContextRef> cdm_context_1,
248 std::unique_ptr<CdmContextRef> cdm_context_2,
249 std::unique_ptr<MediaLog> media_log) {
250 SCOPED_UMA_HISTOGRAM_TIMER("Media.MSE.DemuxerDestructionTime");
251 demuxer_to_destroy.reset();
252 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_1));
253 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_2));
254 main_task_runner->DeleteSoon(FROM_HERE, std::move(media_log));
255 },
256 std::move(main_task_runner), std::move(demuxer),
257 std::move(cdm_context_1), std::move(cdm_context_2),
258 std::move(media_log)));
259}
260
Ted Meyer7f5b4e22019-11-21 03:21:19261std::string SanitizeUserStringProperty(blink::WebString value) {
Ted Meyera698afe2019-11-06 20:58:03262 std::string converted = value.Utf8();
Ted Meyer7f5b4e22019-11-21 03:21:19263 return base::IsStringUTF8(converted) ? converted : "[invalid property]";
Ted Meyera698afe2019-11-06 20:58:03264}
265
[email protected]8931c41a2009-07-07 17:31:49266} // namespace
267
[email protected]6683e1b2014-04-10 01:45:38268class BufferedDataSourceHostImpl;
269
Takashi Toyoshima2e01e692018-11-16 03:23:27270STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeUnspecified,
danakj365175c2016-02-06 00:37:37271 UrlData::CORS_UNSPECIFIED);
Takashi Toyoshima2e01e692018-11-16 03:23:27272STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeAnonymous, UrlData::CORS_ANONYMOUS);
273STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeUseCredentials,
danakj365175c2016-02-06 00:37:37274 UrlData::CORS_USE_CREDENTIALS);
[email protected]a5a01102012-06-06 17:01:24275
[email protected]5b5bb9d2010-10-22 19:57:36276WebMediaPlayerImpl::WebMediaPlayerImpl(
[email protected]35b2a972014-04-04 15:50:22277 blink::WebLocalFrame* frame,
[email protected]180ef242013-11-07 06:50:46278 blink::WebMediaPlayerClient* client,
srirama.m26f864d02015-07-14 05:21:46279 blink::WebMediaPlayerEncryptedMediaClient* encrypted_client,
Antonio Gomes423df612019-07-11 12:40:07280 blink::WebMediaPlayerDelegate* delegate,
tguilbert70d2a00a2017-04-25 00:30:44281 std::unique_ptr<RendererFactorySelector> renderer_factory_selector,
Alok Priyadarshi7166d4d2017-07-29 04:04:25282 UrlIndex* url_index,
CJ DiMegliod7ac6772017-11-10 00:19:06283 std::unique_ptr<VideoFrameCompositor> compositor,
dalecurtis9cddc0b2017-04-19 21:23:38284 std::unique_ptr<WebMediaPlayerParams> params)
[email protected]f6af7592014-02-28 10:09:11285 : frame_(frame),
Alexander Timin310368112017-09-13 10:01:44286 main_task_runner_(
287 frame->GetTaskRunner(blink::TaskType::kMediaElementEvent)),
dalecurtis9cddc0b2017-04-19 21:23:38288 media_task_runner_(params->media_task_runner()),
289 worker_task_runner_(params->worker_task_runner()),
290 media_log_(params->take_media_log()),
[email protected]5badb082010-06-11 17:40:15291 client_(client),
srirama.m26f864d02015-07-14 05:21:46292 encrypted_client_(encrypted_client),
[email protected]baff4512011-10-19 18:21:07293 delegate_(delegate),
dalecurtis9cddc0b2017-04-19 21:23:38294 defer_load_cb_(params->defer_load_cb()),
dalecurtis9cddc0b2017-04-19 21:23:38295 adjust_allocated_memory_cb_(params->adjust_allocated_memory_cb()),
tzik2c963b872017-12-07 06:57:24296 tick_clock_(base::DefaultTickClock::GetInstance()),
hubbe5f0ad43b2015-12-14 20:57:26297 url_index_(url_index),
CJ DiMeglioc60a5cf2017-09-27 20:08:41298 context_provider_(params->context_provider()),
CJ DiMegliod7ac6772017-11-10 00:19:06299 vfc_task_runner_(params->video_frame_compositor_task_runner()),
300 compositor_(std::move(compositor)),
tguilbert70d2a00a2017-04-25 00:30:44301 renderer_factory_selector_(std::move(renderer_factory_selector)),
dalecurtis9cddc0b2017-04-19 21:23:38302 observer_(params->media_observer()),
servolkf94b4602017-01-31 16:44:27303 enable_instant_source_buffer_gc_(
dalecurtis9cddc0b2017-04-19 21:23:38304 params->enable_instant_source_buffer_gc()),
shaktisahu24189c12017-03-11 17:42:55305 embedded_media_experience_enabled_(
liberato2ff93ad2017-05-17 07:28:24306 params->embedded_media_experience_enabled()),
[email protected]69db58f2018-09-26 20:27:56307 surface_layer_mode_(params->use_surface_layer_for_video()),
CJ DiMeglio96c18b692018-07-04 03:39:06308 create_bridge_callback_(params->create_bridge_callback()),
liberato2ff93ad2017-05-17 07:28:24309 request_routing_token_cb_(params->request_routing_token_cb()),
Dale Curtis1adbe6a2017-08-02 02:09:13310 overlay_routing_token_(OverlayInfo::RoutingToken()),
Sergey Volk8b09c2c52018-12-12 23:20:40311 media_metrics_provider_(params->take_metrics_provider()),
312 is_background_suspend_enabled_(params->IsBackgroundSuspendEnabled()),
Junbo Kefba620b2019-01-16 02:54:36313 is_background_video_playback_enabled_(
314 params->IsBackgroundVideoPlaybackEnabled()),
Sergey Volk8b09c2c52018-12-12 23:20:40315 is_background_video_track_optimization_supported_(
Dan Sanders6edfd782019-08-13 00:13:18316 params->IsBackgroundVideoTrackOptimizationSupported()),
Xiaohan Wang48aaa192019-12-05 01:29:00317 reported_renderer_type_(RendererFactoryType::kDefault),
Dan Sanders6edfd782019-08-13 00:13:18318 simple_watch_timer_(
319 base::BindRepeating(&WebMediaPlayerImpl::OnSimpleWatchTimerTick,
320 base::Unretained(this)),
321 base::BindRepeating(&WebMediaPlayerImpl::GetCurrentTimeInternal,
[email protected]91fd3162019-09-05 23:51:32322 base::Unretained(this))),
323 will_play_helper_(nullptr) {
xhwang51139732017-02-24 19:36:08324 DVLOG(1) << __func__;
Dale Curtise25163812018-09-21 22:13:39325 DCHECK(adjust_allocated_memory_cb_);
tguilbert70d2a00a2017-04-25 00:30:44326 DCHECK(renderer_factory_selector_);
servolkef1e5ef2016-03-25 04:55:26327 DCHECK(client_);
tguilbert1bb1c782017-01-23 21:15:11328 DCHECK(delegate_);
dalecurtis83266c72015-10-29 18:43:20329
Antonio Gomes142f32a2019-05-15 23:32:56330 weak_this_ = weak_factory_.GetWeakPtr();
331
Xiaohan Wang2480de72019-11-15 01:44:47332 // Using base::Unretained(this) is safe because the |pipeline| is owned by
333 // |this| and the callback will always be made on the main task runner.
334 // Not using BindToCurrentLoop() because CreateRenderer() is a sync call.
335 auto pipeline = std::make_unique<PipelineImpl>(
336 media_task_runner_, main_task_runner_,
337 base::BindRepeating(&WebMediaPlayerImpl::CreateRenderer,
338 base::Unretained(this)),
339 media_log_.get());
340
Antonio Gomes81b56552019-05-15 22:15:28341 pipeline_controller_ = std::make_unique<PipelineController>(
Xiaohan Wang2480de72019-11-15 01:44:47342 std::move(pipeline),
Antonio Gomes142f32a2019-05-15 23:32:56343 base::BindRepeating(&WebMediaPlayerImpl::OnPipelineSeeked, weak_this_),
344 base::BindRepeating(&WebMediaPlayerImpl::OnPipelineSuspended, weak_this_),
Antonio Gomes81b56552019-05-15 22:15:28345 base::BindRepeating(&WebMediaPlayerImpl::OnBeforePipelineResume,
Antonio Gomes142f32a2019-05-15 23:32:56346 weak_this_),
347 base::BindRepeating(&WebMediaPlayerImpl::OnPipelineResumed, weak_this_),
348 base::BindRepeating(&WebMediaPlayerImpl::OnError, weak_this_));
Antonio Gomes81b56552019-05-15 22:15:28349
350 buffered_data_source_host_ = std::make_unique<BufferedDataSourceHostImpl>(
Antonio Gomes142f32a2019-05-15 23:32:56351 base::BindRepeating(&WebMediaPlayerImpl::OnProgress, weak_this_),
Antonio Gomes81b56552019-05-15 22:15:28352 tick_clock_);
353
[email protected]c8d574722017-08-30 20:53:43354 // If we're supposed to force video overlays, then make sure that they're
355 // enabled all the time.
356 always_enable_overlays_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
tsunghungee562e92016-07-20 18:03:31357 switches::kForceVideoOverlays);
358
Jinsong Fan982342112019-11-07 23:45:45359 if (base::FeatureList::IsEnabled(kOverlayFullscreenVideo))
360 overlay_mode_ = OverlayMode::kUseAndroidOverlay;
361 else
liberato2ff93ad2017-05-17 07:28:24362 overlay_mode_ = OverlayMode::kNoOverlays;
ampea73f792017-01-19 04:05:39363
tguilbert1bb1c782017-01-23 21:15:11364 delegate_id_ = delegate_->AddObserver(this);
365 delegate_->SetIdle(delegate_id_, true);
sandersd1e49fb62015-12-12 01:18:06366
dalecurtis2cff7f372017-05-24 08:30:08367 media_log_->AddEvent(media_log_->CreateCreatedEvent(
368 url::Origin(frame_->GetSecurityOrigin()).GetURL().spec()));
Ted Meyera698afe2019-11-06 20:58:03369
Ted Meyer7f5b4e22019-11-21 03:21:19370 media_log_->SetProperty<MediaLogProperty::kFrameUrl>(
371 SanitizeUserStringProperty(frame_->GetDocument().Url().GetString()));
372 media_log_->SetProperty<MediaLogProperty::kFrameTitle>(
373 SanitizeUserStringProperty(frame_->GetDocument().Title()));
[email protected]52b0b212018-10-10 05:25:28374
dalecurtis9cddc0b2017-04-19 21:23:38375 if (params->initial_cdm())
Chris Cunninghamd4a00192019-03-21 20:02:49376 SetCdmInternal(params->initial_cdm());
xhwang0ad11e512014-11-25 23:43:09377
Xiaohan Wangf63505d2017-10-21 08:00:53378 // Report a false "EncrytpedEvent" here as a baseline.
379 RecordEncryptedEvent(false);
380
xhwangf94a634d2014-10-22 22:07:27381 // TODO(xhwang): When we use an external Renderer, many methods won't work,
xhwang6fa356202014-12-11 00:44:12382 // e.g. GetCurrentFrameFromCompositor(). See http://crbug.com/434861
Antonio Gomes3a858b52019-05-31 02:47:52383 audio_source_provider_ = new blink::WebAudioSourceProviderImpl(
dalecurtis9cddc0b2017-04-19 21:23:38384 params->audio_renderer_sink(), media_log_.get());
xjz4e5d4bf32017-02-15 21:26:35385
386 if (observer_)
387 observer_->SetClient(this);
Hajime Hoshi8bb37dc2017-12-19 09:35:10388
389 memory_usage_reporting_timer_.SetTaskRunner(
Hajime Hoshib5a26ee2018-05-14 12:47:51390 frame_->GetTaskRunner(blink::TaskType::kInternalMedia));
John Delaney6c8ecc1b2018-10-21 19:07:29391
Thomas Guilbert901808982019-07-03 20:38:18392#if defined(OS_ANDROID)
Thomas Guilbertf6d0702e2019-09-12 23:40:14393 renderer_factory_selector_->SetRemotePlayStateChangeCB(
394 BindToCurrentLoop(base::BindRepeating(
395 &WebMediaPlayerImpl::OnRemotePlayStateChange, weak_this_)));
Thomas Guilbert901808982019-07-03 20:38:18396#endif // defined (OS_ANDROID)
[email protected]ec9212f2008-12-18 21:40:36397}
398
[email protected]4e6be3f2009-05-07 02:24:44399WebMediaPlayerImpl::~WebMediaPlayerImpl() {
xhwang51139732017-02-24 19:36:08400 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43401 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53402
xhwang51139732017-02-24 19:36:08403 if (set_cdm_result_) {
Chris Cunninghamd4a00192019-03-21 20:02:49404 DVLOG(2)
405 << "Resolve pending SetCdmInternal() when media player is destroyed.";
Blink Reformat1c4d759e2017-04-09 16:34:54406 set_cdm_result_->Complete();
xhwang51139732017-02-24 19:36:08407 set_cdm_result_.reset();
408 }
409
alokp1116967f2016-06-11 17:30:56410 suppress_destruction_errors_ = true;
tguilbert1bb1c782017-01-23 21:15:11411
412 delegate_->PlayerGone(delegate_id_);
413 delegate_->RemoveObserver(delegate_id_);
[email protected]baff4512011-10-19 18:21:07414
dalecurtis04bdb582016-08-17 22:15:23415 // Finalize any watch time metrics before destroying the pipeline.
416 watch_time_reporter_.reset();
417
tguilbert350936ff2017-02-24 05:39:27418 // The underlying Pipeline must be stopped before it is destroyed.
Dale Curtisf273f8f2018-12-13 23:40:33419 //
420 // Note: This destruction happens synchronously on the media thread and
421 // |demuxer_|, |data_source_|, |compositor_|, and |media_log_| must outlive
422 // this process. They will be destructed by the DestructionHelper below
423 // after trampolining through the media thread.
Antonio Gomes81b56552019-05-15 22:15:28424 pipeline_controller_->Stop();
[email protected]f6af7592014-02-28 10:09:11425
dalecurtis83266c72015-10-29 18:43:20426 if (last_reported_memory_usage_)
427 adjust_allocated_memory_cb_.Run(-last_reported_memory_usage_);
428
dalecurtise1edb312016-06-22 02:33:21429 // Destruct compositor resources in the proper order.
danakj8d204a42018-05-18 18:05:35430 client_->SetCcLayer(nullptr);
CJ DiMeglio2302d202017-08-31 08:38:04431
Xiangjun Zhang5e20cba42018-01-10 19:54:56432 client_->MediaRemotingStopped(
Gyuyoung Kimf99f5f32019-09-26 03:45:15433 blink::WebMediaPlayerClient::kMediaRemotingStopNoText);
Xiangjun Zhang87299142017-09-13 20:35:03434
Dale Curtisf273f8f2018-12-13 23:40:33435 if (!surface_layer_for_video_enabled_ && video_layer_)
danakj25f030112018-05-11 18:26:54436 video_layer_->StopUsingProvider();
Matt Wolenetz95af6362018-01-04 20:23:42437
Dan Sanders6edfd782019-08-13 00:13:18438 simple_watch_timer_.Stop();
Ted Meyer257b682a2019-11-01 20:50:51439 media_log_->OnWebMediaPlayerDestroyed();
[email protected]ec9212f2008-12-18 21:40:36440
Dale Curtisf273f8f2018-12-13 23:40:33441 if (data_source_)
442 data_source_->Stop();
443
444 // Disconnect from the surface layer. We still preserve the |bridge_| until
445 // after pipeline shutdown to ensure any pending frames are painted for tests.
446 if (bridge_)
447 bridge_->ClearObserver();
448
Dale Curtisc96a3542018-12-17 22:15:23449 // Disconnect from the MediaObserver implementation since it's lifetime is
450 // tied to the RendererFactorySelector which can't be destroyed until after
451 // the Pipeline stops.
452 //
453 // Note: We can't use a WeakPtr with the RendererFactory because its methods
454 // are called on the media thread and this destruction takes place on the
455 // renderer thread.
456 if (observer_)
457 observer_->SetClient(nullptr);
458
[email protected]91fd3162019-09-05 23:51:32459 // If we're in the middle of an observation, then finish it.
460 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(false));
461
Dale Curtisf273f8f2018-12-13 23:40:33462 // Handle destruction of things that need to be destructed after the pipeline
463 // completes stopping on the media thread.
464 media_task_runner_->PostTask(
Matt Wolenetz95af6362018-01-04 20:23:42465 FROM_HERE,
Dale Curtisf273f8f2018-12-13 23:40:33466 base::BindOnce(&DestructionHelper, std::move(main_task_runner_),
467 std::move(vfc_task_runner_), std::move(demuxer_),
468 std::move(data_source_), std::move(compositor_),
469 std::move(cdm_context_ref_),
470 std::move(pending_cdm_context_ref_), std::move(media_log_),
471 std::move(renderer_factory_selector_), std::move(bridge_),
472 !!chunk_demuxer_));
Matt Wolenetz95af6362018-01-04 20:23:42473}
474
chcunningham707b821e2018-05-29 08:42:19475WebMediaPlayer::LoadTiming WebMediaPlayerImpl::Load(
476 LoadType load_type,
477 const blink::WebMediaPlayerSource& source,
Takashi Toyoshima2e01e692018-11-16 03:23:27478 CorsMode cors_mode) {
guidou9bfe4e2f2016-04-09 08:31:19479 // Only URL or MSE blob URL is supported.
Blink Reformat1c4d759e2017-04-09 16:34:54480 DCHECK(source.IsURL());
481 blink::WebURL url = source.GetAsURL();
Xiaohan Wang81fd0022017-07-11 17:45:24482 DVLOG(1) << __func__ << "(" << load_type << ", " << GURL(url) << ", "
483 << cors_mode << ")";
chcunningham707b821e2018-05-29 08:42:19484
485 bool is_deferred = false;
486
Dale Curtise25163812018-09-21 22:13:39487 if (defer_load_cb_) {
chcunningham707b821e2018-05-29 08:42:19488 is_deferred = defer_load_cb_.Run(base::BindOnce(
Antonio Gomes142f32a2019-05-15 23:32:56489 &WebMediaPlayerImpl::DoLoad, weak_this_, load_type, url, cors_mode));
chcunningham707b821e2018-05-29 08:42:19490 } else {
491 DoLoad(load_type, url, cors_mode);
[email protected]d726eddc2013-07-02 22:25:55492 }
chcunningham707b821e2018-05-29 08:42:19493
494 return is_deferred ? LoadTiming::kDeferred : LoadTiming::kImmediate;
[email protected]62e5e682013-03-07 23:53:24495}
496
CJ DiMeglio013d4c472017-11-21 03:27:30497void WebMediaPlayerImpl::OnWebLayerUpdated() {}
498
danakj6a062b112018-05-17 16:25:45499void WebMediaPlayerImpl::RegisterContentsLayer(cc::Layer* layer) {
CJ DiMeglio2302d202017-08-31 08:38:04500 DCHECK(bridge_);
CJ DiMeglioa2b13fbc2018-06-27 00:50:59501 bridge_->SetContentsOpaque(opaque_);
danakj8d204a42018-05-18 18:05:35502 client_->SetCcLayer(layer);
CJ DiMeglio013d4c472017-11-21 03:27:30503}
504
danakj6a062b112018-05-17 16:25:45505void WebMediaPlayerImpl::UnregisterContentsLayer(cc::Layer* layer) {
506 // |client_| will unregister its cc::Layer if given a nullptr.
danakj8d204a42018-05-18 18:05:35507 client_->SetCcLayer(nullptr);
CJ DiMeglio2302d202017-08-31 08:38:04508}
509
Jennifer Apaciblec45fd052018-02-25 12:04:55510void WebMediaPlayerImpl::OnSurfaceIdUpdated(viz::SurfaceId surface_id) {
Jennifer Apaciblec45fd052018-02-25 12:04:55511 // TODO(726619): Handle the behavior when Picture-in-Picture mode is
512 // disabled.
Jennifer Apacible2b1dc5eb2018-04-27 16:23:28513 // The viz::SurfaceId may be updated when the video begins playback or when
514 // the size of the video changes.
Mounir Lamouri99ba5a62019-02-12 01:27:47515 if (client_)
516 client_->OnPictureInPictureStateChange();
Jennifer Apaciblec45fd052018-02-25 12:04:55517}
518
tsunghungee562e92016-07-20 18:03:31519void WebMediaPlayerImpl::EnableOverlay() {
520 overlay_enabled_ = true;
[email protected]f7df5b342018-07-13 20:22:13521 if (request_routing_token_cb_ &&
522 overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberatofe8f9692017-06-08 19:17:36523 overlay_routing_token_is_pending_ = true;
liberato2ff93ad2017-05-17 07:28:24524 token_available_cb_.Reset(
Antonio Gomes142f32a2019-05-15 23:32:56525 base::Bind(&WebMediaPlayerImpl::OnOverlayRoutingToken, weak_this_));
liberato2ff93ad2017-05-17 07:28:24526 request_routing_token_cb_.Run(token_available_cb_.callback());
watkf835a792016-06-24 23:24:40527 }
tsunghungee562e92016-07-20 18:03:31528
liberato2ff93ad2017-05-17 07:28:24529 // We have requested (and maybe already have) overlay information. If the
530 // restarted decoder requests overlay information, then we'll defer providing
531 // it if it hasn't arrived yet. Otherwise, this would be a race, since we
532 // don't know if the request for overlay info or restart will complete first.
tsunghungee562e92016-07-20 18:03:31533 if (decoder_requires_restart_for_overlay_)
watkdee516f2016-02-18 02:22:19534 ScheduleRestart();
535}
536
tsunghungee562e92016-07-20 18:03:31537void WebMediaPlayerImpl::DisableOverlay() {
538 overlay_enabled_ = false;
Jinsong Fan982342112019-11-07 23:45:45539 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberato2ff93ad2017-05-17 07:28:24540 token_available_cb_.Cancel();
liberatofe8f9692017-06-08 19:17:36541 overlay_routing_token_is_pending_ = false;
542 overlay_routing_token_ = OverlayInfo::RoutingToken();
liberato2ff93ad2017-05-17 07:28:24543 }
tsunghungee562e92016-07-20 18:03:31544
545 if (decoder_requires_restart_for_overlay_)
watkdee516f2016-02-18 02:22:19546 ScheduleRestart();
liberato2ff93ad2017-05-17 07:28:24547 else
548 MaybeSendOverlayInfoToDecoder();
watkdee516f2016-02-18 02:22:19549}
550
Blink Reformat1c4d759e2017-04-09 16:34:54551void WebMediaPlayerImpl::EnteredFullscreen() {
liberatofe8f9692017-06-08 19:17:36552 overlay_info_.is_fullscreen = true;
553
[email protected]c8d574722017-08-30 20:53:43554 // |always_enable_overlays_| implies that we're already in overlay mode, so
555 // take no action here. Otherwise, switch to an overlay if it's allowed and
556 // if it will display properly.
557 if (!always_enable_overlays_ && overlay_mode_ != OverlayMode::kNoOverlays &&
liberato2fd111be2017-01-04 00:25:06558 DoesOverlaySupportMetadata()) {
tsunghungee562e92016-07-20 18:03:31559 EnableOverlay();
liberato2fd111be2017-01-04 00:25:06560 }
liberato2ff93ad2017-05-17 07:28:24561
liberatofe8f9692017-06-08 19:17:36562 // We send this only if we can send multiple calls. Otherwise, either (a)
563 // we already sent it and we don't have a callback anyway (we reset it when
564 // it's called in restart mode), or (b) we'll send this later when the surface
565 // actually arrives. GVD assumes that the first overlay info will have the
566 // routing information. Note that we set |is_fullscreen_| earlier, so that
567 // if EnableOverlay() can include fullscreen info in case it sends the overlay
568 // info before returning.
569 if (!decoder_requires_restart_for_overlay_)
570 MaybeSendOverlayInfoToDecoder();
tsunghungee562e92016-07-20 18:03:31571}
572
Blink Reformat1c4d759e2017-04-09 16:34:54573void WebMediaPlayerImpl::ExitedFullscreen() {
liberatofe8f9692017-06-08 19:17:36574 overlay_info_.is_fullscreen = false;
575
[email protected]c8d574722017-08-30 20:53:43576 // If we're in overlay mode, then exit it unless we're supposed to allow
577 // overlays all the time.
578 if (!always_enable_overlays_ && overlay_enabled_)
tsunghungee562e92016-07-20 18:03:31579 DisableOverlay();
liberato2ff93ad2017-05-17 07:28:24580
liberatofe8f9692017-06-08 19:17:36581 // See EnteredFullscreen for why we do this.
582 if (!decoder_requires_restart_for_overlay_)
583 MaybeSendOverlayInfoToDecoder();
tsunghungee562e92016-07-20 18:03:31584}
585
Chisoon Jeong81080c922019-09-03 23:40:18586void WebMediaPlayerImpl::BecameDominantVisibleContent(bool is_dominant) {
xjzcdbbe732016-12-03 20:47:42587 if (observer_)
Chisoon Jeong81080c922019-09-03 23:40:18588 observer_->OnBecameDominantVisibleContent(is_dominant);
xjzcdbbe732016-12-03 20:47:42589}
590
Blink Reformat1c4d759e2017-04-09 16:34:54591void WebMediaPlayerImpl::SetIsEffectivelyFullscreen(
François Beaufortad6c5232018-02-26 11:00:44592 blink::WebFullscreenVideoStatus fullscreen_video_status) {
593 delegate_->SetIsEffectivelyFullscreen(delegate_id_, fullscreen_video_status);
zqzhangabc08242017-03-02 16:07:14594}
595
Mounir Lamouri41a79c62017-06-06 12:53:16596void WebMediaPlayerImpl::OnHasNativeControlsChanged(bool has_native_controls) {
597 if (!watch_time_reporter_)
598 return;
599
600 if (has_native_controls)
601 watch_time_reporter_->OnNativeControlsEnabled();
602 else
603 watch_time_reporter_->OnNativeControlsDisabled();
604}
605
Mounir Lamourif9af74e72017-06-19 19:31:45606void WebMediaPlayerImpl::OnDisplayTypeChanged(
607 WebMediaPlayer::DisplayType display_type) {
Mounir Lamouri0484f40a2018-07-25 03:03:26608 if (surface_layer_for_video_enabled_) {
609 vfc_task_runner_->PostTask(
610 FROM_HERE,
611 base::BindOnce(
612 &VideoFrameCompositor::SetForceSubmit,
613 base::Unretained(compositor_.get()),
614 display_type == WebMediaPlayer::DisplayType::kPictureInPicture));
615 }
616
Mounir Lamourif9af74e72017-06-19 19:31:45617 if (!watch_time_reporter_)
618 return;
619
620 switch (display_type) {
621 case WebMediaPlayer::DisplayType::kInline:
622 watch_time_reporter_->OnDisplayTypeInline();
623 break;
624 case WebMediaPlayer::DisplayType::kFullscreen:
625 watch_time_reporter_->OnDisplayTypeFullscreen();
626 break;
627 case WebMediaPlayer::DisplayType::kPictureInPicture:
628 watch_time_reporter_->OnDisplayTypePictureInPicture();
François Beaufort3f62f382019-01-18 15:05:17629
630 // Resumes playback if it was paused when hidden.
631 if (paused_when_hidden_) {
632 paused_when_hidden_ = false;
633 OnPlay();
634 }
Mounir Lamourif9af74e72017-06-19 19:31:45635 break;
636 }
637}
638
[email protected]ef8394c2013-08-21 20:26:30639void WebMediaPlayerImpl::DoLoad(LoadType load_type,
[email protected]180ef242013-11-07 06:50:46640 const blink::WebURL& url,
Takashi Toyoshima2e01e692018-11-16 03:23:27641 CorsMode cors_mode) {
John Chen5b164a02017-11-01 00:36:09642 TRACE_EVENT1("media", "WebMediaPlayerImpl::DoLoad", "id", media_log_->id());
pkastingf5279482016-07-27 02:18:20643 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43644 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d726eddc2013-07-02 22:25:55645
[email protected]91fd3162019-09-05 23:51:32646 // Start a new observation. If there was one before, then we didn't play it.
647 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(false));
648 // For now, send in an empty set of features. We should fill some in here,
649 // and / or ask blink (via |client_|) for features from the DOM.
650 learning::FeatureDictionary dict;
651 will_play_helper_.BeginObservation(dict);
652
Thomas Guilbert55b48d92019-03-25 23:16:54653#if defined(OS_ANDROID)
654 // Only allow credentials if the crossorigin attribute is unspecified
655 // (kCorsModeUnspecified) or "use-credentials" (kCorsModeUseCredentials).
656 // This value is only used by the MediaPlayerRenderer.
657 // See https://crbug.com/936566.
658 //
659 // The credentials mode also has repercussions in WouldTaintOrigin(), but we
660 // access what we need from |mb_data_source_|->cors_mode() directly, instead
661 // of storing it here.
662 allow_media_player_renderer_credentials_ = cors_mode != kCorsModeAnonymous;
663#endif // defined(OS_ANDROID)
664
Dale Curtis4841c712018-12-13 18:14:05665 // Note: |url| may be very large, take care when making copies.
666 loaded_url_ = GURL(url);
667 load_type_ = load_type;
668
669 ReportMetrics(load_type, loaded_url_, *frame_, media_log_.get());
[email protected]62e5e682013-03-07 23:53:24670
Dale Curtis4841c712018-12-13 18:14:05671 // Set subresource URL for crash reporting; will be truncated to 256 bytes.
Robert Sesekc5e91df2017-12-12 21:11:03672 static base::debug::CrashKeyString* subresource_url =
673 base::debug::AllocateCrashKeyString("subresource_url",
674 base::debug::CrashKeySize::Size256);
Dale Curtis4841c712018-12-13 18:14:05675 base::debug::SetCrashKeyString(subresource_url, loaded_url_.spec());
[email protected]ef8394c2013-08-21 20:26:30676
Blink Reformat1c4d759e2017-04-09 16:34:54677 SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
678 SetReadyState(WebMediaPlayer::kReadyStateHaveNothing);
679 media_log_->AddEvent(media_log_->CreateLoadEvent(url.GetString().Utf8()));
Dale Curtis3899090ea2018-01-12 00:10:35680 load_start_time_ = base::TimeTicks::Now();
[email protected]d726eddc2013-07-02 22:25:55681
Antonio Gomesf01cfbd2019-07-12 08:53:11682 media_metrics_provider_->Initialize(
683 load_type == kLoadTypeMediaSource,
684 load_type == kLoadTypeURL ? blink::GetMediaURLScheme(loaded_url_)
685 : mojom::MediaURLScheme::kUnknown);
Dale Curtis74612b72017-12-14 20:56:19686
[email protected]d726eddc2013-07-02 22:25:55687 // Media source pipelines can start immediately.
Blink Reformat1c4d759e2017-04-09 16:34:54688 if (load_type == kLoadTypeMediaSource) {
[email protected]ef8394c2013-08-21 20:26:30689 StartPipeline();
hubbe5f0ad43b2015-12-14 20:57:26690 } else {
Dale Curtis4841c712018-12-13 18:14:05691 // Short circuit the more complex loading path for data:// URLs. Sending
692 // them through the network based loading path just wastes memory and causes
693 // worse performance since reads become asynchronous.
694 if (loaded_url_.SchemeIs(url::kDataScheme)) {
695 std::string mime_type, charset, data;
Dale Curtis44eacb72019-06-10 20:41:28696 if (!net::DataURL::Parse(loaded_url_, &mime_type, &charset, &data) ||
697 data.empty()) {
Dale Curtis4841c712018-12-13 18:14:05698 DataSourceInitialized(false);
699 return;
700 }
701
702 // Replace |loaded_url_| with an empty data:// URL since it may be large.
703 loaded_url_ = GURL("data:,");
704
705 // Mark all the data as buffered.
Antonio Gomes81b56552019-05-15 22:15:28706 buffered_data_source_host_->SetTotalBytes(data.size());
707 buffered_data_source_host_->AddBufferedByteRange(0, data.size());
Dale Curtis4841c712018-12-13 18:14:05708
709 DCHECK(!mb_data_source_);
710 data_source_.reset(new MemoryDataSource(std::move(data)));
711 DataSourceInitialized(true);
712 return;
713 }
714
John Delaneyb933391602018-10-17 21:50:47715 auto url_data =
Takashi Toyoshima2e01e692018-11-16 03:23:27716 url_index_->GetByUrl(url, static_cast<UrlData::CorsMode>(cors_mode));
Dale Curtis4841c712018-12-13 18:14:05717 mb_data_source_ = new MultibufferDataSource(
John Delaneyb933391602018-10-17 21:50:47718 main_task_runner_, std::move(url_data), media_log_.get(),
Antonio Gomes81b56552019-05-15 22:15:28719 buffered_data_source_host_.get(),
Dale Curtis4841c712018-12-13 18:14:05720 base::BindRepeating(&WebMediaPlayerImpl::NotifyDownloading,
Antonio Gomes142f32a2019-05-15 23:32:56721 weak_this_));
Dale Curtis4841c712018-12-13 18:14:05722 data_source_.reset(mb_data_source_);
723 mb_data_source_->SetPreload(preload_);
724 mb_data_source_->SetIsClientAudioElement(client_->IsAudioElement());
725 mb_data_source_->Initialize(
Antonio Gomes142f32a2019-05-15 23:32:56726 base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, weak_this_));
hubbe5f0ad43b2015-12-14 20:57:26727 }
[email protected]62e5e682013-03-07 23:53:24728}
729
Blink Reformat1c4d759e2017-04-09 16:34:54730void WebMediaPlayerImpl::Play() {
pkastingf5279482016-07-27 02:18:20731 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43732 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53733
avayvod65fad272017-02-24 01:00:48734 // User initiated play unlocks background video playback.
Mustaq Ahmede473e4352017-11-04 01:04:25735 if (blink::WebUserGestureIndicator::IsProcessingUserGesture(frame_))
avayvod65fad272017-02-24 01:00:48736 video_locked_when_paused_when_hidden_ = false;
737
sandersd35d2c3f2017-01-14 02:04:42738 // TODO(sandersd): Do we want to reset the idle timer here?
tguilbert1bb1c782017-01-23 21:15:11739 delegate_->SetIdle(delegate_id_, false);
[email protected]49480902009-07-14 20:23:43740 paused_ = false;
Antonio Gomes81b56552019-05-15 22:15:28741 pipeline_controller_->SetPlaybackRate(playback_rate_);
dalecurtis4619cd02016-09-22 21:39:10742 background_pause_timer_.Stop();
sandersd1c0bba02016-03-04 23:14:08743
xjz48a9cb72016-12-20 04:02:49744 if (observer_)
745 observer_->OnPlaying();
746
Mounir Lamouri89c0a1b2018-03-01 15:00:44747 watch_time_reporter_->SetAutoplayInitiated(client_->WasAutoplayInitiated());
748
Dale Curtis051fdf62017-08-05 00:21:13749 // If we're seeking we'll trigger the watch time reporter upon seek completed;
750 // we don't want to start it here since the seek time is unstable. E.g., when
751 // playing content with a positive start time we would have a zero seek time.
752 if (!Seeking()) {
753 DCHECK(watch_time_reporter_);
754 watch_time_reporter_->OnPlaying();
755 }
756
Chris Cunninghamd9df58e2017-08-29 00:04:23757 if (video_decode_stats_reporter_)
758 video_decode_stats_reporter_->OnPlaying();
759
Dan Sanders6edfd782019-08-13 00:13:18760 simple_watch_timer_.Start();
Ted Meyerd5885f82019-07-16 19:19:17761 media_metrics_provider_->SetHasPlayed();
acolwell9e0840d2014-09-06 19:01:32762 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PLAY));
Dale Curtis18ad391b2019-05-30 23:25:09763
764 MaybeUpdateBufferSizesForPlayback();
sandersd50a635e2016-04-04 22:50:09765 UpdatePlayState();
[email protected]91fd3162019-09-05 23:51:32766
767 // Notify the learning task, if needed.
768 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(true));
[email protected]ec9212f2008-12-18 21:40:36769}
770
Blink Reformat1c4d759e2017-04-09 16:34:54771void WebMediaPlayerImpl::Pause() {
pkastingf5279482016-07-27 02:18:20772 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43773 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53774
sandersd50a635e2016-04-04 22:50:09775 // We update the paused state even when casting, since we expect pause() to be
776 // called when casting begins, and when we exit casting we should end up in a
777 // paused state.
[email protected]49480902009-07-14 20:23:43778 paused_ = true;
hubbed5f36882016-01-15 22:40:37779
avayvodeb9098d2017-01-07 00:33:03780 // No longer paused because it was hidden.
781 paused_when_hidden_ = false;
782
avayvod65fad272017-02-24 01:00:48783 // User initiated pause locks background videos.
Mustaq Ahmede473e4352017-11-04 01:04:25784 if (blink::WebUserGestureIndicator::IsProcessingUserGesture(frame_))
avayvod65fad272017-02-24 01:00:48785 video_locked_when_paused_when_hidden_ = true;
786
Antonio Gomes81b56552019-05-15 22:15:28787 pipeline_controller_->SetPlaybackRate(0.0);
Dale Curtis2fc01cc2019-05-20 22:53:52788
789 // For states <= kReadyStateHaveMetadata, we may not have a renderer yet.
790 if (highest_ready_state_ > WebMediaPlayer::kReadyStateHaveMetadata)
791 paused_time_ = pipeline_controller_->GetMediaTime();
[email protected]090f7312011-08-05 23:26:40792
xjz48a9cb72016-12-20 04:02:49793 if (observer_)
794 observer_->OnPaused();
795
dalecurtis04bdb582016-08-17 22:15:23796 DCHECK(watch_time_reporter_);
797 watch_time_reporter_->OnPaused();
Chris Cunninghamd9df58e2017-08-29 00:04:23798
799 if (video_decode_stats_reporter_)
800 video_decode_stats_reporter_->OnPaused();
801
Dan Sanders6edfd782019-08-13 00:13:18802 simple_watch_timer_.Stop();
acolwell9e0840d2014-09-06 19:01:32803 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PAUSE));
avayvod2135a642017-01-13 00:17:14804
Becca Hughes7a85bf22019-07-24 16:16:58805 // Paused changed so we should update media position state.
806 UpdateMediaPositionState();
807
sandersd50a635e2016-04-04 22:50:09808 UpdatePlayState();
[email protected]ec9212f2008-12-18 21:40:36809}
810
Blink Reformat1c4d759e2017-04-09 16:34:54811void WebMediaPlayerImpl::Seek(double seconds) {
pkastingf5279482016-07-27 02:18:20812 DVLOG(1) << __func__ << "(" << seconds << "s)";
acolwellb4034942014-08-28 15:42:43813 DCHECK(main_task_runner_->BelongsToCurrentThread());
Mounir Lamourid864f752019-02-08 22:22:41814 media_log_->AddEvent(
815 media_log_->CreateTimeEvent(MediaLogEvent::SEEK, "seek_target", seconds));
sandersd1c0bba02016-03-04 23:14:08816 DoSeek(base::TimeDelta::FromSecondsD(seconds), true);
817}
818
819void WebMediaPlayerImpl::DoSeek(base::TimeDelta time, bool time_updated) {
820 DCHECK(main_task_runner_->BelongsToCurrentThread());
John Chen5b164a02017-11-01 00:36:09821 TRACE_EVENT2("media", "WebMediaPlayerImpl::DoSeek", "target",
822 time.InSecondsF(), "id", media_log_->id());
[email protected]d43ed912009-02-03 04:52:53823
srirama.mccf671812015-01-08 11:59:13824 ReadyState old_state = ready_state_;
Blink Reformat1c4d759e2017-04-09 16:34:54825 if (ready_state_ > WebMediaPlayer::kReadyStateHaveMetadata)
826 SetReadyState(WebMediaPlayer::kReadyStateHaveMetadata);
[email protected]1bb666802013-11-28 06:12:08827
Dale Curtis051fdf62017-08-05 00:21:13828 // When paused or ended, we know exactly what the current time is and can
829 // elide seeks to it. However, there are two cases that are not elided:
sandersd1c0bba02016-03-04 23:14:08830 // 1) When the pipeline state is not stable.
831 // In this case we just let |pipeline_controller_| decide what to do, as
832 // it has complete information.
833 // 2) For MSE.
834 // Because the buffers may have changed between seeks, MSE seeks are
835 // never elided.
Antonio Gomes81b56552019-05-15 22:15:28836 if (paused_ && pipeline_controller_->IsStable() &&
Dale Curtis051fdf62017-08-05 00:21:13837 (paused_time_ == time ||
838 (ended_ && time == base::TimeDelta::FromSecondsD(Duration()))) &&
sandersd1c0bba02016-03-04 23:14:08839 !chunk_demuxer_) {
840 // If the ready state was high enough before, we can indicate that the seek
841 // completed just by restoring it. Otherwise we will just wait for the real
842 // ready state change to eventually happen.
Blink Reformat1c4d759e2017-04-09 16:34:54843 if (old_state == kReadyStateHaveEnoughData) {
srirama.m8f4a37562014-12-13 08:16:18844 main_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:51845 FROM_HERE, base::BindOnce(&WebMediaPlayerImpl::OnBufferingStateChange,
Chris Cunninghamfc0d67e2019-07-22 20:29:16846 weak_this_, BUFFERING_HAVE_ENOUGH,
847 BUFFERING_CHANGE_REASON_UNKNOWN));
srirama.m36ab2682014-12-11 04:20:01848 }
sandersd1c0bba02016-03-04 23:14:08849 return;
srirama.m36ab2682014-12-11 04:20:01850 }
[email protected]44ff37c02009-10-24 01:03:03851
dalecurtis04bdb582016-08-17 22:15:23852 // Call this before setting |seeking_| so that the current media time can be
853 // recorded by the reporter.
854 if (watch_time_reporter_)
855 watch_time_reporter_->OnSeeking();
856
sandersd35d2c3f2017-01-14 02:04:42857 // TODO(sandersd): Move |seeking_| to PipelineController.
858 // TODO(sandersd): Do we want to reset the idle timer here?
tguilbert1bb1c782017-01-23 21:15:11859 delegate_->SetIdle(delegate_id_, false);
sandersd50a635e2016-04-04 22:50:09860 ended_ = false;
[email protected]b3766a22010-12-22 17:34:13861 seeking_ = true;
sandersd1c0bba02016-03-04 23:14:08862 seek_time_ = time;
863 if (paused_)
864 paused_time_ = time;
Antonio Gomes81b56552019-05-15 22:15:28865 pipeline_controller_->Seek(time, time_updated);
[email protected]b3766a22010-12-22 17:34:13866
sandersd50a635e2016-04-04 22:50:09867 // This needs to be called after Seek() so that if a resume is triggered, it
868 // is to the correct time.
869 UpdatePlayState();
Becca Hughes7a85bf22019-07-24 16:16:58870
871 // The seek time has changed so we should update the media position state.
872 UpdateMediaPositionState();
[email protected]ec9212f2008-12-18 21:40:36873}
874
Blink Reformat1c4d759e2017-04-09 16:34:54875void WebMediaPlayerImpl::SetRate(double rate) {
pkastingf5279482016-07-27 02:18:20876 DVLOG(1) << __func__ << "(" << rate << ")";
acolwellb4034942014-08-28 15:42:43877 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53878
Matt Wolenetz6010f6c2017-10-18 00:44:36879 if (rate != playback_rate_) {
880 LIMITED_MEDIA_LOG(INFO, media_log_.get(), num_playback_rate_logs_,
881 kMaxNumPlaybackRateLogs)
882 << "Effective playback rate changed from " << playback_rate_ << " to "
883 << rate;
884 }
885
[email protected]49480902009-07-14 20:23:43886 playback_rate_ = rate;
Dale Curtis18ad391b2019-05-30 23:25:09887 if (!paused_)
Antonio Gomes81b56552019-05-15 22:15:28888 pipeline_controller_->SetPlaybackRate(rate);
Dale Curtis18ad391b2019-05-30 23:25:09889
890 MaybeUpdateBufferSizesForPlayback();
[email protected]ec9212f2008-12-18 21:40:36891}
892
Blink Reformat1c4d759e2017-04-09 16:34:54893void WebMediaPlayerImpl::SetVolume(double volume) {
pkastingf5279482016-07-27 02:18:20894 DVLOG(1) << __func__ << "(" << volume << ")";
acolwellb4034942014-08-28 15:42:43895 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtisbb3eaac2016-01-27 21:10:25896 volume_ = volume;
Antonio Gomes81b56552019-05-15 22:15:28897 pipeline_controller_->SetVolume(volume_ * volume_multiplier_);
dalecurtis04bdb582016-08-17 22:15:23898 if (watch_time_reporter_)
899 watch_time_reporter_->OnVolumeChange(volume);
Becca Hughes9f6fd4b82017-06-15 10:01:40900 delegate_->DidPlayerMutedStatusChange(delegate_id_, volume == 0.0);
mlamouri910111362016-11-04 11:28:24901
902 // The play state is updated because the player might have left the autoplay
903 // muted state.
904 UpdatePlayState();
[email protected]ec9212f2008-12-18 21:40:36905}
[email protected]f0a51fb52009-03-05 12:46:38906
Chris Cunningham8c2ef912019-11-15 23:10:41907void WebMediaPlayerImpl::SetLatencyHint(double seconds) {
908 DVLOG(1) << __func__ << "(" << seconds << ")";
Chris Cunninghame8c626332019-11-20 23:34:27909 DCHECK(main_task_runner_->BelongsToCurrentThread());
910 base::Optional<base::TimeDelta> latency_hint;
911 if (std::isfinite(seconds)) {
912 DCHECK_GE(seconds, 0);
913 latency_hint = base::TimeDelta::FromSecondsD(seconds);
914 }
915 pipeline_controller_->SetLatencyHint(latency_hint);
Chris Cunningham8c2ef912019-11-15 23:10:41916}
917
Mounir Lamouri967f8fb72019-02-13 02:34:22918void WebMediaPlayerImpl::OnRequestPictureInPicture() {
[email protected]69db58f2018-09-26 20:27:56919 if (!surface_layer_for_video_enabled_)
920 ActivateSurfaceLayerForVideo();
921
Mounir Lamourib642a3c2018-07-09 15:45:31922 DCHECK(bridge_);
Mounir Lamouri99ba5a62019-02-12 01:27:47923 DCHECK(bridge_->GetSurfaceId().is_valid());
Jennifer Apacible3f0489102018-01-19 20:10:31924}
925
Daniel Chengc1710b52018-10-24 03:12:28926void WebMediaPlayerImpl::SetSinkId(
927 const blink::WebString& sink_id,
Antonio Gomese7813f32019-04-02 06:11:03928 blink::WebSetSinkIdCompleteCallback completion_callback) {
guidou69223ce2015-06-16 10:36:19929 DCHECK(main_task_runner_->BelongsToCurrentThread());
pkastingf5279482016-07-27 02:18:20930 DVLOG(1) << __func__;
guidouc7babef2015-10-22 00:42:35931
Dale Curtisca1b78f2019-01-15 03:11:26932 OutputDeviceStatusCB callback =
Antonio Gomese7813f32019-04-02 06:11:03933 ConvertToOutputDeviceStatusCB(std::move(completion_callback));
guidouc7babef2015-10-22 00:42:35934 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:51935 FROM_HERE, base::BindOnce(&SetSinkIdOnMediaThread, audio_source_provider_,
Daniel Chengc1710b52018-10-24 03:12:28936 sink_id.Utf8(), std::move(callback)));
guidou69223ce2015-06-16 10:36:19937}
938
Blink Reformat1c4d759e2017-04-09 16:34:54939STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadNone, MultibufferDataSource::NONE);
940STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadMetaData,
dalecurtisb6e052f52016-08-25 00:35:55941 MultibufferDataSource::METADATA);
Blink Reformat1c4d759e2017-04-09 16:34:54942STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadAuto, MultibufferDataSource::AUTO);
[email protected]23a8b1d82011-04-05 16:28:20943
Blink Reformat1c4d759e2017-04-09 16:34:54944void WebMediaPlayerImpl::SetPreload(WebMediaPlayer::Preload preload) {
pkastingf5279482016-07-27 02:18:20945 DVLOG(1) << __func__ << "(" << preload << ")";
acolwellb4034942014-08-28 15:42:43946 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]4e6be3f2009-05-07 02:24:44947
dalecurtisb6e052f52016-08-25 00:35:55948 preload_ = static_cast<MultibufferDataSource::Preload>(preload);
Dale Curtis4841c712018-12-13 18:14:05949 if (mb_data_source_)
950 mb_data_source_->SetPreload(preload_);
[email protected]4e6be3f2009-05-07 02:24:44951}
952
Blink Reformat1c4d759e2017-04-09 16:34:54953bool WebMediaPlayerImpl::HasVideo() const {
acolwellb4034942014-08-28 15:42:43954 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53955
[email protected]b8877772014-03-26 20:17:15956 return pipeline_metadata_.has_video;
[email protected]d43ed912009-02-03 04:52:53957}
958
Blink Reformat1c4d759e2017-04-09 16:34:54959bool WebMediaPlayerImpl::HasAudio() const {
acolwellb4034942014-08-28 15:42:43960 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]fc367af2009-08-14 23:06:35961
[email protected]b8877772014-03-26 20:17:15962 return pipeline_metadata_.has_audio;
[email protected]fc367af2009-08-14 23:06:35963}
964
Blink Reformat1c4d759e2017-04-09 16:34:54965void WebMediaPlayerImpl::EnabledAudioTracksChanged(
servolkf25ceed2016-07-01 03:44:38966 const blink::WebVector<blink::WebMediaPlayer::TrackId>& enabledTrackIds) {
967 DCHECK(main_task_runner_->BelongsToCurrentThread());
968
969 std::ostringstream logstr;
970 std::vector<MediaTrack::Id> enabledMediaTrackIds;
971 for (const auto& blinkTrackId : enabledTrackIds) {
Maciej Pawlowskif2556d122019-06-03 08:14:18972 const auto track_id = MediaTrack::Id(blinkTrackId.Utf8().data());
servolkf25ceed2016-07-01 03:44:38973 logstr << track_id << " ";
974 enabledMediaTrackIds.push_back(track_id);
975 }
dalecurtis9cddc0b2017-04-19 21:23:38976 MEDIA_LOG(INFO, media_log_.get())
977 << "Enabled audio tracks: [" << logstr.str() << "]";
Antonio Gomes81b56552019-05-15 22:15:28978 pipeline_controller_->OnEnabledAudioTracksChanged(enabledMediaTrackIds);
servolkf25ceed2016-07-01 03:44:38979}
980
Blink Reformat1c4d759e2017-04-09 16:34:54981void WebMediaPlayerImpl::SelectedVideoTrackChanged(
servolkf25ceed2016-07-01 03:44:38982 blink::WebMediaPlayer::TrackId* selectedTrackId) {
983 DCHECK(main_task_runner_->BelongsToCurrentThread());
984
servolk9bed6602017-02-24 01:20:11985 base::Optional<MediaTrack::Id> selected_video_track_id;
986 if (selectedTrackId && !video_track_disabled_)
Blink Reformat1c4d759e2017-04-09 16:34:54987 selected_video_track_id = MediaTrack::Id(selectedTrackId->Utf8().data());
dalecurtis9cddc0b2017-04-19 21:23:38988 MEDIA_LOG(INFO, media_log_.get())
Maciej Pawlowskif2556d122019-06-03 08:14:18989 << "Selected video track: ["
990 << selected_video_track_id.value_or(MediaTrack::Id()) << "]";
Antonio Gomes81b56552019-05-15 22:15:28991 pipeline_controller_->OnSelectedVideoTrackChanged(selected_video_track_id);
servolkf25ceed2016-07-01 03:44:38992}
993
Blink Reformat1c4d759e2017-04-09 16:34:54994blink::WebSize WebMediaPlayerImpl::NaturalSize() const {
acolwellb4034942014-08-28 15:42:43995 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53996
[email protected]b8877772014-03-26 20:17:15997 return blink::WebSize(pipeline_metadata_.natural_size);
[email protected]d43ed912009-02-03 04:52:53998}
999
Jiajia Qin82acdc02017-07-31 09:55:141000blink::WebSize WebMediaPlayerImpl::VisibleRect() const {
1001 DCHECK(main_task_runner_->BelongsToCurrentThread());
1002 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
1003 if (!video_frame)
1004 return blink::WebSize();
1005
1006 const gfx::Rect& visible_rect = video_frame->visible_rect();
1007 return blink::WebSize(visible_rect.width(), visible_rect.height());
1008}
1009
Blink Reformat1c4d759e2017-04-09 16:34:541010bool WebMediaPlayerImpl::Paused() const {
acolwellb4034942014-08-28 15:42:431011 DCHECK(main_task_runner_->BelongsToCurrentThread());
Antonio Gomes81b56552019-05-15 22:15:281012 return pipeline_controller_->GetPlaybackRate() == 0.0f;
[email protected]d43ed912009-02-03 04:52:531013}
1014
François Beaufort184f6042019-01-25 05:50:051015bool WebMediaPlayerImpl::PausedWhenHidden() const {
1016 return paused_when_hidden_;
1017}
1018
Blink Reformat1c4d759e2017-04-09 16:34:541019bool WebMediaPlayerImpl::Seeking() const {
acolwellb4034942014-08-28 15:42:431020 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:531021
Blink Reformat1c4d759e2017-04-09 16:34:541022 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
[email protected]0acebfa2009-08-21 22:45:401023 return false;
[email protected]67cd5052009-09-10 21:53:221024
[email protected]b3766a22010-12-22 17:34:131025 return seeking_;
[email protected]ec9212f2008-12-18 21:40:361026}
1027
Blink Reformat1c4d759e2017-04-09 16:34:541028double WebMediaPlayerImpl::Duration() const {
acolwellb4034942014-08-28 15:42:431029 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]39bdde32013-04-17 17:44:201030
Blink Reformat1c4d759e2017-04-09 16:34:541031 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
[email protected]39bdde32013-04-17 17:44:201032 return std::numeric_limits<double>::quiet_NaN();
1033
chcunninghamb92d5062017-01-10 21:50:221034 // Use duration from ChunkDemuxer when present. MSE allows users to specify
1035 // duration as a double. This propagates to the rest of the pipeline as a
1036 // TimeDelta with potentially reduced precision (limited to Microseconds).
1037 // ChunkDemuxer returns the full-precision user-specified double. This ensures
1038 // users can "get" the exact duration they "set".
1039 if (chunk_demuxer_)
1040 return chunk_demuxer_->GetDuration();
1041
avayvodcc273dd2017-01-19 19:35:121042 base::TimeDelta pipeline_duration = GetPipelineMediaDuration();
chcunninghamb92d5062017-01-10 21:50:221043 return pipeline_duration == kInfiniteDuration
1044 ? std::numeric_limits<double>::infinity()
1045 : pipeline_duration.InSecondsF();
[email protected]d43ed912009-02-03 04:52:531046}
1047
[email protected]db66d0092014-04-16 07:15:121048double WebMediaPlayerImpl::timelineOffset() const {
acolwellb4034942014-08-28 15:42:431049 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]db66d0092014-04-16 07:15:121050
1051 if (pipeline_metadata_.timeline_offset.is_null())
1052 return std::numeric_limits<double>::quiet_NaN();
1053
1054 return pipeline_metadata_.timeline_offset.ToJsTime();
1055}
1056
Dale Curtis051fdf62017-08-05 00:21:131057base::TimeDelta WebMediaPlayerImpl::GetCurrentTimeInternal() const {
1058 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtis051fdf62017-08-05 00:21:131059
1060 base::TimeDelta current_time;
1061 if (Seeking())
1062 current_time = seek_time_;
Dale Curtis051fdf62017-08-05 00:21:131063 else if (paused_)
1064 current_time = paused_time_;
1065 else
Antonio Gomes81b56552019-05-15 22:15:281066 current_time = pipeline_controller_->GetMediaTime();
Dale Curtis051fdf62017-08-05 00:21:131067
Dale Curtis77d6057b2019-05-03 01:31:561068 // It's possible for |current_time| to be kInfiniteDuration here if the page
1069 // seeks to kInfiniteDuration (2**64 - 1) when Duration() is infinite.
Dale Curtis051fdf62017-08-05 00:21:131070 DCHECK_GE(current_time, base::TimeDelta());
1071 return current_time;
1072}
1073
Blink Reformat1c4d759e2017-04-09 16:34:541074double WebMediaPlayerImpl::CurrentTime() const {
acolwellb4034942014-08-28 15:42:431075 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:541076 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
scherkusd2c745b2014-09-04 05:03:401077
1078 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
1079 // see http://crbug.com/409280
Dale Curtis051fdf62017-08-05 00:21:131080 // Note: Duration() may be infinity.
josephlolak918863bc2017-11-15 08:54:331081 return (ended_ && !std::isinf(Duration()))
1082 ? Duration()
1083 : GetCurrentTimeInternal().InSecondsF();
[email protected]d43ed912009-02-03 04:52:531084}
1085
Blink Reformat1c4d759e2017-04-09 16:34:541086WebMediaPlayer::NetworkState WebMediaPlayerImpl::GetNetworkState() const {
acolwellb4034942014-08-28 15:42:431087 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddb1e5a2010-12-13 20:10:451088 return network_state_;
1089}
1090
Blink Reformat1c4d759e2017-04-09 16:34:541091WebMediaPlayer::ReadyState WebMediaPlayerImpl::GetReadyState() const {
acolwellb4034942014-08-28 15:42:431092 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddb1e5a2010-12-13 20:10:451093 return ready_state_;
1094}
1095
CJ DiMeglio89240472018-10-18 18:21:101096blink::WebMediaPlayer::SurfaceLayerMode
1097WebMediaPlayerImpl::GetVideoSurfaceLayerMode() const {
1098 return surface_layer_mode_;
1099}
1100
wolenetzed8e7092017-04-21 16:28:591101blink::WebString WebMediaPlayerImpl::GetErrorMessage() const {
wolenetz4d39cc02016-04-05 19:54:411102 DCHECK(main_task_runner_->BelongsToCurrentThread());
wolenetzed8e7092017-04-21 16:28:591103 return blink::WebString::FromUTF8(media_log_->GetErrorMessage());
wolenetz4d39cc02016-04-05 19:54:411104}
1105
Blink Reformat1c4d759e2017-04-09 16:34:541106blink::WebTimeRanges WebMediaPlayerImpl::Buffered() const {
acolwellb4034942014-08-28 15:42:431107 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]779a8322014-08-22 21:28:371108
acolwell9e0840d2014-09-06 19:01:321109 Ranges<base::TimeDelta> buffered_time_ranges =
Antonio Gomes81b56552019-05-15 22:15:281110 pipeline_controller_->GetBufferedTimeRanges();
[email protected]779a8322014-08-22 21:28:371111
avayvodcc273dd2017-01-19 19:35:121112 const base::TimeDelta duration = GetPipelineMediaDuration();
dalecurtis39a7f932016-07-19 18:34:591113 if (duration != kInfiniteDuration) {
Antonio Gomes81b56552019-05-15 22:15:281114 buffered_data_source_host_->AddBufferedTimeRanges(&buffered_time_ranges,
1115 duration);
[email protected]779a8322014-08-22 21:28:371116 }
Antonio Gomesf01cfbd2019-07-12 08:53:111117 return blink::ConvertToWebTimeRanges(buffered_time_ranges);
[email protected]02022fc2014-05-16 00:05:311118}
1119
Blink Reformat1c4d759e2017-04-09 16:34:541120blink::WebTimeRanges WebMediaPlayerImpl::Seekable() const {
acolwellb4034942014-08-28 15:42:431121 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]39bdde32013-04-17 17:44:201122
Blink Reformat1c4d759e2017-04-09 16:34:541123 if (ready_state_ < WebMediaPlayer::kReadyStateHaveMetadata)
philipjb0e6f3f2014-09-30 09:51:531124 return blink::WebTimeRanges();
1125
Blink Reformat1c4d759e2017-04-09 16:34:541126 const double seekable_end = Duration();
dalecurtis56359cb2014-10-28 00:06:291127
1128 // Allow a special exception for seeks to zero for streaming sources with a
1129 // finite duration; this allows looping to work.
Dale Curtis4841c712018-12-13 18:14:051130 const bool is_finite_stream = mb_data_source_ &&
1131 mb_data_source_->IsStreaming() &&
tguilbertade2bcb2017-01-07 02:57:451132 std::isfinite(seekable_end);
1133
tguilbert75e2bf62017-04-26 20:13:121134 // Do not change the seekable range when using the MediaPlayerRenderer. It
1135 // will take care of dropping invalid seeks.
1136 const bool force_seeks_to_zero =
1137 !using_media_player_renderer_ && is_finite_stream;
dalecurtis56359cb2014-10-28 00:06:291138
1139 // TODO(dalecurtis): Technically this allows seeking on media which return an
tguilbertade2bcb2017-01-07 02:57:451140 // infinite duration so long as DataSource::IsStreaming() is false. While not
dalecurtis56359cb2014-10-28 00:06:291141 // expected, disabling this breaks semi-live players, http://crbug.com/427412.
1142 const blink::WebTimeRange seekable_range(
tguilbertade2bcb2017-01-07 02:57:451143 0.0, force_seeks_to_zero ? 0.0 : seekable_end);
philipjb0e6f3f2014-09-30 09:51:531144 return blink::WebTimeRanges(&seekable_range, 1);
[email protected]ec9212f2008-12-18 21:40:361145}
1146
sandersd35d2c3f2017-01-14 02:04:421147bool WebMediaPlayerImpl::IsPrerollAttemptNeeded() {
1148 // TODO(sandersd): Replace with |highest_ready_state_since_seek_| if we need
1149 // to ensure that preroll always gets a chance to complete.
1150 // See http://crbug.com/671525.
Dale Curtis69e8f302019-05-22 07:36:581151 //
1152 // Note: Even though we get play/pause signals at kReadyStateHaveMetadata, we
1153 // must attempt to preroll until kReadyStateHaveFutureData so that the
1154 // canplaythrough event will be fired to the page (which may be waiting).
1155 //
1156 // TODO(dalecurtis): We should try signaling kReadyStateHaveFutureData upon
1157 // automatic-suspend of a non-playing element to avoid wasting resources.
1158 if (highest_ready_state_ >= ReadyState::kReadyStateHaveFutureData)
sandersd35d2c3f2017-01-14 02:04:421159 return false;
1160
Fredrik Hubinette4cfb4412017-08-23 00:03:071161 // To suspend before we reach kReadyStateHaveCurrentData is only ok
1162 // if we know we're going to get woken up when we get more data, which
1163 // will only happen if the network is in the "Loading" state.
1164 // This happens when the network is fast, but multiple videos are loading
1165 // and multiplexing gets held up waiting for available threads.
1166 if (highest_ready_state_ <= ReadyState::kReadyStateHaveMetadata &&
1167 network_state_ != WebMediaPlayer::kNetworkStateLoading) {
1168 return true;
1169 }
1170
sandersd35d2c3f2017-01-14 02:04:421171 if (preroll_attempt_pending_)
1172 return true;
1173
1174 // Freshly initialized; there has never been any loading progress. (Otherwise
1175 // |preroll_attempt_pending_| would be true when the start time is null.)
1176 if (preroll_attempt_start_time_.is_null())
1177 return false;
1178
1179 base::TimeDelta preroll_attempt_duration =
1180 tick_clock_->NowTicks() - preroll_attempt_start_time_;
1181 return preroll_attempt_duration < kPrerollAttemptTimeout;
1182}
1183
Blink Reformat1c4d759e2017-04-09 16:34:541184bool WebMediaPlayerImpl::DidLoadingProgress() {
acolwellb4034942014-08-28 15:42:431185 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtise7120dc2016-09-03 02:54:351186
1187 // Note: Separate variables used to ensure both methods are called every time.
Antonio Gomes81b56552019-05-15 22:15:281188 const bool pipeline_progress = pipeline_controller_->DidLoadingProgress();
1189 const bool data_progress = buffered_data_source_host_->DidLoadingProgress();
hubbeb2d3efd2017-05-05 23:26:381190 return pipeline_progress || data_progress;
[email protected]d43ed912009-02-03 04:52:531191}
1192
danakjff6a0262018-06-26 19:50:311193void WebMediaPlayerImpl::Paint(cc::PaintCanvas* canvas,
[email protected]dd5c7972014-08-21 15:00:371194 const blink::WebRect& rect,
Kai Ninomiya9e8ae29b2017-09-06 23:45:161195 cc::PaintFlags& flags,
1196 int already_uploaded_id,
1197 VideoFrameUploadMetadata* out_metadata) {
acolwellb4034942014-08-28 15:42:431198 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]dd061e12014-05-06 19:21:221199 TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
[email protected]4e6be3f2009-05-07 02:24:441200
watkd16bb3e2017-04-25 01:18:311201 // We can't copy from protected frames.
Xiaohan Wang24cfe2c2018-01-22 23:16:001202 if (cdm_context_ref_)
xhwang80739452016-01-13 00:48:001203 return;
1204
mcasasf1236fc22015-05-29 22:38:561205 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
[email protected]0fe5d43b2014-01-24 23:32:451206
[email protected]b49beeb2013-03-01 20:04:001207 gfx::Rect gfx_rect(rect);
mcasas265bdbf82015-06-12 18:44:071208 if (video_frame.get() && video_frame->HasTextures()) {
Antoine Labourfee4ae52019-04-24 23:53:571209 if (!context_provider_)
danakj53f7ec902016-05-21 01:30:101210 return; // Unable to get/create a shared main thread context.
Antoine Labourfee4ae52019-04-24 23:53:571211 if (!context_provider_->GrContext())
danakj53f7ec902016-05-21 01:30:101212 return; // The context has been lost since and can't setup a GrContext.
dongseong.hwang0c4e9d82015-01-08 20:11:131213 }
Kai Ninomiyaef8c9e02017-09-27 04:07:401214 if (out_metadata && video_frame) {
Kai Ninomiya9e8ae29b2017-09-06 23:45:161215 // WebGL last-uploaded-frame-metadata API enabled. https://crbug.com/639174
1216 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1217 out_metadata);
1218 if (out_metadata->skipped) {
1219 // Skip uploading this frame.
1220 return;
1221 }
1222 }
zhuoyu.qian4689dde22017-10-16 04:11:481223 video_renderer_.Paint(
Julien Isorce6c83d8de2017-10-12 13:11:291224 video_frame, canvas, gfx::RectF(gfx_rect), flags,
Ted Meyer4a427632019-05-01 19:05:271225 pipeline_metadata_.video_decoder_config.video_transformation(),
Antoine Labourfee4ae52019-04-24 23:53:571226 context_provider_.get());
[email protected]ec9212f2008-12-18 21:40:361227}
[email protected]5df51652009-01-17 00:03:001228
Yutaka Hirano657a0552018-11-09 00:52:551229bool WebMediaPlayerImpl::WouldTaintOrigin() const {
Thomas Guilbert153f84572018-07-19 05:03:581230 if (demuxer_found_hls_) {
1231 // HLS manifests might pull segments from a different origin. We can't know
1232 // for sure, so we conservatively say no here.
Yutaka Hiranoa9cbaa72018-10-10 08:35:221233 return true;
1234 }
1235
Dale Curtis4841c712018-12-13 18:14:051236 if (!mb_data_source_)
Yutaka Hirano657a0552018-11-09 00:52:551237 return false;
1238
1239 // When the resource is redirected to another origin we think it as
1240 // tainted. This is actually not specified, and is under discussion.
1241 // See https://github.com/whatwg/fetch/issues/737.
Dale Curtis4841c712018-12-13 18:14:051242 if (!mb_data_source_->HasSingleOrigin() &&
1243 mb_data_source_->cors_mode() == UrlData::CORS_UNSPECIFIED) {
Yutaka Hirano657a0552018-11-09 00:52:551244 return true;
1245 }
1246
Dale Curtis4841c712018-12-13 18:14:051247 return mb_data_source_->IsCorsCrossOrigin();
[email protected]3fe27112012-06-07 04:00:011248}
1249
Blink Reformat1c4d759e2017-04-09 16:34:541250double WebMediaPlayerImpl::MediaTimeForTimeValue(double timeValue) const {
qinminb4c39782015-08-10 18:43:241251 return base::TimeDelta::FromSecondsD(timeValue).InSecondsF();
[email protected]e06e16d82011-05-26 22:13:331252}
1253
Blink Reformat1c4d759e2017-04-09 16:34:541254unsigned WebMediaPlayerImpl::DecodedFrameCount() const {
acolwellb4034942014-08-28 15:42:431255 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051256 return GetPipelineStatistics().video_frames_decoded;
[email protected]4c51bc662011-02-16 02:03:161257}
1258
Blink Reformat1c4d759e2017-04-09 16:34:541259unsigned WebMediaPlayerImpl::DroppedFrameCount() const {
acolwellb4034942014-08-28 15:42:431260 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051261 return GetPipelineStatistics().video_frames_dropped;
[email protected]4c51bc662011-02-16 02:03:161262}
1263
Dave Tapuska6c7154912018-07-30 20:39:001264uint64_t WebMediaPlayerImpl::AudioDecodedByteCount() const {
acolwellb4034942014-08-28 15:42:431265 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051266 return GetPipelineStatistics().audio_bytes_decoded;
[email protected]4c51bc662011-02-16 02:03:161267}
1268
Dave Tapuska6c7154912018-07-30 20:39:001269uint64_t WebMediaPlayerImpl::VideoDecodedByteCount() const {
acolwellb4034942014-08-28 15:42:431270 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051271 return GetPipelineStatistics().video_bytes_decoded;
[email protected]4c51bc662011-02-16 02:03:161272}
1273
Dale Curtiscdfc6f22019-06-26 22:05:231274bool WebMediaPlayerImpl::HasAvailableVideoFrame() const {
1275 return has_first_frame_;
1276}
1277
Blink Reformat1c4d759e2017-04-09 16:34:541278bool WebMediaPlayerImpl::CopyVideoTextureToPlatformTexture(
danakj46070b02016-03-28 21:54:111279 gpu::gles2::GLES2Interface* gl,
jiajia.qinc2943162017-05-12 01:34:391280 unsigned int target,
zmo57d577a2015-10-30 18:28:591281 unsigned int texture,
kbr0986e622017-04-13 02:34:581282 unsigned internal_format,
1283 unsigned format,
1284 unsigned type,
jiajia.qinc2943162017-05-12 01:34:391285 int level,
zmo57d577a2015-10-30 18:28:591286 bool premultiply_alpha,
Kai Ninomiya9e8ae29b2017-09-06 23:45:161287 bool flip_y,
1288 int already_uploaded_id,
1289 VideoFrameUploadMetadata* out_metadata) {
xhwang213e50c2016-10-10 23:56:311290 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]bfc05f22013-10-19 17:55:161291 TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
1292
watkd16bb3e2017-04-25 01:18:311293 // We can't copy from protected frames.
Xiaohan Wang24cfe2c2018-01-22 23:16:001294 if (cdm_context_ref_)
xhwang213e50c2016-10-10 23:56:311295 return false;
[email protected]dd061e12014-05-06 19:21:221296
xhwang213e50c2016-10-10 23:56:311297 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
jbauman581d041c2016-07-21 01:01:031298 if (!video_frame.get() || !video_frame->HasTextures()) {
[email protected]e56f88c72013-06-25 22:31:291299 return false;
dongseong.hwang0c4e9d82015-01-08 20:11:131300 }
Kai Ninomiya9e8ae29b2017-09-06 23:45:161301 if (out_metadata) {
1302 // WebGL last-uploaded-frame-metadata API is enabled.
1303 // https://crbug.com/639174
1304 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1305 out_metadata);
1306 if (out_metadata->skipped) {
1307 // Skip uploading this frame.
1308 return true;
1309 }
1310 }
[email protected]df41e252014-02-03 23:39:501311
zhuoyu.qian4689dde22017-10-16 04:11:481312 return video_renderer_.CopyVideoFrameTexturesToGLTexture(
Antoine Labourfee4ae52019-04-24 23:53:571313 context_provider_.get(), gl, video_frame.get(), target, texture,
Dan Sanders930cc1d2018-10-03 00:45:081314 internal_format, format, type, level, premultiply_alpha, flip_y);
[email protected]6523b242013-03-13 11:10:071315}
1316
Yan, Shaobo44b79ba2019-04-02 06:09:271317bool WebMediaPlayerImpl::PrepareVideoFrameForWebGL(
1318 gpu::gles2::GLES2Interface* gl,
1319 unsigned target,
1320 unsigned texture,
1321 int already_uploaded_id,
1322 WebMediaPlayer::VideoFrameUploadMetadata* out_metadata) {
1323 DCHECK(main_task_runner_->BelongsToCurrentThread());
1324 TRACE_EVENT0("media", "WebMediaPlayerImpl::PrepareVideoFrameForWebGL");
1325
1326 // TODO(crbug.com/776222): How to deal with protected frames.
1327 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
1328 if (!video_frame.get() || !video_frame->HasTextures()) {
1329 return false;
1330 }
1331 if (out_metadata) {
1332 // WebGL last-uploaded-frame-metadata API is enabled.
1333 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1334 out_metadata);
1335 if (out_metadata->skipped) {
1336 // Skip uploading this frame.
1337 return true;
1338 }
1339 }
1340
Yan, Shaobo44b79ba2019-04-02 06:09:271341 return video_renderer_.PrepareVideoFrameForWebGL(
Antoine Labourfee4ae52019-04-24 23:53:571342 context_provider_.get(), gl, video_frame.get(), target, texture);
Yan, Shaobo44b79ba2019-04-02 06:09:271343}
1344
Matt Wolenetz95af6362018-01-04 20:23:421345// static
Kai Ninomiya9e8ae29b2017-09-06 23:45:161346void WebMediaPlayerImpl::ComputeFrameUploadMetadata(
1347 VideoFrame* frame,
1348 int already_uploaded_id,
1349 VideoFrameUploadMetadata* out_metadata) {
1350 DCHECK(out_metadata);
Kai Ninomiyaef8c9e02017-09-27 04:07:401351 DCHECK(frame);
Kai Ninomiya9e8ae29b2017-09-06 23:45:161352 out_metadata->frame_id = frame->unique_id();
1353 out_metadata->visible_rect = frame->visible_rect();
1354 out_metadata->timestamp = frame->timestamp();
Li, Hao0fab96a2019-10-31 02:46:471355 base::TimeDelta frame_duration;
1356 if (frame->metadata()->GetTimeDelta(media::VideoFrameMetadata::FRAME_DURATION,
1357 &frame_duration)) {
1358 out_metadata->expected_timestamp = frame->timestamp() + frame_duration;
1359 };
Kai Ninomiya9e8ae29b2017-09-06 23:45:161360 bool skip_possible = already_uploaded_id != -1;
1361 bool same_frame_id = frame->unique_id() == already_uploaded_id;
1362 out_metadata->skipped = skip_possible && same_frame_id;
1363}
1364
Blink Reformat1c4d759e2017-04-09 16:34:541365void WebMediaPlayerImpl::SetContentDecryptionModule(
[email protected]9ebc3b03f2014-08-13 04:01:231366 blink::WebContentDecryptionModule* cdm,
1367 blink::WebContentDecryptionModuleResult result) {
xhwang51139732017-02-24 19:36:081368 DVLOG(1) << __func__ << ": cdm = " << cdm;
acolwellb4034942014-08-28 15:42:431369 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]9ebc3b03f2014-08-13 04:01:231370
jrummell06f27072015-06-08 18:12:381371 // Once the CDM is set it can't be cleared as there may be frames being
1372 // decrypted on other threads. So fail this request.
1373 // http://crbug.com/462365#c7.
xhwang97de4202014-11-25 08:44:011374 if (!cdm) {
Blink Reformat1c4d759e2017-04-09 16:34:541375 result.CompleteWithError(
1376 blink::kWebContentDecryptionModuleExceptionInvalidStateError, 0,
xhwang79b193042016-12-13 18:52:431377 "The existing ContentDecryptionModule object cannot be removed at this "
1378 "time.");
xhwang97de4202014-11-25 08:44:011379 return;
1380 }
1381
jrummell89e61d82015-07-23 20:03:341382 // Create a local copy of |result| to avoid problems with the callback
1383 // getting passed to the media thread and causing |result| to be destructed
jrummell4acbec912016-02-27 02:45:031384 // on the wrong thread in some failure conditions. Blink should prevent
1385 // multiple simultaneous calls.
1386 DCHECK(!set_cdm_result_);
jrummell89e61d82015-07-23 20:03:341387 set_cdm_result_.reset(new blink::WebContentDecryptionModuleResult(result));
1388
Chris Cunninghamd4a00192019-03-21 20:02:491389 SetCdmInternal(cdm);
xhwang97de4202014-11-25 08:44:011390}
1391
xhwange8c4181a2014-12-06 08:10:011392void WebMediaPlayerImpl::OnEncryptedMediaInitData(
jrummellcf78967c2015-04-03 05:03:581393 EmeInitDataType init_data_type,
Avi Drissman97785ea2015-12-19 01:11:311394 const std::vector<uint8_t>& init_data) {
jrummellcf78967c2015-04-03 05:03:581395 DCHECK(init_data_type != EmeInitDataType::UNKNOWN);
xhwangbab66f52014-12-02 23:49:501396
Xiaohan Wangf63505d2017-10-21 08:00:531397 RecordEncryptedEvent(true);
xhwangbab66f52014-12-02 23:49:501398
dalecurtis04bdb582016-08-17 22:15:231399 // Recreate the watch time reporter if necessary.
1400 const bool was_encrypted = is_encrypted_;
1401 is_encrypted_ = true;
Dale Curtis3899090ea2018-01-12 00:10:351402 if (!was_encrypted) {
1403 media_metrics_provider_->SetIsEME();
1404 if (watch_time_reporter_)
1405 CreateWatchTimeReporter();
dalecurtis04bdb582016-08-17 22:15:231406
Chris Cunningham6c0ec292019-04-04 18:31:111407 // |was_encrypted| = false means we didn't have a CDM prior to observing
1408 // encrypted media init data. Reset the reporter until the CDM arrives. See
1409 // SetCdmInternal().
1410 DCHECK(!cdm_config_);
1411 video_decode_stats_reporter_.reset();
1412 }
Chris Cunninghamd9df58e2017-08-29 00:04:231413
Blink Reformat1c4d759e2017-04-09 16:34:541414 encrypted_client_->Encrypted(
Antonio Gomes89b70572019-07-13 00:44:211415 init_data_type, init_data.data(),
srirama.m26f864d02015-07-14 05:21:461416 base::saturated_cast<unsigned int>(init_data.size()));
xhwangbab66f52014-12-02 23:49:501417}
1418
servolk81e01e02016-03-05 03:29:151419void WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated(
dcheng3076abbf2016-04-22 20:42:391420 std::unique_ptr<MediaTracks> tracks) {
servolk81e01e02016-03-05 03:29:151421 // For MSE/chunk_demuxer case the media track updates are handled by
1422 // WebSourceBufferImpl.
1423 DCHECK(demuxer_.get());
1424 DCHECK(!chunk_demuxer_);
servolkef1e5ef2016-03-25 04:55:261425
servolk16e8bdf82017-04-11 17:00:391426 // Report the media track information to blink. Only the first audio track and
1427 // the first video track are enabled by default to match blink logic.
1428 bool is_first_audio_track = true;
1429 bool is_first_video_track = true;
servolkef1e5ef2016-03-25 04:55:261430 for (const auto& track : tracks->tracks()) {
1431 if (track->type() == MediaTrack::Audio) {
Maciej Pawlowskif2556d122019-06-03 08:14:181432 client_->AddAudioTrack(
1433 blink::WebString::FromUTF8(track->id().value()),
1434 blink::WebMediaPlayerClient::kAudioTrackKindMain,
1435 blink::WebString::FromUTF8(track->label().value()),
1436 blink::WebString::FromUTF8(track->language().value()),
1437 is_first_audio_track);
servolk16e8bdf82017-04-11 17:00:391438 is_first_audio_track = false;
servolkef1e5ef2016-03-25 04:55:261439 } else if (track->type() == MediaTrack::Video) {
Maciej Pawlowskif2556d122019-06-03 08:14:181440 client_->AddVideoTrack(
1441 blink::WebString::FromUTF8(track->id().value()),
1442 blink::WebMediaPlayerClient::kVideoTrackKindMain,
1443 blink::WebString::FromUTF8(track->label().value()),
1444 blink::WebString::FromUTF8(track->language().value()),
1445 is_first_video_track);
servolk16e8bdf82017-04-11 17:00:391446 is_first_video_track = false;
servolkef1e5ef2016-03-25 04:55:261447 } else {
1448 // Text tracks are not supported through this code path yet.
1449 NOTREACHED();
1450 }
1451 }
servolk81e01e02016-03-05 03:29:151452}
1453
Chris Cunninghamd4a00192019-03-21 20:02:491454void WebMediaPlayerImpl::SetCdmInternal(
1455 blink::WebContentDecryptionModule* cdm) {
jrummelle616ee92016-10-08 02:15:441456 DCHECK(main_task_runner_->BelongsToCurrentThread());
1457 DCHECK(cdm);
Xiaohan Wang24cfe2c2018-01-22 23:16:001458
Chris Cunninghamd4a00192019-03-21 20:02:491459 const bool was_encrypted = is_encrypted_;
1460 is_encrypted_ = true;
1461
1462 // Recreate the watch time reporter if necessary.
1463 if (!was_encrypted) {
1464 media_metrics_provider_->SetIsEME();
1465 if (watch_time_reporter_)
1466 CreateWatchTimeReporter();
1467 }
1468
Chris Cunningham6c0ec292019-04-04 18:31:111469 WebContentDecryptionModuleImpl* web_cdm =
1470 ToWebContentDecryptionModuleImpl(cdm);
1471 auto cdm_context_ref = web_cdm->GetCdmContextRef();
Xiaohan Wang24cfe2c2018-01-22 23:16:001472 if (!cdm_context_ref) {
jrummelle616ee92016-10-08 02:15:441473 NOTREACHED();
1474 OnCdmAttached(false);
xhwang80739452016-01-13 00:48:001475 return;
1476 }
1477
Chris Cunningham6c0ec292019-04-04 18:31:111478 // Arrival of |cdm_config_| and |key_system_| unblocks recording of encrypted
1479 // stats. Attempt to create the stats reporter. Note, we do NOT guard this
1480 // within !was_encypted above because often the CDM arrives after the call to
1481 // OnEncryptedMediaInitData().
1482 cdm_config_ = web_cdm->GetCdmConfig();
1483 key_system_ = web_cdm->GetKeySystem();
1484 DCHECK(!key_system_.empty());
1485 CreateVideoDecodeStatsReporter();
1486
Xiaohan Wang24cfe2c2018-01-22 23:16:001487 CdmContext* cdm_context = cdm_context_ref->GetCdmContext();
1488 DCHECK(cdm_context);
jrummelle616ee92016-10-08 02:15:441489
1490 // Keep the reference to the CDM, as it shouldn't be destroyed until
1491 // after the pipeline is done with the |cdm_context|.
Xiaohan Wang24cfe2c2018-01-22 23:16:001492 pending_cdm_context_ref_ = std::move(cdm_context_ref);
Antonio Gomes81b56552019-05-15 22:15:281493 pipeline_controller_->SetCdm(
Antonio Gomes142f32a2019-05-15 23:32:561494 cdm_context, base::Bind(&WebMediaPlayerImpl::OnCdmAttached, weak_this_));
xhwang97de4202014-11-25 08:44:011495}
1496
jrummell89e61d82015-07-23 20:03:341497void WebMediaPlayerImpl::OnCdmAttached(bool success) {
xhwang51139732017-02-24 19:36:081498 DVLOG(1) << __func__ << ": success = " << success;
jrummelle616ee92016-10-08 02:15:441499 DCHECK(main_task_runner_->BelongsToCurrentThread());
Xiaohan Wang24cfe2c2018-01-22 23:16:001500 DCHECK(pending_cdm_context_ref_);
jrummelle616ee92016-10-08 02:15:441501
1502 // If the CDM is set from the constructor there is no promise
1503 // (|set_cdm_result_|) to fulfill.
xhwang97de4202014-11-25 08:44:011504 if (success) {
Ted Meyer7f5b4e22019-11-21 03:21:191505 media_log_->SetProperty<MediaLogProperty::kIsVideoEncrypted>(true);
xhwang29c5ad202017-04-14 07:02:191506
jrummelle616ee92016-10-08 02:15:441507 // This will release the previously attached CDM (if any).
Xiaohan Wang24cfe2c2018-01-22 23:16:001508 cdm_context_ref_ = std::move(pending_cdm_context_ref_);
jrummelle616ee92016-10-08 02:15:441509 if (set_cdm_result_) {
Blink Reformat1c4d759e2017-04-09 16:34:541510 set_cdm_result_->Complete();
jrummelle616ee92016-10-08 02:15:441511 set_cdm_result_.reset();
1512 }
1513
xhwang97de4202014-11-25 08:44:011514 return;
1515 }
1516
Xiaohan Wang24cfe2c2018-01-22 23:16:001517 pending_cdm_context_ref_.reset();
jrummelle616ee92016-10-08 02:15:441518 if (set_cdm_result_) {
Blink Reformat1c4d759e2017-04-09 16:34:541519 set_cdm_result_->CompleteWithError(
1520 blink::kWebContentDecryptionModuleExceptionNotSupportedError, 0,
xhwang79b193042016-12-13 18:52:431521 "Unable to set ContentDecryptionModule object");
jrummelle616ee92016-10-08 02:15:441522 set_cdm_result_.reset();
1523 }
[email protected]9ebc3b03f2014-08-13 04:01:231524}
1525
sandersd1c0bba02016-03-04 23:14:081526void WebMediaPlayerImpl::OnPipelineSeeked(bool time_updated) {
John Chen5b164a02017-11-01 00:36:091527 TRACE_EVENT2("media", "WebMediaPlayerImpl::OnPipelineSeeked", "target",
1528 seek_time_.InSecondsF(), "id", media_log_->id());
[email protected]5d11eff2011-09-15 00:06:061529 seeking_ = false;
wolenetz1b2ae7d2015-06-10 00:44:211530 seek_time_ = base::TimeDelta();
avayvod2135a642017-01-13 00:17:141531
hubbe5a2dec022016-03-17 01:14:231532 if (paused_) {
Antonio Gomes81b56552019-05-15 22:15:281533 paused_time_ = pipeline_controller_->GetMediaTime();
dalecurtis04bdb582016-08-17 22:15:231534 } else {
1535 DCHECK(watch_time_reporter_);
1536 watch_time_reporter_->OnPlaying();
hubbe5a2dec022016-03-17 01:14:231537 }
sandersd1c0bba02016-03-04 23:14:081538 if (time_updated)
1539 should_notify_time_changed_ = true;
dalecurtisaf34d8712016-09-20 04:32:261540
dalecurtis4f6d14d2017-02-22 17:42:221541 // Reset underflow duration upon seek; this prevents looping videos and user
1542 // actions from artificially inflating the duration.
1543 underflow_timer_.reset();
avayvod56e1f3942017-01-21 02:06:311544
1545 // Background video optimizations are delayed when shown/hidden if pipeline
1546 // is seeking.
1547 UpdateBackgroundVideoOptimizationState();
Dale Curtis2dc6089a2018-03-26 16:47:581548
Dale Curtisd71061f02019-05-21 21:33:541549 // If we successfully completed a suspended startup, we need to make a call to
1550 // UpdatePlayState() in case any events which should trigger a resume have
1551 // occurred during startup.
Dale Curtis2dc6089a2018-03-26 16:47:581552 if (attempting_suspended_start_ &&
Antonio Gomes81b56552019-05-15 22:15:281553 pipeline_controller_->IsPipelineSuspended()) {
Dale Curtisff576552018-03-30 02:32:441554 skip_metrics_due_to_startup_suspend_ = true;
Dale Curtisd71061f02019-05-21 21:33:541555
1556 // If we successfully completed a suspended startup, signal that we have
1557 // reached BUFFERING_HAVE_ENOUGH so that canplay and canplaythrough fire
1558 // correctly. We must unfortunately always do this because it's valid for
1559 // elements to play while not visible nor even in the DOM.
1560 //
1561 // Note: This call is dual purpose, it is also responsible for triggering an
1562 // UpdatePlayState() call which may need to resume the pipeline once Blink
1563 // has been told about the ReadyState change.
Chris Cunninghamfc0d67e2019-07-22 20:29:161564 OnBufferingStateChangeInternal(BUFFERING_HAVE_ENOUGH,
1565 BUFFERING_CHANGE_REASON_UNKNOWN, true);
Dale Curtisff576552018-03-30 02:32:441566
1567 // If |skip_metrics_due_to_startup_suspend_| is unset by a resume started by
1568 // the OnBufferingStateChangeInternal() call, record a histogram of it here.
1569 //
1570 // If the value is unset, that means we should not have suspended and we've
1571 // likely incurred some cost to TimeToFirstFrame and TimeToPlayReady which
1572 // will be reflected in those statistics.
1573 base::UmaHistogramBoolean(
1574 std::string("Media.PreloadMetadataSuspendWasIdeal.") +
1575 ((HasVideo() && HasAudio()) ? "AudioVideo"
1576 : (HasVideo() ? "Video" : "Audio")),
1577 skip_metrics_due_to_startup_suspend_);
Dale Curtis2dc6089a2018-03-26 16:47:581578 }
1579
1580 attempting_suspended_start_ = false;
Becca Hughes7a85bf22019-07-24 16:16:581581
1582 // The current time has changed so we should update the media position state.
1583 UpdateMediaPositionState();
[email protected]8931c41a2009-07-07 17:31:491584}
1585
sandersd1c0bba02016-03-04 23:14:081586void WebMediaPlayerImpl::OnPipelineSuspended() {
Dale Curtis83321152018-12-01 01:22:061587 // Add a log event so the player shows up as "SUSPENDED" in media-internals.
1588 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::SUSPENDED));
1589
Dale Curtis04769ca2019-05-25 00:38:101590 if (attempting_suspended_start_) {
1591 DCHECK(pipeline_controller_->IsSuspended());
1592 did_lazy_load_ = !has_poster_ && HasVideo();
1593 }
1594
sandersd2f5bb6152017-03-29 22:57:531595 // Tell the data source we have enough data so that it may release the
Dale Curtis04769ca2019-05-25 00:38:101596 // connection (unless blink is waiting on us to signal play()).
1597 if (mb_data_source_ && !client_->CouldPlayIfEnoughData()) {
1598 // |attempting_suspended_start_| will be cleared by OnPipelineSeeked() which
1599 // will occur after this method during a suspended startup.
1600 if (attempting_suspended_start_ && did_lazy_load_) {
1601 DCHECK(!has_first_frame_);
1602 DCHECK(have_enough_after_lazy_load_cb_.IsCancelled());
1603
1604 // For lazy load, we won't know if the element is non-visible until a
1605 // layout completes, so to avoid unnecessarily tearing down the network
1606 // connection, briefly (250ms chosen arbitrarily) delay signaling "have
1607 // enough" to the MultiBufferDataSource.
1608 //
1609 // base::Unretained() is safe here since the base::CancelableOnceClosure
1610 // will cancel upon destruction of this class and |mb_data_source_| is
1611 // gauranteeed to outlive us.
1612 have_enough_after_lazy_load_cb_.Reset(
1613 base::BindOnce(&MultibufferDataSource::OnBufferingHaveEnough,
1614 base::Unretained(mb_data_source_), true));
1615 main_task_runner_->PostDelayedTask(
1616 FROM_HERE, have_enough_after_lazy_load_cb_.callback(),
1617 base::TimeDelta::FromMilliseconds(250));
1618 } else {
1619 have_enough_after_lazy_load_cb_.Cancel();
1620 mb_data_source_->OnBufferingHaveEnough(true);
1621 }
1622 }
dalecurtis37fe5862016-03-15 19:29:091623
sandersd50a635e2016-04-04 22:50:091624 ReportMemoryUsage();
1625
sandersd1c0bba02016-03-04 23:14:081626 if (pending_suspend_resume_cycle_) {
watkdee516f2016-02-18 02:22:191627 pending_suspend_resume_cycle_ = false;
sandersd50a635e2016-04-04 22:50:091628 UpdatePlayState();
dalecurtis0431cbf2016-03-12 01:19:431629 }
sandersd1c0bba02016-03-04 23:14:081630}
1631
avayvod2135a642017-01-13 00:17:141632void WebMediaPlayerImpl::OnBeforePipelineResume() {
Dale Curtis04769ca2019-05-25 00:38:101633 // Since we're resuming, cancel closing of the network connection.
1634 have_enough_after_lazy_load_cb_.Cancel();
1635
Dale Curtisff576552018-03-30 02:32:441636 // We went through suspended startup, so the player is only just now spooling
1637 // up for playback. As such adjust |load_start_time_| so it reports the same
1638 // metric as what would be reported if we had not suspended at startup.
1639 if (skip_metrics_due_to_startup_suspend_) {
1640 // In the event that the call to SetReadyState() initiated after pipeline
1641 // startup immediately tries to start playback, we should not update
1642 // |load_start_time_| to avoid losing visibility into the impact of a
1643 // suspended startup on the time until first frame / play ready for cases
1644 // where suspended startup was applied incorrectly.
1645 if (!attempting_suspended_start_)
1646 load_start_time_ = base::TimeTicks::Now() - time_to_metadata_;
1647 skip_metrics_due_to_startup_suspend_ = false;
1648 }
1649
avayvod2135a642017-01-13 00:17:141650 // Enable video track if we disabled it in the background - this way the new
1651 // renderer will attach its callbacks to the video stream properly.
1652 // TODO(avayvod): Remove this when disabling and enabling video tracks in
1653 // non-playing state works correctly. See https://crbug.com/678374.
1654 EnableVideoTrackIfNeeded();
1655 is_pipeline_resuming_ = true;
1656}
1657
1658void WebMediaPlayerImpl::OnPipelineResumed() {
1659 is_pipeline_resuming_ = false;
1660
avayvod56e1f3942017-01-21 02:06:311661 UpdateBackgroundVideoOptimizationState();
avayvod2135a642017-01-13 00:17:141662}
1663
alokp967c902452016-05-06 05:21:371664void WebMediaPlayerImpl::OnDemuxerOpened() {
1665 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtis9cddc0b2017-04-19 21:23:381666 client_->MediaSourceOpened(new WebMediaSourceImpl(chunk_demuxer_));
alokp967c902452016-05-06 05:21:371667}
1668
servolkf94b4602017-01-31 16:44:271669void WebMediaPlayerImpl::OnMemoryPressure(
1670 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1671 DVLOG(2) << __func__ << " memory_pressure_level=" << memory_pressure_level;
1672 DCHECK(main_task_runner_->BelongsToCurrentThread());
1673 DCHECK(base::FeatureList::IsEnabled(kMemoryPressureBasedSourceBufferGC));
1674 DCHECK(chunk_demuxer_);
1675
1676 // The new value of |memory_pressure_level| will take effect on the next
1677 // garbage collection. Typically this means the next SourceBuffer append()
1678 // operation, since per MSE spec, the garbage collection must only occur
1679 // during SourceBuffer append(). But if memory pressure is critical it might
1680 // be better to perform GC immediately rather than wait for the next append
1681 // and potentially get killed due to out-of-memory.
1682 // So if this experiment is enabled and pressure level is critical, we'll pass
1683 // down force_instant_gc==true, which will force immediate GC on
1684 // SourceBufferStreams.
1685 bool force_instant_gc =
1686 (enable_instant_source_buffer_gc_ &&
1687 memory_pressure_level ==
1688 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
1689
Matt Wolenetz95af6362018-01-04 20:23:421690 // base::Unretained is safe, since |chunk_demuxer_| is actually owned by
1691 // |this| via this->demuxer_. Note the destruction of |chunk_demuxer_| is done
1692 // from ~WMPI by first hopping to |media_task_runner_| to prevent race with
1693 // this task.
servolkf94b4602017-01-31 16:44:271694 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:511695 FROM_HERE, base::BindOnce(&ChunkDemuxer::OnMemoryPressure,
1696 base::Unretained(chunk_demuxer_),
1697 base::TimeDelta::FromSecondsD(CurrentTime()),
1698 memory_pressure_level, force_instant_gc));
servolkf94b4602017-01-31 16:44:271699}
1700
alokp967c902452016-05-06 05:21:371701void WebMediaPlayerImpl::OnError(PipelineStatus status) {
Xiaohan Wang73b433f2019-11-05 20:13:011702 DVLOG(1) << __func__ << ": status=" << status;
alokp967c902452016-05-06 05:21:371703 DCHECK(main_task_runner_->BelongsToCurrentThread());
1704 DCHECK_NE(status, PIPELINE_OK);
1705
1706 if (suppress_destruction_errors_)
1707 return;
1708
Thomas Guilbert6b6be3d2017-08-18 03:17:271709#if defined(OS_ANDROID)
Dale Curtisf273f8f2018-12-13 23:40:331710 // |mb_data_source_| may be nullptr if someone passes in a m3u8 as a data://
1711 // URL, since MediaPlayer doesn't support data:// URLs, fail playback now.
Dan Sanders675250992019-05-11 00:07:491712 const bool found_hls = base::FeatureList::IsEnabled(kHlsPlayer) &&
1713 status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS;
Dale Curtisf273f8f2018-12-13 23:40:331714 if (found_hls && mb_data_source_) {
Dan Sandersae245e42019-03-07 23:25:291715 demuxer_found_hls_ = true;
1716
Dan Sandersd80b1842019-02-05 00:36:161717 UMA_HISTOGRAM_BOOLEAN("Media.WebMediaPlayerImpl.HLS.IsCorsCrossOrigin",
1718 mb_data_source_->IsCorsCrossOrigin());
Dan Sandersae245e42019-03-07 23:25:291719 if (mb_data_source_->IsCorsCrossOrigin()) {
1720 UMA_HISTOGRAM_BOOLEAN("Media.WebMediaPlayerImpl.HLS.HasAccessControl",
1721 mb_data_source_->HasAccessControl());
1722 }
1723
1724 // Note: Does not consider the full redirect chain, which could contain
1725 // undetected mixed content.
Dan Sandersd80b1842019-02-05 00:36:161726 bool frame_url_is_cryptographic = url::Origin(frame_->GetSecurityOrigin())
1727 .GetURL()
1728 .SchemeIsCryptographic();
1729 bool manifest_url_is_cryptographic =
1730 loaded_url_.SchemeIsCryptographic() &&
1731 mb_data_source_->GetUrlAfterRedirects().SchemeIsCryptographic();
1732 UMA_HISTOGRAM_BOOLEAN(
1733 "Media.WebMediaPlayerImpl.HLS.IsMixedContent",
1734 frame_url_is_cryptographic && !manifest_url_is_cryptographic);
Thomas Guilbert153f84572018-07-19 05:03:581735
Xiaohan Wang3684e0c2019-10-30 01:04:301736 renderer_factory_selector_->SetBaseFactoryType(
Xiaohan Wang48aaa192019-12-05 01:29:001737 RendererFactoryType::kMediaPlayer);
Thomas Guilbert6b6be3d2017-08-18 03:17:271738
Dale Curtisf273f8f2018-12-13 23:40:331739 loaded_url_ = mb_data_source_->GetUrlAfterRedirects();
1740 DCHECK(data_source_);
1741 data_source_->Stop();
1742 mb_data_source_ = nullptr;
1743
Antonio Gomes81b56552019-05-15 22:15:281744 pipeline_controller_->Stop();
Dale Curtis8a6281322017-08-31 00:35:531745 SetMemoryReportingState(false);
Thomas Guilbert6b6be3d2017-08-18 03:17:271746
Dale Curtisf273f8f2018-12-13 23:40:331747 // Trampoline through the media task runner to destruct the demuxer and
1748 // data source now that we're switching to HLS playback.
1749 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:511750 FROM_HERE,
Dale Curtisf273f8f2018-12-13 23:40:331751 BindToCurrentLoop(base::BindOnce(
1752 [](std::unique_ptr<Demuxer> demuxer,
1753 std::unique_ptr<DataSource> data_source,
1754 base::OnceClosure start_pipeline_cb) {
1755 // Release resources before starting HLS.
1756 demuxer.reset();
1757 data_source.reset();
1758
1759 std::move(start_pipeline_cb).Run();
1760 },
1761 std::move(demuxer_), std::move(data_source_),
Antonio Gomes142f32a2019-05-15 23:32:561762 base::BindOnce(&WebMediaPlayerImpl::StartPipeline, weak_this_))));
Dale Curtisf273f8f2018-12-13 23:40:331763
Thomas Guilbert6b6be3d2017-08-18 03:17:271764 return;
1765 }
Dale Curtisf273f8f2018-12-13 23:40:331766
1767 // We found hls in a data:// URL, fail immediately.
1768 if (found_hls)
1769 status = PIPELINE_ERROR_EXTERNAL_RENDERER_FAILED;
Thomas Guilbert6b6be3d2017-08-18 03:17:271770#endif
1771
Dale Curtis5bba03232018-08-30 17:57:381772 MaybeSetContainerName();
Dan Sanders6edfd782019-08-13 00:13:181773 simple_watch_timer_.Stop();
alokp967c902452016-05-06 05:21:371774 media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status));
Dale Curtis74612b72017-12-14 20:56:191775 media_metrics_provider_->OnError(status);
Dale Curtisccfd0cca2017-08-31 01:27:561776 if (watch_time_reporter_)
1777 watch_time_reporter_->OnError(status);
alokp967c902452016-05-06 05:21:371778
Blink Reformat1c4d759e2017-04-09 16:34:541779 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) {
alokp967c902452016-05-06 05:21:371780 // Any error that occurs before reaching ReadyStateHaveMetadata should
1781 // be considered a format error.
Blink Reformat1c4d759e2017-04-09 16:34:541782 SetNetworkState(WebMediaPlayer::kNetworkStateFormatError);
alokp967c902452016-05-06 05:21:371783 } else {
Antonio Gomesf01cfbd2019-07-12 08:53:111784 SetNetworkState(blink::PipelineErrorToNetworkState(status));
alokp967c902452016-05-06 05:21:371785 }
1786
Thomas Guilbert2e591392017-08-12 00:56:381787 // PipelineController::Stop() is idempotent.
Antonio Gomes81b56552019-05-15 22:15:281788 pipeline_controller_->Stop();
Thomas Guilbert2e591392017-08-12 00:56:381789
alokp967c902452016-05-06 05:21:371790 UpdatePlayState();
1791}
1792
1793void WebMediaPlayerImpl::OnEnded() {
John Chen5b164a02017-11-01 00:36:091794 TRACE_EVENT2("media", "WebMediaPlayerImpl::OnEnded", "duration", Duration(),
1795 "id", media_log_->id());
pkastingf5279482016-07-27 02:18:201796 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:431797 DCHECK(main_task_runner_->BelongsToCurrentThread());
scherkusd2c745b2014-09-04 05:03:401798
sandersd1c0bba02016-03-04 23:14:081799 // Ignore state changes until we've completed all outstanding operations.
Antonio Gomes81b56552019-05-15 22:15:281800 if (!pipeline_controller_->IsStable())
scherkusd2c745b2014-09-04 05:03:401801 return;
1802
1803 ended_ = true;
Blink Reformat1c4d759e2017-04-09 16:34:541804 client_->TimeChanged();
sandersd50a635e2016-04-04 22:50:091805
1806 // We don't actually want this to run until |client_| calls seek() or pause(),
1807 // but that should have already happened in timeChanged() and so this is
1808 // expected to be a no-op.
1809 UpdatePlayState();
[email protected]576537842009-08-12 23:52:051810}
1811
Chisoon Jeong0a8e4bc2019-05-11 00:06:141812void WebMediaPlayerImpl::OnMetadata(const PipelineMetadata& metadata) {
pkastingf5279482016-07-27 02:18:201813 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:431814 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisff576552018-03-30 02:32:441815
1816 // Cache the |time_to_metadata_| to use for adjusting the TimeToFirstFrame and
1817 // TimeToPlayReady metrics later if we end up doing a suspended startup.
1818 time_to_metadata_ = base::TimeTicks::Now() - load_start_time_;
1819 media_metrics_provider_->SetTimeToMetadata(time_to_metadata_);
1820 RecordTimingUMA("Media.TimeToMetadata", time_to_metadata_);
[email protected]a8e2cb82012-08-17 00:02:391821
Dale Curtis5bba03232018-08-30 17:57:381822 MaybeSetContainerName();
1823
[email protected]b8877772014-03-26 20:17:151824 pipeline_metadata_ = metadata;
[email protected]739847c02014-01-16 00:12:251825
Ted Meyer4a427632019-05-01 19:05:271826 UMA_HISTOGRAM_ENUMERATION(
1827 "Media.VideoRotation",
1828 metadata.video_decoder_config.video_transformation().rotation,
1829 VIDEO_ROTATION_MAX + 1);
[email protected]21c3f7502013-03-23 03:29:511830
John Rummelldb5a7ef2018-05-16 00:28:011831 if (HasAudio()) {
Ted Meyerd5885f82019-07-16 19:19:171832 media_metrics_provider_->SetHasAudio(metadata.audio_decoder_config.codec());
John Rummelldb5a7ef2018-05-16 00:28:011833 RecordEncryptionScheme("Audio",
1834 metadata.audio_decoder_config.encryption_scheme());
1835 }
1836
Blink Reformat1c4d759e2017-04-09 16:34:541837 if (HasVideo()) {
Ted Meyerd5885f82019-07-16 19:19:171838 media_metrics_provider_->SetHasVideo(metadata.video_decoder_config.codec());
John Rummelldb5a7ef2018-05-16 00:28:011839 RecordEncryptionScheme("Video",
1840 metadata.video_decoder_config.encryption_scheme());
1841
liberato2fd111be2017-01-04 00:25:061842 if (overlay_enabled_) {
1843 // SurfaceView doesn't support rotated video, so transition back if
[email protected]c8d574722017-08-30 20:53:431844 // the video is now rotated. If |always_enable_overlays_|, we keep the
liberato2fd111be2017-01-04 00:25:061845 // overlay anyway so that the state machine keeps working.
[email protected]c8d574722017-08-30 20:53:431846 // TODO(liberato): verify if compositor feedback catches this. If so,
1847 // then we don't need this check.
1848 if (!always_enable_overlays_ && !DoesOverlaySupportMetadata())
liberato2fd111be2017-01-04 00:25:061849 DisableOverlay();
liberato2fd111be2017-01-04 00:25:061850 }
watkf835a792016-06-24 23:24:401851
[email protected]702d721d2018-10-25 21:55:271852 if (surface_layer_mode_ ==
Mounir Lamouri28d648102019-11-27 16:49:031853 blink::WebMediaPlayer::SurfaceLayerMode::kAlways) {
[email protected]702d721d2018-10-25 21:55:271854 ActivateSurfaceLayerForVideo();
1855 } else {
danakj6e669e782018-05-16 16:57:171856 DCHECK(!video_layer_);
Ted Meyer4a427632019-05-01 19:05:271857 // TODO(tmathmeyer) does this need support for reflections as well?
danakj25f030112018-05-11 18:26:541858 video_layer_ = cc::VideoLayer::Create(
Julien Isorce6c83d8de2017-10-12 13:11:291859 compositor_.get(),
Ted Meyer4a427632019-05-01 19:05:271860 pipeline_metadata_.video_decoder_config.video_transformation()
1861 .rotation);
danakj8bc61c72018-05-16 13:55:061862 video_layer_->SetContentsOpaque(opaque_);
danakj8d204a42018-05-18 18:05:351863 client_->SetCcLayer(video_layer_.get());
lethalantidote7f6009d2017-07-07 21:47:391864 }
[email protected]a8e2cb82012-08-17 00:02:391865 }
dalecurtis8e4dc682016-03-15 02:30:301866
xjzd3fe45a2016-10-12 18:26:371867 if (observer_)
xjz15b483f2017-01-12 00:21:361868 observer_->OnMetadataChanged(pipeline_metadata_);
xjzd3fe45a2016-10-12 18:26:371869
Dale Curtisc7d2a7d22018-01-11 20:01:051870 // TODO(dalecurtis): Don't create these until kReadyStateHaveFutureData; when
1871 // we create them early we just increase the chances of needing to throw them
1872 // away unnecessarily.
dalecurtis04bdb582016-08-17 22:15:231873 CreateWatchTimeReporter();
Chris Cunninghamd9df58e2017-08-29 00:04:231874 CreateVideoDecodeStatsReporter();
Dale Curtisc7d2a7d22018-01-11 20:01:051875
Dale Curtis1e7a02b42019-05-28 20:12:241876 // SetReadyState() may trigger all sorts of calls into this class (e.g.,
1877 // Play(), Pause(), etc) so do it last to avoid unexpected states during the
1878 // calls. An exception to this is UpdatePlayState(), which is safe to call and
1879 // needs to use the new ReadyState in its calculations.
Dale Curtis2fc01cc2019-05-20 22:53:521880 SetReadyState(WebMediaPlayer::kReadyStateHaveMetadata);
Dale Curtis1e7a02b42019-05-28 20:12:241881 UpdatePlayState();
[email protected]a8e2cb82012-08-17 00:02:391882}
1883
[email protected]69db58f2018-09-26 20:27:561884void WebMediaPlayerImpl::ActivateSurfaceLayerForVideo() {
1885 // Note that we might or might not already be in VideoLayer mode.
1886 DCHECK(!bridge_);
1887
1888 surface_layer_for_video_enabled_ = true;
1889
1890 // If we're in VideoLayer mode, then get rid of the layer.
1891 if (video_layer_) {
1892 client_->SetCcLayer(nullptr);
1893 video_layer_ = nullptr;
1894 }
1895
1896 bridge_ = std::move(create_bridge_callback_)
1897 .Run(this, compositor_->GetUpdateSubmissionStateCallback());
1898 bridge_->CreateSurfaceLayer();
1899
Ted Meyer4a427632019-05-01 19:05:271900 // TODO(tmathmeyer) does this need support for the reflection transformation
1901 // as well?
[email protected]69db58f2018-09-26 20:27:561902 vfc_task_runner_->PostTask(
1903 FROM_HERE,
Ted Meyer4a427632019-05-01 19:05:271904 base::BindOnce(
1905 &VideoFrameCompositor::EnableSubmission,
1906 base::Unretained(compositor_.get()), bridge_->GetSurfaceId(),
1907 bridge_->GetLocalSurfaceIdAllocationTime(),
1908 pipeline_metadata_.video_decoder_config.video_transformation()
1909 .rotation,
1910 IsInPictureInPicture()));
[email protected]69db58f2018-09-26 20:27:561911 bridge_->SetContentsOpaque(opaque_);
1912
1913 // If the element is already in Picture-in-Picture mode, it means that it
1914 // was set in this mode prior to this load, with a different
1915 // WebMediaPlayerImpl. The new player needs to send its id, size and
1916 // surface id to the browser process to make sure the states are properly
1917 // updated.
1918 // TODO(872056): the surface should be activated but for some reasons, it
1919 // does not. It is possible that this will no longer be needed after 872056
1920 // is fixed.
Dale Curtisca1b78f2019-01-15 03:11:261921 if (IsInPictureInPicture())
[email protected]69db58f2018-09-26 20:27:561922 OnSurfaceIdUpdated(bridge_->GetSurfaceId());
[email protected]69db58f2018-09-26 20:27:561923}
1924
Chris Cunninghamfc0d67e2019-07-22 20:29:161925void WebMediaPlayerImpl::OnBufferingStateChange(
1926 BufferingState state,
1927 BufferingStateChangeReason reason) {
1928 OnBufferingStateChangeInternal(state, reason, false);
Dale Curtis2dc6089a2018-03-26 16:47:581929}
1930
Chris Cunninghamd9df58e2017-08-29 00:04:231931void WebMediaPlayerImpl::CreateVideoDecodeStatsReporter() {
1932 // TODO(chcunningham): destroy reporter if we initially have video but the
1933 // track gets disabled. Currently not possible in default desktop Chrome.
1934 if (!HasVideo())
1935 return;
1936
Chris Cunningham89b4b762019-03-27 17:13:331937 // Only record stats from the local pipeline.
1938 if (is_flinging_ || is_remote_rendering_ || using_media_player_renderer_)
1939 return;
1940
Chris Cunninghamd9df58e2017-08-29 00:04:231941 // Stats reporter requires a valid config. We may not have one for HLS cases
1942 // where URL demuxer doesn't know details of the stream.
1943 if (!pipeline_metadata_.video_decoder_config.IsValidConfig())
1944 return;
1945
Chris Cunningham6c0ec292019-04-04 18:31:111946 // Profile must be known for use as index to save the reported stats.
Chris Cunningham5b1b67eb2019-03-23 03:24:411947 if (pipeline_metadata_.video_decoder_config.profile() ==
1948 VIDEO_CODEC_PROFILE_UNKNOWN) {
1949 return;
1950 }
1951
Chris Cunningham6c0ec292019-04-04 18:31:111952 // CdmConfig must be provided for use as index to save encrypted stats.
1953 if (is_encrypted_ && !cdm_config_) {
Chris Cunninghamd9df58e2017-08-29 00:04:231954 return;
Chris Cunningham6c0ec292019-04-04 18:31:111955 } else if (cdm_config_) {
1956 DCHECK(!key_system_.empty());
1957 }
Chris Cunninghamd9df58e2017-08-29 00:04:231958
Gyuyoung Kima040bc52019-10-30 01:14:351959 mojo::PendingRemote<mojom::VideoDecodeStatsRecorder> recorder;
Dale Curtis7e8a510d2017-12-14 19:19:481960 media_metrics_provider_->AcquireVideoDecodeStatsRecorder(
Gyuyoung Kima040bc52019-10-30 01:14:351961 recorder.InitWithNewPipeAndPassReceiver());
Chris Cunninghamc7c6a6d2017-11-23 14:06:451962
Chris Cunninghamd9df58e2017-08-29 00:04:231963 // Create capabilities reporter and synchronize its initial state.
1964 video_decode_stats_reporter_.reset(new VideoDecodeStatsReporter(
Chris Cunninghamc7c6a6d2017-11-23 14:06:451965 std::move(recorder),
Chris Cunninghamd9df58e2017-08-29 00:04:231966 base::Bind(&WebMediaPlayerImpl::GetPipelineStatistics,
1967 base::Unretained(this)),
Chris Cunningham5b1b67eb2019-03-23 03:24:411968 pipeline_metadata_.video_decoder_config.profile(),
Chris Cunningham6c0ec292019-04-04 18:31:111969 pipeline_metadata_.natural_size, key_system_, cdm_config_,
Hajime Hoshib5a26ee2018-05-14 12:47:511970 frame_->GetTaskRunner(blink::TaskType::kInternalMedia)));
Chris Cunninghamd9df58e2017-08-29 00:04:231971
1972 if (delegate_->IsFrameHidden())
1973 video_decode_stats_reporter_->OnHidden();
1974 else
1975 video_decode_stats_reporter_->OnShown();
1976
1977 if (paused_)
1978 video_decode_stats_reporter_->OnPaused();
1979 else
1980 video_decode_stats_reporter_->OnPlaying();
1981}
1982
hubbeb2d3efd2017-05-05 23:26:381983void WebMediaPlayerImpl::OnProgress() {
Chris Watkins1ffabc5f2017-05-10 20:52:091984 DVLOG(4) << __func__;
Dale Curtisad645f72019-09-06 23:28:161985
1986 // See IsPrerollAttemptNeeded() for more details. We can't use that method
1987 // here since it considers |preroll_attempt_start_time_| and for OnProgress()
1988 // events we must make the attempt -- since there may not be another event.
1989 if (highest_ready_state_ < ReadyState::kReadyStateHaveFutureData) {
hubbeb2d3efd2017-05-05 23:26:381990 // Reset the preroll attempt clock.
1991 preroll_attempt_pending_ = true;
1992 preroll_attempt_start_time_ = base::TimeTicks();
1993
1994 // Clear any 'stale' flag and give the pipeline a chance to resume. If we
1995 // are already resumed, this will cause |preroll_attempt_start_time_| to
1996 // be set.
1997 delegate_->ClearStaleFlag(delegate_id_);
1998 UpdatePlayState();
1999 } else if (ready_state_ == ReadyState::kReadyStateHaveFutureData &&
2000 CanPlayThrough()) {
2001 SetReadyState(WebMediaPlayer::kReadyStateHaveEnoughData);
2002 }
2003}
2004
2005bool WebMediaPlayerImpl::CanPlayThrough() {
2006 if (!base::FeatureList::IsEnabled(kSpecCompliantCanPlayThrough))
2007 return true;
2008 if (chunk_demuxer_)
2009 return true;
Dale Curtis4841c712018-12-13 18:14:052010 if (data_source_ && data_source_->AssumeFullyBuffered())
hubbeb2d3efd2017-05-05 23:26:382011 return true;
2012 // If we're not currently downloading, we have as much buffer as
2013 // we're ever going to get, which means we say we can play through.
2014 if (network_state_ == WebMediaPlayer::kNetworkStateIdle)
2015 return true;
Antonio Gomes81b56552019-05-15 22:15:282016 return buffered_data_source_host_->CanPlayThrough(
hubbeb2d3efd2017-05-05 23:26:382017 base::TimeDelta::FromSecondsD(CurrentTime()),
2018 base::TimeDelta::FromSecondsD(Duration()),
2019 playback_rate_ == 0.0 ? 1.0 : playback_rate_);
2020}
2021
Dale Curtisff576552018-03-30 02:32:442022void WebMediaPlayerImpl::OnBufferingStateChangeInternal(
2023 BufferingState state,
Chris Cunninghamfc0d67e2019-07-22 20:29:162024 BufferingStateChangeReason reason,
Dale Curtisff576552018-03-30 02:32:442025 bool for_suspended_start) {
Chris Cunninghamfc0d67e2019-07-22 20:29:162026 DVLOG(1) << __func__ << "(" << state << ", " << reason << ")";
alokp967c902452016-05-06 05:21:372027 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]b8877772014-03-26 20:17:152028
Ted Meyer742212b82018-08-22 17:21:422029 // Ignore buffering state changes caused by back-to-back seeking, so as not
2030 // to assume the second seek has finished when it was only the first seek.
Antonio Gomes81b56552019-05-15 22:15:282031 if (pipeline_controller_->IsPendingSeek())
[email protected]ba7d5f92014-06-24 05:37:402032 return;
[email protected]b8877772014-03-26 20:17:152033
Dale Curtisff576552018-03-30 02:32:442034 auto log_event = media_log_->CreateBufferingStateChangedEvent(
Chris Cunninghamfc0d67e2019-07-22 20:29:162035 "pipeline_buffering_state", state, reason);
Dale Curtisff576552018-03-30 02:32:442036 log_event->params.SetBoolean("for_suspended_start", for_suspended_start);
2037 media_log_->AddEvent(std::move(log_event));
dalecurtis869bf2f2017-01-10 18:01:102038
Ted Meyerd5885f82019-07-16 19:19:172039 if (state == BUFFERING_HAVE_ENOUGH && !for_suspended_start)
2040 media_metrics_provider_->SetHaveEnough();
2041
chcunninghameb270c92016-07-15 01:00:452042 if (state == BUFFERING_HAVE_ENOUGH) {
John Chen5b164a02017-11-01 00:36:092043 TRACE_EVENT1("media", "WebMediaPlayerImpl::BufferingHaveEnough", "id",
2044 media_log_->id());
Dale Curtisff576552018-03-30 02:32:442045 // The SetReadyState() call below may clear
2046 // |skip_metrics_due_to_startup_suspend_| so report this first.
2047 if (!have_reported_time_to_play_ready_ &&
2048 !skip_metrics_due_to_startup_suspend_) {
2049 DCHECK(!for_suspended_start);
Dale Curtis3899090ea2018-01-12 00:10:352050 have_reported_time_to_play_ready_ = true;
2051 const base::TimeDelta elapsed = base::TimeTicks::Now() - load_start_time_;
2052 media_metrics_provider_->SetTimeToPlayReady(elapsed);
2053 RecordTimingUMA("Media.TimeToPlayReady", elapsed);
2054 }
[email protected]ba7d5f92014-06-24 05:37:402055
Dale Curtisff576552018-03-30 02:32:442056 // Warning: This call may be re-entrant.
2057 SetReadyState(CanPlayThrough() ? WebMediaPlayer::kReadyStateHaveEnoughData
2058 : WebMediaPlayer::kReadyStateHaveFutureData);
2059
Dale Curtis18ad391b2019-05-30 23:25:092060 // Let the DataSource know we have enough data -- this is the only function
2061 // during which we advance to (or past) the kReadyStateHaveEnoughData state.
2062 // It may use this information to update buffer sizes or release unused
2063 // network connections.
2064 MaybeUpdateBufferSizesForPlayback();
Dale Curtis04769ca2019-05-25 00:38:102065 if (mb_data_source_ && !client_->CouldPlayIfEnoughData()) {
2066 // For LazyLoad this will be handled during OnPipelineSuspended().
2067 if (for_suspended_start && did_lazy_load_)
2068 DCHECK(!have_enough_after_lazy_load_cb_.IsCancelled());
2069 else
2070 mb_data_source_->OnBufferingHaveEnough(false);
2071 }
dalecurtis849cf4b22015-03-27 18:35:452072
chcunninghameb270c92016-07-15 01:00:452073 // Blink expects a timeChanged() in response to a seek().
sandersd35d2c3f2017-01-14 02:04:422074 if (should_notify_time_changed_) {
2075 should_notify_time_changed_ = false;
Blink Reformat1c4d759e2017-04-09 16:34:542076 client_->TimeChanged();
sandersd35d2c3f2017-01-14 02:04:422077 }
dalecurtis0f0097a2015-12-01 17:40:472078
chcunninghameb270c92016-07-15 01:00:452079 // Once we have enough, start reporting the total memory usage. We'll also
2080 // report once playback starts.
2081 ReportMemoryUsage();
dalecurtis9d638a12016-08-30 06:20:552082
dalecurtis4f6d14d2017-02-22 17:42:222083 // Report the amount of time it took to leave the underflow state.
2084 if (underflow_timer_) {
Dale Curtisc9069622019-10-24 20:20:502085 auto elapsed = underflow_timer_->Elapsed();
2086 RecordUnderflowDuration(elapsed);
2087 watch_time_reporter_->OnUnderflowComplete(elapsed);
dalecurtis9d638a12016-08-30 06:20:552088 underflow_timer_.reset();
2089 }
chcunninghameb270c92016-07-15 01:00:452090 } else {
2091 // Buffering has underflowed.
2092 DCHECK_EQ(state, BUFFERING_HAVE_NOTHING);
dalecurtisacd77d62016-09-09 23:23:142093
dalecurtisd06eabc2017-02-24 23:43:292094 // Report the number of times we've entered the underflow state. Ensure we
2095 // only report the value when transitioning from HAVE_ENOUGH to
2096 // HAVE_NOTHING.
Dale Curtis6995b862017-05-31 22:20:082097 if (ready_state_ == WebMediaPlayer::kReadyStateHaveEnoughData &&
2098 !seeking_) {
dalecurtisacd77d62016-09-09 23:23:142099 underflow_timer_.reset(new base::ElapsedTimer());
Dale Curtis6995b862017-05-31 22:20:082100 watch_time_reporter_->OnUnderflow();
2101 }
dalecurtisacd77d62016-09-09 23:23:142102
chcunninghameb270c92016-07-15 01:00:452103 // It shouldn't be possible to underflow if we've not advanced past
2104 // HAVE_CURRENT_DATA.
Blink Reformat1c4d759e2017-04-09 16:34:542105 DCHECK_GT(highest_ready_state_, WebMediaPlayer::kReadyStateHaveCurrentData);
2106 SetReadyState(WebMediaPlayer::kReadyStateHaveCurrentData);
chcunninghameb270c92016-07-15 01:00:452107 }
sandersd50a635e2016-04-04 22:50:092108
2109 UpdatePlayState();
[email protected]b8877772014-03-26 20:17:152110}
2111
alokp967c902452016-05-06 05:21:372112void WebMediaPlayerImpl::OnDurationChange() {
acolwellb4034942014-08-28 15:42:432113 DCHECK(main_task_runner_->BelongsToCurrentThread());
alokp967c902452016-05-06 05:21:372114
John Delaney2371b452018-12-13 04:30:332115 if (frame_->IsAdSubframe()) {
2116 UMA_HISTOGRAM_CUSTOM_TIMES("Ads.Media.Duration", GetPipelineMediaDuration(),
2117 base::TimeDelta::FromMilliseconds(1),
2118 base::TimeDelta::FromDays(1),
2119 50 /* bucket_count */);
2120 }
2121
alokp967c902452016-05-06 05:21:372122 // TODO(sandersd): We should call delegate_->DidPlay() with the new duration,
2123 // especially if it changed from <5s to >5s.
Blink Reformat1c4d759e2017-04-09 16:34:542124 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
alokp967c902452016-05-06 05:21:372125 return;
2126
Blink Reformat1c4d759e2017-04-09 16:34:542127 client_->DurationChanged();
Dale Curtisaebaeea2018-07-19 23:42:112128 if (watch_time_reporter_)
2129 watch_time_reporter_->OnDurationChanged(GetPipelineMediaDuration());
Becca Hughes7a85bf22019-07-24 16:16:582130
2131 // The duration has changed so we should update the media position state.
2132 UpdateMediaPositionState();
[email protected]81bb3322011-07-21 15:55:502133}
2134
alokp967c902452016-05-06 05:21:372135void WebMediaPlayerImpl::OnAddTextTrack(const TextTrackConfig& config,
2136 const AddTextTrackDoneCB& done_cb) {
acolwellb4034942014-08-28 15:42:432137 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]71537722013-05-23 06:47:532138
[email protected]8a561062013-11-22 01:19:312139 const WebInbandTextTrackImpl::Kind web_kind =
2140 static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
Blink Reformat1c4d759e2017-04-09 16:34:542141 const blink::WebString web_label = blink::WebString::FromUTF8(config.label());
[email protected]8a561062013-11-22 01:19:312142 const blink::WebString web_language =
Blink Reformat1c4d759e2017-04-09 16:34:542143 blink::WebString::FromUTF8(config.language());
2144 const blink::WebString web_id = blink::WebString::FromUTF8(config.id());
[email protected]71537722013-05-23 06:47:532145
dcheng3076abbf2016-04-22 20:42:392146 std::unique_ptr<WebInbandTextTrackImpl> web_inband_text_track(
henriks9cce5fa2014-12-12 09:35:302147 new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id));
[email protected]8a561062013-11-22 01:19:312148
Dale Curtisca1b78f2019-01-15 03:11:262149 std::unique_ptr<TextTrack> text_track(new TextTrackImpl(
dcheng652f5ff2015-12-27 08:54:002150 main_task_runner_, client_, std::move(web_inband_text_track)));
[email protected]8a561062013-11-22 01:19:312151
dcheng652f5ff2015-12-27 08:54:002152 done_cb.Run(std::move(text_track));
[email protected]71537722013-05-23 06:47:532153}
2154
Xiaohan Wang640b41d2018-12-18 19:00:462155void WebMediaPlayerImpl::OnWaiting(WaitingReason reason) {
alokp967c902452016-05-06 05:21:372156 DCHECK(main_task_runner_->BelongsToCurrentThread());
2157
Xiaohan Wang640b41d2018-12-18 19:00:462158 switch (reason) {
Xiaohan Wangb54a75282019-10-04 21:34:432159 case WaitingReason::kNoCdm:
Xiaohan Wang640b41d2018-12-18 19:00:462160 case WaitingReason::kNoDecryptionKey:
2161 encrypted_client_->DidBlockPlaybackWaitingForKey();
2162 // TODO(jrummell): didResumePlaybackBlockedForKey() should only be called
2163 // when a key has been successfully added (e.g. OnSessionKeysChange() with
2164 // |has_additional_usable_key| = true). http://crbug.com/461903
2165 encrypted_client_->DidResumePlaybackBlockedForKey();
2166 return;
Xiaohan Wang640b41d2018-12-18 19:00:462167
Xiaohan Wanga7224d62019-01-04 22:22:302168 // Ideally this should be handled by PipelineController directly without
2169 // being proxied here. But currently Pipeline::Client (|this|) is passed to
2170 // PipelineImpl directly without going through |pipeline_controller_|,
2171 // making it difficult to do.
2172 // TODO(xhwang): Handle this in PipelineController when we have a clearer
2173 // picture on how to refactor WebMediaPlayerImpl, PipelineController and
2174 // PipelineImpl.
2175 case WaitingReason::kDecoderStateLost:
Antonio Gomes81b56552019-05-15 22:15:282176 pipeline_controller_->OnDecoderStateLost();
Xiaohan Wanga7224d62019-01-04 22:22:302177 return;
2178 }
alokp967c902452016-05-06 05:21:372179}
2180
alokp5d86e9b2016-05-17 20:20:412181void WebMediaPlayerImpl::OnVideoNaturalSizeChange(const gfx::Size& size) {
2182 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:542183 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
alokp5d86e9b2016-05-17 20:20:412184
Chris Cunningham038548b2017-07-10 22:36:302185 TRACE_EVENT0("media", "WebMediaPlayerImpl::OnVideoNaturalSizeChange");
xhwang60802652017-04-19 07:29:582186
xjz15b483f2017-01-12 00:21:362187 // The input |size| is from the decoded video frame, which is the original
2188 // natural size and need to be rotated accordingly.
Julien Isorce6c83d8de2017-10-12 13:11:292189 gfx::Size rotated_size = GetRotatedVideoSize(
Ted Meyer4a427632019-05-01 19:05:272190 pipeline_metadata_.video_decoder_config.video_transformation().rotation,
2191 size);
sandersd2c478422016-08-02 01:19:252192
xhwang60802652017-04-19 07:29:582193 RecordVideoNaturalSize(rotated_size);
2194
2195 gfx::Size old_size = pipeline_metadata_.natural_size;
2196 if (rotated_size == old_size)
alokp5d86e9b2016-05-17 20:20:412197 return;
2198
xjz516ef6d2017-01-07 00:23:062199 pipeline_metadata_.natural_size = rotated_size;
Dan Sanders7ef5d0f2019-05-03 18:30:112200
2201 if (using_media_player_renderer_ && old_size.IsEmpty()) {
2202 // If we are using MediaPlayerRenderer and this is the first size change, we
2203 // now know that there is a video track. This condition is paired with code
2204 // in CreateWatchTimeReporter() that guesses the existence of a video track.
2205 CreateWatchTimeReporter();
2206 } else {
Dan Sanders7ef5d0f2019-05-03 18:30:112207 UpdateSecondaryProperties();
2208 }
dalecurtis25405562017-04-14 23:35:112209
Chris Cunningham5b1b67eb2019-03-23 03:24:412210 if (video_decode_stats_reporter_ &&
2211 !video_decode_stats_reporter_->MatchesBucketedNaturalSize(
2212 pipeline_metadata_.natural_size)) {
2213 CreateVideoDecodeStatsReporter();
2214 }
Chris Cunninghamd9df58e2017-08-29 00:04:232215
Blink Reformat1c4d759e2017-04-09 16:34:542216 client_->SizeChanged();
xjz516ef6d2017-01-07 00:23:062217
xjz15b483f2017-01-12 00:21:362218 if (observer_)
2219 observer_->OnMetadataChanged(pipeline_metadata_);
peconn257951522017-06-09 18:24:592220
2221 delegate_->DidPlayerSizeChange(delegate_id_, NaturalSize());
alokp5d86e9b2016-05-17 20:20:412222}
2223
2224void WebMediaPlayerImpl::OnVideoOpacityChange(bool opaque) {
2225 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:542226 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
alokp5d86e9b2016-05-17 20:20:412227
2228 opaque_ = opaque;
Dale Curtis357630f22019-01-18 01:10:172229 if (!surface_layer_for_video_enabled_ && video_layer_)
2230 video_layer_->SetContentsOpaque(opaque_);
2231 else if (bridge_->GetCcLayer())
CJ DiMeglioa2b13fbc2018-06-27 00:50:592232 bridge_->SetContentsOpaque(opaque_);
alokp5d86e9b2016-05-17 20:20:412233}
2234
Chris Cunningham038548b2017-07-10 22:36:302235void WebMediaPlayerImpl::OnAudioConfigChange(const AudioDecoderConfig& config) {
2236 DCHECK(main_task_runner_->BelongsToCurrentThread());
2237 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
2238
Dale Curtisccfd0cca2017-08-31 01:27:562239 const bool codec_change =
2240 pipeline_metadata_.audio_decoder_config.codec() != config.codec();
Chris Cunningham038548b2017-07-10 22:36:302241 pipeline_metadata_.audio_decoder_config = config;
2242
2243 if (observer_)
2244 observer_->OnMetadataChanged(pipeline_metadata_);
Dale Curtisccfd0cca2017-08-31 01:27:562245
2246 if (codec_change)
Dale Curtis96d6e9382018-07-18 18:01:072247 UpdateSecondaryProperties();
Chris Cunningham038548b2017-07-10 22:36:302248}
2249
2250void WebMediaPlayerImpl::OnVideoConfigChange(const VideoDecoderConfig& config) {
2251 DCHECK(main_task_runner_->BelongsToCurrentThread());
2252 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
2253
Dale Curtisccfd0cca2017-08-31 01:27:562254 const bool codec_change =
2255 pipeline_metadata_.video_decoder_config.codec() != config.codec();
Chris Cunningham5b1b67eb2019-03-23 03:24:412256 const bool codec_profile_change =
2257 pipeline_metadata_.video_decoder_config.profile() != config.profile();
Dale Curtisccfd0cca2017-08-31 01:27:562258
Chris Cunningham038548b2017-07-10 22:36:302259 pipeline_metadata_.video_decoder_config = config;
2260
2261 if (observer_)
2262 observer_->OnMetadataChanged(pipeline_metadata_);
Chris Cunninghamd9df58e2017-08-29 00:04:232263
Dale Curtisccfd0cca2017-08-31 01:27:562264 if (codec_change)
Dale Curtis96d6e9382018-07-18 18:01:072265 UpdateSecondaryProperties();
Chris Cunningham5b1b67eb2019-03-23 03:24:412266
2267 if (video_decode_stats_reporter_ && codec_profile_change)
2268 CreateVideoDecodeStatsReporter();
Chris Cunningham038548b2017-07-10 22:36:302269}
2270
avayvodeecec52c2017-02-14 01:25:092271void WebMediaPlayerImpl::OnVideoAverageKeyframeDistanceUpdate() {
2272 UpdateBackgroundVideoOptimizationState();
2273}
2274
Ted Meyerd5885f82019-07-16 19:19:172275void WebMediaPlayerImpl::OnAudioDecoderChange(const PipelineDecoderInfo& info) {
2276 media_metrics_provider_->SetAudioPipelineInfo(info);
2277 if (info.decoder_name == audio_decoder_name_)
Dale Curtisc7d2a7d22018-01-11 20:01:052278 return;
2279
Ted Meyerd5885f82019-07-16 19:19:172280 audio_decoder_name_ = info.decoder_name;
Dale Curtisc7d2a7d22018-01-11 20:01:052281
2282 // If there's no current reporter, there's nothing to be done.
2283 if (!watch_time_reporter_)
2284 return;
2285
Dale Curtis96d6e9382018-07-18 18:01:072286 UpdateSecondaryProperties();
Dale Curtisc7d2a7d22018-01-11 20:01:052287}
2288
Ted Meyerd5885f82019-07-16 19:19:172289void WebMediaPlayerImpl::OnVideoDecoderChange(const PipelineDecoderInfo& info) {
2290 media_metrics_provider_->SetVideoPipelineInfo(info);
2291 if (info.decoder_name == video_decoder_name_)
Dale Curtisc7d2a7d22018-01-11 20:01:052292 return;
2293
Ted Meyerd5885f82019-07-16 19:19:172294 video_decoder_name_ = info.decoder_name;
Dale Curtisc7d2a7d22018-01-11 20:01:052295
2296 // If there's no current reporter, there's nothing to be done.
2297 if (!watch_time_reporter_)
2298 return;
2299
Dale Curtis96d6e9382018-07-18 18:01:072300 UpdateSecondaryProperties();
Dale Curtisc7d2a7d22018-01-11 20:01:052301}
2302
sandersd35d2c3f2017-01-14 02:04:422303void WebMediaPlayerImpl::OnFrameHidden() {
sandersd1e49fb62015-12-12 01:18:062304 DCHECK(main_task_runner_->BelongsToCurrentThread());
avayvod39c102402016-11-23 21:43:132305
avayvod65fad272017-02-24 01:00:482306 // Backgrounding a video requires a user gesture to resume playback.
2307 if (IsHidden())
2308 video_locked_when_paused_when_hidden_ = true;
2309
dalecurtis04bdb582016-08-17 22:15:232310 if (watch_time_reporter_)
2311 watch_time_reporter_->OnHidden();
avayvod48a8be52016-08-04 19:52:502312
Chris Cunninghamd9df58e2017-08-29 00:04:232313 if (video_decode_stats_reporter_)
2314 video_decode_stats_reporter_->OnHidden();
2315
avayvod65fad272017-02-24 01:00:482316 UpdateBackgroundVideoOptimizationState();
sandersd50a635e2016-04-04 22:50:092317 UpdatePlayState();
dalecurtis8b8505e72016-06-10 21:59:172318
2319 // Schedule suspended playing media to be paused if the user doesn't come back
2320 // to it within some timeout period to avoid any autoplay surprises.
2321 ScheduleIdlePauseTimer();
Dale Curtisca1b78f2019-01-15 03:11:262322
2323 // Notify the compositor of our page visibility status.
2324 vfc_task_runner_->PostTask(
2325 FROM_HERE,
2326 base::BindOnce(&VideoFrameCompositor::SetIsPageVisible,
2327 base::Unretained(compositor_.get()), !IsHidden()));
sandersd1e49fb62015-12-12 01:18:062328}
2329
sandersd35d2c3f2017-01-14 02:04:422330void WebMediaPlayerImpl::OnFrameClosed() {
sandersd1e49fb62015-12-12 01:18:062331 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]28347e72017-06-27 17:30:112332
sandersd35d2c3f2017-01-14 02:04:422333 UpdatePlayState();
2334}
2335
2336void WebMediaPlayerImpl::OnFrameShown() {
2337 DCHECK(main_task_runner_->BelongsToCurrentThread());
2338 background_pause_timer_.Stop();
2339
avayvod65fad272017-02-24 01:00:482340 // Foreground videos don't require user gesture to continue playback.
2341 video_locked_when_paused_when_hidden_ = false;
2342
dalecurtis04bdb582016-08-17 22:15:232343 if (watch_time_reporter_)
2344 watch_time_reporter_->OnShown();
2345
Chris Cunninghamd9df58e2017-08-29 00:04:232346 if (video_decode_stats_reporter_)
2347 video_decode_stats_reporter_->OnShown();
2348
Dale Curtisca1b78f2019-01-15 03:11:262349 // Notify the compositor of our page visibility status.
2350 vfc_task_runner_->PostTask(
2351 FROM_HERE,
2352 base::BindOnce(&VideoFrameCompositor::SetIsPageVisible,
2353 base::Unretained(compositor_.get()), !IsHidden()));
2354
Dale Curtisdcbb81a2017-08-18 01:06:122355 UpdateBackgroundVideoOptimizationState();
avayvod65fad272017-02-24 01:00:482356
avayvod2135a642017-01-13 00:17:142357 if (paused_when_hidden_) {
2358 paused_when_hidden_ = false;
2359 OnPlay(); // Calls UpdatePlayState() so return afterwards.
2360 return;
2361 }
2362
sandersd50a635e2016-04-04 22:50:092363 UpdatePlayState();
sandersd1e49fb62015-12-12 01:18:062364}
2365
sandersd35d2c3f2017-01-14 02:04:422366void WebMediaPlayerImpl::OnIdleTimeout() {
dalecurtis0431cbf2016-03-12 01:19:432367 DCHECK(main_task_runner_->BelongsToCurrentThread());
2368
Dale Curtis99a9b482018-02-01 02:23:282369 // This should never be called when stale state testing overrides are used.
2370 DCHECK(!stale_state_override_for_testing_.has_value());
2371
sandersd35d2c3f2017-01-14 02:04:422372 // If we are attempting preroll, clear the stale flag.
2373 if (IsPrerollAttemptNeeded()) {
tguilbert1bb1c782017-01-23 21:15:112374 delegate_->ClearStaleFlag(delegate_id_);
sandersd35d2c3f2017-01-14 02:04:422375 return;
watkd026f792016-11-05 00:28:512376 }
sandersd50a635e2016-04-04 22:50:092377
sandersd35d2c3f2017-01-14 02:04:422378 UpdatePlayState();
dalecurtis0431cbf2016-03-12 01:19:432379}
2380
dalecurtisbb3eaac2016-01-27 21:10:252381void WebMediaPlayerImpl::OnPlay() {
Mounir Lamouri703106e2018-05-30 14:31:092382 client_->RequestPlay();
dalecurtisbb3eaac2016-01-27 21:10:252383}
2384
2385void WebMediaPlayerImpl::OnPause() {
Mounir Lamouri703106e2018-05-30 14:31:092386 client_->RequestPause();
dalecurtisbb3eaac2016-01-27 21:10:252387}
2388
François Beaufortb4fe7c62019-02-27 08:19:442389void WebMediaPlayerImpl::OnMuted(bool muted) {
2390 client_->RequestMuted(muted);
2391}
2392
Alec Douglas316cce42017-10-31 13:28:082393void WebMediaPlayerImpl::OnSeekForward(double seconds) {
2394 DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
2395 client_->RequestSeek(CurrentTime() + seconds);
2396}
2397
2398void WebMediaPlayerImpl::OnSeekBackward(double seconds) {
2399 DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
2400 client_->RequestSeek(CurrentTime() - seconds);
2401}
2402
dalecurtisbb3eaac2016-01-27 21:10:252403void WebMediaPlayerImpl::OnVolumeMultiplierUpdate(double multiplier) {
2404 volume_multiplier_ = multiplier;
Blink Reformat1c4d759e2017-04-09 16:34:542405 SetVolume(volume_);
dalecurtisbb3eaac2016-01-27 21:10:252406}
2407
zqzhang8ac49002017-03-16 21:51:352408void WebMediaPlayerImpl::OnBecamePersistentVideo(bool value) {
Blink Reformat1c4d759e2017-04-09 16:34:542409 client_->OnBecamePersistentVideo(value);
[email protected]6490e2d12019-01-14 19:18:372410 overlay_info_.is_persistent_video = value;
2411 MaybeSendOverlayInfoToDecoder();
zqzhang8ac49002017-03-16 21:51:352412}
2413
watkdee516f2016-02-18 02:22:192414void WebMediaPlayerImpl::ScheduleRestart() {
sandersd50a635e2016-04-04 22:50:092415 // TODO(watk): All restart logic should be moved into PipelineController.
Antonio Gomes81b56552019-05-15 22:15:282416 if (pipeline_controller_->IsPipelineRunning() &&
2417 !pipeline_controller_->IsPipelineSuspended()) {
watkdee516f2016-02-18 02:22:192418 pending_suspend_resume_cycle_ = true;
sandersd50a635e2016-04-04 22:50:092419 UpdatePlayState();
watkdee516f2016-02-18 02:22:192420 }
2421}
2422
Blink Reformat1c4d759e2017-04-09 16:34:542423void WebMediaPlayerImpl::RequestRemotePlaybackDisabled(bool disabled) {
miu77f914c2016-11-19 23:56:182424 if (observer_)
2425 observer_->OnRemotePlaybackDisabled(disabled);
2426}
2427
Thomas Guilbert7350fdad2019-01-29 23:09:242428#if defined(OS_ANDROID)
Thomas Guilbertb341bae02018-05-09 00:02:132429void WebMediaPlayerImpl::FlingingStarted() {
2430 DCHECK(main_task_runner_->BelongsToCurrentThread());
2431 DCHECK(!disable_pipeline_auto_suspend_);
2432 disable_pipeline_auto_suspend_ = true;
2433
Thomas Guilbert29ae1a902018-10-20 01:53:382434 is_flinging_ = true;
2435
Thomas Guilbertb341bae02018-05-09 00:02:132436 // Capabilities reporting should only be performed for local playbacks.
2437 video_decode_stats_reporter_.reset();
2438
2439 // Requests to restart media pipeline. A flinging renderer will be created via
2440 // the |renderer_factory_selector_|.
2441 ScheduleRestart();
2442}
2443
2444void WebMediaPlayerImpl::FlingingStopped() {
2445 DCHECK(main_task_runner_->BelongsToCurrentThread());
2446 DCHECK(disable_pipeline_auto_suspend_);
2447 disable_pipeline_auto_suspend_ = false;
2448
Thomas Guilbert29ae1a902018-10-20 01:53:382449 is_flinging_ = false;
2450
Thomas Guilbertb341bae02018-05-09 00:02:132451 CreateVideoDecodeStatsReporter();
2452
2453 ScheduleRestart();
2454}
Thomas Guilbert901808982019-07-03 20:38:182455
2456void WebMediaPlayerImpl::OnRemotePlayStateChange(MediaStatus::State state) {
2457 DCHECK(is_flinging_);
Thomas Guilbertf6d0702e2019-09-12 23:40:142458 DCHECK(main_task_runner_->BelongsToCurrentThread());
Thomas Guilbert901808982019-07-03 20:38:182459
2460 if (state == MediaStatus::State::PLAYING && Paused()) {
2461 DVLOG(1) << __func__ << " requesting PLAY.";
2462 client_->RequestPlay();
2463 } else if (state == MediaStatus::State::PAUSED && !Paused()) {
2464 DVLOG(1) << __func__ << " requesting PAUSE.";
2465 client_->RequestPause();
2466 }
2467}
Thomas Guilbert7350fdad2019-01-29 23:09:242468#endif // defined(OS_ANDROID)
hubbee4027f92016-05-19 05:18:132469
Blink Reformat1c4d759e2017-04-09 16:34:542470void WebMediaPlayerImpl::SetPoster(const blink::WebURL& poster) {
Dan Sanderscd8981c2017-08-31 22:37:022471 has_poster_ = !poster.IsEmpty();
Dan Sanderscd8981c2017-08-31 22:37:022472}
xjzc102fd82017-01-04 20:13:532473
[email protected]fee8a902014-06-03 13:43:362474void WebMediaPlayerImpl::DataSourceInitialized(bool success) {
pkastingf5279482016-07-27 02:18:202475 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:432476 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]a9415292012-01-19 19:55:202477
Thomas Guilberta8a6e922019-02-01 00:02:472478 if (observer_ && mb_data_source_)
Dale Curtis4841c712018-12-13 18:14:052479 observer_->OnDataSourceInitialized(mb_data_source_->GetUrlAfterRedirects());
Anton Vayvod09fa66e2017-07-20 23:02:122480
[email protected]d250190da3b2012-07-23 22:57:302481 if (!success) {
Blink Reformat1c4d759e2017-04-09 16:34:542482 SetNetworkState(WebMediaPlayer::kNetworkStateFormatError);
Dale Curtis74612b72017-12-14 20:56:192483 media_metrics_provider_->OnError(PIPELINE_ERROR_NETWORK);
sandersd50a635e2016-04-04 22:50:092484
2485 // Not really necessary, since the pipeline was never started, but it at
2486 // least this makes sure that the error handling code is in sync.
2487 UpdatePlayState();
2488
[email protected]a9415292012-01-19 19:55:202489 return;
2490 }
2491
hubbee2cc88c092017-07-14 23:10:412492 // No point in preloading data as we'll probably just throw it away anyways.
Dale Curtis4841c712018-12-13 18:14:052493 if (IsStreaming() && preload_ > MultibufferDataSource::METADATA &&
2494 mb_data_source_) {
2495 mb_data_source_->SetPreload(MultibufferDataSource::METADATA);
hubbee2cc88c092017-07-14 23:10:412496 }
2497
[email protected]ef8394c2013-08-21 20:26:302498 StartPipeline();
[email protected]a9415292012-01-19 19:55:202499}
2500
[email protected]122f40252012-06-12 05:01:562501void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
hubbeb2d3efd2017-05-05 23:26:382502 DVLOG(1) << __func__ << "(" << is_downloading << ")";
Blink Reformat1c4d759e2017-04-09 16:34:542503 if (!is_downloading && network_state_ == WebMediaPlayer::kNetworkStateLoading)
2504 SetNetworkState(WebMediaPlayer::kNetworkStateIdle);
2505 else if (is_downloading &&
2506 network_state_ == WebMediaPlayer::kNetworkStateIdle)
2507 SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
hubbeb2d3efd2017-05-05 23:26:382508 if (ready_state_ == ReadyState::kReadyStateHaveFutureData && !is_downloading)
2509 SetReadyState(WebMediaPlayer::kReadyStateHaveEnoughData);
[email protected]122f40252012-06-12 05:01:562510}
2511
liberato2ff93ad2017-05-17 07:28:242512void WebMediaPlayerImpl::OnOverlayRoutingToken(
2513 const base::UnguessableToken& token) {
2514 DCHECK(overlay_mode_ == OverlayMode::kUseAndroidOverlay);
liberatofe8f9692017-06-08 19:17:362515 // TODO(liberato): |token| should already be a RoutingToken.
2516 overlay_routing_token_is_pending_ = false;
2517 overlay_routing_token_ = OverlayInfo::RoutingToken(token);
liberato2ff93ad2017-05-17 07:28:242518 MaybeSendOverlayInfoToDecoder();
2519}
2520
2521void WebMediaPlayerImpl::OnOverlayInfoRequested(
dalecurtis4b632fce22016-11-10 00:52:172522 bool decoder_requires_restart_for_overlay,
liberato2ff93ad2017-05-17 07:28:242523 const ProvideOverlayInfoCB& provide_overlay_info_cb) {
watkdee516f2016-02-18 02:22:192524 DCHECK(main_task_runner_->BelongsToCurrentThread());
watkdee516f2016-02-18 02:22:192525
Chris Watkins557f84d2017-09-16 02:31:462526 // If we get a non-null cb, a decoder is initializing and requires overlay
2527 // info. If we get a null cb, a previously initialized decoder is
2528 // unregistering for overlay info updates.
Dale Curtise25163812018-09-21 22:13:392529 if (!provide_overlay_info_cb) {
tsunghungee562e92016-07-20 18:03:312530 decoder_requires_restart_for_overlay_ = false;
liberato2ff93ad2017-05-17 07:28:242531 provide_overlay_info_cb_.Reset();
watkdee516f2016-02-18 02:22:192532 return;
2533 }
2534
dalecurtis4b632fce22016-11-10 00:52:172535 // If |decoder_requires_restart_for_overlay| is true, we must restart the
2536 // pipeline for fullscreen transitions. The decoder is unable to switch
2537 // surfaces otherwise. If false, we simply need to tell the decoder about the
2538 // new surface and it will handle things seamlessly.
Chris Watkins557f84d2017-09-16 02:31:462539 // For encrypted video we pretend that the decoder doesn't require a restart
2540 // because it needs an overlay all the time anyway. We'll switch into
2541 // |always_enable_overlays_| mode below.
2542 decoder_requires_restart_for_overlay_ =
2543 (overlay_mode_ == OverlayMode::kUseAndroidOverlay && is_encrypted_)
2544 ? false
2545 : decoder_requires_restart_for_overlay;
liberato2ff93ad2017-05-17 07:28:242546 provide_overlay_info_cb_ = provide_overlay_info_cb;
dalecurtis4b632fce22016-11-10 00:52:172547
Chris Watkins557f84d2017-09-16 02:31:462548 // If the decoder doesn't require restarts for surface transitions, and we're
2549 // using AndroidOverlay mode, we can always enable the overlay and the decoder
2550 // can choose whether or not to use it. Otherwise, we'll restart the decoder
2551 // and enable the overlay on fullscreen transitions.
[email protected]77568482017-06-21 21:16:522552 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay &&
Chris Watkins557f84d2017-09-16 02:31:462553 !decoder_requires_restart_for_overlay_) {
[email protected]c8d574722017-08-30 20:53:432554 always_enable_overlays_ = true;
[email protected]77568482017-06-21 21:16:522555 if (!overlay_enabled_)
2556 EnableOverlay();
2557 }
2558
Chris Watkins557f84d2017-09-16 02:31:462559 // Send the overlay info if we already have it. If not, it will be sent later.
liberato2ff93ad2017-05-17 07:28:242560 MaybeSendOverlayInfoToDecoder();
2561}
2562
2563void WebMediaPlayerImpl::MaybeSendOverlayInfoToDecoder() {
2564 // If the decoder didn't request overlay info, then don't send it.
2565 if (!provide_overlay_info_cb_)
dalecurtis4b632fce22016-11-10 00:52:172566 return;
2567
liberato2ff93ad2017-05-17 07:28:242568 // We should send the overlay info as long as we know it. This includes the
2569 // case where |!overlay_enabled_|, since we want to tell the decoder to avoid
2570 // using overlays. Assuming that the decoder has requested info, the only
2571 // case in which we don't want to send something is if we've requested the
2572 // info but not received it yet. Then, we should wait until we do.
liberatofe8f9692017-06-08 19:17:362573 //
2574 // Initialization requires this; AVDA should start with enough info to make an
2575 // overlay, so that (pre-M) the initial codec is created with the right output
2576 // surface; it can't switch later.
[email protected]f7df5b342018-07-13 20:22:132577 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberatofe8f9692017-06-08 19:17:362578 if (overlay_routing_token_is_pending_)
liberato2ff93ad2017-05-17 07:28:242579 return;
liberatofe8f9692017-06-08 19:17:362580
2581 overlay_info_.routing_token = overlay_routing_token_;
liberato2ff93ad2017-05-17 07:28:242582 }
2583
liberato2ff93ad2017-05-17 07:28:242584 // If restart is required, the callback is one-shot only.
2585 if (decoder_requires_restart_for_overlay_) {
Dale Curtise25163812018-09-21 22:13:392586 std::move(provide_overlay_info_cb_).Run(overlay_info_);
liberato2ff93ad2017-05-17 07:28:242587 } else {
liberatofe8f9692017-06-08 19:17:362588 provide_overlay_info_cb_.Run(overlay_info_);
liberato2ff93ad2017-05-17 07:28:242589 }
watkdee516f2016-02-18 02:22:192590}
2591
Xiaohan Wangcd4df0a2019-12-04 20:59:242592std::unique_ptr<Renderer> WebMediaPlayerImpl::CreateRenderer(
Xiaohan Wang48aaa192019-12-05 01:29:002593 base::Optional<RendererFactoryType> factory_type) {
dcheng37b415b92017-01-27 20:17:432594 DCHECK(main_task_runner_->BelongsToCurrentThread());
2595
[email protected]c8d574722017-08-30 20:53:432596 // Make sure that overlays are enabled if they're always allowed.
2597 if (always_enable_overlays_)
tsunghungee562e92016-07-20 18:03:312598 EnableOverlay();
2599
liberato2ff93ad2017-05-17 07:28:242600 RequestOverlayInfoCB request_overlay_info_cb;
watkdee516f2016-02-18 02:22:192601#if defined(OS_ANDROID)
liberato2ff93ad2017-05-17 07:28:242602 request_overlay_info_cb = BindToCurrentLoop(
Antonio Gomes142f32a2019-05-15 23:32:562603 base::Bind(&WebMediaPlayerImpl::OnOverlayInfoRequested, weak_this_));
watkdee516f2016-02-18 02:22:192604#endif
Xiaohan Wangcd4df0a2019-12-04 20:59:242605
2606 if (factory_type) {
Xiaohan Wang48aaa192019-12-05 01:29:002607 DVLOG(1) << __func__
2608 << ": factory_type=" << static_cast<int>(factory_type.value());
Xiaohan Wangcd4df0a2019-12-04 20:59:242609 renderer_factory_selector_->SetBaseFactoryType(factory_type.value());
2610 }
2611
Dan Sanders6edfd782019-08-13 00:13:182612 reported_renderer_type_ = renderer_factory_selector_->GetCurrentFactoryType();
Xiaohan Wang73b433f2019-11-05 20:13:012613
Xiaohan Wang2480de72019-11-15 01:44:472614 return renderer_factory_selector_->GetCurrentFactory()->CreateRenderer(
2615 media_task_runner_, worker_task_runner_, audio_source_provider_.get(),
2616 compositor_.get(), request_overlay_info_cb, client_->TargetColorSpace());
sandersd1e49fb62015-12-12 01:18:062617}
2618
[email protected]ef8394c2013-08-21 20:26:302619void WebMediaPlayerImpl::StartPipeline() {
acolwellb4034942014-08-28 15:42:432620 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddbc6ff2013-04-19 15:28:332621
xhwange8c4181a2014-12-06 08:10:012622 Demuxer::EncryptedMediaInitDataCB encrypted_media_init_data_cb =
dcheng37b415b92017-01-27 20:17:432623 BindToCurrentLoop(base::Bind(
Antonio Gomes142f32a2019-05-15 23:32:562624 &WebMediaPlayerImpl::OnEncryptedMediaInitData, weak_this_));
[email protected]2b57e2e2014-05-09 11:07:252625
Dale Curtis3899090ea2018-01-12 00:10:352626 vfc_task_runner_->PostTask(
2627 FROM_HERE,
2628 base::BindOnce(&VideoFrameCompositor::SetOnNewProcessedFrameCallback,
2629 base::Unretained(compositor_.get()),
2630 BindToCurrentLoop(base::BindOnce(
Antonio Gomes142f32a2019-05-15 23:32:562631 &WebMediaPlayerImpl::OnFirstFrame, weak_this_))));
Dale Curtis3899090ea2018-01-12 00:10:352632
Thomas Guilbert55b48d92019-03-25 23:16:542633#if defined(OS_ANDROID)
Dale Curtis65c151a2019-02-26 02:09:322634 if (demuxer_found_hls_ ||
2635 renderer_factory_selector_->GetCurrentFactory()
2636 ->GetRequiredMediaResourceType() == MediaResource::Type::URL) {
Thomas Guilbert8a42fcf2019-03-01 20:21:452637 // MediaPlayerRendererClientFactory is the only factory that a uses
2638 // MediaResource::Type::URL for the moment.
tguilbert75e2bf62017-04-26 20:13:122639 using_media_player_renderer_ = true;
2640
Chris Cunninghamd9df58e2017-08-29 00:04:232641 // MediaPlayerRenderer does not provide pipeline stats, so nuke capabilities
2642 // reporter.
2643 video_decode_stats_reporter_.reset();
2644
Thomas Guilbert55b48d92019-03-25 23:16:542645 demuxer_.reset(new MediaUrlDemuxer(
2646 media_task_runner_, loaded_url_, frame_->GetDocument().SiteForCookies(),
Christian Dullweberacff9bd32019-08-20 09:44:372647 frame_->GetDocument().TopFrameOrigin(),
Dan Sanders3ff9ffe2019-07-19 22:24:122648 allow_media_player_renderer_credentials_, demuxer_found_hls_));
Antonio Gomes81b56552019-05-15 22:15:282649 pipeline_controller_->Start(Pipeline::StartType::kNormal, demuxer_.get(),
2650 this, false, false);
tguilbert25a4d112016-10-13 21:56:512651 return;
2652 }
Thomas Guilbert55b48d92019-03-25 23:16:542653#endif // defined(OS_ANDROID)
tguilbert25a4d112016-10-13 21:56:512654
[email protected]ddbc6ff2013-04-19 15:28:332655 // Figure out which demuxer to use.
Blink Reformat1c4d759e2017-04-09 16:34:542656 if (load_type_ != kLoadTypeMediaSource) {
[email protected]ddbc6ff2013-04-19 15:28:332657 DCHECK(!chunk_demuxer_);
[email protected]f5443ef72013-04-22 04:03:382658 DCHECK(data_source_);
2659
Dale Curtisbcf523b2018-01-17 02:59:012660#if BUILDFLAG(ENABLE_FFMPEG)
servolk81e01e02016-03-05 03:29:152661 Demuxer::MediaTracksUpdatedCB media_tracks_updated_cb =
dcheng37b415b92017-01-27 20:17:432662 BindToCurrentLoop(base::Bind(
Antonio Gomes142f32a2019-05-15 23:32:562663 &WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated, weak_this_));
servolk81e01e02016-03-05 03:29:152664
dalecurtis9cddc0b2017-04-19 21:23:382665 demuxer_.reset(new FFmpegDemuxer(
2666 media_task_runner_, data_source_.get(), encrypted_media_init_data_cb,
Dale Curtisb8139f72018-08-27 23:28:482667 media_tracks_updated_cb, media_log_.get(), IsLocalFile(loaded_url_)));
j.isorcef6778e652015-11-16 17:14:252668#else
alokp967c902452016-05-06 05:21:372669 OnError(PipelineStatus::DEMUXER_ERROR_COULD_NOT_OPEN);
j.isorcef6778e652015-11-16 17:14:252670 return;
2671#endif
[email protected]ddbc6ff2013-04-19 15:28:332672 } else {
[email protected]f5443ef72013-04-22 04:03:382673 DCHECK(!chunk_demuxer_);
2674 DCHECK(!data_source_);
2675
Antonio Gomes142f32a2019-05-15 23:32:562676 chunk_demuxer_ =
2677 new ChunkDemuxer(BindToCurrentLoop(base::Bind(
2678 &WebMediaPlayerImpl::OnDemuxerOpened, weak_this_)),
2679 BindToCurrentLoop(base::Bind(
2680 &WebMediaPlayerImpl::OnProgress, weak_this_)),
2681 encrypted_media_init_data_cb, media_log_.get());
[email protected]f5443ef72013-04-22 04:03:382682 demuxer_.reset(chunk_demuxer_);
servolkf94b4602017-01-31 16:44:272683
2684 if (base::FeatureList::IsEnabled(kMemoryPressureBasedSourceBufferGC)) {
2685 // base::Unretained is safe because |this| owns memory_pressure_listener_.
2686 memory_pressure_listener_ =
Gyuyoung Kim62a5de42018-01-10 09:48:422687 std::make_unique<base::MemoryPressureListener>(base::Bind(
servolkf94b4602017-01-31 16:44:272688 &WebMediaPlayerImpl::OnMemoryPressure, base::Unretained(this)));
2689 }
[email protected]ddbc6ff2013-04-19 15:28:332690 }
2691
sandersdb5e21462016-03-09 01:49:072692 // TODO(sandersd): FileSystem objects may also be non-static, but due to our
2693 // caching layer such situations are broken already. http://crbug.com/593159
2694 bool is_static = !chunk_demuxer_;
avayvod102cdb62017-01-07 03:11:092695 bool is_streaming = IsStreaming();
sandersdb8eb5f1d2016-11-19 04:04:022696 UMA_HISTOGRAM_BOOLEAN("Media.IsStreaming", is_streaming);
sandersdb5e21462016-03-09 01:49:072697
Dale Curtis2dc6089a2018-03-26 16:47:582698 // If possible attempt to avoid decoder spool up until playback starts.
2699 Pipeline::StartType start_type = Pipeline::StartType::kNormal;
Dale Curtis7c63f2e22018-09-19 21:06:272700 if (!chunk_demuxer_ && preload_ == MultibufferDataSource::METADATA &&
Dale Curtisd6ccd1992019-04-29 19:03:462701 !client_->CouldPlayIfEnoughData() && !IsStreaming()) {
Dale Curtis7c63f2e22018-09-19 21:06:272702 start_type =
2703 (has_poster_ || base::FeatureList::IsEnabled(kPreloadMetadataLazyLoad))
2704 ? Pipeline::StartType::kSuspendAfterMetadata
2705 : Pipeline::StartType::kSuspendAfterMetadataForAudioOnly;
Dale Curtis2dc6089a2018-03-26 16:47:582706 attempting_suspended_start_ = true;
2707 }
2708
[email protected]f5443ef72013-04-22 04:03:382709 // ... and we're ready to go!
sandersd1e49fb62015-12-12 01:18:062710 // TODO(sandersd): On Android, defer Start() if the tab is not visible.
sandersdb8eb5f1d2016-11-19 04:04:022711 seeking_ = true;
Antonio Gomes81b56552019-05-15 22:15:282712 pipeline_controller_->Start(start_type, demuxer_.get(), this, is_streaming,
2713 is_static);
[email protected]f5443ef72013-04-22 04:03:382714}
2715
2716void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState state) {
pkastingf5279482016-07-27 02:18:202717 DVLOG(1) << __func__ << "(" << state << ")";
acolwellb4034942014-08-28 15:42:432718 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]f5443ef72013-04-22 04:03:382719 network_state_ = state;
2720 // Always notify to ensure client has the latest value.
Blink Reformat1c4d759e2017-04-09 16:34:542721 client_->NetworkStateChanged();
[email protected]f5443ef72013-04-22 04:03:382722}
2723
2724void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state) {
pkastingf5279482016-07-27 02:18:202725 DVLOG(1) << __func__ << "(" << state << ")";
acolwellb4034942014-08-28 15:42:432726 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]f5443ef72013-04-22 04:03:382727
Blink Reformat1c4d759e2017-04-09 16:34:542728 if (state == WebMediaPlayer::kReadyStateHaveEnoughData && data_source_ &&
Dale Curtis4841c712018-12-13 18:14:052729 data_source_->AssumeFullyBuffered() &&
2730 network_state_ == WebMediaPlayer::kNetworkStateLoading) {
Blink Reformat1c4d759e2017-04-09 16:34:542731 SetNetworkState(WebMediaPlayer::kNetworkStateLoaded);
Dale Curtis4841c712018-12-13 18:14:052732 }
[email protected]f5443ef72013-04-22 04:03:382733
2734 ready_state_ = state;
sandersd50a635e2016-04-04 22:50:092735 highest_ready_state_ = std::max(highest_ready_state_, ready_state_);
2736
[email protected]f5443ef72013-04-22 04:03:382737 // Always notify to ensure client has the latest value.
Blink Reformat1c4d759e2017-04-09 16:34:542738 client_->ReadyStateChanged();
[email protected]f5443ef72013-04-22 04:03:382739}
2740
Antonio Gomesa38bb7cb2019-05-31 03:02:522741scoped_refptr<blink::WebAudioSourceProviderImpl>
2742WebMediaPlayerImpl::GetAudioSourceProvider() {
2743 return audio_source_provider_;
[email protected]f5443ef72013-04-22 04:03:382744}
2745
Jiajia Qin82acdc02017-07-31 09:55:142746scoped_refptr<VideoFrame> WebMediaPlayerImpl::GetCurrentFrameFromCompositor()
2747 const {
xhwang213e50c2016-10-10 23:56:312748 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]dd061e12014-05-06 19:21:222749 TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor");
xhwang213e50c2016-10-10 23:56:312750
Thomas Guilberte90fe312019-11-07 22:27:562751 if (current_frame_override_)
2752 return current_frame_override_;
2753
Thomas Guilbertd85407412017-11-08 05:03:462754 // Can be null.
2755 scoped_refptr<VideoFrame> video_frame =
2756 compositor_->GetCurrentFrameOnAnyThread();
[email protected]dd061e12014-05-06 19:21:222757
Thomas Guilbertd85407412017-11-08 05:03:462758 // base::Unretained is safe here because |compositor_| is destroyed on
2759 // |vfc_task_runner_|. The destruction is queued from |this|' destructor,
2760 // which also runs on |main_task_runner_|, which makes it impossible for
2761 // UpdateCurrentFrameIfStale() to be queued after |compositor_|'s dtor.
CJ DiMeglio2302d202017-08-31 08:38:042762 vfc_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:512763 FROM_HERE,
2764 base::BindOnce(&VideoFrameCompositor::UpdateCurrentFrameIfStale,
2765 base::Unretained(compositor_.get())));
kainino36eeff82017-03-30 00:55:302766
[email protected]dd061e12014-05-06 19:21:222767 return video_frame;
2768}
2769
sandersd50a635e2016-04-04 22:50:092770void WebMediaPlayerImpl::UpdatePlayState() {
xhwang213e50c2016-10-10 23:56:312771 DCHECK(main_task_runner_->BelongsToCurrentThread());
hubbee2cc88c092017-07-14 23:10:412772 bool can_auto_suspend = !disable_pipeline_auto_suspend_;
2773 // For streaming videos, we only allow suspending at the very beginning of the
2774 // video, and only if we know the length of the video. (If we don't know
2775 // the length, it might be a dynamically generated video, and suspending
2776 // will not work at all.)
2777 if (IsStreaming()) {
2778 bool at_beginning =
2779 ready_state_ == WebMediaPlayer::kReadyStateHaveNothing ||
2780 CurrentTime() == 0.0;
2781 if (!at_beginning || GetPipelineMediaDuration() == kInfiniteDuration)
2782 can_auto_suspend = false;
2783 }
xhwang213e50c2016-10-10 23:56:312784
Antonio Gomes81b56552019-05-15 22:15:282785 bool is_suspended = pipeline_controller_->IsSuspended();
Sergey Volk8b09c2c52018-12-12 23:20:402786 bool is_backgrounded = IsBackgroundSuspendEnabled(this) && IsHidden();
sandersdaaff1a652016-11-17 01:47:252787 PlayState state = UpdatePlayState_ComputePlayState(
Thomas Guilbert7350fdad2019-01-29 23:09:242788 is_flinging_, can_auto_suspend, is_suspended, is_backgrounded);
sandersd35d2c3f2017-01-14 02:04:422789 SetDelegateState(state.delegate_state, state.is_idle);
sandersd50a635e2016-04-04 22:50:092790 SetMemoryReportingState(state.is_memory_reporting_enabled);
2791 SetSuspendState(state.is_suspended || pending_suspend_resume_cycle_);
2792}
dalecurtis5bbc487e2016-02-27 04:15:052793
Becca Hughes7a85bf22019-07-24 16:16:582794void WebMediaPlayerImpl::UpdateMediaPositionState() {
2795 DCHECK(delegate_);
2796
2797 // When seeking the current time can go beyond the duration so we should
2798 // cap the current time at the duration.
2799 base::TimeDelta duration = GetPipelineMediaDuration();
2800 base::TimeDelta current_time = GetCurrentTimeInternal();
2801 if (current_time > duration)
2802 current_time = duration;
2803
2804 media_session::MediaPosition new_position(paused_ ? 0.0 : playback_rate_,
2805 duration, current_time);
2806
2807 if (media_position_state_ == new_position)
2808 return;
2809
2810 DVLOG(2) << __func__ << "(" << new_position.ToString() << ")";
2811 media_position_state_ = new_position;
2812 delegate_->DidPlayerMediaPositionStateChange(delegate_id_,
2813 media_position_state_);
2814}
2815
sandersd35d2c3f2017-01-14 02:04:422816void WebMediaPlayerImpl::SetDelegateState(DelegateState new_state,
2817 bool is_idle) {
tguilbert1bb1c782017-01-23 21:15:112818 DCHECK(delegate_);
Dale Curtis779ed842018-03-10 06:20:132819 DVLOG(2) << __func__ << "(" << static_cast<int>(new_state) << ", " << is_idle
2820 << ")";
dalecurtis5bbc487e2016-02-27 04:15:052821
sandersd35d2c3f2017-01-14 02:04:422822 // Prevent duplicate delegate calls.
2823 // TODO(sandersd): Move this deduplication into the delegate itself.
2824 // TODO(sandersd): WebContentsObserverSanityChecker does not allow sending the
2825 // 'playing' IPC more than once in a row, even if the metadata has changed.
2826 // Figure out whether it should.
Mounir Lamouri366dd8472018-06-19 17:20:042827 // Pretend that the media has no audio if it never played unmuted. This is to
2828 // avoid any action related to audible media such as taking audio focus or
2829 // showing a media notification. To preserve a consistent experience, it does
2830 // not apply if a media was audible so the system states do not flicker
2831 // depending on whether the user muted the player.
2832 bool has_audio = HasAudio() && !client_->WasAlwaysMuted();
sandersd35d2c3f2017-01-14 02:04:422833 if (delegate_state_ == new_state &&
2834 (delegate_state_ != DelegateState::PLAYING ||
2835 delegate_has_audio_ == has_audio)) {
2836 return;
mlamouri910111362016-11-04 11:28:242837 }
sandersd50a635e2016-04-04 22:50:092838 delegate_state_ = new_state;
sandersd35d2c3f2017-01-14 02:04:422839 delegate_has_audio_ = has_audio;
sandersd50a635e2016-04-04 22:50:092840
sandersd35d2c3f2017-01-14 02:04:422841 switch (new_state) {
sandersd50a635e2016-04-04 22:50:092842 case DelegateState::GONE:
2843 delegate_->PlayerGone(delegate_id_);
2844 break;
mlamouri910111362016-11-04 11:28:242845 case DelegateState::PLAYING: {
peconn257951522017-06-09 18:24:592846 if (HasVideo())
2847 delegate_->DidPlayerSizeChange(delegate_id_, NaturalSize());
zqzhang5d8eab72016-08-26 20:34:302848 delegate_->DidPlay(
Blink Reformat1c4d759e2017-04-09 16:34:542849 delegate_id_, HasVideo(), has_audio,
Dale Curtisca1b78f2019-01-15 03:11:262850 DurationToMediaContentType(GetPipelineMediaDuration()));
sandersd50a635e2016-04-04 22:50:092851 break;
mlamouri910111362016-11-04 11:28:242852 }
sandersd50a635e2016-04-04 22:50:092853 case DelegateState::PAUSED:
sandersd35d2c3f2017-01-14 02:04:422854 delegate_->DidPause(delegate_id_);
sandersd50a635e2016-04-04 22:50:092855 break;
dalecurtis0f0097a2015-12-01 17:40:472856 }
sandersd35d2c3f2017-01-14 02:04:422857
2858 delegate_->SetIdle(delegate_id_, is_idle);
dalecurtis0f0097a2015-12-01 17:40:472859}
2860
sandersd50a635e2016-04-04 22:50:092861void WebMediaPlayerImpl::SetMemoryReportingState(
2862 bool is_memory_reporting_enabled) {
2863 if (memory_usage_reporting_timer_.IsRunning() ==
2864 is_memory_reporting_enabled) {
hubbed5f36882016-01-15 22:40:372865 return;
sandersd50a635e2016-04-04 22:50:092866 }
sandersd1c0bba02016-03-04 23:14:082867
sandersd50a635e2016-04-04 22:50:092868 if (is_memory_reporting_enabled) {
2869 memory_usage_reporting_timer_.Start(FROM_HERE,
2870 base::TimeDelta::FromSeconds(2), this,
2871 &WebMediaPlayerImpl::ReportMemoryUsage);
2872 } else {
2873 memory_usage_reporting_timer_.Stop();
2874 ReportMemoryUsage();
2875 }
2876}
2877
2878void WebMediaPlayerImpl::SetSuspendState(bool is_suspended) {
xhwang213e50c2016-10-10 23:56:312879 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtis779ed842018-03-10 06:20:132880 DVLOG(2) << __func__ << "(" << is_suspended << ")";
xhwang213e50c2016-10-10 23:56:312881
sandersd50a635e2016-04-04 22:50:092882 // Do not change the state after an error has occurred.
2883 // TODO(sandersd): Update PipelineController to remove the need for this.
2884 if (IsNetworkStateError(network_state_))
sandersd1c0bba02016-03-04 23:14:082885 return;
2886
jameswest451a5bb2017-01-27 03:59:392887 if (is_suspended) {
sandersd35d2c3f2017-01-14 02:04:422888 // If we were not resumed for long enough to satisfy the preroll attempt,
2889 // reset the clock.
2890 if (!preroll_attempt_pending_ && IsPrerollAttemptNeeded()) {
2891 preroll_attempt_pending_ = true;
2892 preroll_attempt_start_time_ = base::TimeTicks();
2893 }
Antonio Gomes81b56552019-05-15 22:15:282894 pipeline_controller_->Suspend();
sandersd50a635e2016-04-04 22:50:092895 } else {
sandersd35d2c3f2017-01-14 02:04:422896 // When resuming, start the preroll attempt clock.
2897 if (preroll_attempt_pending_) {
2898 preroll_attempt_pending_ = false;
2899 preroll_attempt_start_time_ = tick_clock_->NowTicks();
2900 }
Antonio Gomes81b56552019-05-15 22:15:282901 pipeline_controller_->Resume();
sandersd50a635e2016-04-04 22:50:092902 }
2903}
2904
2905WebMediaPlayerImpl::PlayState
Thomas Guilbert7350fdad2019-01-29 23:09:242906WebMediaPlayerImpl::UpdatePlayState_ComputePlayState(bool is_flinging,
xjz4e5d4bf32017-02-15 21:26:352907 bool can_auto_suspend,
dalecurtis8b8505e72016-06-10 21:59:172908 bool is_suspended,
sandersd50a635e2016-04-04 22:50:092909 bool is_backgrounded) {
2910 PlayState result;
2911
tguilbert1bb1c782017-01-23 21:15:112912 bool must_suspend = delegate_->IsFrameClosed();
Dale Curtis6438cf12018-03-29 02:34:012913 bool is_stale = delegate_->IsStale(delegate_id_);
2914
2915 if (stale_state_override_for_testing_.has_value() &&
2916 ready_state_ >= stale_state_override_for_testing_.value()) {
2917 is_stale = true;
2918 }
sandersd35d2c3f2017-01-14 02:04:422919
sandersd50a635e2016-04-04 22:50:092920 // This includes both data source (before pipeline startup) and pipeline
2921 // errors.
2922 bool has_error = IsNetworkStateError(network_state_);
2923
Dale Curtisc56158c2019-09-09 23:00:322924 // Note: Even though we get play/pause signals at kReadyStateHaveMetadata, we
2925 // must attempt to preroll until kReadyStateHaveFutureData so that the
2926 // canplaythrough event will be fired to the page (which may be waiting).
2927 bool have_future_data =
2928 highest_ready_state_ >= WebMediaPlayer::kReadyStateHaveFutureData;
sandersd50a635e2016-04-04 22:50:092929
avayvod65fad272017-02-24 01:00:482930 // Background suspend is only enabled for paused players.
2931 // In the case of players with audio the session should be kept.
2932 bool background_suspended =
Dale Curtisc56158c2019-09-09 23:00:322933 can_auto_suspend && is_backgrounded && paused_ && have_future_data;
sandersd50a635e2016-04-04 22:50:092934
Dale Curtisd71061f02019-05-21 21:33:542935 // Idle suspension is allowed prior to kReadyStateHaveMetadata since there
2936 // exist mechanisms to exit the idle state when the player is capable of
2937 // reaching the kReadyStateHaveMetadata state; see didLoadingProgress().
dalecurtiscc8baf72016-10-27 01:49:442938 //
sandersd50a635e2016-04-04 22:50:092939 // TODO(sandersd): Make the delegate suspend idle players immediately when
2940 // hidden.
Dale Curtis7c63f2e22018-09-19 21:06:272941 bool idle_suspended = can_auto_suspend && is_stale && paused_ && !seeking_ &&
2942 !overlay_enabled_ && !needs_first_frame_;
dalecurtise7120dc2016-09-03 02:54:352943
2944 // If we're already suspended, see if we can wait for user interaction. Prior
Dale Curtisd71061f02019-05-21 21:33:542945 // to kReadyStateHaveMetadata, we require |is_stale| to remain suspended.
2946 // |is_stale| will be cleared when we receive data which may take us to
2947 // kReadyStateHaveMetadata.
Dale Curtisc56158c2019-09-09 23:00:322948 bool can_stay_suspended = (is_stale || have_future_data) && is_suspended &&
Dale Curtis7c63f2e22018-09-19 21:06:272949 paused_ && !seeking_ && !needs_first_frame_;
sandersd50a635e2016-04-04 22:50:092950
2951 // Combined suspend state.
Thomas Guilbert7350fdad2019-01-29 23:09:242952 result.is_suspended = must_suspend || idle_suspended ||
avayvod65fad272017-02-24 01:00:482953 background_suspended || can_stay_suspended;
sandersd50a635e2016-04-04 22:50:092954
Thomas Guilbert7350fdad2019-01-29 23:09:242955 DVLOG(3) << __func__ << ": must_suspend=" << must_suspend
Dale Curtis779ed842018-03-10 06:20:132956 << ", idle_suspended=" << idle_suspended
2957 << ", background_suspended=" << background_suspended
2958 << ", can_stay_suspended=" << can_stay_suspended
Dale Curtisc56158c2019-09-09 23:00:322959 << ", is_stale=" << is_stale
2960 << ", have_future_data=" << have_future_data
Dale Curtis779ed842018-03-10 06:20:132961 << ", paused_=" << paused_ << ", seeking_=" << seeking_;
2962
sandersd50a635e2016-04-04 22:50:092963 // We do not treat |playback_rate_| == 0 as paused. For the media session,
2964 // being paused implies displaying a play button, which is incorrect in this
2965 // case. For memory usage reporting, we just use the same definition (but we
2966 // don't have to).
2967 //
2968 // Similarly, we don't consider |ended_| to be paused. Blink will immediately
2969 // call pause() or seek(), so |ended_| should not affect the computation.
2970 // Despite that, |ended_| does result in a separate paused state, to simplfy
2971 // the contract for SetDelegateState().
2972 //
avayvod65fad272017-02-24 01:00:482973 // |has_remote_controls| indicates if the player can be controlled outside the
2974 // page (e.g. via the notification controls or by audio focus events). Idle
sandersd50a635e2016-04-04 22:50:092975 // suspension does not destroy the media session, because we expect that the
avayvod5f34b642017-03-23 03:14:042976 // notification controls (and audio focus) remain. With some exceptions for
2977 // background videos, the player only needs to have audio to have controls
Dale Curtisd71061f02019-05-21 21:33:542978 // (requires |have_current_data|).
avayvod5f34b642017-03-23 03:14:042979 //
2980 // |alive| indicates if the player should be present (not |GONE|) to the
2981 // delegate, either paused or playing. The following must be true for the
2982 // player:
Dale Curtisd71061f02019-05-21 21:33:542983 // - |have_current_data|, since playback can't begin before that point, we
2984 // need to know whether we are paused to correctly configure the session,
2985 // and also because the tracks and duration are passed to DidPlay(),
Thomas Guilbert7350fdad2019-01-29 23:09:242986 // - |is_flinging| is false (RemotePlayback is not handled by the delegate)
avayvod5f34b642017-03-23 03:14:042987 // - |has_error| is false as player should have no errors,
2988 // - |background_suspended| is false, otherwise |has_remote_controls| must
2989 // be true.
sandersd50a635e2016-04-04 22:50:092990 //
avayvod65fad272017-02-24 01:00:482991 // TODO(sandersd): If Blink told us the paused state sooner, we could detect
2992 // if the remote controls are available sooner.
2993
2994 // Background videos with audio don't have remote controls if background
2995 // suspend is enabled and resuming background videos is not (original Android
2996 // behavior).
2997 bool backgrounded_video_has_no_remote_controls =
Sergey Volk8b09c2c52018-12-12 23:20:402998 IsBackgroundSuspendEnabled(this) && !IsResumeBackgroundVideosEnabled() &&
2999 is_backgrounded && HasVideo();
Dale Curtisd71061f02019-05-21 21:33:543000 bool have_current_data = highest_ready_state_ >= kReadyStateHaveCurrentData;
3001 bool can_play = !has_error && have_current_data;
avayvod5f34b642017-03-23 03:14:043002 bool has_remote_controls =
Blink Reformat1c4d759e2017-04-09 16:34:543003 HasAudio() && !backgrounded_video_has_no_remote_controls;
Thomas Guilbert7350fdad2019-01-29 23:09:243004 bool alive = can_play && !is_flinging && !must_suspend &&
avayvod5f34b642017-03-23 03:14:043005 (!background_suspended || has_remote_controls);
3006 if (!alive) {
Thomas Guilbert4c6feff2018-11-09 19:53:323007 // Do not mark players as idle when flinging.
sandersd50a635e2016-04-04 22:50:093008 result.delegate_state = DelegateState::GONE;
Thomas Guilbert4c6feff2018-11-09 19:53:323009 result.is_idle = delegate_->IsIdle(delegate_id_) && !is_flinging;
avayvod65fad272017-02-24 01:00:483010 } else if (paused_) {
sandersd35d2c3f2017-01-14 02:04:423011 // TODO(sandersd): Is it possible to have a suspended session, be ended,
3012 // and not be paused? If so we should be in a PLAYING state.
dalecurtise7120dc2016-09-03 02:54:353013 result.delegate_state =
sandersd35d2c3f2017-01-14 02:04:423014 ended_ ? DelegateState::GONE : DelegateState::PAUSED;
3015 result.is_idle = !seeking_;
sandersd50a635e2016-04-04 22:50:093016 } else {
3017 result.delegate_state = DelegateState::PLAYING;
sandersd35d2c3f2017-01-14 02:04:423018 result.is_idle = false;
sandersd50a635e2016-04-04 22:50:093019 }
3020
dalecurtis8b8505e72016-06-10 21:59:173021 // It's not critical if some cases where memory usage can change are missed,
sandersd50a635e2016-04-04 22:50:093022 // since media memory changes are usually gradual.
Thomas Guilbert7350fdad2019-01-29 23:09:243023 result.is_memory_reporting_enabled = !has_error && can_play && !is_flinging &&
3024 !result.is_suspended &&
3025 (!paused_ || seeking_);
sandersd50a635e2016-04-04 22:50:093026
3027 return result;
dalecurtis0f0097a2015-12-01 17:40:473028}
3029
dalecurtis83266c72015-10-29 18:43:203030void WebMediaPlayerImpl::ReportMemoryUsage() {
3031 DCHECK(main_task_runner_->BelongsToCurrentThread());
3032
wdzierzanowskifd4cd91c52015-12-02 23:50:203033 // About base::Unretained() usage below: We destroy |demuxer_| on the main
3034 // thread. Before that, however, ~WebMediaPlayerImpl() posts a task to the
3035 // media thread and waits for it to finish. Hence, the GetMemoryUsage() task
3036 // posted here must finish earlier.
Dale Curtis8a6281322017-08-31 00:35:533037 //
3038 // The exception to the above is when OnError() has been called. If we're in
3039 // the error state we've already shut down the pipeline and can't rely on it
3040 // to cycle the media thread before we destroy |demuxer_|. In this case skip
3041 // collection of the demuxer memory stats.
3042 if (demuxer_ && !IsNetworkStateError(network_state_)) {
wdzierzanowskifd4cd91c52015-12-02 23:50:203043 base::PostTaskAndReplyWithResult(
3044 media_task_runner_.get(), FROM_HERE,
3045 base::Bind(&Demuxer::GetMemoryUsage, base::Unretained(demuxer_.get())),
Antonio Gomes142f32a2019-05-15 23:32:563046 base::Bind(&WebMediaPlayerImpl::FinishMemoryUsageReport, weak_this_));
wdzierzanowskifd4cd91c52015-12-02 23:50:203047 } else {
3048 FinishMemoryUsageReport(0);
3049 }
3050}
3051
3052void WebMediaPlayerImpl::FinishMemoryUsageReport(int64_t demuxer_memory_usage) {
3053 DCHECK(main_task_runner_->BelongsToCurrentThread());
3054
avayvodc4bfb0e62017-01-13 01:07:013055 const PipelineStatistics stats = GetPipelineStatistics();
servolk639473e492016-12-15 04:14:203056 const int64_t data_source_memory_usage =
3057 data_source_ ? data_source_->GetMemoryUsage() : 0;
dalecurtisecc76612017-04-19 00:31:203058
Dale Curtisc2c5dcb12018-04-16 23:21:293059 // If we have video and no video memory usage and we've rendered the first
3060 // frame, assume the VideoFrameCompositor is holding onto the last frame after
3061 // we've suspended the pipeline; which thus reports zero memory usage from the
3062 // video renderer.
dalecurtisecc76612017-04-19 00:31:203063 //
3064 // Technically this should use the coded size, but that requires us to hop to
3065 // the compositor to get and byte-perfect accuracy isn't important here.
3066 const int64_t video_memory_usage =
3067 stats.video_memory_usage +
Dale Curtisc2c5dcb12018-04-16 23:21:293068 ((pipeline_metadata_.has_video && !stats.video_memory_usage &&
3069 has_first_frame_)
Miguel Casas9e7766022018-01-08 16:13:133070 ? VideoFrame::AllocationSize(PIXEL_FORMAT_I420,
dalecurtisecc76612017-04-19 00:31:203071 pipeline_metadata_.natural_size)
3072 : 0);
3073
dalecurtis83266c72015-10-29 18:43:203074 const int64_t current_memory_usage =
dalecurtisecc76612017-04-19 00:31:203075 stats.audio_memory_usage + video_memory_usage + data_source_memory_usage +
3076 demuxer_memory_usage;
dalecurtis83266c72015-10-29 18:43:203077
dalecurtisecc76612017-04-19 00:31:203078 DVLOG(2) << "Memory Usage -- Total: " << current_memory_usage
3079 << " Audio: " << stats.audio_memory_usage
3080 << ", Video: " << video_memory_usage
servolk639473e492016-12-15 04:14:203081 << ", DataSource: " << data_source_memory_usage
wdzierzanowskifd4cd91c52015-12-02 23:50:203082 << ", Demuxer: " << demuxer_memory_usage;
dalecurtis83266c72015-10-29 18:43:203083
3084 const int64_t delta = current_memory_usage - last_reported_memory_usage_;
3085 last_reported_memory_usage_ = current_memory_usage;
3086 adjust_allocated_memory_cb_.Run(delta);
servolk639473e492016-12-15 04:14:203087
Blink Reformat1c4d759e2017-04-09 16:34:543088 if (HasAudio()) {
servolk639473e492016-12-15 04:14:203089 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.Audio",
3090 stats.audio_memory_usage / 1024);
3091 }
Blink Reformat1c4d759e2017-04-09 16:34:543092 if (HasVideo()) {
servolk639473e492016-12-15 04:14:203093 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.Video",
dalecurtisecc76612017-04-19 00:31:203094 video_memory_usage / 1024);
servolk639473e492016-12-15 04:14:203095 }
3096 if (data_source_) {
3097 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.DataSource",
3098 data_source_memory_usage / 1024);
3099 }
3100 if (demuxer_) {
3101 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.Demuxer",
3102 demuxer_memory_usage / 1024);
3103 }
dalecurtis83266c72015-10-29 18:43:203104}
3105
dalecurtis8b8505e72016-06-10 21:59:173106void WebMediaPlayerImpl::ScheduleIdlePauseTimer() {
avayvod65fad272017-02-24 01:00:483107 // Only schedule the pause timer if we're not paused or paused but going to
avayvod52efd282017-03-07 21:13:043108 // resume when foregrounded, and are suspended and have audio.
3109 if ((paused_ && !paused_when_hidden_) ||
Antonio Gomes81b56552019-05-15 22:15:283110 !pipeline_controller_->IsSuspended() || !HasAudio()) {
dalecurtis8b8505e72016-06-10 21:59:173111 return;
avayvod52efd282017-03-07 21:13:043112 }
dalecurtis8b8505e72016-06-10 21:59:173113
3114#if defined(OS_ANDROID)
Thomas Guilbert7350fdad2019-01-29 23:09:243115 // Don't pause videos casted as part of RemotePlayback.
3116 if (is_flinging_)
dalecurtis8b8505e72016-06-10 21:59:173117 return;
3118#endif
3119
3120 // Idle timeout chosen arbitrarily.
3121 background_pause_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(5),
3122 this, &WebMediaPlayerImpl::OnPause);
3123}
3124
dalecurtis04bdb582016-08-17 22:15:233125void WebMediaPlayerImpl::CreateWatchTimeReporter() {
wdzierzanowskia78fa9b2017-06-13 18:12:103126 if (!HasVideo() && !HasAudio())
3127 return;
3128
Dan Sanders7ef5d0f2019-05-03 18:30:113129 // MediaPlayerRenderer does not know about tracks until playback starts.
3130 // Assume audio-only unless the natural size has been detected.
3131 bool has_video = pipeline_metadata_.has_video;
3132 if (using_media_player_renderer_) {
3133 has_video = !pipeline_metadata_.natural_size.IsEmpty();
3134 }
3135
dalecurtis04bdb582016-08-17 22:15:233136 // Create the watch time reporter and synchronize its initial state.
Dale Curtis1adbe6a2017-08-02 02:09:133137 watch_time_reporter_.reset(new WatchTimeReporter(
Dan Sanders7ef5d0f2019-05-03 18:30:113138 mojom::PlaybackProperties::New(
3139 pipeline_metadata_.has_audio, has_video, false, false,
3140 !!chunk_demuxer_, is_encrypted_, embedded_media_experience_enabled_),
Dale Curtis96d6e9382018-07-18 18:01:073141 pipeline_metadata_.natural_size,
Dale Curtis051fdf62017-08-05 00:21:133142 base::BindRepeating(&WebMediaPlayerImpl::GetCurrentTimeInternal,
3143 base::Unretained(this)),
Dale Curtis0f8d7b32019-10-24 22:10:283144 base::BindRepeating(&WebMediaPlayerImpl::GetPipelineStatistics,
3145 base::Unretained(this)),
Hajime Hoshi8bb37dc2017-12-19 09:35:103146 media_metrics_provider_.get(),
Hajime Hoshib5a26ee2018-05-14 12:47:513147 frame_->GetTaskRunner(blink::TaskType::kInternalMedia)));
dalecurtis04bdb582016-08-17 22:15:233148 watch_time_reporter_->OnVolumeChange(volume_);
Dale Curtisaebaeea2018-07-19 23:42:113149 watch_time_reporter_->OnDurationChanged(GetPipelineMediaDuration());
Mounir Lamourif9af74e72017-06-19 19:31:453150
tguilbert1bb1c782017-01-23 21:15:113151 if (delegate_->IsFrameHidden())
dalecurtis04bdb582016-08-17 22:15:233152 watch_time_reporter_->OnHidden();
3153 else
3154 watch_time_reporter_->OnShown();
Mounir Lamourif9af74e72017-06-19 19:31:453155
Mounir Lamouri41a79c62017-06-06 12:53:163156 if (client_->HasNativeControls())
3157 watch_time_reporter_->OnNativeControlsEnabled();
3158 else
3159 watch_time_reporter_->OnNativeControlsDisabled();
Mounir Lamourif9af74e72017-06-19 19:31:453160
3161 switch (client_->DisplayType()) {
3162 case WebMediaPlayer::DisplayType::kInline:
3163 watch_time_reporter_->OnDisplayTypeInline();
3164 break;
3165 case WebMediaPlayer::DisplayType::kFullscreen:
3166 watch_time_reporter_->OnDisplayTypeFullscreen();
3167 break;
3168 case WebMediaPlayer::DisplayType::kPictureInPicture:
3169 watch_time_reporter_->OnDisplayTypePictureInPicture();
3170 break;
3171 }
Dale Curtis96d6e9382018-07-18 18:01:073172
3173 UpdateSecondaryProperties();
Dale Curtis7fd27c4b2018-07-30 22:14:213174
3175 // If the WatchTimeReporter was recreated in the middle of playback, we want
3176 // to resume playback here too since we won't get another play() call. When
3177 // seeking, the seek completion will restart it if necessary.
3178 if (!paused_ && !seeking_)
3179 watch_time_reporter_->OnPlaying();
Dale Curtis96d6e9382018-07-18 18:01:073180}
3181
3182void WebMediaPlayerImpl::UpdateSecondaryProperties() {
3183 watch_time_reporter_->UpdateSecondaryProperties(
3184 mojom::SecondaryPlaybackProperties::New(
3185 pipeline_metadata_.audio_decoder_config.codec(),
Dale Curtis7140b502019-10-23 20:34:423186 pipeline_metadata_.video_decoder_config.codec(),
3187 pipeline_metadata_.video_decoder_config.profile(),
3188 audio_decoder_name_, video_decoder_name_,
Yuchen Liub33bfc12019-11-08 20:16:123189 pipeline_metadata_.audio_decoder_config.encryption_scheme(),
3190 pipeline_metadata_.video_decoder_config.encryption_scheme(),
John Rummelld30555352018-09-21 20:47:253191 pipeline_metadata_.natural_size));
dalecurtis04bdb582016-08-17 22:15:233192}
3193
avayvod39c102402016-11-23 21:43:133194bool WebMediaPlayerImpl::IsHidden() const {
3195 DCHECK(main_task_runner_->BelongsToCurrentThread());
3196
tguilbert1bb1c782017-01-23 21:15:113197 return delegate_->IsFrameHidden() && !delegate_->IsFrameClosed();
avayvod39c102402016-11-23 21:43:133198}
3199
avayvod102cdb62017-01-07 03:11:093200bool WebMediaPlayerImpl::IsStreaming() const {
3201 return data_source_ && data_source_->IsStreaming();
3202}
3203
liberato2fd111be2017-01-04 00:25:063204bool WebMediaPlayerImpl::DoesOverlaySupportMetadata() const {
Ted Meyer4a427632019-05-01 19:05:273205 return pipeline_metadata_.video_decoder_config.video_transformation() ==
3206 kNoTransformation;
liberato2fd111be2017-01-04 00:25:063207}
3208
xjzaf29d4182016-12-16 01:52:323209void WebMediaPlayerImpl::ActivateViewportIntersectionMonitoring(bool activate) {
3210 DCHECK(main_task_runner_->BelongsToCurrentThread());
3211
Blink Reformat1c4d759e2017-04-09 16:34:543212 client_->ActivateViewportIntersectionMonitoring(activate);
xjzaf29d4182016-12-16 01:52:323213}
3214
Anton Vayvod09fa66e2017-07-20 23:02:123215void WebMediaPlayerImpl::UpdateRemotePlaybackCompatibility(bool is_compatible) {
3216 DCHECK(main_task_runner_->BelongsToCurrentThread());
3217
3218 client_->RemotePlaybackCompatibilityChanged(loaded_url_, is_compatible);
3219}
3220
Dale Curtis6438cf12018-03-29 02:34:013221void WebMediaPlayerImpl::ForceStaleStateForTesting(ReadyState target_state) {
3222 stale_state_override_for_testing_.emplace(target_state);
Dale Curtis99a9b482018-02-01 02:23:283223 UpdatePlayState();
3224}
3225
3226bool WebMediaPlayerImpl::IsSuspendedForTesting() {
3227 // This intentionally uses IsPipelineSuspended since we need to know when the
3228 // pipeline has reached the suspended state, not when it's in suspending.
Antonio Gomes81b56552019-05-15 22:15:283229 return pipeline_controller_->IsPipelineSuspended();
Dale Curtis99a9b482018-02-01 02:23:283230}
3231
Dale Curtis7c63f2e22018-09-19 21:06:273232bool WebMediaPlayerImpl::DidLazyLoad() const {
3233 return did_lazy_load_;
3234}
3235
3236void WebMediaPlayerImpl::OnBecameVisible() {
Dale Curtis04769ca2019-05-25 00:38:103237 have_enough_after_lazy_load_cb_.Cancel();
Dale Curtis7c63f2e22018-09-19 21:06:273238 needs_first_frame_ = !has_first_frame_;
3239 UpdatePlayState();
3240}
3241
Miguel Casasfb63a5792018-12-04 23:50:413242bool WebMediaPlayerImpl::IsOpaque() const {
3243 return opaque_;
3244}
3245
Mounir Lamouri99ba5a62019-02-12 01:27:473246int WebMediaPlayerImpl::GetDelegateId() {
3247 return delegate_id_;
3248}
3249
3250base::Optional<viz::SurfaceId> WebMediaPlayerImpl::GetSurfaceId() {
3251 if (!surface_layer_for_video_enabled_)
3252 return base::nullopt;
3253 return bridge_->GetSurfaceId();
3254}
3255
Thomas Guilberte90fe312019-11-07 22:27:563256void WebMediaPlayerImpl::RequestAnimationFrame() {
3257 vfc_task_runner_->PostTask(
3258 FROM_HERE,
3259 base::BindOnce(&VideoFrameCompositor::SetOnFramePresentedCallback,
3260 base::Unretained(compositor_.get()),
3261 BindToCurrentLoop(base::BindOnce(
3262 &WebMediaPlayerImpl::OnNewFramePresentedCallback,
3263 weak_factory_.GetWeakPtr()))));
3264}
3265
3266void WebMediaPlayerImpl::OnNewFramePresentedCallback(
3267 scoped_refptr<VideoFrame> presented_frame,
3268 base::TimeTicks presentation_time,
3269 base::TimeTicks expected_presentation_time,
3270 uint32_t presentation_counter) {
3271 current_frame_override_ = std::move(presented_frame);
3272 client_->OnRequestAnimationFrame(
3273 presentation_time, expected_presentation_time, presentation_counter,
3274 *current_frame_override_);
3275 current_frame_override_.reset();
3276}
3277
Antonio Gomes142f32a2019-05-15 23:32:563278base::WeakPtr<blink::WebMediaPlayer> WebMediaPlayerImpl::AsWeakPtr() {
3279 return weak_this_;
3280}
3281
Yuchen Liue7813972019-04-12 22:34:243282bool WebMediaPlayerImpl::ShouldPausePlaybackWhenHidden() const {
3283 // Audio only stream is allowed to play when in background.
3284 // TODO: We should check IsBackgroundOptimizationCandidate here. But we need
3285 // to move the logic of checking video frames out of that function.
3286 if (!HasVideo())
3287 return false;
3288
Junbo Kefba620b2019-01-16 02:54:363289 if (!is_background_video_playback_enabled_)
3290 return true;
3291
avayvod65fad272017-02-24 01:00:483292 // If suspending background video, pause any video that's not remoted or
3293 // not unlocked to play in the background.
Sergey Volk8b09c2c52018-12-12 23:20:403294 if (IsBackgroundSuspendEnabled(this)) {
avayvod65fad272017-02-24 01:00:483295#if defined(OS_ANDROID)
Thomas Guilbert7350fdad2019-01-29 23:09:243296 if (is_flinging_)
avayvod65fad272017-02-24 01:00:483297 return false;
avayvodcc273dd2017-01-19 19:35:123298#endif
avayvodeb9098d2017-01-07 00:33:033299
Blink Reformat1c4d759e2017-04-09 16:34:543300 return !HasAudio() || (IsResumeBackgroundVideosEnabled() &&
3301 video_locked_when_paused_when_hidden_);
avayvod65fad272017-02-24 01:00:483302 }
3303
3304 // Otherwise only pause if the optimization is on and it's a video-only
3305 // optimization candidate.
avayvod01201332017-04-14 00:27:153306 return IsBackgroundVideoPauseOptimizationEnabled() && !HasAudio() &&
Thomas Guilbert29ae1a902018-10-20 01:53:383307 IsBackgroundOptimizationCandidate() && !is_flinging_;
avayvodeb9098d2017-01-07 00:33:033308}
3309
avayvod2135a642017-01-13 00:17:143310bool WebMediaPlayerImpl::ShouldDisableVideoWhenHidden() const {
Ted Meyera918e592018-09-08 00:16:203311 // This optimization is behind the flag on all platforms, only for non-mse
3312 // video. MSE video track switching on hide has gone through a field test.
3313 // TODO(tmathmeyer): Passing load_type_ won't be needed after src= field
3314 // testing is finished. see: http://crbug.com/709302
Ted Meyer0e105992019-05-04 01:47:213315 if (!is_background_video_track_optimization_supported_)
avayvodc4bfb0e62017-01-13 01:07:013316 return false;
avayvodc4bfb0e62017-01-13 01:07:013317
avayvodcc273dd2017-01-19 19:35:123318 // Disable video track only for players with audio that match the criteria for
3319 // being optimized.
Blink Reformat1c4d759e2017-04-09 16:34:543320 return HasAudio() && IsBackgroundOptimizationCandidate();
avayvodcc273dd2017-01-19 19:35:123321}
3322
3323bool WebMediaPlayerImpl::IsBackgroundOptimizationCandidate() const {
3324 DCHECK(main_task_runner_->BelongsToCurrentThread());
3325
François Beaufort664c3ca72018-04-13 07:24:513326 // Don't optimize Picture-in-Picture players.
Mounir Lamouri0484f40a2018-07-25 03:03:263327 if (IsInPictureInPicture())
François Beaufort664c3ca72018-04-13 07:24:513328 return false;
3329
Thomas Guilbert7350fdad2019-01-29 23:09:243330#if defined(OS_ANDROID)
3331 // Don't optimize videos casted as part of RemotePlayback.
3332 if (is_flinging_)
avayvodcc273dd2017-01-19 19:35:123333 return false;
Thomas Guilbert7350fdad2019-01-29 23:09:243334#endif
avayvodcc273dd2017-01-19 19:35:123335
3336 // Don't optimize audio-only or streaming players.
Blink Reformat1c4d759e2017-04-09 16:34:543337 if (!HasVideo() || IsStreaming())
avayvodcc273dd2017-01-19 19:35:123338 return false;
3339
Dale Curtis3f4935b2017-09-09 00:11:593340 // Video-only players are always optimized (paused).
3341 // Don't check the keyframe distance and duration.
3342 if (!HasAudio() && HasVideo())
3343 return true;
3344
avayvodcc273dd2017-01-19 19:35:123345 // Videos shorter than the maximum allowed keyframe distance can be optimized.
3346 base::TimeDelta duration = GetPipelineMediaDuration();
Ted Meyera918e592018-09-08 00:16:203347
Dale Curtis456808a2018-10-23 17:50:213348 constexpr base::TimeDelta kMaxKeyframeDistanceToDisableBackgroundVideo =
3349 base::TimeDelta::FromMilliseconds(
3350 kMaxKeyframeDistanceToDisableBackgroundVideoMs);
3351 if (duration < kMaxKeyframeDistanceToDisableBackgroundVideo)
avayvodcc273dd2017-01-19 19:35:123352 return true;
3353
3354 // Otherwise, only optimize videos with shorter average keyframe distance.
avayvodc4bfb0e62017-01-13 01:07:013355 PipelineStatistics stats = GetPipelineStatistics();
Dale Curtis456808a2018-10-23 17:50:213356 return stats.video_keyframe_distance_average <
3357 kMaxKeyframeDistanceToDisableBackgroundVideo;
avayvod2135a642017-01-13 00:17:143358}
3359
avayvod56e1f3942017-01-21 02:06:313360void WebMediaPlayerImpl::UpdateBackgroundVideoOptimizationState() {
Takumi Fujimotof2319684e2019-12-03 18:51:513361 if (IsHidden()) {
Yuchen Liue7813972019-04-12 22:34:243362 if (ShouldPausePlaybackWhenHidden()) {
avayvod56e1f3942017-01-21 02:06:313363 PauseVideoIfNeeded();
Dale Curtisa75a7892017-08-09 20:21:513364 } else if (update_background_status_cb_.IsCancelled()) {
3365 // Only trigger updates when we don't have one already scheduled.
3366 update_background_status_cb_.Reset(
3367 base::Bind(&WebMediaPlayerImpl::DisableVideoTrackIfNeeded,
3368 base::Unretained(this)));
3369
3370 // Defer disable track until we're sure the clip will be backgrounded for
3371 // some time. Resuming may take half a second, so frequent tab switches
3372 // will yield a poor user experience otherwise. http://crbug.com/709302
3373 // may also cause AV sync issues if disable/enable happens too fast.
3374 main_task_runner_->PostDelayedTask(
3375 FROM_HERE, update_background_status_cb_.callback(),
3376 base::TimeDelta::FromSeconds(10));
3377 }
avayvod56e1f3942017-01-21 02:06:313378 } else {
Dale Curtisa75a7892017-08-09 20:21:513379 update_background_status_cb_.Cancel();
avayvod56e1f3942017-01-21 02:06:313380 EnableVideoTrackIfNeeded();
3381 }
3382}
3383
3384void WebMediaPlayerImpl::PauseVideoIfNeeded() {
3385 DCHECK(IsHidden());
3386
3387 // Don't pause video while the pipeline is stopped, resuming or seeking.
3388 // Also if the video is paused already.
Antonio Gomes81b56552019-05-15 22:15:283389 if (!pipeline_controller_->IsPipelineRunning() || is_pipeline_resuming_ ||
tguilbert350936ff2017-02-24 05:39:273390 seeking_ || paused_)
avayvod56e1f3942017-01-21 02:06:313391 return;
3392
3393 // OnPause() will set |paused_when_hidden_| to false and call
3394 // UpdatePlayState(), so set the flag to true after and then return.
3395 OnPause();
3396 paused_when_hidden_ = true;
3397}
3398
avayvod2135a642017-01-13 00:17:143399void WebMediaPlayerImpl::EnableVideoTrackIfNeeded() {
avayvod56e1f3942017-01-21 02:06:313400 // Don't change video track while the pipeline is stopped, resuming or
3401 // seeking.
Antonio Gomes81b56552019-05-15 22:15:283402 if (!pipeline_controller_->IsPipelineRunning() || is_pipeline_resuming_ ||
tguilbert350936ff2017-02-24 05:39:273403 seeking_)
avayvod2135a642017-01-13 00:17:143404 return;
3405
3406 if (video_track_disabled_) {
3407 video_track_disabled_ = false;
Blink Reformat1c4d759e2017-04-09 16:34:543408 if (client_->HasSelectedVideoTrack()) {
3409 WebMediaPlayer::TrackId trackId = client_->GetSelectedVideoTrackId();
3410 SelectedVideoTrackChanged(&trackId);
avayvod2135a642017-01-13 00:17:143411 }
3412 }
3413}
3414
3415void WebMediaPlayerImpl::DisableVideoTrackIfNeeded() {
3416 DCHECK(IsHidden());
3417
3418 // Don't change video track while the pipeline is resuming or seeking.
3419 if (is_pipeline_resuming_ || seeking_)
3420 return;
3421
3422 if (!video_track_disabled_ && ShouldDisableVideoWhenHidden()) {
3423 video_track_disabled_ = true;
Blink Reformat1c4d759e2017-04-09 16:34:543424 SelectedVideoTrackChanged(nullptr);
avayvod2135a642017-01-13 00:17:143425 }
3426}
3427
avayvodc4bfb0e62017-01-13 01:07:013428void WebMediaPlayerImpl::SetPipelineStatisticsForTest(
3429 const PipelineStatistics& stats) {
3430 pipeline_statistics_for_test_ = base::make_optional(stats);
3431}
3432
3433PipelineStatistics WebMediaPlayerImpl::GetPipelineStatistics() const {
3434 DCHECK(main_task_runner_->BelongsToCurrentThread());
3435
tguilbert350936ff2017-02-24 05:39:273436 return pipeline_statistics_for_test_.value_or(
Antonio Gomes81b56552019-05-15 22:15:283437 pipeline_controller_->GetStatistics());
avayvodc4bfb0e62017-01-13 01:07:013438}
3439
avayvodcc273dd2017-01-19 19:35:123440void WebMediaPlayerImpl::SetPipelineMediaDurationForTest(
3441 base::TimeDelta duration) {
3442 pipeline_media_duration_for_test_ = base::make_optional(duration);
3443}
3444
3445base::TimeDelta WebMediaPlayerImpl::GetPipelineMediaDuration() const {
3446 DCHECK(main_task_runner_->BelongsToCurrentThread());
3447
3448 return pipeline_media_duration_for_test_.value_or(
Antonio Gomes81b56552019-05-15 22:15:283449 pipeline_controller_->GetMediaDuration());
avayvodcc273dd2017-01-19 19:35:123450}
3451
Xiangjun Zhangba8724f482017-08-03 06:43:253452void WebMediaPlayerImpl::SwitchToRemoteRenderer(
3453 const std::string& remote_device_friendly_name) {
xjz4e5d4bf32017-02-15 21:26:353454 DCHECK(main_task_runner_->BelongsToCurrentThread());
Chris Cunningham89b4b762019-03-27 17:13:333455
3456 DCHECK(!is_remote_rendering_);
3457 is_remote_rendering_ = true;
3458
Thomas Guilbertb341bae02018-05-09 00:02:133459 DCHECK(!disable_pipeline_auto_suspend_);
Xiangjun Zhangba8724f482017-08-03 06:43:253460 disable_pipeline_auto_suspend_ = true;
Chris Cunninghamd9df58e2017-08-29 00:04:233461
3462 // Capabilities reporting should only be performed for local playbacks.
3463 video_decode_stats_reporter_.reset();
3464
Xiangjun Zhangba8724f482017-08-03 06:43:253465 // Requests to restart media pipeline. A remote renderer will be created via
3466 // the |renderer_factory_selector_|.
xjz4e5d4bf32017-02-15 21:26:353467 ScheduleRestart();
xjzdf9b67e2017-04-13 23:28:253468 if (client_) {
Xiangjun Zhangba8724f482017-08-03 06:43:253469 client_->MediaRemotingStarted(
3470 WebString::FromUTF8(remote_device_friendly_name));
xjzdf9b67e2017-04-13 23:28:253471 }
xjz4e5d4bf32017-02-15 21:26:353472}
3473
Xiangjun Zhang5e20cba42018-01-10 19:54:563474void WebMediaPlayerImpl::SwitchToLocalRenderer(
3475 MediaObserverClient::ReasonToSwitchToLocal reason) {
Xiangjun Zhangba8724f482017-08-03 06:43:253476 DCHECK(main_task_runner_->BelongsToCurrentThread());
Chris Cunningham89b4b762019-03-27 17:13:333477 if (!is_remote_rendering_)
Xiangjun Zhang12f55272018-07-30 23:19:373478 return; // Is currently with local renderer.
Chris Cunningham89b4b762019-03-27 17:13:333479 is_remote_rendering_ = false;
3480
3481 DCHECK(disable_pipeline_auto_suspend_);
Xiangjun Zhangba8724f482017-08-03 06:43:253482 disable_pipeline_auto_suspend_ = false;
Chris Cunninghamd9df58e2017-08-29 00:04:233483
3484 // Capabilities reporting may resume now that playback is local.
3485 CreateVideoDecodeStatsReporter();
3486
Xiangjun Zhangba8724f482017-08-03 06:43:253487 // Requests to restart media pipeline. A local renderer will be created via
3488 // the |renderer_factory_selector_|.
3489 ScheduleRestart();
3490 if (client_)
Xiangjun Zhang5e20cba42018-01-10 19:54:563491 client_->MediaRemotingStopped(GetSwitchToLocalMessage(reason));
Xiangjun Zhangba8724f482017-08-03 06:43:253492}
3493
dalecurtis4f6d14d2017-02-22 17:42:223494void WebMediaPlayerImpl::RecordUnderflowDuration(base::TimeDelta duration) {
3495 DCHECK(data_source_ || chunk_demuxer_);
xhwang68b3fab82017-05-17 21:31:463496
dalecurtis4f6d14d2017-02-22 17:42:223497 if (data_source_)
Jennifer Apacible82e25c92017-08-07 18:15:273498 UMA_HISTOGRAM_TIMES("Media.UnderflowDuration2.SRC", duration);
dalecurtis4f6d14d2017-02-22 17:42:223499 else
Jennifer Apacible82e25c92017-08-07 18:15:273500 UMA_HISTOGRAM_TIMES("Media.UnderflowDuration2.MSE", duration);
xhwang68b3fab82017-05-17 21:31:463501
3502 if (is_encrypted_)
Jennifer Apacible82e25c92017-08-07 18:15:273503 UMA_HISTOGRAM_TIMES("Media.UnderflowDuration2.EME", duration);
dalecurtis4f6d14d2017-02-22 17:42:223504}
3505
xhwang60802652017-04-19 07:29:583506#define UMA_HISTOGRAM_VIDEO_HEIGHT(name, sample) \
3507 UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 100, 10000, 50)
3508
3509void WebMediaPlayerImpl::RecordVideoNaturalSize(const gfx::Size& natural_size) {
3510 // Always report video natural size to MediaLog.
3511 media_log_->AddEvent(media_log_->CreateVideoSizeSetEvent(
3512 natural_size.width(), natural_size.height()));
Ted Meyer7f5b4e22019-11-21 03:21:193513 media_log_->SetProperty<MediaLogProperty::kResolution>(natural_size);
xhwang60802652017-04-19 07:29:583514
3515 if (initial_video_height_recorded_)
3516 return;
3517
3518 initial_video_height_recorded_ = true;
3519
3520 int height = natural_size.height();
3521
3522 if (load_type_ == kLoadTypeURL)
3523 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.SRC", height);
3524 else if (load_type_ == kLoadTypeMediaSource)
3525 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.MSE", height);
3526
3527 if (is_encrypted_)
3528 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.EME", height);
3529
3530 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.All", height);
3531}
3532
3533#undef UMA_HISTOGRAM_VIDEO_HEIGHT
3534
Greg Thompsonaa48ce8d2018-04-03 06:11:433535void WebMediaPlayerImpl::SetTickClockForTest(
3536 const base::TickClock* tick_clock) {
tzik2c963b872017-12-07 06:57:243537 tick_clock_ = tick_clock;
Antonio Gomes81b56552019-05-15 22:15:283538 buffered_data_source_host_->SetTickClockForTest(tick_clock);
hubbeb2d3efd2017-05-05 23:26:383539}
3540
Dale Curtis3899090ea2018-01-12 00:10:353541void WebMediaPlayerImpl::OnFirstFrame(base::TimeTicks frame_time) {
3542 DCHECK(!load_start_time_.is_null());
Dale Curtisff576552018-03-30 02:32:443543 DCHECK(!skip_metrics_due_to_startup_suspend_);
Dale Curtisc2c5dcb12018-04-16 23:21:293544 has_first_frame_ = true;
Dale Curtis7c63f2e22018-09-19 21:06:273545 needs_first_frame_ = false;
Dale Curtis3899090ea2018-01-12 00:10:353546 const base::TimeDelta elapsed = frame_time - load_start_time_;
3547 media_metrics_provider_->SetTimeToFirstFrame(elapsed);
3548 RecordTimingUMA("Media.TimeToFirstFrame", elapsed);
Dale Curtiscdfc6f22019-06-26 22:05:233549
3550 // Needed to signal HTMLVideoElement that it should remove the poster image.
Dale Curtis66790f32019-07-11 00:14:243551 if (client_ && has_poster_)
Dale Curtiscdfc6f22019-06-26 22:05:233552 client_->Repaint();
Dale Curtis3899090ea2018-01-12 00:10:353553}
3554
3555void WebMediaPlayerImpl::RecordTimingUMA(const std::string& key,
3556 base::TimeDelta elapsed) {
3557 if (chunk_demuxer_)
3558 base::UmaHistogramMediumTimes(key + ".MSE", elapsed);
3559 else
3560 base::UmaHistogramMediumTimes(key + ".SRC", elapsed);
3561 if (is_encrypted_)
3562 base::UmaHistogramMediumTimes(key + ".EME", elapsed);
3563}
3564
John Rummelldb5a7ef2018-05-16 00:28:013565void WebMediaPlayerImpl::RecordEncryptionScheme(
3566 const std::string& stream_name,
Yuchen Liub33bfc12019-11-08 20:16:123567 EncryptionScheme encryption_scheme) {
John Rummelldb5a7ef2018-05-16 00:28:013568 DCHECK(stream_name == "Audio" || stream_name == "Video");
3569
3570 // If the stream is not encrypted, don't record it.
Yuchen Liub33bfc12019-11-08 20:16:123571 if (encryption_scheme == EncryptionScheme::kUnencrypted)
John Rummelldb5a7ef2018-05-16 00:28:013572 return;
3573
3574 base::UmaHistogramEnumeration(
3575 "Media.EME.EncryptionScheme.Initial." + stream_name,
3576 DetermineEncryptionSchemeUMAValue(encryption_scheme),
3577 EncryptionSchemeUMA::kCount);
3578}
3579
Mounir Lamouri0484f40a2018-07-25 03:03:263580bool WebMediaPlayerImpl::IsInPictureInPicture() const {
3581 DCHECK(client_);
3582 return client_->DisplayType() ==
3583 WebMediaPlayer::DisplayType::kPictureInPicture;
3584}
3585
Dale Curtis5bba03232018-08-30 17:57:383586void WebMediaPlayerImpl::MaybeSetContainerName() {
Dale Curtisf01c8262018-09-04 23:50:433587 // MSE nor MediaPlayerRenderer provide container information.
3588 if (chunk_demuxer_ || using_media_player_renderer_)
Dale Curtis5bba03232018-08-30 17:57:383589 return;
3590
3591 // Pipeline startup failed before even getting a demuxer setup.
3592 if (!demuxer_)
3593 return;
3594
3595 // Container has already been set.
3596 if (highest_ready_state_ >= WebMediaPlayer::kReadyStateHaveMetadata)
3597 return;
3598
3599// If ffmpeg isn't enabled, we can't get the container name.
3600#if BUILDFLAG(ENABLE_FFMPEG)
3601 media_metrics_provider_->SetContainerName(
3602 static_cast<FFmpegDemuxer*>(demuxer_.get())->container());
3603#endif
3604}
3605
Dale Curtis18ad391b2019-05-30 23:25:093606void WebMediaPlayerImpl::MaybeUpdateBufferSizesForPlayback() {
3607 // Don't increase the MultiBufferDataSource buffer size until we've reached
3608 // kReadyStateHaveEnoughData. Otherwise we will unnecessarily slow down
3609 // playback startup -- it can instead be done for free after playback starts.
3610 if (!mb_data_source_ || highest_ready_state_ < kReadyStateHaveEnoughData)
3611 return;
3612
3613 mb_data_source_->MediaPlaybackRateChanged(playback_rate_);
3614 if (!paused_)
3615 mb_data_source_->MediaIsPlaying();
Becca Hughes7a85bf22019-07-24 16:16:583616
3617 // The playback rate has changed so we should rebuild the media position
3618 // state.
3619 UpdateMediaPositionState();
Dale Curtis18ad391b2019-05-30 23:25:093620}
3621
Dan Sanders6edfd782019-08-13 00:13:183622void WebMediaPlayerImpl::OnSimpleWatchTimerTick() {
3623 RecordSimpleWatchTimeUMA(reported_renderer_type_);
3624}
3625
[email protected]dbb3ff372019-10-15 19:09:423626GURL WebMediaPlayerImpl::GetSrcAfterRedirects() {
3627 return mb_data_source_ ? mb_data_source_->GetUrlAfterRedirects() : GURL();
3628}
3629
Thomas Guilberte90fe312019-11-07 22:27:563630void WebMediaPlayerImpl::SetCurrentFrameOverrideForTesting(
3631 scoped_refptr<VideoFrame> current_frame_override) {
3632 current_frame_override_ = current_frame_override;
3633}
3634
acolwell9e0840d2014-09-06 19:01:323635} // namespace media