Skip to content

Commit

Permalink
[media] Workaround to support video poster (#1037)
Browse files Browse the repository at this point in the history
This CL allows the web app to set a poster image for video element by:
1. Playing the video in decode-to-texture mode.
2. Setting the poster image as the background image of the video
element.

Previously the video background is painted to black when there are no
frames to display. This isn't the expected behavior as it overwrites any
background image or color settings on the video element.

Now by default Cobalt won't paint the video background to black.

H5vcc setting `MediaElement.PaintingVideoBackgroundToBlack` is also
introduced so the web app can opt for the previous behavior, i.e. set
the background to black.

b/261922568

(cherry picked from commit a816c49)
  • Loading branch information
xiaomings authored and anonymous1-me committed Jul 26, 2023
1 parent 51686c9 commit 55d65b0
Show file tree
Hide file tree
Showing 13 changed files with 260 additions and 17 deletions.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<!DOCTYPE html>
<!--
| Copyright 2023 The Cobalt Authors. All Rights Reserved.
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
-->

<html>
<head>
<title>Video Elements With Background</title>
<style>
body {
margin: 0;
}

video {
width: 100%;
height: 100%;
}

#ui-layer {
display: flex;
justify-content: space-between;
position: absolute;
top: 15%;
height: 85%;
width: 100%;
background-color: rgba(33, 33, 33, .75);
padding: 24px;
margin: auto;
}

.item {
width: 320px;
height: 240px;
display: inline-block;
margin: 24px;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="ui-layer">
<div class="item">
<video id="video1" muted="1" style="background-color: #4285F4">
</video>
</div>
<div class="item">
<video id="video2" muted="1"
style="background-image: url(sddefault.jpg);
background-size: 320px 240px;">
</video>
</div>
<div class="item">
<video id="video3" muted="1" style="background-color: #4285F4">
</video>
</div>
<div class="item">
<video id="video4" muted="1"
style="background-image: url(sddefault.jpg);
background-size: 320px 240px;">
</video>
</div>
</div>
<script src="video-background-demo.js"></script>
</body>
</html>
106 changes: 106 additions & 0 deletions cobalt/demos/content/video-background-demo/video-background-demo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright 2023 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var nextVideoElementIndex = 0;
var audioData;
var videoData;

function downloadMediaData(downloadedCallback) {
var xhr = new XMLHttpRequest;

xhr.onload = function() {
audioData = xhr.response;
console.log("Downloaded " + audioData.byteLength + " of audio data.");

xhr.onload = function() {
videoData = xhr.response;
console.log("Downloaded " + videoData.byteLength + " of video data.");
downloadedCallback();
}

xhr.open("GET", "vp9-720p.webm", true);
xhr.send();
}

xhr.open("GET", "dash-audio.mp4", true);
xhr.responseType = "arraybuffer";
xhr.send();
}

function playVideoOn(videoElement) {
var ms = new MediaSource;
ms.addEventListener('sourceopen', function() {
console.log("Creating SourceBuffer objects.");
var audioBuffer = ms.addSourceBuffer('audio/mp4; codecs="mp4a.40.2"');
var videoBuffer = ms.addSourceBuffer('video/webm; codecs="vp9"; decode-to-texture=true');
audioBuffer.addEventListener("updateend", function() {
audioBuffer.abort();
videoBuffer.addEventListener("updateend", function() {
setTimeout(function() {
videoBuffer.addEventListener("updateend", function() {
videoBuffer.abort();
ms.endOfStream();
videoElement.ontimeupdate = function() {
if (videoElement.currentTime > 10) {
console.log("Stop playback.");
videoElement.src = '';
videoElement.load();
videoElement.ontimeupdate = null;
}
}
console.log("Start playback.");
videoElement.play();
});
videoBuffer.appendBuffer(videoData.slice(1024));
}, 5000);
});
videoBuffer.appendBuffer(videoData.slice(0, 1024));
});
audioBuffer.appendBuffer(audioData);
});

console.log("Attaching MediaSource to video element.");
videoElement.src = URL.createObjectURL(ms);
}

function setupKeyHandler() {
document.onkeydown = function() {
videoElements = document.getElementsByTagName('video');
for(let i = 0; i < videoElements.length; i++) {
if (videoElements[i].playing) {
console.log("Ignore key press as a video is still playing.");
return;
}
}

nextVideoElementIndex = nextVideoElementIndex % videoElements.length;

console.log("Trying to play next video at index " + nextVideoElementIndex);

var currentVideoElement = videoElements[nextVideoElementIndex];
if (currentVideoElement.setMaxVideoCapabilities) {
if (nextVideoElementIndex < videoElements.length / 2) {
currentVideoElement.setMaxVideoCapabilities("");
} else {
currentVideoElement.setMaxVideoCapabilities("width=1920; height=1080");
}
}

nextVideoElementIndex++;

playVideoOn(currentVideoElement);
};
}

downloadMediaData(setupKeyHandler);
Binary file not shown.
20 changes: 18 additions & 2 deletions cobalt/dom/html_video_element.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "cobalt/dom/dom_settings.h"
#include "cobalt/dom/media_settings.h"
#include "cobalt/dom/performance.h"
#include "cobalt/dom/window.h"
#include "cobalt/math/size_f.h"
Expand All @@ -30,6 +31,15 @@ using media::WebMediaPlayer;

const char HTMLVideoElement::kTagName[] = "video";

const MediaSettings& GetMediaSettings(web::EnvironmentSettings* settings) {
DCHECK(settings);
DCHECK(settings->context());
DCHECK(settings->context()->web_settings());

const auto& web_settings = settings->context()->web_settings();
return web_settings->media_settings();
}

HTMLVideoElement::HTMLVideoElement(Document* document)
: HTMLMediaElement(document, base::Token(kTagName)) {}

Expand Down Expand Up @@ -98,9 +108,15 @@ scoped_refptr<VideoPlaybackQuality> HTMLVideoElement::GetVideoPlaybackQuality(
}
}

scoped_refptr<DecodeTargetProvider>
HTMLVideoElement::GetDecodeTargetProvider() {
scoped_refptr<DecodeTargetProvider> HTMLVideoElement::GetDecodeTargetProvider(
bool* paint_to_black) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(paint_to_black);

*paint_to_black = GetMediaSettings(environment_settings())
.IsPaintingVideoBackgroundToBlack()
.value_or(false);

return player() ? player()->GetDecodeTargetProvider() : NULL;
}

Expand Down
5 changes: 4 additions & 1 deletion cobalt/dom/html_video_element.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ class HTMLVideoElement : public HTMLMediaElement {
// From HTMLElement
scoped_refptr<HTMLVideoElement> AsHTMLVideoElement() override { return this; }

scoped_refptr<DecodeTargetProvider> GetDecodeTargetProvider();
// When the return value is nullptr, and |paint_to_black| is set to true, the
// caller is expected to paint the area covered by the video to black.
scoped_refptr<DecodeTargetProvider> GetDecodeTargetProvider(
bool* paint_to_black);

WebMediaPlayer::SetBoundsCB GetSetBoundsCB();

Expand Down
6 changes: 6 additions & 0 deletions cobalt/dom/media_settings.cc
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ bool MediaSettingsImpl::Set(const std::string& name, int value) {
LOG(INFO) << name << ": set to " << value;
return true;
}
} else if (name == "MediaElement.PaintingVideoBackgroundToBlack") {
if (value == 0 || value == 1) {
is_painting_video_background_to_black_ = value != 0;
LOG(INFO) << name << ": set to " << value;
return true;
}
} else {
LOG(WARNING) << "Ignore unknown setting with name \"" << name << "\"";
return false;
Expand Down
6 changes: 6 additions & 0 deletions cobalt/dom/media_settings.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class MediaSettings {

virtual base::Optional<int>
GetMediaElementTimeupdateEventIntervalInMilliseconds() const = 0;
virtual base::Optional<bool> IsPaintingVideoBackgroundToBlack() const = 0;

protected:
MediaSettings() = default;
Expand Down Expand Up @@ -89,6 +90,9 @@ class MediaSettingsImpl : public MediaSettings {
const override {
return media_element_timeupdate_event_interval_in_milliseconds_;
}
base::Optional<bool> IsPaintingVideoBackgroundToBlack() const override {
return is_painting_video_background_to_black_;
}

// Returns true when the setting associated with `name` is set to `value`.
// Returns false when `name` is not associated with any settings, or if
Expand All @@ -106,6 +110,8 @@ class MediaSettingsImpl : public MediaSettings {
base::Optional<int> max_source_buffer_append_size_in_bytes_;

base::Optional<int> media_element_timeupdate_event_interval_in_milliseconds_;

base::Optional<bool> is_painting_video_background_to_black_;
};

} // namespace dom
Expand Down
10 changes: 10 additions & 0 deletions cobalt/dom/media_settings_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ TEST(MediaSettingsImplTest, Empty) {
EXPECT_FALSE(impl.GetMaxSizeForImmediateJob());
EXPECT_FALSE(impl.GetMaxSourceBufferAppendSizeInBytes());
EXPECT_FALSE(impl.GetMediaElementTimeupdateEventIntervalInMilliseconds());
EXPECT_FALSE(impl.IsPaintingVideoBackgroundToBlack());
}

TEST(MediaSettingsImplTest, SunnyDay) {
Expand All @@ -46,6 +47,7 @@ TEST(MediaSettingsImplTest, SunnyDay) {
ASSERT_TRUE(impl.Set("MediaSource.MaxSourceBufferAppendSizeInBytes", 100000));
ASSERT_TRUE(
impl.Set("MediaElement.TimeupdateEventIntervalInMilliseconds", 100001));
ASSERT_TRUE(impl.Set("MediaElement.PaintingVideoBackgroundToBlack", 1));

EXPECT_EQ(impl.GetSourceBufferEvictExtraInBytes().value(), 100);
EXPECT_EQ(impl.GetMinimumProcessorCountToOffloadAlgorithm().value(), 101);
Expand All @@ -56,6 +58,7 @@ TEST(MediaSettingsImplTest, SunnyDay) {
EXPECT_EQ(impl.GetMaxSourceBufferAppendSizeInBytes().value(), 100000);
EXPECT_EQ(impl.GetMediaElementTimeupdateEventIntervalInMilliseconds().value(),
100001);
EXPECT_TRUE(impl.IsPaintingVideoBackgroundToBlack().value());
}

TEST(MediaSettingsImplTest, RainyDay) {
Expand All @@ -71,6 +74,7 @@ TEST(MediaSettingsImplTest, RainyDay) {
ASSERT_FALSE(impl.Set("MediaSource.MaxSourceBufferAppendSizeInBytes", 0));
ASSERT_FALSE(
impl.Set("MediaElement.TimeupdateEventIntervalInMilliseconds", 0));
ASSERT_FALSE(impl.Set("MediaElement.PaintingVideoBackgroundToBlack", 2));

EXPECT_FALSE(impl.GetSourceBufferEvictExtraInBytes());
EXPECT_FALSE(impl.GetMinimumProcessorCountToOffloadAlgorithm());
Expand All @@ -80,6 +84,7 @@ TEST(MediaSettingsImplTest, RainyDay) {
EXPECT_FALSE(impl.GetMaxSizeForImmediateJob());
EXPECT_FALSE(impl.GetMaxSourceBufferAppendSizeInBytes());
EXPECT_FALSE(impl.GetMediaElementTimeupdateEventIntervalInMilliseconds());
EXPECT_FALSE(impl.IsPaintingVideoBackgroundToBlack());
}

TEST(MediaSettingsImplTest, ZeroValuesWork) {
Expand All @@ -95,13 +100,15 @@ TEST(MediaSettingsImplTest, ZeroValuesWork) {
// O is an invalid value for "MediaSource.MaxSourceBufferAppendSizeInBytes".
// O is an invalid value for
// "MediaElement.TimeupdateEventIntervalInMilliseconds".
ASSERT_TRUE(impl.Set("MediaElement.PaintingVideoBackgroundToBlack", 0));

EXPECT_EQ(impl.GetSourceBufferEvictExtraInBytes().value(), 0);
EXPECT_EQ(impl.GetMinimumProcessorCountToOffloadAlgorithm().value(), 0);
EXPECT_FALSE(impl.IsAsynchronousReductionEnabled().value());
EXPECT_FALSE(impl.IsAvoidCopyingArrayBufferEnabled().value());
EXPECT_FALSE(impl.IsCallingEndedWhenClosedEnabled().value());
EXPECT_EQ(impl.GetMaxSizeForImmediateJob().value(), 0);
EXPECT_FALSE(impl.IsPaintingVideoBackgroundToBlack().value());
}

TEST(MediaSettingsImplTest, Updatable) {
Expand All @@ -117,6 +124,7 @@ TEST(MediaSettingsImplTest, Updatable) {
ASSERT_TRUE(impl.Set("MediaSource.MaxSourceBufferAppendSizeInBytes", 1));
ASSERT_TRUE(
impl.Set("MediaElement.TimeupdateEventIntervalInMilliseconds", 1));
ASSERT_TRUE(impl.Set("MediaElement.PaintingVideoBackgroundToBlack", 0));

ASSERT_TRUE(impl.Set("MediaSource.SourceBufferEvictExtraInBytes", 1));
ASSERT_TRUE(
Expand All @@ -128,6 +136,7 @@ TEST(MediaSettingsImplTest, Updatable) {
ASSERT_TRUE(impl.Set("MediaSource.MaxSourceBufferAppendSizeInBytes", 2));
ASSERT_TRUE(
impl.Set("MediaElement.TimeupdateEventIntervalInMilliseconds", 2));
ASSERT_TRUE(impl.Set("MediaElement.PaintingVideoBackgroundToBlack", 1));

EXPECT_EQ(impl.GetSourceBufferEvictExtraInBytes().value(), 1);
EXPECT_EQ(impl.GetMinimumProcessorCountToOffloadAlgorithm().value(), 1);
Expand All @@ -138,6 +147,7 @@ TEST(MediaSettingsImplTest, Updatable) {
EXPECT_EQ(impl.GetMaxSourceBufferAppendSizeInBytes().value(), 2);
EXPECT_EQ(impl.GetMediaElementTimeupdateEventIntervalInMilliseconds().value(),
2);
EXPECT_TRUE(impl.IsPaintingVideoBackgroundToBlack().value());
}

TEST(MediaSettingsImplTest, InvalidSettingNames) {
Expand Down
23 changes: 16 additions & 7 deletions cobalt/layout/box_generator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -339,22 +339,31 @@ void BoxGenerator::VisitVideoElement(dom::HTMLVideoElement* video_element) {
// If the optional is disengaged, then we don't know if punch out is enabled
// or not.
base::Optional<ReplacedBox::ReplacedBoxMode> replaced_box_mode;
if (video_element->GetDecodeTargetProvider()) {
bool paint_to_black = false;
auto decode_target_provider =
video_element->GetDecodeTargetProvider(&paint_to_black);
if (decode_target_provider) {
DecodeTargetProvider::OutputMode output_mode =
video_element->GetDecodeTargetProvider()->GetOutputMode();
if (output_mode != DecodeTargetProvider::kOutputModeInvalid) {
decode_target_provider->GetOutputMode();
if (output_mode == DecodeTargetProvider::kOutputModeInvalid) {
if (paint_to_black) {
replaced_box_mode = ReplacedBox::ReplacedBoxMode::kPaintToBlack;
}
} else {
replaced_box_mode =
(output_mode == DecodeTargetProvider::kOutputModePunchOut)
? ReplacedBox::ReplacedBoxMode::kPunchOutVideo
: ReplacedBox::ReplacedBoxMode::kVideo;
: ReplacedBox::ReplacedBoxMode::kDecodeToTextureVideo;
}
} else {
// ReplacedBox won't paint anything when |decode_target_provider| is
// nullptr, as |replace_image_cb_| is also null in this case.
}

ReplacedBoxGenerator replaced_box_generator(
video_element->css_computed_style_declaration(),
video_element->GetDecodeTargetProvider()
? base::Bind(GetVideoFrame, video_element->GetDecodeTargetProvider(),
resource_provider)
decode_target_provider
? base::Bind(GetVideoFrame, decode_target_provider, resource_provider)
: ReplacedBox::ReplaceImageCB(),
video_element->GetSetBoundsCB(), *paragraph_, text_position,
base::nullopt, base::nullopt, base::nullopt, context_, replaced_box_mode,
Expand Down
Loading

0 comments on commit 55d65b0

Please sign in to comment.