Truly independent web browser
LibMedia: Allow MSE playback to begin with a non-zero first frame
Zaggy1024248ad408d4f9
diff --git a/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.cpp b/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.cppindex 1e6eaacfdcd..19cfe3d0e54 100644--- a/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.cpp+++ b/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.cpp@@ -44,6 +44,17 @@ AK::Duration SourceBufferDemuxer::maximum_time_range_gap(TrackData const& data)return data.maximum_frame_duration + data.maximum_frame_duration;}+// https://w3c.github.io/media-source/#presentation-start-time+bool SourceBufferDemuxer::is_within_start_gap_allowance(AK::Duration timestamp, AK::Duration first_data_start)+{+ // NOTE: For the purposes of determining if HTMLMediaElement's buffered contains a TimeRanges that includes the+ // current playback position, implementations MAY choose to allow a current playback position at or after+ // presentation start time and before the first TimeRanges to play the first TimeRanges if that TimeRanges+ // starts within a reasonably short time, like 1 second, after presentation start time.+ constexpr auto start_gap_allowance = AK::Duration::from_seconds(1);+ return timestamp >= AK::Duration::zero() && timestamp < first_data_start && first_data_start <= start_gap_allowance;+}+Media::TimeRanges SourceBufferDemuxer::coalesced_track_buffer_ranges(TrackData const& data){// https://w3c.github.io/media-source/#track-buffer-ranges@@ -620,6 +631,8 @@ Optional<size_t> SourceBufferDemuxer::find_run_to_play_from_while_locked(TrackDa// Resolve seeks to the following run if they are within the permitted gap size.if (run.presentation_start - timestamp <= maximum_time_range_gap(data))return index;+ if (index == 0 && is_within_start_gap_allowance(timestamp, run.presentation_start))+ return index;return {};}@@ -652,7 +665,9 @@ bool SourceBufferDemuxer::may_read_frame_while_locked(TrackData const& data, Med// A read may only move forward within the buffered range that it is already in. A seek target shortly before a// range plays from that range, as the track's own seeks do.auto range = m_buffered_ranges.range_at_or_after(anchor);- if (!range.has_value() || range->start > anchor + maximum_time_range_gap(data))+ if (!range.has_value())+ return false;+ if (range->start > anchor + maximum_time_range_gap(data) && !is_within_start_gap_allowance(anchor, m_buffered_ranges[0].start))return false;return frame.presentation_timestamp() < range->end;}diff --git a/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.h b/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.hindex ca4c69744b6..900f2d565c8 100644--- a/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.h+++ b/Libraries/LibMedia/MediaSourceExtensions/SourceBufferDemuxer.h@@ -129,6 +129,7 @@ private:static bool contributes_to_buffered_ranges(TrackData const&);static AK::Duration maximum_time_range_gap(TrackData const&);+ static bool is_within_start_gap_allowance(AK::Duration timestamp, AK::Duration first_data_start);static Media::TimeRanges coalesced_track_buffer_ranges(TrackData const&);static void count_frame_duration(TrackData&, AK::Duration);static void decrement_frames_with_maximum_duration(TrackData&, size_t count);diff --git a/Tests/LibMedia/TestSourceBufferDemuxer.cpp b/Tests/LibMedia/TestSourceBufferDemuxer.cppindex 3ee884dee2a..cac337e1d9c 100644--- a/Tests/LibMedia/TestSourceBufferDemuxer.cpp+++ b/Tests/LibMedia/TestSourceBufferDemuxer.cpp@@ -263,6 +263,41 @@ TEST_CASE(a_track_stops_where_another_tracks_data_ends)EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(video_track)).presentation_timestamp(), AK::Duration::from_seconds(3));}+static Media::CodedFrame tenth_of_a_second_frame_at(u64 milliseconds, Media::CodecID codec_id)+{+ auto data = MUST(FixedArray<u8>::create(1));+ auto timestamp = AK::Duration::from_milliseconds(milliseconds);+ return { codec_id, timestamp, timestamp, AK::Duration::from_milliseconds(100), Media::FrameFlags::Keyframe, move(data), {} };+}++TEST_CASE(a_seek_into_a_gap_after_the_first_range_does_not_play_across_it)+{+ Media::Track video_track { Media::TrackType::Video, 1, Media::Track::Kind::Main, {}, {} };+ Media::Track audio_track { Media::TrackType::Audio, 2, Media::Track::Kind::Main, {}, {} };+ auto demuxer = make_ref_counted<Media::MediaSourceExtensions::SourceBufferDemuxer>(Vector { video_track, audio_track });++ for (u64 milliseconds = 0; milliseconds < 1'000; milliseconds += 100)+ demuxer->add_coded_frame(video_track, tenth_of_a_second_frame_at(milliseconds, Media::CodecID::H264));+ for (u64 milliseconds : { 0, 100, 800, 900 })+ demuxer->add_coded_frame(audio_track, tenth_of_a_second_frame_at(milliseconds, Media::CodecID::Opus));++ // The range after the gap starts within the allowance for playing from the start, but a gap between ranges is+ // not the start.+ auto buffered = demuxer->buffered_ranges();+ EXPECT_EQ(buffered.size(), 2u);+ EXPECT_EQ(buffered[1].start, AK::Duration::from_milliseconds(800));++ MUST(demuxer->seek_to_most_recent_keyframe(video_track, AK::Duration::from_milliseconds(400), Media::DemuxerSeekOptions::None));+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(video_track)).presentation_timestamp(), AK::Duration::from_milliseconds(400));++ // The next video frame lies in the gap, so the read would wait; aborting it shows that it did not deliver the+ // frame.+ demuxer->set_blocking_reads_aborted_for_track(video_track);+ auto blocked_read = demuxer->get_next_sample_for_track(video_track);+ EXPECT(blocked_read.is_error());+ EXPECT_EQ(blocked_read.error().category(), Media::DecoderErrorCategory::Aborted);+}+TEST_CASE(the_end_of_the_stream_lets_the_longer_track_play_out){Media::Track video_track { Media::TrackType::Video, 1, Media::Track::Kind::Main, {}, {} };diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 0e2916f4790..5c5486af0ce 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -160,6 +160,7 @@ Text/input/HTML/media-source-mp4.htmlText/input/HTML/media-source-mp4-byte-stream-parser.htmlText/input/HTML/media-source-mp4-encoder-delay.htmlText/input/HTML/media-source-mp4-reordered-frames.html+Text/input/HTML/media-source-plays-from-start-before-first-range.htmlText/input/HTML/media-source-presented-frame-advances-when-first-painted-during-playback.htmlText/input/HTML/media-source-presented-frame-after-seek-past-replaced-end.htmlText/input/HTML/media-source-presented-frame-replaced-after-decoding-ahead.html@@ -174,11 +175,11 @@ Text/input/HTML/media-source-track-list-change-events.htmlText/input/HTML/media-source-tracks-of-detached-source.htmlText/input/HTML/media-source-unknown-size-cluster.htmlText/input/HTML/media-source-unsupported-codec-in-init-segment.html+Text/input/HTML/media-source-waits-for-audio-at-start.htmlText/input/HTML/media-source-vorbis-without-block-durations.htmlText/input/HTML/media-source-waiting-at-end-of-appended-audio.htmlText/input/HTML/media-source-waiting-at-end-of-appended-data.htmlText/input/HTML/media-source-waiting-at-end-of-disabled-track.html-Text/input/HTML/media-source-waits-for-audio-at-start.htmlText/input/HTML/media-source-webm-block-groups.htmlText/input/HTML/media-source-mismatched-codec-configuration.htmlText/input/wpt-import/media-source/mediasource-activesourcebuffers.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/media-source-plays-from-start-before-first-range.txt b/Tests/LibWeb/Text/expected/HTML/media-source-plays-from-start-before-first-range.txtnew file mode 100644index 00000000000..e17b7fcb975--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-plays-from-start-before-first-range.txt@@ -0,0 +1,5 @@+near: buffered: [0.112-6.531219955]+near: playing fired: true, readyState=HAVE_ENOUGH_DATA+near: played into the first range+far: buffered: [2.112-8.531219955]+far: playing fired: false, readyState=HAVE_METADATAdiff --git a/Tests/LibWeb/Text/input/HTML/media-source-plays-from-start-before-first-range.html b/Tests/LibWeb/Text/input/HTML/media-source-plays-from-start-before-first-range.htmlnew file mode 100644index 00000000000..7aef1ebb6e3--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-plays-from-start-before-first-range.html@@ -0,0 +1,57 @@+<!DOCTYPE html>+<script>internals.setAutoplayPolicy("allow-audio-and-video");</script>+<video id="near" muted></video>+<video id="far" muted></video>+<script src="../include.js"></script>+<script src="HTMLMediaElement-include.js"></script>+<script>+ // Muxed streams often begin a track shortly after time 0, so a buffered range that starts within a second of it+ // plays from the start rather than waiting for data before that range. A range that starts later does not.+ asyncTest(async done => {+ const media = await (await fetch("../wpt-import/media-source/webm/test.webm")).arrayBuffer();++ async function appendStartingAfter(video, timestampOffset) {+ const mediaSource = new MediaSource();+ video.src = URL.createObjectURL(mediaSource);+ await new Promise(resolve => mediaSource.addEventListener("sourceopen", resolve, { once: true }));+ const sourceBuffer = mediaSource.addSourceBuffer('video/webm;codecs="vp8,vorbis"');+ sourceBuffer.timestampOffset = timestampOffset;+ sourceBuffer.appendBuffer(media);+ await new Promise(resolve => sourceBuffer.addEventListener("updateend", resolve, { once: true }));+ println(`${video.id}: buffered: ${timeRangesToString(video.buffered)}`);+ }++ function playsWithin(video, milliseconds) {+ const playing = new Promise(resolve => video.addEventListener("playing", () => resolve(true), { once: true }));+ const timedOut = new Promise(resolve => setTimeout(() => resolve(false), milliseconds));+ video.play();+ return Promise.race([playing, timedOut]);+ }++ // The first video frame of this file is at 0.112 seconds.+ const near = document.getElementById("near");+ await appendStartingAfter(near, 0);+ const nearPlayed = await playsWithin(near, 2000);+ println(`near: playing fired: ${nearPlayed}, readyState=${readyStateName(near.readyState)}`);+ if (nearPlayed) {+ const firstRangeStart = near.buffered.start(0);+ await new Promise(resolve => {+ const check = () => {+ if (near.currentTime <= firstRangeStart)+ return;+ near.removeEventListener("timeupdate", check);+ resolve();+ };+ near.addEventListener("timeupdate", check);+ });+ println("near: played into the first range");+ near.pause();+ }++ const far = document.getElementById("far");+ await appendStartingAfter(far, 2);+ const farPlayed = await playsWithin(far, 500);+ println(`far: playing fired: ${farPlayed}, readyState=${readyStateName(far.readyState)}`);+ done();+ });+</script>