blob: cbc2125670ad095884e7fae9719530f5a8453916 [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
99void RecordSimpleWatchTimeUMA(RendererFactorySelector::FactoryType type) {
100 UMA_HISTOGRAM_ENUMERATION(kWatchTimeHistogram, type,
101 RendererFactorySelector::FACTORY_TYPE_MAX + 1);
102}
103
Antonio Gomes3a858b52019-05-31 02:47:52104void SetSinkIdOnMediaThread(
105 scoped_refptr<blink::WebAudioSourceProviderImpl> sink,
106 const std::string& device_id,
107 OutputDeviceStatusCB callback) {
Daniel Chengc1710b52018-10-24 03:12:28108 sink->SwitchOutputDevice(device_id, std::move(callback));
guidouc7babef2015-10-22 00:42:35109}
110
Sergey Volk8b09c2c52018-12-12 23:20:40111bool IsBackgroundSuspendEnabled(const WebMediaPlayerImpl* wmpi) {
Luke Halliwell7a8a8982018-07-25 01:07:05112 // TODO(crbug.com/867146): remove these switches.
113 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
114 switches::kDisableMediaSuspend))
115 return false;
116 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
117 switches::kEnableMediaSuspend))
118 return true;
119
Sergey Volk8b09c2c52018-12-12 23:20:40120 return wmpi->IsBackgroundMediaSuspendEnabled();
dalecurtis0431cbf2016-03-12 01:19:43121}
122
avayvod48a8be52016-08-04 19:52:50123bool IsResumeBackgroundVideosEnabled() {
124 return base::FeatureList::IsEnabled(kResumeBackgroundVideo);
125}
126
avayvod01201332017-04-14 00:27:15127bool IsBackgroundVideoPauseOptimizationEnabled() {
128 return base::FeatureList::IsEnabled(kBackgroundVideoPauseOptimization);
129}
130
sandersd50a635e2016-04-04 22:50:09131bool IsNetworkStateError(blink::WebMediaPlayer::NetworkState state) {
Blink Reformat1c4d759e2017-04-09 16:34:54132 bool result = state == blink::WebMediaPlayer::kNetworkStateFormatError ||
133 state == blink::WebMediaPlayer::kNetworkStateNetworkError ||
134 state == blink::WebMediaPlayer::kNetworkStateDecodeError;
135 DCHECK_EQ(state > blink::WebMediaPlayer::kNetworkStateLoaded, result);
sandersd50a635e2016-04-04 22:50:09136 return result;
137}
138
sandersd2c478422016-08-02 01:19:25139gfx::Size GetRotatedVideoSize(VideoRotation rotation, gfx::Size natural_size) {
140 if (rotation == VIDEO_ROTATION_90 || rotation == VIDEO_ROTATION_270)
141 return gfx::Size(natural_size.height(), natural_size.width());
142 return natural_size;
143}
144
Xiaohan Wangf63505d2017-10-21 08:00:53145void RecordEncryptedEvent(bool encrypted_event_fired) {
146 UMA_HISTOGRAM_BOOLEAN("Media.EME.EncryptedEvent", encrypted_event_fired);
147}
148
sandersd35d2c3f2017-01-14 02:04:42149// How much time must have elapsed since loading last progressed before we
150// assume that the decoder will have had time to complete preroll.
151constexpr base::TimeDelta kPrerollAttemptTimeout =
watkd026f792016-11-05 00:28:51152 base::TimeDelta::FromSeconds(3);
153
Matt Wolenetz6010f6c2017-10-18 00:44:36154// Maximum number, per-WMPI, of media logs of playback rate changes.
155constexpr int kMaxNumPlaybackRateLogs = 10;
156
Gyuyoung Kimf99f5f32019-09-26 03:45:15157int GetSwitchToLocalMessage(MediaObserverClient::ReasonToSwitchToLocal reason) {
Xiangjun Zhang5e20cba42018-01-10 19:54:56158 switch (reason) {
159 case MediaObserverClient::ReasonToSwitchToLocal::NORMAL:
Gyuyoung Kimf99f5f32019-09-26 03:45:15160 return IDS_MEDIA_REMOTING_STOP_TEXT;
Xiangjun Zhang5e20cba42018-01-10 19:54:56161 case MediaObserverClient::ReasonToSwitchToLocal::POOR_PLAYBACK_QUALITY:
Gyuyoung Kimf99f5f32019-09-26 03:45:15162 return IDS_MEDIA_REMOTING_STOP_BY_PLAYBACK_QUALITY_TEXT;
Xiangjun Zhang5e20cba42018-01-10 19:54:56163 case MediaObserverClient::ReasonToSwitchToLocal::PIPELINE_ERROR:
Gyuyoung Kimf99f5f32019-09-26 03:45:15164 return IDS_MEDIA_REMOTING_STOP_BY_ERROR_TEXT;
Xiangjun Zhang5e20cba42018-01-10 19:54:56165 case MediaObserverClient::ReasonToSwitchToLocal::ROUTE_TERMINATED:
Gyuyoung Kimf99f5f32019-09-26 03:45:15166 return blink::WebMediaPlayerClient::kMediaRemotingStopNoText;
Xiangjun Zhang5e20cba42018-01-10 19:54:56167 }
168 NOTREACHED();
169 // To suppress compiler warning on Windows.
Gyuyoung Kimf99f5f32019-09-26 03:45:15170 return blink::WebMediaPlayerClient::kMediaRemotingStopNoText;
Xiangjun Zhang5e20cba42018-01-10 19:54:56171}
172
John Rummelldb5a7ef2018-05-16 00:28:01173// These values are persisted to UMA. Entries should not be renumbered and
174// numeric values should never be reused.
Yuchen Liub33bfc12019-11-08 20:16:12175// TODO(crbug.com/825041): This should use EncryptionScheme when kUnencrypted
John Rummelldb5a7ef2018-05-16 00:28:01176// removed.
177enum class EncryptionSchemeUMA { kCenc = 0, kCbcs = 1, kCount };
178
179EncryptionSchemeUMA DetermineEncryptionSchemeUMAValue(
Yuchen Liub33bfc12019-11-08 20:16:12180 EncryptionScheme encryption_scheme) {
181 if (encryption_scheme == EncryptionScheme::kCbcs)
John Rummelldb5a7ef2018-05-16 00:28:01182 return EncryptionSchemeUMA::kCbcs;
183
Yuchen Liub33bfc12019-11-08 20:16:12184 DCHECK_EQ(encryption_scheme, EncryptionScheme::kCenc);
John Rummelldb5a7ef2018-05-16 00:28:01185 return EncryptionSchemeUMA::kCenc;
186}
187
Pavel Feldman023c3e62018-08-28 17:59:47188#if BUILDFLAG(ENABLE_FFMPEG)
Dale Curtisb8139f72018-08-27 23:28:48189// Returns true if |url| represents (or is likely to) a local file.
190bool IsLocalFile(const GURL& url) {
191 return url.SchemeIsFile() || url.SchemeIsFileSystem() ||
192 url.SchemeIs(url::kContentScheme) ||
193 url.SchemeIs(url::kContentIDScheme) ||
194 url.SchemeIs("chrome-extension");
195}
Pavel Feldman023c3e62018-08-28 17:59:47196#endif
Dale Curtisb8139f72018-08-27 23:28:48197
Dale Curtisf273f8f2018-12-13 23:40:33198// Handles destruction of media::Renderer dependent components after the
199// renderer has been destructed on the media thread.
200void DestructionHelper(
201 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
202 scoped_refptr<base::SingleThreadTaskRunner> vfc_task_runner,
203 std::unique_ptr<Demuxer> demuxer,
204 std::unique_ptr<DataSource> data_source,
205 std::unique_ptr<VideoFrameCompositor> compositor,
206 std::unique_ptr<CdmContextRef> cdm_context_1,
207 std::unique_ptr<CdmContextRef> cdm_context_2,
208 std::unique_ptr<MediaLog> media_log,
209 std::unique_ptr<RendererFactorySelector> renderer_factory_selector,
210 std::unique_ptr<blink::WebSurfaceLayerBridge> bridge,
211 bool is_chunk_demuxer) {
212 // We release |bridge| after pipeline stop to ensure layout tests receive
213 // painted video frames before test harness exit.
214 main_task_runner->DeleteSoon(FROM_HERE, std::move(bridge));
215
216 // Since the media::Renderer is gone we can now destroy the compositor and
217 // renderer factory selector.
218 vfc_task_runner->DeleteSoon(FROM_HERE, std::move(compositor));
219 main_task_runner->DeleteSoon(FROM_HERE, std::move(renderer_factory_selector));
220
221 // ChunkDemuxer can be deleted on any thread, but other demuxers are bound to
222 // the main thread and must be deleted there now that the renderer is gone.
223 if (!is_chunk_demuxer) {
224 main_task_runner->DeleteSoon(FROM_HERE, std::move(demuxer));
225 main_task_runner->DeleteSoon(FROM_HERE, std::move(data_source));
226 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_1));
227 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_2));
228 main_task_runner->DeleteSoon(FROM_HERE, std::move(media_log));
229 return;
230 }
231
232 // ChunkDemuxer's streams may contain much buffered, compressed media that
233 // may need to be paged back in during destruction. Paging delay may exceed
234 // the renderer hang monitor's threshold on at least Windows while also
235 // blocking other work on the renderer main thread, so we do the actual
236 // destruction in the background without blocking WMPI destruction or
237 // |task_runner|. On advice of task_scheduler OWNERS, MayBlock() is not
238 // used because virtual memory overhead is not considered blocking I/O; and
239 // CONTINUE_ON_SHUTDOWN is used to allow process termination to not block on
240 // completing the task.
Sami Kyostila127d6632019-08-06 21:32:25241 base::PostTask(
Dale Curtisf273f8f2018-12-13 23:40:33242 FROM_HERE,
Sami Kyostila127d6632019-08-06 21:32:25243 {base::ThreadPool(), base::TaskPriority::BEST_EFFORT,
Dale Curtisf273f8f2018-12-13 23:40:33244 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
245 base::BindOnce(
246 [](scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
247 std::unique_ptr<Demuxer> demuxer_to_destroy,
248 std::unique_ptr<CdmContextRef> cdm_context_1,
249 std::unique_ptr<CdmContextRef> cdm_context_2,
250 std::unique_ptr<MediaLog> media_log) {
251 SCOPED_UMA_HISTOGRAM_TIMER("Media.MSE.DemuxerDestructionTime");
252 demuxer_to_destroy.reset();
253 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_1));
254 main_task_runner->DeleteSoon(FROM_HERE, std::move(cdm_context_2));
255 main_task_runner->DeleteSoon(FROM_HERE, std::move(media_log));
256 },
257 std::move(main_task_runner), std::move(demuxer),
258 std::move(cdm_context_1), std::move(cdm_context_2),
259 std::move(media_log)));
260}
261
Ted Meyer7f5b4e22019-11-21 03:21:19262std::string SanitizeUserStringProperty(blink::WebString value) {
Ted Meyera698afe2019-11-06 20:58:03263 std::string converted = value.Utf8();
Ted Meyer7f5b4e22019-11-21 03:21:19264 return base::IsStringUTF8(converted) ? converted : "[invalid property]";
Ted Meyera698afe2019-11-06 20:58:03265}
266
[email protected]8931c41a2009-07-07 17:31:49267} // namespace
268
[email protected]6683e1b2014-04-10 01:45:38269class BufferedDataSourceHostImpl;
270
Takashi Toyoshima2e01e692018-11-16 03:23:27271STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeUnspecified,
danakj365175c2016-02-06 00:37:37272 UrlData::CORS_UNSPECIFIED);
Takashi Toyoshima2e01e692018-11-16 03:23:27273STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeAnonymous, UrlData::CORS_ANONYMOUS);
274STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeUseCredentials,
danakj365175c2016-02-06 00:37:37275 UrlData::CORS_USE_CREDENTIALS);
[email protected]a5a01102012-06-06 17:01:24276
[email protected]5b5bb9d2010-10-22 19:57:36277WebMediaPlayerImpl::WebMediaPlayerImpl(
[email protected]35b2a972014-04-04 15:50:22278 blink::WebLocalFrame* frame,
[email protected]180ef242013-11-07 06:50:46279 blink::WebMediaPlayerClient* client,
srirama.m26f864d02015-07-14 05:21:46280 blink::WebMediaPlayerEncryptedMediaClient* encrypted_client,
Antonio Gomes423df612019-07-11 12:40:07281 blink::WebMediaPlayerDelegate* delegate,
tguilbert70d2a00a2017-04-25 00:30:44282 std::unique_ptr<RendererFactorySelector> renderer_factory_selector,
Alok Priyadarshi7166d4d2017-07-29 04:04:25283 UrlIndex* url_index,
CJ DiMegliod7ac6772017-11-10 00:19:06284 std::unique_ptr<VideoFrameCompositor> compositor,
dalecurtis9cddc0b2017-04-19 21:23:38285 std::unique_ptr<WebMediaPlayerParams> params)
[email protected]f6af7592014-02-28 10:09:11286 : frame_(frame),
Alexander Timin310368112017-09-13 10:01:44287 main_task_runner_(
288 frame->GetTaskRunner(blink::TaskType::kMediaElementEvent)),
dalecurtis9cddc0b2017-04-19 21:23:38289 media_task_runner_(params->media_task_runner()),
290 worker_task_runner_(params->worker_task_runner()),
291 media_log_(params->take_media_log()),
[email protected]5badb082010-06-11 17:40:15292 client_(client),
srirama.m26f864d02015-07-14 05:21:46293 encrypted_client_(encrypted_client),
[email protected]baff4512011-10-19 18:21:07294 delegate_(delegate),
dalecurtis9cddc0b2017-04-19 21:23:38295 defer_load_cb_(params->defer_load_cb()),
dalecurtis9cddc0b2017-04-19 21:23:38296 adjust_allocated_memory_cb_(params->adjust_allocated_memory_cb()),
tzik2c963b872017-12-07 06:57:24297 tick_clock_(base::DefaultTickClock::GetInstance()),
hubbe5f0ad43b2015-12-14 20:57:26298 url_index_(url_index),
CJ DiMeglioc60a5cf2017-09-27 20:08:41299 context_provider_(params->context_provider()),
CJ DiMegliod7ac6772017-11-10 00:19:06300 vfc_task_runner_(params->video_frame_compositor_task_runner()),
301 compositor_(std::move(compositor)),
tguilbert70d2a00a2017-04-25 00:30:44302 renderer_factory_selector_(std::move(renderer_factory_selector)),
dalecurtis9cddc0b2017-04-19 21:23:38303 observer_(params->media_observer()),
servolkf94b4602017-01-31 16:44:27304 enable_instant_source_buffer_gc_(
dalecurtis9cddc0b2017-04-19 21:23:38305 params->enable_instant_source_buffer_gc()),
shaktisahu24189c12017-03-11 17:42:55306 embedded_media_experience_enabled_(
liberato2ff93ad2017-05-17 07:28:24307 params->embedded_media_experience_enabled()),
[email protected]69db58f2018-09-26 20:27:56308 surface_layer_mode_(params->use_surface_layer_for_video()),
CJ DiMeglio96c18b692018-07-04 03:39:06309 create_bridge_callback_(params->create_bridge_callback()),
liberato2ff93ad2017-05-17 07:28:24310 request_routing_token_cb_(params->request_routing_token_cb()),
Dale Curtis1adbe6a2017-08-02 02:09:13311 overlay_routing_token_(OverlayInfo::RoutingToken()),
Sergey Volk8b09c2c52018-12-12 23:20:40312 media_metrics_provider_(params->take_metrics_provider()),
313 is_background_suspend_enabled_(params->IsBackgroundSuspendEnabled()),
Junbo Kefba620b2019-01-16 02:54:36314 is_background_video_playback_enabled_(
315 params->IsBackgroundVideoPlaybackEnabled()),
Sergey Volk8b09c2c52018-12-12 23:20:40316 is_background_video_track_optimization_supported_(
Dan Sanders6edfd782019-08-13 00:13:18317 params->IsBackgroundVideoTrackOptimizationSupported()),
318 reported_renderer_type_(RendererFactorySelector::DEFAULT),
319 simple_watch_timer_(
320 base::BindRepeating(&WebMediaPlayerImpl::OnSimpleWatchTimerTick,
321 base::Unretained(this)),
322 base::BindRepeating(&WebMediaPlayerImpl::GetCurrentTimeInternal,
[email protected]91fd3162019-09-05 23:51:32323 base::Unretained(this))),
324 will_play_helper_(nullptr) {
xhwang51139732017-02-24 19:36:08325 DVLOG(1) << __func__;
Dale Curtise25163812018-09-21 22:13:39326 DCHECK(adjust_allocated_memory_cb_);
tguilbert70d2a00a2017-04-25 00:30:44327 DCHECK(renderer_factory_selector_);
servolkef1e5ef2016-03-25 04:55:26328 DCHECK(client_);
tguilbert1bb1c782017-01-23 21:15:11329 DCHECK(delegate_);
dalecurtis83266c72015-10-29 18:43:20330
Antonio Gomes142f32a2019-05-15 23:32:56331 weak_this_ = weak_factory_.GetWeakPtr();
332
Xiaohan Wang2480de72019-11-15 01:44:47333 // Using base::Unretained(this) is safe because the |pipeline| is owned by
334 // |this| and the callback will always be made on the main task runner.
335 // Not using BindToCurrentLoop() because CreateRenderer() is a sync call.
336 auto pipeline = std::make_unique<PipelineImpl>(
337 media_task_runner_, main_task_runner_,
338 base::BindRepeating(&WebMediaPlayerImpl::CreateRenderer,
339 base::Unretained(this)),
340 media_log_.get());
341
Antonio Gomes81b56552019-05-15 22:15:28342 pipeline_controller_ = std::make_unique<PipelineController>(
Xiaohan Wang2480de72019-11-15 01:44:47343 std::move(pipeline),
Antonio Gomes142f32a2019-05-15 23:32:56344 base::BindRepeating(&WebMediaPlayerImpl::OnPipelineSeeked, weak_this_),
345 base::BindRepeating(&WebMediaPlayerImpl::OnPipelineSuspended, weak_this_),
Antonio Gomes81b56552019-05-15 22:15:28346 base::BindRepeating(&WebMediaPlayerImpl::OnBeforePipelineResume,
Antonio Gomes142f32a2019-05-15 23:32:56347 weak_this_),
348 base::BindRepeating(&WebMediaPlayerImpl::OnPipelineResumed, weak_this_),
349 base::BindRepeating(&WebMediaPlayerImpl::OnError, weak_this_));
Antonio Gomes81b56552019-05-15 22:15:28350
351 buffered_data_source_host_ = std::make_unique<BufferedDataSourceHostImpl>(
Antonio Gomes142f32a2019-05-15 23:32:56352 base::BindRepeating(&WebMediaPlayerImpl::OnProgress, weak_this_),
Antonio Gomes81b56552019-05-15 22:15:28353 tick_clock_);
354
[email protected]c8d574722017-08-30 20:53:43355 // If we're supposed to force video overlays, then make sure that they're
356 // enabled all the time.
357 always_enable_overlays_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
tsunghungee562e92016-07-20 18:03:31358 switches::kForceVideoOverlays);
359
Jinsong Fan982342112019-11-07 23:45:45360 if (base::FeatureList::IsEnabled(kOverlayFullscreenVideo))
361 overlay_mode_ = OverlayMode::kUseAndroidOverlay;
362 else
liberato2ff93ad2017-05-17 07:28:24363 overlay_mode_ = OverlayMode::kNoOverlays;
ampea73f792017-01-19 04:05:39364
tguilbert1bb1c782017-01-23 21:15:11365 delegate_id_ = delegate_->AddObserver(this);
366 delegate_->SetIdle(delegate_id_, true);
sandersd1e49fb62015-12-12 01:18:06367
dalecurtis2cff7f372017-05-24 08:30:08368 media_log_->AddEvent(media_log_->CreateCreatedEvent(
369 url::Origin(frame_->GetSecurityOrigin()).GetURL().spec()));
Ted Meyera698afe2019-11-06 20:58:03370
Ted Meyer7f5b4e22019-11-21 03:21:19371 media_log_->SetProperty<MediaLogProperty::kFrameUrl>(
372 SanitizeUserStringProperty(frame_->GetDocument().Url().GetString()));
373 media_log_->SetProperty<MediaLogProperty::kFrameTitle>(
374 SanitizeUserStringProperty(frame_->GetDocument().Title()));
[email protected]52b0b212018-10-10 05:25:28375
dalecurtis9cddc0b2017-04-19 21:23:38376 if (params->initial_cdm())
Chris Cunninghamd4a00192019-03-21 20:02:49377 SetCdmInternal(params->initial_cdm());
xhwang0ad11e512014-11-25 23:43:09378
Xiaohan Wangf63505d2017-10-21 08:00:53379 // Report a false "EncrytpedEvent" here as a baseline.
380 RecordEncryptedEvent(false);
381
xhwangf94a634d2014-10-22 22:07:27382 // TODO(xhwang): When we use an external Renderer, many methods won't work,
xhwang6fa356202014-12-11 00:44:12383 // e.g. GetCurrentFrameFromCompositor(). See http://crbug.com/434861
Antonio Gomes3a858b52019-05-31 02:47:52384 audio_source_provider_ = new blink::WebAudioSourceProviderImpl(
dalecurtis9cddc0b2017-04-19 21:23:38385 params->audio_renderer_sink(), media_log_.get());
xjz4e5d4bf32017-02-15 21:26:35386
387 if (observer_)
388 observer_->SetClient(this);
Hajime Hoshi8bb37dc2017-12-19 09:35:10389
390 memory_usage_reporting_timer_.SetTaskRunner(
Hajime Hoshib5a26ee2018-05-14 12:47:51391 frame_->GetTaskRunner(blink::TaskType::kInternalMedia));
John Delaney6c8ecc1b2018-10-21 19:07:29392
Thomas Guilbert901808982019-07-03 20:38:18393#if defined(OS_ANDROID)
Thomas Guilbertf6d0702e2019-09-12 23:40:14394 renderer_factory_selector_->SetRemotePlayStateChangeCB(
395 BindToCurrentLoop(base::BindRepeating(
396 &WebMediaPlayerImpl::OnRemotePlayStateChange, weak_this_)));
Thomas Guilbert901808982019-07-03 20:38:18397#endif // defined (OS_ANDROID)
[email protected]ec9212f2008-12-18 21:40:36398}
399
[email protected]4e6be3f2009-05-07 02:24:44400WebMediaPlayerImpl::~WebMediaPlayerImpl() {
xhwang51139732017-02-24 19:36:08401 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43402 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53403
xhwang51139732017-02-24 19:36:08404 if (set_cdm_result_) {
Chris Cunninghamd4a00192019-03-21 20:02:49405 DVLOG(2)
406 << "Resolve pending SetCdmInternal() when media player is destroyed.";
Blink Reformat1c4d759e2017-04-09 16:34:54407 set_cdm_result_->Complete();
xhwang51139732017-02-24 19:36:08408 set_cdm_result_.reset();
409 }
410
alokp1116967f2016-06-11 17:30:56411 suppress_destruction_errors_ = true;
tguilbert1bb1c782017-01-23 21:15:11412
413 delegate_->PlayerGone(delegate_id_);
414 delegate_->RemoveObserver(delegate_id_);
[email protected]baff4512011-10-19 18:21:07415
dalecurtis04bdb582016-08-17 22:15:23416 // Finalize any watch time metrics before destroying the pipeline.
417 watch_time_reporter_.reset();
418
tguilbert350936ff2017-02-24 05:39:27419 // The underlying Pipeline must be stopped before it is destroyed.
Dale Curtisf273f8f2018-12-13 23:40:33420 //
421 // Note: This destruction happens synchronously on the media thread and
422 // |demuxer_|, |data_source_|, |compositor_|, and |media_log_| must outlive
423 // this process. They will be destructed by the DestructionHelper below
424 // after trampolining through the media thread.
Antonio Gomes81b56552019-05-15 22:15:28425 pipeline_controller_->Stop();
[email protected]f6af7592014-02-28 10:09:11426
dalecurtis83266c72015-10-29 18:43:20427 if (last_reported_memory_usage_)
428 adjust_allocated_memory_cb_.Run(-last_reported_memory_usage_);
429
dalecurtise1edb312016-06-22 02:33:21430 // Destruct compositor resources in the proper order.
danakj8d204a42018-05-18 18:05:35431 client_->SetCcLayer(nullptr);
CJ DiMeglio2302d202017-08-31 08:38:04432
Xiangjun Zhang5e20cba42018-01-10 19:54:56433 client_->MediaRemotingStopped(
Gyuyoung Kimf99f5f32019-09-26 03:45:15434 blink::WebMediaPlayerClient::kMediaRemotingStopNoText);
Xiangjun Zhang87299142017-09-13 20:35:03435
Dale Curtisf273f8f2018-12-13 23:40:33436 if (!surface_layer_for_video_enabled_ && video_layer_)
danakj25f030112018-05-11 18:26:54437 video_layer_->StopUsingProvider();
Matt Wolenetz95af6362018-01-04 20:23:42438
Dan Sanders6edfd782019-08-13 00:13:18439 simple_watch_timer_.Stop();
Ted Meyer257b682a2019-11-01 20:50:51440 media_log_->OnWebMediaPlayerDestroyed();
[email protected]ec9212f2008-12-18 21:40:36441
Dale Curtisf273f8f2018-12-13 23:40:33442 if (data_source_)
443 data_source_->Stop();
444
445 // Disconnect from the surface layer. We still preserve the |bridge_| until
446 // after pipeline shutdown to ensure any pending frames are painted for tests.
447 if (bridge_)
448 bridge_->ClearObserver();
449
Dale Curtisc96a3542018-12-17 22:15:23450 // Disconnect from the MediaObserver implementation since it's lifetime is
451 // tied to the RendererFactorySelector which can't be destroyed until after
452 // the Pipeline stops.
453 //
454 // Note: We can't use a WeakPtr with the RendererFactory because its methods
455 // are called on the media thread and this destruction takes place on the
456 // renderer thread.
457 if (observer_)
458 observer_->SetClient(nullptr);
459
[email protected]91fd3162019-09-05 23:51:32460 // If we're in the middle of an observation, then finish it.
461 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(false));
462
Dale Curtisf273f8f2018-12-13 23:40:33463 // Handle destruction of things that need to be destructed after the pipeline
464 // completes stopping on the media thread.
465 media_task_runner_->PostTask(
Matt Wolenetz95af6362018-01-04 20:23:42466 FROM_HERE,
Dale Curtisf273f8f2018-12-13 23:40:33467 base::BindOnce(&DestructionHelper, std::move(main_task_runner_),
468 std::move(vfc_task_runner_), std::move(demuxer_),
469 std::move(data_source_), std::move(compositor_),
470 std::move(cdm_context_ref_),
471 std::move(pending_cdm_context_ref_), std::move(media_log_),
472 std::move(renderer_factory_selector_), std::move(bridge_),
473 !!chunk_demuxer_));
Matt Wolenetz95af6362018-01-04 20:23:42474}
475
chcunningham707b821e2018-05-29 08:42:19476WebMediaPlayer::LoadTiming WebMediaPlayerImpl::Load(
477 LoadType load_type,
478 const blink::WebMediaPlayerSource& source,
Takashi Toyoshima2e01e692018-11-16 03:23:27479 CorsMode cors_mode) {
guidou9bfe4e2f2016-04-09 08:31:19480 // Only URL or MSE blob URL is supported.
Blink Reformat1c4d759e2017-04-09 16:34:54481 DCHECK(source.IsURL());
482 blink::WebURL url = source.GetAsURL();
Xiaohan Wang81fd0022017-07-11 17:45:24483 DVLOG(1) << __func__ << "(" << load_type << ", " << GURL(url) << ", "
484 << cors_mode << ")";
chcunningham707b821e2018-05-29 08:42:19485
486 bool is_deferred = false;
487
Dale Curtise25163812018-09-21 22:13:39488 if (defer_load_cb_) {
chcunningham707b821e2018-05-29 08:42:19489 is_deferred = defer_load_cb_.Run(base::BindOnce(
Antonio Gomes142f32a2019-05-15 23:32:56490 &WebMediaPlayerImpl::DoLoad, weak_this_, load_type, url, cors_mode));
chcunningham707b821e2018-05-29 08:42:19491 } else {
492 DoLoad(load_type, url, cors_mode);
[email protected]d726eddc2013-07-02 22:25:55493 }
chcunningham707b821e2018-05-29 08:42:19494
495 return is_deferred ? LoadTiming::kDeferred : LoadTiming::kImmediate;
[email protected]62e5e682013-03-07 23:53:24496}
497
CJ DiMeglio013d4c472017-11-21 03:27:30498void WebMediaPlayerImpl::OnWebLayerUpdated() {}
499
danakj6a062b112018-05-17 16:25:45500void WebMediaPlayerImpl::RegisterContentsLayer(cc::Layer* layer) {
CJ DiMeglio2302d202017-08-31 08:38:04501 DCHECK(bridge_);
CJ DiMeglioa2b13fbc2018-06-27 00:50:59502 bridge_->SetContentsOpaque(opaque_);
danakj8d204a42018-05-18 18:05:35503 client_->SetCcLayer(layer);
CJ DiMeglio013d4c472017-11-21 03:27:30504}
505
danakj6a062b112018-05-17 16:25:45506void WebMediaPlayerImpl::UnregisterContentsLayer(cc::Layer* layer) {
507 // |client_| will unregister its cc::Layer if given a nullptr.
danakj8d204a42018-05-18 18:05:35508 client_->SetCcLayer(nullptr);
CJ DiMeglio2302d202017-08-31 08:38:04509}
510
Jennifer Apaciblec45fd052018-02-25 12:04:55511void WebMediaPlayerImpl::OnSurfaceIdUpdated(viz::SurfaceId surface_id) {
Jennifer Apaciblec45fd052018-02-25 12:04:55512 // TODO(726619): Handle the behavior when Picture-in-Picture mode is
513 // disabled.
Jennifer Apacible2b1dc5eb2018-04-27 16:23:28514 // The viz::SurfaceId may be updated when the video begins playback or when
515 // the size of the video changes.
Mounir Lamouri99ba5a62019-02-12 01:27:47516 if (client_)
517 client_->OnPictureInPictureStateChange();
Jennifer Apaciblec45fd052018-02-25 12:04:55518}
519
tsunghungee562e92016-07-20 18:03:31520void WebMediaPlayerImpl::EnableOverlay() {
521 overlay_enabled_ = true;
[email protected]f7df5b342018-07-13 20:22:13522 if (request_routing_token_cb_ &&
523 overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberatofe8f9692017-06-08 19:17:36524 overlay_routing_token_is_pending_ = true;
liberato2ff93ad2017-05-17 07:28:24525 token_available_cb_.Reset(
Antonio Gomes142f32a2019-05-15 23:32:56526 base::Bind(&WebMediaPlayerImpl::OnOverlayRoutingToken, weak_this_));
liberato2ff93ad2017-05-17 07:28:24527 request_routing_token_cb_.Run(token_available_cb_.callback());
watkf835a792016-06-24 23:24:40528 }
tsunghungee562e92016-07-20 18:03:31529
liberato2ff93ad2017-05-17 07:28:24530 // We have requested (and maybe already have) overlay information. If the
531 // restarted decoder requests overlay information, then we'll defer providing
532 // it if it hasn't arrived yet. Otherwise, this would be a race, since we
533 // don't know if the request for overlay info or restart will complete first.
tsunghungee562e92016-07-20 18:03:31534 if (decoder_requires_restart_for_overlay_)
watkdee516f2016-02-18 02:22:19535 ScheduleRestart();
536}
537
tsunghungee562e92016-07-20 18:03:31538void WebMediaPlayerImpl::DisableOverlay() {
539 overlay_enabled_ = false;
Jinsong Fan982342112019-11-07 23:45:45540 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberato2ff93ad2017-05-17 07:28:24541 token_available_cb_.Cancel();
liberatofe8f9692017-06-08 19:17:36542 overlay_routing_token_is_pending_ = false;
543 overlay_routing_token_ = OverlayInfo::RoutingToken();
liberato2ff93ad2017-05-17 07:28:24544 }
tsunghungee562e92016-07-20 18:03:31545
546 if (decoder_requires_restart_for_overlay_)
watkdee516f2016-02-18 02:22:19547 ScheduleRestart();
liberato2ff93ad2017-05-17 07:28:24548 else
549 MaybeSendOverlayInfoToDecoder();
watkdee516f2016-02-18 02:22:19550}
551
Blink Reformat1c4d759e2017-04-09 16:34:54552void WebMediaPlayerImpl::EnteredFullscreen() {
liberatofe8f9692017-06-08 19:17:36553 overlay_info_.is_fullscreen = true;
554
[email protected]c8d574722017-08-30 20:53:43555 // |always_enable_overlays_| implies that we're already in overlay mode, so
556 // take no action here. Otherwise, switch to an overlay if it's allowed and
557 // if it will display properly.
558 if (!always_enable_overlays_ && overlay_mode_ != OverlayMode::kNoOverlays &&
liberato2fd111be2017-01-04 00:25:06559 DoesOverlaySupportMetadata()) {
tsunghungee562e92016-07-20 18:03:31560 EnableOverlay();
liberato2fd111be2017-01-04 00:25:06561 }
liberato2ff93ad2017-05-17 07:28:24562
liberatofe8f9692017-06-08 19:17:36563 // We send this only if we can send multiple calls. Otherwise, either (a)
564 // we already sent it and we don't have a callback anyway (we reset it when
565 // it's called in restart mode), or (b) we'll send this later when the surface
566 // actually arrives. GVD assumes that the first overlay info will have the
567 // routing information. Note that we set |is_fullscreen_| earlier, so that
568 // if EnableOverlay() can include fullscreen info in case it sends the overlay
569 // info before returning.
570 if (!decoder_requires_restart_for_overlay_)
571 MaybeSendOverlayInfoToDecoder();
tsunghungee562e92016-07-20 18:03:31572}
573
Blink Reformat1c4d759e2017-04-09 16:34:54574void WebMediaPlayerImpl::ExitedFullscreen() {
liberatofe8f9692017-06-08 19:17:36575 overlay_info_.is_fullscreen = false;
576
[email protected]c8d574722017-08-30 20:53:43577 // If we're in overlay mode, then exit it unless we're supposed to allow
578 // overlays all the time.
579 if (!always_enable_overlays_ && overlay_enabled_)
tsunghungee562e92016-07-20 18:03:31580 DisableOverlay();
liberato2ff93ad2017-05-17 07:28:24581
liberatofe8f9692017-06-08 19:17:36582 // See EnteredFullscreen for why we do this.
583 if (!decoder_requires_restart_for_overlay_)
584 MaybeSendOverlayInfoToDecoder();
tsunghungee562e92016-07-20 18:03:31585}
586
Chisoon Jeong81080c922019-09-03 23:40:18587void WebMediaPlayerImpl::BecameDominantVisibleContent(bool is_dominant) {
xjzcdbbe732016-12-03 20:47:42588 if (observer_)
Chisoon Jeong81080c922019-09-03 23:40:18589 observer_->OnBecameDominantVisibleContent(is_dominant);
xjzcdbbe732016-12-03 20:47:42590}
591
Blink Reformat1c4d759e2017-04-09 16:34:54592void WebMediaPlayerImpl::SetIsEffectivelyFullscreen(
François Beaufortad6c5232018-02-26 11:00:44593 blink::WebFullscreenVideoStatus fullscreen_video_status) {
594 delegate_->SetIsEffectivelyFullscreen(delegate_id_, fullscreen_video_status);
zqzhangabc08242017-03-02 16:07:14595}
596
Mounir Lamouri41a79c62017-06-06 12:53:16597void WebMediaPlayerImpl::OnHasNativeControlsChanged(bool has_native_controls) {
598 if (!watch_time_reporter_)
599 return;
600
601 if (has_native_controls)
602 watch_time_reporter_->OnNativeControlsEnabled();
603 else
604 watch_time_reporter_->OnNativeControlsDisabled();
605}
606
Mounir Lamourif9af74e72017-06-19 19:31:45607void WebMediaPlayerImpl::OnDisplayTypeChanged(
608 WebMediaPlayer::DisplayType display_type) {
Mounir Lamouri0484f40a2018-07-25 03:03:26609 if (surface_layer_for_video_enabled_) {
610 vfc_task_runner_->PostTask(
611 FROM_HERE,
612 base::BindOnce(
613 &VideoFrameCompositor::SetForceSubmit,
614 base::Unretained(compositor_.get()),
615 display_type == WebMediaPlayer::DisplayType::kPictureInPicture));
616 }
617
Mounir Lamourif9af74e72017-06-19 19:31:45618 if (!watch_time_reporter_)
619 return;
620
621 switch (display_type) {
622 case WebMediaPlayer::DisplayType::kInline:
623 watch_time_reporter_->OnDisplayTypeInline();
624 break;
625 case WebMediaPlayer::DisplayType::kFullscreen:
626 watch_time_reporter_->OnDisplayTypeFullscreen();
627 break;
628 case WebMediaPlayer::DisplayType::kPictureInPicture:
629 watch_time_reporter_->OnDisplayTypePictureInPicture();
François Beaufort3f62f382019-01-18 15:05:17630
631 // Resumes playback if it was paused when hidden.
632 if (paused_when_hidden_) {
633 paused_when_hidden_ = false;
634 OnPlay();
635 }
Mounir Lamourif9af74e72017-06-19 19:31:45636 break;
637 }
638}
639
[email protected]ef8394c2013-08-21 20:26:30640void WebMediaPlayerImpl::DoLoad(LoadType load_type,
[email protected]180ef242013-11-07 06:50:46641 const blink::WebURL& url,
Takashi Toyoshima2e01e692018-11-16 03:23:27642 CorsMode cors_mode) {
John Chen5b164a02017-11-01 00:36:09643 TRACE_EVENT1("media", "WebMediaPlayerImpl::DoLoad", "id", media_log_->id());
pkastingf5279482016-07-27 02:18:20644 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43645 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d726eddc2013-07-02 22:25:55646
[email protected]91fd3162019-09-05 23:51:32647 // Start a new observation. If there was one before, then we didn't play it.
648 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(false));
649 // For now, send in an empty set of features. We should fill some in here,
650 // and / or ask blink (via |client_|) for features from the DOM.
651 learning::FeatureDictionary dict;
652 will_play_helper_.BeginObservation(dict);
653
Thomas Guilbert55b48d92019-03-25 23:16:54654#if defined(OS_ANDROID)
655 // Only allow credentials if the crossorigin attribute is unspecified
656 // (kCorsModeUnspecified) or "use-credentials" (kCorsModeUseCredentials).
657 // This value is only used by the MediaPlayerRenderer.
658 // See https://crbug.com/936566.
659 //
660 // The credentials mode also has repercussions in WouldTaintOrigin(), but we
661 // access what we need from |mb_data_source_|->cors_mode() directly, instead
662 // of storing it here.
663 allow_media_player_renderer_credentials_ = cors_mode != kCorsModeAnonymous;
664#endif // defined(OS_ANDROID)
665
Dale Curtis4841c712018-12-13 18:14:05666 // Note: |url| may be very large, take care when making copies.
667 loaded_url_ = GURL(url);
668 load_type_ = load_type;
669
670 ReportMetrics(load_type, loaded_url_, *frame_, media_log_.get());
[email protected]62e5e682013-03-07 23:53:24671
Dale Curtis4841c712018-12-13 18:14:05672 // Set subresource URL for crash reporting; will be truncated to 256 bytes.
Robert Sesekc5e91df2017-12-12 21:11:03673 static base::debug::CrashKeyString* subresource_url =
674 base::debug::AllocateCrashKeyString("subresource_url",
675 base::debug::CrashKeySize::Size256);
Dale Curtis4841c712018-12-13 18:14:05676 base::debug::SetCrashKeyString(subresource_url, loaded_url_.spec());
[email protected]ef8394c2013-08-21 20:26:30677
Blink Reformat1c4d759e2017-04-09 16:34:54678 SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
679 SetReadyState(WebMediaPlayer::kReadyStateHaveNothing);
680 media_log_->AddEvent(media_log_->CreateLoadEvent(url.GetString().Utf8()));
Dale Curtis3899090ea2018-01-12 00:10:35681 load_start_time_ = base::TimeTicks::Now();
[email protected]d726eddc2013-07-02 22:25:55682
Antonio Gomesf01cfbd2019-07-12 08:53:11683 media_metrics_provider_->Initialize(
684 load_type == kLoadTypeMediaSource,
685 load_type == kLoadTypeURL ? blink::GetMediaURLScheme(loaded_url_)
686 : mojom::MediaURLScheme::kUnknown);
Dale Curtis74612b72017-12-14 20:56:19687
[email protected]d726eddc2013-07-02 22:25:55688 // Media source pipelines can start immediately.
Blink Reformat1c4d759e2017-04-09 16:34:54689 if (load_type == kLoadTypeMediaSource) {
[email protected]ef8394c2013-08-21 20:26:30690 StartPipeline();
hubbe5f0ad43b2015-12-14 20:57:26691 } else {
Dale Curtis4841c712018-12-13 18:14:05692 // Short circuit the more complex loading path for data:// URLs. Sending
693 // them through the network based loading path just wastes memory and causes
694 // worse performance since reads become asynchronous.
695 if (loaded_url_.SchemeIs(url::kDataScheme)) {
696 std::string mime_type, charset, data;
Dale Curtis44eacb72019-06-10 20:41:28697 if (!net::DataURL::Parse(loaded_url_, &mime_type, &charset, &data) ||
698 data.empty()) {
Dale Curtis4841c712018-12-13 18:14:05699 DataSourceInitialized(false);
700 return;
701 }
702
703 // Replace |loaded_url_| with an empty data:// URL since it may be large.
704 loaded_url_ = GURL("data:,");
705
706 // Mark all the data as buffered.
Antonio Gomes81b56552019-05-15 22:15:28707 buffered_data_source_host_->SetTotalBytes(data.size());
708 buffered_data_source_host_->AddBufferedByteRange(0, data.size());
Dale Curtis4841c712018-12-13 18:14:05709
710 DCHECK(!mb_data_source_);
711 data_source_.reset(new MemoryDataSource(std::move(data)));
712 DataSourceInitialized(true);
713 return;
714 }
715
John Delaneyb933391602018-10-17 21:50:47716 auto url_data =
Takashi Toyoshima2e01e692018-11-16 03:23:27717 url_index_->GetByUrl(url, static_cast<UrlData::CorsMode>(cors_mode));
Dale Curtis4841c712018-12-13 18:14:05718 mb_data_source_ = new MultibufferDataSource(
John Delaneyb933391602018-10-17 21:50:47719 main_task_runner_, std::move(url_data), media_log_.get(),
Antonio Gomes81b56552019-05-15 22:15:28720 buffered_data_source_host_.get(),
Dale Curtis4841c712018-12-13 18:14:05721 base::BindRepeating(&WebMediaPlayerImpl::NotifyDownloading,
Antonio Gomes142f32a2019-05-15 23:32:56722 weak_this_));
Dale Curtis4841c712018-12-13 18:14:05723 data_source_.reset(mb_data_source_);
724 mb_data_source_->SetPreload(preload_);
725 mb_data_source_->SetIsClientAudioElement(client_->IsAudioElement());
726 mb_data_source_->Initialize(
Antonio Gomes142f32a2019-05-15 23:32:56727 base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, weak_this_));
hubbe5f0ad43b2015-12-14 20:57:26728 }
[email protected]62e5e682013-03-07 23:53:24729}
730
Blink Reformat1c4d759e2017-04-09 16:34:54731void WebMediaPlayerImpl::Play() {
pkastingf5279482016-07-27 02:18:20732 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43733 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53734
avayvod65fad272017-02-24 01:00:48735 // User initiated play unlocks background video playback.
Mustaq Ahmede473e4352017-11-04 01:04:25736 if (blink::WebUserGestureIndicator::IsProcessingUserGesture(frame_))
avayvod65fad272017-02-24 01:00:48737 video_locked_when_paused_when_hidden_ = false;
738
sandersd35d2c3f2017-01-14 02:04:42739 // TODO(sandersd): Do we want to reset the idle timer here?
tguilbert1bb1c782017-01-23 21:15:11740 delegate_->SetIdle(delegate_id_, false);
[email protected]49480902009-07-14 20:23:43741 paused_ = false;
Antonio Gomes81b56552019-05-15 22:15:28742 pipeline_controller_->SetPlaybackRate(playback_rate_);
dalecurtis4619cd02016-09-22 21:39:10743 background_pause_timer_.Stop();
sandersd1c0bba02016-03-04 23:14:08744
xjz48a9cb72016-12-20 04:02:49745 if (observer_)
746 observer_->OnPlaying();
747
Mounir Lamouri89c0a1b2018-03-01 15:00:44748 watch_time_reporter_->SetAutoplayInitiated(client_->WasAutoplayInitiated());
749
Dale Curtis051fdf62017-08-05 00:21:13750 // If we're seeking we'll trigger the watch time reporter upon seek completed;
751 // we don't want to start it here since the seek time is unstable. E.g., when
752 // playing content with a positive start time we would have a zero seek time.
753 if (!Seeking()) {
754 DCHECK(watch_time_reporter_);
755 watch_time_reporter_->OnPlaying();
756 }
757
Chris Cunninghamd9df58e2017-08-29 00:04:23758 if (video_decode_stats_reporter_)
759 video_decode_stats_reporter_->OnPlaying();
760
Dan Sanders6edfd782019-08-13 00:13:18761 simple_watch_timer_.Start();
Ted Meyerd5885f82019-07-16 19:19:17762 media_metrics_provider_->SetHasPlayed();
acolwell9e0840d2014-09-06 19:01:32763 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PLAY));
Dale Curtis18ad391b2019-05-30 23:25:09764
765 MaybeUpdateBufferSizesForPlayback();
sandersd50a635e2016-04-04 22:50:09766 UpdatePlayState();
[email protected]91fd3162019-09-05 23:51:32767
768 // Notify the learning task, if needed.
769 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(true));
[email protected]ec9212f2008-12-18 21:40:36770}
771
Blink Reformat1c4d759e2017-04-09 16:34:54772void WebMediaPlayerImpl::Pause() {
pkastingf5279482016-07-27 02:18:20773 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43774 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53775
sandersd50a635e2016-04-04 22:50:09776 // We update the paused state even when casting, since we expect pause() to be
777 // called when casting begins, and when we exit casting we should end up in a
778 // paused state.
[email protected]49480902009-07-14 20:23:43779 paused_ = true;
hubbed5f36882016-01-15 22:40:37780
avayvodeb9098d2017-01-07 00:33:03781 // No longer paused because it was hidden.
782 paused_when_hidden_ = false;
783
avayvod65fad272017-02-24 01:00:48784 // User initiated pause locks background videos.
Mustaq Ahmede473e4352017-11-04 01:04:25785 if (blink::WebUserGestureIndicator::IsProcessingUserGesture(frame_))
avayvod65fad272017-02-24 01:00:48786 video_locked_when_paused_when_hidden_ = true;
787
Antonio Gomes81b56552019-05-15 22:15:28788 pipeline_controller_->SetPlaybackRate(0.0);
Dale Curtis2fc01cc2019-05-20 22:53:52789
790 // For states <= kReadyStateHaveMetadata, we may not have a renderer yet.
791 if (highest_ready_state_ > WebMediaPlayer::kReadyStateHaveMetadata)
792 paused_time_ = pipeline_controller_->GetMediaTime();
[email protected]090f7312011-08-05 23:26:40793
xjz48a9cb72016-12-20 04:02:49794 if (observer_)
795 observer_->OnPaused();
796
dalecurtis04bdb582016-08-17 22:15:23797 DCHECK(watch_time_reporter_);
798 watch_time_reporter_->OnPaused();
Chris Cunninghamd9df58e2017-08-29 00:04:23799
800 if (video_decode_stats_reporter_)
801 video_decode_stats_reporter_->OnPaused();
802
Dan Sanders6edfd782019-08-13 00:13:18803 simple_watch_timer_.Stop();
acolwell9e0840d2014-09-06 19:01:32804 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PAUSE));
avayvod2135a642017-01-13 00:17:14805
Becca Hughes7a85bf22019-07-24 16:16:58806 // Paused changed so we should update media position state.
807 UpdateMediaPositionState();
808
sandersd50a635e2016-04-04 22:50:09809 UpdatePlayState();
[email protected]ec9212f2008-12-18 21:40:36810}
811
Blink Reformat1c4d759e2017-04-09 16:34:54812void WebMediaPlayerImpl::Seek(double seconds) {
pkastingf5279482016-07-27 02:18:20813 DVLOG(1) << __func__ << "(" << seconds << "s)";
acolwellb4034942014-08-28 15:42:43814 DCHECK(main_task_runner_->BelongsToCurrentThread());
Mounir Lamourid864f752019-02-08 22:22:41815 media_log_->AddEvent(
816 media_log_->CreateTimeEvent(MediaLogEvent::SEEK, "seek_target", seconds));
sandersd1c0bba02016-03-04 23:14:08817 DoSeek(base::TimeDelta::FromSecondsD(seconds), true);
818}
819
820void WebMediaPlayerImpl::DoSeek(base::TimeDelta time, bool time_updated) {
821 DCHECK(main_task_runner_->BelongsToCurrentThread());
John Chen5b164a02017-11-01 00:36:09822 TRACE_EVENT2("media", "WebMediaPlayerImpl::DoSeek", "target",
823 time.InSecondsF(), "id", media_log_->id());
[email protected]d43ed912009-02-03 04:52:53824
srirama.mccf671812015-01-08 11:59:13825 ReadyState old_state = ready_state_;
Blink Reformat1c4d759e2017-04-09 16:34:54826 if (ready_state_ > WebMediaPlayer::kReadyStateHaveMetadata)
827 SetReadyState(WebMediaPlayer::kReadyStateHaveMetadata);
[email protected]1bb666802013-11-28 06:12:08828
Dale Curtis051fdf62017-08-05 00:21:13829 // When paused or ended, we know exactly what the current time is and can
830 // elide seeks to it. However, there are two cases that are not elided:
sandersd1c0bba02016-03-04 23:14:08831 // 1) When the pipeline state is not stable.
832 // In this case we just let |pipeline_controller_| decide what to do, as
833 // it has complete information.
834 // 2) For MSE.
835 // Because the buffers may have changed between seeks, MSE seeks are
836 // never elided.
Antonio Gomes81b56552019-05-15 22:15:28837 if (paused_ && pipeline_controller_->IsStable() &&
Dale Curtis051fdf62017-08-05 00:21:13838 (paused_time_ == time ||
839 (ended_ && time == base::TimeDelta::FromSecondsD(Duration()))) &&
sandersd1c0bba02016-03-04 23:14:08840 !chunk_demuxer_) {
841 // If the ready state was high enough before, we can indicate that the seek
842 // completed just by restoring it. Otherwise we will just wait for the real
843 // ready state change to eventually happen.
Blink Reformat1c4d759e2017-04-09 16:34:54844 if (old_state == kReadyStateHaveEnoughData) {
srirama.m8f4a37562014-12-13 08:16:18845 main_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:51846 FROM_HERE, base::BindOnce(&WebMediaPlayerImpl::OnBufferingStateChange,
Chris Cunninghamfc0d67e2019-07-22 20:29:16847 weak_this_, BUFFERING_HAVE_ENOUGH,
848 BUFFERING_CHANGE_REASON_UNKNOWN));
srirama.m36ab2682014-12-11 04:20:01849 }
sandersd1c0bba02016-03-04 23:14:08850 return;
srirama.m36ab2682014-12-11 04:20:01851 }
[email protected]44ff37c02009-10-24 01:03:03852
dalecurtis04bdb582016-08-17 22:15:23853 // Call this before setting |seeking_| so that the current media time can be
854 // recorded by the reporter.
855 if (watch_time_reporter_)
856 watch_time_reporter_->OnSeeking();
857
sandersd35d2c3f2017-01-14 02:04:42858 // TODO(sandersd): Move |seeking_| to PipelineController.
859 // TODO(sandersd): Do we want to reset the idle timer here?
tguilbert1bb1c782017-01-23 21:15:11860 delegate_->SetIdle(delegate_id_, false);
sandersd50a635e2016-04-04 22:50:09861 ended_ = false;
[email protected]b3766a22010-12-22 17:34:13862 seeking_ = true;
sandersd1c0bba02016-03-04 23:14:08863 seek_time_ = time;
864 if (paused_)
865 paused_time_ = time;
Antonio Gomes81b56552019-05-15 22:15:28866 pipeline_controller_->Seek(time, time_updated);
[email protected]b3766a22010-12-22 17:34:13867
sandersd50a635e2016-04-04 22:50:09868 // This needs to be called after Seek() so that if a resume is triggered, it
869 // is to the correct time.
870 UpdatePlayState();
Becca Hughes7a85bf22019-07-24 16:16:58871
872 // The seek time has changed so we should update the media position state.
873 UpdateMediaPositionState();
[email protected]ec9212f2008-12-18 21:40:36874}
875
Blink Reformat1c4d759e2017-04-09 16:34:54876void WebMediaPlayerImpl::SetRate(double rate) {
pkastingf5279482016-07-27 02:18:20877 DVLOG(1) << __func__ << "(" << rate << ")";
acolwellb4034942014-08-28 15:42:43878 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53879
Matt Wolenetz6010f6c2017-10-18 00:44:36880 if (rate != playback_rate_) {
881 LIMITED_MEDIA_LOG(INFO, media_log_.get(), num_playback_rate_logs_,
882 kMaxNumPlaybackRateLogs)
883 << "Effective playback rate changed from " << playback_rate_ << " to "
884 << rate;
885 }
886
[email protected]49480902009-07-14 20:23:43887 playback_rate_ = rate;
Dale Curtis18ad391b2019-05-30 23:25:09888 if (!paused_)
Antonio Gomes81b56552019-05-15 22:15:28889 pipeline_controller_->SetPlaybackRate(rate);
Dale Curtis18ad391b2019-05-30 23:25:09890
891 MaybeUpdateBufferSizesForPlayback();
[email protected]ec9212f2008-12-18 21:40:36892}
893
Blink Reformat1c4d759e2017-04-09 16:34:54894void WebMediaPlayerImpl::SetVolume(double volume) {
pkastingf5279482016-07-27 02:18:20895 DVLOG(1) << __func__ << "(" << volume << ")";
acolwellb4034942014-08-28 15:42:43896 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtisbb3eaac2016-01-27 21:10:25897 volume_ = volume;
Antonio Gomes81b56552019-05-15 22:15:28898 pipeline_controller_->SetVolume(volume_ * volume_multiplier_);
dalecurtis04bdb582016-08-17 22:15:23899 if (watch_time_reporter_)
900 watch_time_reporter_->OnVolumeChange(volume);
Becca Hughes9f6fd4b82017-06-15 10:01:40901 delegate_->DidPlayerMutedStatusChange(delegate_id_, volume == 0.0);
mlamouri910111362016-11-04 11:28:24902
903 // The play state is updated because the player might have left the autoplay
904 // muted state.
905 UpdatePlayState();
[email protected]ec9212f2008-12-18 21:40:36906}
[email protected]f0a51fb52009-03-05 12:46:38907
Chris Cunningham8c2ef912019-11-15 23:10:41908void WebMediaPlayerImpl::SetLatencyHint(double seconds) {
909 DVLOG(1) << __func__ << "(" << seconds << ")";
Chris Cunninghame8c626332019-11-20 23:34:27910 DCHECK(main_task_runner_->BelongsToCurrentThread());
911 base::Optional<base::TimeDelta> latency_hint;
912 if (std::isfinite(seconds)) {
913 DCHECK_GE(seconds, 0);
914 latency_hint = base::TimeDelta::FromSecondsD(seconds);
915 }
916 pipeline_controller_->SetLatencyHint(latency_hint);
Chris Cunningham8c2ef912019-11-15 23:10:41917}
918
Mounir Lamouri967f8fb72019-02-13 02:34:22919void WebMediaPlayerImpl::OnRequestPictureInPicture() {
[email protected]69db58f2018-09-26 20:27:56920 if (!surface_layer_for_video_enabled_)
921 ActivateSurfaceLayerForVideo();
922
Mounir Lamourib642a3c2018-07-09 15:45:31923 DCHECK(bridge_);
Mounir Lamouri99ba5a62019-02-12 01:27:47924 DCHECK(bridge_->GetSurfaceId().is_valid());
Jennifer Apacible3f0489102018-01-19 20:10:31925}
926
Daniel Chengc1710b52018-10-24 03:12:28927void WebMediaPlayerImpl::SetSinkId(
928 const blink::WebString& sink_id,
Antonio Gomese7813f32019-04-02 06:11:03929 blink::WebSetSinkIdCompleteCallback completion_callback) {
guidou69223ce2015-06-16 10:36:19930 DCHECK(main_task_runner_->BelongsToCurrentThread());
pkastingf5279482016-07-27 02:18:20931 DVLOG(1) << __func__;
guidouc7babef2015-10-22 00:42:35932
Dale Curtisca1b78f2019-01-15 03:11:26933 OutputDeviceStatusCB callback =
Antonio Gomese7813f32019-04-02 06:11:03934 ConvertToOutputDeviceStatusCB(std::move(completion_callback));
guidouc7babef2015-10-22 00:42:35935 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:51936 FROM_HERE, base::BindOnce(&SetSinkIdOnMediaThread, audio_source_provider_,
Daniel Chengc1710b52018-10-24 03:12:28937 sink_id.Utf8(), std::move(callback)));
guidou69223ce2015-06-16 10:36:19938}
939
Blink Reformat1c4d759e2017-04-09 16:34:54940STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadNone, MultibufferDataSource::NONE);
941STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadMetaData,
dalecurtisb6e052f52016-08-25 00:35:55942 MultibufferDataSource::METADATA);
Blink Reformat1c4d759e2017-04-09 16:34:54943STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadAuto, MultibufferDataSource::AUTO);
[email protected]23a8b1d82011-04-05 16:28:20944
Blink Reformat1c4d759e2017-04-09 16:34:54945void WebMediaPlayerImpl::SetPreload(WebMediaPlayer::Preload preload) {
pkastingf5279482016-07-27 02:18:20946 DVLOG(1) << __func__ << "(" << preload << ")";
acolwellb4034942014-08-28 15:42:43947 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]4e6be3f2009-05-07 02:24:44948
dalecurtisb6e052f52016-08-25 00:35:55949 preload_ = static_cast<MultibufferDataSource::Preload>(preload);
Dale Curtis4841c712018-12-13 18:14:05950 if (mb_data_source_)
951 mb_data_source_->SetPreload(preload_);
[email protected]4e6be3f2009-05-07 02:24:44952}
953
Blink Reformat1c4d759e2017-04-09 16:34:54954bool WebMediaPlayerImpl::HasVideo() const {
acolwellb4034942014-08-28 15:42:43955 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53956
[email protected]b8877772014-03-26 20:17:15957 return pipeline_metadata_.has_video;
[email protected]d43ed912009-02-03 04:52:53958}
959
Blink Reformat1c4d759e2017-04-09 16:34:54960bool WebMediaPlayerImpl::HasAudio() const {
acolwellb4034942014-08-28 15:42:43961 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]fc367af2009-08-14 23:06:35962
[email protected]b8877772014-03-26 20:17:15963 return pipeline_metadata_.has_audio;
[email protected]fc367af2009-08-14 23:06:35964}
965
Blink Reformat1c4d759e2017-04-09 16:34:54966void WebMediaPlayerImpl::EnabledAudioTracksChanged(
servolkf25ceed2016-07-01 03:44:38967 const blink::WebVector<blink::WebMediaPlayer::TrackId>& enabledTrackIds) {
968 DCHECK(main_task_runner_->BelongsToCurrentThread());
969
970 std::ostringstream logstr;
971 std::vector<MediaTrack::Id> enabledMediaTrackIds;
972 for (const auto& blinkTrackId : enabledTrackIds) {
Maciej Pawlowskif2556d122019-06-03 08:14:18973 const auto track_id = MediaTrack::Id(blinkTrackId.Utf8().data());
servolkf25ceed2016-07-01 03:44:38974 logstr << track_id << " ";
975 enabledMediaTrackIds.push_back(track_id);
976 }
dalecurtis9cddc0b2017-04-19 21:23:38977 MEDIA_LOG(INFO, media_log_.get())
978 << "Enabled audio tracks: [" << logstr.str() << "]";
Antonio Gomes81b56552019-05-15 22:15:28979 pipeline_controller_->OnEnabledAudioTracksChanged(enabledMediaTrackIds);
servolkf25ceed2016-07-01 03:44:38980}
981
Blink Reformat1c4d759e2017-04-09 16:34:54982void WebMediaPlayerImpl::SelectedVideoTrackChanged(
servolkf25ceed2016-07-01 03:44:38983 blink::WebMediaPlayer::TrackId* selectedTrackId) {
984 DCHECK(main_task_runner_->BelongsToCurrentThread());
985
servolk9bed6602017-02-24 01:20:11986 base::Optional<MediaTrack::Id> selected_video_track_id;
987 if (selectedTrackId && !video_track_disabled_)
Blink Reformat1c4d759e2017-04-09 16:34:54988 selected_video_track_id = MediaTrack::Id(selectedTrackId->Utf8().data());
dalecurtis9cddc0b2017-04-19 21:23:38989 MEDIA_LOG(INFO, media_log_.get())
Maciej Pawlowskif2556d122019-06-03 08:14:18990 << "Selected video track: ["
991 << selected_video_track_id.value_or(MediaTrack::Id()) << "]";
Antonio Gomes81b56552019-05-15 22:15:28992 pipeline_controller_->OnSelectedVideoTrackChanged(selected_video_track_id);
servolkf25ceed2016-07-01 03:44:38993}
994
Blink Reformat1c4d759e2017-04-09 16:34:54995blink::WebSize WebMediaPlayerImpl::NaturalSize() const {
acolwellb4034942014-08-28 15:42:43996 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53997
[email protected]b8877772014-03-26 20:17:15998 return blink::WebSize(pipeline_metadata_.natural_size);
[email protected]d43ed912009-02-03 04:52:53999}
1000
Jiajia Qin82acdc02017-07-31 09:55:141001blink::WebSize WebMediaPlayerImpl::VisibleRect() const {
1002 DCHECK(main_task_runner_->BelongsToCurrentThread());
1003 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
1004 if (!video_frame)
1005 return blink::WebSize();
1006
1007 const gfx::Rect& visible_rect = video_frame->visible_rect();
1008 return blink::WebSize(visible_rect.width(), visible_rect.height());
1009}
1010
Blink Reformat1c4d759e2017-04-09 16:34:541011bool WebMediaPlayerImpl::Paused() const {
acolwellb4034942014-08-28 15:42:431012 DCHECK(main_task_runner_->BelongsToCurrentThread());
Antonio Gomes81b56552019-05-15 22:15:281013 return pipeline_controller_->GetPlaybackRate() == 0.0f;
[email protected]d43ed912009-02-03 04:52:531014}
1015
François Beaufort184f6042019-01-25 05:50:051016bool WebMediaPlayerImpl::PausedWhenHidden() const {
1017 return paused_when_hidden_;
1018}
1019
Blink Reformat1c4d759e2017-04-09 16:34:541020bool WebMediaPlayerImpl::Seeking() const {
acolwellb4034942014-08-28 15:42:431021 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:531022
Blink Reformat1c4d759e2017-04-09 16:34:541023 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
[email protected]0acebfa2009-08-21 22:45:401024 return false;
[email protected]67cd5052009-09-10 21:53:221025
[email protected]b3766a22010-12-22 17:34:131026 return seeking_;
[email protected]ec9212f2008-12-18 21:40:361027}
1028
Blink Reformat1c4d759e2017-04-09 16:34:541029double WebMediaPlayerImpl::Duration() const {
acolwellb4034942014-08-28 15:42:431030 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]39bdde32013-04-17 17:44:201031
Blink Reformat1c4d759e2017-04-09 16:34:541032 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
[email protected]39bdde32013-04-17 17:44:201033 return std::numeric_limits<double>::quiet_NaN();
1034
chcunninghamb92d5062017-01-10 21:50:221035 // Use duration from ChunkDemuxer when present. MSE allows users to specify
1036 // duration as a double. This propagates to the rest of the pipeline as a
1037 // TimeDelta with potentially reduced precision (limited to Microseconds).
1038 // ChunkDemuxer returns the full-precision user-specified double. This ensures
1039 // users can "get" the exact duration they "set".
1040 if (chunk_demuxer_)
1041 return chunk_demuxer_->GetDuration();
1042
avayvodcc273dd2017-01-19 19:35:121043 base::TimeDelta pipeline_duration = GetPipelineMediaDuration();
chcunninghamb92d5062017-01-10 21:50:221044 return pipeline_duration == kInfiniteDuration
1045 ? std::numeric_limits<double>::infinity()
1046 : pipeline_duration.InSecondsF();
[email protected]d43ed912009-02-03 04:52:531047}
1048
[email protected]db66d0092014-04-16 07:15:121049double WebMediaPlayerImpl::timelineOffset() const {
acolwellb4034942014-08-28 15:42:431050 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]db66d0092014-04-16 07:15:121051
1052 if (pipeline_metadata_.timeline_offset.is_null())
1053 return std::numeric_limits<double>::quiet_NaN();
1054
1055 return pipeline_metadata_.timeline_offset.ToJsTime();
1056}
1057
Dale Curtis051fdf62017-08-05 00:21:131058base::TimeDelta WebMediaPlayerImpl::GetCurrentTimeInternal() const {
1059 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtis051fdf62017-08-05 00:21:131060
1061 base::TimeDelta current_time;
1062 if (Seeking())
1063 current_time = seek_time_;
Dale Curtis051fdf62017-08-05 00:21:131064 else if (paused_)
1065 current_time = paused_time_;
1066 else
Antonio Gomes81b56552019-05-15 22:15:281067 current_time = pipeline_controller_->GetMediaTime();
Dale Curtis051fdf62017-08-05 00:21:131068
Dale Curtis77d6057b2019-05-03 01:31:561069 // It's possible for |current_time| to be kInfiniteDuration here if the page
1070 // seeks to kInfiniteDuration (2**64 - 1) when Duration() is infinite.
Dale Curtis051fdf62017-08-05 00:21:131071 DCHECK_GE(current_time, base::TimeDelta());
1072 return current_time;
1073}
1074
Blink Reformat1c4d759e2017-04-09 16:34:541075double WebMediaPlayerImpl::CurrentTime() const {
acolwellb4034942014-08-28 15:42:431076 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:541077 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
scherkusd2c745b2014-09-04 05:03:401078
1079 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
1080 // see http://crbug.com/409280
Dale Curtis051fdf62017-08-05 00:21:131081 // Note: Duration() may be infinity.
josephlolak918863bc2017-11-15 08:54:331082 return (ended_ && !std::isinf(Duration()))
1083 ? Duration()
1084 : GetCurrentTimeInternal().InSecondsF();
[email protected]d43ed912009-02-03 04:52:531085}
1086
Blink Reformat1c4d759e2017-04-09 16:34:541087WebMediaPlayer::NetworkState WebMediaPlayerImpl::GetNetworkState() const {
acolwellb4034942014-08-28 15:42:431088 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddb1e5a2010-12-13 20:10:451089 return network_state_;
1090}
1091
Blink Reformat1c4d759e2017-04-09 16:34:541092WebMediaPlayer::ReadyState WebMediaPlayerImpl::GetReadyState() const {
acolwellb4034942014-08-28 15:42:431093 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddb1e5a2010-12-13 20:10:451094 return ready_state_;
1095}
1096
CJ DiMeglio89240472018-10-18 18:21:101097blink::WebMediaPlayer::SurfaceLayerMode
1098WebMediaPlayerImpl::GetVideoSurfaceLayerMode() const {
1099 return surface_layer_mode_;
1100}
1101
wolenetzed8e7092017-04-21 16:28:591102blink::WebString WebMediaPlayerImpl::GetErrorMessage() const {
wolenetz4d39cc02016-04-05 19:54:411103 DCHECK(main_task_runner_->BelongsToCurrentThread());
wolenetzed8e7092017-04-21 16:28:591104 return blink::WebString::FromUTF8(media_log_->GetErrorMessage());
wolenetz4d39cc02016-04-05 19:54:411105}
1106
Blink Reformat1c4d759e2017-04-09 16:34:541107blink::WebTimeRanges WebMediaPlayerImpl::Buffered() const {
acolwellb4034942014-08-28 15:42:431108 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]779a8322014-08-22 21:28:371109
acolwell9e0840d2014-09-06 19:01:321110 Ranges<base::TimeDelta> buffered_time_ranges =
Antonio Gomes81b56552019-05-15 22:15:281111 pipeline_controller_->GetBufferedTimeRanges();
[email protected]779a8322014-08-22 21:28:371112
avayvodcc273dd2017-01-19 19:35:121113 const base::TimeDelta duration = GetPipelineMediaDuration();
dalecurtis39a7f932016-07-19 18:34:591114 if (duration != kInfiniteDuration) {
Antonio Gomes81b56552019-05-15 22:15:281115 buffered_data_source_host_->AddBufferedTimeRanges(&buffered_time_ranges,
1116 duration);
[email protected]779a8322014-08-22 21:28:371117 }
Antonio Gomesf01cfbd2019-07-12 08:53:111118 return blink::ConvertToWebTimeRanges(buffered_time_ranges);
[email protected]02022fc2014-05-16 00:05:311119}
1120
Blink Reformat1c4d759e2017-04-09 16:34:541121blink::WebTimeRanges WebMediaPlayerImpl::Seekable() const {
acolwellb4034942014-08-28 15:42:431122 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]39bdde32013-04-17 17:44:201123
Blink Reformat1c4d759e2017-04-09 16:34:541124 if (ready_state_ < WebMediaPlayer::kReadyStateHaveMetadata)
philipjb0e6f3f2014-09-30 09:51:531125 return blink::WebTimeRanges();
1126
Blink Reformat1c4d759e2017-04-09 16:34:541127 const double seekable_end = Duration();
dalecurtis56359cb2014-10-28 00:06:291128
1129 // Allow a special exception for seeks to zero for streaming sources with a
1130 // finite duration; this allows looping to work.
Dale Curtis4841c712018-12-13 18:14:051131 const bool is_finite_stream = mb_data_source_ &&
1132 mb_data_source_->IsStreaming() &&
tguilbertade2bcb2017-01-07 02:57:451133 std::isfinite(seekable_end);
1134
tguilbert75e2bf62017-04-26 20:13:121135 // Do not change the seekable range when using the MediaPlayerRenderer. It
1136 // will take care of dropping invalid seeks.
1137 const bool force_seeks_to_zero =
1138 !using_media_player_renderer_ && is_finite_stream;
dalecurtis56359cb2014-10-28 00:06:291139
1140 // TODO(dalecurtis): Technically this allows seeking on media which return an
tguilbertade2bcb2017-01-07 02:57:451141 // infinite duration so long as DataSource::IsStreaming() is false. While not
dalecurtis56359cb2014-10-28 00:06:291142 // expected, disabling this breaks semi-live players, http://crbug.com/427412.
1143 const blink::WebTimeRange seekable_range(
tguilbertade2bcb2017-01-07 02:57:451144 0.0, force_seeks_to_zero ? 0.0 : seekable_end);
philipjb0e6f3f2014-09-30 09:51:531145 return blink::WebTimeRanges(&seekable_range, 1);
[email protected]ec9212f2008-12-18 21:40:361146}
1147
sandersd35d2c3f2017-01-14 02:04:421148bool WebMediaPlayerImpl::IsPrerollAttemptNeeded() {
1149 // TODO(sandersd): Replace with |highest_ready_state_since_seek_| if we need
1150 // to ensure that preroll always gets a chance to complete.
1151 // See http://crbug.com/671525.
Dale Curtis69e8f302019-05-22 07:36:581152 //
1153 // Note: Even though we get play/pause signals at kReadyStateHaveMetadata, we
1154 // must attempt to preroll until kReadyStateHaveFutureData so that the
1155 // canplaythrough event will be fired to the page (which may be waiting).
1156 //
1157 // TODO(dalecurtis): We should try signaling kReadyStateHaveFutureData upon
1158 // automatic-suspend of a non-playing element to avoid wasting resources.
1159 if (highest_ready_state_ >= ReadyState::kReadyStateHaveFutureData)
sandersd35d2c3f2017-01-14 02:04:421160 return false;
1161
Fredrik Hubinette4cfb4412017-08-23 00:03:071162 // To suspend before we reach kReadyStateHaveCurrentData is only ok
1163 // if we know we're going to get woken up when we get more data, which
1164 // will only happen if the network is in the "Loading" state.
1165 // This happens when the network is fast, but multiple videos are loading
1166 // and multiplexing gets held up waiting for available threads.
1167 if (highest_ready_state_ <= ReadyState::kReadyStateHaveMetadata &&
1168 network_state_ != WebMediaPlayer::kNetworkStateLoading) {
1169 return true;
1170 }
1171
sandersd35d2c3f2017-01-14 02:04:421172 if (preroll_attempt_pending_)
1173 return true;
1174
1175 // Freshly initialized; there has never been any loading progress. (Otherwise
1176 // |preroll_attempt_pending_| would be true when the start time is null.)
1177 if (preroll_attempt_start_time_.is_null())
1178 return false;
1179
1180 base::TimeDelta preroll_attempt_duration =
1181 tick_clock_->NowTicks() - preroll_attempt_start_time_;
1182 return preroll_attempt_duration < kPrerollAttemptTimeout;
1183}
1184
Blink Reformat1c4d759e2017-04-09 16:34:541185bool WebMediaPlayerImpl::DidLoadingProgress() {
acolwellb4034942014-08-28 15:42:431186 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtise7120dc2016-09-03 02:54:351187
1188 // Note: Separate variables used to ensure both methods are called every time.
Antonio Gomes81b56552019-05-15 22:15:281189 const bool pipeline_progress = pipeline_controller_->DidLoadingProgress();
1190 const bool data_progress = buffered_data_source_host_->DidLoadingProgress();
hubbeb2d3efd2017-05-05 23:26:381191 return pipeline_progress || data_progress;
[email protected]d43ed912009-02-03 04:52:531192}
1193
danakjff6a0262018-06-26 19:50:311194void WebMediaPlayerImpl::Paint(cc::PaintCanvas* canvas,
[email protected]dd5c7972014-08-21 15:00:371195 const blink::WebRect& rect,
Kai Ninomiya9e8ae29b2017-09-06 23:45:161196 cc::PaintFlags& flags,
1197 int already_uploaded_id,
1198 VideoFrameUploadMetadata* out_metadata) {
acolwellb4034942014-08-28 15:42:431199 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]dd061e12014-05-06 19:21:221200 TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
[email protected]4e6be3f2009-05-07 02:24:441201
watkd16bb3e2017-04-25 01:18:311202 // We can't copy from protected frames.
Xiaohan Wang24cfe2c2018-01-22 23:16:001203 if (cdm_context_ref_)
xhwang80739452016-01-13 00:48:001204 return;
1205
mcasasf1236fc22015-05-29 22:38:561206 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
[email protected]0fe5d43b2014-01-24 23:32:451207
[email protected]b49beeb2013-03-01 20:04:001208 gfx::Rect gfx_rect(rect);
mcasas265bdbf82015-06-12 18:44:071209 if (video_frame.get() && video_frame->HasTextures()) {
Antoine Labourfee4ae52019-04-24 23:53:571210 if (!context_provider_)
danakj53f7ec902016-05-21 01:30:101211 return; // Unable to get/create a shared main thread context.
Antoine Labourfee4ae52019-04-24 23:53:571212 if (!context_provider_->GrContext())
danakj53f7ec902016-05-21 01:30:101213 return; // The context has been lost since and can't setup a GrContext.
dongseong.hwang0c4e9d82015-01-08 20:11:131214 }
Kai Ninomiyaef8c9e02017-09-27 04:07:401215 if (out_metadata && video_frame) {
Kai Ninomiya9e8ae29b2017-09-06 23:45:161216 // WebGL last-uploaded-frame-metadata API enabled. https://crbug.com/639174
1217 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1218 out_metadata);
1219 if (out_metadata->skipped) {
1220 // Skip uploading this frame.
1221 return;
1222 }
1223 }
zhuoyu.qian4689dde22017-10-16 04:11:481224 video_renderer_.Paint(
Julien Isorce6c83d8de2017-10-12 13:11:291225 video_frame, canvas, gfx::RectF(gfx_rect), flags,
Ted Meyer4a427632019-05-01 19:05:271226 pipeline_metadata_.video_decoder_config.video_transformation(),
Antoine Labourfee4ae52019-04-24 23:53:571227 context_provider_.get());
[email protected]ec9212f2008-12-18 21:40:361228}
[email protected]5df51652009-01-17 00:03:001229
Yutaka Hirano657a0552018-11-09 00:52:551230bool WebMediaPlayerImpl::WouldTaintOrigin() const {
Thomas Guilbert153f84572018-07-19 05:03:581231 if (demuxer_found_hls_) {
1232 // HLS manifests might pull segments from a different origin. We can't know
1233 // for sure, so we conservatively say no here.
Yutaka Hiranoa9cbaa72018-10-10 08:35:221234 return true;
1235 }
1236
Dale Curtis4841c712018-12-13 18:14:051237 if (!mb_data_source_)
Yutaka Hirano657a0552018-11-09 00:52:551238 return false;
1239
1240 // When the resource is redirected to another origin we think it as
1241 // tainted. This is actually not specified, and is under discussion.
1242 // See https://github.com/whatwg/fetch/issues/737.
Dale Curtis4841c712018-12-13 18:14:051243 if (!mb_data_source_->HasSingleOrigin() &&
1244 mb_data_source_->cors_mode() == UrlData::CORS_UNSPECIFIED) {
Yutaka Hirano657a0552018-11-09 00:52:551245 return true;
1246 }
1247
Dale Curtis4841c712018-12-13 18:14:051248 return mb_data_source_->IsCorsCrossOrigin();
[email protected]3fe27112012-06-07 04:00:011249}
1250
Blink Reformat1c4d759e2017-04-09 16:34:541251double WebMediaPlayerImpl::MediaTimeForTimeValue(double timeValue) const {
qinminb4c39782015-08-10 18:43:241252 return base::TimeDelta::FromSecondsD(timeValue).InSecondsF();
[email protected]e06e16d82011-05-26 22:13:331253}
1254
Blink Reformat1c4d759e2017-04-09 16:34:541255unsigned WebMediaPlayerImpl::DecodedFrameCount() const {
acolwellb4034942014-08-28 15:42:431256 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051257 return GetPipelineStatistics().video_frames_decoded;
[email protected]4c51bc662011-02-16 02:03:161258}
1259
Blink Reformat1c4d759e2017-04-09 16:34:541260unsigned WebMediaPlayerImpl::DroppedFrameCount() const {
acolwellb4034942014-08-28 15:42:431261 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051262 return GetPipelineStatistics().video_frames_dropped;
[email protected]4c51bc662011-02-16 02:03:161263}
1264
Dave Tapuska6c7154912018-07-30 20:39:001265uint64_t WebMediaPlayerImpl::AudioDecodedByteCount() const {
acolwellb4034942014-08-28 15:42:431266 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051267 return GetPipelineStatistics().audio_bytes_decoded;
[email protected]4c51bc662011-02-16 02:03:161268}
1269
Dave Tapuska6c7154912018-07-30 20:39:001270uint64_t WebMediaPlayerImpl::VideoDecodedByteCount() const {
acolwellb4034942014-08-28 15:42:431271 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051272 return GetPipelineStatistics().video_bytes_decoded;
[email protected]4c51bc662011-02-16 02:03:161273}
1274
Dale Curtiscdfc6f22019-06-26 22:05:231275bool WebMediaPlayerImpl::HasAvailableVideoFrame() const {
1276 return has_first_frame_;
1277}
1278
Blink Reformat1c4d759e2017-04-09 16:34:541279bool WebMediaPlayerImpl::CopyVideoTextureToPlatformTexture(
danakj46070b02016-03-28 21:54:111280 gpu::gles2::GLES2Interface* gl,
jiajia.qinc2943162017-05-12 01:34:391281 unsigned int target,
zmo57d577a2015-10-30 18:28:591282 unsigned int texture,
kbr0986e622017-04-13 02:34:581283 unsigned internal_format,
1284 unsigned format,
1285 unsigned type,
jiajia.qinc2943162017-05-12 01:34:391286 int level,
zmo57d577a2015-10-30 18:28:591287 bool premultiply_alpha,
Kai Ninomiya9e8ae29b2017-09-06 23:45:161288 bool flip_y,
1289 int already_uploaded_id,
1290 VideoFrameUploadMetadata* out_metadata) {
xhwang213e50c2016-10-10 23:56:311291 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]bfc05f22013-10-19 17:55:161292 TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
1293
watkd16bb3e2017-04-25 01:18:311294 // We can't copy from protected frames.
Xiaohan Wang24cfe2c2018-01-22 23:16:001295 if (cdm_context_ref_)
xhwang213e50c2016-10-10 23:56:311296 return false;
[email protected]dd061e12014-05-06 19:21:221297
xhwang213e50c2016-10-10 23:56:311298 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
jbauman581d041c2016-07-21 01:01:031299 if (!video_frame.get() || !video_frame->HasTextures()) {
[email protected]e56f88c72013-06-25 22:31:291300 return false;
dongseong.hwang0c4e9d82015-01-08 20:11:131301 }
Kai Ninomiya9e8ae29b2017-09-06 23:45:161302 if (out_metadata) {
1303 // WebGL last-uploaded-frame-metadata API is enabled.
1304 // https://crbug.com/639174
1305 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1306 out_metadata);
1307 if (out_metadata->skipped) {
1308 // Skip uploading this frame.
1309 return true;
1310 }
1311 }
[email protected]df41e252014-02-03 23:39:501312
zhuoyu.qian4689dde22017-10-16 04:11:481313 return video_renderer_.CopyVideoFrameTexturesToGLTexture(
Antoine Labourfee4ae52019-04-24 23:53:571314 context_provider_.get(), gl, video_frame.get(), target, texture,
Dan Sanders930cc1d2018-10-03 00:45:081315 internal_format, format, type, level, premultiply_alpha, flip_y);
[email protected]6523b242013-03-13 11:10:071316}
1317
Yan, Shaobo44b79ba2019-04-02 06:09:271318bool WebMediaPlayerImpl::PrepareVideoFrameForWebGL(
1319 gpu::gles2::GLES2Interface* gl,
1320 unsigned target,
1321 unsigned texture,
1322 int already_uploaded_id,
1323 WebMediaPlayer::VideoFrameUploadMetadata* out_metadata) {
1324 DCHECK(main_task_runner_->BelongsToCurrentThread());
1325 TRACE_EVENT0("media", "WebMediaPlayerImpl::PrepareVideoFrameForWebGL");
1326
1327 // TODO(crbug.com/776222): How to deal with protected frames.
1328 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
1329 if (!video_frame.get() || !video_frame->HasTextures()) {
1330 return false;
1331 }
1332 if (out_metadata) {
1333 // WebGL last-uploaded-frame-metadata API is enabled.
1334 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1335 out_metadata);
1336 if (out_metadata->skipped) {
1337 // Skip uploading this frame.
1338 return true;
1339 }
1340 }
1341
Yan, Shaobo44b79ba2019-04-02 06:09:271342 return video_renderer_.PrepareVideoFrameForWebGL(
Antoine Labourfee4ae52019-04-24 23:53:571343 context_provider_.get(), gl, video_frame.get(), target, texture);
Yan, Shaobo44b79ba2019-04-02 06:09:271344}
1345
Matt Wolenetz95af6362018-01-04 20:23:421346// static
Kai Ninomiya9e8ae29b2017-09-06 23:45:161347void WebMediaPlayerImpl::ComputeFrameUploadMetadata(
1348 VideoFrame* frame,
1349 int already_uploaded_id,
1350 VideoFrameUploadMetadata* out_metadata) {
1351 DCHECK(out_metadata);
Kai Ninomiyaef8c9e02017-09-27 04:07:401352 DCHECK(frame);
Kai Ninomiya9e8ae29b2017-09-06 23:45:161353 out_metadata->frame_id = frame->unique_id();
1354 out_metadata->visible_rect = frame->visible_rect();
1355 out_metadata->timestamp = frame->timestamp();
Li, Hao0fab96a2019-10-31 02:46:471356 base::TimeDelta frame_duration;
1357 if (frame->metadata()->GetTimeDelta(media::VideoFrameMetadata::FRAME_DURATION,
1358 &frame_duration)) {
1359 out_metadata->expected_timestamp = frame->timestamp() + frame_duration;
1360 };
Kai Ninomiya9e8ae29b2017-09-06 23:45:161361 bool skip_possible = already_uploaded_id != -1;
1362 bool same_frame_id = frame->unique_id() == already_uploaded_id;
1363 out_metadata->skipped = skip_possible && same_frame_id;
1364}
1365
Blink Reformat1c4d759e2017-04-09 16:34:541366void WebMediaPlayerImpl::SetContentDecryptionModule(
[email protected]9ebc3b03f2014-08-13 04:01:231367 blink::WebContentDecryptionModule* cdm,
1368 blink::WebContentDecryptionModuleResult result) {
xhwang51139732017-02-24 19:36:081369 DVLOG(1) << __func__ << ": cdm = " << cdm;
acolwellb4034942014-08-28 15:42:431370 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]9ebc3b03f2014-08-13 04:01:231371
jrummell06f27072015-06-08 18:12:381372 // Once the CDM is set it can't be cleared as there may be frames being
1373 // decrypted on other threads. So fail this request.
1374 // http://crbug.com/462365#c7.
xhwang97de4202014-11-25 08:44:011375 if (!cdm) {
Blink Reformat1c4d759e2017-04-09 16:34:541376 result.CompleteWithError(
1377 blink::kWebContentDecryptionModuleExceptionInvalidStateError, 0,
xhwang79b193042016-12-13 18:52:431378 "The existing ContentDecryptionModule object cannot be removed at this "
1379 "time.");
xhwang97de4202014-11-25 08:44:011380 return;
1381 }
1382
jrummell89e61d82015-07-23 20:03:341383 // Create a local copy of |result| to avoid problems with the callback
1384 // getting passed to the media thread and causing |result| to be destructed
jrummell4acbec912016-02-27 02:45:031385 // on the wrong thread in some failure conditions. Blink should prevent
1386 // multiple simultaneous calls.
1387 DCHECK(!set_cdm_result_);
jrummell89e61d82015-07-23 20:03:341388 set_cdm_result_.reset(new blink::WebContentDecryptionModuleResult(result));
1389
Chris Cunninghamd4a00192019-03-21 20:02:491390 SetCdmInternal(cdm);
xhwang97de4202014-11-25 08:44:011391}
1392
xhwange8c4181a2014-12-06 08:10:011393void WebMediaPlayerImpl::OnEncryptedMediaInitData(
jrummellcf78967c2015-04-03 05:03:581394 EmeInitDataType init_data_type,
Avi Drissman97785ea2015-12-19 01:11:311395 const std::vector<uint8_t>& init_data) {
jrummellcf78967c2015-04-03 05:03:581396 DCHECK(init_data_type != EmeInitDataType::UNKNOWN);
xhwangbab66f52014-12-02 23:49:501397
Xiaohan Wangf63505d2017-10-21 08:00:531398 RecordEncryptedEvent(true);
xhwangbab66f52014-12-02 23:49:501399
dalecurtis04bdb582016-08-17 22:15:231400 // Recreate the watch time reporter if necessary.
1401 const bool was_encrypted = is_encrypted_;
1402 is_encrypted_ = true;
Dale Curtis3899090ea2018-01-12 00:10:351403 if (!was_encrypted) {
1404 media_metrics_provider_->SetIsEME();
1405 if (watch_time_reporter_)
1406 CreateWatchTimeReporter();
dalecurtis04bdb582016-08-17 22:15:231407
Chris Cunningham6c0ec292019-04-04 18:31:111408 // |was_encrypted| = false means we didn't have a CDM prior to observing
1409 // encrypted media init data. Reset the reporter until the CDM arrives. See
1410 // SetCdmInternal().
1411 DCHECK(!cdm_config_);
1412 video_decode_stats_reporter_.reset();
1413 }
Chris Cunninghamd9df58e2017-08-29 00:04:231414
Blink Reformat1c4d759e2017-04-09 16:34:541415 encrypted_client_->Encrypted(
Antonio Gomes89b70572019-07-13 00:44:211416 init_data_type, init_data.data(),
srirama.m26f864d02015-07-14 05:21:461417 base::saturated_cast<unsigned int>(init_data.size()));
xhwangbab66f52014-12-02 23:49:501418}
1419
servolk81e01e02016-03-05 03:29:151420void WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated(
dcheng3076abbf2016-04-22 20:42:391421 std::unique_ptr<MediaTracks> tracks) {
servolk81e01e02016-03-05 03:29:151422 // For MSE/chunk_demuxer case the media track updates are handled by
1423 // WebSourceBufferImpl.
1424 DCHECK(demuxer_.get());
1425 DCHECK(!chunk_demuxer_);
servolkef1e5ef2016-03-25 04:55:261426
servolk16e8bdf82017-04-11 17:00:391427 // Report the media track information to blink. Only the first audio track and
1428 // the first video track are enabled by default to match blink logic.
1429 bool is_first_audio_track = true;
1430 bool is_first_video_track = true;
servolkef1e5ef2016-03-25 04:55:261431 for (const auto& track : tracks->tracks()) {
1432 if (track->type() == MediaTrack::Audio) {
Maciej Pawlowskif2556d122019-06-03 08:14:181433 client_->AddAudioTrack(
1434 blink::WebString::FromUTF8(track->id().value()),
1435 blink::WebMediaPlayerClient::kAudioTrackKindMain,
1436 blink::WebString::FromUTF8(track->label().value()),
1437 blink::WebString::FromUTF8(track->language().value()),
1438 is_first_audio_track);
servolk16e8bdf82017-04-11 17:00:391439 is_first_audio_track = false;
servolkef1e5ef2016-03-25 04:55:261440 } else if (track->type() == MediaTrack::Video) {
Maciej Pawlowskif2556d122019-06-03 08:14:181441 client_->AddVideoTrack(
1442 blink::WebString::FromUTF8(track->id().value()),
1443 blink::WebMediaPlayerClient::kVideoTrackKindMain,
1444 blink::WebString::FromUTF8(track->label().value()),
1445 blink::WebString::FromUTF8(track->language().value()),
1446 is_first_video_track);
servolk16e8bdf82017-04-11 17:00:391447 is_first_video_track = false;
servolkef1e5ef2016-03-25 04:55:261448 } else {
1449 // Text tracks are not supported through this code path yet.
1450 NOTREACHED();
1451 }
1452 }
servolk81e01e02016-03-05 03:29:151453}
1454
Chris Cunninghamd4a00192019-03-21 20:02:491455void WebMediaPlayerImpl::SetCdmInternal(
1456 blink::WebContentDecryptionModule* cdm) {
jrummelle616ee92016-10-08 02:15:441457 DCHECK(main_task_runner_->BelongsToCurrentThread());
1458 DCHECK(cdm);
Xiaohan Wang24cfe2c2018-01-22 23:16:001459
Chris Cunninghamd4a00192019-03-21 20:02:491460 const bool was_encrypted = is_encrypted_;
1461 is_encrypted_ = true;
1462
1463 // Recreate the watch time reporter if necessary.
1464 if (!was_encrypted) {
1465 media_metrics_provider_->SetIsEME();
1466 if (watch_time_reporter_)
1467 CreateWatchTimeReporter();
1468 }
1469
Chris Cunningham6c0ec292019-04-04 18:31:111470 WebContentDecryptionModuleImpl* web_cdm =
1471 ToWebContentDecryptionModuleImpl(cdm);
1472 auto cdm_context_ref = web_cdm->GetCdmContextRef();
Xiaohan Wang24cfe2c2018-01-22 23:16:001473 if (!cdm_context_ref) {
jrummelle616ee92016-10-08 02:15:441474 NOTREACHED();
1475 OnCdmAttached(false);
xhwang80739452016-01-13 00:48:001476 return;
1477 }
1478
Chris Cunningham6c0ec292019-04-04 18:31:111479 // Arrival of |cdm_config_| and |key_system_| unblocks recording of encrypted
1480 // stats. Attempt to create the stats reporter. Note, we do NOT guard this
1481 // within !was_encypted above because often the CDM arrives after the call to
1482 // OnEncryptedMediaInitData().
1483 cdm_config_ = web_cdm->GetCdmConfig();
1484 key_system_ = web_cdm->GetKeySystem();
1485 DCHECK(!key_system_.empty());
1486 CreateVideoDecodeStatsReporter();
1487
Xiaohan Wang24cfe2c2018-01-22 23:16:001488 CdmContext* cdm_context = cdm_context_ref->GetCdmContext();
1489 DCHECK(cdm_context);
jrummelle616ee92016-10-08 02:15:441490
1491 // Keep the reference to the CDM, as it shouldn't be destroyed until
1492 // after the pipeline is done with the |cdm_context|.
Xiaohan Wang24cfe2c2018-01-22 23:16:001493 pending_cdm_context_ref_ = std::move(cdm_context_ref);
Antonio Gomes81b56552019-05-15 22:15:281494 pipeline_controller_->SetCdm(
Antonio Gomes142f32a2019-05-15 23:32:561495 cdm_context, base::Bind(&WebMediaPlayerImpl::OnCdmAttached, weak_this_));
xhwang97de4202014-11-25 08:44:011496}
1497
jrummell89e61d82015-07-23 20:03:341498void WebMediaPlayerImpl::OnCdmAttached(bool success) {
xhwang51139732017-02-24 19:36:081499 DVLOG(1) << __func__ << ": success = " << success;
jrummelle616ee92016-10-08 02:15:441500 DCHECK(main_task_runner_->BelongsToCurrentThread());
Xiaohan Wang24cfe2c2018-01-22 23:16:001501 DCHECK(pending_cdm_context_ref_);
jrummelle616ee92016-10-08 02:15:441502
1503 // If the CDM is set from the constructor there is no promise
1504 // (|set_cdm_result_|) to fulfill.
xhwang97de4202014-11-25 08:44:011505 if (success) {
Ted Meyer7f5b4e22019-11-21 03:21:191506 media_log_->SetProperty<MediaLogProperty::kIsVideoEncrypted>(true);
xhwang29c5ad202017-04-14 07:02:191507
jrummelle616ee92016-10-08 02:15:441508 // This will release the previously attached CDM (if any).
Xiaohan Wang24cfe2c2018-01-22 23:16:001509 cdm_context_ref_ = std::move(pending_cdm_context_ref_);
jrummelle616ee92016-10-08 02:15:441510 if (set_cdm_result_) {
Blink Reformat1c4d759e2017-04-09 16:34:541511 set_cdm_result_->Complete();
jrummelle616ee92016-10-08 02:15:441512 set_cdm_result_.reset();
1513 }
1514
xhwang97de4202014-11-25 08:44:011515 return;
1516 }
1517
Xiaohan Wang24cfe2c2018-01-22 23:16:001518 pending_cdm_context_ref_.reset();
jrummelle616ee92016-10-08 02:15:441519 if (set_cdm_result_) {
Blink Reformat1c4d759e2017-04-09 16:34:541520 set_cdm_result_->CompleteWithError(
1521 blink::kWebContentDecryptionModuleExceptionNotSupportedError, 0,
xhwang79b193042016-12-13 18:52:431522 "Unable to set ContentDecryptionModule object");
jrummelle616ee92016-10-08 02:15:441523 set_cdm_result_.reset();
1524 }
[email protected]9ebc3b03f2014-08-13 04:01:231525}
1526
sandersd1c0bba02016-03-04 23:14:081527void WebMediaPlayerImpl::OnPipelineSeeked(bool time_updated) {
John Chen5b164a02017-11-01 00:36:091528 TRACE_EVENT2("media", "WebMediaPlayerImpl::OnPipelineSeeked", "target",
1529 seek_time_.InSecondsF(), "id", media_log_->id());
[email protected]5d11eff2011-09-15 00:06:061530 seeking_ = false;
wolenetz1b2ae7d2015-06-10 00:44:211531 seek_time_ = base::TimeDelta();
avayvod2135a642017-01-13 00:17:141532
hubbe5a2dec022016-03-17 01:14:231533 if (paused_) {
Antonio Gomes81b56552019-05-15 22:15:281534 paused_time_ = pipeline_controller_->GetMediaTime();
dalecurtis04bdb582016-08-17 22:15:231535 } else {
1536 DCHECK(watch_time_reporter_);
1537 watch_time_reporter_->OnPlaying();
hubbe5a2dec022016-03-17 01:14:231538 }
sandersd1c0bba02016-03-04 23:14:081539 if (time_updated)
1540 should_notify_time_changed_ = true;
dalecurtisaf34d8712016-09-20 04:32:261541
dalecurtis4f6d14d2017-02-22 17:42:221542 // Reset underflow duration upon seek; this prevents looping videos and user
1543 // actions from artificially inflating the duration.
1544 underflow_timer_.reset();
avayvod56e1f3942017-01-21 02:06:311545
1546 // Background video optimizations are delayed when shown/hidden if pipeline
1547 // is seeking.
1548 UpdateBackgroundVideoOptimizationState();
Dale Curtis2dc6089a2018-03-26 16:47:581549
Dale Curtisd71061f02019-05-21 21:33:541550 // If we successfully completed a suspended startup, we need to make a call to
1551 // UpdatePlayState() in case any events which should trigger a resume have
1552 // occurred during startup.
Dale Curtis2dc6089a2018-03-26 16:47:581553 if (attempting_suspended_start_ &&
Antonio Gomes81b56552019-05-15 22:15:281554 pipeline_controller_->IsPipelineSuspended()) {
Dale Curtisff576552018-03-30 02:32:441555 skip_metrics_due_to_startup_suspend_ = true;
Dale Curtisd71061f02019-05-21 21:33:541556
1557 // If we successfully completed a suspended startup, signal that we have
1558 // reached BUFFERING_HAVE_ENOUGH so that canplay and canplaythrough fire
1559 // correctly. We must unfortunately always do this because it's valid for
1560 // elements to play while not visible nor even in the DOM.
1561 //
1562 // Note: This call is dual purpose, it is also responsible for triggering an
1563 // UpdatePlayState() call which may need to resume the pipeline once Blink
1564 // has been told about the ReadyState change.
Chris Cunninghamfc0d67e2019-07-22 20:29:161565 OnBufferingStateChangeInternal(BUFFERING_HAVE_ENOUGH,
1566 BUFFERING_CHANGE_REASON_UNKNOWN, true);
Dale Curtisff576552018-03-30 02:32:441567
1568 // If |skip_metrics_due_to_startup_suspend_| is unset by a resume started by
1569 // the OnBufferingStateChangeInternal() call, record a histogram of it here.
1570 //
1571 // If the value is unset, that means we should not have suspended and we've
1572 // likely incurred some cost to TimeToFirstFrame and TimeToPlayReady which
1573 // will be reflected in those statistics.
1574 base::UmaHistogramBoolean(
1575 std::string("Media.PreloadMetadataSuspendWasIdeal.") +
1576 ((HasVideo() && HasAudio()) ? "AudioVideo"
1577 : (HasVideo() ? "Video" : "Audio")),
1578 skip_metrics_due_to_startup_suspend_);
Dale Curtis2dc6089a2018-03-26 16:47:581579 }
1580
1581 attempting_suspended_start_ = false;
Becca Hughes7a85bf22019-07-24 16:16:581582
1583 // The current time has changed so we should update the media position state.
1584 UpdateMediaPositionState();
[email protected]8931c41a2009-07-07 17:31:491585}
1586
sandersd1c0bba02016-03-04 23:14:081587void WebMediaPlayerImpl::OnPipelineSuspended() {
Dale Curtis83321152018-12-01 01:22:061588 // Add a log event so the player shows up as "SUSPENDED" in media-internals.
1589 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::SUSPENDED));
1590
Dale Curtis04769ca2019-05-25 00:38:101591 if (attempting_suspended_start_) {
1592 DCHECK(pipeline_controller_->IsSuspended());
1593 did_lazy_load_ = !has_poster_ && HasVideo();
1594 }
1595
sandersd2f5bb6152017-03-29 22:57:531596 // Tell the data source we have enough data so that it may release the
Dale Curtis04769ca2019-05-25 00:38:101597 // connection (unless blink is waiting on us to signal play()).
1598 if (mb_data_source_ && !client_->CouldPlayIfEnoughData()) {
1599 // |attempting_suspended_start_| will be cleared by OnPipelineSeeked() which
1600 // will occur after this method during a suspended startup.
1601 if (attempting_suspended_start_ && did_lazy_load_) {
1602 DCHECK(!has_first_frame_);
1603 DCHECK(have_enough_after_lazy_load_cb_.IsCancelled());
1604
1605 // For lazy load, we won't know if the element is non-visible until a
1606 // layout completes, so to avoid unnecessarily tearing down the network
1607 // connection, briefly (250ms chosen arbitrarily) delay signaling "have
1608 // enough" to the MultiBufferDataSource.
1609 //
1610 // base::Unretained() is safe here since the base::CancelableOnceClosure
1611 // will cancel upon destruction of this class and |mb_data_source_| is
1612 // gauranteeed to outlive us.
1613 have_enough_after_lazy_load_cb_.Reset(
1614 base::BindOnce(&MultibufferDataSource::OnBufferingHaveEnough,
1615 base::Unretained(mb_data_source_), true));
1616 main_task_runner_->PostDelayedTask(
1617 FROM_HERE, have_enough_after_lazy_load_cb_.callback(),
1618 base::TimeDelta::FromMilliseconds(250));
1619 } else {
1620 have_enough_after_lazy_load_cb_.Cancel();
1621 mb_data_source_->OnBufferingHaveEnough(true);
1622 }
1623 }
dalecurtis37fe5862016-03-15 19:29:091624
sandersd50a635e2016-04-04 22:50:091625 ReportMemoryUsage();
1626
sandersd1c0bba02016-03-04 23:14:081627 if (pending_suspend_resume_cycle_) {
watkdee516f2016-02-18 02:22:191628 pending_suspend_resume_cycle_ = false;
sandersd50a635e2016-04-04 22:50:091629 UpdatePlayState();
dalecurtis0431cbf2016-03-12 01:19:431630 }
sandersd1c0bba02016-03-04 23:14:081631}
1632
avayvod2135a642017-01-13 00:17:141633void WebMediaPlayerImpl::OnBeforePipelineResume() {
Dale Curtis04769ca2019-05-25 00:38:101634 // Since we're resuming, cancel closing of the network connection.
1635 have_enough_after_lazy_load_cb_.Cancel();
1636
Dale Curtisff576552018-03-30 02:32:441637 // We went through suspended startup, so the player is only just now spooling
1638 // up for playback. As such adjust |load_start_time_| so it reports the same
1639 // metric as what would be reported if we had not suspended at startup.
1640 if (skip_metrics_due_to_startup_suspend_) {
1641 // In the event that the call to SetReadyState() initiated after pipeline
1642 // startup immediately tries to start playback, we should not update
1643 // |load_start_time_| to avoid losing visibility into the impact of a
1644 // suspended startup on the time until first frame / play ready for cases
1645 // where suspended startup was applied incorrectly.
1646 if (!attempting_suspended_start_)
1647 load_start_time_ = base::TimeTicks::Now() - time_to_metadata_;
1648 skip_metrics_due_to_startup_suspend_ = false;
1649 }
1650
avayvod2135a642017-01-13 00:17:141651 // Enable video track if we disabled it in the background - this way the new
1652 // renderer will attach its callbacks to the video stream properly.
1653 // TODO(avayvod): Remove this when disabling and enabling video tracks in
1654 // non-playing state works correctly. See https://crbug.com/678374.
1655 EnableVideoTrackIfNeeded();
1656 is_pipeline_resuming_ = true;
1657}
1658
1659void WebMediaPlayerImpl::OnPipelineResumed() {
1660 is_pipeline_resuming_ = false;
1661
avayvod56e1f3942017-01-21 02:06:311662 UpdateBackgroundVideoOptimizationState();
avayvod2135a642017-01-13 00:17:141663}
1664
alokp967c902452016-05-06 05:21:371665void WebMediaPlayerImpl::OnDemuxerOpened() {
1666 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtis9cddc0b2017-04-19 21:23:381667 client_->MediaSourceOpened(new WebMediaSourceImpl(chunk_demuxer_));
alokp967c902452016-05-06 05:21:371668}
1669
servolkf94b4602017-01-31 16:44:271670void WebMediaPlayerImpl::OnMemoryPressure(
1671 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1672 DVLOG(2) << __func__ << " memory_pressure_level=" << memory_pressure_level;
1673 DCHECK(main_task_runner_->BelongsToCurrentThread());
1674 DCHECK(base::FeatureList::IsEnabled(kMemoryPressureBasedSourceBufferGC));
1675 DCHECK(chunk_demuxer_);
1676
1677 // The new value of |memory_pressure_level| will take effect on the next
1678 // garbage collection. Typically this means the next SourceBuffer append()
1679 // operation, since per MSE spec, the garbage collection must only occur
1680 // during SourceBuffer append(). But if memory pressure is critical it might
1681 // be better to perform GC immediately rather than wait for the next append
1682 // and potentially get killed due to out-of-memory.
1683 // So if this experiment is enabled and pressure level is critical, we'll pass
1684 // down force_instant_gc==true, which will force immediate GC on
1685 // SourceBufferStreams.
1686 bool force_instant_gc =
1687 (enable_instant_source_buffer_gc_ &&
1688 memory_pressure_level ==
1689 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
1690
Matt Wolenetz95af6362018-01-04 20:23:421691 // base::Unretained is safe, since |chunk_demuxer_| is actually owned by
1692 // |this| via this->demuxer_. Note the destruction of |chunk_demuxer_| is done
1693 // from ~WMPI by first hopping to |media_task_runner_| to prevent race with
1694 // this task.
servolkf94b4602017-01-31 16:44:271695 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:511696 FROM_HERE, base::BindOnce(&ChunkDemuxer::OnMemoryPressure,
1697 base::Unretained(chunk_demuxer_),
1698 base::TimeDelta::FromSecondsD(CurrentTime()),
1699 memory_pressure_level, force_instant_gc));
servolkf94b4602017-01-31 16:44:271700}
1701
alokp967c902452016-05-06 05:21:371702void WebMediaPlayerImpl::OnError(PipelineStatus status) {
Xiaohan Wang73b433f2019-11-05 20:13:011703 DVLOG(1) << __func__ << ": status=" << status;
alokp967c902452016-05-06 05:21:371704 DCHECK(main_task_runner_->BelongsToCurrentThread());
1705 DCHECK_NE(status, PIPELINE_OK);
1706
1707 if (suppress_destruction_errors_)
1708 return;
1709
Thomas Guilbert6b6be3d2017-08-18 03:17:271710#if defined(OS_ANDROID)
Dale Curtisf273f8f2018-12-13 23:40:331711 // |mb_data_source_| may be nullptr if someone passes in a m3u8 as a data://
1712 // URL, since MediaPlayer doesn't support data:// URLs, fail playback now.
Dan Sanders675250992019-05-11 00:07:491713 const bool found_hls = base::FeatureList::IsEnabled(kHlsPlayer) &&
1714 status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS;
Dale Curtisf273f8f2018-12-13 23:40:331715 if (found_hls && mb_data_source_) {
Dan Sandersae245e42019-03-07 23:25:291716 demuxer_found_hls_ = true;
1717
Dan Sandersd80b1842019-02-05 00:36:161718 UMA_HISTOGRAM_BOOLEAN("Media.WebMediaPlayerImpl.HLS.IsCorsCrossOrigin",
1719 mb_data_source_->IsCorsCrossOrigin());
Dan Sandersae245e42019-03-07 23:25:291720 if (mb_data_source_->IsCorsCrossOrigin()) {
1721 UMA_HISTOGRAM_BOOLEAN("Media.WebMediaPlayerImpl.HLS.HasAccessControl",
1722 mb_data_source_->HasAccessControl());
1723 }
1724
1725 // Note: Does not consider the full redirect chain, which could contain
1726 // undetected mixed content.
Dan Sandersd80b1842019-02-05 00:36:161727 bool frame_url_is_cryptographic = url::Origin(frame_->GetSecurityOrigin())
1728 .GetURL()
1729 .SchemeIsCryptographic();
1730 bool manifest_url_is_cryptographic =
1731 loaded_url_.SchemeIsCryptographic() &&
1732 mb_data_source_->GetUrlAfterRedirects().SchemeIsCryptographic();
1733 UMA_HISTOGRAM_BOOLEAN(
1734 "Media.WebMediaPlayerImpl.HLS.IsMixedContent",
1735 frame_url_is_cryptographic && !manifest_url_is_cryptographic);
Thomas Guilbert153f84572018-07-19 05:03:581736
Xiaohan Wang3684e0c2019-10-30 01:04:301737 renderer_factory_selector_->SetBaseFactoryType(
1738 RendererFactorySelector::FactoryType::MEDIA_PLAYER);
Thomas Guilbert6b6be3d2017-08-18 03:17:271739
Dale Curtisf273f8f2018-12-13 23:40:331740 loaded_url_ = mb_data_source_->GetUrlAfterRedirects();
1741 DCHECK(data_source_);
1742 data_source_->Stop();
1743 mb_data_source_ = nullptr;
1744
Antonio Gomes81b56552019-05-15 22:15:281745 pipeline_controller_->Stop();
Dale Curtis8a6281322017-08-31 00:35:531746 SetMemoryReportingState(false);
Thomas Guilbert6b6be3d2017-08-18 03:17:271747
Dale Curtisf273f8f2018-12-13 23:40:331748 // Trampoline through the media task runner to destruct the demuxer and
1749 // data source now that we're switching to HLS playback.
1750 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:511751 FROM_HERE,
Dale Curtisf273f8f2018-12-13 23:40:331752 BindToCurrentLoop(base::BindOnce(
1753 [](std::unique_ptr<Demuxer> demuxer,
1754 std::unique_ptr<DataSource> data_source,
1755 base::OnceClosure start_pipeline_cb) {
1756 // Release resources before starting HLS.
1757 demuxer.reset();
1758 data_source.reset();
1759
1760 std::move(start_pipeline_cb).Run();
1761 },
1762 std::move(demuxer_), std::move(data_source_),
Antonio Gomes142f32a2019-05-15 23:32:561763 base::BindOnce(&WebMediaPlayerImpl::StartPipeline, weak_this_))));
Dale Curtisf273f8f2018-12-13 23:40:331764
Thomas Guilbert6b6be3d2017-08-18 03:17:271765 return;
1766 }
Dale Curtisf273f8f2018-12-13 23:40:331767
1768 // We found hls in a data:// URL, fail immediately.
1769 if (found_hls)
1770 status = PIPELINE_ERROR_EXTERNAL_RENDERER_FAILED;
Thomas Guilbert6b6be3d2017-08-18 03:17:271771#endif
1772
Dale Curtis5bba03232018-08-30 17:57:381773 MaybeSetContainerName();
Dan Sanders6edfd782019-08-13 00:13:181774 simple_watch_timer_.Stop();
alokp967c902452016-05-06 05:21:371775 media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status));
Dale Curtis74612b72017-12-14 20:56:191776 media_metrics_provider_->OnError(status);
Dale Curtisccfd0cca2017-08-31 01:27:561777 if (watch_time_reporter_)
1778 watch_time_reporter_->OnError(status);
alokp967c902452016-05-06 05:21:371779
Blink Reformat1c4d759e2017-04-09 16:34:541780 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) {
alokp967c902452016-05-06 05:21:371781 // Any error that occurs before reaching ReadyStateHaveMetadata should
1782 // be considered a format error.
Blink Reformat1c4d759e2017-04-09 16:34:541783 SetNetworkState(WebMediaPlayer::kNetworkStateFormatError);
alokp967c902452016-05-06 05:21:371784 } else {
Antonio Gomesf01cfbd2019-07-12 08:53:111785 SetNetworkState(blink::PipelineErrorToNetworkState(status));
alokp967c902452016-05-06 05:21:371786 }
1787
Thomas Guilbert2e591392017-08-12 00:56:381788 // PipelineController::Stop() is idempotent.
Antonio Gomes81b56552019-05-15 22:15:281789 pipeline_controller_->Stop();
Thomas Guilbert2e591392017-08-12 00:56:381790
alokp967c902452016-05-06 05:21:371791 UpdatePlayState();
1792}
1793
1794void WebMediaPlayerImpl::OnEnded() {
John Chen5b164a02017-11-01 00:36:091795 TRACE_EVENT2("media", "WebMediaPlayerImpl::OnEnded", "duration", Duration(),
1796 "id", media_log_->id());
pkastingf5279482016-07-27 02:18:201797 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:431798 DCHECK(main_task_runner_->BelongsToCurrentThread());
scherkusd2c745b2014-09-04 05:03:401799
sandersd1c0bba02016-03-04 23:14:081800 // Ignore state changes until we've completed all outstanding operations.
Antonio Gomes81b56552019-05-15 22:15:281801 if (!pipeline_controller_->IsStable())
scherkusd2c745b2014-09-04 05:03:401802 return;
1803
1804 ended_ = true;
Blink Reformat1c4d759e2017-04-09 16:34:541805 client_->TimeChanged();
sandersd50a635e2016-04-04 22:50:091806
1807 // We don't actually want this to run until |client_| calls seek() or pause(),
1808 // but that should have already happened in timeChanged() and so this is
1809 // expected to be a no-op.
1810 UpdatePlayState();
[email protected]576537842009-08-12 23:52:051811}
1812
Chisoon Jeong0a8e4bc2019-05-11 00:06:141813void WebMediaPlayerImpl::OnMetadata(const PipelineMetadata& metadata) {
pkastingf5279482016-07-27 02:18:201814 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:431815 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisff576552018-03-30 02:32:441816
1817 // Cache the |time_to_metadata_| to use for adjusting the TimeToFirstFrame and
1818 // TimeToPlayReady metrics later if we end up doing a suspended startup.
1819 time_to_metadata_ = base::TimeTicks::Now() - load_start_time_;
1820 media_metrics_provider_->SetTimeToMetadata(time_to_metadata_);
1821 RecordTimingUMA("Media.TimeToMetadata", time_to_metadata_);
[email protected]a8e2cb82012-08-17 00:02:391822
Dale Curtis5bba03232018-08-30 17:57:381823 MaybeSetContainerName();
1824
[email protected]b8877772014-03-26 20:17:151825 pipeline_metadata_ = metadata;
[email protected]739847c02014-01-16 00:12:251826
Ted Meyer4a427632019-05-01 19:05:271827 UMA_HISTOGRAM_ENUMERATION(
1828 "Media.VideoRotation",
1829 metadata.video_decoder_config.video_transformation().rotation,
1830 VIDEO_ROTATION_MAX + 1);
[email protected]21c3f7502013-03-23 03:29:511831
John Rummelldb5a7ef2018-05-16 00:28:011832 if (HasAudio()) {
Ted Meyerd5885f82019-07-16 19:19:171833 media_metrics_provider_->SetHasAudio(metadata.audio_decoder_config.codec());
John Rummelldb5a7ef2018-05-16 00:28:011834 RecordEncryptionScheme("Audio",
1835 metadata.audio_decoder_config.encryption_scheme());
1836 }
1837
Blink Reformat1c4d759e2017-04-09 16:34:541838 if (HasVideo()) {
Ted Meyerd5885f82019-07-16 19:19:171839 media_metrics_provider_->SetHasVideo(metadata.video_decoder_config.codec());
John Rummelldb5a7ef2018-05-16 00:28:011840 RecordEncryptionScheme("Video",
1841 metadata.video_decoder_config.encryption_scheme());
1842
liberato2fd111be2017-01-04 00:25:061843 if (overlay_enabled_) {
1844 // SurfaceView doesn't support rotated video, so transition back if
[email protected]c8d574722017-08-30 20:53:431845 // the video is now rotated. If |always_enable_overlays_|, we keep the
liberato2fd111be2017-01-04 00:25:061846 // overlay anyway so that the state machine keeps working.
[email protected]c8d574722017-08-30 20:53:431847 // TODO(liberato): verify if compositor feedback catches this. If so,
1848 // then we don't need this check.
1849 if (!always_enable_overlays_ && !DoesOverlaySupportMetadata())
liberato2fd111be2017-01-04 00:25:061850 DisableOverlay();
liberato2fd111be2017-01-04 00:25:061851 }
watkf835a792016-06-24 23:24:401852
[email protected]702d721d2018-10-25 21:55:271853 if (surface_layer_mode_ ==
Mounir Lamouri28d648102019-11-27 16:49:031854 blink::WebMediaPlayer::SurfaceLayerMode::kAlways) {
[email protected]702d721d2018-10-25 21:55:271855 ActivateSurfaceLayerForVideo();
1856 } else {
danakj6e669e782018-05-16 16:57:171857 DCHECK(!video_layer_);
Ted Meyer4a427632019-05-01 19:05:271858 // TODO(tmathmeyer) does this need support for reflections as well?
danakj25f030112018-05-11 18:26:541859 video_layer_ = cc::VideoLayer::Create(
Julien Isorce6c83d8de2017-10-12 13:11:291860 compositor_.get(),
Ted Meyer4a427632019-05-01 19:05:271861 pipeline_metadata_.video_decoder_config.video_transformation()
1862 .rotation);
danakj8bc61c72018-05-16 13:55:061863 video_layer_->SetContentsOpaque(opaque_);
danakj8d204a42018-05-18 18:05:351864 client_->SetCcLayer(video_layer_.get());
lethalantidote7f6009d2017-07-07 21:47:391865 }
[email protected]a8e2cb82012-08-17 00:02:391866 }
dalecurtis8e4dc682016-03-15 02:30:301867
xjzd3fe45a2016-10-12 18:26:371868 if (observer_)
xjz15b483f2017-01-12 00:21:361869 observer_->OnMetadataChanged(pipeline_metadata_);
xjzd3fe45a2016-10-12 18:26:371870
Dale Curtisc7d2a7d22018-01-11 20:01:051871 // TODO(dalecurtis): Don't create these until kReadyStateHaveFutureData; when
1872 // we create them early we just increase the chances of needing to throw them
1873 // away unnecessarily.
dalecurtis04bdb582016-08-17 22:15:231874 CreateWatchTimeReporter();
Chris Cunninghamd9df58e2017-08-29 00:04:231875 CreateVideoDecodeStatsReporter();
Dale Curtisc7d2a7d22018-01-11 20:01:051876
Dale Curtis1e7a02b42019-05-28 20:12:241877 // SetReadyState() may trigger all sorts of calls into this class (e.g.,
1878 // Play(), Pause(), etc) so do it last to avoid unexpected states during the
1879 // calls. An exception to this is UpdatePlayState(), which is safe to call and
1880 // needs to use the new ReadyState in its calculations.
Dale Curtis2fc01cc2019-05-20 22:53:521881 SetReadyState(WebMediaPlayer::kReadyStateHaveMetadata);
Dale Curtis1e7a02b42019-05-28 20:12:241882 UpdatePlayState();
[email protected]a8e2cb82012-08-17 00:02:391883}
1884
[email protected]69db58f2018-09-26 20:27:561885void WebMediaPlayerImpl::ActivateSurfaceLayerForVideo() {
1886 // Note that we might or might not already be in VideoLayer mode.
1887 DCHECK(!bridge_);
1888
1889 surface_layer_for_video_enabled_ = true;
1890
1891 // If we're in VideoLayer mode, then get rid of the layer.
1892 if (video_layer_) {
1893 client_->SetCcLayer(nullptr);
1894 video_layer_ = nullptr;
1895 }
1896
1897 bridge_ = std::move(create_bridge_callback_)
1898 .Run(this, compositor_->GetUpdateSubmissionStateCallback());
1899 bridge_->CreateSurfaceLayer();
1900
Ted Meyer4a427632019-05-01 19:05:271901 // TODO(tmathmeyer) does this need support for the reflection transformation
1902 // as well?
[email protected]69db58f2018-09-26 20:27:561903 vfc_task_runner_->PostTask(
1904 FROM_HERE,
Ted Meyer4a427632019-05-01 19:05:271905 base::BindOnce(
1906 &VideoFrameCompositor::EnableSubmission,
1907 base::Unretained(compositor_.get()), bridge_->GetSurfaceId(),
1908 bridge_->GetLocalSurfaceIdAllocationTime(),
1909 pipeline_metadata_.video_decoder_config.video_transformation()
1910 .rotation,
1911 IsInPictureInPicture()));
[email protected]69db58f2018-09-26 20:27:561912 bridge_->SetContentsOpaque(opaque_);
1913
1914 // If the element is already in Picture-in-Picture mode, it means that it
1915 // was set in this mode prior to this load, with a different
1916 // WebMediaPlayerImpl. The new player needs to send its id, size and
1917 // surface id to the browser process to make sure the states are properly
1918 // updated.
1919 // TODO(872056): the surface should be activated but for some reasons, it
1920 // does not. It is possible that this will no longer be needed after 872056
1921 // is fixed.
Dale Curtisca1b78f2019-01-15 03:11:261922 if (IsInPictureInPicture())
[email protected]69db58f2018-09-26 20:27:561923 OnSurfaceIdUpdated(bridge_->GetSurfaceId());
[email protected]69db58f2018-09-26 20:27:561924}
1925
Chris Cunninghamfc0d67e2019-07-22 20:29:161926void WebMediaPlayerImpl::OnBufferingStateChange(
1927 BufferingState state,
1928 BufferingStateChangeReason reason) {
1929 OnBufferingStateChangeInternal(state, reason, false);
Dale Curtis2dc6089a2018-03-26 16:47:581930}
1931
Chris Cunninghamd9df58e2017-08-29 00:04:231932void WebMediaPlayerImpl::CreateVideoDecodeStatsReporter() {
1933 // TODO(chcunningham): destroy reporter if we initially have video but the
1934 // track gets disabled. Currently not possible in default desktop Chrome.
1935 if (!HasVideo())
1936 return;
1937
Chris Cunningham89b4b762019-03-27 17:13:331938 // Only record stats from the local pipeline.
1939 if (is_flinging_ || is_remote_rendering_ || using_media_player_renderer_)
1940 return;
1941
Chris Cunninghamd9df58e2017-08-29 00:04:231942 // Stats reporter requires a valid config. We may not have one for HLS cases
1943 // where URL demuxer doesn't know details of the stream.
1944 if (!pipeline_metadata_.video_decoder_config.IsValidConfig())
1945 return;
1946
Chris Cunningham6c0ec292019-04-04 18:31:111947 // Profile must be known for use as index to save the reported stats.
Chris Cunningham5b1b67eb2019-03-23 03:24:411948 if (pipeline_metadata_.video_decoder_config.profile() ==
1949 VIDEO_CODEC_PROFILE_UNKNOWN) {
1950 return;
1951 }
1952
Chris Cunningham6c0ec292019-04-04 18:31:111953 // CdmConfig must be provided for use as index to save encrypted stats.
1954 if (is_encrypted_ && !cdm_config_) {
Chris Cunninghamd9df58e2017-08-29 00:04:231955 return;
Chris Cunningham6c0ec292019-04-04 18:31:111956 } else if (cdm_config_) {
1957 DCHECK(!key_system_.empty());
1958 }
Chris Cunninghamd9df58e2017-08-29 00:04:231959
Gyuyoung Kima040bc52019-10-30 01:14:351960 mojo::PendingRemote<mojom::VideoDecodeStatsRecorder> recorder;
Dale Curtis7e8a510d2017-12-14 19:19:481961 media_metrics_provider_->AcquireVideoDecodeStatsRecorder(
Gyuyoung Kima040bc52019-10-30 01:14:351962 recorder.InitWithNewPipeAndPassReceiver());
Chris Cunninghamc7c6a6d2017-11-23 14:06:451963
Chris Cunninghamd9df58e2017-08-29 00:04:231964 // Create capabilities reporter and synchronize its initial state.
1965 video_decode_stats_reporter_.reset(new VideoDecodeStatsReporter(
Chris Cunninghamc7c6a6d2017-11-23 14:06:451966 std::move(recorder),
Chris Cunninghamd9df58e2017-08-29 00:04:231967 base::Bind(&WebMediaPlayerImpl::GetPipelineStatistics,
1968 base::Unretained(this)),
Chris Cunningham5b1b67eb2019-03-23 03:24:411969 pipeline_metadata_.video_decoder_config.profile(),
Chris Cunningham6c0ec292019-04-04 18:31:111970 pipeline_metadata_.natural_size, key_system_, cdm_config_,
Hajime Hoshib5a26ee2018-05-14 12:47:511971 frame_->GetTaskRunner(blink::TaskType::kInternalMedia)));
Chris Cunninghamd9df58e2017-08-29 00:04:231972
1973 if (delegate_->IsFrameHidden())
1974 video_decode_stats_reporter_->OnHidden();
1975 else
1976 video_decode_stats_reporter_->OnShown();
1977
1978 if (paused_)
1979 video_decode_stats_reporter_->OnPaused();
1980 else
1981 video_decode_stats_reporter_->OnPlaying();
1982}
1983
hubbeb2d3efd2017-05-05 23:26:381984void WebMediaPlayerImpl::OnProgress() {
Chris Watkins1ffabc5f2017-05-10 20:52:091985 DVLOG(4) << __func__;
Dale Curtisad645f72019-09-06 23:28:161986
1987 // See IsPrerollAttemptNeeded() for more details. We can't use that method
1988 // here since it considers |preroll_attempt_start_time_| and for OnProgress()
1989 // events we must make the attempt -- since there may not be another event.
1990 if (highest_ready_state_ < ReadyState::kReadyStateHaveFutureData) {
hubbeb2d3efd2017-05-05 23:26:381991 // Reset the preroll attempt clock.
1992 preroll_attempt_pending_ = true;
1993 preroll_attempt_start_time_ = base::TimeTicks();
1994
1995 // Clear any 'stale' flag and give the pipeline a chance to resume. If we
1996 // are already resumed, this will cause |preroll_attempt_start_time_| to
1997 // be set.
1998 delegate_->ClearStaleFlag(delegate_id_);
1999 UpdatePlayState();
2000 } else if (ready_state_ == ReadyState::kReadyStateHaveFutureData &&
2001 CanPlayThrough()) {
2002 SetReadyState(WebMediaPlayer::kReadyStateHaveEnoughData);
2003 }
2004}
2005
2006bool WebMediaPlayerImpl::CanPlayThrough() {
2007 if (!base::FeatureList::IsEnabled(kSpecCompliantCanPlayThrough))
2008 return true;
2009 if (chunk_demuxer_)
2010 return true;
Dale Curtis4841c712018-12-13 18:14:052011 if (data_source_ && data_source_->AssumeFullyBuffered())
hubbeb2d3efd2017-05-05 23:26:382012 return true;
2013 // If we're not currently downloading, we have as much buffer as
2014 // we're ever going to get, which means we say we can play through.
2015 if (network_state_ == WebMediaPlayer::kNetworkStateIdle)
2016 return true;
Antonio Gomes81b56552019-05-15 22:15:282017 return buffered_data_source_host_->CanPlayThrough(
hubbeb2d3efd2017-05-05 23:26:382018 base::TimeDelta::FromSecondsD(CurrentTime()),
2019 base::TimeDelta::FromSecondsD(Duration()),
2020 playback_rate_ == 0.0 ? 1.0 : playback_rate_);
2021}
2022
Dale Curtisff576552018-03-30 02:32:442023void WebMediaPlayerImpl::OnBufferingStateChangeInternal(
2024 BufferingState state,
Chris Cunninghamfc0d67e2019-07-22 20:29:162025 BufferingStateChangeReason reason,
Dale Curtisff576552018-03-30 02:32:442026 bool for_suspended_start) {
Chris Cunninghamfc0d67e2019-07-22 20:29:162027 DVLOG(1) << __func__ << "(" << state << ", " << reason << ")";
alokp967c902452016-05-06 05:21:372028 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]b8877772014-03-26 20:17:152029
Ted Meyer742212b82018-08-22 17:21:422030 // Ignore buffering state changes caused by back-to-back seeking, so as not
2031 // to assume the second seek has finished when it was only the first seek.
Antonio Gomes81b56552019-05-15 22:15:282032 if (pipeline_controller_->IsPendingSeek())
[email protected]ba7d5f92014-06-24 05:37:402033 return;
[email protected]b8877772014-03-26 20:17:152034
Dale Curtisff576552018-03-30 02:32:442035 auto log_event = media_log_->CreateBufferingStateChangedEvent(
Chris Cunninghamfc0d67e2019-07-22 20:29:162036 "pipeline_buffering_state", state, reason);
Dale Curtisff576552018-03-30 02:32:442037 log_event->params.SetBoolean("for_suspended_start", for_suspended_start);
2038 media_log_->AddEvent(std::move(log_event));
dalecurtis869bf2f2017-01-10 18:01:102039
Ted Meyerd5885f82019-07-16 19:19:172040 if (state == BUFFERING_HAVE_ENOUGH && !for_suspended_start)
2041 media_metrics_provider_->SetHaveEnough();
2042
chcunninghameb270c92016-07-15 01:00:452043 if (state == BUFFERING_HAVE_ENOUGH) {
John Chen5b164a02017-11-01 00:36:092044 TRACE_EVENT1("media", "WebMediaPlayerImpl::BufferingHaveEnough", "id",
2045 media_log_->id());
Dale Curtisff576552018-03-30 02:32:442046 // The SetReadyState() call below may clear
2047 // |skip_metrics_due_to_startup_suspend_| so report this first.
2048 if (!have_reported_time_to_play_ready_ &&
2049 !skip_metrics_due_to_startup_suspend_) {
2050 DCHECK(!for_suspended_start);
Dale Curtis3899090ea2018-01-12 00:10:352051 have_reported_time_to_play_ready_ = true;
2052 const base::TimeDelta elapsed = base::TimeTicks::Now() - load_start_time_;
2053 media_metrics_provider_->SetTimeToPlayReady(elapsed);
2054 RecordTimingUMA("Media.TimeToPlayReady", elapsed);
2055 }
[email protected]ba7d5f92014-06-24 05:37:402056
Dale Curtisff576552018-03-30 02:32:442057 // Warning: This call may be re-entrant.
2058 SetReadyState(CanPlayThrough() ? WebMediaPlayer::kReadyStateHaveEnoughData
2059 : WebMediaPlayer::kReadyStateHaveFutureData);
2060
Dale Curtis18ad391b2019-05-30 23:25:092061 // Let the DataSource know we have enough data -- this is the only function
2062 // during which we advance to (or past) the kReadyStateHaveEnoughData state.
2063 // It may use this information to update buffer sizes or release unused
2064 // network connections.
2065 MaybeUpdateBufferSizesForPlayback();
Dale Curtis04769ca2019-05-25 00:38:102066 if (mb_data_source_ && !client_->CouldPlayIfEnoughData()) {
2067 // For LazyLoad this will be handled during OnPipelineSuspended().
2068 if (for_suspended_start && did_lazy_load_)
2069 DCHECK(!have_enough_after_lazy_load_cb_.IsCancelled());
2070 else
2071 mb_data_source_->OnBufferingHaveEnough(false);
2072 }
dalecurtis849cf4b22015-03-27 18:35:452073
chcunninghameb270c92016-07-15 01:00:452074 // Blink expects a timeChanged() in response to a seek().
sandersd35d2c3f2017-01-14 02:04:422075 if (should_notify_time_changed_) {
2076 should_notify_time_changed_ = false;
Blink Reformat1c4d759e2017-04-09 16:34:542077 client_->TimeChanged();
sandersd35d2c3f2017-01-14 02:04:422078 }
dalecurtis0f0097a2015-12-01 17:40:472079
chcunninghameb270c92016-07-15 01:00:452080 // Once we have enough, start reporting the total memory usage. We'll also
2081 // report once playback starts.
2082 ReportMemoryUsage();
dalecurtis9d638a12016-08-30 06:20:552083
dalecurtis4f6d14d2017-02-22 17:42:222084 // Report the amount of time it took to leave the underflow state.
2085 if (underflow_timer_) {
Dale Curtisc9069622019-10-24 20:20:502086 auto elapsed = underflow_timer_->Elapsed();
2087 RecordUnderflowDuration(elapsed);
2088 watch_time_reporter_->OnUnderflowComplete(elapsed);
dalecurtis9d638a12016-08-30 06:20:552089 underflow_timer_.reset();
2090 }
chcunninghameb270c92016-07-15 01:00:452091 } else {
2092 // Buffering has underflowed.
2093 DCHECK_EQ(state, BUFFERING_HAVE_NOTHING);
dalecurtisacd77d62016-09-09 23:23:142094
dalecurtisd06eabc2017-02-24 23:43:292095 // Report the number of times we've entered the underflow state. Ensure we
2096 // only report the value when transitioning from HAVE_ENOUGH to
2097 // HAVE_NOTHING.
Dale Curtis6995b862017-05-31 22:20:082098 if (ready_state_ == WebMediaPlayer::kReadyStateHaveEnoughData &&
2099 !seeking_) {
dalecurtisacd77d62016-09-09 23:23:142100 underflow_timer_.reset(new base::ElapsedTimer());
Dale Curtis6995b862017-05-31 22:20:082101 watch_time_reporter_->OnUnderflow();
2102 }
dalecurtisacd77d62016-09-09 23:23:142103
chcunninghameb270c92016-07-15 01:00:452104 // It shouldn't be possible to underflow if we've not advanced past
2105 // HAVE_CURRENT_DATA.
Blink Reformat1c4d759e2017-04-09 16:34:542106 DCHECK_GT(highest_ready_state_, WebMediaPlayer::kReadyStateHaveCurrentData);
2107 SetReadyState(WebMediaPlayer::kReadyStateHaveCurrentData);
chcunninghameb270c92016-07-15 01:00:452108 }
sandersd50a635e2016-04-04 22:50:092109
2110 UpdatePlayState();
[email protected]b8877772014-03-26 20:17:152111}
2112
alokp967c902452016-05-06 05:21:372113void WebMediaPlayerImpl::OnDurationChange() {
acolwellb4034942014-08-28 15:42:432114 DCHECK(main_task_runner_->BelongsToCurrentThread());
alokp967c902452016-05-06 05:21:372115
John Delaney2371b452018-12-13 04:30:332116 if (frame_->IsAdSubframe()) {
2117 UMA_HISTOGRAM_CUSTOM_TIMES("Ads.Media.Duration", GetPipelineMediaDuration(),
2118 base::TimeDelta::FromMilliseconds(1),
2119 base::TimeDelta::FromDays(1),
2120 50 /* bucket_count */);
2121 }
2122
alokp967c902452016-05-06 05:21:372123 // TODO(sandersd): We should call delegate_->DidPlay() with the new duration,
2124 // especially if it changed from <5s to >5s.
Blink Reformat1c4d759e2017-04-09 16:34:542125 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
alokp967c902452016-05-06 05:21:372126 return;
2127
Blink Reformat1c4d759e2017-04-09 16:34:542128 client_->DurationChanged();
Dale Curtisaebaeea2018-07-19 23:42:112129 if (watch_time_reporter_)
2130 watch_time_reporter_->OnDurationChanged(GetPipelineMediaDuration());
Becca Hughes7a85bf22019-07-24 16:16:582131
2132 // The duration has changed so we should update the media position state.
2133 UpdateMediaPositionState();
[email protected]81bb3322011-07-21 15:55:502134}
2135
alokp967c902452016-05-06 05:21:372136void WebMediaPlayerImpl::OnAddTextTrack(const TextTrackConfig& config,
2137 const AddTextTrackDoneCB& done_cb) {
acolwellb4034942014-08-28 15:42:432138 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]71537722013-05-23 06:47:532139
[email protected]8a561062013-11-22 01:19:312140 const WebInbandTextTrackImpl::Kind web_kind =
2141 static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
Blink Reformat1c4d759e2017-04-09 16:34:542142 const blink::WebString web_label = blink::WebString::FromUTF8(config.label());
[email protected]8a561062013-11-22 01:19:312143 const blink::WebString web_language =
Blink Reformat1c4d759e2017-04-09 16:34:542144 blink::WebString::FromUTF8(config.language());
2145 const blink::WebString web_id = blink::WebString::FromUTF8(config.id());
[email protected]71537722013-05-23 06:47:532146
dcheng3076abbf2016-04-22 20:42:392147 std::unique_ptr<WebInbandTextTrackImpl> web_inband_text_track(
henriks9cce5fa2014-12-12 09:35:302148 new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id));
[email protected]8a561062013-11-22 01:19:312149
Dale Curtisca1b78f2019-01-15 03:11:262150 std::unique_ptr<TextTrack> text_track(new TextTrackImpl(
dcheng652f5ff2015-12-27 08:54:002151 main_task_runner_, client_, std::move(web_inband_text_track)));
[email protected]8a561062013-11-22 01:19:312152
dcheng652f5ff2015-12-27 08:54:002153 done_cb.Run(std::move(text_track));
[email protected]71537722013-05-23 06:47:532154}
2155
Xiaohan Wang640b41d2018-12-18 19:00:462156void WebMediaPlayerImpl::OnWaiting(WaitingReason reason) {
alokp967c902452016-05-06 05:21:372157 DCHECK(main_task_runner_->BelongsToCurrentThread());
2158
Xiaohan Wang640b41d2018-12-18 19:00:462159 switch (reason) {
Xiaohan Wangb54a75282019-10-04 21:34:432160 case WaitingReason::kNoCdm:
Xiaohan Wang640b41d2018-12-18 19:00:462161 case WaitingReason::kNoDecryptionKey:
2162 encrypted_client_->DidBlockPlaybackWaitingForKey();
2163 // TODO(jrummell): didResumePlaybackBlockedForKey() should only be called
2164 // when a key has been successfully added (e.g. OnSessionKeysChange() with
2165 // |has_additional_usable_key| = true). http://crbug.com/461903
2166 encrypted_client_->DidResumePlaybackBlockedForKey();
2167 return;
Xiaohan Wang640b41d2018-12-18 19:00:462168
Xiaohan Wanga7224d62019-01-04 22:22:302169 // Ideally this should be handled by PipelineController directly without
2170 // being proxied here. But currently Pipeline::Client (|this|) is passed to
2171 // PipelineImpl directly without going through |pipeline_controller_|,
2172 // making it difficult to do.
2173 // TODO(xhwang): Handle this in PipelineController when we have a clearer
2174 // picture on how to refactor WebMediaPlayerImpl, PipelineController and
2175 // PipelineImpl.
2176 case WaitingReason::kDecoderStateLost:
Antonio Gomes81b56552019-05-15 22:15:282177 pipeline_controller_->OnDecoderStateLost();
Xiaohan Wanga7224d62019-01-04 22:22:302178 return;
2179 }
alokp967c902452016-05-06 05:21:372180}
2181
alokp5d86e9b2016-05-17 20:20:412182void WebMediaPlayerImpl::OnVideoNaturalSizeChange(const gfx::Size& size) {
2183 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:542184 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
alokp5d86e9b2016-05-17 20:20:412185
Chris Cunningham038548b2017-07-10 22:36:302186 TRACE_EVENT0("media", "WebMediaPlayerImpl::OnVideoNaturalSizeChange");
xhwang60802652017-04-19 07:29:582187
xjz15b483f2017-01-12 00:21:362188 // The input |size| is from the decoded video frame, which is the original
2189 // natural size and need to be rotated accordingly.
Julien Isorce6c83d8de2017-10-12 13:11:292190 gfx::Size rotated_size = GetRotatedVideoSize(
Ted Meyer4a427632019-05-01 19:05:272191 pipeline_metadata_.video_decoder_config.video_transformation().rotation,
2192 size);
sandersd2c478422016-08-02 01:19:252193
xhwang60802652017-04-19 07:29:582194 RecordVideoNaturalSize(rotated_size);
2195
2196 gfx::Size old_size = pipeline_metadata_.natural_size;
2197 if (rotated_size == old_size)
alokp5d86e9b2016-05-17 20:20:412198 return;
2199
xjz516ef6d2017-01-07 00:23:062200 pipeline_metadata_.natural_size = rotated_size;
Dan Sanders7ef5d0f2019-05-03 18:30:112201
2202 if (using_media_player_renderer_ && old_size.IsEmpty()) {
2203 // If we are using MediaPlayerRenderer and this is the first size change, we
2204 // now know that there is a video track. This condition is paired with code
2205 // in CreateWatchTimeReporter() that guesses the existence of a video track.
2206 CreateWatchTimeReporter();
2207 } else {
Dan Sanders7ef5d0f2019-05-03 18:30:112208 UpdateSecondaryProperties();
2209 }
dalecurtis25405562017-04-14 23:35:112210
Chris Cunningham5b1b67eb2019-03-23 03:24:412211 if (video_decode_stats_reporter_ &&
2212 !video_decode_stats_reporter_->MatchesBucketedNaturalSize(
2213 pipeline_metadata_.natural_size)) {
2214 CreateVideoDecodeStatsReporter();
2215 }
Chris Cunninghamd9df58e2017-08-29 00:04:232216
Blink Reformat1c4d759e2017-04-09 16:34:542217 client_->SizeChanged();
xjz516ef6d2017-01-07 00:23:062218
xjz15b483f2017-01-12 00:21:362219 if (observer_)
2220 observer_->OnMetadataChanged(pipeline_metadata_);
peconn257951522017-06-09 18:24:592221
2222 delegate_->DidPlayerSizeChange(delegate_id_, NaturalSize());
alokp5d86e9b2016-05-17 20:20:412223}
2224
2225void WebMediaPlayerImpl::OnVideoOpacityChange(bool opaque) {
2226 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:542227 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
alokp5d86e9b2016-05-17 20:20:412228
2229 opaque_ = opaque;
Dale Curtis357630f22019-01-18 01:10:172230 if (!surface_layer_for_video_enabled_ && video_layer_)
2231 video_layer_->SetContentsOpaque(opaque_);
2232 else if (bridge_->GetCcLayer())
CJ DiMeglioa2b13fbc2018-06-27 00:50:592233 bridge_->SetContentsOpaque(opaque_);
alokp5d86e9b2016-05-17 20:20:412234}
2235
Chris Cunningham038548b2017-07-10 22:36:302236void WebMediaPlayerImpl::OnAudioConfigChange(const AudioDecoderConfig& config) {
2237 DCHECK(main_task_runner_->BelongsToCurrentThread());
2238 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
2239
Dale Curtisccfd0cca2017-08-31 01:27:562240 const bool codec_change =
2241 pipeline_metadata_.audio_decoder_config.codec() != config.codec();
Chris Cunningham038548b2017-07-10 22:36:302242 pipeline_metadata_.audio_decoder_config = config;
2243
2244 if (observer_)
2245 observer_->OnMetadataChanged(pipeline_metadata_);
Dale Curtisccfd0cca2017-08-31 01:27:562246
2247 if (codec_change)
Dale Curtis96d6e9382018-07-18 18:01:072248 UpdateSecondaryProperties();
Chris Cunningham038548b2017-07-10 22:36:302249}
2250
2251void WebMediaPlayerImpl::OnVideoConfigChange(const VideoDecoderConfig& config) {
2252 DCHECK(main_task_runner_->BelongsToCurrentThread());
2253 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
2254
Dale Curtisccfd0cca2017-08-31 01:27:562255 const bool codec_change =
2256 pipeline_metadata_.video_decoder_config.codec() != config.codec();
Chris Cunningham5b1b67eb2019-03-23 03:24:412257 const bool codec_profile_change =
2258 pipeline_metadata_.video_decoder_config.profile() != config.profile();
Dale Curtisccfd0cca2017-08-31 01:27:562259
Chris Cunningham038548b2017-07-10 22:36:302260 pipeline_metadata_.video_decoder_config = config;
2261
2262 if (observer_)
2263 observer_->OnMetadataChanged(pipeline_metadata_);
Chris Cunninghamd9df58e2017-08-29 00:04:232264
Dale Curtisccfd0cca2017-08-31 01:27:562265 if (codec_change)
Dale Curtis96d6e9382018-07-18 18:01:072266 UpdateSecondaryProperties();
Chris Cunningham5b1b67eb2019-03-23 03:24:412267
2268 if (video_decode_stats_reporter_ && codec_profile_change)
2269 CreateVideoDecodeStatsReporter();
Chris Cunningham038548b2017-07-10 22:36:302270}
2271
avayvodeecec52c2017-02-14 01:25:092272void WebMediaPlayerImpl::OnVideoAverageKeyframeDistanceUpdate() {
2273 UpdateBackgroundVideoOptimizationState();
2274}
2275
Ted Meyerd5885f82019-07-16 19:19:172276void WebMediaPlayerImpl::OnAudioDecoderChange(const PipelineDecoderInfo& info) {
2277 media_metrics_provider_->SetAudioPipelineInfo(info);
2278 if (info.decoder_name == audio_decoder_name_)
Dale Curtisc7d2a7d22018-01-11 20:01:052279 return;
2280
Ted Meyerd5885f82019-07-16 19:19:172281 audio_decoder_name_ = info.decoder_name;
Dale Curtisc7d2a7d22018-01-11 20:01:052282
2283 // If there's no current reporter, there's nothing to be done.
2284 if (!watch_time_reporter_)
2285 return;
2286
Dale Curtis96d6e9382018-07-18 18:01:072287 UpdateSecondaryProperties();
Dale Curtisc7d2a7d22018-01-11 20:01:052288}
2289
Ted Meyerd5885f82019-07-16 19:19:172290void WebMediaPlayerImpl::OnVideoDecoderChange(const PipelineDecoderInfo& info) {
2291 media_metrics_provider_->SetVideoPipelineInfo(info);
2292 if (info.decoder_name == video_decoder_name_)
Dale Curtisc7d2a7d22018-01-11 20:01:052293 return;
2294
Ted Meyerd5885f82019-07-16 19:19:172295 video_decoder_name_ = info.decoder_name;
Dale Curtisc7d2a7d22018-01-11 20:01:052296
2297 // If there's no current reporter, there's nothing to be done.
2298 if (!watch_time_reporter_)
2299 return;
2300
Dale Curtis96d6e9382018-07-18 18:01:072301 UpdateSecondaryProperties();
Dale Curtisc7d2a7d22018-01-11 20:01:052302}
2303
sandersd35d2c3f2017-01-14 02:04:422304void WebMediaPlayerImpl::OnFrameHidden() {
sandersd1e49fb62015-12-12 01:18:062305 DCHECK(main_task_runner_->BelongsToCurrentThread());
avayvod39c102402016-11-23 21:43:132306
avayvod65fad272017-02-24 01:00:482307 // Backgrounding a video requires a user gesture to resume playback.
2308 if (IsHidden())
2309 video_locked_when_paused_when_hidden_ = true;
2310
dalecurtis04bdb582016-08-17 22:15:232311 if (watch_time_reporter_)
2312 watch_time_reporter_->OnHidden();
avayvod48a8be52016-08-04 19:52:502313
Chris Cunninghamd9df58e2017-08-29 00:04:232314 if (video_decode_stats_reporter_)
2315 video_decode_stats_reporter_->OnHidden();
2316
avayvod65fad272017-02-24 01:00:482317 UpdateBackgroundVideoOptimizationState();
sandersd50a635e2016-04-04 22:50:092318 UpdatePlayState();
dalecurtis8b8505e72016-06-10 21:59:172319
2320 // Schedule suspended playing media to be paused if the user doesn't come back
2321 // to it within some timeout period to avoid any autoplay surprises.
2322 ScheduleIdlePauseTimer();
Dale Curtisca1b78f2019-01-15 03:11:262323
2324 // Notify the compositor of our page visibility status.
2325 vfc_task_runner_->PostTask(
2326 FROM_HERE,
2327 base::BindOnce(&VideoFrameCompositor::SetIsPageVisible,
2328 base::Unretained(compositor_.get()), !IsHidden()));
sandersd1e49fb62015-12-12 01:18:062329}
2330
sandersd35d2c3f2017-01-14 02:04:422331void WebMediaPlayerImpl::OnFrameClosed() {
sandersd1e49fb62015-12-12 01:18:062332 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]28347e72017-06-27 17:30:112333
sandersd35d2c3f2017-01-14 02:04:422334 UpdatePlayState();
2335}
2336
2337void WebMediaPlayerImpl::OnFrameShown() {
2338 DCHECK(main_task_runner_->BelongsToCurrentThread());
2339 background_pause_timer_.Stop();
2340
avayvod65fad272017-02-24 01:00:482341 // Foreground videos don't require user gesture to continue playback.
2342 video_locked_when_paused_when_hidden_ = false;
2343
dalecurtis04bdb582016-08-17 22:15:232344 if (watch_time_reporter_)
2345 watch_time_reporter_->OnShown();
2346
Chris Cunninghamd9df58e2017-08-29 00:04:232347 if (video_decode_stats_reporter_)
2348 video_decode_stats_reporter_->OnShown();
2349
Dale Curtisca1b78f2019-01-15 03:11:262350 // Notify the compositor of our page visibility status.
2351 vfc_task_runner_->PostTask(
2352 FROM_HERE,
2353 base::BindOnce(&VideoFrameCompositor::SetIsPageVisible,
2354 base::Unretained(compositor_.get()), !IsHidden()));
2355
Dale Curtisdcbb81a2017-08-18 01:06:122356 UpdateBackgroundVideoOptimizationState();
avayvod65fad272017-02-24 01:00:482357
avayvod2135a642017-01-13 00:17:142358 if (paused_when_hidden_) {
2359 paused_when_hidden_ = false;
2360 OnPlay(); // Calls UpdatePlayState() so return afterwards.
2361 return;
2362 }
2363
sandersd50a635e2016-04-04 22:50:092364 UpdatePlayState();
sandersd1e49fb62015-12-12 01:18:062365}
2366
sandersd35d2c3f2017-01-14 02:04:422367void WebMediaPlayerImpl::OnIdleTimeout() {
dalecurtis0431cbf2016-03-12 01:19:432368 DCHECK(main_task_runner_->BelongsToCurrentThread());
2369
Dale Curtis99a9b482018-02-01 02:23:282370 // This should never be called when stale state testing overrides are used.
2371 DCHECK(!stale_state_override_for_testing_.has_value());
2372
sandersd35d2c3f2017-01-14 02:04:422373 // If we are attempting preroll, clear the stale flag.
2374 if (IsPrerollAttemptNeeded()) {
tguilbert1bb1c782017-01-23 21:15:112375 delegate_->ClearStaleFlag(delegate_id_);
sandersd35d2c3f2017-01-14 02:04:422376 return;
watkd026f792016-11-05 00:28:512377 }
sandersd50a635e2016-04-04 22:50:092378
sandersd35d2c3f2017-01-14 02:04:422379 UpdatePlayState();
dalecurtis0431cbf2016-03-12 01:19:432380}
2381
dalecurtisbb3eaac2016-01-27 21:10:252382void WebMediaPlayerImpl::OnPlay() {
Mounir Lamouri703106e2018-05-30 14:31:092383 client_->RequestPlay();
dalecurtisbb3eaac2016-01-27 21:10:252384}
2385
2386void WebMediaPlayerImpl::OnPause() {
Mounir Lamouri703106e2018-05-30 14:31:092387 client_->RequestPause();
dalecurtisbb3eaac2016-01-27 21:10:252388}
2389
François Beaufortb4fe7c62019-02-27 08:19:442390void WebMediaPlayerImpl::OnMuted(bool muted) {
2391 client_->RequestMuted(muted);
2392}
2393
Alec Douglas316cce42017-10-31 13:28:082394void WebMediaPlayerImpl::OnSeekForward(double seconds) {
2395 DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
2396 client_->RequestSeek(CurrentTime() + seconds);
2397}
2398
2399void WebMediaPlayerImpl::OnSeekBackward(double seconds) {
2400 DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
2401 client_->RequestSeek(CurrentTime() - seconds);
2402}
2403
dalecurtisbb3eaac2016-01-27 21:10:252404void WebMediaPlayerImpl::OnVolumeMultiplierUpdate(double multiplier) {
2405 volume_multiplier_ = multiplier;
Blink Reformat1c4d759e2017-04-09 16:34:542406 SetVolume(volume_);
dalecurtisbb3eaac2016-01-27 21:10:252407}
2408
zqzhang8ac49002017-03-16 21:51:352409void WebMediaPlayerImpl::OnBecamePersistentVideo(bool value) {
Blink Reformat1c4d759e2017-04-09 16:34:542410 client_->OnBecamePersistentVideo(value);
[email protected]6490e2d12019-01-14 19:18:372411 overlay_info_.is_persistent_video = value;
2412 MaybeSendOverlayInfoToDecoder();
zqzhang8ac49002017-03-16 21:51:352413}
2414
watkdee516f2016-02-18 02:22:192415void WebMediaPlayerImpl::ScheduleRestart() {
sandersd50a635e2016-04-04 22:50:092416 // TODO(watk): All restart logic should be moved into PipelineController.
Antonio Gomes81b56552019-05-15 22:15:282417 if (pipeline_controller_->IsPipelineRunning() &&
2418 !pipeline_controller_->IsPipelineSuspended()) {
watkdee516f2016-02-18 02:22:192419 pending_suspend_resume_cycle_ = true;
sandersd50a635e2016-04-04 22:50:092420 UpdatePlayState();
watkdee516f2016-02-18 02:22:192421 }
2422}
2423
Blink Reformat1c4d759e2017-04-09 16:34:542424void WebMediaPlayerImpl::RequestRemotePlaybackDisabled(bool disabled) {
miu77f914c2016-11-19 23:56:182425 if (observer_)
2426 observer_->OnRemotePlaybackDisabled(disabled);
2427}
2428
Thomas Guilbert7350fdad2019-01-29 23:09:242429#if defined(OS_ANDROID)
Thomas Guilbertb341bae02018-05-09 00:02:132430void WebMediaPlayerImpl::FlingingStarted() {
2431 DCHECK(main_task_runner_->BelongsToCurrentThread());
2432 DCHECK(!disable_pipeline_auto_suspend_);
2433 disable_pipeline_auto_suspend_ = true;
2434
Thomas Guilbert29ae1a902018-10-20 01:53:382435 is_flinging_ = true;
2436
Thomas Guilbertb341bae02018-05-09 00:02:132437 // Capabilities reporting should only be performed for local playbacks.
2438 video_decode_stats_reporter_.reset();
2439
2440 // Requests to restart media pipeline. A flinging renderer will be created via
2441 // the |renderer_factory_selector_|.
2442 ScheduleRestart();
2443}
2444
2445void WebMediaPlayerImpl::FlingingStopped() {
2446 DCHECK(main_task_runner_->BelongsToCurrentThread());
2447 DCHECK(disable_pipeline_auto_suspend_);
2448 disable_pipeline_auto_suspend_ = false;
2449
Thomas Guilbert29ae1a902018-10-20 01:53:382450 is_flinging_ = false;
2451
Thomas Guilbertb341bae02018-05-09 00:02:132452 CreateVideoDecodeStatsReporter();
2453
2454 ScheduleRestart();
2455}
Thomas Guilbert901808982019-07-03 20:38:182456
2457void WebMediaPlayerImpl::OnRemotePlayStateChange(MediaStatus::State state) {
2458 DCHECK(is_flinging_);
Thomas Guilbertf6d0702e2019-09-12 23:40:142459 DCHECK(main_task_runner_->BelongsToCurrentThread());
Thomas Guilbert901808982019-07-03 20:38:182460
2461 if (state == MediaStatus::State::PLAYING && Paused()) {
2462 DVLOG(1) << __func__ << " requesting PLAY.";
2463 client_->RequestPlay();
2464 } else if (state == MediaStatus::State::PAUSED && !Paused()) {
2465 DVLOG(1) << __func__ << " requesting PAUSE.";
2466 client_->RequestPause();
2467 }
2468}
Thomas Guilbert7350fdad2019-01-29 23:09:242469#endif // defined(OS_ANDROID)
hubbee4027f92016-05-19 05:18:132470
Blink Reformat1c4d759e2017-04-09 16:34:542471void WebMediaPlayerImpl::SetPoster(const blink::WebURL& poster) {
Dan Sanderscd8981c2017-08-31 22:37:022472 has_poster_ = !poster.IsEmpty();
Dan Sanderscd8981c2017-08-31 22:37:022473}
xjzc102fd82017-01-04 20:13:532474
[email protected]fee8a902014-06-03 13:43:362475void WebMediaPlayerImpl::DataSourceInitialized(bool success) {
pkastingf5279482016-07-27 02:18:202476 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:432477 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]a9415292012-01-19 19:55:202478
Thomas Guilberta8a6e922019-02-01 00:02:472479 if (observer_ && mb_data_source_)
Dale Curtis4841c712018-12-13 18:14:052480 observer_->OnDataSourceInitialized(mb_data_source_->GetUrlAfterRedirects());
Anton Vayvod09fa66e2017-07-20 23:02:122481
[email protected]d250190da3b2012-07-23 22:57:302482 if (!success) {
Blink Reformat1c4d759e2017-04-09 16:34:542483 SetNetworkState(WebMediaPlayer::kNetworkStateFormatError);
Dale Curtis74612b72017-12-14 20:56:192484 media_metrics_provider_->OnError(PIPELINE_ERROR_NETWORK);
sandersd50a635e2016-04-04 22:50:092485
2486 // Not really necessary, since the pipeline was never started, but it at
2487 // least this makes sure that the error handling code is in sync.
2488 UpdatePlayState();
2489
[email protected]a9415292012-01-19 19:55:202490 return;
2491 }
2492
hubbee2cc88c092017-07-14 23:10:412493 // No point in preloading data as we'll probably just throw it away anyways.
Dale Curtis4841c712018-12-13 18:14:052494 if (IsStreaming() && preload_ > MultibufferDataSource::METADATA &&
2495 mb_data_source_) {
2496 mb_data_source_->SetPreload(MultibufferDataSource::METADATA);
hubbee2cc88c092017-07-14 23:10:412497 }
2498
[email protected]ef8394c2013-08-21 20:26:302499 StartPipeline();
[email protected]a9415292012-01-19 19:55:202500}
2501
[email protected]122f40252012-06-12 05:01:562502void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
hubbeb2d3efd2017-05-05 23:26:382503 DVLOG(1) << __func__ << "(" << is_downloading << ")";
Blink Reformat1c4d759e2017-04-09 16:34:542504 if (!is_downloading && network_state_ == WebMediaPlayer::kNetworkStateLoading)
2505 SetNetworkState(WebMediaPlayer::kNetworkStateIdle);
2506 else if (is_downloading &&
2507 network_state_ == WebMediaPlayer::kNetworkStateIdle)
2508 SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
hubbeb2d3efd2017-05-05 23:26:382509 if (ready_state_ == ReadyState::kReadyStateHaveFutureData && !is_downloading)
2510 SetReadyState(WebMediaPlayer::kReadyStateHaveEnoughData);
[email protected]122f40252012-06-12 05:01:562511}
2512
liberato2ff93ad2017-05-17 07:28:242513void WebMediaPlayerImpl::OnOverlayRoutingToken(
2514 const base::UnguessableToken& token) {
2515 DCHECK(overlay_mode_ == OverlayMode::kUseAndroidOverlay);
liberatofe8f9692017-06-08 19:17:362516 // TODO(liberato): |token| should already be a RoutingToken.
2517 overlay_routing_token_is_pending_ = false;
2518 overlay_routing_token_ = OverlayInfo::RoutingToken(token);
liberato2ff93ad2017-05-17 07:28:242519 MaybeSendOverlayInfoToDecoder();
2520}
2521
2522void WebMediaPlayerImpl::OnOverlayInfoRequested(
dalecurtis4b632fce22016-11-10 00:52:172523 bool decoder_requires_restart_for_overlay,
liberato2ff93ad2017-05-17 07:28:242524 const ProvideOverlayInfoCB& provide_overlay_info_cb) {
watkdee516f2016-02-18 02:22:192525 DCHECK(main_task_runner_->BelongsToCurrentThread());
watkdee516f2016-02-18 02:22:192526
Chris Watkins557f84d2017-09-16 02:31:462527 // If we get a non-null cb, a decoder is initializing and requires overlay
2528 // info. If we get a null cb, a previously initialized decoder is
2529 // unregistering for overlay info updates.
Dale Curtise25163812018-09-21 22:13:392530 if (!provide_overlay_info_cb) {
tsunghungee562e92016-07-20 18:03:312531 decoder_requires_restart_for_overlay_ = false;
liberato2ff93ad2017-05-17 07:28:242532 provide_overlay_info_cb_.Reset();
watkdee516f2016-02-18 02:22:192533 return;
2534 }
2535
dalecurtis4b632fce22016-11-10 00:52:172536 // If |decoder_requires_restart_for_overlay| is true, we must restart the
2537 // pipeline for fullscreen transitions. The decoder is unable to switch
2538 // surfaces otherwise. If false, we simply need to tell the decoder about the
2539 // new surface and it will handle things seamlessly.
Chris Watkins557f84d2017-09-16 02:31:462540 // For encrypted video we pretend that the decoder doesn't require a restart
2541 // because it needs an overlay all the time anyway. We'll switch into
2542 // |always_enable_overlays_| mode below.
2543 decoder_requires_restart_for_overlay_ =
2544 (overlay_mode_ == OverlayMode::kUseAndroidOverlay && is_encrypted_)
2545 ? false
2546 : decoder_requires_restart_for_overlay;
liberato2ff93ad2017-05-17 07:28:242547 provide_overlay_info_cb_ = provide_overlay_info_cb;
dalecurtis4b632fce22016-11-10 00:52:172548
Chris Watkins557f84d2017-09-16 02:31:462549 // If the decoder doesn't require restarts for surface transitions, and we're
2550 // using AndroidOverlay mode, we can always enable the overlay and the decoder
2551 // can choose whether or not to use it. Otherwise, we'll restart the decoder
2552 // and enable the overlay on fullscreen transitions.
[email protected]77568482017-06-21 21:16:522553 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay &&
Chris Watkins557f84d2017-09-16 02:31:462554 !decoder_requires_restart_for_overlay_) {
[email protected]c8d574722017-08-30 20:53:432555 always_enable_overlays_ = true;
[email protected]77568482017-06-21 21:16:522556 if (!overlay_enabled_)
2557 EnableOverlay();
2558 }
2559
Chris Watkins557f84d2017-09-16 02:31:462560 // Send the overlay info if we already have it. If not, it will be sent later.
liberato2ff93ad2017-05-17 07:28:242561 MaybeSendOverlayInfoToDecoder();
2562}
2563
2564void WebMediaPlayerImpl::MaybeSendOverlayInfoToDecoder() {
2565 // If the decoder didn't request overlay info, then don't send it.
2566 if (!provide_overlay_info_cb_)
dalecurtis4b632fce22016-11-10 00:52:172567 return;
2568
liberato2ff93ad2017-05-17 07:28:242569 // We should send the overlay info as long as we know it. This includes the
2570 // case where |!overlay_enabled_|, since we want to tell the decoder to avoid
2571 // using overlays. Assuming that the decoder has requested info, the only
2572 // case in which we don't want to send something is if we've requested the
2573 // info but not received it yet. Then, we should wait until we do.
liberatofe8f9692017-06-08 19:17:362574 //
2575 // Initialization requires this; AVDA should start with enough info to make an
2576 // overlay, so that (pre-M) the initial codec is created with the right output
2577 // surface; it can't switch later.
[email protected]f7df5b342018-07-13 20:22:132578 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberatofe8f9692017-06-08 19:17:362579 if (overlay_routing_token_is_pending_)
liberato2ff93ad2017-05-17 07:28:242580 return;
liberatofe8f9692017-06-08 19:17:362581
2582 overlay_info_.routing_token = overlay_routing_token_;
liberato2ff93ad2017-05-17 07:28:242583 }
2584
liberato2ff93ad2017-05-17 07:28:242585 // If restart is required, the callback is one-shot only.
2586 if (decoder_requires_restart_for_overlay_) {
Dale Curtise25163812018-09-21 22:13:392587 std::move(provide_overlay_info_cb_).Run(overlay_info_);
liberato2ff93ad2017-05-17 07:28:242588 } else {
liberatofe8f9692017-06-08 19:17:362589 provide_overlay_info_cb_.Run(overlay_info_);
liberato2ff93ad2017-05-17 07:28:242590 }
watkdee516f2016-02-18 02:22:192591}
2592
Xiaohan Wangcd4df0a2019-12-04 20:59:242593std::unique_ptr<Renderer> WebMediaPlayerImpl::CreateRenderer(
2594 base::Optional<RendererFactorySelector::FactoryType> factory_type) {
dcheng37b415b92017-01-27 20:17:432595 DCHECK(main_task_runner_->BelongsToCurrentThread());
2596
[email protected]c8d574722017-08-30 20:53:432597 // Make sure that overlays are enabled if they're always allowed.
2598 if (always_enable_overlays_)
tsunghungee562e92016-07-20 18:03:312599 EnableOverlay();
2600
liberato2ff93ad2017-05-17 07:28:242601 RequestOverlayInfoCB request_overlay_info_cb;
watkdee516f2016-02-18 02:22:192602#if defined(OS_ANDROID)
liberato2ff93ad2017-05-17 07:28:242603 request_overlay_info_cb = BindToCurrentLoop(
Antonio Gomes142f32a2019-05-15 23:32:562604 base::Bind(&WebMediaPlayerImpl::OnOverlayInfoRequested, weak_this_));
watkdee516f2016-02-18 02:22:192605#endif
Xiaohan Wangcd4df0a2019-12-04 20:59:242606
2607 if (factory_type) {
2608 DVLOG(1) << __func__ << ": factory_type=" << factory_type.value();
2609 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