blob: 657890d05b4ddf719002bea287612641ab9e5d56 [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 Meyera698afe2019-11-06 20:58:03262void SetSanitizedStringProperty(MediaLog* log,
263 std::string key,
264 blink::WebString value) {
265 std::string converted = value.Utf8();
266 if (converted.empty() || !base::IsStringUTF8(converted)) {
267 converted = "<invalid property>";
268 }
269 log->SetStringProperty(key, converted);
270}
271
[email protected]8931c41a2009-07-07 17:31:49272} // namespace
273
[email protected]6683e1b2014-04-10 01:45:38274class BufferedDataSourceHostImpl;
275
Takashi Toyoshima2e01e692018-11-16 03:23:27276STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeUnspecified,
danakj365175c2016-02-06 00:37:37277 UrlData::CORS_UNSPECIFIED);
Takashi Toyoshima2e01e692018-11-16 03:23:27278STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeAnonymous, UrlData::CORS_ANONYMOUS);
279STATIC_ASSERT_ENUM(WebMediaPlayer::kCorsModeUseCredentials,
danakj365175c2016-02-06 00:37:37280 UrlData::CORS_USE_CREDENTIALS);
[email protected]a5a01102012-06-06 17:01:24281
[email protected]5b5bb9d2010-10-22 19:57:36282WebMediaPlayerImpl::WebMediaPlayerImpl(
[email protected]35b2a972014-04-04 15:50:22283 blink::WebLocalFrame* frame,
[email protected]180ef242013-11-07 06:50:46284 blink::WebMediaPlayerClient* client,
srirama.m26f864d02015-07-14 05:21:46285 blink::WebMediaPlayerEncryptedMediaClient* encrypted_client,
Antonio Gomes423df612019-07-11 12:40:07286 blink::WebMediaPlayerDelegate* delegate,
tguilbert70d2a00a2017-04-25 00:30:44287 std::unique_ptr<RendererFactorySelector> renderer_factory_selector,
Alok Priyadarshi7166d4d2017-07-29 04:04:25288 UrlIndex* url_index,
CJ DiMegliod7ac6772017-11-10 00:19:06289 std::unique_ptr<VideoFrameCompositor> compositor,
dalecurtis9cddc0b2017-04-19 21:23:38290 std::unique_ptr<WebMediaPlayerParams> params)
[email protected]f6af7592014-02-28 10:09:11291 : frame_(frame),
Alexander Timin310368112017-09-13 10:01:44292 main_task_runner_(
293 frame->GetTaskRunner(blink::TaskType::kMediaElementEvent)),
dalecurtis9cddc0b2017-04-19 21:23:38294 media_task_runner_(params->media_task_runner()),
295 worker_task_runner_(params->worker_task_runner()),
296 media_log_(params->take_media_log()),
[email protected]5badb082010-06-11 17:40:15297 client_(client),
srirama.m26f864d02015-07-14 05:21:46298 encrypted_client_(encrypted_client),
[email protected]baff4512011-10-19 18:21:07299 delegate_(delegate),
dalecurtis9cddc0b2017-04-19 21:23:38300 defer_load_cb_(params->defer_load_cb()),
dalecurtis9cddc0b2017-04-19 21:23:38301 adjust_allocated_memory_cb_(params->adjust_allocated_memory_cb()),
tzik2c963b872017-12-07 06:57:24302 tick_clock_(base::DefaultTickClock::GetInstance()),
hubbe5f0ad43b2015-12-14 20:57:26303 url_index_(url_index),
CJ DiMeglioc60a5cf2017-09-27 20:08:41304 context_provider_(params->context_provider()),
CJ DiMegliod7ac6772017-11-10 00:19:06305 vfc_task_runner_(params->video_frame_compositor_task_runner()),
306 compositor_(std::move(compositor)),
tguilbert70d2a00a2017-04-25 00:30:44307 renderer_factory_selector_(std::move(renderer_factory_selector)),
dalecurtis9cddc0b2017-04-19 21:23:38308 observer_(params->media_observer()),
servolkf94b4602017-01-31 16:44:27309 enable_instant_source_buffer_gc_(
dalecurtis9cddc0b2017-04-19 21:23:38310 params->enable_instant_source_buffer_gc()),
shaktisahu24189c12017-03-11 17:42:55311 embedded_media_experience_enabled_(
liberato2ff93ad2017-05-17 07:28:24312 params->embedded_media_experience_enabled()),
[email protected]69db58f2018-09-26 20:27:56313 surface_layer_mode_(params->use_surface_layer_for_video()),
CJ DiMeglio96c18b692018-07-04 03:39:06314 create_bridge_callback_(params->create_bridge_callback()),
liberato2ff93ad2017-05-17 07:28:24315 request_routing_token_cb_(params->request_routing_token_cb()),
Dale Curtis1adbe6a2017-08-02 02:09:13316 overlay_routing_token_(OverlayInfo::RoutingToken()),
Sergey Volk8b09c2c52018-12-12 23:20:40317 media_metrics_provider_(params->take_metrics_provider()),
318 is_background_suspend_enabled_(params->IsBackgroundSuspendEnabled()),
Junbo Kefba620b2019-01-16 02:54:36319 is_background_video_playback_enabled_(
320 params->IsBackgroundVideoPlaybackEnabled()),
Sergey Volk8b09c2c52018-12-12 23:20:40321 is_background_video_track_optimization_supported_(
Dan Sanders6edfd782019-08-13 00:13:18322 params->IsBackgroundVideoTrackOptimizationSupported()),
323 reported_renderer_type_(RendererFactorySelector::DEFAULT),
324 simple_watch_timer_(
325 base::BindRepeating(&WebMediaPlayerImpl::OnSimpleWatchTimerTick,
326 base::Unretained(this)),
327 base::BindRepeating(&WebMediaPlayerImpl::GetCurrentTimeInternal,
[email protected]91fd3162019-09-05 23:51:32328 base::Unretained(this))),
329 will_play_helper_(nullptr) {
xhwang51139732017-02-24 19:36:08330 DVLOG(1) << __func__;
Dale Curtise25163812018-09-21 22:13:39331 DCHECK(adjust_allocated_memory_cb_);
tguilbert70d2a00a2017-04-25 00:30:44332 DCHECK(renderer_factory_selector_);
servolkef1e5ef2016-03-25 04:55:26333 DCHECK(client_);
tguilbert1bb1c782017-01-23 21:15:11334 DCHECK(delegate_);
dalecurtis83266c72015-10-29 18:43:20335
Antonio Gomes142f32a2019-05-15 23:32:56336 weak_this_ = weak_factory_.GetWeakPtr();
337
Antonio Gomes81b56552019-05-15 22:15:28338 pipeline_controller_ = std::make_unique<PipelineController>(
Xiaohan Wang73b433f2019-11-05 20:13:01339 std::make_unique<PipelineImpl>(
340 media_task_runner_, main_task_runner_,
341 BindToCurrentLoop(base::BindRepeating(
342 &WebMediaPlayerImpl::CreateRenderer, weak_this_)),
343 media_log_.get()),
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
371 SetSanitizedStringProperty(media_log_.get(), "frame_url",
372 frame_->GetDocument().Url().GetString());
373
374 SetSanitizedStringProperty(media_log_.get(), "frame_title",
375 frame_->GetDocument().Title());
[email protected]4e6be3f2009-05-07 02:24:44376
[email protected]52b0b212018-10-10 05:25:28377 // To make manual testing easier, include |surface_layer_mode_| in the log.
378 // TODO(liberato): Move this into media_factory.cc, so that it can be shared
379 // with the MediaStream startup.
380 const char* surface_layer_mode_name = "(unset)";
381 switch (surface_layer_mode_) {
CJ DiMeglio89240472018-10-18 18:21:10382 case SurfaceLayerMode::kAlways:
[email protected]52b0b212018-10-10 05:25:28383 surface_layer_mode_name = "kAlways";
384 break;
CJ DiMeglio89240472018-10-18 18:21:10385 case SurfaceLayerMode::kOnDemand:
[email protected]52b0b212018-10-10 05:25:28386 surface_layer_mode_name = "kOnDemand";
387 break;
CJ DiMeglio89240472018-10-18 18:21:10388 case SurfaceLayerMode::kNever:
[email protected]52b0b212018-10-10 05:25:28389 surface_layer_mode_name = "kNever";
390 break;
391 }
392 media_log_->SetStringProperty("surface_layer_mode", surface_layer_mode_name);
393
dalecurtis9cddc0b2017-04-19 21:23:38394 if (params->initial_cdm())
Chris Cunninghamd4a00192019-03-21 20:02:49395 SetCdmInternal(params->initial_cdm());
xhwang0ad11e512014-11-25 23:43:09396
Xiaohan Wangf63505d2017-10-21 08:00:53397 // Report a false "EncrytpedEvent" here as a baseline.
398 RecordEncryptedEvent(false);
399
xhwangf94a634d2014-10-22 22:07:27400 // TODO(xhwang): When we use an external Renderer, many methods won't work,
xhwang6fa356202014-12-11 00:44:12401 // e.g. GetCurrentFrameFromCompositor(). See http://crbug.com/434861
Antonio Gomes3a858b52019-05-31 02:47:52402 audio_source_provider_ = new blink::WebAudioSourceProviderImpl(
dalecurtis9cddc0b2017-04-19 21:23:38403 params->audio_renderer_sink(), media_log_.get());
xjz4e5d4bf32017-02-15 21:26:35404
405 if (observer_)
406 observer_->SetClient(this);
Hajime Hoshi8bb37dc2017-12-19 09:35:10407
408 memory_usage_reporting_timer_.SetTaskRunner(
Hajime Hoshib5a26ee2018-05-14 12:47:51409 frame_->GetTaskRunner(blink::TaskType::kInternalMedia));
John Delaney6c8ecc1b2018-10-21 19:07:29410
Thomas Guilbert901808982019-07-03 20:38:18411#if defined(OS_ANDROID)
Thomas Guilbertf6d0702e2019-09-12 23:40:14412 renderer_factory_selector_->SetRemotePlayStateChangeCB(
413 BindToCurrentLoop(base::BindRepeating(
414 &WebMediaPlayerImpl::OnRemotePlayStateChange, weak_this_)));
Thomas Guilbert901808982019-07-03 20:38:18415#endif // defined (OS_ANDROID)
[email protected]ec9212f2008-12-18 21:40:36416}
417
[email protected]4e6be3f2009-05-07 02:24:44418WebMediaPlayerImpl::~WebMediaPlayerImpl() {
xhwang51139732017-02-24 19:36:08419 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43420 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53421
xhwang51139732017-02-24 19:36:08422 if (set_cdm_result_) {
Chris Cunninghamd4a00192019-03-21 20:02:49423 DVLOG(2)
424 << "Resolve pending SetCdmInternal() when media player is destroyed.";
Blink Reformat1c4d759e2017-04-09 16:34:54425 set_cdm_result_->Complete();
xhwang51139732017-02-24 19:36:08426 set_cdm_result_.reset();
427 }
428
alokp1116967f2016-06-11 17:30:56429 suppress_destruction_errors_ = true;
tguilbert1bb1c782017-01-23 21:15:11430
431 delegate_->PlayerGone(delegate_id_);
432 delegate_->RemoveObserver(delegate_id_);
[email protected]baff4512011-10-19 18:21:07433
dalecurtis04bdb582016-08-17 22:15:23434 // Finalize any watch time metrics before destroying the pipeline.
435 watch_time_reporter_.reset();
436
tguilbert350936ff2017-02-24 05:39:27437 // The underlying Pipeline must be stopped before it is destroyed.
Dale Curtisf273f8f2018-12-13 23:40:33438 //
439 // Note: This destruction happens synchronously on the media thread and
440 // |demuxer_|, |data_source_|, |compositor_|, and |media_log_| must outlive
441 // this process. They will be destructed by the DestructionHelper below
442 // after trampolining through the media thread.
Antonio Gomes81b56552019-05-15 22:15:28443 pipeline_controller_->Stop();
[email protected]f6af7592014-02-28 10:09:11444
dalecurtis83266c72015-10-29 18:43:20445 if (last_reported_memory_usage_)
446 adjust_allocated_memory_cb_.Run(-last_reported_memory_usage_);
447
dalecurtise1edb312016-06-22 02:33:21448 // Destruct compositor resources in the proper order.
danakj8d204a42018-05-18 18:05:35449 client_->SetCcLayer(nullptr);
CJ DiMeglio2302d202017-08-31 08:38:04450
Xiangjun Zhang5e20cba42018-01-10 19:54:56451 client_->MediaRemotingStopped(
Gyuyoung Kimf99f5f32019-09-26 03:45:15452 blink::WebMediaPlayerClient::kMediaRemotingStopNoText);
Xiangjun Zhang87299142017-09-13 20:35:03453
Dale Curtisf273f8f2018-12-13 23:40:33454 if (!surface_layer_for_video_enabled_ && video_layer_)
danakj25f030112018-05-11 18:26:54455 video_layer_->StopUsingProvider();
Matt Wolenetz95af6362018-01-04 20:23:42456
Dan Sanders6edfd782019-08-13 00:13:18457 simple_watch_timer_.Stop();
Ted Meyer257b682a2019-11-01 20:50:51458 media_log_->OnWebMediaPlayerDestroyed();
[email protected]ec9212f2008-12-18 21:40:36459
Dale Curtisf273f8f2018-12-13 23:40:33460 if (data_source_)
461 data_source_->Stop();
462
463 // Disconnect from the surface layer. We still preserve the |bridge_| until
464 // after pipeline shutdown to ensure any pending frames are painted for tests.
465 if (bridge_)
466 bridge_->ClearObserver();
467
Dale Curtisc96a3542018-12-17 22:15:23468 // Disconnect from the MediaObserver implementation since it's lifetime is
469 // tied to the RendererFactorySelector which can't be destroyed until after
470 // the Pipeline stops.
471 //
472 // Note: We can't use a WeakPtr with the RendererFactory because its methods
473 // are called on the media thread and this destruction takes place on the
474 // renderer thread.
475 if (observer_)
476 observer_->SetClient(nullptr);
477
[email protected]91fd3162019-09-05 23:51:32478 // If we're in the middle of an observation, then finish it.
479 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(false));
480
Dale Curtisf273f8f2018-12-13 23:40:33481 // Handle destruction of things that need to be destructed after the pipeline
482 // completes stopping on the media thread.
483 media_task_runner_->PostTask(
Matt Wolenetz95af6362018-01-04 20:23:42484 FROM_HERE,
Dale Curtisf273f8f2018-12-13 23:40:33485 base::BindOnce(&DestructionHelper, std::move(main_task_runner_),
486 std::move(vfc_task_runner_), std::move(demuxer_),
487 std::move(data_source_), std::move(compositor_),
488 std::move(cdm_context_ref_),
489 std::move(pending_cdm_context_ref_), std::move(media_log_),
490 std::move(renderer_factory_selector_), std::move(bridge_),
491 !!chunk_demuxer_));
Matt Wolenetz95af6362018-01-04 20:23:42492}
493
chcunningham707b821e2018-05-29 08:42:19494WebMediaPlayer::LoadTiming WebMediaPlayerImpl::Load(
495 LoadType load_type,
496 const blink::WebMediaPlayerSource& source,
Takashi Toyoshima2e01e692018-11-16 03:23:27497 CorsMode cors_mode) {
guidou9bfe4e2f2016-04-09 08:31:19498 // Only URL or MSE blob URL is supported.
Blink Reformat1c4d759e2017-04-09 16:34:54499 DCHECK(source.IsURL());
500 blink::WebURL url = source.GetAsURL();
Xiaohan Wang81fd0022017-07-11 17:45:24501 DVLOG(1) << __func__ << "(" << load_type << ", " << GURL(url) << ", "
502 << cors_mode << ")";
chcunningham707b821e2018-05-29 08:42:19503
504 bool is_deferred = false;
505
Dale Curtise25163812018-09-21 22:13:39506 if (defer_load_cb_) {
chcunningham707b821e2018-05-29 08:42:19507 is_deferred = defer_load_cb_.Run(base::BindOnce(
Antonio Gomes142f32a2019-05-15 23:32:56508 &WebMediaPlayerImpl::DoLoad, weak_this_, load_type, url, cors_mode));
chcunningham707b821e2018-05-29 08:42:19509 } else {
510 DoLoad(load_type, url, cors_mode);
[email protected]d726eddc2013-07-02 22:25:55511 }
chcunningham707b821e2018-05-29 08:42:19512
513 return is_deferred ? LoadTiming::kDeferred : LoadTiming::kImmediate;
[email protected]62e5e682013-03-07 23:53:24514}
515
CJ DiMeglio013d4c472017-11-21 03:27:30516void WebMediaPlayerImpl::OnWebLayerUpdated() {}
517
danakj6a062b112018-05-17 16:25:45518void WebMediaPlayerImpl::RegisterContentsLayer(cc::Layer* layer) {
CJ DiMeglio2302d202017-08-31 08:38:04519 DCHECK(bridge_);
CJ DiMeglioa2b13fbc2018-06-27 00:50:59520 bridge_->SetContentsOpaque(opaque_);
danakj8d204a42018-05-18 18:05:35521 client_->SetCcLayer(layer);
CJ DiMeglio013d4c472017-11-21 03:27:30522}
523
danakj6a062b112018-05-17 16:25:45524void WebMediaPlayerImpl::UnregisterContentsLayer(cc::Layer* layer) {
525 // |client_| will unregister its cc::Layer if given a nullptr.
danakj8d204a42018-05-18 18:05:35526 client_->SetCcLayer(nullptr);
CJ DiMeglio2302d202017-08-31 08:38:04527}
528
Jennifer Apaciblec45fd052018-02-25 12:04:55529void WebMediaPlayerImpl::OnSurfaceIdUpdated(viz::SurfaceId surface_id) {
Jennifer Apaciblec45fd052018-02-25 12:04:55530 // TODO(726619): Handle the behavior when Picture-in-Picture mode is
531 // disabled.
Jennifer Apacible2b1dc5eb2018-04-27 16:23:28532 // The viz::SurfaceId may be updated when the video begins playback or when
533 // the size of the video changes.
Mounir Lamouri99ba5a62019-02-12 01:27:47534 if (client_)
535 client_->OnPictureInPictureStateChange();
Jennifer Apaciblec45fd052018-02-25 12:04:55536}
537
tsunghungee562e92016-07-20 18:03:31538void WebMediaPlayerImpl::EnableOverlay() {
539 overlay_enabled_ = true;
[email protected]f7df5b342018-07-13 20:22:13540 if (request_routing_token_cb_ &&
541 overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberatofe8f9692017-06-08 19:17:36542 overlay_routing_token_is_pending_ = true;
liberato2ff93ad2017-05-17 07:28:24543 token_available_cb_.Reset(
Antonio Gomes142f32a2019-05-15 23:32:56544 base::Bind(&WebMediaPlayerImpl::OnOverlayRoutingToken, weak_this_));
liberato2ff93ad2017-05-17 07:28:24545 request_routing_token_cb_.Run(token_available_cb_.callback());
watkf835a792016-06-24 23:24:40546 }
tsunghungee562e92016-07-20 18:03:31547
liberato2ff93ad2017-05-17 07:28:24548 // We have requested (and maybe already have) overlay information. If the
549 // restarted decoder requests overlay information, then we'll defer providing
550 // it if it hasn't arrived yet. Otherwise, this would be a race, since we
551 // don't know if the request for overlay info or restart will complete first.
tsunghungee562e92016-07-20 18:03:31552 if (decoder_requires_restart_for_overlay_)
watkdee516f2016-02-18 02:22:19553 ScheduleRestart();
554}
555
tsunghungee562e92016-07-20 18:03:31556void WebMediaPlayerImpl::DisableOverlay() {
557 overlay_enabled_ = false;
Jinsong Fan982342112019-11-07 23:45:45558 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberato2ff93ad2017-05-17 07:28:24559 token_available_cb_.Cancel();
liberatofe8f9692017-06-08 19:17:36560 overlay_routing_token_is_pending_ = false;
561 overlay_routing_token_ = OverlayInfo::RoutingToken();
liberato2ff93ad2017-05-17 07:28:24562 }
tsunghungee562e92016-07-20 18:03:31563
564 if (decoder_requires_restart_for_overlay_)
watkdee516f2016-02-18 02:22:19565 ScheduleRestart();
liberato2ff93ad2017-05-17 07:28:24566 else
567 MaybeSendOverlayInfoToDecoder();
watkdee516f2016-02-18 02:22:19568}
569
Blink Reformat1c4d759e2017-04-09 16:34:54570void WebMediaPlayerImpl::EnteredFullscreen() {
liberatofe8f9692017-06-08 19:17:36571 overlay_info_.is_fullscreen = true;
572
[email protected]c8d574722017-08-30 20:53:43573 // |always_enable_overlays_| implies that we're already in overlay mode, so
574 // take no action here. Otherwise, switch to an overlay if it's allowed and
575 // if it will display properly.
576 if (!always_enable_overlays_ && overlay_mode_ != OverlayMode::kNoOverlays &&
liberato2fd111be2017-01-04 00:25:06577 DoesOverlaySupportMetadata()) {
tsunghungee562e92016-07-20 18:03:31578 EnableOverlay();
liberato2fd111be2017-01-04 00:25:06579 }
liberato2ff93ad2017-05-17 07:28:24580
liberatofe8f9692017-06-08 19:17:36581 // We send this only if we can send multiple calls. Otherwise, either (a)
582 // we already sent it and we don't have a callback anyway (we reset it when
583 // it's called in restart mode), or (b) we'll send this later when the surface
584 // actually arrives. GVD assumes that the first overlay info will have the
585 // routing information. Note that we set |is_fullscreen_| earlier, so that
586 // if EnableOverlay() can include fullscreen info in case it sends the overlay
587 // info before returning.
588 if (!decoder_requires_restart_for_overlay_)
589 MaybeSendOverlayInfoToDecoder();
tsunghungee562e92016-07-20 18:03:31590}
591
Blink Reformat1c4d759e2017-04-09 16:34:54592void WebMediaPlayerImpl::ExitedFullscreen() {
liberatofe8f9692017-06-08 19:17:36593 overlay_info_.is_fullscreen = false;
594
[email protected]c8d574722017-08-30 20:53:43595 // If we're in overlay mode, then exit it unless we're supposed to allow
596 // overlays all the time.
597 if (!always_enable_overlays_ && overlay_enabled_)
tsunghungee562e92016-07-20 18:03:31598 DisableOverlay();
liberato2ff93ad2017-05-17 07:28:24599
liberatofe8f9692017-06-08 19:17:36600 // See EnteredFullscreen for why we do this.
601 if (!decoder_requires_restart_for_overlay_)
602 MaybeSendOverlayInfoToDecoder();
tsunghungee562e92016-07-20 18:03:31603}
604
Chisoon Jeong81080c922019-09-03 23:40:18605void WebMediaPlayerImpl::BecameDominantVisibleContent(bool is_dominant) {
xjzcdbbe732016-12-03 20:47:42606 if (observer_)
Chisoon Jeong81080c922019-09-03 23:40:18607 observer_->OnBecameDominantVisibleContent(is_dominant);
xjzcdbbe732016-12-03 20:47:42608}
609
Blink Reformat1c4d759e2017-04-09 16:34:54610void WebMediaPlayerImpl::SetIsEffectivelyFullscreen(
François Beaufortad6c5232018-02-26 11:00:44611 blink::WebFullscreenVideoStatus fullscreen_video_status) {
612 delegate_->SetIsEffectivelyFullscreen(delegate_id_, fullscreen_video_status);
zqzhangabc08242017-03-02 16:07:14613}
614
Mounir Lamouri41a79c62017-06-06 12:53:16615void WebMediaPlayerImpl::OnHasNativeControlsChanged(bool has_native_controls) {
616 if (!watch_time_reporter_)
617 return;
618
619 if (has_native_controls)
620 watch_time_reporter_->OnNativeControlsEnabled();
621 else
622 watch_time_reporter_->OnNativeControlsDisabled();
623}
624
Mounir Lamourif9af74e72017-06-19 19:31:45625void WebMediaPlayerImpl::OnDisplayTypeChanged(
626 WebMediaPlayer::DisplayType display_type) {
Mounir Lamouri0484f40a2018-07-25 03:03:26627 if (surface_layer_for_video_enabled_) {
628 vfc_task_runner_->PostTask(
629 FROM_HERE,
630 base::BindOnce(
631 &VideoFrameCompositor::SetForceSubmit,
632 base::Unretained(compositor_.get()),
633 display_type == WebMediaPlayer::DisplayType::kPictureInPicture));
634 }
635
Mounir Lamourif9af74e72017-06-19 19:31:45636 if (!watch_time_reporter_)
637 return;
638
639 switch (display_type) {
640 case WebMediaPlayer::DisplayType::kInline:
641 watch_time_reporter_->OnDisplayTypeInline();
642 break;
643 case WebMediaPlayer::DisplayType::kFullscreen:
644 watch_time_reporter_->OnDisplayTypeFullscreen();
645 break;
646 case WebMediaPlayer::DisplayType::kPictureInPicture:
647 watch_time_reporter_->OnDisplayTypePictureInPicture();
François Beaufort3f62f382019-01-18 15:05:17648
649 // Resumes playback if it was paused when hidden.
650 if (paused_when_hidden_) {
651 paused_when_hidden_ = false;
652 OnPlay();
653 }
Mounir Lamourif9af74e72017-06-19 19:31:45654 break;
655 }
656}
657
[email protected]ef8394c2013-08-21 20:26:30658void WebMediaPlayerImpl::DoLoad(LoadType load_type,
[email protected]180ef242013-11-07 06:50:46659 const blink::WebURL& url,
Takashi Toyoshima2e01e692018-11-16 03:23:27660 CorsMode cors_mode) {
John Chen5b164a02017-11-01 00:36:09661 TRACE_EVENT1("media", "WebMediaPlayerImpl::DoLoad", "id", media_log_->id());
pkastingf5279482016-07-27 02:18:20662 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43663 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d726eddc2013-07-02 22:25:55664
[email protected]91fd3162019-09-05 23:51:32665 // Start a new observation. If there was one before, then we didn't play it.
666 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(false));
667 // For now, send in an empty set of features. We should fill some in here,
668 // and / or ask blink (via |client_|) for features from the DOM.
669 learning::FeatureDictionary dict;
670 will_play_helper_.BeginObservation(dict);
671
Thomas Guilbert55b48d92019-03-25 23:16:54672#if defined(OS_ANDROID)
673 // Only allow credentials if the crossorigin attribute is unspecified
674 // (kCorsModeUnspecified) or "use-credentials" (kCorsModeUseCredentials).
675 // This value is only used by the MediaPlayerRenderer.
676 // See https://crbug.com/936566.
677 //
678 // The credentials mode also has repercussions in WouldTaintOrigin(), but we
679 // access what we need from |mb_data_source_|->cors_mode() directly, instead
680 // of storing it here.
681 allow_media_player_renderer_credentials_ = cors_mode != kCorsModeAnonymous;
682#endif // defined(OS_ANDROID)
683
Dale Curtis4841c712018-12-13 18:14:05684 // Note: |url| may be very large, take care when making copies.
685 loaded_url_ = GURL(url);
686 load_type_ = load_type;
687
688 ReportMetrics(load_type, loaded_url_, *frame_, media_log_.get());
[email protected]62e5e682013-03-07 23:53:24689
Dale Curtis4841c712018-12-13 18:14:05690 // Set subresource URL for crash reporting; will be truncated to 256 bytes.
Robert Sesekc5e91df2017-12-12 21:11:03691 static base::debug::CrashKeyString* subresource_url =
692 base::debug::AllocateCrashKeyString("subresource_url",
693 base::debug::CrashKeySize::Size256);
Dale Curtis4841c712018-12-13 18:14:05694 base::debug::SetCrashKeyString(subresource_url, loaded_url_.spec());
[email protected]ef8394c2013-08-21 20:26:30695
Blink Reformat1c4d759e2017-04-09 16:34:54696 SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
697 SetReadyState(WebMediaPlayer::kReadyStateHaveNothing);
698 media_log_->AddEvent(media_log_->CreateLoadEvent(url.GetString().Utf8()));
Dale Curtis3899090ea2018-01-12 00:10:35699 load_start_time_ = base::TimeTicks::Now();
[email protected]d726eddc2013-07-02 22:25:55700
Antonio Gomesf01cfbd2019-07-12 08:53:11701 media_metrics_provider_->Initialize(
702 load_type == kLoadTypeMediaSource,
703 load_type == kLoadTypeURL ? blink::GetMediaURLScheme(loaded_url_)
704 : mojom::MediaURLScheme::kUnknown);
Dale Curtis74612b72017-12-14 20:56:19705
[email protected]d726eddc2013-07-02 22:25:55706 // Media source pipelines can start immediately.
Blink Reformat1c4d759e2017-04-09 16:34:54707 if (load_type == kLoadTypeMediaSource) {
[email protected]ef8394c2013-08-21 20:26:30708 StartPipeline();
hubbe5f0ad43b2015-12-14 20:57:26709 } else {
Dale Curtis4841c712018-12-13 18:14:05710 // Short circuit the more complex loading path for data:// URLs. Sending
711 // them through the network based loading path just wastes memory and causes
712 // worse performance since reads become asynchronous.
713 if (loaded_url_.SchemeIs(url::kDataScheme)) {
714 std::string mime_type, charset, data;
Dale Curtis44eacb72019-06-10 20:41:28715 if (!net::DataURL::Parse(loaded_url_, &mime_type, &charset, &data) ||
716 data.empty()) {
Dale Curtis4841c712018-12-13 18:14:05717 DataSourceInitialized(false);
718 return;
719 }
720
721 // Replace |loaded_url_| with an empty data:// URL since it may be large.
722 loaded_url_ = GURL("data:,");
723
724 // Mark all the data as buffered.
Antonio Gomes81b56552019-05-15 22:15:28725 buffered_data_source_host_->SetTotalBytes(data.size());
726 buffered_data_source_host_->AddBufferedByteRange(0, data.size());
Dale Curtis4841c712018-12-13 18:14:05727
728 DCHECK(!mb_data_source_);
729 data_source_.reset(new MemoryDataSource(std::move(data)));
730 DataSourceInitialized(true);
731 return;
732 }
733
John Delaneyb933391602018-10-17 21:50:47734 auto url_data =
Takashi Toyoshima2e01e692018-11-16 03:23:27735 url_index_->GetByUrl(url, static_cast<UrlData::CorsMode>(cors_mode));
Dale Curtis4841c712018-12-13 18:14:05736 mb_data_source_ = new MultibufferDataSource(
John Delaneyb933391602018-10-17 21:50:47737 main_task_runner_, std::move(url_data), media_log_.get(),
Antonio Gomes81b56552019-05-15 22:15:28738 buffered_data_source_host_.get(),
Dale Curtis4841c712018-12-13 18:14:05739 base::BindRepeating(&WebMediaPlayerImpl::NotifyDownloading,
Antonio Gomes142f32a2019-05-15 23:32:56740 weak_this_));
Dale Curtis4841c712018-12-13 18:14:05741 data_source_.reset(mb_data_source_);
742 mb_data_source_->SetPreload(preload_);
743 mb_data_source_->SetIsClientAudioElement(client_->IsAudioElement());
744 mb_data_source_->Initialize(
Antonio Gomes142f32a2019-05-15 23:32:56745 base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, weak_this_));
hubbe5f0ad43b2015-12-14 20:57:26746 }
[email protected]62e5e682013-03-07 23:53:24747}
748
Blink Reformat1c4d759e2017-04-09 16:34:54749void WebMediaPlayerImpl::Play() {
pkastingf5279482016-07-27 02:18:20750 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43751 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53752
avayvod65fad272017-02-24 01:00:48753 // User initiated play unlocks background video playback.
Mustaq Ahmede473e4352017-11-04 01:04:25754 if (blink::WebUserGestureIndicator::IsProcessingUserGesture(frame_))
avayvod65fad272017-02-24 01:00:48755 video_locked_when_paused_when_hidden_ = false;
756
sandersd35d2c3f2017-01-14 02:04:42757 // TODO(sandersd): Do we want to reset the idle timer here?
tguilbert1bb1c782017-01-23 21:15:11758 delegate_->SetIdle(delegate_id_, false);
[email protected]49480902009-07-14 20:23:43759 paused_ = false;
Antonio Gomes81b56552019-05-15 22:15:28760 pipeline_controller_->SetPlaybackRate(playback_rate_);
dalecurtis4619cd02016-09-22 21:39:10761 background_pause_timer_.Stop();
sandersd1c0bba02016-03-04 23:14:08762
xjz48a9cb72016-12-20 04:02:49763 if (observer_)
764 observer_->OnPlaying();
765
Mounir Lamouri89c0a1b2018-03-01 15:00:44766 watch_time_reporter_->SetAutoplayInitiated(client_->WasAutoplayInitiated());
767
Dale Curtis051fdf62017-08-05 00:21:13768 // If we're seeking we'll trigger the watch time reporter upon seek completed;
769 // we don't want to start it here since the seek time is unstable. E.g., when
770 // playing content with a positive start time we would have a zero seek time.
771 if (!Seeking()) {
772 DCHECK(watch_time_reporter_);
773 watch_time_reporter_->OnPlaying();
774 }
775
Chris Cunninghamd9df58e2017-08-29 00:04:23776 if (video_decode_stats_reporter_)
777 video_decode_stats_reporter_->OnPlaying();
778
Dan Sanders6edfd782019-08-13 00:13:18779 simple_watch_timer_.Start();
Ted Meyerd5885f82019-07-16 19:19:17780 media_metrics_provider_->SetHasPlayed();
acolwell9e0840d2014-09-06 19:01:32781 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PLAY));
Dale Curtis18ad391b2019-05-30 23:25:09782
783 MaybeUpdateBufferSizesForPlayback();
sandersd50a635e2016-04-04 22:50:09784 UpdatePlayState();
[email protected]91fd3162019-09-05 23:51:32785
786 // Notify the learning task, if needed.
787 will_play_helper_.CompleteObservationIfNeeded(learning::TargetValue(true));
[email protected]ec9212f2008-12-18 21:40:36788}
789
Blink Reformat1c4d759e2017-04-09 16:34:54790void WebMediaPlayerImpl::Pause() {
pkastingf5279482016-07-27 02:18:20791 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:43792 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53793
sandersd50a635e2016-04-04 22:50:09794 // We update the paused state even when casting, since we expect pause() to be
795 // called when casting begins, and when we exit casting we should end up in a
796 // paused state.
[email protected]49480902009-07-14 20:23:43797 paused_ = true;
hubbed5f36882016-01-15 22:40:37798
avayvodeb9098d2017-01-07 00:33:03799 // No longer paused because it was hidden.
800 paused_when_hidden_ = false;
801
avayvod65fad272017-02-24 01:00:48802 // User initiated pause locks background videos.
Mustaq Ahmede473e4352017-11-04 01:04:25803 if (blink::WebUserGestureIndicator::IsProcessingUserGesture(frame_))
avayvod65fad272017-02-24 01:00:48804 video_locked_when_paused_when_hidden_ = true;
805
Antonio Gomes81b56552019-05-15 22:15:28806 pipeline_controller_->SetPlaybackRate(0.0);
Dale Curtis2fc01cc2019-05-20 22:53:52807
808 // For states <= kReadyStateHaveMetadata, we may not have a renderer yet.
809 if (highest_ready_state_ > WebMediaPlayer::kReadyStateHaveMetadata)
810 paused_time_ = pipeline_controller_->GetMediaTime();
[email protected]090f7312011-08-05 23:26:40811
xjz48a9cb72016-12-20 04:02:49812 if (observer_)
813 observer_->OnPaused();
814
dalecurtis04bdb582016-08-17 22:15:23815 DCHECK(watch_time_reporter_);
816 watch_time_reporter_->OnPaused();
Chris Cunninghamd9df58e2017-08-29 00:04:23817
818 if (video_decode_stats_reporter_)
819 video_decode_stats_reporter_->OnPaused();
820
Dan Sanders6edfd782019-08-13 00:13:18821 simple_watch_timer_.Stop();
acolwell9e0840d2014-09-06 19:01:32822 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PAUSE));
avayvod2135a642017-01-13 00:17:14823
Becca Hughes7a85bf22019-07-24 16:16:58824 // Paused changed so we should update media position state.
825 UpdateMediaPositionState();
826
sandersd50a635e2016-04-04 22:50:09827 UpdatePlayState();
[email protected]ec9212f2008-12-18 21:40:36828}
829
Blink Reformat1c4d759e2017-04-09 16:34:54830void WebMediaPlayerImpl::Seek(double seconds) {
pkastingf5279482016-07-27 02:18:20831 DVLOG(1) << __func__ << "(" << seconds << "s)";
acolwellb4034942014-08-28 15:42:43832 DCHECK(main_task_runner_->BelongsToCurrentThread());
Mounir Lamourid864f752019-02-08 22:22:41833 media_log_->AddEvent(
834 media_log_->CreateTimeEvent(MediaLogEvent::SEEK, "seek_target", seconds));
sandersd1c0bba02016-03-04 23:14:08835 DoSeek(base::TimeDelta::FromSecondsD(seconds), true);
836}
837
838void WebMediaPlayerImpl::DoSeek(base::TimeDelta time, bool time_updated) {
839 DCHECK(main_task_runner_->BelongsToCurrentThread());
John Chen5b164a02017-11-01 00:36:09840 TRACE_EVENT2("media", "WebMediaPlayerImpl::DoSeek", "target",
841 time.InSecondsF(), "id", media_log_->id());
[email protected]d43ed912009-02-03 04:52:53842
srirama.mccf671812015-01-08 11:59:13843 ReadyState old_state = ready_state_;
Blink Reformat1c4d759e2017-04-09 16:34:54844 if (ready_state_ > WebMediaPlayer::kReadyStateHaveMetadata)
845 SetReadyState(WebMediaPlayer::kReadyStateHaveMetadata);
[email protected]1bb666802013-11-28 06:12:08846
Dale Curtis051fdf62017-08-05 00:21:13847 // When paused or ended, we know exactly what the current time is and can
848 // elide seeks to it. However, there are two cases that are not elided:
sandersd1c0bba02016-03-04 23:14:08849 // 1) When the pipeline state is not stable.
850 // In this case we just let |pipeline_controller_| decide what to do, as
851 // it has complete information.
852 // 2) For MSE.
853 // Because the buffers may have changed between seeks, MSE seeks are
854 // never elided.
Antonio Gomes81b56552019-05-15 22:15:28855 if (paused_ && pipeline_controller_->IsStable() &&
Dale Curtis051fdf62017-08-05 00:21:13856 (paused_time_ == time ||
857 (ended_ && time == base::TimeDelta::FromSecondsD(Duration()))) &&
sandersd1c0bba02016-03-04 23:14:08858 !chunk_demuxer_) {
859 // If the ready state was high enough before, we can indicate that the seek
860 // completed just by restoring it. Otherwise we will just wait for the real
861 // ready state change to eventually happen.
Blink Reformat1c4d759e2017-04-09 16:34:54862 if (old_state == kReadyStateHaveEnoughData) {
srirama.m8f4a37562014-12-13 08:16:18863 main_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:51864 FROM_HERE, base::BindOnce(&WebMediaPlayerImpl::OnBufferingStateChange,
Chris Cunninghamfc0d67e2019-07-22 20:29:16865 weak_this_, BUFFERING_HAVE_ENOUGH,
866 BUFFERING_CHANGE_REASON_UNKNOWN));
srirama.m36ab2682014-12-11 04:20:01867 }
sandersd1c0bba02016-03-04 23:14:08868 return;
srirama.m36ab2682014-12-11 04:20:01869 }
[email protected]44ff37c02009-10-24 01:03:03870
dalecurtis04bdb582016-08-17 22:15:23871 // Call this before setting |seeking_| so that the current media time can be
872 // recorded by the reporter.
873 if (watch_time_reporter_)
874 watch_time_reporter_->OnSeeking();
875
sandersd35d2c3f2017-01-14 02:04:42876 // TODO(sandersd): Move |seeking_| to PipelineController.
877 // TODO(sandersd): Do we want to reset the idle timer here?
tguilbert1bb1c782017-01-23 21:15:11878 delegate_->SetIdle(delegate_id_, false);
sandersd50a635e2016-04-04 22:50:09879 ended_ = false;
[email protected]b3766a22010-12-22 17:34:13880 seeking_ = true;
sandersd1c0bba02016-03-04 23:14:08881 seek_time_ = time;
882 if (paused_)
883 paused_time_ = time;
Antonio Gomes81b56552019-05-15 22:15:28884 pipeline_controller_->Seek(time, time_updated);
[email protected]b3766a22010-12-22 17:34:13885
sandersd50a635e2016-04-04 22:50:09886 // This needs to be called after Seek() so that if a resume is triggered, it
887 // is to the correct time.
888 UpdatePlayState();
Becca Hughes7a85bf22019-07-24 16:16:58889
890 // The seek time has changed so we should update the media position state.
891 UpdateMediaPositionState();
[email protected]ec9212f2008-12-18 21:40:36892}
893
Blink Reformat1c4d759e2017-04-09 16:34:54894void WebMediaPlayerImpl::SetRate(double rate) {
pkastingf5279482016-07-27 02:18:20895 DVLOG(1) << __func__ << "(" << rate << ")";
acolwellb4034942014-08-28 15:42:43896 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53897
Matt Wolenetz6010f6c2017-10-18 00:44:36898 if (rate != playback_rate_) {
899 LIMITED_MEDIA_LOG(INFO, media_log_.get(), num_playback_rate_logs_,
900 kMaxNumPlaybackRateLogs)
901 << "Effective playback rate changed from " << playback_rate_ << " to "
902 << rate;
903 }
904
[email protected]49480902009-07-14 20:23:43905 playback_rate_ = rate;
Dale Curtis18ad391b2019-05-30 23:25:09906 if (!paused_)
Antonio Gomes81b56552019-05-15 22:15:28907 pipeline_controller_->SetPlaybackRate(rate);
Dale Curtis18ad391b2019-05-30 23:25:09908
909 MaybeUpdateBufferSizesForPlayback();
[email protected]ec9212f2008-12-18 21:40:36910}
911
Blink Reformat1c4d759e2017-04-09 16:34:54912void WebMediaPlayerImpl::SetVolume(double volume) {
pkastingf5279482016-07-27 02:18:20913 DVLOG(1) << __func__ << "(" << volume << ")";
acolwellb4034942014-08-28 15:42:43914 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtisbb3eaac2016-01-27 21:10:25915 volume_ = volume;
Antonio Gomes81b56552019-05-15 22:15:28916 pipeline_controller_->SetVolume(volume_ * volume_multiplier_);
dalecurtis04bdb582016-08-17 22:15:23917 if (watch_time_reporter_)
918 watch_time_reporter_->OnVolumeChange(volume);
Becca Hughes9f6fd4b82017-06-15 10:01:40919 delegate_->DidPlayerMutedStatusChange(delegate_id_, volume == 0.0);
mlamouri910111362016-11-04 11:28:24920
921 // The play state is updated because the player might have left the autoplay
922 // muted state.
923 UpdatePlayState();
[email protected]ec9212f2008-12-18 21:40:36924}
[email protected]f0a51fb52009-03-05 12:46:38925
Mounir Lamouri967f8fb72019-02-13 02:34:22926void WebMediaPlayerImpl::OnRequestPictureInPicture() {
[email protected]69db58f2018-09-26 20:27:56927 if (!surface_layer_for_video_enabled_)
928 ActivateSurfaceLayerForVideo();
929
Mounir Lamourib642a3c2018-07-09 15:45:31930 DCHECK(bridge_);
Mounir Lamouri99ba5a62019-02-12 01:27:47931 DCHECK(bridge_->GetSurfaceId().is_valid());
Jennifer Apacible3f0489102018-01-19 20:10:31932}
933
Daniel Chengc1710b52018-10-24 03:12:28934void WebMediaPlayerImpl::SetSinkId(
935 const blink::WebString& sink_id,
Antonio Gomese7813f32019-04-02 06:11:03936 blink::WebSetSinkIdCompleteCallback completion_callback) {
guidou69223ce2015-06-16 10:36:19937 DCHECK(main_task_runner_->BelongsToCurrentThread());
pkastingf5279482016-07-27 02:18:20938 DVLOG(1) << __func__;
guidouc7babef2015-10-22 00:42:35939
Dale Curtisca1b78f2019-01-15 03:11:26940 OutputDeviceStatusCB callback =
Antonio Gomese7813f32019-04-02 06:11:03941 ConvertToOutputDeviceStatusCB(std::move(completion_callback));
guidouc7babef2015-10-22 00:42:35942 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:51943 FROM_HERE, base::BindOnce(&SetSinkIdOnMediaThread, audio_source_provider_,
Daniel Chengc1710b52018-10-24 03:12:28944 sink_id.Utf8(), std::move(callback)));
guidou69223ce2015-06-16 10:36:19945}
946
Blink Reformat1c4d759e2017-04-09 16:34:54947STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadNone, MultibufferDataSource::NONE);
948STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadMetaData,
dalecurtisb6e052f52016-08-25 00:35:55949 MultibufferDataSource::METADATA);
Blink Reformat1c4d759e2017-04-09 16:34:54950STATIC_ASSERT_ENUM(WebMediaPlayer::kPreloadAuto, MultibufferDataSource::AUTO);
[email protected]23a8b1d82011-04-05 16:28:20951
Blink Reformat1c4d759e2017-04-09 16:34:54952void WebMediaPlayerImpl::SetPreload(WebMediaPlayer::Preload preload) {
pkastingf5279482016-07-27 02:18:20953 DVLOG(1) << __func__ << "(" << preload << ")";
acolwellb4034942014-08-28 15:42:43954 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]4e6be3f2009-05-07 02:24:44955
dalecurtisb6e052f52016-08-25 00:35:55956 preload_ = static_cast<MultibufferDataSource::Preload>(preload);
Dale Curtis4841c712018-12-13 18:14:05957 if (mb_data_source_)
958 mb_data_source_->SetPreload(preload_);
[email protected]4e6be3f2009-05-07 02:24:44959}
960
Blink Reformat1c4d759e2017-04-09 16:34:54961bool WebMediaPlayerImpl::HasVideo() const {
acolwellb4034942014-08-28 15:42:43962 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:53963
[email protected]b8877772014-03-26 20:17:15964 return pipeline_metadata_.has_video;
[email protected]d43ed912009-02-03 04:52:53965}
966
Blink Reformat1c4d759e2017-04-09 16:34:54967bool WebMediaPlayerImpl::HasAudio() const {
acolwellb4034942014-08-28 15:42:43968 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]fc367af2009-08-14 23:06:35969
[email protected]b8877772014-03-26 20:17:15970 return pipeline_metadata_.has_audio;
[email protected]fc367af2009-08-14 23:06:35971}
972
Blink Reformat1c4d759e2017-04-09 16:34:54973void WebMediaPlayerImpl::EnabledAudioTracksChanged(
servolkf25ceed2016-07-01 03:44:38974 const blink::WebVector<blink::WebMediaPlayer::TrackId>& enabledTrackIds) {
975 DCHECK(main_task_runner_->BelongsToCurrentThread());
976
977 std::ostringstream logstr;
978 std::vector<MediaTrack::Id> enabledMediaTrackIds;
979 for (const auto& blinkTrackId : enabledTrackIds) {
Maciej Pawlowskif2556d122019-06-03 08:14:18980 const auto track_id = MediaTrack::Id(blinkTrackId.Utf8().data());
servolkf25ceed2016-07-01 03:44:38981 logstr << track_id << " ";
982 enabledMediaTrackIds.push_back(track_id);
983 }
dalecurtis9cddc0b2017-04-19 21:23:38984 MEDIA_LOG(INFO, media_log_.get())
985 << "Enabled audio tracks: [" << logstr.str() << "]";
Antonio Gomes81b56552019-05-15 22:15:28986 pipeline_controller_->OnEnabledAudioTracksChanged(enabledMediaTrackIds);
servolkf25ceed2016-07-01 03:44:38987}
988
Blink Reformat1c4d759e2017-04-09 16:34:54989void WebMediaPlayerImpl::SelectedVideoTrackChanged(
servolkf25ceed2016-07-01 03:44:38990 blink::WebMediaPlayer::TrackId* selectedTrackId) {
991 DCHECK(main_task_runner_->BelongsToCurrentThread());
992
servolk9bed6602017-02-24 01:20:11993 base::Optional<MediaTrack::Id> selected_video_track_id;
994 if (selectedTrackId && !video_track_disabled_)
Blink Reformat1c4d759e2017-04-09 16:34:54995 selected_video_track_id = MediaTrack::Id(selectedTrackId->Utf8().data());
dalecurtis9cddc0b2017-04-19 21:23:38996 MEDIA_LOG(INFO, media_log_.get())
Maciej Pawlowskif2556d122019-06-03 08:14:18997 << "Selected video track: ["
998 << selected_video_track_id.value_or(MediaTrack::Id()) << "]";
Antonio Gomes81b56552019-05-15 22:15:28999 pipeline_controller_->OnSelectedVideoTrackChanged(selected_video_track_id);
servolkf25ceed2016-07-01 03:44:381000}
1001
Blink Reformat1c4d759e2017-04-09 16:34:541002blink::WebSize WebMediaPlayerImpl::NaturalSize() const {
acolwellb4034942014-08-28 15:42:431003 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:531004
[email protected]b8877772014-03-26 20:17:151005 return blink::WebSize(pipeline_metadata_.natural_size);
[email protected]d43ed912009-02-03 04:52:531006}
1007
Jiajia Qin82acdc02017-07-31 09:55:141008blink::WebSize WebMediaPlayerImpl::VisibleRect() const {
1009 DCHECK(main_task_runner_->BelongsToCurrentThread());
1010 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
1011 if (!video_frame)
1012 return blink::WebSize();
1013
1014 const gfx::Rect& visible_rect = video_frame->visible_rect();
1015 return blink::WebSize(visible_rect.width(), visible_rect.height());
1016}
1017
Blink Reformat1c4d759e2017-04-09 16:34:541018bool WebMediaPlayerImpl::Paused() const {
acolwellb4034942014-08-28 15:42:431019 DCHECK(main_task_runner_->BelongsToCurrentThread());
Antonio Gomes81b56552019-05-15 22:15:281020 return pipeline_controller_->GetPlaybackRate() == 0.0f;
[email protected]d43ed912009-02-03 04:52:531021}
1022
François Beaufort184f6042019-01-25 05:50:051023bool WebMediaPlayerImpl::PausedWhenHidden() const {
1024 return paused_when_hidden_;
1025}
1026
Blink Reformat1c4d759e2017-04-09 16:34:541027bool WebMediaPlayerImpl::Seeking() const {
acolwellb4034942014-08-28 15:42:431028 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]d43ed912009-02-03 04:52:531029
Blink Reformat1c4d759e2017-04-09 16:34:541030 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
[email protected]0acebfa2009-08-21 22:45:401031 return false;
[email protected]67cd5052009-09-10 21:53:221032
[email protected]b3766a22010-12-22 17:34:131033 return seeking_;
[email protected]ec9212f2008-12-18 21:40:361034}
1035
Blink Reformat1c4d759e2017-04-09 16:34:541036double WebMediaPlayerImpl::Duration() const {
acolwellb4034942014-08-28 15:42:431037 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]39bdde32013-04-17 17:44:201038
Blink Reformat1c4d759e2017-04-09 16:34:541039 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
[email protected]39bdde32013-04-17 17:44:201040 return std::numeric_limits<double>::quiet_NaN();
1041
chcunninghamb92d5062017-01-10 21:50:221042 // Use duration from ChunkDemuxer when present. MSE allows users to specify
1043 // duration as a double. This propagates to the rest of the pipeline as a
1044 // TimeDelta with potentially reduced precision (limited to Microseconds).
1045 // ChunkDemuxer returns the full-precision user-specified double. This ensures
1046 // users can "get" the exact duration they "set".
1047 if (chunk_demuxer_)
1048 return chunk_demuxer_->GetDuration();
1049
avayvodcc273dd2017-01-19 19:35:121050 base::TimeDelta pipeline_duration = GetPipelineMediaDuration();
chcunninghamb92d5062017-01-10 21:50:221051 return pipeline_duration == kInfiniteDuration
1052 ? std::numeric_limits<double>::infinity()
1053 : pipeline_duration.InSecondsF();
[email protected]d43ed912009-02-03 04:52:531054}
1055
[email protected]db66d0092014-04-16 07:15:121056double WebMediaPlayerImpl::timelineOffset() const {
acolwellb4034942014-08-28 15:42:431057 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]db66d0092014-04-16 07:15:121058
1059 if (pipeline_metadata_.timeline_offset.is_null())
1060 return std::numeric_limits<double>::quiet_NaN();
1061
1062 return pipeline_metadata_.timeline_offset.ToJsTime();
1063}
1064
Dale Curtis051fdf62017-08-05 00:21:131065base::TimeDelta WebMediaPlayerImpl::GetCurrentTimeInternal() const {
1066 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtis051fdf62017-08-05 00:21:131067
1068 base::TimeDelta current_time;
1069 if (Seeking())
1070 current_time = seek_time_;
Dale Curtis051fdf62017-08-05 00:21:131071 else if (paused_)
1072 current_time = paused_time_;
1073 else
Antonio Gomes81b56552019-05-15 22:15:281074 current_time = pipeline_controller_->GetMediaTime();
Dale Curtis051fdf62017-08-05 00:21:131075
Dale Curtis77d6057b2019-05-03 01:31:561076 // It's possible for |current_time| to be kInfiniteDuration here if the page
1077 // seeks to kInfiniteDuration (2**64 - 1) when Duration() is infinite.
Dale Curtis051fdf62017-08-05 00:21:131078 DCHECK_GE(current_time, base::TimeDelta());
1079 return current_time;
1080}
1081
Blink Reformat1c4d759e2017-04-09 16:34:541082double WebMediaPlayerImpl::CurrentTime() const {
acolwellb4034942014-08-28 15:42:431083 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:541084 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
scherkusd2c745b2014-09-04 05:03:401085
1086 // TODO(scherkus): Replace with an explicit ended signal to HTMLMediaElement,
1087 // see http://crbug.com/409280
Dale Curtis051fdf62017-08-05 00:21:131088 // Note: Duration() may be infinity.
josephlolak918863bc2017-11-15 08:54:331089 return (ended_ && !std::isinf(Duration()))
1090 ? Duration()
1091 : GetCurrentTimeInternal().InSecondsF();
[email protected]d43ed912009-02-03 04:52:531092}
1093
Blink Reformat1c4d759e2017-04-09 16:34:541094WebMediaPlayer::NetworkState WebMediaPlayerImpl::GetNetworkState() const {
acolwellb4034942014-08-28 15:42:431095 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddb1e5a2010-12-13 20:10:451096 return network_state_;
1097}
1098
Blink Reformat1c4d759e2017-04-09 16:34:541099WebMediaPlayer::ReadyState WebMediaPlayerImpl::GetReadyState() const {
acolwellb4034942014-08-28 15:42:431100 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddb1e5a2010-12-13 20:10:451101 return ready_state_;
1102}
1103
CJ DiMeglio89240472018-10-18 18:21:101104blink::WebMediaPlayer::SurfaceLayerMode
1105WebMediaPlayerImpl::GetVideoSurfaceLayerMode() const {
1106 return surface_layer_mode_;
1107}
1108
wolenetzed8e7092017-04-21 16:28:591109blink::WebString WebMediaPlayerImpl::GetErrorMessage() const {
wolenetz4d39cc02016-04-05 19:54:411110 DCHECK(main_task_runner_->BelongsToCurrentThread());
wolenetzed8e7092017-04-21 16:28:591111 return blink::WebString::FromUTF8(media_log_->GetErrorMessage());
wolenetz4d39cc02016-04-05 19:54:411112}
1113
Blink Reformat1c4d759e2017-04-09 16:34:541114blink::WebTimeRanges WebMediaPlayerImpl::Buffered() const {
acolwellb4034942014-08-28 15:42:431115 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]779a8322014-08-22 21:28:371116
acolwell9e0840d2014-09-06 19:01:321117 Ranges<base::TimeDelta> buffered_time_ranges =
Antonio Gomes81b56552019-05-15 22:15:281118 pipeline_controller_->GetBufferedTimeRanges();
[email protected]779a8322014-08-22 21:28:371119
avayvodcc273dd2017-01-19 19:35:121120 const base::TimeDelta duration = GetPipelineMediaDuration();
dalecurtis39a7f932016-07-19 18:34:591121 if (duration != kInfiniteDuration) {
Antonio Gomes81b56552019-05-15 22:15:281122 buffered_data_source_host_->AddBufferedTimeRanges(&buffered_time_ranges,
1123 duration);
[email protected]779a8322014-08-22 21:28:371124 }
Antonio Gomesf01cfbd2019-07-12 08:53:111125 return blink::ConvertToWebTimeRanges(buffered_time_ranges);
[email protected]02022fc2014-05-16 00:05:311126}
1127
Blink Reformat1c4d759e2017-04-09 16:34:541128blink::WebTimeRanges WebMediaPlayerImpl::Seekable() const {
acolwellb4034942014-08-28 15:42:431129 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]39bdde32013-04-17 17:44:201130
Blink Reformat1c4d759e2017-04-09 16:34:541131 if (ready_state_ < WebMediaPlayer::kReadyStateHaveMetadata)
philipjb0e6f3f2014-09-30 09:51:531132 return blink::WebTimeRanges();
1133
Blink Reformat1c4d759e2017-04-09 16:34:541134 const double seekable_end = Duration();
dalecurtis56359cb2014-10-28 00:06:291135
1136 // Allow a special exception for seeks to zero for streaming sources with a
1137 // finite duration; this allows looping to work.
Dale Curtis4841c712018-12-13 18:14:051138 const bool is_finite_stream = mb_data_source_ &&
1139 mb_data_source_->IsStreaming() &&
tguilbertade2bcb2017-01-07 02:57:451140 std::isfinite(seekable_end);
1141
tguilbert75e2bf62017-04-26 20:13:121142 // Do not change the seekable range when using the MediaPlayerRenderer. It
1143 // will take care of dropping invalid seeks.
1144 const bool force_seeks_to_zero =
1145 !using_media_player_renderer_ && is_finite_stream;
dalecurtis56359cb2014-10-28 00:06:291146
1147 // TODO(dalecurtis): Technically this allows seeking on media which return an
tguilbertade2bcb2017-01-07 02:57:451148 // infinite duration so long as DataSource::IsStreaming() is false. While not
dalecurtis56359cb2014-10-28 00:06:291149 // expected, disabling this breaks semi-live players, http://crbug.com/427412.
1150 const blink::WebTimeRange seekable_range(
tguilbertade2bcb2017-01-07 02:57:451151 0.0, force_seeks_to_zero ? 0.0 : seekable_end);
philipjb0e6f3f2014-09-30 09:51:531152 return blink::WebTimeRanges(&seekable_range, 1);
[email protected]ec9212f2008-12-18 21:40:361153}
1154
sandersd35d2c3f2017-01-14 02:04:421155bool WebMediaPlayerImpl::IsPrerollAttemptNeeded() {
1156 // TODO(sandersd): Replace with |highest_ready_state_since_seek_| if we need
1157 // to ensure that preroll always gets a chance to complete.
1158 // See http://crbug.com/671525.
Dale Curtis69e8f302019-05-22 07:36:581159 //
1160 // Note: Even though we get play/pause signals at kReadyStateHaveMetadata, we
1161 // must attempt to preroll until kReadyStateHaveFutureData so that the
1162 // canplaythrough event will be fired to the page (which may be waiting).
1163 //
1164 // TODO(dalecurtis): We should try signaling kReadyStateHaveFutureData upon
1165 // automatic-suspend of a non-playing element to avoid wasting resources.
1166 if (highest_ready_state_ >= ReadyState::kReadyStateHaveFutureData)
sandersd35d2c3f2017-01-14 02:04:421167 return false;
1168
Fredrik Hubinette4cfb4412017-08-23 00:03:071169 // To suspend before we reach kReadyStateHaveCurrentData is only ok
1170 // if we know we're going to get woken up when we get more data, which
1171 // will only happen if the network is in the "Loading" state.
1172 // This happens when the network is fast, but multiple videos are loading
1173 // and multiplexing gets held up waiting for available threads.
1174 if (highest_ready_state_ <= ReadyState::kReadyStateHaveMetadata &&
1175 network_state_ != WebMediaPlayer::kNetworkStateLoading) {
1176 return true;
1177 }
1178
sandersd35d2c3f2017-01-14 02:04:421179 if (preroll_attempt_pending_)
1180 return true;
1181
1182 // Freshly initialized; there has never been any loading progress. (Otherwise
1183 // |preroll_attempt_pending_| would be true when the start time is null.)
1184 if (preroll_attempt_start_time_.is_null())
1185 return false;
1186
1187 base::TimeDelta preroll_attempt_duration =
1188 tick_clock_->NowTicks() - preroll_attempt_start_time_;
1189 return preroll_attempt_duration < kPrerollAttemptTimeout;
1190}
1191
Blink Reformat1c4d759e2017-04-09 16:34:541192bool WebMediaPlayerImpl::DidLoadingProgress() {
acolwellb4034942014-08-28 15:42:431193 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtise7120dc2016-09-03 02:54:351194
1195 // Note: Separate variables used to ensure both methods are called every time.
Antonio Gomes81b56552019-05-15 22:15:281196 const bool pipeline_progress = pipeline_controller_->DidLoadingProgress();
1197 const bool data_progress = buffered_data_source_host_->DidLoadingProgress();
hubbeb2d3efd2017-05-05 23:26:381198 return pipeline_progress || data_progress;
[email protected]d43ed912009-02-03 04:52:531199}
1200
danakjff6a0262018-06-26 19:50:311201void WebMediaPlayerImpl::Paint(cc::PaintCanvas* canvas,
[email protected]dd5c7972014-08-21 15:00:371202 const blink::WebRect& rect,
Kai Ninomiya9e8ae29b2017-09-06 23:45:161203 cc::PaintFlags& flags,
1204 int already_uploaded_id,
1205 VideoFrameUploadMetadata* out_metadata) {
acolwellb4034942014-08-28 15:42:431206 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]dd061e12014-05-06 19:21:221207 TRACE_EVENT0("media", "WebMediaPlayerImpl:paint");
[email protected]4e6be3f2009-05-07 02:24:441208
watkd16bb3e2017-04-25 01:18:311209 // We can't copy from protected frames.
Xiaohan Wang24cfe2c2018-01-22 23:16:001210 if (cdm_context_ref_)
xhwang80739452016-01-13 00:48:001211 return;
1212
mcasasf1236fc22015-05-29 22:38:561213 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
[email protected]0fe5d43b2014-01-24 23:32:451214
[email protected]b49beeb2013-03-01 20:04:001215 gfx::Rect gfx_rect(rect);
mcasas265bdbf82015-06-12 18:44:071216 if (video_frame.get() && video_frame->HasTextures()) {
Antoine Labourfee4ae52019-04-24 23:53:571217 if (!context_provider_)
danakj53f7ec902016-05-21 01:30:101218 return; // Unable to get/create a shared main thread context.
Antoine Labourfee4ae52019-04-24 23:53:571219 if (!context_provider_->GrContext())
danakj53f7ec902016-05-21 01:30:101220 return; // The context has been lost since and can't setup a GrContext.
dongseong.hwang0c4e9d82015-01-08 20:11:131221 }
Kai Ninomiyaef8c9e02017-09-27 04:07:401222 if (out_metadata && video_frame) {
Kai Ninomiya9e8ae29b2017-09-06 23:45:161223 // WebGL last-uploaded-frame-metadata API enabled. https://crbug.com/639174
1224 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1225 out_metadata);
1226 if (out_metadata->skipped) {
1227 // Skip uploading this frame.
1228 return;
1229 }
1230 }
zhuoyu.qian4689dde22017-10-16 04:11:481231 video_renderer_.Paint(
Julien Isorce6c83d8de2017-10-12 13:11:291232 video_frame, canvas, gfx::RectF(gfx_rect), flags,
Ted Meyer4a427632019-05-01 19:05:271233 pipeline_metadata_.video_decoder_config.video_transformation(),
Antoine Labourfee4ae52019-04-24 23:53:571234 context_provider_.get());
[email protected]ec9212f2008-12-18 21:40:361235}
[email protected]5df51652009-01-17 00:03:001236
Yutaka Hirano657a0552018-11-09 00:52:551237bool WebMediaPlayerImpl::WouldTaintOrigin() const {
Thomas Guilbert153f84572018-07-19 05:03:581238 if (demuxer_found_hls_) {
1239 // HLS manifests might pull segments from a different origin. We can't know
1240 // for sure, so we conservatively say no here.
Yutaka Hiranoa9cbaa72018-10-10 08:35:221241 return true;
1242 }
1243
Dale Curtis4841c712018-12-13 18:14:051244 if (!mb_data_source_)
Yutaka Hirano657a0552018-11-09 00:52:551245 return false;
1246
1247 // When the resource is redirected to another origin we think it as
1248 // tainted. This is actually not specified, and is under discussion.
1249 // See https://github.com/whatwg/fetch/issues/737.
Dale Curtis4841c712018-12-13 18:14:051250 if (!mb_data_source_->HasSingleOrigin() &&
1251 mb_data_source_->cors_mode() == UrlData::CORS_UNSPECIFIED) {
Yutaka Hirano657a0552018-11-09 00:52:551252 return true;
1253 }
1254
Dale Curtis4841c712018-12-13 18:14:051255 return mb_data_source_->IsCorsCrossOrigin();
[email protected]3fe27112012-06-07 04:00:011256}
1257
Blink Reformat1c4d759e2017-04-09 16:34:541258double WebMediaPlayerImpl::MediaTimeForTimeValue(double timeValue) const {
qinminb4c39782015-08-10 18:43:241259 return base::TimeDelta::FromSecondsD(timeValue).InSecondsF();
[email protected]e06e16d82011-05-26 22:13:331260}
1261
Blink Reformat1c4d759e2017-04-09 16:34:541262unsigned WebMediaPlayerImpl::DecodedFrameCount() const {
acolwellb4034942014-08-28 15:42:431263 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051264 return GetPipelineStatistics().video_frames_decoded;
[email protected]4c51bc662011-02-16 02:03:161265}
1266
Blink Reformat1c4d759e2017-04-09 16:34:541267unsigned WebMediaPlayerImpl::DroppedFrameCount() const {
acolwellb4034942014-08-28 15:42:431268 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051269 return GetPipelineStatistics().video_frames_dropped;
[email protected]4c51bc662011-02-16 02:03:161270}
1271
Dave Tapuska6c7154912018-07-30 20:39:001272uint64_t WebMediaPlayerImpl::AudioDecodedByteCount() const {
acolwellb4034942014-08-28 15:42:431273 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051274 return GetPipelineStatistics().audio_bytes_decoded;
[email protected]4c51bc662011-02-16 02:03:161275}
1276
Dave Tapuska6c7154912018-07-30 20:39:001277uint64_t WebMediaPlayerImpl::VideoDecodedByteCount() const {
acolwellb4034942014-08-28 15:42:431278 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisc7d2a7d22018-01-11 20:01:051279 return GetPipelineStatistics().video_bytes_decoded;
[email protected]4c51bc662011-02-16 02:03:161280}
1281
Dale Curtiscdfc6f22019-06-26 22:05:231282bool WebMediaPlayerImpl::HasAvailableVideoFrame() const {
1283 return has_first_frame_;
1284}
1285
Blink Reformat1c4d759e2017-04-09 16:34:541286bool WebMediaPlayerImpl::CopyVideoTextureToPlatformTexture(
danakj46070b02016-03-28 21:54:111287 gpu::gles2::GLES2Interface* gl,
jiajia.qinc2943162017-05-12 01:34:391288 unsigned int target,
zmo57d577a2015-10-30 18:28:591289 unsigned int texture,
kbr0986e622017-04-13 02:34:581290 unsigned internal_format,
1291 unsigned format,
1292 unsigned type,
jiajia.qinc2943162017-05-12 01:34:391293 int level,
zmo57d577a2015-10-30 18:28:591294 bool premultiply_alpha,
Kai Ninomiya9e8ae29b2017-09-06 23:45:161295 bool flip_y,
1296 int already_uploaded_id,
1297 VideoFrameUploadMetadata* out_metadata) {
xhwang213e50c2016-10-10 23:56:311298 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]bfc05f22013-10-19 17:55:161299 TRACE_EVENT0("media", "WebMediaPlayerImpl:copyVideoTextureToPlatformTexture");
1300
watkd16bb3e2017-04-25 01:18:311301 // We can't copy from protected frames.
Xiaohan Wang24cfe2c2018-01-22 23:16:001302 if (cdm_context_ref_)
xhwang213e50c2016-10-10 23:56:311303 return false;
[email protected]dd061e12014-05-06 19:21:221304
xhwang213e50c2016-10-10 23:56:311305 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
jbauman581d041c2016-07-21 01:01:031306 if (!video_frame.get() || !video_frame->HasTextures()) {
[email protected]e56f88c72013-06-25 22:31:291307 return false;
dongseong.hwang0c4e9d82015-01-08 20:11:131308 }
Kai Ninomiya9e8ae29b2017-09-06 23:45:161309 if (out_metadata) {
1310 // WebGL last-uploaded-frame-metadata API is enabled.
1311 // https://crbug.com/639174
1312 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1313 out_metadata);
1314 if (out_metadata->skipped) {
1315 // Skip uploading this frame.
1316 return true;
1317 }
1318 }
[email protected]df41e252014-02-03 23:39:501319
zhuoyu.qian4689dde22017-10-16 04:11:481320 return video_renderer_.CopyVideoFrameTexturesToGLTexture(
Antoine Labourfee4ae52019-04-24 23:53:571321 context_provider_.get(), gl, video_frame.get(), target, texture,
Dan Sanders930cc1d2018-10-03 00:45:081322 internal_format, format, type, level, premultiply_alpha, flip_y);
[email protected]6523b242013-03-13 11:10:071323}
1324
Yan, Shaobo44b79ba2019-04-02 06:09:271325bool WebMediaPlayerImpl::PrepareVideoFrameForWebGL(
1326 gpu::gles2::GLES2Interface* gl,
1327 unsigned target,
1328 unsigned texture,
1329 int already_uploaded_id,
1330 WebMediaPlayer::VideoFrameUploadMetadata* out_metadata) {
1331 DCHECK(main_task_runner_->BelongsToCurrentThread());
1332 TRACE_EVENT0("media", "WebMediaPlayerImpl::PrepareVideoFrameForWebGL");
1333
1334 // TODO(crbug.com/776222): How to deal with protected frames.
1335 scoped_refptr<VideoFrame> video_frame = GetCurrentFrameFromCompositor();
1336 if (!video_frame.get() || !video_frame->HasTextures()) {
1337 return false;
1338 }
1339 if (out_metadata) {
1340 // WebGL last-uploaded-frame-metadata API is enabled.
1341 ComputeFrameUploadMetadata(video_frame.get(), already_uploaded_id,
1342 out_metadata);
1343 if (out_metadata->skipped) {
1344 // Skip uploading this frame.
1345 return true;
1346 }
1347 }
1348
Yan, Shaobo44b79ba2019-04-02 06:09:271349 return video_renderer_.PrepareVideoFrameForWebGL(
Antoine Labourfee4ae52019-04-24 23:53:571350 context_provider_.get(), gl, video_frame.get(), target, texture);
Yan, Shaobo44b79ba2019-04-02 06:09:271351}
1352
Matt Wolenetz95af6362018-01-04 20:23:421353// static
Kai Ninomiya9e8ae29b2017-09-06 23:45:161354void WebMediaPlayerImpl::ComputeFrameUploadMetadata(
1355 VideoFrame* frame,
1356 int already_uploaded_id,
1357 VideoFrameUploadMetadata* out_metadata) {
1358 DCHECK(out_metadata);
Kai Ninomiyaef8c9e02017-09-27 04:07:401359 DCHECK(frame);
Kai Ninomiya9e8ae29b2017-09-06 23:45:161360 out_metadata->frame_id = frame->unique_id();
1361 out_metadata->visible_rect = frame->visible_rect();
1362 out_metadata->timestamp = frame->timestamp();
Li, Hao0fab96a2019-10-31 02:46:471363 base::TimeDelta frame_duration;
1364 if (frame->metadata()->GetTimeDelta(media::VideoFrameMetadata::FRAME_DURATION,
1365 &frame_duration)) {
1366 out_metadata->expected_timestamp = frame->timestamp() + frame_duration;
1367 };
Kai Ninomiya9e8ae29b2017-09-06 23:45:161368 bool skip_possible = already_uploaded_id != -1;
1369 bool same_frame_id = frame->unique_id() == already_uploaded_id;
1370 out_metadata->skipped = skip_possible && same_frame_id;
1371}
1372
Blink Reformat1c4d759e2017-04-09 16:34:541373void WebMediaPlayerImpl::SetContentDecryptionModule(
[email protected]9ebc3b03f2014-08-13 04:01:231374 blink::WebContentDecryptionModule* cdm,
1375 blink::WebContentDecryptionModuleResult result) {
xhwang51139732017-02-24 19:36:081376 DVLOG(1) << __func__ << ": cdm = " << cdm;
acolwellb4034942014-08-28 15:42:431377 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]9ebc3b03f2014-08-13 04:01:231378
jrummell06f27072015-06-08 18:12:381379 // Once the CDM is set it can't be cleared as there may be frames being
1380 // decrypted on other threads. So fail this request.
1381 // http://crbug.com/462365#c7.
xhwang97de4202014-11-25 08:44:011382 if (!cdm) {
Blink Reformat1c4d759e2017-04-09 16:34:541383 result.CompleteWithError(
1384 blink::kWebContentDecryptionModuleExceptionInvalidStateError, 0,
xhwang79b193042016-12-13 18:52:431385 "The existing ContentDecryptionModule object cannot be removed at this "
1386 "time.");
xhwang97de4202014-11-25 08:44:011387 return;
1388 }
1389
jrummell89e61d82015-07-23 20:03:341390 // Create a local copy of |result| to avoid problems with the callback
1391 // getting passed to the media thread and causing |result| to be destructed
jrummell4acbec912016-02-27 02:45:031392 // on the wrong thread in some failure conditions. Blink should prevent
1393 // multiple simultaneous calls.
1394 DCHECK(!set_cdm_result_);
jrummell89e61d82015-07-23 20:03:341395 set_cdm_result_.reset(new blink::WebContentDecryptionModuleResult(result));
1396
Chris Cunninghamd4a00192019-03-21 20:02:491397 SetCdmInternal(cdm);
xhwang97de4202014-11-25 08:44:011398}
1399
xhwange8c4181a2014-12-06 08:10:011400void WebMediaPlayerImpl::OnEncryptedMediaInitData(
jrummellcf78967c2015-04-03 05:03:581401 EmeInitDataType init_data_type,
Avi Drissman97785ea2015-12-19 01:11:311402 const std::vector<uint8_t>& init_data) {
jrummellcf78967c2015-04-03 05:03:581403 DCHECK(init_data_type != EmeInitDataType::UNKNOWN);
xhwangbab66f52014-12-02 23:49:501404
Xiaohan Wangf63505d2017-10-21 08:00:531405 RecordEncryptedEvent(true);
xhwangbab66f52014-12-02 23:49:501406
dalecurtis04bdb582016-08-17 22:15:231407 // Recreate the watch time reporter if necessary.
1408 const bool was_encrypted = is_encrypted_;
1409 is_encrypted_ = true;
Dale Curtis3899090ea2018-01-12 00:10:351410 if (!was_encrypted) {
1411 media_metrics_provider_->SetIsEME();
1412 if (watch_time_reporter_)
1413 CreateWatchTimeReporter();
dalecurtis04bdb582016-08-17 22:15:231414
Chris Cunningham6c0ec292019-04-04 18:31:111415 // |was_encrypted| = false means we didn't have a CDM prior to observing
1416 // encrypted media init data. Reset the reporter until the CDM arrives. See
1417 // SetCdmInternal().
1418 DCHECK(!cdm_config_);
1419 video_decode_stats_reporter_.reset();
1420 }
Chris Cunninghamd9df58e2017-08-29 00:04:231421
Blink Reformat1c4d759e2017-04-09 16:34:541422 encrypted_client_->Encrypted(
Antonio Gomes89b70572019-07-13 00:44:211423 init_data_type, init_data.data(),
srirama.m26f864d02015-07-14 05:21:461424 base::saturated_cast<unsigned int>(init_data.size()));
xhwangbab66f52014-12-02 23:49:501425}
1426
servolk81e01e02016-03-05 03:29:151427void WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated(
dcheng3076abbf2016-04-22 20:42:391428 std::unique_ptr<MediaTracks> tracks) {
servolk81e01e02016-03-05 03:29:151429 // For MSE/chunk_demuxer case the media track updates are handled by
1430 // WebSourceBufferImpl.
1431 DCHECK(demuxer_.get());
1432 DCHECK(!chunk_demuxer_);
servolkef1e5ef2016-03-25 04:55:261433
servolk16e8bdf82017-04-11 17:00:391434 // Report the media track information to blink. Only the first audio track and
1435 // the first video track are enabled by default to match blink logic.
1436 bool is_first_audio_track = true;
1437 bool is_first_video_track = true;
servolkef1e5ef2016-03-25 04:55:261438 for (const auto& track : tracks->tracks()) {
1439 if (track->type() == MediaTrack::Audio) {
Maciej Pawlowskif2556d122019-06-03 08:14:181440 client_->AddAudioTrack(
1441 blink::WebString::FromUTF8(track->id().value()),
1442 blink::WebMediaPlayerClient::kAudioTrackKindMain,
1443 blink::WebString::FromUTF8(track->label().value()),
1444 blink::WebString::FromUTF8(track->language().value()),
1445 is_first_audio_track);
servolk16e8bdf82017-04-11 17:00:391446 is_first_audio_track = false;
servolkef1e5ef2016-03-25 04:55:261447 } else if (track->type() == MediaTrack::Video) {
Maciej Pawlowskif2556d122019-06-03 08:14:181448 client_->AddVideoTrack(
1449 blink::WebString::FromUTF8(track->id().value()),
1450 blink::WebMediaPlayerClient::kVideoTrackKindMain,
1451 blink::WebString::FromUTF8(track->label().value()),
1452 blink::WebString::FromUTF8(track->language().value()),
1453 is_first_video_track);
servolk16e8bdf82017-04-11 17:00:391454 is_first_video_track = false;
servolkef1e5ef2016-03-25 04:55:261455 } else {
1456 // Text tracks are not supported through this code path yet.
1457 NOTREACHED();
1458 }
1459 }
servolk81e01e02016-03-05 03:29:151460}
1461
Chris Cunninghamd4a00192019-03-21 20:02:491462void WebMediaPlayerImpl::SetCdmInternal(
1463 blink::WebContentDecryptionModule* cdm) {
jrummelle616ee92016-10-08 02:15:441464 DCHECK(main_task_runner_->BelongsToCurrentThread());
1465 DCHECK(cdm);
Xiaohan Wang24cfe2c2018-01-22 23:16:001466
Chris Cunninghamd4a00192019-03-21 20:02:491467 const bool was_encrypted = is_encrypted_;
1468 is_encrypted_ = true;
1469
1470 // Recreate the watch time reporter if necessary.
1471 if (!was_encrypted) {
1472 media_metrics_provider_->SetIsEME();
1473 if (watch_time_reporter_)
1474 CreateWatchTimeReporter();
1475 }
1476
Chris Cunningham6c0ec292019-04-04 18:31:111477 WebContentDecryptionModuleImpl* web_cdm =
1478 ToWebContentDecryptionModuleImpl(cdm);
1479 auto cdm_context_ref = web_cdm->GetCdmContextRef();
Xiaohan Wang24cfe2c2018-01-22 23:16:001480 if (!cdm_context_ref) {
jrummelle616ee92016-10-08 02:15:441481 NOTREACHED();
1482 OnCdmAttached(false);
xhwang80739452016-01-13 00:48:001483 return;
1484 }
1485
Chris Cunningham6c0ec292019-04-04 18:31:111486 // Arrival of |cdm_config_| and |key_system_| unblocks recording of encrypted
1487 // stats. Attempt to create the stats reporter. Note, we do NOT guard this
1488 // within !was_encypted above because often the CDM arrives after the call to
1489 // OnEncryptedMediaInitData().
1490 cdm_config_ = web_cdm->GetCdmConfig();
1491 key_system_ = web_cdm->GetKeySystem();
1492 DCHECK(!key_system_.empty());
1493 CreateVideoDecodeStatsReporter();
1494
Xiaohan Wang24cfe2c2018-01-22 23:16:001495 CdmContext* cdm_context = cdm_context_ref->GetCdmContext();
1496 DCHECK(cdm_context);
jrummelle616ee92016-10-08 02:15:441497
1498 // Keep the reference to the CDM, as it shouldn't be destroyed until
1499 // after the pipeline is done with the |cdm_context|.
Xiaohan Wang24cfe2c2018-01-22 23:16:001500 pending_cdm_context_ref_ = std::move(cdm_context_ref);
Antonio Gomes81b56552019-05-15 22:15:281501 pipeline_controller_->SetCdm(
Antonio Gomes142f32a2019-05-15 23:32:561502 cdm_context, base::Bind(&WebMediaPlayerImpl::OnCdmAttached, weak_this_));
xhwang97de4202014-11-25 08:44:011503}
1504
jrummell89e61d82015-07-23 20:03:341505void WebMediaPlayerImpl::OnCdmAttached(bool success) {
xhwang51139732017-02-24 19:36:081506 DVLOG(1) << __func__ << ": success = " << success;
jrummelle616ee92016-10-08 02:15:441507 DCHECK(main_task_runner_->BelongsToCurrentThread());
Xiaohan Wang24cfe2c2018-01-22 23:16:001508 DCHECK(pending_cdm_context_ref_);
jrummelle616ee92016-10-08 02:15:441509
1510 // If the CDM is set from the constructor there is no promise
1511 // (|set_cdm_result_|) to fulfill.
xhwang97de4202014-11-25 08:44:011512 if (success) {
xhwang29c5ad202017-04-14 07:02:191513 media_log_->SetBooleanProperty("has_cdm", true);
1514
jrummelle616ee92016-10-08 02:15:441515 // This will release the previously attached CDM (if any).
Xiaohan Wang24cfe2c2018-01-22 23:16:001516 cdm_context_ref_ = std::move(pending_cdm_context_ref_);
jrummelle616ee92016-10-08 02:15:441517 if (set_cdm_result_) {
Blink Reformat1c4d759e2017-04-09 16:34:541518 set_cdm_result_->Complete();
jrummelle616ee92016-10-08 02:15:441519 set_cdm_result_.reset();
1520 }
1521
xhwang97de4202014-11-25 08:44:011522 return;
1523 }
1524
Xiaohan Wang24cfe2c2018-01-22 23:16:001525 pending_cdm_context_ref_.reset();
jrummelle616ee92016-10-08 02:15:441526 if (set_cdm_result_) {
Blink Reformat1c4d759e2017-04-09 16:34:541527 set_cdm_result_->CompleteWithError(
1528 blink::kWebContentDecryptionModuleExceptionNotSupportedError, 0,
xhwang79b193042016-12-13 18:52:431529 "Unable to set ContentDecryptionModule object");
jrummelle616ee92016-10-08 02:15:441530 set_cdm_result_.reset();
1531 }
[email protected]9ebc3b03f2014-08-13 04:01:231532}
1533
sandersd1c0bba02016-03-04 23:14:081534void WebMediaPlayerImpl::OnPipelineSeeked(bool time_updated) {
John Chen5b164a02017-11-01 00:36:091535 TRACE_EVENT2("media", "WebMediaPlayerImpl::OnPipelineSeeked", "target",
1536 seek_time_.InSecondsF(), "id", media_log_->id());
[email protected]5d11eff2011-09-15 00:06:061537 seeking_ = false;
wolenetz1b2ae7d2015-06-10 00:44:211538 seek_time_ = base::TimeDelta();
avayvod2135a642017-01-13 00:17:141539
hubbe5a2dec022016-03-17 01:14:231540 if (paused_) {
Antonio Gomes81b56552019-05-15 22:15:281541 paused_time_ = pipeline_controller_->GetMediaTime();
dalecurtis04bdb582016-08-17 22:15:231542 } else {
1543 DCHECK(watch_time_reporter_);
1544 watch_time_reporter_->OnPlaying();
hubbe5a2dec022016-03-17 01:14:231545 }
sandersd1c0bba02016-03-04 23:14:081546 if (time_updated)
1547 should_notify_time_changed_ = true;
dalecurtisaf34d8712016-09-20 04:32:261548
dalecurtis4f6d14d2017-02-22 17:42:221549 // Reset underflow duration upon seek; this prevents looping videos and user
1550 // actions from artificially inflating the duration.
1551 underflow_timer_.reset();
avayvod56e1f3942017-01-21 02:06:311552
1553 // Background video optimizations are delayed when shown/hidden if pipeline
1554 // is seeking.
1555 UpdateBackgroundVideoOptimizationState();
Dale Curtis2dc6089a2018-03-26 16:47:581556
Dale Curtisd71061f02019-05-21 21:33:541557 // If we successfully completed a suspended startup, we need to make a call to
1558 // UpdatePlayState() in case any events which should trigger a resume have
1559 // occurred during startup.
Dale Curtis2dc6089a2018-03-26 16:47:581560 if (attempting_suspended_start_ &&
Antonio Gomes81b56552019-05-15 22:15:281561 pipeline_controller_->IsPipelineSuspended()) {
Dale Curtisff576552018-03-30 02:32:441562 skip_metrics_due_to_startup_suspend_ = true;
Dale Curtisd71061f02019-05-21 21:33:541563
1564 // If we successfully completed a suspended startup, signal that we have
1565 // reached BUFFERING_HAVE_ENOUGH so that canplay and canplaythrough fire
1566 // correctly. We must unfortunately always do this because it's valid for
1567 // elements to play while not visible nor even in the DOM.
1568 //
1569 // Note: This call is dual purpose, it is also responsible for triggering an
1570 // UpdatePlayState() call which may need to resume the pipeline once Blink
1571 // has been told about the ReadyState change.
Chris Cunninghamfc0d67e2019-07-22 20:29:161572 OnBufferingStateChangeInternal(BUFFERING_HAVE_ENOUGH,
1573 BUFFERING_CHANGE_REASON_UNKNOWN, true);
Dale Curtisff576552018-03-30 02:32:441574
1575 // If |skip_metrics_due_to_startup_suspend_| is unset by a resume started by
1576 // the OnBufferingStateChangeInternal() call, record a histogram of it here.
1577 //
1578 // If the value is unset, that means we should not have suspended and we've
1579 // likely incurred some cost to TimeToFirstFrame and TimeToPlayReady which
1580 // will be reflected in those statistics.
1581 base::UmaHistogramBoolean(
1582 std::string("Media.PreloadMetadataSuspendWasIdeal.") +
1583 ((HasVideo() && HasAudio()) ? "AudioVideo"
1584 : (HasVideo() ? "Video" : "Audio")),
1585 skip_metrics_due_to_startup_suspend_);
Dale Curtis2dc6089a2018-03-26 16:47:581586 }
1587
1588 attempting_suspended_start_ = false;
Becca Hughes7a85bf22019-07-24 16:16:581589
1590 // The current time has changed so we should update the media position state.
1591 UpdateMediaPositionState();
[email protected]8931c41a2009-07-07 17:31:491592}
1593
sandersd1c0bba02016-03-04 23:14:081594void WebMediaPlayerImpl::OnPipelineSuspended() {
Dale Curtis83321152018-12-01 01:22:061595 // Add a log event so the player shows up as "SUSPENDED" in media-internals.
1596 media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::SUSPENDED));
1597
Dale Curtis04769ca2019-05-25 00:38:101598 if (attempting_suspended_start_) {
1599 DCHECK(pipeline_controller_->IsSuspended());
1600 did_lazy_load_ = !has_poster_ && HasVideo();
1601 }
1602
sandersd2f5bb6152017-03-29 22:57:531603 // Tell the data source we have enough data so that it may release the
Dale Curtis04769ca2019-05-25 00:38:101604 // connection (unless blink is waiting on us to signal play()).
1605 if (mb_data_source_ && !client_->CouldPlayIfEnoughData()) {
1606 // |attempting_suspended_start_| will be cleared by OnPipelineSeeked() which
1607 // will occur after this method during a suspended startup.
1608 if (attempting_suspended_start_ && did_lazy_load_) {
1609 DCHECK(!has_first_frame_);
1610 DCHECK(have_enough_after_lazy_load_cb_.IsCancelled());
1611
1612 // For lazy load, we won't know if the element is non-visible until a
1613 // layout completes, so to avoid unnecessarily tearing down the network
1614 // connection, briefly (250ms chosen arbitrarily) delay signaling "have
1615 // enough" to the MultiBufferDataSource.
1616 //
1617 // base::Unretained() is safe here since the base::CancelableOnceClosure
1618 // will cancel upon destruction of this class and |mb_data_source_| is
1619 // gauranteeed to outlive us.
1620 have_enough_after_lazy_load_cb_.Reset(
1621 base::BindOnce(&MultibufferDataSource::OnBufferingHaveEnough,
1622 base::Unretained(mb_data_source_), true));
1623 main_task_runner_->PostDelayedTask(
1624 FROM_HERE, have_enough_after_lazy_load_cb_.callback(),
1625 base::TimeDelta::FromMilliseconds(250));
1626 } else {
1627 have_enough_after_lazy_load_cb_.Cancel();
1628 mb_data_source_->OnBufferingHaveEnough(true);
1629 }
1630 }
dalecurtis37fe5862016-03-15 19:29:091631
sandersd50a635e2016-04-04 22:50:091632 ReportMemoryUsage();
1633
sandersd1c0bba02016-03-04 23:14:081634 if (pending_suspend_resume_cycle_) {
watkdee516f2016-02-18 02:22:191635 pending_suspend_resume_cycle_ = false;
sandersd50a635e2016-04-04 22:50:091636 UpdatePlayState();
dalecurtis0431cbf2016-03-12 01:19:431637 }
sandersd1c0bba02016-03-04 23:14:081638}
1639
avayvod2135a642017-01-13 00:17:141640void WebMediaPlayerImpl::OnBeforePipelineResume() {
Dale Curtis04769ca2019-05-25 00:38:101641 // Since we're resuming, cancel closing of the network connection.
1642 have_enough_after_lazy_load_cb_.Cancel();
1643
Dale Curtisff576552018-03-30 02:32:441644 // We went through suspended startup, so the player is only just now spooling
1645 // up for playback. As such adjust |load_start_time_| so it reports the same
1646 // metric as what would be reported if we had not suspended at startup.
1647 if (skip_metrics_due_to_startup_suspend_) {
1648 // In the event that the call to SetReadyState() initiated after pipeline
1649 // startup immediately tries to start playback, we should not update
1650 // |load_start_time_| to avoid losing visibility into the impact of a
1651 // suspended startup on the time until first frame / play ready for cases
1652 // where suspended startup was applied incorrectly.
1653 if (!attempting_suspended_start_)
1654 load_start_time_ = base::TimeTicks::Now() - time_to_metadata_;
1655 skip_metrics_due_to_startup_suspend_ = false;
1656 }
1657
avayvod2135a642017-01-13 00:17:141658 // Enable video track if we disabled it in the background - this way the new
1659 // renderer will attach its callbacks to the video stream properly.
1660 // TODO(avayvod): Remove this when disabling and enabling video tracks in
1661 // non-playing state works correctly. See https://crbug.com/678374.
1662 EnableVideoTrackIfNeeded();
1663 is_pipeline_resuming_ = true;
1664}
1665
1666void WebMediaPlayerImpl::OnPipelineResumed() {
1667 is_pipeline_resuming_ = false;
1668
avayvod56e1f3942017-01-21 02:06:311669 UpdateBackgroundVideoOptimizationState();
avayvod2135a642017-01-13 00:17:141670}
1671
alokp967c902452016-05-06 05:21:371672void WebMediaPlayerImpl::OnDemuxerOpened() {
1673 DCHECK(main_task_runner_->BelongsToCurrentThread());
dalecurtis9cddc0b2017-04-19 21:23:381674 client_->MediaSourceOpened(new WebMediaSourceImpl(chunk_demuxer_));
alokp967c902452016-05-06 05:21:371675}
1676
servolkf94b4602017-01-31 16:44:271677void WebMediaPlayerImpl::OnMemoryPressure(
1678 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1679 DVLOG(2) << __func__ << " memory_pressure_level=" << memory_pressure_level;
1680 DCHECK(main_task_runner_->BelongsToCurrentThread());
1681 DCHECK(base::FeatureList::IsEnabled(kMemoryPressureBasedSourceBufferGC));
1682 DCHECK(chunk_demuxer_);
1683
1684 // The new value of |memory_pressure_level| will take effect on the next
1685 // garbage collection. Typically this means the next SourceBuffer append()
1686 // operation, since per MSE spec, the garbage collection must only occur
1687 // during SourceBuffer append(). But if memory pressure is critical it might
1688 // be better to perform GC immediately rather than wait for the next append
1689 // and potentially get killed due to out-of-memory.
1690 // So if this experiment is enabled and pressure level is critical, we'll pass
1691 // down force_instant_gc==true, which will force immediate GC on
1692 // SourceBufferStreams.
1693 bool force_instant_gc =
1694 (enable_instant_source_buffer_gc_ &&
1695 memory_pressure_level ==
1696 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
1697
Matt Wolenetz95af6362018-01-04 20:23:421698 // base::Unretained is safe, since |chunk_demuxer_| is actually owned by
1699 // |this| via this->demuxer_. Note the destruction of |chunk_demuxer_| is done
1700 // from ~WMPI by first hopping to |media_task_runner_| to prevent race with
1701 // this task.
servolkf94b4602017-01-31 16:44:271702 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:511703 FROM_HERE, base::BindOnce(&ChunkDemuxer::OnMemoryPressure,
1704 base::Unretained(chunk_demuxer_),
1705 base::TimeDelta::FromSecondsD(CurrentTime()),
1706 memory_pressure_level, force_instant_gc));
servolkf94b4602017-01-31 16:44:271707}
1708
alokp967c902452016-05-06 05:21:371709void WebMediaPlayerImpl::OnError(PipelineStatus status) {
Xiaohan Wang73b433f2019-11-05 20:13:011710 DVLOG(1) << __func__ << ": status=" << status;
alokp967c902452016-05-06 05:21:371711 DCHECK(main_task_runner_->BelongsToCurrentThread());
1712 DCHECK_NE(status, PIPELINE_OK);
1713
1714 if (suppress_destruction_errors_)
1715 return;
1716
Thomas Guilbert6b6be3d2017-08-18 03:17:271717#if defined(OS_ANDROID)
Dale Curtisf273f8f2018-12-13 23:40:331718 // |mb_data_source_| may be nullptr if someone passes in a m3u8 as a data://
1719 // URL, since MediaPlayer doesn't support data:// URLs, fail playback now.
Dan Sanders675250992019-05-11 00:07:491720 const bool found_hls = base::FeatureList::IsEnabled(kHlsPlayer) &&
1721 status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS;
Dale Curtisf273f8f2018-12-13 23:40:331722 if (found_hls && mb_data_source_) {
Dan Sandersae245e42019-03-07 23:25:291723 demuxer_found_hls_ = true;
1724
Dan Sandersd80b1842019-02-05 00:36:161725 UMA_HISTOGRAM_BOOLEAN("Media.WebMediaPlayerImpl.HLS.IsCorsCrossOrigin",
1726 mb_data_source_->IsCorsCrossOrigin());
Dan Sandersae245e42019-03-07 23:25:291727 if (mb_data_source_->IsCorsCrossOrigin()) {
1728 UMA_HISTOGRAM_BOOLEAN("Media.WebMediaPlayerImpl.HLS.HasAccessControl",
1729 mb_data_source_->HasAccessControl());
1730 }
1731
1732 // Note: Does not consider the full redirect chain, which could contain
1733 // undetected mixed content.
Dan Sandersd80b1842019-02-05 00:36:161734 bool frame_url_is_cryptographic = url::Origin(frame_->GetSecurityOrigin())
1735 .GetURL()
1736 .SchemeIsCryptographic();
1737 bool manifest_url_is_cryptographic =
1738 loaded_url_.SchemeIsCryptographic() &&
1739 mb_data_source_->GetUrlAfterRedirects().SchemeIsCryptographic();
1740 UMA_HISTOGRAM_BOOLEAN(
1741 "Media.WebMediaPlayerImpl.HLS.IsMixedContent",
1742 frame_url_is_cryptographic && !manifest_url_is_cryptographic);
Thomas Guilbert153f84572018-07-19 05:03:581743
Xiaohan Wang3684e0c2019-10-30 01:04:301744 renderer_factory_selector_->SetBaseFactoryType(
1745 RendererFactorySelector::FactoryType::MEDIA_PLAYER);
Thomas Guilbert6b6be3d2017-08-18 03:17:271746
Dale Curtisf273f8f2018-12-13 23:40:331747 loaded_url_ = mb_data_source_->GetUrlAfterRedirects();
1748 DCHECK(data_source_);
1749 data_source_->Stop();
1750 mb_data_source_ = nullptr;
1751
Antonio Gomes81b56552019-05-15 22:15:281752 pipeline_controller_->Stop();
Dale Curtis8a6281322017-08-31 00:35:531753 SetMemoryReportingState(false);
Thomas Guilbert6b6be3d2017-08-18 03:17:271754
Dale Curtisf273f8f2018-12-13 23:40:331755 // Trampoline through the media task runner to destruct the demuxer and
1756 // data source now that we're switching to HLS playback.
1757 media_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:511758 FROM_HERE,
Dale Curtisf273f8f2018-12-13 23:40:331759 BindToCurrentLoop(base::BindOnce(
1760 [](std::unique_ptr<Demuxer> demuxer,
1761 std::unique_ptr<DataSource> data_source,
1762 base::OnceClosure start_pipeline_cb) {
1763 // Release resources before starting HLS.
1764 demuxer.reset();
1765 data_source.reset();
1766
1767 std::move(start_pipeline_cb).Run();
1768 },
1769 std::move(demuxer_), std::move(data_source_),
Antonio Gomes142f32a2019-05-15 23:32:561770 base::BindOnce(&WebMediaPlayerImpl::StartPipeline, weak_this_))));
Dale Curtisf273f8f2018-12-13 23:40:331771
Thomas Guilbert6b6be3d2017-08-18 03:17:271772 return;
1773 }
Dale Curtisf273f8f2018-12-13 23:40:331774
1775 // We found hls in a data:// URL, fail immediately.
1776 if (found_hls)
1777 status = PIPELINE_ERROR_EXTERNAL_RENDERER_FAILED;
Thomas Guilbert6b6be3d2017-08-18 03:17:271778#endif
1779
Dale Curtis5bba03232018-08-30 17:57:381780 MaybeSetContainerName();
Dan Sanders6edfd782019-08-13 00:13:181781 simple_watch_timer_.Stop();
alokp967c902452016-05-06 05:21:371782 media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status));
Dale Curtis74612b72017-12-14 20:56:191783 media_metrics_provider_->OnError(status);
Dale Curtisccfd0cca2017-08-31 01:27:561784 if (watch_time_reporter_)
1785 watch_time_reporter_->OnError(status);
alokp967c902452016-05-06 05:21:371786
Blink Reformat1c4d759e2017-04-09 16:34:541787 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) {
alokp967c902452016-05-06 05:21:371788 // Any error that occurs before reaching ReadyStateHaveMetadata should
1789 // be considered a format error.
Blink Reformat1c4d759e2017-04-09 16:34:541790 SetNetworkState(WebMediaPlayer::kNetworkStateFormatError);
alokp967c902452016-05-06 05:21:371791 } else {
Antonio Gomesf01cfbd2019-07-12 08:53:111792 SetNetworkState(blink::PipelineErrorToNetworkState(status));
alokp967c902452016-05-06 05:21:371793 }
1794
Thomas Guilbert2e591392017-08-12 00:56:381795 // PipelineController::Stop() is idempotent.
Antonio Gomes81b56552019-05-15 22:15:281796 pipeline_controller_->Stop();
Thomas Guilbert2e591392017-08-12 00:56:381797
alokp967c902452016-05-06 05:21:371798 UpdatePlayState();
1799}
1800
1801void WebMediaPlayerImpl::OnEnded() {
John Chen5b164a02017-11-01 00:36:091802 TRACE_EVENT2("media", "WebMediaPlayerImpl::OnEnded", "duration", Duration(),
1803 "id", media_log_->id());
pkastingf5279482016-07-27 02:18:201804 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:431805 DCHECK(main_task_runner_->BelongsToCurrentThread());
scherkusd2c745b2014-09-04 05:03:401806
sandersd1c0bba02016-03-04 23:14:081807 // Ignore state changes until we've completed all outstanding operations.
Antonio Gomes81b56552019-05-15 22:15:281808 if (!pipeline_controller_->IsStable())
scherkusd2c745b2014-09-04 05:03:401809 return;
1810
1811 ended_ = true;
Blink Reformat1c4d759e2017-04-09 16:34:541812 client_->TimeChanged();
sandersd50a635e2016-04-04 22:50:091813
1814 // We don't actually want this to run until |client_| calls seek() or pause(),
1815 // but that should have already happened in timeChanged() and so this is
1816 // expected to be a no-op.
1817 UpdatePlayState();
[email protected]576537842009-08-12 23:52:051818}
1819
Chisoon Jeong0a8e4bc2019-05-11 00:06:141820void WebMediaPlayerImpl::OnMetadata(const PipelineMetadata& metadata) {
pkastingf5279482016-07-27 02:18:201821 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:431822 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtisff576552018-03-30 02:32:441823
1824 // Cache the |time_to_metadata_| to use for adjusting the TimeToFirstFrame and
1825 // TimeToPlayReady metrics later if we end up doing a suspended startup.
1826 time_to_metadata_ = base::TimeTicks::Now() - load_start_time_;
1827 media_metrics_provider_->SetTimeToMetadata(time_to_metadata_);
1828 RecordTimingUMA("Media.TimeToMetadata", time_to_metadata_);
[email protected]a8e2cb82012-08-17 00:02:391829
Dale Curtis5bba03232018-08-30 17:57:381830 MaybeSetContainerName();
1831
[email protected]b8877772014-03-26 20:17:151832 pipeline_metadata_ = metadata;
[email protected]739847c02014-01-16 00:12:251833
Ted Meyer4a427632019-05-01 19:05:271834 UMA_HISTOGRAM_ENUMERATION(
1835 "Media.VideoRotation",
1836 metadata.video_decoder_config.video_transformation().rotation,
1837 VIDEO_ROTATION_MAX + 1);
[email protected]21c3f7502013-03-23 03:29:511838
John Rummelldb5a7ef2018-05-16 00:28:011839 if (HasAudio()) {
Ted Meyerd5885f82019-07-16 19:19:171840 media_metrics_provider_->SetHasAudio(metadata.audio_decoder_config.codec());
John Rummelldb5a7ef2018-05-16 00:28:011841 RecordEncryptionScheme("Audio",
1842 metadata.audio_decoder_config.encryption_scheme());
1843 }
1844
Blink Reformat1c4d759e2017-04-09 16:34:541845 if (HasVideo()) {
Ted Meyerd5885f82019-07-16 19:19:171846 media_metrics_provider_->SetHasVideo(metadata.video_decoder_config.codec());
John Rummelldb5a7ef2018-05-16 00:28:011847 RecordEncryptionScheme("Video",
1848 metadata.video_decoder_config.encryption_scheme());
1849
liberato2fd111be2017-01-04 00:25:061850 if (overlay_enabled_) {
1851 // SurfaceView doesn't support rotated video, so transition back if
[email protected]c8d574722017-08-30 20:53:431852 // the video is now rotated. If |always_enable_overlays_|, we keep the
liberato2fd111be2017-01-04 00:25:061853 // overlay anyway so that the state machine keeps working.
[email protected]c8d574722017-08-30 20:53:431854 // TODO(liberato): verify if compositor feedback catches this. If so,
1855 // then we don't need this check.
1856 if (!always_enable_overlays_ && !DoesOverlaySupportMetadata())
liberato2fd111be2017-01-04 00:25:061857 DisableOverlay();
liberato2fd111be2017-01-04 00:25:061858 }
watkf835a792016-06-24 23:24:401859
[email protected]702d721d2018-10-25 21:55:271860 if (surface_layer_mode_ ==
1861 blink::WebMediaPlayer::SurfaceLayerMode::kAlways ||
1862 (surface_layer_mode_ ==
1863 blink::WebMediaPlayer::SurfaceLayerMode::kOnDemand &&
1864 client_->DisplayType() ==
1865 WebMediaPlayer::DisplayType::kPictureInPicture)) {
1866 ActivateSurfaceLayerForVideo();
1867 } else {
danakj6e669e782018-05-16 16:57:171868 DCHECK(!video_layer_);
Ted Meyer4a427632019-05-01 19:05:271869 // TODO(tmathmeyer) does this need support for reflections as well?
danakj25f030112018-05-11 18:26:541870 video_layer_ = cc::VideoLayer::Create(
Julien Isorce6c83d8de2017-10-12 13:11:291871 compositor_.get(),
Ted Meyer4a427632019-05-01 19:05:271872 pipeline_metadata_.video_decoder_config.video_transformation()
1873 .rotation);
danakj8bc61c72018-05-16 13:55:061874 video_layer_->SetContentsOpaque(opaque_);
danakj8d204a42018-05-18 18:05:351875 client_->SetCcLayer(video_layer_.get());
lethalantidote7f6009d2017-07-07 21:47:391876 }
[email protected]a8e2cb82012-08-17 00:02:391877 }
dalecurtis8e4dc682016-03-15 02:30:301878
xjzd3fe45a2016-10-12 18:26:371879 if (observer_)
xjz15b483f2017-01-12 00:21:361880 observer_->OnMetadataChanged(pipeline_metadata_);
xjzd3fe45a2016-10-12 18:26:371881
Dale Curtisc7d2a7d22018-01-11 20:01:051882 // TODO(dalecurtis): Don't create these until kReadyStateHaveFutureData; when
1883 // we create them early we just increase the chances of needing to throw them
1884 // away unnecessarily.
dalecurtis04bdb582016-08-17 22:15:231885 CreateWatchTimeReporter();
Chris Cunninghamd9df58e2017-08-29 00:04:231886 CreateVideoDecodeStatsReporter();
Dale Curtisc7d2a7d22018-01-11 20:01:051887
Dale Curtis1e7a02b42019-05-28 20:12:241888 // SetReadyState() may trigger all sorts of calls into this class (e.g.,
1889 // Play(), Pause(), etc) so do it last to avoid unexpected states during the
1890 // calls. An exception to this is UpdatePlayState(), which is safe to call and
1891 // needs to use the new ReadyState in its calculations.
Dale Curtis2fc01cc2019-05-20 22:53:521892 SetReadyState(WebMediaPlayer::kReadyStateHaveMetadata);
Dale Curtis1e7a02b42019-05-28 20:12:241893 UpdatePlayState();
[email protected]a8e2cb82012-08-17 00:02:391894}
1895
[email protected]69db58f2018-09-26 20:27:561896void WebMediaPlayerImpl::ActivateSurfaceLayerForVideo() {
1897 // Note that we might or might not already be in VideoLayer mode.
1898 DCHECK(!bridge_);
1899
1900 surface_layer_for_video_enabled_ = true;
1901
1902 // If we're in VideoLayer mode, then get rid of the layer.
1903 if (video_layer_) {
1904 client_->SetCcLayer(nullptr);
1905 video_layer_ = nullptr;
1906 }
1907
1908 bridge_ = std::move(create_bridge_callback_)
1909 .Run(this, compositor_->GetUpdateSubmissionStateCallback());
1910 bridge_->CreateSurfaceLayer();
1911
Ted Meyer4a427632019-05-01 19:05:271912 // TODO(tmathmeyer) does this need support for the reflection transformation
1913 // as well?
[email protected]69db58f2018-09-26 20:27:561914 vfc_task_runner_->PostTask(
1915 FROM_HERE,
Ted Meyer4a427632019-05-01 19:05:271916 base::BindOnce(
1917 &VideoFrameCompositor::EnableSubmission,
1918 base::Unretained(compositor_.get()), bridge_->GetSurfaceId(),
1919 bridge_->GetLocalSurfaceIdAllocationTime(),
1920 pipeline_metadata_.video_decoder_config.video_transformation()
1921 .rotation,
1922 IsInPictureInPicture()));
[email protected]69db58f2018-09-26 20:27:561923 bridge_->SetContentsOpaque(opaque_);
1924
1925 // If the element is already in Picture-in-Picture mode, it means that it
1926 // was set in this mode prior to this load, with a different
1927 // WebMediaPlayerImpl. The new player needs to send its id, size and
1928 // surface id to the browser process to make sure the states are properly
1929 // updated.
1930 // TODO(872056): the surface should be activated but for some reasons, it
1931 // does not. It is possible that this will no longer be needed after 872056
1932 // is fixed.
Dale Curtisca1b78f2019-01-15 03:11:261933 if (IsInPictureInPicture())
[email protected]69db58f2018-09-26 20:27:561934 OnSurfaceIdUpdated(bridge_->GetSurfaceId());
[email protected]69db58f2018-09-26 20:27:561935}
1936
Chris Cunninghamfc0d67e2019-07-22 20:29:161937void WebMediaPlayerImpl::OnBufferingStateChange(
1938 BufferingState state,
1939 BufferingStateChangeReason reason) {
1940 OnBufferingStateChangeInternal(state, reason, false);
Dale Curtis2dc6089a2018-03-26 16:47:581941}
1942
Chris Cunninghamd9df58e2017-08-29 00:04:231943void WebMediaPlayerImpl::CreateVideoDecodeStatsReporter() {
1944 // TODO(chcunningham): destroy reporter if we initially have video but the
1945 // track gets disabled. Currently not possible in default desktop Chrome.
1946 if (!HasVideo())
1947 return;
1948
Chris Cunningham89b4b762019-03-27 17:13:331949 // Only record stats from the local pipeline.
1950 if (is_flinging_ || is_remote_rendering_ || using_media_player_renderer_)
1951 return;
1952
Chris Cunninghamd9df58e2017-08-29 00:04:231953 // Stats reporter requires a valid config. We may not have one for HLS cases
1954 // where URL demuxer doesn't know details of the stream.
1955 if (!pipeline_metadata_.video_decoder_config.IsValidConfig())
1956 return;
1957
Chris Cunningham6c0ec292019-04-04 18:31:111958 // Profile must be known for use as index to save the reported stats.
Chris Cunningham5b1b67eb2019-03-23 03:24:411959 if (pipeline_metadata_.video_decoder_config.profile() ==
1960 VIDEO_CODEC_PROFILE_UNKNOWN) {
1961 return;
1962 }
1963
Chris Cunningham6c0ec292019-04-04 18:31:111964 // CdmConfig must be provided for use as index to save encrypted stats.
1965 if (is_encrypted_ && !cdm_config_) {
Chris Cunninghamd9df58e2017-08-29 00:04:231966 return;
Chris Cunningham6c0ec292019-04-04 18:31:111967 } else if (cdm_config_) {
1968 DCHECK(!key_system_.empty());
1969 }
Chris Cunninghamd9df58e2017-08-29 00:04:231970
Gyuyoung Kima040bc52019-10-30 01:14:351971 mojo::PendingRemote<mojom::VideoDecodeStatsRecorder> recorder;
Dale Curtis7e8a510d2017-12-14 19:19:481972 media_metrics_provider_->AcquireVideoDecodeStatsRecorder(
Gyuyoung Kima040bc52019-10-30 01:14:351973 recorder.InitWithNewPipeAndPassReceiver());
Chris Cunninghamc7c6a6d2017-11-23 14:06:451974
Chris Cunninghamd9df58e2017-08-29 00:04:231975 // Create capabilities reporter and synchronize its initial state.
1976 video_decode_stats_reporter_.reset(new VideoDecodeStatsReporter(
Chris Cunninghamc7c6a6d2017-11-23 14:06:451977 std::move(recorder),
Chris Cunninghamd9df58e2017-08-29 00:04:231978 base::Bind(&WebMediaPlayerImpl::GetPipelineStatistics,
1979 base::Unretained(this)),
Chris Cunningham5b1b67eb2019-03-23 03:24:411980 pipeline_metadata_.video_decoder_config.profile(),
Chris Cunningham6c0ec292019-04-04 18:31:111981 pipeline_metadata_.natural_size, key_system_, cdm_config_,
Hajime Hoshib5a26ee2018-05-14 12:47:511982 frame_->GetTaskRunner(blink::TaskType::kInternalMedia)));
Chris Cunninghamd9df58e2017-08-29 00:04:231983
1984 if (delegate_->IsFrameHidden())
1985 video_decode_stats_reporter_->OnHidden();
1986 else
1987 video_decode_stats_reporter_->OnShown();
1988
1989 if (paused_)
1990 video_decode_stats_reporter_->OnPaused();
1991 else
1992 video_decode_stats_reporter_->OnPlaying();
1993}
1994
hubbeb2d3efd2017-05-05 23:26:381995void WebMediaPlayerImpl::OnProgress() {
Chris Watkins1ffabc5f2017-05-10 20:52:091996 DVLOG(4) << __func__;
Dale Curtisad645f72019-09-06 23:28:161997
1998 // See IsPrerollAttemptNeeded() for more details. We can't use that method
1999 // here since it considers |preroll_attempt_start_time_| and for OnProgress()
2000 // events we must make the attempt -- since there may not be another event.
2001 if (highest_ready_state_ < ReadyState::kReadyStateHaveFutureData) {
hubbeb2d3efd2017-05-05 23:26:382002 // Reset the preroll attempt clock.
2003 preroll_attempt_pending_ = true;
2004 preroll_attempt_start_time_ = base::TimeTicks();
2005
2006 // Clear any 'stale' flag and give the pipeline a chance to resume. If we
2007 // are already resumed, this will cause |preroll_attempt_start_time_| to
2008 // be set.
2009 delegate_->ClearStaleFlag(delegate_id_);
2010 UpdatePlayState();
2011 } else if (ready_state_ == ReadyState::kReadyStateHaveFutureData &&
2012 CanPlayThrough()) {
2013 SetReadyState(WebMediaPlayer::kReadyStateHaveEnoughData);
2014 }
2015}
2016
2017bool WebMediaPlayerImpl::CanPlayThrough() {
2018 if (!base::FeatureList::IsEnabled(kSpecCompliantCanPlayThrough))
2019 return true;
2020 if (chunk_demuxer_)
2021 return true;
Dale Curtis4841c712018-12-13 18:14:052022 if (data_source_ && data_source_->AssumeFullyBuffered())
hubbeb2d3efd2017-05-05 23:26:382023 return true;
2024 // If we're not currently downloading, we have as much buffer as
2025 // we're ever going to get, which means we say we can play through.
2026 if (network_state_ == WebMediaPlayer::kNetworkStateIdle)
2027 return true;
Antonio Gomes81b56552019-05-15 22:15:282028 return buffered_data_source_host_->CanPlayThrough(
hubbeb2d3efd2017-05-05 23:26:382029 base::TimeDelta::FromSecondsD(CurrentTime()),
2030 base::TimeDelta::FromSecondsD(Duration()),
2031 playback_rate_ == 0.0 ? 1.0 : playback_rate_);
2032}
2033
Dale Curtisff576552018-03-30 02:32:442034void WebMediaPlayerImpl::OnBufferingStateChangeInternal(
2035 BufferingState state,
Chris Cunninghamfc0d67e2019-07-22 20:29:162036 BufferingStateChangeReason reason,
Dale Curtisff576552018-03-30 02:32:442037 bool for_suspended_start) {
Chris Cunninghamfc0d67e2019-07-22 20:29:162038 DVLOG(1) << __func__ << "(" << state << ", " << reason << ")";
alokp967c902452016-05-06 05:21:372039 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]b8877772014-03-26 20:17:152040
Ted Meyer742212b82018-08-22 17:21:422041 // Ignore buffering state changes caused by back-to-back seeking, so as not
2042 // to assume the second seek has finished when it was only the first seek.
Antonio Gomes81b56552019-05-15 22:15:282043 if (pipeline_controller_->IsPendingSeek())
[email protected]ba7d5f92014-06-24 05:37:402044 return;
[email protected]b8877772014-03-26 20:17:152045
Dale Curtisff576552018-03-30 02:32:442046 auto log_event = media_log_->CreateBufferingStateChangedEvent(
Chris Cunninghamfc0d67e2019-07-22 20:29:162047 "pipeline_buffering_state", state, reason);
Dale Curtisff576552018-03-30 02:32:442048 log_event->params.SetBoolean("for_suspended_start", for_suspended_start);
2049 media_log_->AddEvent(std::move(log_event));
dalecurtis869bf2f2017-01-10 18:01:102050
Ted Meyerd5885f82019-07-16 19:19:172051 if (state == BUFFERING_HAVE_ENOUGH && !for_suspended_start)
2052 media_metrics_provider_->SetHaveEnough();
2053
chcunninghameb270c92016-07-15 01:00:452054 if (state == BUFFERING_HAVE_ENOUGH) {
John Chen5b164a02017-11-01 00:36:092055 TRACE_EVENT1("media", "WebMediaPlayerImpl::BufferingHaveEnough", "id",
2056 media_log_->id());
Dale Curtisff576552018-03-30 02:32:442057 // The SetReadyState() call below may clear
2058 // |skip_metrics_due_to_startup_suspend_| so report this first.
2059 if (!have_reported_time_to_play_ready_ &&
2060 !skip_metrics_due_to_startup_suspend_) {
2061 DCHECK(!for_suspended_start);
Dale Curtis3899090ea2018-01-12 00:10:352062 have_reported_time_to_play_ready_ = true;
2063 const base::TimeDelta elapsed = base::TimeTicks::Now() - load_start_time_;
2064 media_metrics_provider_->SetTimeToPlayReady(elapsed);
2065 RecordTimingUMA("Media.TimeToPlayReady", elapsed);
2066 }
[email protected]ba7d5f92014-06-24 05:37:402067
Dale Curtisff576552018-03-30 02:32:442068 // Warning: This call may be re-entrant.
2069 SetReadyState(CanPlayThrough() ? WebMediaPlayer::kReadyStateHaveEnoughData
2070 : WebMediaPlayer::kReadyStateHaveFutureData);
2071
Dale Curtis18ad391b2019-05-30 23:25:092072 // Let the DataSource know we have enough data -- this is the only function
2073 // during which we advance to (or past) the kReadyStateHaveEnoughData state.
2074 // It may use this information to update buffer sizes or release unused
2075 // network connections.
2076 MaybeUpdateBufferSizesForPlayback();
Dale Curtis04769ca2019-05-25 00:38:102077 if (mb_data_source_ && !client_->CouldPlayIfEnoughData()) {
2078 // For LazyLoad this will be handled during OnPipelineSuspended().
2079 if (for_suspended_start && did_lazy_load_)
2080 DCHECK(!have_enough_after_lazy_load_cb_.IsCancelled());
2081 else
2082 mb_data_source_->OnBufferingHaveEnough(false);
2083 }
dalecurtis849cf4b22015-03-27 18:35:452084
chcunninghameb270c92016-07-15 01:00:452085 // Blink expects a timeChanged() in response to a seek().
sandersd35d2c3f2017-01-14 02:04:422086 if (should_notify_time_changed_) {
2087 should_notify_time_changed_ = false;
Blink Reformat1c4d759e2017-04-09 16:34:542088 client_->TimeChanged();
sandersd35d2c3f2017-01-14 02:04:422089 }
dalecurtis0f0097a2015-12-01 17:40:472090
chcunninghameb270c92016-07-15 01:00:452091 // Once we have enough, start reporting the total memory usage. We'll also
2092 // report once playback starts.
2093 ReportMemoryUsage();
dalecurtis9d638a12016-08-30 06:20:552094
dalecurtis4f6d14d2017-02-22 17:42:222095 // Report the amount of time it took to leave the underflow state.
2096 if (underflow_timer_) {
Dale Curtisc9069622019-10-24 20:20:502097 auto elapsed = underflow_timer_->Elapsed();
2098 RecordUnderflowDuration(elapsed);
2099 watch_time_reporter_->OnUnderflowComplete(elapsed);
dalecurtis9d638a12016-08-30 06:20:552100 underflow_timer_.reset();
2101 }
chcunninghameb270c92016-07-15 01:00:452102 } else {
2103 // Buffering has underflowed.
2104 DCHECK_EQ(state, BUFFERING_HAVE_NOTHING);
dalecurtisacd77d62016-09-09 23:23:142105
dalecurtisd06eabc2017-02-24 23:43:292106 // Report the number of times we've entered the underflow state. Ensure we
2107 // only report the value when transitioning from HAVE_ENOUGH to
2108 // HAVE_NOTHING.
Dale Curtis6995b862017-05-31 22:20:082109 if (ready_state_ == WebMediaPlayer::kReadyStateHaveEnoughData &&
2110 !seeking_) {
dalecurtisacd77d62016-09-09 23:23:142111 underflow_timer_.reset(new base::ElapsedTimer());
Dale Curtis6995b862017-05-31 22:20:082112 watch_time_reporter_->OnUnderflow();
2113 }
dalecurtisacd77d62016-09-09 23:23:142114
chcunninghameb270c92016-07-15 01:00:452115 // It shouldn't be possible to underflow if we've not advanced past
2116 // HAVE_CURRENT_DATA.
Blink Reformat1c4d759e2017-04-09 16:34:542117 DCHECK_GT(highest_ready_state_, WebMediaPlayer::kReadyStateHaveCurrentData);
2118 SetReadyState(WebMediaPlayer::kReadyStateHaveCurrentData);
chcunninghameb270c92016-07-15 01:00:452119 }
sandersd50a635e2016-04-04 22:50:092120
2121 UpdatePlayState();
[email protected]b8877772014-03-26 20:17:152122}
2123
alokp967c902452016-05-06 05:21:372124void WebMediaPlayerImpl::OnDurationChange() {
acolwellb4034942014-08-28 15:42:432125 DCHECK(main_task_runner_->BelongsToCurrentThread());
alokp967c902452016-05-06 05:21:372126
John Delaney2371b452018-12-13 04:30:332127 if (frame_->IsAdSubframe()) {
2128 UMA_HISTOGRAM_CUSTOM_TIMES("Ads.Media.Duration", GetPipelineMediaDuration(),
2129 base::TimeDelta::FromMilliseconds(1),
2130 base::TimeDelta::FromDays(1),
2131 50 /* bucket_count */);
2132 }
2133
alokp967c902452016-05-06 05:21:372134 // TODO(sandersd): We should call delegate_->DidPlay() with the new duration,
2135 // especially if it changed from <5s to >5s.
Blink Reformat1c4d759e2017-04-09 16:34:542136 if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing)
alokp967c902452016-05-06 05:21:372137 return;
2138
Blink Reformat1c4d759e2017-04-09 16:34:542139 client_->DurationChanged();
Dale Curtisaebaeea2018-07-19 23:42:112140 if (watch_time_reporter_)
2141 watch_time_reporter_->OnDurationChanged(GetPipelineMediaDuration());
Becca Hughes7a85bf22019-07-24 16:16:582142
2143 // The duration has changed so we should update the media position state.
2144 UpdateMediaPositionState();
[email protected]81bb3322011-07-21 15:55:502145}
2146
alokp967c902452016-05-06 05:21:372147void WebMediaPlayerImpl::OnAddTextTrack(const TextTrackConfig& config,
2148 const AddTextTrackDoneCB& done_cb) {
acolwellb4034942014-08-28 15:42:432149 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]71537722013-05-23 06:47:532150
[email protected]8a561062013-11-22 01:19:312151 const WebInbandTextTrackImpl::Kind web_kind =
2152 static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
Blink Reformat1c4d759e2017-04-09 16:34:542153 const blink::WebString web_label = blink::WebString::FromUTF8(config.label());
[email protected]8a561062013-11-22 01:19:312154 const blink::WebString web_language =
Blink Reformat1c4d759e2017-04-09 16:34:542155 blink::WebString::FromUTF8(config.language());
2156 const blink::WebString web_id = blink::WebString::FromUTF8(config.id());
[email protected]71537722013-05-23 06:47:532157
dcheng3076abbf2016-04-22 20:42:392158 std::unique_ptr<WebInbandTextTrackImpl> web_inband_text_track(
henriks9cce5fa2014-12-12 09:35:302159 new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id));
[email protected]8a561062013-11-22 01:19:312160
Dale Curtisca1b78f2019-01-15 03:11:262161 std::unique_ptr<TextTrack> text_track(new TextTrackImpl(
dcheng652f5ff2015-12-27 08:54:002162 main_task_runner_, client_, std::move(web_inband_text_track)));
[email protected]8a561062013-11-22 01:19:312163
dcheng652f5ff2015-12-27 08:54:002164 done_cb.Run(std::move(text_track));
[email protected]71537722013-05-23 06:47:532165}
2166
Xiaohan Wang640b41d2018-12-18 19:00:462167void WebMediaPlayerImpl::OnWaiting(WaitingReason reason) {
alokp967c902452016-05-06 05:21:372168 DCHECK(main_task_runner_->BelongsToCurrentThread());
2169
Xiaohan Wang640b41d2018-12-18 19:00:462170 switch (reason) {
Xiaohan Wangb54a75282019-10-04 21:34:432171 case WaitingReason::kNoCdm:
Xiaohan Wang640b41d2018-12-18 19:00:462172 case WaitingReason::kNoDecryptionKey:
2173 encrypted_client_->DidBlockPlaybackWaitingForKey();
2174 // TODO(jrummell): didResumePlaybackBlockedForKey() should only be called
2175 // when a key has been successfully added (e.g. OnSessionKeysChange() with
2176 // |has_additional_usable_key| = true). http://crbug.com/461903
2177 encrypted_client_->DidResumePlaybackBlockedForKey();
2178 return;
Xiaohan Wang640b41d2018-12-18 19:00:462179
Xiaohan Wanga7224d62019-01-04 22:22:302180 // Ideally this should be handled by PipelineController directly without
2181 // being proxied here. But currently Pipeline::Client (|this|) is passed to
2182 // PipelineImpl directly without going through |pipeline_controller_|,
2183 // making it difficult to do.
2184 // TODO(xhwang): Handle this in PipelineController when we have a clearer
2185 // picture on how to refactor WebMediaPlayerImpl, PipelineController and
2186 // PipelineImpl.
2187 case WaitingReason::kDecoderStateLost:
Antonio Gomes81b56552019-05-15 22:15:282188 pipeline_controller_->OnDecoderStateLost();
Xiaohan Wanga7224d62019-01-04 22:22:302189 return;
2190 }
alokp967c902452016-05-06 05:21:372191}
2192
alokp5d86e9b2016-05-17 20:20:412193void WebMediaPlayerImpl::OnVideoNaturalSizeChange(const gfx::Size& size) {
2194 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:542195 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
alokp5d86e9b2016-05-17 20:20:412196
Chris Cunningham038548b2017-07-10 22:36:302197 TRACE_EVENT0("media", "WebMediaPlayerImpl::OnVideoNaturalSizeChange");
xhwang60802652017-04-19 07:29:582198
xjz15b483f2017-01-12 00:21:362199 // The input |size| is from the decoded video frame, which is the original
2200 // natural size and need to be rotated accordingly.
Julien Isorce6c83d8de2017-10-12 13:11:292201 gfx::Size rotated_size = GetRotatedVideoSize(
Ted Meyer4a427632019-05-01 19:05:272202 pipeline_metadata_.video_decoder_config.video_transformation().rotation,
2203 size);
sandersd2c478422016-08-02 01:19:252204
xhwang60802652017-04-19 07:29:582205 RecordVideoNaturalSize(rotated_size);
2206
2207 gfx::Size old_size = pipeline_metadata_.natural_size;
2208 if (rotated_size == old_size)
alokp5d86e9b2016-05-17 20:20:412209 return;
2210
xjz516ef6d2017-01-07 00:23:062211 pipeline_metadata_.natural_size = rotated_size;
Dan Sanders7ef5d0f2019-05-03 18:30:112212
2213 if (using_media_player_renderer_ && old_size.IsEmpty()) {
2214 // If we are using MediaPlayerRenderer and this is the first size change, we
2215 // now know that there is a video track. This condition is paired with code
2216 // in CreateWatchTimeReporter() that guesses the existence of a video track.
2217 CreateWatchTimeReporter();
2218 } else {
Dan Sanders7ef5d0f2019-05-03 18:30:112219 UpdateSecondaryProperties();
2220 }
dalecurtis25405562017-04-14 23:35:112221
Chris Cunningham5b1b67eb2019-03-23 03:24:412222 if (video_decode_stats_reporter_ &&
2223 !video_decode_stats_reporter_->MatchesBucketedNaturalSize(
2224 pipeline_metadata_.natural_size)) {
2225 CreateVideoDecodeStatsReporter();
2226 }
Chris Cunninghamd9df58e2017-08-29 00:04:232227
Blink Reformat1c4d759e2017-04-09 16:34:542228 client_->SizeChanged();
xjz516ef6d2017-01-07 00:23:062229
xjz15b483f2017-01-12 00:21:362230 if (observer_)
2231 observer_->OnMetadataChanged(pipeline_metadata_);
peconn257951522017-06-09 18:24:592232
2233 delegate_->DidPlayerSizeChange(delegate_id_, NaturalSize());
alokp5d86e9b2016-05-17 20:20:412234}
2235
2236void WebMediaPlayerImpl::OnVideoOpacityChange(bool opaque) {
2237 DCHECK(main_task_runner_->BelongsToCurrentThread());
Blink Reformat1c4d759e2017-04-09 16:34:542238 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
alokp5d86e9b2016-05-17 20:20:412239
2240 opaque_ = opaque;
Dale Curtis357630f22019-01-18 01:10:172241 if (!surface_layer_for_video_enabled_ && video_layer_)
2242 video_layer_->SetContentsOpaque(opaque_);
2243 else if (bridge_->GetCcLayer())
CJ DiMeglioa2b13fbc2018-06-27 00:50:592244 bridge_->SetContentsOpaque(opaque_);
alokp5d86e9b2016-05-17 20:20:412245}
2246
Chris Cunningham038548b2017-07-10 22:36:302247void WebMediaPlayerImpl::OnAudioConfigChange(const AudioDecoderConfig& config) {
2248 DCHECK(main_task_runner_->BelongsToCurrentThread());
2249 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
2250
Dale Curtisccfd0cca2017-08-31 01:27:562251 const bool codec_change =
2252 pipeline_metadata_.audio_decoder_config.codec() != config.codec();
Chris Cunningham038548b2017-07-10 22:36:302253 pipeline_metadata_.audio_decoder_config = config;
2254
2255 if (observer_)
2256 observer_->OnMetadataChanged(pipeline_metadata_);
Dale Curtisccfd0cca2017-08-31 01:27:562257
2258 if (codec_change)
Dale Curtis96d6e9382018-07-18 18:01:072259 UpdateSecondaryProperties();
Chris Cunningham038548b2017-07-10 22:36:302260}
2261
2262void WebMediaPlayerImpl::OnVideoConfigChange(const VideoDecoderConfig& config) {
2263 DCHECK(main_task_runner_->BelongsToCurrentThread());
2264 DCHECK_NE(ready_state_, WebMediaPlayer::kReadyStateHaveNothing);
2265
Dale Curtisccfd0cca2017-08-31 01:27:562266 const bool codec_change =
2267 pipeline_metadata_.video_decoder_config.codec() != config.codec();
Chris Cunningham5b1b67eb2019-03-23 03:24:412268 const bool codec_profile_change =
2269 pipeline_metadata_.video_decoder_config.profile() != config.profile();
Dale Curtisccfd0cca2017-08-31 01:27:562270
Chris Cunningham038548b2017-07-10 22:36:302271 pipeline_metadata_.video_decoder_config = config;
2272
2273 if (observer_)
2274 observer_->OnMetadataChanged(pipeline_metadata_);
Chris Cunninghamd9df58e2017-08-29 00:04:232275
Dale Curtisccfd0cca2017-08-31 01:27:562276 if (codec_change)
Dale Curtis96d6e9382018-07-18 18:01:072277 UpdateSecondaryProperties();
Chris Cunningham5b1b67eb2019-03-23 03:24:412278
2279 if (video_decode_stats_reporter_ && codec_profile_change)
2280 CreateVideoDecodeStatsReporter();
Chris Cunningham038548b2017-07-10 22:36:302281}
2282
avayvodeecec52c2017-02-14 01:25:092283void WebMediaPlayerImpl::OnVideoAverageKeyframeDistanceUpdate() {
2284 UpdateBackgroundVideoOptimizationState();
2285}
2286
Ted Meyerd5885f82019-07-16 19:19:172287void WebMediaPlayerImpl::OnAudioDecoderChange(const PipelineDecoderInfo& info) {
2288 media_metrics_provider_->SetAudioPipelineInfo(info);
2289 if (info.decoder_name == audio_decoder_name_)
Dale Curtisc7d2a7d22018-01-11 20:01:052290 return;
2291
Ted Meyerd5885f82019-07-16 19:19:172292 audio_decoder_name_ = info.decoder_name;
Dale Curtisc7d2a7d22018-01-11 20:01:052293
2294 // If there's no current reporter, there's nothing to be done.
2295 if (!watch_time_reporter_)
2296 return;
2297
Dale Curtis96d6e9382018-07-18 18:01:072298 UpdateSecondaryProperties();
Dale Curtisc7d2a7d22018-01-11 20:01:052299}
2300
Ted Meyerd5885f82019-07-16 19:19:172301void WebMediaPlayerImpl::OnVideoDecoderChange(const PipelineDecoderInfo& info) {
2302 media_metrics_provider_->SetVideoPipelineInfo(info);
2303 if (info.decoder_name == video_decoder_name_)
Dale Curtisc7d2a7d22018-01-11 20:01:052304 return;
2305
Ted Meyerd5885f82019-07-16 19:19:172306 video_decoder_name_ = info.decoder_name;
Dale Curtisc7d2a7d22018-01-11 20:01:052307
2308 // If there's no current reporter, there's nothing to be done.
2309 if (!watch_time_reporter_)
2310 return;
2311
Dale Curtis96d6e9382018-07-18 18:01:072312 UpdateSecondaryProperties();
Dale Curtisc7d2a7d22018-01-11 20:01:052313}
2314
sandersd35d2c3f2017-01-14 02:04:422315void WebMediaPlayerImpl::OnFrameHidden() {
sandersd1e49fb62015-12-12 01:18:062316 DCHECK(main_task_runner_->BelongsToCurrentThread());
avayvod39c102402016-11-23 21:43:132317
avayvod65fad272017-02-24 01:00:482318 // Backgrounding a video requires a user gesture to resume playback.
2319 if (IsHidden())
2320 video_locked_when_paused_when_hidden_ = true;
2321
dalecurtis04bdb582016-08-17 22:15:232322 if (watch_time_reporter_)
2323 watch_time_reporter_->OnHidden();
avayvod48a8be52016-08-04 19:52:502324
Chris Cunninghamd9df58e2017-08-29 00:04:232325 if (video_decode_stats_reporter_)
2326 video_decode_stats_reporter_->OnHidden();
2327
avayvod65fad272017-02-24 01:00:482328 UpdateBackgroundVideoOptimizationState();
sandersd50a635e2016-04-04 22:50:092329 UpdatePlayState();
dalecurtis8b8505e72016-06-10 21:59:172330
2331 // Schedule suspended playing media to be paused if the user doesn't come back
2332 // to it within some timeout period to avoid any autoplay surprises.
2333 ScheduleIdlePauseTimer();
Dale Curtisca1b78f2019-01-15 03:11:262334
2335 // Notify the compositor of our page visibility status.
2336 vfc_task_runner_->PostTask(
2337 FROM_HERE,
2338 base::BindOnce(&VideoFrameCompositor::SetIsPageVisible,
2339 base::Unretained(compositor_.get()), !IsHidden()));
sandersd1e49fb62015-12-12 01:18:062340}
2341
sandersd35d2c3f2017-01-14 02:04:422342void WebMediaPlayerImpl::OnFrameClosed() {
sandersd1e49fb62015-12-12 01:18:062343 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]28347e72017-06-27 17:30:112344
sandersd35d2c3f2017-01-14 02:04:422345 UpdatePlayState();
2346}
2347
2348void WebMediaPlayerImpl::OnFrameShown() {
2349 DCHECK(main_task_runner_->BelongsToCurrentThread());
2350 background_pause_timer_.Stop();
2351
avayvod65fad272017-02-24 01:00:482352 // Foreground videos don't require user gesture to continue playback.
2353 video_locked_when_paused_when_hidden_ = false;
2354
dalecurtis04bdb582016-08-17 22:15:232355 if (watch_time_reporter_)
2356 watch_time_reporter_->OnShown();
2357
Chris Cunninghamd9df58e2017-08-29 00:04:232358 if (video_decode_stats_reporter_)
2359 video_decode_stats_reporter_->OnShown();
2360
Dale Curtisca1b78f2019-01-15 03:11:262361 // Notify the compositor of our page visibility status.
2362 vfc_task_runner_->PostTask(
2363 FROM_HERE,
2364 base::BindOnce(&VideoFrameCompositor::SetIsPageVisible,
2365 base::Unretained(compositor_.get()), !IsHidden()));
2366
Dale Curtisdcbb81a2017-08-18 01:06:122367 UpdateBackgroundVideoOptimizationState();
avayvod65fad272017-02-24 01:00:482368
avayvod2135a642017-01-13 00:17:142369 if (paused_when_hidden_) {
2370 paused_when_hidden_ = false;
2371 OnPlay(); // Calls UpdatePlayState() so return afterwards.
2372 return;
2373 }
2374
sandersd50a635e2016-04-04 22:50:092375 UpdatePlayState();
sandersd1e49fb62015-12-12 01:18:062376}
2377
sandersd35d2c3f2017-01-14 02:04:422378void WebMediaPlayerImpl::OnIdleTimeout() {
dalecurtis0431cbf2016-03-12 01:19:432379 DCHECK(main_task_runner_->BelongsToCurrentThread());
2380
Dale Curtis99a9b482018-02-01 02:23:282381 // This should never be called when stale state testing overrides are used.
2382 DCHECK(!stale_state_override_for_testing_.has_value());
2383
sandersd35d2c3f2017-01-14 02:04:422384 // If we are attempting preroll, clear the stale flag.
2385 if (IsPrerollAttemptNeeded()) {
tguilbert1bb1c782017-01-23 21:15:112386 delegate_->ClearStaleFlag(delegate_id_);
sandersd35d2c3f2017-01-14 02:04:422387 return;
watkd026f792016-11-05 00:28:512388 }
sandersd50a635e2016-04-04 22:50:092389
sandersd35d2c3f2017-01-14 02:04:422390 UpdatePlayState();
dalecurtis0431cbf2016-03-12 01:19:432391}
2392
dalecurtisbb3eaac2016-01-27 21:10:252393void WebMediaPlayerImpl::OnPlay() {
Mounir Lamouri703106e2018-05-30 14:31:092394 client_->RequestPlay();
dalecurtisbb3eaac2016-01-27 21:10:252395}
2396
2397void WebMediaPlayerImpl::OnPause() {
Mounir Lamouri703106e2018-05-30 14:31:092398 client_->RequestPause();
dalecurtisbb3eaac2016-01-27 21:10:252399}
2400
François Beaufortb4fe7c62019-02-27 08:19:442401void WebMediaPlayerImpl::OnMuted(bool muted) {
2402 client_->RequestMuted(muted);
2403}
2404
Alec Douglas316cce42017-10-31 13:28:082405void WebMediaPlayerImpl::OnSeekForward(double seconds) {
2406 DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
2407 client_->RequestSeek(CurrentTime() + seconds);
2408}
2409
2410void WebMediaPlayerImpl::OnSeekBackward(double seconds) {
2411 DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
2412 client_->RequestSeek(CurrentTime() - seconds);
2413}
2414
dalecurtisbb3eaac2016-01-27 21:10:252415void WebMediaPlayerImpl::OnVolumeMultiplierUpdate(double multiplier) {
2416 volume_multiplier_ = multiplier;
Blink Reformat1c4d759e2017-04-09 16:34:542417 SetVolume(volume_);
dalecurtisbb3eaac2016-01-27 21:10:252418}
2419
zqzhang8ac49002017-03-16 21:51:352420void WebMediaPlayerImpl::OnBecamePersistentVideo(bool value) {
Blink Reformat1c4d759e2017-04-09 16:34:542421 client_->OnBecamePersistentVideo(value);
[email protected]6490e2d12019-01-14 19:18:372422 overlay_info_.is_persistent_video = value;
2423 MaybeSendOverlayInfoToDecoder();
zqzhang8ac49002017-03-16 21:51:352424}
2425
watkdee516f2016-02-18 02:22:192426void WebMediaPlayerImpl::ScheduleRestart() {
sandersd50a635e2016-04-04 22:50:092427 // TODO(watk): All restart logic should be moved into PipelineController.
Antonio Gomes81b56552019-05-15 22:15:282428 if (pipeline_controller_->IsPipelineRunning() &&
2429 !pipeline_controller_->IsPipelineSuspended()) {
watkdee516f2016-02-18 02:22:192430 pending_suspend_resume_cycle_ = true;
sandersd50a635e2016-04-04 22:50:092431 UpdatePlayState();
watkdee516f2016-02-18 02:22:192432 }
2433}
2434
Blink Reformat1c4d759e2017-04-09 16:34:542435void WebMediaPlayerImpl::RequestRemotePlaybackDisabled(bool disabled) {
miu77f914c2016-11-19 23:56:182436 if (observer_)
2437 observer_->OnRemotePlaybackDisabled(disabled);
2438}
2439
Thomas Guilbert7350fdad2019-01-29 23:09:242440#if defined(OS_ANDROID)
Thomas Guilbertb341bae02018-05-09 00:02:132441void WebMediaPlayerImpl::FlingingStarted() {
2442 DCHECK(main_task_runner_->BelongsToCurrentThread());
2443 DCHECK(!disable_pipeline_auto_suspend_);
2444 disable_pipeline_auto_suspend_ = true;
2445
Thomas Guilbert29ae1a902018-10-20 01:53:382446 is_flinging_ = true;
2447
Thomas Guilbertb341bae02018-05-09 00:02:132448 // Capabilities reporting should only be performed for local playbacks.
2449 video_decode_stats_reporter_.reset();
2450
2451 // Requests to restart media pipeline. A flinging renderer will be created via
2452 // the |renderer_factory_selector_|.
2453 ScheduleRestart();
2454}
2455
2456void WebMediaPlayerImpl::FlingingStopped() {
2457 DCHECK(main_task_runner_->BelongsToCurrentThread());
2458 DCHECK(disable_pipeline_auto_suspend_);
2459 disable_pipeline_auto_suspend_ = false;
2460
Thomas Guilbert29ae1a902018-10-20 01:53:382461 is_flinging_ = false;
2462
Thomas Guilbertb341bae02018-05-09 00:02:132463 CreateVideoDecodeStatsReporter();
2464
2465 ScheduleRestart();
2466}
Thomas Guilbert901808982019-07-03 20:38:182467
2468void WebMediaPlayerImpl::OnRemotePlayStateChange(MediaStatus::State state) {
2469 DCHECK(is_flinging_);
Thomas Guilbertf6d0702e2019-09-12 23:40:142470 DCHECK(main_task_runner_->BelongsToCurrentThread());
Thomas Guilbert901808982019-07-03 20:38:182471
2472 if (state == MediaStatus::State::PLAYING && Paused()) {
2473 DVLOG(1) << __func__ << " requesting PLAY.";
2474 client_->RequestPlay();
2475 } else if (state == MediaStatus::State::PAUSED && !Paused()) {
2476 DVLOG(1) << __func__ << " requesting PAUSE.";
2477 client_->RequestPause();
2478 }
2479}
Thomas Guilbert7350fdad2019-01-29 23:09:242480#endif // defined(OS_ANDROID)
hubbee4027f92016-05-19 05:18:132481
Blink Reformat1c4d759e2017-04-09 16:34:542482void WebMediaPlayerImpl::SetPoster(const blink::WebURL& poster) {
Dan Sanderscd8981c2017-08-31 22:37:022483 has_poster_ = !poster.IsEmpty();
Dan Sanderscd8981c2017-08-31 22:37:022484}
xjzc102fd82017-01-04 20:13:532485
[email protected]fee8a902014-06-03 13:43:362486void WebMediaPlayerImpl::DataSourceInitialized(bool success) {
pkastingf5279482016-07-27 02:18:202487 DVLOG(1) << __func__;
acolwellb4034942014-08-28 15:42:432488 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]a9415292012-01-19 19:55:202489
Thomas Guilberta8a6e922019-02-01 00:02:472490 if (observer_ && mb_data_source_)
Dale Curtis4841c712018-12-13 18:14:052491 observer_->OnDataSourceInitialized(mb_data_source_->GetUrlAfterRedirects());
Anton Vayvod09fa66e2017-07-20 23:02:122492
[email protected]d250190da3b2012-07-23 22:57:302493 if (!success) {
Blink Reformat1c4d759e2017-04-09 16:34:542494 SetNetworkState(WebMediaPlayer::kNetworkStateFormatError);
Dale Curtis74612b72017-12-14 20:56:192495 media_metrics_provider_->OnError(PIPELINE_ERROR_NETWORK);
sandersd50a635e2016-04-04 22:50:092496
2497 // Not really necessary, since the pipeline was never started, but it at
2498 // least this makes sure that the error handling code is in sync.
2499 UpdatePlayState();
2500
[email protected]a9415292012-01-19 19:55:202501 return;
2502 }
2503
hubbee2cc88c092017-07-14 23:10:412504 // No point in preloading data as we'll probably just throw it away anyways.
Dale Curtis4841c712018-12-13 18:14:052505 if (IsStreaming() && preload_ > MultibufferDataSource::METADATA &&
2506 mb_data_source_) {
2507 mb_data_source_->SetPreload(MultibufferDataSource::METADATA);
hubbee2cc88c092017-07-14 23:10:412508 }
2509
[email protected]ef8394c2013-08-21 20:26:302510 StartPipeline();
[email protected]a9415292012-01-19 19:55:202511}
2512
[email protected]122f40252012-06-12 05:01:562513void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
hubbeb2d3efd2017-05-05 23:26:382514 DVLOG(1) << __func__ << "(" << is_downloading << ")";
Blink Reformat1c4d759e2017-04-09 16:34:542515 if (!is_downloading && network_state_ == WebMediaPlayer::kNetworkStateLoading)
2516 SetNetworkState(WebMediaPlayer::kNetworkStateIdle);
2517 else if (is_downloading &&
2518 network_state_ == WebMediaPlayer::kNetworkStateIdle)
2519 SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
hubbeb2d3efd2017-05-05 23:26:382520 if (ready_state_ == ReadyState::kReadyStateHaveFutureData && !is_downloading)
2521 SetReadyState(WebMediaPlayer::kReadyStateHaveEnoughData);
[email protected]122f40252012-06-12 05:01:562522}
2523
liberato2ff93ad2017-05-17 07:28:242524void WebMediaPlayerImpl::OnOverlayRoutingToken(
2525 const base::UnguessableToken& token) {
2526 DCHECK(overlay_mode_ == OverlayMode::kUseAndroidOverlay);
liberatofe8f9692017-06-08 19:17:362527 // TODO(liberato): |token| should already be a RoutingToken.
2528 overlay_routing_token_is_pending_ = false;
2529 overlay_routing_token_ = OverlayInfo::RoutingToken(token);
liberato2ff93ad2017-05-17 07:28:242530 MaybeSendOverlayInfoToDecoder();
2531}
2532
2533void WebMediaPlayerImpl::OnOverlayInfoRequested(
dalecurtis4b632fce22016-11-10 00:52:172534 bool decoder_requires_restart_for_overlay,
liberato2ff93ad2017-05-17 07:28:242535 const ProvideOverlayInfoCB& provide_overlay_info_cb) {
watkdee516f2016-02-18 02:22:192536 DCHECK(main_task_runner_->BelongsToCurrentThread());
watkdee516f2016-02-18 02:22:192537
Chris Watkins557f84d2017-09-16 02:31:462538 // If we get a non-null cb, a decoder is initializing and requires overlay
2539 // info. If we get a null cb, a previously initialized decoder is
2540 // unregistering for overlay info updates.
Dale Curtise25163812018-09-21 22:13:392541 if (!provide_overlay_info_cb) {
tsunghungee562e92016-07-20 18:03:312542 decoder_requires_restart_for_overlay_ = false;
liberato2ff93ad2017-05-17 07:28:242543 provide_overlay_info_cb_.Reset();
watkdee516f2016-02-18 02:22:192544 return;
2545 }
2546
dalecurtis4b632fce22016-11-10 00:52:172547 // If |decoder_requires_restart_for_overlay| is true, we must restart the
2548 // pipeline for fullscreen transitions. The decoder is unable to switch
2549 // surfaces otherwise. If false, we simply need to tell the decoder about the
2550 // new surface and it will handle things seamlessly.
Chris Watkins557f84d2017-09-16 02:31:462551 // For encrypted video we pretend that the decoder doesn't require a restart
2552 // because it needs an overlay all the time anyway. We'll switch into
2553 // |always_enable_overlays_| mode below.
2554 decoder_requires_restart_for_overlay_ =
2555 (overlay_mode_ == OverlayMode::kUseAndroidOverlay && is_encrypted_)
2556 ? false
2557 : decoder_requires_restart_for_overlay;
liberato2ff93ad2017-05-17 07:28:242558 provide_overlay_info_cb_ = provide_overlay_info_cb;
dalecurtis4b632fce22016-11-10 00:52:172559
Chris Watkins557f84d2017-09-16 02:31:462560 // If the decoder doesn't require restarts for surface transitions, and we're
2561 // using AndroidOverlay mode, we can always enable the overlay and the decoder
2562 // can choose whether or not to use it. Otherwise, we'll restart the decoder
2563 // and enable the overlay on fullscreen transitions.
[email protected]77568482017-06-21 21:16:522564 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay &&
Chris Watkins557f84d2017-09-16 02:31:462565 !decoder_requires_restart_for_overlay_) {
[email protected]c8d574722017-08-30 20:53:432566 always_enable_overlays_ = true;
[email protected]77568482017-06-21 21:16:522567 if (!overlay_enabled_)
2568 EnableOverlay();
2569 }
2570
Chris Watkins557f84d2017-09-16 02:31:462571 // Send the overlay info if we already have it. If not, it will be sent later.
liberato2ff93ad2017-05-17 07:28:242572 MaybeSendOverlayInfoToDecoder();
2573}
2574
2575void WebMediaPlayerImpl::MaybeSendOverlayInfoToDecoder() {
2576 // If the decoder didn't request overlay info, then don't send it.
2577 if (!provide_overlay_info_cb_)
dalecurtis4b632fce22016-11-10 00:52:172578 return;
2579
liberato2ff93ad2017-05-17 07:28:242580 // We should send the overlay info as long as we know it. This includes the
2581 // case where |!overlay_enabled_|, since we want to tell the decoder to avoid
2582 // using overlays. Assuming that the decoder has requested info, the only
2583 // case in which we don't want to send something is if we've requested the
2584 // info but not received it yet. Then, we should wait until we do.
liberatofe8f9692017-06-08 19:17:362585 //
2586 // Initialization requires this; AVDA should start with enough info to make an
2587 // overlay, so that (pre-M) the initial codec is created with the right output
2588 // surface; it can't switch later.
[email protected]f7df5b342018-07-13 20:22:132589 if (overlay_mode_ == OverlayMode::kUseAndroidOverlay) {
liberatofe8f9692017-06-08 19:17:362590 if (overlay_routing_token_is_pending_)
liberato2ff93ad2017-05-17 07:28:242591 return;
liberatofe8f9692017-06-08 19:17:362592
2593 overlay_info_.routing_token = overlay_routing_token_;
liberato2ff93ad2017-05-17 07:28:242594 }
2595
liberato2ff93ad2017-05-17 07:28:242596 // If restart is required, the callback is one-shot only.
2597 if (decoder_requires_restart_for_overlay_) {
Dale Curtise25163812018-09-21 22:13:392598 std::move(provide_overlay_info_cb_).Run(overlay_info_);
liberato2ff93ad2017-05-17 07:28:242599 } else {
liberatofe8f9692017-06-08 19:17:362600 provide_overlay_info_cb_.Run(overlay_info_);
liberato2ff93ad2017-05-17 07:28:242601 }
watkdee516f2016-02-18 02:22:192602}
2603
Xiaohan Wang73b433f2019-11-05 20:13:012604void WebMediaPlayerImpl::CreateRenderer(RendererCreatedCB renderer_created_cb) {
dcheng37b415b92017-01-27 20:17:432605 DCHECK(main_task_runner_->BelongsToCurrentThread());
2606
[email protected]c8d574722017-08-30 20:53:432607 // Make sure that overlays are enabled if they're always allowed.
2608 if (always_enable_overlays_)
tsunghungee562e92016-07-20 18:03:312609 EnableOverlay();
2610
liberato2ff93ad2017-05-17 07:28:242611 RequestOverlayInfoCB request_overlay_info_cb;
watkdee516f2016-02-18 02:22:192612#if defined(OS_ANDROID)
liberato2ff93ad2017-05-17 07:28:242613 request_overlay_info_cb = BindToCurrentLoop(
Antonio Gomes142f32a2019-05-15 23:32:562614 base::Bind(&WebMediaPlayerImpl::OnOverlayInfoRequested, weak_this_));
watkdee516f2016-02-18 02:22:192615#endif
Dan Sanders6edfd782019-08-13 00:13:182616 reported_renderer_type_ = renderer_factory_selector_->GetCurrentFactoryType();
Xiaohan Wang73b433f2019-11-05 20:13:012617
2618 auto renderer =
2619 renderer_factory_selector_->GetCurrentFactory()->CreateRenderer(
2620 media_task_runner_, worker_task_runner_, audio_source_provider_.get(),
2621 compositor_.get(), request_overlay_info_cb,
2622 client_->TargetColorSpace());
2623
2624 std::move(renderer_created_cb).Run(std::move(renderer));
sandersd1e49fb62015-12-12 01:18:062625}
2626
[email protected]ef8394c2013-08-21 20:26:302627void WebMediaPlayerImpl::StartPipeline() {
acolwellb4034942014-08-28 15:42:432628 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]ddbc6ff2013-04-19 15:28:332629
xhwange8c4181a2014-12-06 08:10:012630 Demuxer::EncryptedMediaInitDataCB encrypted_media_init_data_cb =
dcheng37b415b92017-01-27 20:17:432631 BindToCurrentLoop(base::Bind(
Antonio Gomes142f32a2019-05-15 23:32:562632 &WebMediaPlayerImpl::OnEncryptedMediaInitData, weak_this_));
[email protected]2b57e2e2014-05-09 11:07:252633
Dale Curtis3899090ea2018-01-12 00:10:352634 vfc_task_runner_->PostTask(
2635 FROM_HERE,
2636 base::BindOnce(&VideoFrameCompositor::SetOnNewProcessedFrameCallback,
2637 base::Unretained(compositor_.get()),
2638 BindToCurrentLoop(base::BindOnce(
Antonio Gomes142f32a2019-05-15 23:32:562639 &WebMediaPlayerImpl::OnFirstFrame, weak_this_))));
Dale Curtis3899090ea2018-01-12 00:10:352640
Thomas Guilbert55b48d92019-03-25 23:16:542641#if defined(OS_ANDROID)
Dale Curtis65c151a2019-02-26 02:09:322642 if (demuxer_found_hls_ ||
2643 renderer_factory_selector_->GetCurrentFactory()
2644 ->GetRequiredMediaResourceType() == MediaResource::Type::URL) {
Thomas Guilbert8a42fcf2019-03-01 20:21:452645 // MediaPlayerRendererClientFactory is the only factory that a uses
2646 // MediaResource::Type::URL for the moment.
tguilbert75e2bf62017-04-26 20:13:122647 using_media_player_renderer_ = true;
2648
Chris Cunninghamd9df58e2017-08-29 00:04:232649 // MediaPlayerRenderer does not provide pipeline stats, so nuke capabilities
2650 // reporter.
2651 video_decode_stats_reporter_.reset();
2652
Thomas Guilbert55b48d92019-03-25 23:16:542653 demuxer_.reset(new MediaUrlDemuxer(
2654 media_task_runner_, loaded_url_, frame_->GetDocument().SiteForCookies(),
Christian Dullweberacff9bd32019-08-20 09:44:372655 frame_->GetDocument().TopFrameOrigin(),
Dan Sanders3ff9ffe2019-07-19 22:24:122656 allow_media_player_renderer_credentials_, demuxer_found_hls_));
Antonio Gomes81b56552019-05-15 22:15:282657 pipeline_controller_->Start(Pipeline::StartType::kNormal, demuxer_.get(),
2658 this, false, false);
tguilbert25a4d112016-10-13 21:56:512659 return;
2660 }
Thomas Guilbert55b48d92019-03-25 23:16:542661#endif // defined(OS_ANDROID)
tguilbert25a4d112016-10-13 21:56:512662
[email protected]ddbc6ff2013-04-19 15:28:332663 // Figure out which demuxer to use.
Blink Reformat1c4d759e2017-04-09 16:34:542664 if (load_type_ != kLoadTypeMediaSource) {
[email protected]ddbc6ff2013-04-19 15:28:332665 DCHECK(!chunk_demuxer_);
[email protected]f5443ef72013-04-22 04:03:382666 DCHECK(data_source_);
2667
Dale Curtisbcf523b2018-01-17 02:59:012668#if BUILDFLAG(ENABLE_FFMPEG)
servolk81e01e02016-03-05 03:29:152669 Demuxer::MediaTracksUpdatedCB media_tracks_updated_cb =
dcheng37b415b92017-01-27 20:17:432670 BindToCurrentLoop(base::Bind(
Antonio Gomes142f32a2019-05-15 23:32:562671 &WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated, weak_this_));
servolk81e01e02016-03-05 03:29:152672
dalecurtis9cddc0b2017-04-19 21:23:382673 demuxer_.reset(new FFmpegDemuxer(
2674 media_task_runner_, data_source_.get(), encrypted_media_init_data_cb,
Dale Curtisb8139f72018-08-27 23:28:482675 media_tracks_updated_cb, media_log_.get(), IsLocalFile(loaded_url_)));
j.isorcef6778e652015-11-16 17:14:252676#else
alokp967c902452016-05-06 05:21:372677 OnError(PipelineStatus::DEMUXER_ERROR_COULD_NOT_OPEN);
j.isorcef6778e652015-11-16 17:14:252678 return;
2679#endif
[email protected]ddbc6ff2013-04-19 15:28:332680 } else {
[email protected]f5443ef72013-04-22 04:03:382681 DCHECK(!chunk_demuxer_);
2682 DCHECK(!data_source_);
2683
Antonio Gomes142f32a2019-05-15 23:32:562684 chunk_demuxer_ =
2685 new ChunkDemuxer(BindToCurrentLoop(base::Bind(
2686 &WebMediaPlayerImpl::OnDemuxerOpened, weak_this_)),
2687 BindToCurrentLoop(base::Bind(
2688 &WebMediaPlayerImpl::OnProgress, weak_this_)),
2689 encrypted_media_init_data_cb, media_log_.get());
[email protected]f5443ef72013-04-22 04:03:382690 demuxer_.reset(chunk_demuxer_);
servolkf94b4602017-01-31 16:44:272691
2692 if (base::FeatureList::IsEnabled(kMemoryPressureBasedSourceBufferGC)) {
2693 // base::Unretained is safe because |this| owns memory_pressure_listener_.
2694 memory_pressure_listener_ =
Gyuyoung Kim62a5de42018-01-10 09:48:422695 std::make_unique<base::MemoryPressureListener>(base::Bind(
servolkf94b4602017-01-31 16:44:272696 &WebMediaPlayerImpl::OnMemoryPressure, base::Unretained(this)));
2697 }
[email protected]ddbc6ff2013-04-19 15:28:332698 }
2699
sandersdb5e21462016-03-09 01:49:072700 // TODO(sandersd): FileSystem objects may also be non-static, but due to our
2701 // caching layer such situations are broken already. http://crbug.com/593159
2702 bool is_static = !chunk_demuxer_;
avayvod102cdb62017-01-07 03:11:092703 bool is_streaming = IsStreaming();
sandersdb8eb5f1d2016-11-19 04:04:022704 UMA_HISTOGRAM_BOOLEAN("Media.IsStreaming", is_streaming);
sandersdb5e21462016-03-09 01:49:072705
Dale Curtis2dc6089a2018-03-26 16:47:582706 // If possible attempt to avoid decoder spool up until playback starts.
2707 Pipeline::StartType start_type = Pipeline::StartType::kNormal;
Dale Curtis7c63f2e22018-09-19 21:06:272708 if (!chunk_demuxer_ && preload_ == MultibufferDataSource::METADATA &&
Dale Curtisd6ccd1992019-04-29 19:03:462709 !client_->CouldPlayIfEnoughData() && !IsStreaming()) {
Dale Curtis7c63f2e22018-09-19 21:06:272710 start_type =
2711 (has_poster_ || base::FeatureList::IsEnabled(kPreloadMetadataLazyLoad))
2712 ? Pipeline::StartType::kSuspendAfterMetadata
2713 : Pipeline::StartType::kSuspendAfterMetadataForAudioOnly;
Dale Curtis2dc6089a2018-03-26 16:47:582714 attempting_suspended_start_ = true;
2715 }
2716
[email protected]f5443ef72013-04-22 04:03:382717 // ... and we're ready to go!
sandersd1e49fb62015-12-12 01:18:062718 // TODO(sandersd): On Android, defer Start() if the tab is not visible.
sandersdb8eb5f1d2016-11-19 04:04:022719 seeking_ = true;
Antonio Gomes81b56552019-05-15 22:15:282720 pipeline_controller_->Start(start_type, demuxer_.get(), this, is_streaming,
2721 is_static);
[email protected]f5443ef72013-04-22 04:03:382722}
2723
2724void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState 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 network_state_ = state;
2728 // Always notify to ensure client has the latest value.
Blink Reformat1c4d759e2017-04-09 16:34:542729 client_->NetworkStateChanged();
[email protected]f5443ef72013-04-22 04:03:382730}
2731
2732void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state) {
pkastingf5279482016-07-27 02:18:202733 DVLOG(1) << __func__ << "(" << state << ")";
acolwellb4034942014-08-28 15:42:432734 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]f5443ef72013-04-22 04:03:382735
Blink Reformat1c4d759e2017-04-09 16:34:542736 if (state == WebMediaPlayer::kReadyStateHaveEnoughData && data_source_ &&
Dale Curtis4841c712018-12-13 18:14:052737 data_source_->AssumeFullyBuffered() &&
2738 network_state_ == WebMediaPlayer::kNetworkStateLoading) {
Blink Reformat1c4d759e2017-04-09 16:34:542739 SetNetworkState(WebMediaPlayer::kNetworkStateLoaded);
Dale Curtis4841c712018-12-13 18:14:052740 }
[email protected]f5443ef72013-04-22 04:03:382741
2742 ready_state_ = state;
sandersd50a635e2016-04-04 22:50:092743 highest_ready_state_ = std::max(highest_ready_state_, ready_state_);
2744
[email protected]f5443ef72013-04-22 04:03:382745 // Always notify to ensure client has the latest value.
Blink Reformat1c4d759e2017-04-09 16:34:542746 client_->ReadyStateChanged();
[email protected]f5443ef72013-04-22 04:03:382747}
2748
Antonio Gomesa38bb7cb2019-05-31 03:02:522749scoped_refptr<blink::WebAudioSourceProviderImpl>
2750WebMediaPlayerImpl::GetAudioSourceProvider() {
2751 return audio_source_provider_;
[email protected]f5443ef72013-04-22 04:03:382752}
2753
Jiajia Qin82acdc02017-07-31 09:55:142754scoped_refptr<VideoFrame> WebMediaPlayerImpl::GetCurrentFrameFromCompositor()
2755 const {
xhwang213e50c2016-10-10 23:56:312756 DCHECK(main_task_runner_->BelongsToCurrentThread());
[email protected]dd061e12014-05-06 19:21:222757 TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor");
xhwang213e50c2016-10-10 23:56:312758
Thomas Guilberte90fe312019-11-07 22:27:562759 if (current_frame_override_)
2760 return current_frame_override_;
2761
Thomas Guilbertd85407412017-11-08 05:03:462762 // Can be null.
2763 scoped_refptr<VideoFrame> video_frame =
2764 compositor_->GetCurrentFrameOnAnyThread();
[email protected]dd061e12014-05-06 19:21:222765
Thomas Guilbertd85407412017-11-08 05:03:462766 // base::Unretained is safe here because |compositor_| is destroyed on
2767 // |vfc_task_runner_|. The destruction is queued from |this|' destructor,
2768 // which also runs on |main_task_runner_|, which makes it impossible for
2769 // UpdateCurrentFrameIfStale() to be queued after |compositor_|'s dtor.
CJ DiMeglio2302d202017-08-31 08:38:042770 vfc_task_runner_->PostTask(
Dale Curtisee9be30012018-09-21 22:21:512771 FROM_HERE,
2772 base::BindOnce(&VideoFrameCompositor::UpdateCurrentFrameIfStale,
2773 base::Unretained(compositor_.get())));
kainino36eeff82017-03-30 00:55:302774
[email protected]dd061e12014-05-06 19:21:222775 return video_frame;
2776}
2777
sandersd50a635e2016-04-04 22:50:092778void WebMediaPlayerImpl::UpdatePlayState() {
xhwang213e50c2016-10-10 23:56:312779 DCHECK(main_task_runner_->BelongsToCurrentThread());
hubbee2cc88c092017-07-14 23:10:412780 bool can_auto_suspend = !disable_pipeline_auto_suspend_;
2781 // For streaming videos, we only allow suspending at the very beginning of the
2782 // video, and only if we know the length of the video. (If we don't know
2783 // the length, it might be a dynamically generated video, and suspending
2784 // will not work at all.)
2785 if (IsStreaming()) {
2786 bool at_beginning =
2787 ready_state_ == WebMediaPlayer::kReadyStateHaveNothing ||
2788 CurrentTime() == 0.0;
2789 if (!at_beginning || GetPipelineMediaDuration() == kInfiniteDuration)
2790 can_auto_suspend = false;
2791 }
xhwang213e50c2016-10-10 23:56:312792
Antonio Gomes81b56552019-05-15 22:15:282793 bool is_suspended = pipeline_controller_->IsSuspended();
Sergey Volk8b09c2c52018-12-12 23:20:402794 bool is_backgrounded = IsBackgroundSuspendEnabled(this) && IsHidden();
sandersdaaff1a652016-11-17 01:47:252795 PlayState state = UpdatePlayState_ComputePlayState(
Thomas Guilbert7350fdad2019-01-29 23:09:242796 is_flinging_, can_auto_suspend, is_suspended, is_backgrounded);
sandersd35d2c3f2017-01-14 02:04:422797 SetDelegateState(state.delegate_state, state.is_idle);
sandersd50a635e2016-04-04 22:50:092798 SetMemoryReportingState(state.is_memory_reporting_enabled);
2799 SetSuspendState(state.is_suspended || pending_suspend_resume_cycle_);
2800}
dalecurtis5bbc487e2016-02-27 04:15:052801
Becca Hughes7a85bf22019-07-24 16:16:582802void WebMediaPlayerImpl::UpdateMediaPositionState() {
2803 DCHECK(delegate_);
2804
2805 // When seeking the current time can go beyond the duration so we should
2806 // cap the current time at the duration.
2807 base::TimeDelta duration = GetPipelineMediaDuration();
2808 base::TimeDelta current_time = GetCurrentTimeInternal();
2809 if (current_time > duration)
2810 current_time = duration;
2811
2812 media_session::MediaPosition new_position(paused_ ? 0.0 : playback_rate_,
2813 duration, current_time);
2814
2815 if (media_position_state_ == new_position)
2816 return;
2817
2818 DVLOG(2) << __func__ << "(" << new_position.ToString() << ")";
2819 media_position_state_ = new_position;
2820 delegate_->DidPlayerMediaPositionStateChange(delegate_id_,
2821 media_position_state_);
2822}
2823
sandersd35d2c3f2017-01-14 02:04:422824void WebMediaPlayerImpl::SetDelegateState(DelegateState new_state,
2825 bool is_idle) {
tguilbert1bb1c782017-01-23 21:15:112826 DCHECK(delegate_);
Dale Curtis779ed842018-03-10 06:20:132827 DVLOG(2) << __func__ << "(" << static_cast<int>(new_state) << ", " << is_idle
2828 << ")";
dalecurtis5bbc487e2016-02-27 04:15:052829
sandersd35d2c3f2017-01-14 02:04:422830 // Prevent duplicate delegate calls.
2831 // TODO(sandersd): Move this deduplication into the delegate itself.
2832 // TODO(sandersd): WebContentsObserverSanityChecker does not allow sending the
2833 // 'playing' IPC more than once in a row, even if the metadata has changed.
2834 // Figure out whether it should.
Mounir Lamouri366dd8472018-06-19 17:20:042835 // Pretend that the media has no audio if it never played unmuted. This is to
2836 // avoid any action related to audible media such as taking audio focus or
2837 // showing a media notification. To preserve a consistent experience, it does
2838 // not apply if a media was audible so the system states do not flicker
2839 // depending on whether the user muted the player.
2840 bool has_audio = HasAudio() && !client_->WasAlwaysMuted();
sandersd35d2c3f2017-01-14 02:04:422841 if (delegate_state_ == new_state &&
2842 (delegate_state_ != DelegateState::PLAYING ||
2843 delegate_has_audio_ == has_audio)) {
2844 return;
mlamouri910111362016-11-04 11:28:242845 }
sandersd50a635e2016-04-04 22:50:092846 delegate_state_ = new_state;
sandersd35d2c3f2017-01-14 02:04:422847 delegate_has_audio_ = has_audio;
sandersd50a635e2016-04-04 22:50:092848
sandersd35d2c3f2017-01-14 02:04:422849 switch (new_state) {
sandersd50a635e2016-04-04 22:50:092850 case DelegateState::GONE:
2851 delegate_->PlayerGone(delegate_id_);
2852 break;
mlamouri910111362016-11-04 11:28:242853 case DelegateState::PLAYING: {
peconn257951522017-06-09 18:24:592854 if (HasVideo())
2855 delegate_->DidPlayerSizeChange(delegate_id_, NaturalSize());
zqzhang5d8eab72016-08-26 20:34:302856 delegate_->DidPlay(
Blink Reformat1c4d759e2017-04-09 16:34:542857 delegate_id_, HasVideo(), has_audio,
Dale Curtisca1b78f2019-01-15 03:11:262858 DurationToMediaContentType(GetPipelineMediaDuration()));
sandersd50a635e2016-04-04 22:50:092859 break;
mlamouri910111362016-11-04 11:28:242860 }
sandersd50a635e2016-04-04 22:50:092861 case DelegateState::PAUSED:
sandersd35d2c3f2017-01-14 02:04:422862 delegate_->DidPause(delegate_id_);
sandersd50a635e2016-04-04 22:50:092863 break;
dalecurtis0f0097a2015-12-01 17:40:472864 }
sandersd35d2c3f2017-01-14 02:04:422865
2866 delegate_->SetIdle(delegate_id_, is_idle);
dalecurtis0f0097a2015-12-01 17:40:472867}
2868
sandersd50a635e2016-04-04 22:50:092869void WebMediaPlayerImpl::SetMemoryReportingState(
2870 bool is_memory_reporting_enabled) {
2871 if (memory_usage_reporting_timer_.IsRunning() ==
2872 is_memory_reporting_enabled) {
hubbed5f36882016-01-15 22:40:372873 return;
sandersd50a635e2016-04-04 22:50:092874 }
sandersd1c0bba02016-03-04 23:14:082875
sandersd50a635e2016-04-04 22:50:092876 if (is_memory_reporting_enabled) {
2877 memory_usage_reporting_timer_.Start(FROM_HERE,
2878 base::TimeDelta::FromSeconds(2), this,
2879 &WebMediaPlayerImpl::ReportMemoryUsage);
2880 } else {
2881 memory_usage_reporting_timer_.Stop();
2882 ReportMemoryUsage();
2883 }
2884}
2885
2886void WebMediaPlayerImpl::SetSuspendState(bool is_suspended) {
xhwang213e50c2016-10-10 23:56:312887 DCHECK(main_task_runner_->BelongsToCurrentThread());
Dale Curtis779ed842018-03-10 06:20:132888 DVLOG(2) << __func__ << "(" << is_suspended << ")";
xhwang213e50c2016-10-10 23:56:312889
sandersd50a635e2016-04-04 22:50:092890 // Do not change the state after an error has occurred.
2891 // TODO(sandersd): Update PipelineController to remove the need for this.
2892 if (IsNetworkStateError(network_state_))
sandersd1c0bba02016-03-04 23:14:082893 return;
2894
jameswest451a5bb2017-01-27 03:59:392895 if (is_suspended) {
sandersd35d2c3f2017-01-14 02:04:422896 // If we were not resumed for long enough to satisfy the preroll attempt,
2897 // reset the clock.
2898 if (!preroll_attempt_pending_ && IsPrerollAttemptNeeded()) {
2899 preroll_attempt_pending_ = true;
2900 preroll_attempt_start_time_ = base::TimeTicks();
2901 }
Antonio Gomes81b56552019-05-15 22:15:282902 pipeline_controller_->Suspend();
sandersd50a635e2016-04-04 22:50:092903 } else {
sandersd35d2c3f2017-01-14 02:04:422904 // When resuming, start the preroll attempt clock.
2905 if (preroll_attempt_pending_) {
2906 preroll_attempt_pending_ = false;
2907 preroll_attempt_start_time_ = tick_clock_->NowTicks();
2908 }
Antonio Gomes81b56552019-05-15 22:15:282909 pipeline_controller_->Resume();
sandersd50a635e2016-04-04 22:50:092910 }
2911}
2912
2913WebMediaPlayerImpl::PlayState
Thomas Guilbert7350fdad2019-01-29 23:09:242914WebMediaPlayerImpl::UpdatePlayState_ComputePlayState(bool is_flinging,
xjz4e5d4bf32017-02-15 21:26:352915 bool can_auto_suspend,
dalecurtis8b8505e72016-06-10 21:59:172916 bool is_suspended,
sandersd50a635e2016-04-04 22:50:092917 bool is_backgrounded) {
2918 PlayState result;
2919
tguilbert1bb1c782017-01-23 21:15:112920 bool must_suspend = delegate_->IsFrameClosed();
Dale Curtis6438cf12018-03-29 02:34:012921 bool is_stale = delegate_->IsStale(delegate_id_);
2922
2923 if (stale_state_override_for_testing_.has_value() &&
2924 ready_state_ >= stale_state_override_for_testing_.value()) {
2925 is_stale = true;
2926 }
sandersd35d2c3f2017-01-14 02:04:422927
sandersd50a635e2016-04-04 22:50:092928 // This includes both data source (before pipeline startup) and pipeline
2929 // errors.
2930 bool has_error = IsNetworkStateError(network_state_);
2931
Dale Curtisc56158c2019-09-09 23:00:322932 // Note: Even though we get play/pause signals at kReadyStateHaveMetadata, we
2933 // must attempt to preroll until kReadyStateHaveFutureData so that the
2934 // canplaythrough event will be fired to the page (which may be waiting).
2935 bool have_future_data =
2936 highest_ready_state_ >= WebMediaPlayer::kReadyStateHaveFutureData;
sandersd50a635e2016-04-04 22:50:092937
avayvod65fad272017-02-24 01:00:482938 // Background suspend is only enabled for paused players.
2939 // In the case of players with audio the session should be kept.
2940 bool background_suspended =
Dale Curtisc56158c2019-09-09 23:00:322941 can_auto_suspend && is_backgrounded && paused_ && have_future_data;
sandersd50a635e2016-04-04 22:50:092942
Dale Curtisd71061f02019-05-21 21:33:542943 // Idle suspension is allowed prior to kReadyStateHaveMetadata since there
2944 // exist mechanisms to exit the idle state when the player is capable of
2945 // reaching the kReadyStateHaveMetadata state; see didLoadingProgress().
dalecurtiscc8baf72016-10-27 01:49:442946 //
sandersd50a635e2016-04-04 22:50:092947 // TODO(sandersd): Make the delegate suspend idle players immediately when
2948 // hidden.
Dale Curtis7c63f2e22018-09-19 21:06:272949 bool idle_suspended = can_auto_suspend && is_stale && paused_ && !seeking_ &&
2950 !overlay_enabled_ && !needs_first_frame_;
dalecurtise7120dc2016-09-03 02:54:352951
2952 // If we're already suspended, see if we can wait for user interaction. Prior
Dale Curtisd71061f02019-05-21 21:33:542953 // to kReadyStateHaveMetadata, we require |is_stale| to remain suspended.
2954 // |is_stale| will be cleared when we receive data which may take us to
2955 // kReadyStateHaveMetadata.
Dale Curtisc56158c2019-09-09 23:00:322956 bool can_stay_suspended = (is_stale || have_future_data) && is_suspended &&
Dale Curtis7c63f2e22018-09-19 21:06:272957 paused_ && !seeking_ && !needs_first_frame_;
sandersd50a635e2016-04-04 22:50:092958
2959 // Combined suspend state.
Thomas Guilbert7350fdad2019-01-29 23:09:242960 result.is_suspended = must_suspend || idle_suspended ||
avayvod65fad272017-02-24 01:00:482961 background_suspended || can_stay_suspended;
sandersd50a635e2016-04-04 22:50:092962
Thomas Guilbert7350fdad2019-01-29 23:09:242963 DVLOG(3) << __func__ << ": must_suspend=" << must_suspend
Dale Curtis779ed842018-03-10 06:20:132964 << ", idle_suspended=" << idle_suspended
2965 << ", background_suspended=" << background_suspended
2966 << ", can_stay_suspended=" << can_stay_suspended
Dale Curtisc56158c2019-09-09 23:00:322967 << ", is_stale=" << is_stale
2968 << ", have_future_data=" << have_future_data
Dale Curtis779ed842018-03-10 06:20:132969 << ", paused_=" << paused_ << ", seeking_=" << seeking_;
2970
sandersd50a635e2016-04-04 22:50:092971 // We do not treat |playback_rate_| == 0 as paused. For the media session,
2972 // being paused implies displaying a play button, which is incorrect in this
2973 // case. For memory usage reporting, we just use the same definition (but we
2974 // don't have to).
2975 //
2976 // Similarly, we don't consider |ended_| to be paused. Blink will immediately
2977 // call pause() or seek(), so |ended_| should not affect the computation.
2978 // Despite that, |ended_| does result in a separate paused state, to simplfy
2979 // the contract for SetDelegateState().
2980 //
avayvod65fad272017-02-24 01:00:482981 // |has_remote_controls| indicates if the player can be controlled outside the
2982 // page (e.g. via the notification controls or by audio focus events). Idle
sandersd50a635e2016-04-04 22:50:092983 // suspension does not destroy the media session, because we expect that the
avayvod5f34b642017-03-23 03:14:042984 // notification controls (and audio focus) remain. With some exceptions for
2985 // background videos, the player only needs to have audio to have controls
Dale Curtisd71061f02019-05-21 21:33:542986 // (requires |have_current_data|).
avayvod5f34b642017-03-23 03:14:042987 //
2988 // |alive| indicates if the player should be present (not |GONE|) to the
2989 // delegate, either paused or playing. The following must be true for the
2990 // player:
Dale Curtisd71061f02019-05-21 21:33:542991 // - |have_current_data|, since playback can't begin before that point, we
2992 // need to know whether we are paused to correctly configure the session,
2993 // and also because the tracks and duration are passed to DidPlay(),
Thomas Guilbert7350fdad2019-01-29 23:09:242994 // - |is_flinging| is false (RemotePlayback is not handled by the delegate)
avayvod5f34b642017-03-23 03:14:042995 // - |has_error| is false as player should have no errors,
2996 // - |background_suspended| is false, otherwise |has_remote_controls| must
2997 // be true.
sandersd50a635e2016-04-04 22:50:092998 //
avayvod65fad272017-02-24 01:00:482999 // TODO(sandersd): If Blink told us the paused state sooner, we could detect
3000 // if the remote controls are available sooner.
3001
3002 // Background videos with audio don't have remote controls if background
3003 // suspend is enabled and resuming background videos is not (original Android
3004 // behavior).
3005 bool backgrounded_video_has_no_remote_controls =
Sergey Volk8b09c2c52018-12-12 23:20:403006 IsBackgroundSuspendEnabled(this) && !IsResumeBackgroundVideosEnabled() &&
3007 is_backgrounded && HasVideo();
Dale Curtisd71061f02019-05-21 21:33:543008 bool have_current_data = highest_ready_state_ >= kReadyStateHaveCurrentData;
3009 bool can_play = !has_error && have_current_data;
avayvod5f34b642017-03-23 03:14:043010 bool has_remote_controls =
Blink Reformat1c4d759e2017-04-09 16:34:543011 HasAudio() && !backgrounded_video_has_no_remote_controls;
Thomas Guilbert7350fdad2019-01-29 23:09:243012 bool alive = can_play && !is_flinging && !must_suspend &&
avayvod5f34b642017-03-23 03:14:043013 (!background_suspended || has_remote_controls);
3014 if (!alive) {
Thomas Guilbert4c6feff2018-11-09 19:53:323015 // Do not mark players as idle when flinging.
sandersd50a635e2016-04-04 22:50:093016 result.delegate_state = DelegateState::GONE;
Thomas Guilbert4c6feff2018-11-09 19:53:323017 result.is_idle = delegate_->IsIdle(delegate_id_) && !is_flinging;
avayvod65fad272017-02-24 01:00:483018 } else if (paused_) {
sandersd35d2c3f2017-01-14 02:04:423019 // TODO(sandersd): Is it possible to have a suspended session, be ended,
3020 // and not be paused? If so we should be in a PLAYING state.
dalecurtise7120dc2016-09-03 02:54:353021 result.delegate_state =
sandersd35d2c3f2017-01-14 02:04:423022 ended_ ? DelegateState::GONE : DelegateState::PAUSED;
3023 result.is_idle = !seeking_;
sandersd50a635e2016-04-04 22:50:093024 } else {
3025 result.delegate_state = DelegateState::PLAYING;
sandersd35d2c3f2017-01-14 02:04:423026 result.is_idle = false;
sandersd50a635e2016-04-04 22:50:093027 }
3028
dalecurtis8b8505e72016-06-10 21:59:173029 // It's not critical if some cases where memory usage can change are missed,
sandersd50a635e2016-04-04 22:50:093030 // since media memory changes are usually gradual.
Thomas Guilbert7350fdad2019-01-29 23:09:243031 result.is_memory_reporting_enabled = !has_error && can_play && !is_flinging &&
3032 !result.is_suspended &&
3033 (!paused_ || seeking_);
sandersd50a635e2016-04-04 22:50:093034
3035 return result;
dalecurtis0f0097a2015-12-01 17:40:473036}
3037
dalecurtis83266c72015-10-29 18:43:203038void WebMediaPlayerImpl::ReportMemoryUsage() {
3039 DCHECK(main_task_runner_->BelongsToCurrentThread());
3040
wdzierzanowskifd4cd91c52015-12-02 23:50:203041 // About base::Unretained() usage below: We destroy |demuxer_| on the main
3042 // thread. Before that, however, ~WebMediaPlayerImpl() posts a task to the
3043 // media thread and waits for it to finish. Hence, the GetMemoryUsage() task
3044 // posted here must finish earlier.
Dale Curtis8a6281322017-08-31 00:35:533045 //
3046 // The exception to the above is when OnError() has been called. If we're in
3047 // the error state we've already shut down the pipeline and can't rely on it
3048 // to cycle the media thread before we destroy |demuxer_|. In this case skip
3049 // collection of the demuxer memory stats.
3050 if (demuxer_ && !IsNetworkStateError(network_state_)) {
wdzierzanowskifd4cd91c52015-12-02 23:50:203051 base::PostTaskAndReplyWithResult(
3052 media_task_runner_.get(), FROM_HERE,
3053 base::Bind(&Demuxer::GetMemoryUsage, base::Unretained(demuxer_.get())),
Antonio Gomes142f32a2019-05-15 23:32:563054 base::Bind(&WebMediaPlayerImpl::FinishMemoryUsageReport, weak_this_));
wdzierzanowskifd4cd91c52015-12-02 23:50:203055 } else {
3056 FinishMemoryUsageReport(0);
3057 }
3058}
3059
3060void WebMediaPlayerImpl::FinishMemoryUsageReport(int64_t demuxer_memory_usage) {
3061 DCHECK(main_task_runner_->BelongsToCurrentThread());
3062
avayvodc4bfb0e62017-01-13 01:07:013063 const PipelineStatistics stats = GetPipelineStatistics();
servolk639473e492016-12-15 04:14:203064 const int64_t data_source_memory_usage =
3065 data_source_ ? data_source_->GetMemoryUsage() : 0;
dalecurtisecc76612017-04-19 00:31:203066
Dale Curtisc2c5dcb12018-04-16 23:21:293067 // If we have video and no video memory usage and we've rendered the first
3068 // frame, assume the VideoFrameCompositor is holding onto the last frame after
3069 // we've suspended the pipeline; which thus reports zero memory usage from the
3070 // video renderer.
dalecurtisecc76612017-04-19 00:31:203071 //
3072 // Technically this should use the coded size, but that requires us to hop to
3073 // the compositor to get and byte-perfect accuracy isn't important here.
3074 const int64_t video_memory_usage =
3075 stats.video_memory_usage +
Dale Curtisc2c5dcb12018-04-16 23:21:293076 ((pipeline_metadata_.has_video && !stats.video_memory_usage &&
3077 has_first_frame_)
Miguel Casas9e7766022018-01-08 16:13:133078 ? VideoFrame::AllocationSize(PIXEL_FORMAT_I420,
dalecurtisecc76612017-04-19 00:31:203079 pipeline_metadata_.natural_size)
3080 : 0);
3081
dalecurtis83266c72015-10-29 18:43:203082 const int64_t current_memory_usage =
dalecurtisecc76612017-04-19 00:31:203083 stats.audio_memory_usage + video_memory_usage + data_source_memory_usage +
3084 demuxer_memory_usage;
dalecurtis83266c72015-10-29 18:43:203085
dalecurtisecc76612017-04-19 00:31:203086 DVLOG(2) << "Memory Usage -- Total: " << current_memory_usage
3087 << " Audio: " << stats.audio_memory_usage
3088 << ", Video: " << video_memory_usage
servolk639473e492016-12-15 04:14:203089 << ", DataSource: " << data_source_memory_usage
wdzierzanowskifd4cd91c52015-12-02 23:50:203090 << ", Demuxer: " << demuxer_memory_usage;
dalecurtis83266c72015-10-29 18:43:203091
3092 const int64_t delta = current_memory_usage - last_reported_memory_usage_;
3093 last_reported_memory_usage_ = current_memory_usage;
3094 adjust_allocated_memory_cb_.Run(delta);
servolk639473e492016-12-15 04:14:203095
Blink Reformat1c4d759e2017-04-09 16:34:543096 if (HasAudio()) {
servolk639473e492016-12-15 04:14:203097 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.Audio",
3098 stats.audio_memory_usage / 1024);
3099 }
Blink Reformat1c4d759e2017-04-09 16:34:543100 if (HasVideo()) {
servolk639473e492016-12-15 04:14:203101 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.Video",
dalecurtisecc76612017-04-19 00:31:203102 video_memory_usage / 1024);
servolk639473e492016-12-15 04:14:203103 }
3104 if (data_source_) {
3105 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.DataSource",
3106 data_source_memory_usage / 1024);
3107 }
3108 if (demuxer_) {
3109 UMA_HISTOGRAM_MEMORY_KB("Media.WebMediaPlayerImpl.Memory.Demuxer",
3110 demuxer_memory_usage / 1024);
3111 }
dalecurtis83266c72015-10-29 18:43:203112}
3113
dalecurtis8b8505e72016-06-10 21:59:173114void WebMediaPlayerImpl::ScheduleIdlePauseTimer() {
avayvod65fad272017-02-24 01:00:483115 // Only schedule the pause timer if we're not paused or paused but going to
avayvod52efd282017-03-07 21:13:043116 // resume when foregrounded, and are suspended and have audio.
3117 if ((paused_ && !paused_when_hidden_) ||
Antonio Gomes81b56552019-05-15 22:15:283118 !pipeline_controller_->IsSuspended() || !HasAudio()) {
dalecurtis8b8505e72016-06-10 21:59:173119 return;
avayvod52efd282017-03-07 21:13:043120 }
dalecurtis8b8505e72016-06-10 21:59:173121
3122#if defined(OS_ANDROID)
Thomas Guilbert7350fdad2019-01-29 23:09:243123 // Don't pause videos casted as part of RemotePlayback.
3124 if (is_flinging_)
dalecurtis8b8505e72016-06-10 21:59:173125 return;
3126#endif
3127
3128 // Idle timeout chosen arbitrarily.
3129 background_pause_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(5),
3130 this, &WebMediaPlayerImpl::OnPause);
3131}
3132
dalecurtis04bdb582016-08-17 22:15:233133void WebMediaPlayerImpl::CreateWatchTimeReporter() {
wdzierzanowskia78fa9b2017-06-13 18:12:103134 if (!HasVideo() && !HasAudio())
3135 return;
3136
Dan Sanders7ef5d0f2019-05-03 18:30:113137 // MediaPlayerRenderer does not know about tracks until playback starts.
3138 // Assume audio-only unless the natural size has been detected.
3139 bool has_video = pipeline_metadata_.has_video;
3140 if (using_media_player_renderer_) {
3141 has_video = !pipeline_metadata_.natural_size.IsEmpty();
3142 }
3143
dalecurtis04bdb582016-08-17 22:15:233144 // Create the watch time reporter and synchronize its initial state.
Dale Curtis1adbe6a2017-08-02 02:09:133145 watch_time_reporter_.reset(new WatchTimeReporter(
Dan Sanders7ef5d0f2019-05-03 18:30:113146 mojom::PlaybackProperties::New(
3147 pipeline_metadata_.has_audio, has_video, false, false,
3148 !!chunk_demuxer_, is_encrypted_, embedded_media_experience_enabled_),
Dale Curtis96d6e9382018-07-18 18:01:073149 pipeline_metadata_.natural_size,
Dale Curtis051fdf62017-08-05 00:21:133150 base::BindRepeating(&WebMediaPlayerImpl::GetCurrentTimeInternal,
3151 base::Unretained(this)),
Dale Curtis0f8d7b32019-10-24 22:10:283152 base::BindRepeating(&WebMediaPlayerImpl::GetPipelineStatistics,
3153 base::Unretained(this)),
Hajime Hoshi8bb37dc2017-12-19 09:35:103154 media_metrics_provider_.get(),
Hajime Hoshib5a26ee2018-05-14 12:47:513155 frame_->GetTaskRunner(blink::TaskType::kInternalMedia)));
dalecurtis04bdb582016-08-17 22:15:233156 watch_time_reporter_->OnVolumeChange(volume_);
Dale Curtisaebaeea2018-07-19 23:42:113157 watch_time_reporter_->OnDurationChanged(GetPipelineMediaDuration());
Mounir Lamourif9af74e72017-06-19 19:31:453158
tguilbert1bb1c782017-01-23 21:15:113159 if (delegate_->IsFrameHidden())
dalecurtis04bdb582016-08-17 22:15:233160 watch_time_reporter_->OnHidden();
3161 else
3162 watch_time_reporter_->OnShown();
Mounir Lamourif9af74e72017-06-19 19:31:453163
Mounir Lamouri41a79c62017-06-06 12:53:163164 if (client_->HasNativeControls())
3165 watch_time_reporter_->OnNativeControlsEnabled();
3166 else
3167 watch_time_reporter_->OnNativeControlsDisabled();
Mounir Lamourif9af74e72017-06-19 19:31:453168
3169 switch (client_->DisplayType()) {
3170 case WebMediaPlayer::DisplayType::kInline:
3171 watch_time_reporter_->OnDisplayTypeInline();
3172 break;
3173 case WebMediaPlayer::DisplayType::kFullscreen:
3174 watch_time_reporter_->OnDisplayTypeFullscreen();
3175 break;
3176 case WebMediaPlayer::DisplayType::kPictureInPicture:
3177 watch_time_reporter_->OnDisplayTypePictureInPicture();
3178 break;
3179 }
Dale Curtis96d6e9382018-07-18 18:01:073180
3181 UpdateSecondaryProperties();
Dale Curtis7fd27c4b2018-07-30 22:14:213182
3183 // If the WatchTimeReporter was recreated in the middle of playback, we want
3184 // to resume playback here too since we won't get another play() call. When
3185 // seeking, the seek completion will restart it if necessary.
3186 if (!paused_ && !seeking_)
3187 watch_time_reporter_->OnPlaying();
Dale Curtis96d6e9382018-07-18 18:01:073188}
3189
3190void WebMediaPlayerImpl::UpdateSecondaryProperties() {
3191 watch_time_reporter_->UpdateSecondaryProperties(
3192 mojom::SecondaryPlaybackProperties::New(
3193 pipeline_metadata_.audio_decoder_config.codec(),
Dale Curtis7140b502019-10-23 20:34:423194 pipeline_metadata_.video_decoder_config.codec(),
3195 pipeline_metadata_.video_decoder_config.profile(),
3196 audio_decoder_name_, video_decoder_name_,
Yuchen Liub33bfc12019-11-08 20:16:123197 pipeline_metadata_.audio_decoder_config.encryption_scheme(),
3198 pipeline_metadata_.video_decoder_config.encryption_scheme(),
John Rummelld30555352018-09-21 20:47:253199 pipeline_metadata_.natural_size));
dalecurtis04bdb582016-08-17 22:15:233200}
3201
avayvod39c102402016-11-23 21:43:133202bool WebMediaPlayerImpl::IsHidden() const {
3203 DCHECK(main_task_runner_->BelongsToCurrentThread());
3204
tguilbert1bb1c782017-01-23 21:15:113205 return delegate_->IsFrameHidden() && !delegate_->IsFrameClosed();
avayvod39c102402016-11-23 21:43:133206}
3207
avayvod102cdb62017-01-07 03:11:093208bool WebMediaPlayerImpl::IsStreaming() const {
3209 return data_source_ && data_source_->IsStreaming();
3210}
3211
liberato2fd111be2017-01-04 00:25:063212bool WebMediaPlayerImpl::DoesOverlaySupportMetadata() const {
Ted Meyer4a427632019-05-01 19:05:273213 return pipeline_metadata_.video_decoder_config.video_transformation() ==
3214 kNoTransformation;
liberato2fd111be2017-01-04 00:25:063215}
3216
xjzaf29d4182016-12-16 01:52:323217void WebMediaPlayerImpl::ActivateViewportIntersectionMonitoring(bool activate) {
3218 DCHECK(main_task_runner_->BelongsToCurrentThread());
3219
Blink Reformat1c4d759e2017-04-09 16:34:543220 client_->ActivateViewportIntersectionMonitoring(activate);
xjzaf29d4182016-12-16 01:52:323221}
3222
Anton Vayvod09fa66e2017-07-20 23:02:123223void WebMediaPlayerImpl::UpdateRemotePlaybackCompatibility(bool is_compatible) {
3224 DCHECK(main_task_runner_->BelongsToCurrentThread());
3225
3226 client_->RemotePlaybackCompatibilityChanged(loaded_url_, is_compatible);
3227}
3228
Dale Curtis6438cf12018-03-29 02:34:013229void WebMediaPlayerImpl::ForceStaleStateForTesting(ReadyState target_state) {
3230 stale_state_override_for_testing_.emplace(target_state);
Dale Curtis99a9b482018-02-01 02:23:283231 UpdatePlayState();
3232}
3233
3234bool WebMediaPlayerImpl::IsSuspendedForTesting() {
3235 // This intentionally uses IsPipelineSuspended since we need to know when the
3236 // pipeline has reached the suspended state, not when it's in suspending.
Antonio Gomes81b56552019-05-15 22:15:283237 return pipeline_controller_->IsPipelineSuspended();
Dale Curtis99a9b482018-02-01 02:23:283238}
3239
Dale Curtis7c63f2e22018-09-19 21:06:273240bool WebMediaPlayerImpl::DidLazyLoad() const {
3241 return did_lazy_load_;
3242}
3243
3244void WebMediaPlayerImpl::OnBecameVisible() {
Dale Curtis04769ca2019-05-25 00:38:103245 have_enough_after_lazy_load_cb_.Cancel();
Dale Curtis7c63f2e22018-09-19 21:06:273246 needs_first_frame_ = !has_first_frame_;
3247 UpdatePlayState();
3248}
3249
Miguel Casasfb63a5792018-12-04 23:50:413250bool WebMediaPlayerImpl::IsOpaque() const {
3251 return opaque_;
3252}
3253
Mounir Lamouri99ba5a62019-02-12 01:27:473254int WebMediaPlayerImpl::GetDelegateId() {
3255 return delegate_id_;
3256}
3257
3258base::Optional<viz::SurfaceId> WebMediaPlayerImpl::GetSurfaceId() {
3259 if (!surface_layer_for_video_enabled_)
3260 return base::nullopt;
3261 return bridge_->GetSurfaceId();
3262}
3263
Thomas Guilberte90fe312019-11-07 22:27:563264void WebMediaPlayerImpl::RequestAnimationFrame() {
3265 vfc_task_runner_->PostTask(
3266 FROM_HERE,
3267 base::BindOnce(&VideoFrameCompositor::SetOnFramePresentedCallback,
3268 base::Unretained(compositor_.get()),
3269 BindToCurrentLoop(base::BindOnce(
3270 &WebMediaPlayerImpl::OnNewFramePresentedCallback,
3271 weak_factory_.GetWeakPtr()))));
3272}
3273
3274void WebMediaPlayerImpl::OnNewFramePresentedCallback(
3275 scoped_refptr<VideoFrame> presented_frame,
3276 base::TimeTicks presentation_time,
3277 base::TimeTicks expected_presentation_time,
3278 uint32_t presentation_counter) {
3279 current_frame_override_ = std::move(presented_frame);
3280 client_->OnRequestAnimationFrame(
3281 presentation_time, expected_presentation_time, presentation_counter,
3282 *current_frame_override_);
3283 current_frame_override_.reset();
3284}
3285
Antonio Gomes142f32a2019-05-15 23:32:563286base::WeakPtr<blink::WebMediaPlayer> WebMediaPlayerImpl::AsWeakPtr() {
3287 return weak_this_;
3288}
3289
Yuchen Liue7813972019-04-12 22:34:243290bool WebMediaPlayerImpl::ShouldPausePlaybackWhenHidden() const {
3291 // Audio only stream is allowed to play when in background.
3292 // TODO: We should check IsBackgroundOptimizationCandidate here. But we need
3293 // to move the logic of checking video frames out of that function.
3294 if (!HasVideo())
3295 return false;
3296
Junbo Kefba620b2019-01-16 02:54:363297 if (!is_background_video_playback_enabled_)
3298 return true;
3299
avayvod65fad272017-02-24 01:00:483300 // If suspending background video, pause any video that's not remoted or
3301 // not unlocked to play in the background.
Sergey Volk8b09c2c52018-12-12 23:20:403302 if (IsBackgroundSuspendEnabled(this)) {
avayvod65fad272017-02-24 01:00:483303#if defined(OS_ANDROID)
Thomas Guilbert7350fdad2019-01-29 23:09:243304 if (is_flinging_)
avayvod65fad272017-02-24 01:00:483305 return false;
avayvodcc273dd2017-01-19 19:35:123306#endif
avayvodeb9098d2017-01-07 00:33:033307
Blink Reformat1c4d759e2017-04-09 16:34:543308 return !HasAudio() || (IsResumeBackgroundVideosEnabled() &&
3309 video_locked_when_paused_when_hidden_);
avayvod65fad272017-02-24 01:00:483310 }
3311
3312 // Otherwise only pause if the optimization is on and it's a video-only
3313 // optimization candidate.
avayvod01201332017-04-14 00:27:153314 return IsBackgroundVideoPauseOptimizationEnabled() && !HasAudio() &&
Thomas Guilbert29ae1a902018-10-20 01:53:383315 IsBackgroundOptimizationCandidate() && !is_flinging_;
avayvodeb9098d2017-01-07 00:33:033316}
3317
avayvod2135a642017-01-13 00:17:143318bool WebMediaPlayerImpl::ShouldDisableVideoWhenHidden() const {
Ted Meyera918e592018-09-08 00:16:203319 // This optimization is behind the flag on all platforms, only for non-mse
3320 // video. MSE video track switching on hide has gone through a field test.
3321 // TODO(tmathmeyer): Passing load_type_ won't be needed after src= field
3322 // testing is finished. see: http://crbug.com/709302
Ted Meyer0e105992019-05-04 01:47:213323 if (!is_background_video_track_optimization_supported_)
avayvodc4bfb0e62017-01-13 01:07:013324 return false;
avayvodc4bfb0e62017-01-13 01:07:013325
avayvodcc273dd2017-01-19 19:35:123326 // Disable video track only for players with audio that match the criteria for
3327 // being optimized.
Blink Reformat1c4d759e2017-04-09 16:34:543328 return HasAudio() && IsBackgroundOptimizationCandidate();
avayvodcc273dd2017-01-19 19:35:123329}
3330
3331bool WebMediaPlayerImpl::IsBackgroundOptimizationCandidate() const {
3332 DCHECK(main_task_runner_->BelongsToCurrentThread());
3333
François Beaufort664c3ca72018-04-13 07:24:513334 // Don't optimize Picture-in-Picture players.
Mounir Lamouri0484f40a2018-07-25 03:03:263335 if (IsInPictureInPicture())
François Beaufort664c3ca72018-04-13 07:24:513336 return false;
3337
Thomas Guilbert7350fdad2019-01-29 23:09:243338#if defined(OS_ANDROID)
3339 // Don't optimize videos casted as part of RemotePlayback.
3340 if (is_flinging_)
avayvodcc273dd2017-01-19 19:35:123341 return false;
Thomas Guilbert7350fdad2019-01-29 23:09:243342#endif
avayvodcc273dd2017-01-19 19:35:123343
3344 // Don't optimize audio-only or streaming players.
Blink Reformat1c4d759e2017-04-09 16:34:543345 if (!HasVideo() || IsStreaming())
avayvodcc273dd2017-01-19 19:35:123346 return false;
3347
Dale Curtis3f4935b2017-09-09 00:11:593348 // Video-only players are always optimized (paused).
3349 // Don't check the keyframe distance and duration.
3350 if (!HasAudio() && HasVideo())
3351 return true;
3352
avayvodcc273dd2017-01-19 19:35:123353 // Videos shorter than the maximum allowed keyframe distance can be optimized.
3354 base::TimeDelta duration = GetPipelineMediaDuration();
Ted Meyera918e592018-09-08 00:16:203355
Dale Curtis456808a2018-10-23 17:50:213356 constexpr base::TimeDelta kMaxKeyframeDistanceToDisableBackgroundVideo =
3357 base::TimeDelta::FromMilliseconds(
3358 kMaxKeyframeDistanceToDisableBackgroundVideoMs);
3359 if (duration < kMaxKeyframeDistanceToDisableBackgroundVideo)
avayvodcc273dd2017-01-19 19:35:123360 return true;
3361
3362 // Otherwise, only optimize videos with shorter average keyframe distance.
avayvodc4bfb0e62017-01-13 01:07:013363 PipelineStatistics stats = GetPipelineStatistics();
Dale Curtis456808a2018-10-23 17:50:213364 return stats.video_keyframe_distance_average <
3365 kMaxKeyframeDistanceToDisableBackgroundVideo;
avayvod2135a642017-01-13 00:17:143366}
3367
avayvod56e1f3942017-01-21 02:06:313368void WebMediaPlayerImpl::UpdateBackgroundVideoOptimizationState() {
3369 if (IsHidden()) {
Yuchen Liue7813972019-04-12 22:34:243370 if (ShouldPausePlaybackWhenHidden()) {
avayvod56e1f3942017-01-21 02:06:313371 PauseVideoIfNeeded();
Dale Curtisa75a7892017-08-09 20:21:513372 } else if (update_background_status_cb_.IsCancelled()) {
3373 // Only trigger updates when we don't have one already scheduled.
3374 update_background_status_cb_.Reset(
3375 base::Bind(&WebMediaPlayerImpl::DisableVideoTrackIfNeeded,
3376 base::Unretained(this)));
3377
3378 // Defer disable track until we're sure the clip will be backgrounded for
3379 // some time. Resuming may take half a second, so frequent tab switches
3380 // will yield a poor user experience otherwise. http://crbug.com/709302
3381 // may also cause AV sync issues if disable/enable happens too fast.
3382 main_task_runner_->PostDelayedTask(
3383 FROM_HERE, update_background_status_cb_.callback(),
3384 base::TimeDelta::FromSeconds(10));
3385 }
avayvod56e1f3942017-01-21 02:06:313386 } else {
Dale Curtisa75a7892017-08-09 20:21:513387 update_background_status_cb_.Cancel();
avayvod56e1f3942017-01-21 02:06:313388 EnableVideoTrackIfNeeded();
3389 }
3390}
3391
3392void WebMediaPlayerImpl::PauseVideoIfNeeded() {
3393 DCHECK(IsHidden());
3394
3395 // Don't pause video while the pipeline is stopped, resuming or seeking.
3396 // Also if the video is paused already.
Antonio Gomes81b56552019-05-15 22:15:283397 if (!pipeline_controller_->IsPipelineRunning() || is_pipeline_resuming_ ||
tguilbert350936ff2017-02-24 05:39:273398 seeking_ || paused_)
avayvod56e1f3942017-01-21 02:06:313399 return;
3400
3401 // OnPause() will set |paused_when_hidden_| to false and call
3402 // UpdatePlayState(), so set the flag to true after and then return.
3403 OnPause();
3404 paused_when_hidden_ = true;
3405}
3406
avayvod2135a642017-01-13 00:17:143407void WebMediaPlayerImpl::EnableVideoTrackIfNeeded() {
avayvod56e1f3942017-01-21 02:06:313408 // Don't change video track while the pipeline is stopped, resuming or
3409 // seeking.
Antonio Gomes81b56552019-05-15 22:15:283410 if (!pipeline_controller_->IsPipelineRunning() || is_pipeline_resuming_ ||
tguilbert350936ff2017-02-24 05:39:273411 seeking_)
avayvod2135a642017-01-13 00:17:143412 return;
3413
3414 if (video_track_disabled_) {
3415 video_track_disabled_ = false;
Blink Reformat1c4d759e2017-04-09 16:34:543416 if (client_->HasSelectedVideoTrack()) {
3417 WebMediaPlayer::TrackId trackId = client_->GetSelectedVideoTrackId();
3418 SelectedVideoTrackChanged(&trackId);
avayvod2135a642017-01-13 00:17:143419 }
3420 }
3421}
3422
3423void WebMediaPlayerImpl::DisableVideoTrackIfNeeded() {
3424 DCHECK(IsHidden());
3425
3426 // Don't change video track while the pipeline is resuming or seeking.
3427 if (is_pipeline_resuming_ || seeking_)
3428 return;
3429
3430 if (!video_track_disabled_ && ShouldDisableVideoWhenHidden()) {
3431 video_track_disabled_ = true;
Blink Reformat1c4d759e2017-04-09 16:34:543432 SelectedVideoTrackChanged(nullptr);
avayvod2135a642017-01-13 00:17:143433 }
3434}
3435
avayvodc4bfb0e62017-01-13 01:07:013436void WebMediaPlayerImpl::SetPipelineStatisticsForTest(
3437 const PipelineStatistics& stats) {
3438 pipeline_statistics_for_test_ = base::make_optional(stats);
3439}
3440
3441PipelineStatistics WebMediaPlayerImpl::GetPipelineStatistics() const {
3442 DCHECK(main_task_runner_->BelongsToCurrentThread());
3443
tguilbert350936ff2017-02-24 05:39:273444 return pipeline_statistics_for_test_.value_or(
Antonio Gomes81b56552019-05-15 22:15:283445 pipeline_controller_->GetStatistics());
avayvodc4bfb0e62017-01-13 01:07:013446}
3447
avayvodcc273dd2017-01-19 19:35:123448void WebMediaPlayerImpl::SetPipelineMediaDurationForTest(
3449 base::TimeDelta duration) {
3450 pipeline_media_duration_for_test_ = base::make_optional(duration);
3451}
3452
3453base::TimeDelta WebMediaPlayerImpl::GetPipelineMediaDuration() const {
3454 DCHECK(main_task_runner_->BelongsToCurrentThread());
3455
3456 return pipeline_media_duration_for_test_.value_or(
Antonio Gomes81b56552019-05-15 22:15:283457 pipeline_controller_->GetMediaDuration());
avayvodcc273dd2017-01-19 19:35:123458}
3459
Xiangjun Zhangba8724f482017-08-03 06:43:253460void WebMediaPlayerImpl::SwitchToRemoteRenderer(
3461 const std::string& remote_device_friendly_name) {
xjz4e5d4bf32017-02-15 21:26:353462 DCHECK(main_task_runner_->BelongsToCurrentThread());
Chris Cunningham89b4b762019-03-27 17:13:333463
3464 DCHECK(!is_remote_rendering_);
3465 is_remote_rendering_ = true;
3466
Thomas Guilbertb341bae02018-05-09 00:02:133467 DCHECK(!disable_pipeline_auto_suspend_);
Xiangjun Zhangba8724f482017-08-03 06:43:253468 disable_pipeline_auto_suspend_ = true;
Chris Cunninghamd9df58e2017-08-29 00:04:233469
3470 // Capabilities reporting should only be performed for local playbacks.
3471 video_decode_stats_reporter_.reset();
3472
Xiangjun Zhangba8724f482017-08-03 06:43:253473 // Requests to restart media pipeline. A remote renderer will be created via
3474 // the |renderer_factory_selector_|.
xjz4e5d4bf32017-02-15 21:26:353475 ScheduleRestart();
xjzdf9b67e2017-04-13 23:28:253476 if (client_) {
Xiangjun Zhangba8724f482017-08-03 06:43:253477 client_->MediaRemotingStarted(
3478 WebString::FromUTF8(remote_device_friendly_name));
xjzdf9b67e2017-04-13 23:28:253479 }
xjz4e5d4bf32017-02-15 21:26:353480}
3481
Xiangjun Zhang5e20cba42018-01-10 19:54:563482void WebMediaPlayerImpl::SwitchToLocalRenderer(
3483 MediaObserverClient::ReasonToSwitchToLocal reason) {
Xiangjun Zhangba8724f482017-08-03 06:43:253484 DCHECK(main_task_runner_->BelongsToCurrentThread());
Chris Cunningham89b4b762019-03-27 17:13:333485 if (!is_remote_rendering_)
Xiangjun Zhang12f55272018-07-30 23:19:373486 return; // Is currently with local renderer.
Chris Cunningham89b4b762019-03-27 17:13:333487 is_remote_rendering_ = false;
3488
3489 DCHECK(disable_pipeline_auto_suspend_);
Xiangjun Zhangba8724f482017-08-03 06:43:253490 disable_pipeline_auto_suspend_ = false;
Chris Cunninghamd9df58e2017-08-29 00:04:233491
3492 // Capabilities reporting may resume now that playback is local.
3493 CreateVideoDecodeStatsReporter();
3494
Xiangjun Zhangba8724f482017-08-03 06:43:253495 // Requests to restart media pipeline. A local renderer will be created via
3496 // the |renderer_factory_selector_|.
3497 ScheduleRestart();
3498 if (client_)
Xiangjun Zhang5e20cba42018-01-10 19:54:563499 client_->MediaRemotingStopped(GetSwitchToLocalMessage(reason));
Xiangjun Zhangba8724f482017-08-03 06:43:253500}
3501
dalecurtis4f6d14d2017-02-22 17:42:223502void WebMediaPlayerImpl::RecordUnderflowDuration(base::TimeDelta duration) {
3503 DCHECK(data_source_ || chunk_demuxer_);
xhwang68b3fab82017-05-17 21:31:463504
dalecurtis4f6d14d2017-02-22 17:42:223505 if (data_source_)
Jennifer Apacible82e25c92017-08-07 18:15:273506 UMA_HISTOGRAM_TIMES("Media.UnderflowDuration2.SRC", duration);
dalecurtis4f6d14d2017-02-22 17:42:223507 else
Jennifer Apacible82e25c92017-08-07 18:15:273508 UMA_HISTOGRAM_TIMES("Media.UnderflowDuration2.MSE", duration);
xhwang68b3fab82017-05-17 21:31:463509
3510 if (is_encrypted_)
Jennifer Apacible82e25c92017-08-07 18:15:273511 UMA_HISTOGRAM_TIMES("Media.UnderflowDuration2.EME", duration);
dalecurtis4f6d14d2017-02-22 17:42:223512}
3513
xhwang60802652017-04-19 07:29:583514#define UMA_HISTOGRAM_VIDEO_HEIGHT(name, sample) \
3515 UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 100, 10000, 50)
3516
3517void WebMediaPlayerImpl::RecordVideoNaturalSize(const gfx::Size& natural_size) {
3518 // Always report video natural size to MediaLog.
3519 media_log_->AddEvent(media_log_->CreateVideoSizeSetEvent(
3520 natural_size.width(), natural_size.height()));
3521
3522 if (initial_video_height_recorded_)
3523 return;
3524
3525 initial_video_height_recorded_ = true;
3526
3527 int height = natural_size.height();
3528
3529 if (load_type_ == kLoadTypeURL)
3530 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.SRC", height);
3531 else if (load_type_ == kLoadTypeMediaSource)
3532 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.MSE", height);
3533
3534 if (is_encrypted_)
3535 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.EME", height);
3536
3537 UMA_HISTOGRAM_VIDEO_HEIGHT("Media.VideoHeight.Initial.All", height);
3538}
3539
3540#undef UMA_HISTOGRAM_VIDEO_HEIGHT
3541
Greg Thompsonaa48ce8d2018-04-03 06:11:433542void WebMediaPlayerImpl::SetTickClockForTest(
3543 const base::TickClock* tick_clock) {
tzik2c963b872017-12-07 06:57:243544 tick_clock_ = tick_clock;
Antonio Gomes81b56552019-05-15 22:15:283545 buffered_data_source_host_->SetTickClockForTest(tick_clock);
hubbeb2d3efd2017-05-05 23:26:383546}
3547
Dale Curtis3899090ea2018-01-12 00:10:353548void WebMediaPlayerImpl::OnFirstFrame(base::TimeTicks frame_time) {
3549 DCHECK(!load_start_time_.is_null());
Dale Curtisff576552018-03-30 02:32:443550 DCHECK(!skip_metrics_due_to_startup_suspend_);
Dale Curtisc2c5dcb12018-04-16 23:21:293551 has_first_frame_ = true;
Dale Curtis7c63f2e22018-09-19 21:06:273552 needs_first_frame_ = false;
Dale Curtis3899090ea2018-01-12 00:10:353553 const base::TimeDelta elapsed = frame_time - load_start_time_;
3554 media_metrics_provider_->SetTimeToFirstFrame(elapsed);
3555 RecordTimingUMA("Media.TimeToFirstFrame", elapsed);
Dale Curtiscdfc6f22019-06-26 22:05:233556
3557 // Needed to signal HTMLVideoElement that it should remove the poster image.
Dale Curtis66790f32019-07-11 00:14:243558 if (client_ && has_poster_)
Dale Curtiscdfc6f22019-06-26 22:05:233559 client_->Repaint();
Dale Curtis3899090ea2018-01-12 00:10:353560}
3561
3562void WebMediaPlayerImpl::RecordTimingUMA(const std::string& key,
3563 base::TimeDelta elapsed) {
3564 if (chunk_demuxer_)
3565 base::UmaHistogramMediumTimes(key + ".MSE", elapsed);
3566 else
3567 base::UmaHistogramMediumTimes(key + ".SRC", elapsed);
3568 if (is_encrypted_)
3569 base::UmaHistogramMediumTimes(key + ".EME", elapsed);
3570}
3571
John Rummelldb5a7ef2018-05-16 00:28:013572void WebMediaPlayerImpl::RecordEncryptionScheme(
3573 const std::string& stream_name,
Yuchen Liub33bfc12019-11-08 20:16:123574 EncryptionScheme encryption_scheme) {
John Rummelldb5a7ef2018-05-16 00:28:013575 DCHECK(stream_name == "Audio" || stream_name == "Video");
3576
3577 // If the stream is not encrypted, don't record it.
Yuchen Liub33bfc12019-11-08 20:16:123578 if (encryption_scheme == EncryptionScheme::kUnencrypted)
John Rummelldb5a7ef2018-05-16 00:28:013579 return;
3580
3581 base::UmaHistogramEnumeration(
3582 "Media.EME.EncryptionScheme.Initial." + stream_name,
3583 DetermineEncryptionSchemeUMAValue(encryption_scheme),
3584 EncryptionSchemeUMA::kCount);
3585}
3586
Mounir Lamouri0484f40a2018-07-25 03:03:263587bool WebMediaPlayerImpl::IsInPictureInPicture() const {
3588 DCHECK(client_);
3589 return client_->DisplayType() ==
3590 WebMediaPlayer::DisplayType::kPictureInPicture;
3591}
3592
Dale Curtis5bba03232018-08-30 17:57:383593void WebMediaPlayerImpl::MaybeSetContainerName() {
Dale Curtisf01c8262018-09-04 23:50:433594 // MSE nor MediaPlayerRenderer provide container information.
3595 if (chunk_demuxer_ || using_media_player_renderer_)
Dale Curtis5bba03232018-08-30 17:57:383596 return;
3597
3598 // Pipeline startup failed before even getting a demuxer setup.
3599 if (!demuxer_)
3600 return;
3601
3602 // Container has already been set.
3603 if (highest_ready_state_ >= WebMediaPlayer::kReadyStateHaveMetadata)
3604 return;
3605
3606// If ffmpeg isn't enabled, we can't get the container name.
3607#if BUILDFLAG(ENABLE_FFMPEG)
3608 media_metrics_provider_->SetContainerName(
3609 static_cast<FFmpegDemuxer*>(demuxer_.get())->container());
3610#endif
3611}
3612
Dale Curtis18ad391b2019-05-30 23:25:093613void WebMediaPlayerImpl::MaybeUpdateBufferSizesForPlayback() {
3614 // Don't increase the MultiBufferDataSource buffer size until we've reached
3615 // kReadyStateHaveEnoughData. Otherwise we will unnecessarily slow down
3616 // playback startup -- it can instead be done for free after playback starts.
3617 if (!mb_data_source_ || highest_ready_state_ < kReadyStateHaveEnoughData)
3618 return;
3619
3620 mb_data_source_->MediaPlaybackRateChanged(playback_rate_);
3621 if (!paused_)
3622 mb_data_source_->MediaIsPlaying();
Becca Hughes7a85bf22019-07-24 16:16:583623
3624 // The playback rate has changed so we should rebuild the media position
3625 // state.
3626 UpdateMediaPositionState();
Dale Curtis18ad391b2019-05-30 23:25:093627}
3628
Dan Sanders6edfd782019-08-13 00:13:183629void WebMediaPlayerImpl::OnSimpleWatchTimerTick() {
3630 RecordSimpleWatchTimeUMA(reported_renderer_type_);
3631}
3632
[email protected]dbb3ff372019-10-15 19:09:423633GURL WebMediaPlayerImpl::GetSrcAfterRedirects() {
3634 return mb_data_source_ ? mb_data_source_->GetUrlAfterRedirects() : GURL();
3635}
3636
Thomas Guilberte90fe312019-11-07 22:27:563637void WebMediaPlayerImpl::SetCurrentFrameOverrideForTesting(
3638 scoped_refptr<VideoFrame> current_frame_override) {
3639 current_frame_override_ = current_frame_override;
3640}
3641
acolwell9e0840d2014-09-06 19:01:323642} // namespace media