Truly independent web browser
LibMedia: Make demuxers keep their position in a GOP on seeks
Zaggy10241f052f21fa0b
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cpp b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cppindex f1caf11e89d..3a509b210a8 100644--- a/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cpp+++ b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cpp@@ -184,7 +184,9 @@ DecoderErrorOr<CodedFrame> ISOBMFFDemuxer::get_next_sample_for_track(Track constif (status.description_index != sample.sample_description_index)configuration = DECODER_TRY_ALLOC(entry->codec_initialization_data.clone());status.description_index = sample.sample_description_index;- status.last_timestamp = sample.presentation_timestamp;+ // Treat the first frame as a random access point, since the file must begin with one to decode.+ if (sample.is_sync_sample || !status.last_keyframe_decode_timestamp.has_value())+ status.last_keyframe_decode_timestamp = sample.decode_timestamp;CodedFrame frame(entry->codec_id, sample.presentation_timestamp, sample.decode_timestamp, sample.duration,sample.is_sync_sample ? FrameFlags::Keyframe : FrameFlags::None, move(data), move(configuration));status.pending_sample.clear();@@ -243,12 +245,11 @@ DecoderErrorOr<DemuxerSeekResult> ISOBMFFDemuxer::seek_to_most_recent_keyframe(Tauto point = TRY(find_seek_point(status.cursor, track, target, SeekMode::FastBefore));if (!point.has_value())return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "Track has no samples"sv);- if (!has_flag(options, DemuxerSeekOptions::Force) && status.last_timestamp.has_value()- && point->sample.presentation_timestamp <= status.last_timestamp.value() && status.last_timestamp.value() <= target)+ if (!has_flag(options, DemuxerSeekOptions::Force) && status.last_keyframe_decode_timestamp == point->sample.decode_timestamp)return DemuxerSeekResult::KeptCurrentPosition;status.iterator = move(point->iterator);status.pending_sample = point->sample;- status.last_timestamp.clear();+ status.last_keyframe_decode_timestamp = point->sample.decode_timestamp;return DemuxerSeekResult::MovedPosition;}diff --git a/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.hindex 64bc2a5db3e..d1df62bb096 100644--- a/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h+++ b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h@@ -51,7 +51,7 @@ private:NonnullRefPtr<MediaStreamCursor> cursor;SampleIterator iterator;Optional<Sample> pending_sample;- Optional<AK::Duration> last_timestamp;+ Optional<AK::Duration> last_keyframe_decode_timestamp;Optional<u32> description_index;};struct Durations : public AtomicRefCounted<Durations> {diff --git a/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp b/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cppindex 2082ff2fd25..7745ab18998 100644--- a/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp+++ b/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp@@ -5,7 +5,6 @@*/#include <AK/Assertions.h>-#include <AK/Debug.h>#include <AK/Utf16String.h>#include <LibMedia/Containers/Matroska/Utilities.h>#include <LibMedia/MediaStream.h>@@ -154,13 +153,10 @@ DecoderErrorOr<DemuxerSeekResult> MatroskaDemuxer::seek_to_most_recent_keyframe(auto seeked_iterator = TRY(m_reader.seek_to_random_access_point(track_status.iterator, timestamp));- auto last_sample = track_status.iterator.last_timestamp();- if (has_flag(options, DemuxerSeekOptions::Force))- last_sample = {};- if (last_sample.has_value() && seeked_iterator.last_timestamp().has_value()) {- bool skip_seek = seeked_iterator.last_timestamp().value() <= last_sample.value() && last_sample.value() <= timestamp;- dbgln_if(MATROSKA_DEBUG, "The last available sample at {}ms is {}closer to target timestamp {}ms than the keyframe at {}ms, {}", last_sample->to_milliseconds(), skip_seek ? ""sv : "not "sv, timestamp.to_milliseconds(), seeked_iterator.last_timestamp()->to_milliseconds(), skip_seek ? "skipping seek"sv : "seeking"sv);- if (skip_seek)+ if (!has_flag(options, DemuxerSeekOptions::Force) && track_status.last_keyframe_timestamp.has_value()) {+ auto keyframe_iterator = seeked_iterator;+ auto keyframe = keyframe_iterator.next_block();+ if (!keyframe.is_error() && keyframe.value().timestamp() == track_status.last_keyframe_timestamp)return DemuxerSeekResult::KeptCurrentPosition;}@@ -168,6 +164,7 @@ DecoderErrorOr<DemuxerSeekResult> MatroskaDemuxer::seek_to_most_recent_keyframe(track_status.block = {};track_status.frames = {};track_status.frame_index = 0;+ track_status.last_keyframe_timestamp.clear();return DemuxerSeekResult::MovedPosition;}@@ -179,6 +176,9 @@ DecoderErrorOr<CodedFrame> MatroskaDemuxer::get_next_sample_for_track(Track consstatus.block = TRY(status.iterator.next_block());status.frames.clear();status.frame_index = 0;+ // Treat the first frame as a random access point, since the file must begin with one to decode.+ if (status.block->only_keyframes() || !status.last_keyframe_timestamp.has_value())+ status.last_keyframe_timestamp = status.block->timestamp();}if (status.frames.is_empty()) {status.frames = TRY(status.iterator.get_frames(status.block.value()));diff --git a/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.h b/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.hindex b998536392c..9c94766756b 100644--- a/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.h+++ b/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.h@@ -61,6 +61,7 @@ private:Optional<Block> block;SampleIterator::Frames frames;size_t frame_index { 0 };+ Optional<AK::Duration> last_keyframe_timestamp;bool needs_codec_configuration { true };TrackStatus(SampleIterator&& iterator)diff --git a/Libraries/LibMedia/Containers/Matroska/Reader.cpp b/Libraries/LibMedia/Containers/Matroska/Reader.cppindex 5a9a6a9b98e..ff4440571f6 100644--- a/Libraries/LibMedia/Containers/Matroska/Reader.cpp+++ b/Libraries/LibMedia/Containers/Matroska/Reader.cpp@@ -1379,12 +1379,12 @@ DecoderErrorOr<void> Reader::seek_to_cue_for_timestamp(SampleIterator& iterator,return {};}-static DecoderErrorOr<void> search_clusters_for_keyframe_before_timestamp(SampleIterator& iterator, AK::Duration const& timestamp)+static DecoderErrorOr<Optional<SampleIterator>> search_clusters_for_keyframe_before_timestamp(SampleIterator iterator, AK::Duration const& timestamp){#if MATROSKA_DEBUGsize_t inter_frames_count;#endif- SampleIterator last_keyframe = iterator;+ Optional<SampleIterator> last_keyframe;while (true) {SampleIterator rewind_iterator = iterator;@@ -1400,7 +1400,7 @@ static DecoderErrorOr<void> search_clusters_for_keyframe_before_timestamp(Samplebreak;if (block.only_keyframes()) {- last_keyframe = rewind_iterator;+ last_keyframe = move(rewind_iterator);#if MATROSKA_DEBUGinter_frames_count = 0;#endif@@ -1414,9 +1414,7 @@ static DecoderErrorOr<void> search_clusters_for_keyframe_before_timestamp(Sample#if MATROSKA_DEBUGdbgln("Seeked to a keyframe with {} inter frames to skip", inter_frames_count);#endif- iterator = move(last_keyframe);-- return {};+ return last_keyframe;}DecoderErrorOr<SampleIterator> Reader::seek_to_random_access_point(SampleIterator iterator, AK::Duration timestamp) const@@ -1441,17 +1439,20 @@ DecoderErrorOr<SampleIterator> Reader::seek_to_random_access_point(SampleIteratoVERIFY(iterator.last_timestamp().has_value());}- if (!iterator.last_timestamp().has_value() || timestamp < iterator.last_timestamp().value()) {- // If the timestamp is before the iterator's current position, then we need to start from the beginning of the Segment.- if (timestamp > AK::Duration::zero())- warnln("Seeking track {} to {}s required restarting the sample iterator from the start, streaming may be broken for this file.", timestamp, iterator.m_track_number);- iterator = TRY(create_sample_iterator(iterator.m_stream_cursor, iterator.m_track_number));- TRY(search_clusters_for_keyframe_before_timestamp(iterator, timestamp));- return iterator;+ if (iterator.last_timestamp().has_value() && timestamp >= iterator.last_timestamp().value()) {+ auto keyframe = TRY(search_clusters_for_keyframe_before_timestamp(iterator, timestamp));+ if (keyframe.has_value())+ return keyframe.release_value();}- TRY(search_clusters_for_keyframe_before_timestamp(iterator, timestamp));- return iterator;+ // If the timestamp is before the iterator's current position, or no keyframe lies between that position and the+ // timestamp, then the keyframe is behind us, so we need to start from the beginning of the Segment.+ if (timestamp > AK::Duration::zero())+ warnln("Seeking track {} to {}s required restarting the sample iterator from the start, streaming may be broken for this file.", timestamp, iterator.m_track_number);+ iterator = TRY(create_sample_iterator(iterator.m_stream_cursor, iterator.m_track_number));+ auto keyframe = TRY(search_clusters_for_keyframe_before_timestamp(iterator, timestamp));+ // The first block is the random access point even if it isn't marked as a keyframe.+ return keyframe.value_or(move(iterator));}Optional<Vector<TrackCuePoint> const&> Reader::cue_points_for_track(u64 track_number) constdiff --git a/Libraries/LibMedia/Demuxer.h b/Libraries/LibMedia/Demuxer.hindex 1b0f63d2412..59336b51ff4 100644--- a/Libraries/LibMedia/Demuxer.h+++ b/Libraries/LibMedia/Demuxer.h@@ -52,6 +52,10 @@ public:virtual DecoderErrorOr<CodedFrame> get_next_sample_for_track(Track const&) = 0;virtual AK::Duration select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode) = 0;++ // Moves to the keyframe prior to the target. If the track is already reading within the GOP for that keyframe, it+ // will remain where it was unless the seek is forced. Thus, it may return with the track reading a frame past the+ // target, so the caller should ensure that a backwards seek is forced.virtual DecoderErrorOr<DemuxerSeekResult> seek_to_most_recent_keyframe(Track const&, AK::Duration timestamp, DemuxerSeekOptions = DemuxerSeekOptions::None) = 0;virtual DecoderErrorOr<AK::Duration> duration_of_track(Track const&) = 0;diff --git a/Tests/LibMedia/TestISOBMFF.cpp b/Tests/LibMedia/TestISOBMFF.cppindex 71a27849244..f09ac3e9b69 100644--- a/Tests/LibMedia/TestISOBMFF.cpp+++ b/Tests/LibMedia/TestISOBMFF.cpp@@ -801,6 +801,30 @@ TEST_CASE(seeks_by_pts_and_skips_seeks_that_do_not_improve_position)EXPECT_EQ(demuxer->select_fast_seek_target_for_track(track, target, Media::SeekMode::FastAfter), AK::Duration::from_seconds(6));}+TEST_CASE(keeps_its_position_while_reading_the_targets_group_of_pictures)+{+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(seek_test_file());+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).value();+ MUST(demuxer->create_context_for_track(track));+ auto target = AK::Duration::from_seconds(2);++ // The second sample is presented after the target, but the samples presented before it have yet to be read.+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 0);+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).presentation_timestamp(), AK::Duration::from_seconds(3));+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target)), Media::DemuxerSeekResult::KeptCurrentPosition);+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 2);++ // Reading the next keyframe leaves the target's group of pictures.+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 3);+ EXPECT(MUST(demuxer->get_next_sample_for_track(track)).is_keyframe());+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target)), Media::DemuxerSeekResult::MovedPosition);++ // The keyframe a seek moves to counts as read before it is.+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target)), Media::DemuxerSeekResult::KeptCurrentPosition);+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 0);+}+TEST_CASE(seeks_across_movie_and_fragment_samples_in_both_directions){auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(seek_test_file(true));diff --git a/Tests/LibMedia/TestParseMatroska.cpp b/Tests/LibMedia/TestParseMatroska.cppindex 4d8403bc453..c3d824824b5 100644--- a/Tests/LibMedia/TestParseMatroska.cpp+++ b/Tests/LibMedia/TestParseMatroska.cpp@@ -932,6 +932,14 @@ TEST_CASE(seeking)EXPECT_EQ(first_block.timestamp().value().to_milliseconds(), 0);EXPECT(first_block.only_keyframes());+ auto second_block = MUST(iterator.next_block());+ EXPECT(!second_block.only_keyframes());+ EXPECT(second_block.timestamp().value() < AK::Duration::from_milliseconds(50));+ auto seeked_within_first_keyframe = MUST(matroska_reader.seek_to_random_access_point(iterator, AK::Duration::from_milliseconds(50)));+ auto block_after_seek_within_first_keyframe = MUST(seeked_within_first_keyframe.next_block());+ EXPECT_EQ(block_after_seek_within_first_keyframe.timestamp().value().to_milliseconds(), 0);+ EXPECT(block_after_seek_within_first_keyframe.only_keyframes());+iterator = MUST(matroska_reader.seek_to_random_access_point(iterator, AK::Duration::from_milliseconds(150)));auto block_after_forward_seek = MUST(iterator.next_block());EXPECT_EQ(block_after_forward_seek.timestamp().value().to_milliseconds(), 100);@@ -954,6 +962,23 @@ TEST_CASE(seeking)}}+TEST_CASE(keeps_its_position_while_reading_the_targets_keyframe_without_cues)+{+ auto file = MUST(Core::File::open("./test-matroska-seeking-without-cues.mkv"sv, Core::File::OpenMode::Read));+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));+ auto demuxer = MUST(Media::Matroska::MatroskaDemuxer::from_stream(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();+ MUST(demuxer->create_context_for_track(track));++ MUST(demuxer->get_next_sample_for_track(track));+ auto second_sample = MUST(demuxer->get_next_sample_for_track(track));+ EXPECT(second_sample.presentation_timestamp() < AK::Duration::from_milliseconds(50));++ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(50), Media::DemuxerSeekOptions::None)), Media::DemuxerSeekResult::KeptCurrentPosition);+ auto sample_after_seek = MUST(demuxer->get_next_sample_for_track(track));+ EXPECT(sample_after_seek.presentation_timestamp() > second_sample.presentation_timestamp());+}+TEST_CASE(opus_frame_duration){auto file = MUST(Core::File::open("./vp9_in_webm.webm"sv, Core::File::OpenMode::Read));