Skip to content

Truly independent web browser

LibMedia: Add an ISOBMFFDemuxer and use it instead of FFmpeg

Zaggy10240e00724d279e
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txt
index 6bad29bfdef..1e3c3925d86 100644
--- a/Libraries/LibMedia/CMakeLists.txt
+++ b/Libraries/LibMedia/CMakeLists.txt
@@ -25,6 +25,8 @@ set(SOURCES
Containers/ID3.cpp
Containers/IndexedContainerNavigator.cpp
Containers/ISOBMFF/FragmentSampleIterator.cpp
+ Containers/ISOBMFF/ISOBMFFDemuxer.cpp
+ Containers/ISOBMFF/SampleIterator.cpp
Containers/ISOBMFF/Reader.cpp
Containers/ISOBMFF/Streamer.cpp
Containers/Matroska/MatroskaDemuxer.cpp
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/BoxTypes.h b/Libraries/LibMedia/Containers/ISOBMFF/BoxTypes.h
index d2ca476194a..04733785a47 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/BoxTypes.h
+++ b/Libraries/LibMedia/Containers/ISOBMFF/BoxTypes.h
@@ -43,6 +43,7 @@ constexpr FourCC SEGMENT_TYPE_BOX { "styp" };
constexpr FourCC MEDIA_DATA_BOX { "mdat" };
constexpr FourCC FREE_SPACE_BOX { "free" };
constexpr FourCC SKIP_BOX { "skip" };
+constexpr FourCC WIDE_ATOM { "wide" };
constexpr FourCC EXTENDED_TYPE_BOX { "uuid" };
constexpr FourCC PROGRESSIVE_DOWNLOAD_INFO_BOX { "pdin" };
constexpr FourCC SEGMENT_INDEX_BOX { "sidx" };
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h b/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h
index caea88c09fb..096d9f66d1f 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h
+++ b/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h
@@ -6,11 +6,12 @@
#pragma once
+#include <AK/AtomicRefCounted.h>
#include <AK/FixedArray.h>
#include <AK/HashMap.h>
#include <AK/Math.h>
#include <AK/Optional.h>
-#include <AK/RefCounted.h>
+#include <AK/SaturatingMath.h>
#include <AK/String.h>
#include <AK/Time.h>
#include <AK/Vector.h>
@@ -89,7 +90,41 @@ struct TrackFragmentSampleDefaults {
u32 sample_flags { 0 };
};
-struct TrackEntry : public RefCounted<TrackEntry> {
+struct TimeToSampleEntry {
+ u32 sample_count;
+ u32 sample_delta;
+};
+
+struct CompositionOffsetEntry {
+ u32 sample_count;
+ i64 sample_offset;
+};
+
+struct SampleToChunkEntry {
+ u32 first_chunk;
+ u32 samples_per_chunk;
+ u32 sample_description_index;
+};
+
+struct SampleSizes {
+ u32 sample_count { 0 };
+ u32 default_size { 0 };
+ // Empty when default_size is nonzero.
+ Vector<u32> sizes;
+
+ u32 size_of_sample(u32 index) const { return default_size ? default_size : sizes[index]; }
+};
+
+struct SampleTables : public AtomicRefCounted<SampleTables> {
+ Optional<Vector<TimeToSampleEntry>> time_to_sample;
+ Optional<Vector<CompositionOffsetEntry>> composition_offsets;
+ Optional<Vector<SampleToChunkEntry>> sample_to_chunk;
+ Optional<SampleSizes> sample_sizes;
+ Optional<Vector<u64>> chunk_offsets;
+ Optional<Vector<u32>> sync_samples;
+};
+
+struct TrackEntry : public AtomicRefCounted<TrackEntry> {
u32 track_id { 0 };
bool is_enabled { true };
HandlerType handler_type { HandlerType::Unknown };
@@ -101,6 +136,7 @@ struct TrackEntry : public RefCounted<TrackEntry> {
Vector<SampleEntry> sample_entries;
TrackFragmentSampleDefaults fragment_defaults;
u64 sample_table_entry_count { 0 };
+ NonnullRefPtr<SampleTables> sample_tables { make_ref_counted<SampleTables>() };
Optional<SampleEntry const&> sample_entry_for_description_index(u32 sample_description_index) const
{
@@ -134,6 +170,7 @@ struct TrackFragmentContext {
i64 composition_to_presentation_offset { 0 };
size_t sample_description_count { 0 };
TrackFragmentSampleDefaults sample_defaults;
+ i64 next_decode_time { 0 };
};
using TrackFragmentContexts = HashMap<u32, TrackFragmentContext>;
@@ -160,6 +197,16 @@ struct TrackRun {
size_t data_end() const { return data_position + total_data_size; }
+ i64 end_decode_time() const
+ {
+ if (sample_durations.is_empty())
+ return saturating_add(first_decode_time, AK::clamp_to<i64>(static_cast<u64>(sample_count) * defaults.sample_duration));
+ auto end = first_decode_time;
+ for (auto duration : sample_durations)
+ end = saturating_add(end, static_cast<i64>(duration));
+ return end;
+ }
+
u32 duration_of_sample(u32 index) const
{
return sample_durations.is_empty() ? defaults.sample_duration : sample_durations[index];
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.cpp b/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.cpp
index 907ccdde570..6455d36a712 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.cpp
+++ b/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.cpp
@@ -11,7 +11,7 @@
namespace Media::ISOBMFF {
FragmentSampleIterator::FragmentSampleIterator(MovieFragment&& fragment)
- : m_fragment(move(fragment))
+ : m_fragment(make_ref_counted<SharedFragment>(move(fragment)))
{
enter_run();
}
@@ -19,7 +19,7 @@ FragmentSampleIterator::FragmentSampleIterator(MovieFragment&& fragment)
Sample FragmentSampleIterator::peek() const
{
VERIFY(has_next());
- auto const& run = m_fragment.track_runs[m_run_index];
+ auto const& run = m_fragment->value.track_runs[m_run_index];
auto decode_time = saturating_add(m_decode_time, run.composition_to_presentation_offset);
auto presentation_time = saturating_add(decode_time, run.composition_time_offset_of_sample(m_sample_index));
auto presentation_end_time = saturating_add(presentation_time, static_cast<i64>(run.duration_of_sample(m_sample_index)));
@@ -42,7 +42,7 @@ Sample FragmentSampleIterator::peek() const
void FragmentSampleIterator::advance()
{
VERIFY(has_next());
- auto const& run = m_fragment.track_runs[m_run_index];
+ auto const& run = m_fragment->value.track_runs[m_run_index];
m_decode_time = saturating_add(m_decode_time, static_cast<i64>(run.duration_of_sample(m_sample_index)));
m_data_position += run.size_of_sample(m_sample_index);
m_sample_index++;
@@ -55,12 +55,12 @@ void FragmentSampleIterator::advance()
void FragmentSampleIterator::enter_run()
{
- while (m_run_index < m_fragment.track_runs.size() && m_fragment.track_runs[m_run_index].sample_count == 0)
+ while (m_run_index < m_fragment->value.track_runs.size() && m_fragment->value.track_runs[m_run_index].sample_count == 0)
m_run_index++;
if (!has_next())
return;
- m_decode_time = m_fragment.track_runs[m_run_index].first_decode_time;
- m_data_position = m_fragment.track_runs[m_run_index].data_position;
+ m_decode_time = m_fragment->value.track_runs[m_run_index].first_decode_time;
+ m_data_position = m_fragment->value.track_runs[m_run_index].data_position;
}
}
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.h b/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.h
index 80b80409867..d56f335443b 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.h
+++ b/Libraries/LibMedia/Containers/ISOBMFF/FragmentSampleIterator.h
@@ -28,14 +28,21 @@ class MEDIA_API FragmentSampleIterator {
public:
explicit FragmentSampleIterator(MovieFragment&&);
- bool has_next() const { return m_run_index < m_fragment.track_runs.size(); }
+ bool has_next() const { return m_run_index < m_fragment->value.track_runs.size(); }
Sample peek() const;
void advance();
private:
void enter_run();
- MovieFragment m_fragment;
+ struct SharedFragment : public AtomicRefCounted<SharedFragment> {
+ explicit SharedFragment(MovieFragment fragment)
+ : value(move(fragment))
+ {
+ }
+ MovieFragment value;
+ };
+ NonnullRefPtr<SharedFragment const> m_fragment;
size_t m_run_index { 0 };
u32 m_sample_index { 0 };
i64 m_decode_time { 0 };
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cpp b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cpp
new file mode 100644
index 00000000000..2ad63d27553
--- /dev/null
+++ b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.cpp
@@ -0,0 +1,296 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "ISOBMFFDemuxer.h"
+#include "Reader.h"
+
+namespace Media::ISOBMFF {
+
+bool ISOBMFFDemuxer::supports_container_mime_type(ContainerMimeType type)
+{
+ return type.container_id == ContainerID::ISOBMFF && type.media_type != ContainerMediaType::Application;
+}
+
+bool ISOBMFFDemuxer::supports_codec_in_container(ContainerID container, CodecID codec)
+{
+ return container == ContainerID::ISOBMFF && Reader::supports_codec(codec);
+}
+
+DecoderErrorOr<NonnullRefPtr<Demuxer>> ISOBMFFDemuxer::from_stream(NonnullRefPtr<MediaStream> const& source)
+{
+ Streamer stream(source->create_cursor());
+ auto first = Reader::read_box_header(stream);
+ if (first.is_error() || !first_is_one_of(first.value().type, FILE_TYPE_BOX, MOVIE_BOX, FREE_SPACE_BOX, MEDIA_DATA_BOX, SKIP_BOX, WIDE_ATOM))
+ return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Stream is not ISO BMFF"sv);
+ auto header = first.release_value();
+ for (;;) {
+ if (header.type == MOVIE_BOX) {
+ auto movie = TRY(Reader::parse_movie_box(stream, header));
+ auto demuxer = make_ref_counted<ISOBMFFDemuxer>(source, move(movie), header.end_position().value_or(stream.position()));
+ demuxer->start_scan();
+ return demuxer;
+ }
+ if (!header.end_position().has_value())
+ return DecoderError::corrupted("ISO BMFF stream has no movie box"sv);
+ TRY(stream.seek_to_position(header.end_position().value()));
+ header = TRY(Reader::read_box_header(stream));
+ }
+}
+
+ISOBMFFDemuxer::ISOBMFFDemuxer(NonnullRefPtr<MediaStream> stream, Movie movie, size_t movie_end)
+ : m_stream(move(stream))
+ , m_movie(move(movie))
+ , m_movie_end(movie_end)
+{
+ m_durations->total = m_movie.duration_as_time().value_or({});
+ for (auto const& [id, track] : m_movie.tracks) {
+ auto duration = AK::Duration::from_time_units(AK::clamp_to<i64>(track->duration.value_or(0)), 1, track->timescale);
+ m_durations->tracks.set(id, duration);
+ m_durations->total = max(m_durations->total, duration);
+ }
+}
+
+ISOBMFFDemuxer::~ISOBMFFDemuxer()
+{
+ if (m_scan) {
+ m_scan->payload().cursor->abort();
+ m_scan->shutdown();
+ }
+}
+
+void ISOBMFFDemuxer::start_scan()
+{
+ auto cursor = m_stream->create_cursor();
+ cursor->set_is_blocking(false);
+ DemuxerScanState initial;
+ initial.duration = m_durations->total;
+ m_scan = DemuxerScanThread<ScanPayload>::start(m_stream, move(initial), { m_movie, m_movie_end, move(cursor), m_durations }, [](MediaStream& stream, ScanPayload& payload) {
+ DemuxerScanState state;
+ {
+ MutexLocker locker(payload.durations->mutex);
+ state.duration = payload.durations->total;
+ }
+ state.reached_end_of_stream = stream.closing_bytes_are_available();
+ auto ranges = stream.available_byte_ranges();
+ for (auto const& [id, track] : payload.movie.tracks) {
+ if (!first_is_one_of(track->handler_type, HandlerType::Audio, HandlerType::Video))
+ continue;
+ TimeRanges buffered;
+ AK::Duration duration;
+ auto iterator = SampleIterator::create(payload.cursor, payload.movie, id, payload.movie_end);
+ bool can_decode = false;
+ bool last_sample_available = false;
+ if (!iterator.is_error()) {
+ for (;;) {
+ auto next = iterator.value().next();
+ if (next.is_error()) {
+ state.reached_end_of_stream = false;
+ break;
+ }
+ if (!next.value().has_value())
+ break;
+ auto const& sample = next.value().value();
+ auto end = sample.presentation_timestamp + sample.duration;
+ duration = max(duration, end);
+ state.duration = max(state.duration, end);
+ bool available = any_of(ranges, [&](auto const& range) {
+ return sample.data_position >= range.start && sample.data_position <= range.end && sample.data_size <= range.end - sample.data_position;
+ });
+ last_sample_available = available;
+ if (!available)
+ can_decode = false;
+ else if (sample.is_sync_sample)
+ can_decode = true;
+ if (available && can_decode)
+ buffered.add_range(max(sample.presentation_timestamp, AK::Duration::zero()), end);
+ }
+ } else {
+ state.reached_end_of_stream = false;
+ }
+ state.track_buffered_ranges.append(move(buffered));
+ state.reached_end_of_stream &= last_sample_available;
+ {
+ MutexLocker locker(payload.durations->mutex);
+ auto& track_duration = payload.durations->tracks.get(id).value();
+ track_duration = max(track_duration, duration);
+ }
+ }
+ {
+ MutexLocker locker(payload.durations->mutex);
+ payload.durations->total = max(payload.durations->total, state.duration);
+ }
+ return state;
+ });
+}
+
+DecoderErrorOr<void> ISOBMFFDemuxer::create_context_for_track(Track const& track)
+{
+ auto cursor = m_stream->create_cursor();
+ auto iterator = TRY(SampleIterator::create(cursor, m_movie, track.identifier(), m_movie_end));
+ auto status = make<TrackStatus>(move(cursor), move(iterator));
+ MutexLocker locker(m_status_mutex);
+ VERIFY(m_statuses.set(track, move(status)) == HashSetResult::InsertedNewEntry);
+ return {};
+}
+
+ISOBMFFDemuxer::TrackStatus& ISOBMFFDemuxer::status_for_track(Track const& track)
+{
+ MutexLocker locker(m_status_mutex);
+ return **m_statuses.get(track);
+}
+
+DecoderErrorOr<Vector<Track>> ISOBMFFDemuxer::get_tracks_for_type(TrackType type)
+{
+ Vector<Track> tracks;
+ for (auto const& entry : m_movie.tracks) {
+ if (track_type_from_handler_type(entry.value->handler_type) == type)
+ DECODER_TRY_ALLOC(tracks.try_append(track_from_track_entry(*entry.value, tracks.is_empty())));
+ }
+ return tracks;
+}
+
+DecoderErrorOr<Optional<Track>> ISOBMFFDemuxer::get_preferred_track_for_type(TrackType type)
+{
+ auto tracks = TRY(get_tracks_for_type(type));
+ for (auto const& track : tracks) {
+ if (m_movie.tracks.get(track.identifier()).value()->is_enabled)
+ return Optional<Track> { track };
+ }
+ if (tracks.is_empty())
+ return Optional<Track> {};
+ return Optional<Track> { tracks.first() };
+}
+
+DecoderErrorOr<CodedFrame> ISOBMFFDemuxer::get_next_sample_for_track(Track const& track)
+{
+ auto& status = status_for_track(track);
+ if (!status.pending_sample.has_value())
+ status.pending_sample = TRY(status.iterator.next());
+ if (!status.pending_sample.has_value())
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "No more ISO BMFF samples"sv);
+ auto const& sample = status.pending_sample.value();
+ Streamer stream(status.cursor);
+ TRY(stream.seek_to_position(sample.data_position));
+ auto data = TRY(stream.read_bytes(sample.data_size));
+ auto entry = m_movie.tracks.get(track.identifier()).value()->sample_entry_for_description_index(sample.sample_description_index);
+ if (!entry.has_value())
+ return DecoderError::corrupted("Invalid sample description index"sv);
+ Optional<FixedArray<u8>> configuration;
+ if (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;
+ 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();
+ return frame;
+}
+
+DecoderErrorOr<Optional<ISOBMFFDemuxer::SeekPoint>> ISOBMFFDemuxer::find_seek_point(NonnullRefPtr<MediaStreamCursor> cursor, Track const& track, AK::Duration target, SeekMode mode)
+{
+ auto iterator = TRY(SampleIterator::create(move(cursor), m_movie, track.identifier(), m_movie_end));
+ Optional<SeekPoint> before;
+ Optional<SeekPoint> after;
+ bool first_sample = true;
+ for (;;) {
+ auto next = iterator.next();
+ if (next.is_error() && next.error().category() == DecoderErrorCategory::NeedsMoreInput && (before.has_value() || after.has_value()))
+ break;
+ auto sample = TRY(move(next));
+ if (!sample.has_value())
+ break;
+ if (first_sample || sample->is_sync_sample) {
+ auto pts = sample->presentation_timestamp;
+ if (pts <= target && (!before.has_value() || pts > before->sample.presentation_timestamp))
+ before = SeekPoint { iterator, sample.value() };
+ if (pts > target && (!after.has_value() || pts < after->sample.presentation_timestamp))
+ after = SeekPoint { iterator, sample.value() };
+ }
+ first_sample = false;
+ if (mode == SeekMode::FastAfter) {
+ if (after.has_value())
+ break;
+ } else if (sample->presentation_timestamp >= target || sample->presentation_timestamp + sample->duration > target) {
+ // Reordering may leave a closer keyframe ahead in decode order; decoding forward is sufficient.
+ break;
+ }
+ }
+ if (mode == SeekMode::FastAfter)
+ return after;
+ return before.has_value() ? move(before) : move(after);
+}
+
+AK::Duration ISOBMFFDemuxer::select_fast_seek_target_for_track(Track const& track, AK::Duration target, SeekMode mode)
+{
+ auto cursor = m_stream->create_cursor();
+ cursor->set_is_blocking(false);
+ auto point = find_seek_point(move(cursor), track, target, mode);
+ if (point.is_error() || !point.value().has_value())
+ return target;
+ return point.value()->sample.presentation_timestamp;
+}
+
+DecoderErrorOr<DemuxerSeekResult> ISOBMFFDemuxer::seek_to_most_recent_keyframe(Track const& track, AK::Duration target, DemuxerSeekOptions options)
+{
+ auto& status = status_for_track(track);
+ if (has_flag(options, DemuxerSeekOptions::NeedCodecConfiguration))
+ status.description_index.clear();
+ auto 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)
+ return DemuxerSeekResult::KeptCurrentPosition;
+ status.iterator = move(point->iterator);
+ status.pending_sample = point->sample;
+ status.last_timestamp.clear();
+ return DemuxerSeekResult::MovedPosition;
+}
+
+DecoderErrorOr<AK::Duration> ISOBMFFDemuxer::duration_of_track(Track const& track)
+{
+ MutexLocker locker(m_durations->mutex);
+ auto duration = m_durations->tracks.get(track.identifier());
+ if (!duration.has_value())
+ return DecoderError::corrupted("Unknown track"sv);
+ return duration.value();
+}
+
+DecoderErrorOr<AK::Duration> ISOBMFFDemuxer::total_duration()
+{
+ MutexLocker locker(m_durations->mutex);
+ return m_durations->total;
+}
+
+DemuxerScanState const& ISOBMFFDemuxer::scan_state() const
+{
+ return m_scan->main_thread_state();
+}
+
+void ISOBMFFDemuxer::set_scan_state_change_handler(ScanStateChangeHandler handler)
+{
+ m_scan->set_change_handler([handler = move(handler)] {
+ if (handler)
+ handler({});
+ });
+}
+
+void ISOBMFFDemuxer::set_blocking_reads_aborted_for_track(Track const& track)
+{
+ status_for_track(track).cursor->abort();
+}
+
+void ISOBMFFDemuxer::reset_blocking_reads_aborted_for_track(Track const& track)
+{
+ status_for_track(track).cursor->reset_abort();
+}
+
+void ISOBMFFDemuxer::set_read_blocked_change_handler_for_track(Track const& track, ReadBlockedChangeHandler handler)
+{
+ status_for_track(track).cursor->set_blocked_change_handler(move(handler));
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h
new file mode 100644
index 00000000000..64bc2a5db3e
--- /dev/null
+++ b/Libraries/LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include "SampleIterator.h"
+#include <AK/Mutex.h>
+#include <LibMedia/ContainerID.h>
+#include <LibMedia/Demuxer.h>
+#include <LibMedia/DemuxerScanThread.h>
+
+namespace Media::ISOBMFF {
+
+class MEDIA_API ISOBMFFDemuxer final : public Demuxer {
+public:
+ static DecoderErrorOr<NonnullRefPtr<Demuxer>> from_stream(NonnullRefPtr<MediaStream> const&);
+ static bool supports_container_mime_type(ContainerMimeType);
+ static bool supports_codec_in_container(ContainerID, CodecID);
+ ISOBMFFDemuxer(NonnullRefPtr<MediaStream>, Movie, size_t movie_end);
+ virtual ~ISOBMFFDemuxer() override;
+
+ virtual DecoderErrorOr<void> create_context_for_track(Track const&) override;
+ virtual DecoderErrorOr<Vector<Track>> get_tracks_for_type(TrackType) override;
+ virtual DecoderErrorOr<Optional<Track>> get_preferred_track_for_type(TrackType) override;
+ virtual DecoderErrorOr<CodedFrame> get_next_sample_for_track(Track const&) override;
+ virtual AK::Duration select_fast_seek_target_for_track(Track const&, AK::Duration, SeekMode) override;
+ virtual DecoderErrorOr<DemuxerSeekResult> seek_to_most_recent_keyframe(Track const&, AK::Duration, DemuxerSeekOptions) override;
+ virtual DecoderErrorOr<AK::Duration> duration_of_track(Track const&) override;
+ virtual DecoderErrorOr<AK::Duration> total_duration() override;
+ virtual DemuxerScanState const& scan_state() const LIFETIME_BOUND override;
+ virtual void set_scan_state_change_handler(ScanStateChangeHandler) override;
+ virtual void set_blocking_reads_aborted_for_track(Track const&) override;
+ virtual void reset_blocking_reads_aborted_for_track(Track const&) override;
+ virtual void set_read_blocked_change_handler_for_track(Track const&, ReadBlockedChangeHandler) override;
+
+private:
+ struct TrackStatus {
+ AK_MAKE_NONCOPYABLE(TrackStatus);
+ AK_MAKE_NONMOVABLE(TrackStatus);
+ AK_ALLOC_WITH_KMALLOC;
+
+ TrackStatus(NonnullRefPtr<MediaStreamCursor> cursor, SampleIterator iterator)
+ : cursor(move(cursor))
+ , iterator(move(iterator))
+ {
+ }
+
+ NonnullRefPtr<MediaStreamCursor> cursor;
+ SampleIterator iterator;
+ Optional<Sample> pending_sample;
+ Optional<AK::Duration> last_timestamp;
+ Optional<u32> description_index;
+ };
+ struct Durations : public AtomicRefCounted<Durations> {
+ Mutex mutex;
+ HashMap<u32, AK::Duration> tracks;
+ AK::Duration total;
+ };
+ struct ScanPayload {
+ Movie movie;
+ size_t movie_end;
+ NonnullRefPtr<MediaStreamCursor> cursor;
+ NonnullRefPtr<Durations> durations;
+ };
+ struct SeekPoint {
+ SampleIterator iterator;
+ Sample sample;
+ };
+ DecoderErrorOr<Optional<SeekPoint>> find_seek_point(NonnullRefPtr<MediaStreamCursor>, Track const&, AK::Duration, SeekMode);
+ TrackStatus& status_for_track(Track const&);
+ void start_scan();
+ NonnullRefPtr<MediaStream> m_stream;
+ Movie m_movie;
+ size_t m_movie_end;
+ Mutex m_status_mutex;
+ HashMap<Track, NonnullOwnPtr<TrackStatus>> m_statuses;
+ NonnullRefPtr<Durations> m_durations { make_ref_counted<Durations>() };
+ RefPtr<DemuxerScanThread<ScanPayload>> m_scan;
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp b/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp
index abaf2f7584f..39bf8d4a77e 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp
+++ b/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp
@@ -271,6 +271,9 @@ static void synthesize_missing_aac_configurations(TrackEntry& track)
for (auto& entry : track.sample_entries) {
if (entry.format != MPEG4_AUDIO_SAMPLE_ENTRY || !entry.codec_initialization_data.is_empty())
continue;
+ // mp4a also carries MPEG-1/2 audio, which has no DecoderSpecificInfo. Preserve the codec identified by esds.
+ if (!first_is_one_of(entry.codec_id, CodecID::Unknown, CodecID::AAC))
+ continue;
if (!entry.audio.has_value() || entry.audio->sample_rate == 0)
continue;
auto channel_count = entry.audio->channel_count;
@@ -458,12 +461,99 @@ DecoderErrorOr<void> Reader::parse_sample_table_box(Streamer& streamer, BoxHeade
return parse_child_boxes(streamer, header, IsTopLevel::No, [&](BoxHeader const& child) -> DecoderErrorOr<IterationDecision> {
if (child.type == SAMPLE_DESCRIPTION_BOX) {
track.sample_entries = TRY(parse_sample_description_box(streamer, child, track.handler_type));
- } else if (first_is_one_of(child.type, TIME_TO_SAMPLE_BOX, SAMPLE_TO_CHUNK_BOX, CHUNK_OFFSET_BOX, CHUNK_LARGE_OFFSET_BOX)) {
- // FIXME: Parse the sample tables so that unfragmented files can be demuxed. For now we only record
- // whether they describe any samples at all.
- TRY(read_full_box_header(streamer));
- track.sample_table_entry_count += static_cast<u64>(TRY(streamer.read<u32>()));
+ return IterationDecision::Continue;
+ }
+ if (!first_is_one_of(child.type, TIME_TO_SAMPLE_BOX, FourCC { "ctts" }, SAMPLE_TO_CHUNK_BOX,
+ SAMPLE_SIZE_BOX, FourCC { "stz2" }, CHUNK_OFFSET_BOX, CHUNK_LARGE_OFFSET_BOX, FourCC { "stss" }))
+ return IterationDecision::Continue;
+
+ bool is_size_table = first_is_one_of(child.type, SAMPLE_SIZE_BOX, FourCC { "stz2" });
+ if (child.content_size.value() < (is_size_table ? 12u : 8u))
+ return DecoderError::corrupted("Sample table is smaller than its header"sv);
+ auto full_box = TRY(read_full_box_header(streamer));
+ if (full_box.version > (child.type == FourCC { "ctts" } ? 1 : 0))
+ return DecoderError::corrupted("Unsupported sample table version"sv);
+
+ auto validate_entries = [&](u32 count, u8 bits_per_entry) -> DecoderErrorOr<void> {
+ auto required_bytes = (static_cast<u64>(count) * bits_per_entry + 7) / 8;
+ if (required_bytes > child.end_position().value() - streamer.position())
+ return DecoderError::corrupted("Sample table is smaller than the entries it declares"sv);
+ return {};
+ };
+ auto& tables = *track.sample_tables;
+ if (is_size_table) {
+ if (tables.sample_sizes.has_value())
+ return DecoderError::corrupted("Duplicate sample table"sv);
+ SampleSizes sizes;
+ auto size_field = TRY(streamer.read<u32>());
+ u8 bits_per_entry = 32;
+ if (child.type == SAMPLE_SIZE_BOX) {
+ sizes.default_size = size_field;
+ } else {
+ bits_per_entry = size_field & 0xff;
+ if (!first_is_one_of(bits_per_entry, 4, 8, 16))
+ return DecoderError::corrupted("Invalid compact sample size width"sv);
+ }
+ sizes.sample_count = TRY(streamer.read<u32>());
+ if (sizes.default_size == 0) {
+ TRY(validate_entries(sizes.sample_count, bits_per_entry));
+ DECODER_TRY_ALLOC(sizes.sizes.try_ensure_capacity(sizes.sample_count));
+ u8 packed_sizes = 0;
+ for (u32 index = 0; index < sizes.sample_count; ++index) {
+ u32 size;
+ if (bits_per_entry == 32)
+ size = TRY(streamer.read<u32>());
+ else if (bits_per_entry == 16)
+ size = TRY(streamer.read<u16>());
+ else if (bits_per_entry == 8)
+ size = TRY(streamer.read<u8>());
+ else {
+ if (index % 2 == 0)
+ packed_sizes = TRY(streamer.read<u8>());
+ size = (index % 2 == 0 ? packed_sizes >> 4 : packed_sizes) & 0xf;
+ }
+ sizes.sizes.unchecked_append(size);
+ }
+ }
+ tables.sample_sizes = move(sizes);
+ return IterationDecision::Continue;
+ }
+
+ auto count = TRY(streamer.read<u32>());
+ auto read_entries = [&](auto& table, u8 bits_per_entry, auto read_entry) -> DecoderErrorOr<void> {
+ if (table.has_value())
+ return DecoderError::corrupted("Duplicate sample table"sv);
+ TRY(validate_entries(count, bits_per_entry));
+ table.emplace();
+ DECODER_TRY_ALLOC(table->try_ensure_capacity(count));
+ for (u32 index = 0; index < count; ++index)
+ table->unchecked_append(TRY(read_entry()));
+ return {};
+ };
+ if (child.type == TIME_TO_SAMPLE_BOX) {
+ TRY(read_entries(tables.time_to_sample, 64, [&]() -> DecoderErrorOr<TimeToSampleEntry> {
+ return TimeToSampleEntry { TRY(streamer.read<u32>()), TRY(streamer.read<u32>()) };
+ }));
+ } else if (child.type == FourCC { "ctts" }) {
+ TRY(read_entries(tables.composition_offsets, 64, [&]() -> DecoderErrorOr<CompositionOffsetEntry> {
+ auto sample_count = TRY(streamer.read<u32>());
+ i64 offset = full_box.version == 1 ? static_cast<i64>(TRY(streamer.read<i32>())) : TRY(streamer.read<u32>());
+ return CompositionOffsetEntry { sample_count, offset };
+ }));
+ } else if (child.type == SAMPLE_TO_CHUNK_BOX) {
+ TRY(read_entries(tables.sample_to_chunk, 96, [&]() -> DecoderErrorOr<SampleToChunkEntry> {
+ return SampleToChunkEntry { TRY(streamer.read<u32>()), TRY(streamer.read<u32>()), TRY(streamer.read<u32>()) };
+ }));
+ } else if (first_is_one_of(child.type, CHUNK_OFFSET_BOX, CHUNK_LARGE_OFFSET_BOX)) {
+ bool large = child.type == CHUNK_LARGE_OFFSET_BOX;
+ TRY(read_entries(tables.chunk_offsets, large ? 64 : 32, [&]() -> DecoderErrorOr<u64> {
+ return large ? TRY(streamer.read<u64>()) : TRY(streamer.read<u32>());
+ }));
+ } else {
+ TRY(read_entries(tables.sync_samples, 32, [&] { return streamer.read<u32>(); }));
}
+ if (first_is_one_of(child.type, TIME_TO_SAMPLE_BOX, SAMPLE_TO_CHUNK_BOX, CHUNK_OFFSET_BOX, CHUNK_LARGE_OFFSET_BOX))
+ track.sample_table_entry_count += count;
return IterationDecision::Continue;
});
}
@@ -757,6 +847,15 @@ DecoderErrorOr<void> Reader::parse_track_fragment_box(Streamer& streamer, BoxHea
return DecoderError::format(DecoderErrorCategory::Corrupted, "Track fragment refers to unknown track ID {}", track_id);
context = maybe_context.release_value();
defaults = context.sample_defaults;
+ next_sample_decode_time = context.next_decode_time;
+ // A track may have multiple traf boxes in one moof. Without tfdt, continue its preceding run.
+ for (size_t index = fragment.track_runs.size(); index > 0; --index) {
+ auto const& run = fragment.track_runs[index - 1];
+ if (run.track_id == track_id) {
+ next_sample_decode_time = run.end_decode_time();
+ break;
+ }
+ }
auto has_base_data_offset = (full_box.flags & TRACK_FRAGMENT_BASE_DATA_OFFSET_PRESENT) != 0;
auto default_base_is_movie_fragment = !has_base_data_offset && (full_box.flags & TRACK_FRAGMENT_DEFAULT_BASE_IS_MOVIE_FRAGMENT) != 0;
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/SampleIterator.cpp b/Libraries/LibMedia/Containers/ISOBMFF/SampleIterator.cpp
new file mode 100644
index 00000000000..e1dc4debb7b
--- /dev/null
+++ b/Libraries/LibMedia/Containers/ISOBMFF/SampleIterator.cpp
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "SampleIterator.h"
+#include "Reader.h"
+#include <AK/Checked.h>
+#include <AK/SaturatingMath.h>
+
+namespace Media::ISOBMFF {
+
+DecoderErrorOr<SampleTableIterator> SampleTableIterator::create(TrackEntry const& track)
+{
+ SampleTableIterator iterator(*track.sample_tables);
+ auto const& tables = *iterator.m_tables;
+ if (tables.time_to_sample.has_value())
+ iterator.m_times = tables.time_to_sample->span();
+ if (tables.composition_offsets.has_value())
+ iterator.m_compositions = tables.composition_offsets->span();
+ if (tables.sample_to_chunk.has_value())
+ iterator.m_chunks = tables.sample_to_chunk->span();
+ if (tables.chunk_offsets.has_value())
+ iterator.m_offsets = tables.chunk_offsets->span();
+ if (tables.sync_samples.has_value())
+ iterator.m_sync = tables.sync_samples->span();
+ if (tables.sample_sizes.has_value())
+ iterator.m_sample_count = tables.sample_sizes->sample_count;
+ else if (track.sample_table_entry_count != 0)
+ return DecoderError::corrupted("Missing sample sizes"sv);
+ return iterator;
+}
+
+DecoderErrorOr<Optional<Sample>> SampleTableIterator::next(TrackEntry const& track)
+{
+ if (m_sample_index == m_sample_count) {
+ if (m_time_index != m_times.size() || m_composition_index != m_compositions.size()
+ || m_chunk_index != m_offsets.size() || m_chunk_run_index != m_chunks.size() || m_sync_index != m_sync.size())
+ return DecoderError::corrupted("Sample tables contain unused entries"sv);
+ return Optional<Sample> {};
+ }
+ if (m_time_remaining == 0) {
+ if (m_time_index == m_times.size())
+ return DecoderError::corrupted("Sample timing table ended early"sv);
+ auto const& entry = m_times[m_time_index++];
+ m_time_remaining = entry.sample_count;
+ m_delta = entry.sample_delta;
+ if (m_time_remaining == 0 || m_time_remaining > m_sample_count - m_sample_index)
+ return DecoderError::corrupted("Invalid sample timing run length"sv);
+ }
+ if (m_tables->composition_offsets.has_value() && m_composition_remaining == 0) {
+ if (m_composition_index == m_compositions.size())
+ return DecoderError::corrupted("Composition offset table ended early"sv);
+ auto const& entry = m_compositions[m_composition_index++];
+ m_composition_remaining = entry.sample_count;
+ m_composition_offset = entry.sample_offset;
+ if (m_composition_remaining == 0 || m_composition_remaining > m_sample_count - m_sample_index)
+ return DecoderError::corrupted("Invalid composition offset run length"sv);
+ }
+ if (m_chunk_remaining == 0) {
+ if (m_chunk_index == m_offsets.size())
+ return DecoderError::corrupted("Chunk offset table ended early"sv);
+ ++m_chunk_index;
+ if (m_chunk_index == m_next_chunk_run) {
+ if (m_chunk_run_index == m_chunks.size())
+ return DecoderError::corrupted("Sample to chunk table ended early"sv);
+ auto const& entry = m_chunks[m_chunk_run_index++];
+ if (entry.first_chunk != m_chunk_index)
+ return DecoderError::corrupted("Invalid first chunk in sample to chunk table"sv);
+ m_samples_per_chunk = entry.samples_per_chunk;
+ m_description_index = entry.sample_description_index;
+ if (m_samples_per_chunk == 0 || !track.sample_entry_for_description_index(m_description_index).has_value())
+ return DecoderError::corrupted("Invalid sample to chunk entry"sv);
+ m_next_chunk_run = 0;
+ if (m_chunk_run_index < m_chunks.size()) {
+ m_next_chunk_run = m_chunks[m_chunk_run_index].first_chunk;
+ if (m_next_chunk_run <= m_chunk_index || m_next_chunk_run > m_offsets.size())
+ return DecoderError::corrupted("Sample to chunk entries are out of order"sv);
+ }
+ }
+ m_chunk_remaining = m_samples_per_chunk;
+ if (m_chunk_remaining > m_sample_count - m_sample_index)
+ return DecoderError::corrupted("Chunk contains too many samples"sv);
+ auto offset = m_offsets[m_chunk_index - 1];
+ if (offset > NumericLimits<i64>::max())
+ return DecoderError::corrupted("Chunk offset is too large"sv);
+ m_data_position = offset;
+ }
+ auto size = m_tables->sample_sizes->size_of_sample(m_sample_index);
+ if (m_tables->sync_samples.has_value() && m_next_sync_sample <= m_sample_index && m_sync_index < m_sync.size()) {
+ auto next = m_sync[m_sync_index++];
+ if (next <= m_next_sync_sample || next > m_sample_count)
+ return DecoderError::corrupted("Invalid sync sample number"sv);
+ m_next_sync_sample = next;
+ }
+ auto decode_time = saturating_add(m_decode_time, track.composition_to_presentation_offset);
+ auto pts = saturating_add(decode_time, m_composition_offset);
+ auto presentation_time = AK::Duration::from_time_units(pts, 1, track.timescale);
+ Sample sample {
+ .track_id = track.track_id,
+ .sample_description_index = m_description_index,
+ .decode_timestamp = AK::Duration::from_time_units(decode_time, 1, track.timescale),
+ .presentation_timestamp = presentation_time,
+ .duration = AK::Duration::from_time_units(saturating_add(pts, static_cast<i64>(m_delta)), 1, track.timescale) - presentation_time,
+ .is_sync_sample = !m_tables->sync_samples.has_value() || m_next_sync_sample == m_sample_index + 1,
+ .data_position = m_data_position,
+ .data_size = size,
+ };
+ Checked<size_t> end = m_data_position;
+ end += size;
+ if (end.has_overflow() || end.value() > NumericLimits<i64>::max())
+ return DecoderError::corrupted("Sample data offset overflow"sv);
+ m_data_position = end.value();
+ m_decode_time = saturating_add(m_decode_time, static_cast<i64>(m_delta));
+ ++m_sample_index;
+ --m_time_remaining;
+ --m_chunk_remaining;
+ if (m_composition_remaining)
+ --m_composition_remaining;
+ return Optional<Sample> { sample };
+}
+
+SampleIterator::SampleIterator(NonnullRefPtr<MediaStreamCursor> cursor, NonnullRefPtr<TrackEntry const> track, SampleTableIterator table, TrackFragmentContexts contexts, size_t movie_end, bool has_fragments)
+ : m_cursor(move(cursor))
+ , m_track(move(track))
+ , m_table(move(table))
+ , m_contexts(move(contexts))
+ , m_next_box(movie_end)
+ , m_finished(!has_fragments)
+{
+}
+
+DecoderErrorOr<SampleIterator> SampleIterator::create(NonnullRefPtr<MediaStreamCursor> cursor, Movie const& movie, u32 track_id, size_t movie_end)
+{
+ auto track = movie.tracks.get(track_id);
+ if (!track.has_value())
+ return DecoderError::corrupted("Unknown track"sv);
+ auto table = TRY(SampleTableIterator::create(**track));
+ TrackFragmentContexts contexts;
+ for (auto const& [id, entry] : movie.tracks)
+ contexts.set(id, { entry->timescale, entry->composition_to_presentation_offset, entry->sample_entries.size(), entry->fragment_defaults, AK::clamp_to<i64>(entry->duration.value_or(0)) });
+ return SampleIterator(move(cursor), **track, move(table), move(contexts), movie_end, movie.has_movie_extends_box);
+}
+
+DecoderErrorOr<Optional<Sample>> SampleIterator::next()
+{
+ if (m_cursor->is_aborted())
+ return DecoderError::with_description(DecoderErrorCategory::Aborted, "Sample iteration aborted"sv);
+ Streamer stream(m_cursor);
+ if (!m_finished_table) {
+ auto table = m_table;
+ auto sample = TRY(table.next(*m_track));
+ m_table = table;
+ if (sample.has_value())
+ return sample;
+ m_contexts.get(m_track->track_id)->next_decode_time = table.next_decode_time();
+ m_finished_table = true;
+ }
+ while (!m_finished) {
+ if (m_cursor->is_aborted())
+ return DecoderError::with_description(DecoderErrorCategory::Aborted, "Sample iteration aborted"sv);
+ if (m_fragment.has_value() && m_fragment->has_next()) {
+ auto sample = m_fragment->peek();
+ m_fragment->advance();
+ if (sample.track_id == m_track->track_id)
+ return Optional<Sample> { sample };
+ continue;
+ }
+ if (m_cursor->size().has_value() && m_next_box >= m_cursor->size().value()) {
+ m_finished = true;
+ break;
+ }
+ TRY(stream.seek_to_position(m_next_box));
+ auto header = TRY(Reader::read_box_header(stream));
+ if (!header.end_position().has_value()) {
+ // A box extending to EOF cannot be followed by another fragment.
+ m_finished = true;
+ break;
+ }
+ if (header.type == MOVIE_FRAGMENT_BOX) {
+ auto fragment = TRY(Reader::parse_movie_fragment_box(stream, header, m_contexts));
+ for (auto const& run : fragment.track_runs)
+ m_contexts.get(run.track_id)->next_decode_time = run.end_decode_time();
+ m_fragment.emplace(move(fragment));
+ }
+ m_next_box = header.end_position().value();
+ }
+ return Optional<Sample> {};
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/SampleIterator.h b/Libraries/LibMedia/Containers/ISOBMFF/SampleIterator.h
new file mode 100644
index 00000000000..641f6e3c5cc
--- /dev/null
+++ b/Libraries/LibMedia/Containers/ISOBMFF/SampleIterator.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include "FragmentSampleIterator.h"
+#include "Streamer.h"
+
+namespace Media::ISOBMFF {
+
+// A constant-sized cursor over shared sample tables. Copies are cheap seek bookmarks.
+class MEDIA_API SampleTableIterator {
+public:
+ static DecoderErrorOr<SampleTableIterator> create(TrackEntry const&);
+ DecoderErrorOr<Optional<Sample>> next(TrackEntry const&);
+ i64 next_decode_time() const { return m_decode_time; }
+
+private:
+ explicit SampleTableIterator(NonnullRefPtr<SampleTables const> tables)
+ : m_tables(move(tables))
+ {
+ }
+ NonnullRefPtr<SampleTables const> m_tables;
+ ReadonlySpan<TimeToSampleEntry> m_times;
+ ReadonlySpan<CompositionOffsetEntry> m_compositions;
+ ReadonlySpan<SampleToChunkEntry> m_chunks;
+ ReadonlySpan<u64> m_offsets;
+ ReadonlySpan<u32> m_sync;
+ u32 m_sample_count { 0 };
+ u32 m_sample_index { 0 };
+ u32 m_time_index { 0 };
+ u32 m_time_remaining { 0 };
+ u32 m_delta { 0 };
+ u32 m_composition_index { 0 };
+ u32 m_composition_remaining { 0 };
+ i64 m_composition_offset { 0 };
+ u32 m_chunk_index { 0 };
+ u32 m_chunk_run_index { 0 };
+ u32 m_chunk_remaining { 0 };
+ u32 m_samples_per_chunk { 0 };
+ u32 m_description_index { 0 };
+ u32 m_next_chunk_run { 1 };
+ u32 m_sync_index { 0 };
+ u32 m_next_sync_sample { 0 };
+ size_t m_data_position { 0 };
+ i64 m_decode_time { 0 };
+};
+
+// Delivers a track's moov samples followed by its moof samples, in decode order.
+class MEDIA_API SampleIterator {
+public:
+ static DecoderErrorOr<SampleIterator> create(NonnullRefPtr<MediaStreamCursor>, Movie const&, u32 track_id, size_t movie_end);
+ DecoderErrorOr<Optional<Sample>> next();
+ MediaStreamCursor& cursor() { return *m_cursor; }
+
+private:
+ SampleIterator(NonnullRefPtr<MediaStreamCursor>, NonnullRefPtr<TrackEntry const>, SampleTableIterator, TrackFragmentContexts, size_t, bool has_fragments);
+ NonnullRefPtr<MediaStreamCursor> m_cursor;
+ NonnullRefPtr<TrackEntry const> m_track;
+ SampleTableIterator m_table;
+ TrackFragmentContexts m_contexts;
+ Optional<FragmentSampleIterator> m_fragment;
+ size_t m_next_box { 0 };
+ bool m_finished_table { false };
+ bool m_finished { false };
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/Streamer.h b/Libraries/LibMedia/Containers/ISOBMFF/Streamer.h
index f3f7dcc73f2..c05823e23a4 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/Streamer.h
+++ b/Libraries/LibMedia/Containers/ISOBMFF/Streamer.h
@@ -24,7 +24,17 @@ public:
template<Integral T>
DecoderErrorOr<T> read()
{
- return m_stream_cursor->read_value<T>();
+ T value = 0;
+ auto start = m_stream_cursor->position();
+ auto count = TRY(m_stream_cursor->read_into({ &value, sizeof(T) }));
+ if (count != sizeof(T)) {
+ auto size = m_stream_cursor->size();
+ if (size.has_value() && (start > size.value() || sizeof(T) > size.value() - start))
+ return DecoderError::corrupted("Unexpected end of ISO BMFF stream"sv);
+ // Non-blocking cursors return short reads when a range has not arrived (or was evicted).
+ return DecoderError::with_description(DecoderErrorCategory::NeedsMoreInput, "ISO BMFF data is not available yet"sv);
+ }
+ return AK::convert_between_host_and_big_endian(value);
}
DecoderErrorOr<FourCC> read_four_cc();
diff --git a/Libraries/LibMedia/DemuxerRegistry.cpp b/Libraries/LibMedia/DemuxerRegistry.cpp
index 32929d3df6c..7900b9c7856 100644
--- a/Libraries/LibMedia/DemuxerRegistry.cpp
+++ b/Libraries/LibMedia/DemuxerRegistry.cpp
@@ -6,6 +6,7 @@
#include <AK/Array.h>
#include <LibMedia/Containers/ADTS/ADTSDemuxer.h>
+#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>
#include <LibMedia/Containers/MP3/MP3Demuxer.h>
#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
#include <LibMedia/DemuxerRegistry.h>
@@ -25,6 +26,7 @@ struct DemuxerRegistration {
};
static constexpr Array demuxers_in_priority_order {
+ DemuxerRegistration { ISOBMFF::ISOBMFFDemuxer::from_stream, ISOBMFF::ISOBMFFDemuxer::supports_container_mime_type, ISOBMFF::ISOBMFFDemuxer::supports_codec_in_container },
DemuxerRegistration { Matroska::MatroskaDemuxer::from_stream, Matroska::MatroskaDemuxer::supports_container_mime_type, Matroska::MatroskaDemuxer::supports_codec_in_container },
DemuxerRegistration { FFmpeg::FFmpegDemuxer::from_stream, FFmpeg::FFmpegDemuxer::supports_container_mime_type, FFmpeg::FFmpegDemuxer::supports_codec_in_container },
DemuxerRegistration { MP3::MP3Demuxer::from_stream, MP3::MP3Demuxer::supports_container_mime_type, MP3::MP3Demuxer::supports_codec_in_container },
diff --git a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp b/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
index 3be856b2521..f62fb3112c4 100644
--- a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
+++ b/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
@@ -146,7 +146,7 @@ static DecoderErrorOr<void> initialize_format_context(AVFormatContext*& format_c
AVDictionary* options = nullptr;
ScopeGuard free_options = [&] { av_dict_free(&options); };
- if (av_dict_set(&options, "format_whitelist", "flac,mov,ogg,wav", 0) < 0)
+ if (av_dict_set(&options, "format_whitelist", "flac,ogg,wav", 0) < 0)
return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg format whitelist"sv);
auto const& codecs = codec_whitelist();
diff --git a/Meta/CMake/flatpak/org.ladybird.Ladybird.json b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
index 724d6eae930..8711702eb19 100644
--- a/Meta/CMake/flatpak/org.ladybird.Ladybird.json
+++ b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
@@ -634,7 +634,7 @@
"name": "ffmpeg",
"buildsystem": "simple",
"build-commands": [
- "./configure --prefix=/app --libdir=/app/lib --enable-shared --disable-static --enable-pic --disable-doc --enable-debug --enable-runtime-cpudetect --disable-autodetect --build-suffix=-ladybird --disable-everything --disable-network --disable-ffmpeg --disable-ffplay --disable-ffprobe --enable-avcodec --disable-avdevice --enable-avformat --disable-avfilter --disable-postproc --enable-swresample --disable-swscale --enable-libdav1d --enable-zlib --enable-decoder=vp8,vp9,libdav1d,theora,vorbis,opus,flac,mp3float,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_alaw,pcm_mulaw --enable-parser=vp8,vp9,av1,flac,mpegaudio --enable-demuxer=ogg,mov,flac,wav --disable-optimizations",
+ "./configure --prefix=/app --libdir=/app/lib --enable-shared --disable-static --enable-pic --disable-doc --enable-debug --enable-runtime-cpudetect --disable-autodetect --build-suffix=-ladybird --disable-everything --disable-network --disable-ffmpeg --disable-ffplay --disable-ffprobe --enable-avcodec --disable-avdevice --enable-avformat --disable-avfilter --disable-postproc --enable-swresample --disable-swscale --enable-libdav1d --enable-zlib --enable-decoder=vp8,vp9,libdav1d,theora,vorbis,opus,flac,mp3float,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_alaw,pcm_mulaw --enable-parser=vp8,vp9,av1,flac,mpegaudio --enable-demuxer=ogg,flac,wav --disable-optimizations",
"make -j$(nproc) V=1",
"make install"
],
diff --git a/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake b/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
index ff5e681067c..c7d3765c3a6 100644
--- a/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
+++ b/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
@@ -268,7 +268,7 @@ if("ladybird-components" IN_LIST FEATURES)
set(OPTIONS "${OPTIONS} --disable-everything --disable-network")
set(OPTIONS "${OPTIONS} --enable-decoder=vp8,vp9,libdav1d,theora,vorbis,opus,flac,mp3float,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_alaw,pcm_mulaw")
set(OPTIONS "${OPTIONS} --enable-parser=vp8,vp9,av1,flac,mpegaudio")
- set(OPTIONS "${OPTIONS} --enable-demuxer=ogg,mov,flac,wav")
+ set(OPTIONS "${OPTIONS} --enable-demuxer=ogg,flac,wav")
endif()
if("swscale" IN_LIST FEATURES)
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index 1b09986ed6c..6b509e11535 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -62,6 +62,7 @@ target_link_libraries(TestDecodedAudioProducer PRIVATE LibGfx)
target_link_libraries(TestDisplayingVideoSink PRIVATE LibGfx)
target_link_libraries(TestVP9Decode PRIVATE LibGfx)
target_link_libraries(TestFFmpegDemuxer PRIVATE LibThreading)
+target_link_libraries(TestISOBMFF PRIVATE LibThreading)
target_link_libraries(TestMediaTime PRIVATE LibThreading)
target_link_libraries(TestVideoFramePool PRIVATE LibThreading)
target_link_libraries(TestIncrementallyPopulatedStream PRIVATE LibThreading)
diff --git a/Tests/LibMedia/TestDecodedVideoProducer.cpp b/Tests/LibMedia/TestDecodedVideoProducer.cpp
index 5b96d444e5c..6e342f1586b 100644
--- a/Tests/LibMedia/TestDecodedVideoProducer.cpp
+++ b/Tests/LibMedia/TestDecodedVideoProducer.cpp
@@ -168,12 +168,7 @@ DemuxerAndTrack demuxer_and_video_track_for(StringView path)
{
auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
- auto demuxer = MUST([&] -> Media::DecoderErrorOr<NonnullRefPtr<Media::Demuxer>> {
- auto matroska_result = Media::Matroska::MatroskaDemuxer::from_stream(stream);
- if (!matroska_result.is_error())
- return matroska_result.release_value();
- return Media::FFmpeg::FFmpegDemuxer::from_stream(stream);
- }());
+ auto demuxer = MUST(Media::create_demuxer(stream));
auto tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Video));
VERIFY(!tracks.is_empty());
return { move(demuxer), tracks[0] };
diff --git a/Tests/LibMedia/TestFFmpegDemuxer.cpp b/Tests/LibMedia/TestFFmpegDemuxer.cpp
index 47fa7314d1f..b050c7484d8 100644
--- a/Tests/LibMedia/TestFFmpegDemuxer.cpp
+++ b/Tests/LibMedia/TestFFmpegDemuxer.cpp
@@ -15,10 +15,11 @@
TEST_CASE(rejects_formats_handled_by_other_demuxers)
{
- auto file = MUST(Core::File::open("./vfr.mkv"sv, Core::File::OpenMode::Read));
- auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
-
- EXPECT(Media::FFmpeg::FFmpegDemuxer::from_stream(stream).is_error());
+ for (auto path : { "./vfr.mkv"sv, "./avc.mp4"sv }) {
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
+ EXPECT(Media::FFmpeg::FFmpegDemuxer::from_stream(stream).is_error());
+ }
}
TEST_CASE(read_after_aborted_blocking_read)
@@ -31,7 +32,7 @@ TEST_CASE(read_after_aborted_blocking_read)
// The fix was to only return AVERROR_EOF from the IO context callbacks, and then determine whether to change
// the error to an Aborted error within the FFmpegDemuxer on top of the avformat context that used the IO.
- auto file = MUST(Core::File::open("./avc.mp4"sv, Core::File::OpenMode::Read));
+ auto file = MUST(Core::File::open("./buffered-ranges/tone.wav"sv, Core::File::OpenMode::Read));
auto file_data = MUST(file->read_until_eof());
// Feed only a portion of the file into the stream so that the demuxer will eventually block
@@ -43,9 +44,9 @@ TEST_CASE(read_after_aborted_blocking_read)
// Create the demuxer from the partial stream.
IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::FFmpeg::FFmpegDemuxer::from_stream(stream));
- auto optional_track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video));
- VERIFY(optional_track.has_value());
- IGNORE_USE_IN_ESCAPING_LAMBDA auto track = optional_track.release_value();
+ auto tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio));
+ VERIFY(tracks.size() == 1);
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto track = tracks.first();
MUST(demuxer->create_context_for_track(track));
// Start a thread to read the frames in parallel and check the errors returned.
@@ -106,55 +107,3 @@ TEST_CASE(read_after_aborted_blocking_read)
// and then get EndOfStream.
MUST(reader_thread->join());
}
-
-static Optional<FixedArray<u8>> first_frame_codec_configuration(ByteBuffer const& data)
-{
- auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
- auto demuxer = MUST(Media::FFmpeg::FFmpegDemuxer::from_stream(stream));
- auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Audio));
- VERIFY(track.has_value());
- MUST(demuxer->create_context_for_track(*track));
-
- auto frame = MUST(demuxer->get_next_sample_for_track(*track));
- auto configuration = frame.new_codec_configuration();
- if (!configuration.has_value())
- return {};
- return MUST(FixedArray<u8>::create(*configuration));
-}
-
-TEST_CASE(aac_track_keeps_the_configuration_its_container_carries)
-{
- auto file = MUST(Core::File::open("./hevc_10bit.mp4"sv, Core::File::OpenMode::Read));
- auto configuration = first_frame_codec_configuration(MUST(file->read_until_eof()));
-
- // The track describes its own codec, so nothing is invented for it.
- EXPECT(configuration.has_value());
- EXPECT(configuration->size() >= 2);
-}
-
-TEST_CASE(aac_track_without_a_configuration_is_described_by_its_container)
-{
- auto file = MUST(Core::File::open("./hevc_10bit.mp4"sv, Core::File::OpenMode::Read));
- auto data = MUST(file->read_until_eof());
-
- // Renaming the Elementary Stream Descriptor Box leaves a track that states its sample rate and
- // channel count but never describes the codec that decodes it.
- Optional<size_t> esds;
- for (size_t index = 0; index + 4 <= data.size(); index++) {
- if (StringView { data.bytes().slice(index, 4) } == "esds"sv) {
- EXPECT(!esds.has_value());
- esds = index;
- }
- }
- VERIFY(esds.has_value());
- data.overwrite(*esds, "free", 4);
-
- auto configuration = first_frame_codec_configuration(data);
- EXPECT(configuration.has_value());
-
- // An Audio Specific Config of object type 2, sampling frequency index 3 and channel
- // configuration 1: Low Complexity AAC at the 48000 Hz mono the container declares.
- EXPECT_EQ(configuration->size(), 2u);
- EXPECT_EQ((*configuration)[0], 0x11);
- EXPECT_EQ((*configuration)[1], 0x88);
-}
diff --git a/Tests/LibMedia/TestH264Decode.cpp b/Tests/LibMedia/TestH264Decode.cpp
index f4e3c81a046..61801b4aa5f 100644
--- a/Tests/LibMedia/TestH264Decode.cpp
+++ b/Tests/LibMedia/TestH264Decode.cpp
@@ -4,9 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>
#include <LibMedia/Demuxer.h>
#include <LibMedia/DemuxerRegistry.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>
#include <LibMedia/FFmpeg/SystemFFmpeg.h>
#include <LibMedia/IncrementallyPopulatedStream.h>
@@ -87,7 +87,7 @@ TEST_CASE(avc_in_mp4_with_reordered_frames)
auto file = MUST(Core::File::open("./avc.mp4"sv, Core::File::OpenMode::Read));
auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
- auto demuxer = MUST(Media::FFmpeg::FFmpegDemuxer::from_stream(stream));
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(stream));
auto optional_track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video));
VERIFY(optional_track.has_value());
auto track = optional_track.release_value();
diff --git a/Tests/LibMedia/TestISOBMFF.cpp b/Tests/LibMedia/TestISOBMFF.cpp
index c0de8fe79e5..176035701cd 100644
--- a/Tests/LibMedia/TestISOBMFF.cpp
+++ b/Tests/LibMedia/TestISOBMFF.cpp
@@ -4,14 +4,19 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Atomic.h>
#include <AK/BitCast.h>
#include <AK/ByteBuffer.h>
#include <AK/NumericLimits.h>
+#include <LibCore/File.h>
#include <LibMedia/Containers/ISOBMFF/FragmentSampleIterator.h>
+#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>
#include <LibMedia/Containers/ISOBMFF/Reader.h>
#include <LibMedia/Containers/ISOBMFF/Streamer.h>
+#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMedia/ReadonlyBytesCursor.h>
#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
namespace {
@@ -300,7 +305,7 @@ void append_vp9_configuration_box(ByteBuffer& bytes)
finish_box(bytes, configuration);
}
-void append_video_movie(ByteBuffer& bytes, char const (&format)[5], void (*append_configuration_box)(ByteBuffer&), ColourBoxOrder colour_box_order)
+void append_video_movie(ByteBuffer& bytes, char const (&format)[5], void (*append_configuration_box)(ByteBuffer&), ColourBoxOrder colour_box_order, Function<void(ByteBuffer&)> const& append_tables = {}, bool fragmented = false)
{
auto movie = begin_box(bytes, "moov");
auto track = begin_box(bytes, "trak");
@@ -355,14 +360,18 @@ void append_video_movie(ByteBuffer& bytes, char const (&format)[5], void (*appen
finish_box(bytes, sample_entry);
finish_box(bytes, sample_description);
+ if (append_tables)
+ append_tables(bytes);
finish_box(bytes, sample_table);
finish_box(bytes, media_information);
finish_box(bytes, media);
finish_box(bytes, track);
+ if (fragmented)
+ append_movie_extends_box(bytes);
finish_box(bytes, movie);
}
-void append_audio_movie(ByteBuffer& bytes, u32 timescale, u32 sample_rate, u16 channel_count)
+void append_audio_movie(ByteBuffer& bytes, u32 timescale, u32 sample_rate, u16 channel_count, void (*append_configuration_box)(ByteBuffer&) = nullptr)
{
auto movie = begin_box(bytes, "moov");
auto track = begin_box(bytes, "trak");
@@ -412,6 +421,8 @@ void append_audio_movie(ByteBuffer& bytes, u32 timescale, u32 sample_rate, u16 c
append_u16(bytes, 0); // pre_defined
append_u16(bytes, 0); // reserved
append_u32(bytes, sample_rate << 16);
+ if (append_configuration_box)
+ append_configuration_box(bytes);
finish_box(bytes, sample_entry);
finish_box(bytes, sample_description);
@@ -447,6 +458,58 @@ SampleEntrySummary parse_only_sample_entry(ByteBuffer& bytes)
}
+static Optional<FixedArray<u8>> first_frame_codec_configuration(ByteBuffer const& data)
+{
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(stream));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Audio));
+ VERIFY(track.has_value());
+ MUST(demuxer->create_context_for_track(*track));
+
+ auto frame = MUST(demuxer->get_next_sample_for_track(*track));
+ auto configuration = frame.new_codec_configuration();
+ if (!configuration.has_value())
+ return {};
+ return MUST(FixedArray<u8>::create(*configuration));
+}
+
+TEST_CASE(aac_track_keeps_the_configuration_its_container_carries)
+{
+ auto file = MUST(Core::File::open("./hevc_10bit.mp4"sv, Core::File::OpenMode::Read));
+ auto configuration = first_frame_codec_configuration(MUST(file->read_until_eof()));
+
+ // The track describes its own codec, so nothing is invented for it.
+ EXPECT(configuration.has_value());
+ EXPECT(configuration->size() >= 2);
+}
+
+TEST_CASE(aac_track_without_a_configuration_is_described_by_its_container)
+{
+ auto file = MUST(Core::File::open("./hevc_10bit.mp4"sv, Core::File::OpenMode::Read));
+ auto data = MUST(file->read_until_eof());
+
+ // Renaming the Elementary Stream Descriptor Box leaves a track that states its sample rate and
+ // channel count but never describes the codec that decodes it.
+ Optional<size_t> esds;
+ for (size_t index = 0; index + 4 <= data.size(); index++) {
+ if (StringView { data.bytes().slice(index, 4) } == "esds"sv) {
+ EXPECT(!esds.has_value());
+ esds = index;
+ }
+ }
+ VERIFY(esds.has_value());
+ data.overwrite(*esds, "free", 4);
+
+ auto configuration = first_frame_codec_configuration(data);
+ EXPECT(configuration.has_value());
+
+ // An Audio Specific Config of object type 2, sampling frequency index 3 and channel
+ // configuration 1: Low Complexity AAC at the 48000 Hz mono the container declares.
+ EXPECT_EQ(configuration->size(), 2u);
+ EXPECT_EQ((*configuration)[0], 0x11);
+ EXPECT_EQ((*configuration)[1], 0x88);
+}
+
TEST_CASE(rejects_file_type_box_with_partial_compatible_brand)
{
ByteBuffer bytes;
@@ -461,6 +524,511 @@ TEST_CASE(rejects_file_type_box_with_partial_compatible_brand)
EXPECT(Media::ISOBMFF::Reader::parse_file_type_box(streamer, header).is_error());
}
+TEST_CASE(preserves_mp3_in_mp4a_without_decoder_specific_configuration)
+{
+ for (u8 object_type : { 0x69, 0x6b }) {
+ ByteBuffer bytes;
+ append_audio_movie(bytes, 48'000, 48'000, 2, [](ByteBuffer& bytes) {
+ auto esds = begin_box(bytes, "esds");
+ append_full_box_header(bytes);
+ bytes.append(3); // ES_Descriptor
+ bytes.append(18);
+ append_u16(bytes, 1); // ES_ID
+ bytes.append(0); // flags
+ bytes.append(4); // DecoderConfigDescriptor
+ bytes.append(13);
+ bytes.append(0x6b); // MPEG-1 Audio
+ bytes.append(0x15); // audio stream type, reserved bit
+ bytes.append(0);
+ append_u16(bytes, 0); // bufferSizeDB
+ append_u32(bytes, 160'000);
+ append_u32(bytes, 160'000);
+ finish_box(bytes, esds);
+ });
+ // The final DecoderConfigDescriptor has a 13-byte payload beginning with the object type.
+ bytes[bytes.size() - 13] = object_type;
+ auto movie = MUST(parse_movie(bytes));
+ auto const& entry = movie.tracks.get(1).value()->sample_entries.first();
+ EXPECT_EQ(entry.codec_id, Media::CodecID::MP3);
+ EXPECT(entry.codec_initialization_data.is_empty());
+ auto track = Media::ISOBMFF::track_from_track_entry(*movie.tracks.get(1).value(), true);
+ EXPECT_EQ(track.parsed_codec().codec_id(), Media::CodecID::MP3);
+ }
+}
+
+static void append_seek_test_tables(ByteBuffer& bytes, u8 size_width = 0, u32 data_offset = 8, bool mark_sync_samples = true)
+{
+ auto times = begin_box(bytes, "stts");
+ append_full_box_header(bytes);
+ append_u32(bytes, 1);
+ append_u32(bytes, 6);
+ append_u32(bytes, 1);
+ finish_box(bytes, times);
+
+ auto compositions = begin_box(bytes, "ctts");
+ append_full_box_header(bytes, 1);
+ append_u32(bytes, 6);
+ for (i32 offset : { 0, 2, -1, -1, 2, -1 }) {
+ append_u32(bytes, 1);
+ append_u32(bytes, static_cast<u32>(offset));
+ }
+ finish_box(bytes, compositions);
+
+ auto chunks = begin_box(bytes, "stsc");
+ append_full_box_header(bytes);
+ append_u32(bytes, 2);
+ for (u32 chunk = 1; chunk <= 2; ++chunk) {
+ append_u32(bytes, chunk);
+ append_u32(bytes, 3);
+ append_u32(bytes, 1);
+ }
+ finish_box(bytes, chunks);
+
+ bool compact = size_width != 0 && size_width != 32;
+ auto sizes = begin_box(bytes, compact ? "stz2" : "stsz");
+ append_full_box_header(bytes);
+ append_u32(bytes, compact ? size_width : size_width == 0 ? 1
+ : 0);
+ append_u32(bytes, 6);
+ if (size_width == 4) {
+ bytes.append(0x12);
+ bytes.append(0x34);
+ bytes.append(0x56);
+ } else if (size_width != 0) {
+ for (u32 size = 1; size <= 6; ++size) {
+ if (size_width == 8)
+ bytes.append(size);
+ else if (size_width == 16)
+ append_u16(bytes, size);
+ else
+ append_u32(bytes, size);
+ }
+ }
+ finish_box(bytes, sizes);
+
+ auto offsets = begin_box(bytes, size_width == 0 ? "stco" : "co64");
+ append_full_box_header(bytes);
+ append_u32(bytes, 2);
+ if (size_width == 0) {
+ append_u32(bytes, data_offset);
+ append_u32(bytes, data_offset + 3);
+ } else {
+ append_u64(bytes, 0x1'0000'0000);
+ append_u64(bytes, 0x2'0000'0000);
+ }
+ finish_box(bytes, offsets);
+
+ auto sync = begin_box(bytes, "stss");
+ append_full_box_header(bytes);
+ append_u32(bytes, mark_sync_samples ? 2 : 0);
+ if (mark_sync_samples) {
+ append_u32(bytes, 1);
+ append_u32(bytes, 5);
+ }
+ finish_box(bytes, sync);
+}
+
+TEST_CASE(demuxes_quicktime_with_a_leading_wide_atom)
+{
+ ByteBuffer bytes;
+ auto wide = begin_box(bytes, "wide");
+ finish_box(bytes, wide);
+ auto data = begin_box(bytes, "mdat");
+ for (u8 i = 0; i < 6; ++i)
+ bytes.append(i);
+ finish_box(bytes, data);
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [](ByteBuffer& bytes) { append_seek_test_tables(bytes, 0, 16); });
+
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(bytes);
+ 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));
+ for (u8 i = 0; i < 6; ++i) {
+ auto sample = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(sample.data().size(), 1u);
+ EXPECT_EQ(sample.data()[0], i);
+ }
+ auto end = demuxer->get_next_sample_for_track(track);
+ EXPECT(end.is_error());
+ EXPECT_EQ(end.error().category(), Media::DecoderErrorCategory::EndOfStream);
+}
+
+static ByteBuffer seek_test_file(bool fragmented = false, Optional<u32> fragment_decode_time = {}, bool movie_has_samples = true)
+{
+ ByteBuffer bytes;
+ auto data = begin_box(bytes, "mdat");
+ for (u8 i = 0; i < 6; ++i)
+ bytes.append(i);
+ finish_box(bytes, data);
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [&](ByteBuffer& bytes) {
+ if (movie_has_samples)
+ append_seek_test_tables(bytes); }, fragmented);
+ if (fragmented) {
+ auto fragment = begin_box(bytes, "moof");
+ auto fragment_header = begin_box(bytes, "mfhd");
+ append_full_box_header(bytes);
+ append_u32(bytes, 1);
+ finish_box(bytes, fragment_header);
+ auto traf = begin_box(bytes, "traf");
+ auto header = begin_box(bytes, "tfhd");
+ append_full_box_header(bytes, 0, 0x020018); // moof-relative offsets, default duration and size
+ append_u32(bytes, 1);
+ append_u32(bytes, 1);
+ append_u32(bytes, 1);
+ finish_box(bytes, header);
+ // Without tfdt, decoding continues after the samples in moov or the preceding fragment.
+ if (fragment_decode_time.has_value()) {
+ auto decode_time = begin_box(bytes, "tfdt");
+ append_full_box_header(bytes);
+ append_u32(bytes, fragment_decode_time.value());
+ finish_box(bytes, decode_time);
+ }
+ auto run = begin_box(bytes, "trun");
+ append_full_box_header(bytes, 1, 0x000c01); // data offset, flags, composition offsets
+ append_u32(bytes, 2);
+ auto data_offset_position = bytes.size();
+ append_u32(bytes, 0);
+ append_u32(bytes, 0);
+ append_u32(bytes, 2);
+ append_u32(bytes, Media::ISOBMFF::SAMPLE_IS_NON_SYNC_SAMPLE);
+ append_u32(bytes, 0);
+ finish_box(bytes, run);
+ finish_box(bytes, traf);
+ finish_box(bytes, fragment);
+ patch_u32(bytes, data_offset_position, bytes.size() + 8 - fragment.start);
+ auto fragment_data = begin_box(bytes, "mdat");
+ bytes.append(6);
+ bytes.append(7);
+ finish_box(bytes, fragment_data);
+ }
+ return bytes;
+}
+
+TEST_CASE(demuxes_sample_tables_in_decode_order_with_signed_composition_offsets)
+{
+ 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));
+ Array<i64, 6> timestamps { 0, 3, 1, 2, 6, 4 };
+ for (size_t index = 0; index < timestamps.size(); ++index) {
+ auto sample = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(sample.decode_timestamp(), AK::Duration::from_seconds(index));
+ EXPECT_EQ(sample.presentation_timestamp(), AK::Duration::from_seconds(timestamps[index]));
+ EXPECT_EQ(sample.data()[0], index);
+ EXPECT_EQ(sample.is_keyframe(), index == 0 || index == 4);
+ EXPECT_EQ(sample.new_codec_configuration().has_value(), index == 0);
+ }
+ EXPECT_EQ(demuxer->get_next_sample_for_track(track).error().category(), Media::DecoderErrorCategory::EndOfStream);
+}
+
+TEST_CASE(seeks_by_pts_and_skips_seeks_that_do_not_improve_position)
+{
+ 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(5);
+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target)), Media::DemuxerSeekResult::MovedPosition);
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 0);
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 1);
+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target, Media::DemuxerSeekOptions::NeedCodecConfiguration)), Media::DemuxerSeekResult::KeptCurrentPosition);
+ auto next = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(next.data()[0], 2);
+ EXPECT(next.new_codec_configuration().has_value());
+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target, Media::DemuxerSeekOptions::Force)), Media::DemuxerSeekResult::MovedPosition);
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 0);
+ EXPECT_EQ(demuxer->select_fast_seek_target_for_track(track, target, Media::SeekMode::FastBefore), AK::Duration::zero());
+ EXPECT_EQ(demuxer->select_fast_seek_target_for_track(track, target, Media::SeekMode::FastAfter), AK::Duration::from_seconds(6));
+}
+
+TEST_CASE(seeks_across_movie_and_fragment_samples_in_both_directions)
+{
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(seek_test_file(true));
+ 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));
+ for (u8 index = 0; index < 8; ++index) {
+ auto sample = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(sample.data()[0], index);
+ EXPECT_EQ(sample.decode_timestamp(), AK::Duration::from_seconds(index));
+ }
+ struct SeekExpectation {
+ i64 target;
+ u8 sample_index;
+ };
+ for (auto [target, sample_index] : { SeekExpectation { 8, 6 }, SeekExpectation { 5, 0 }, SeekExpectation { 7, 4 }, SeekExpectation { 10, 6 } }) {
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(target), Media::DemuxerSeekOptions::Force));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], sample_index);
+ }
+}
+
+TEST_CASE(sample_tables_remain_available_after_movie_bytes_are_evicted)
+{
+ auto bytes = seek_test_file();
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(bytes);
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(stream));
+ // Retain only the mdat. Creating iterators and seeking must use the owned table bytes.
+ stream->remove_byte_range(14, bytes.size());
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).value();
+ MUST(demuxer->create_context_for_track(track));
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(6)));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 4);
+}
+
+TEST_CASE(rejects_sample_table_counts_larger_than_box_before_allocating)
+{
+ constexpr char types[][5] = { "stts", "ctts", "stsc", "stco", "co64", "stss", "stsz", "stz2" };
+ for (auto const& type : types) {
+ ByteBuffer bytes;
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [&](ByteBuffer& bytes) {
+ auto box = begin_box(bytes, type);
+ append_full_box_header(bytes);
+ if (StringView(type, 4) == "stsz"sv)
+ append_u32(bytes, 0); // variable sample sizes
+ else if (StringView(type, 4) == "stz2"sv)
+ append_u32(bytes, 4); // four-bit sample sizes
+ append_u32(bytes, NumericLimits<u32>::max());
+ finish_box(bytes, box);
+ });
+ EXPECT(parse_movie(bytes).is_error());
+ }
+}
+
+TEST_CASE(iterates_compact_and_variable_sample_sizes_with_large_chunk_offsets)
+{
+ for (u8 width : { 4, 8, 16, 32 }) {
+ ByteBuffer bytes;
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [&](ByteBuffer& bytes) {
+ append_seek_test_tables(bytes, width);
+ });
+ auto movie = MUST(parse_movie(bytes));
+ auto& track = *movie.tracks.get(1).value();
+ EXPECT_EQ(track.sample_tables->sample_sizes->sizes.size(), 6u);
+ track.sample_tables->sync_samples.clear();
+ auto iterator = MUST(Media::ISOBMFF::SampleTableIterator::create(track));
+ size_t expected_position = 0x1'0000'0000;
+ for (u32 index = 0; index < 6; ++index) {
+ if (index == 3)
+ expected_position = 0x2'0000'0000;
+ auto sample = MUST(iterator.next(track)).value();
+ EXPECT_EQ(sample.data_size, index + 1);
+ EXPECT_EQ(sample.data_position, expected_position);
+ EXPECT(sample.is_sync_sample);
+ expected_position += index + 1;
+ }
+ EXPECT(!MUST(iterator.next(track)).has_value());
+ }
+}
+
+TEST_CASE(normalizes_composition_offset_versions_without_losing_unsigned_values)
+{
+ for (u8 version : { 0, 1 }) {
+ ByteBuffer bytes;
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [&](ByteBuffer& bytes) {
+ auto box = begin_box(bytes, "ctts");
+ append_full_box_header(bytes, version);
+ append_u32(bytes, 1);
+ append_u32(bytes, 100);
+ append_u32(bytes, 0xffff'ffff);
+ finish_box(bytes, box);
+ });
+ auto movie = MUST(parse_movie(bytes));
+ auto const& offsets = movie.tracks.get(1).value()->sample_tables->composition_offsets.value();
+ EXPECT_EQ(offsets.size(), 1u);
+ EXPECT_EQ(offsets[0].sample_count, 100u);
+ EXPECT_EQ(offsets[0].sample_offset, version == 0 ? 0xffff'ffffLL : -1LL);
+ }
+}
+
+TEST_CASE(parses_odd_compact_sample_count_and_keeps_constant_sample_sizes_compressed)
+{
+ for (bool compact : { false, true }) {
+ ByteBuffer bytes;
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [&](ByteBuffer& bytes) {
+ auto box = begin_box(bytes, compact ? "stz2" : "stsz");
+ append_full_box_header(bytes);
+ append_u32(bytes, compact ? 4 : 123);
+ append_u32(bytes, compact ? 3 : NumericLimits<u32>::max());
+ if (compact) {
+ bytes.append(0x12);
+ bytes.append(0x3f); // The unused low nibble must not become another sample.
+ }
+ finish_box(bytes, box);
+ });
+ auto movie = MUST(parse_movie(bytes));
+ auto const& sizes = movie.tracks.get(1).value()->sample_tables->sample_sizes.value();
+ if (compact) {
+ EXPECT_EQ(sizes.sizes.size(), 3u);
+ EXPECT_EQ(sizes.sample_count, 3u);
+ for (u32 index = 0; index < 3; ++index)
+ EXPECT_EQ(sizes.size_of_sample(index), index + 1);
+ } else {
+ EXPECT(sizes.sizes.is_empty());
+ EXPECT_EQ(sizes.sample_count, NumericLimits<u32>::max());
+ EXPECT_EQ(sizes.size_of_sample(sizes.sample_count - 1), 123u);
+ }
+ }
+}
+
+TEST_CASE(retries_incomplete_fragment_metadata_without_losing_samples)
+{
+ auto bytes = seek_test_file(true);
+ auto reader = streamer_for(bytes);
+ MUST(reader.seek_to_position(14));
+ auto header = MUST(Media::ISOBMFF::Reader::read_box_header(reader));
+ auto movie = MUST(Media::ISOBMFF::Reader::parse_movie_box(reader, header));
+ auto movie_end = header.end_position().value();
+ auto source = Media::IncrementallyPopulatedStream::create_empty();
+ source->set_expected_size(bytes.size());
+ source->add_chunk_at(0, bytes.bytes().trim(movie_end + 16));
+ auto cursor = source->create_cursor();
+ cursor->set_is_blocking(false);
+ auto iterator = MUST(Media::ISOBMFF::SampleIterator::create(cursor, movie, 1, movie_end));
+ for (u32 index = 0; index < 6; ++index)
+ EXPECT_EQ(MUST(iterator.next())->decode_timestamp, AK::Duration::from_seconds(index));
+ EXPECT_EQ(iterator.next().error().category(), Media::DecoderErrorCategory::NeedsMoreInput);
+ source->add_chunk_at(movie_end + 16, bytes.bytes().slice(movie_end + 16));
+ for (u32 index = 6; index < 8; ++index)
+ EXPECT_EQ(MUST(iterator.next())->decode_timestamp, AK::Duration::from_seconds(index));
+ EXPECT(!MUST(iterator.next()).has_value());
+}
+
+TEST_CASE(seeking_movie_samples_does_not_wait_for_later_fragments)
+{
+ auto bytes = seek_test_file(true);
+ auto reader = streamer_for(bytes);
+ MUST(reader.seek_to_position(14));
+ auto header = MUST(Media::ISOBMFF::Reader::read_box_header(reader));
+ auto source = Media::IncrementallyPopulatedStream::create_empty();
+ source->set_expected_size(bytes.size());
+ source->add_chunk_at(0, bytes.bytes().trim(header.end_position().value() + 16));
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(source));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).value();
+ MUST(demuxer->create_context_for_track(track));
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(5)));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 0);
+}
+
+TEST_CASE(aborted_sample_iteration_can_be_resumed)
+{
+ auto source = Media::IncrementallyPopulatedStream::create_from_buffer(seek_test_file(true));
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(source));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).value();
+ MUST(demuxer->create_context_for_track(track));
+ for (u32 index = 0; index < 8; ++index) {
+ demuxer->set_blocking_reads_aborted_for_track(track);
+ EXPECT_EQ(demuxer->get_next_sample_for_track(track).error().category(), Media::DecoderErrorCategory::Aborted);
+ demuxer->reset_blocking_reads_aborted_for_track(track);
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], index);
+ }
+}
+
+TEST_CASE(fragment_seeks_block_until_the_target_metadata_arrives_and_can_be_aborted)
+{
+ for (bool movie_has_samples : { false, true }) {
+ auto bytes = seek_test_file(true, {}, movie_has_samples);
+ auto reader = streamer_for(bytes);
+ MUST(reader.seek_to_position(14));
+ auto header = MUST(Media::ISOBMFF::Reader::read_box_header(reader));
+ auto available_end = header.end_position().value() + 16;
+ auto source = Media::IncrementallyPopulatedStream::create_empty();
+ // Leave a later box unavailable, so seeking must stop before reaching the end of the file.
+ source->set_expected_size(bytes.size() + 8);
+ source->add_chunk_at(0, bytes.bytes().trim(available_end));
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(source));
+ 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_milliseconds(movie_has_samples ? 8500 : 2500);
+ EXPECT_EQ(demuxer->select_fast_seek_target_for_track(track, target, Media::SeekMode::FastBefore), movie_has_samples ? AK::Duration::from_seconds(6) : target);
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> blocked { false };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> completed { false };
+ demuxer->set_read_blocked_change_handler_for_track(track, [&](Media::ReadBlocked state) {
+ blocked = state == Media::ReadBlocked::Yes;
+ });
+ for (bool abort : { true, false }) {
+ completed = false;
+ demuxer->reset_blocking_reads_aborted_for_track(track);
+ auto thread = Threading::Thread::construct("TestSeek"sv, [&, demuxer, track, target, abort]() -> intptr_t {
+ auto result = demuxer->seek_to_most_recent_keyframe(track, target);
+ if (abort) {
+ EXPECT(result.is_error());
+ if (result.is_error())
+ EXPECT_EQ(result.error().category(), Media::DecoderErrorCategory::Aborted);
+ } else {
+ EXPECT(!result.is_error());
+ }
+ completed = true;
+ return 0;
+ });
+ thread->start();
+ auto deadline = MonotonicTime::now() + AK::Duration::from_seconds(5);
+ while (!blocked.load() && !completed.load() && MonotonicTime::now() < deadline) { }
+ EXPECT(blocked.load());
+ EXPECT(!completed.load());
+ if (abort)
+ demuxer->set_blocking_reads_aborted_for_track(track);
+ else
+ source->add_chunk_at(available_end, bytes.bytes().slice(available_end));
+ MUST(thread->join());
+ }
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 6);
+ demuxer->set_read_blocked_change_handler_for_track(track, {});
+ }
+}
+
+TEST_CASE(seeking_uses_the_first_sample_when_no_samples_are_marked_sync)
+{
+ ByteBuffer bytes;
+ auto data = begin_box(bytes, "mdat");
+ for (u8 i = 0; i < 6; ++i)
+ bytes.append(i);
+ finish_box(bytes, data);
+ append_video_movie(bytes, "vp09", append_vp9_configuration_box, ColourBoxOrder::None, [](ByteBuffer& bytes) { append_seek_test_tables(bytes, 0, 8, false); });
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(bytes);
+ 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));
+ for (auto target : { 0, 2, 5, 10 }) {
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(target), Media::DemuxerSeekOptions::Force));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 0);
+ }
+}
+
+TEST_CASE(explicit_fragment_decode_time_overrides_movie_duration)
+{
+ auto source = Media::IncrementallyPopulatedStream::create_from_buffer(seek_test_file(true, 100));
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(source));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).value();
+ MUST(demuxer->create_context_for_track(track));
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(101), Media::DemuxerSeekOptions::Force));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).data()[0], 4);
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(102), Media::DemuxerSeekOptions::Force));
+ auto sample = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(sample.decode_timestamp(), AK::Duration::from_seconds(100));
+ EXPECT_EQ(sample.presentation_timestamp(), AK::Duration::from_seconds(102));
+}
+
+TEST_CASE(fragment_decode_time_continues_across_successive_fragments)
+{
+ auto bytes = seek_test_file(true);
+ auto reader = streamer_for(bytes);
+ MUST(reader.seek_to_position(14));
+ auto header = MUST(Media::ISOBMFF::Reader::read_box_header(reader));
+ auto fragment_bytes = MUST(ByteBuffer::copy(bytes.bytes().slice(header.end_position().value())));
+ patch_u32(fragment_bytes, 20, 2); // mfhd sequence_number
+ MUST(bytes.try_append(fragment_bytes.bytes()));
+ auto source = Media::IncrementallyPopulatedStream::create_from_buffer(bytes);
+ auto demuxer = MUST(Media::ISOBMFF::ISOBMFFDemuxer::from_stream(source));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).value();
+ MUST(demuxer->create_context_for_track(track));
+ for (u32 index = 0; index < 10; ++index)
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).decode_timestamp(), AK::Duration::from_seconds(index));
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(10), Media::DemuxerSeekOptions::Force));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).decode_timestamp(), AK::Duration::from_seconds(8));
+}
+
TEST_CASE(rejects_child_box_smaller_than_parsed_fields)
{
ByteBuffer bytes;
@@ -488,15 +1056,14 @@ TEST_CASE(rejects_nonzero_edit_list_media_rate_fraction)
EXPECT(Media::ISOBMFF::Reader::parse_movie_box(streamer, header).is_error());
}
-TEST_CASE(sample_table_entry_count_does_not_wrap)
+TEST_CASE(rejects_oversized_sample_table_entry_count)
{
ByteBuffer bytes;
append_movie_box(bytes, true);
auto streamer = streamer_for(bytes);
auto header = MUST(Media::ISOBMFF::Reader::read_box_header(streamer));
- auto movie = MUST(Media::ISOBMFF::Reader::parse_movie_box(streamer, header));
- EXPECT_EQ(movie.tracks.get(1).value()->sample_table_entry_count, static_cast<u64>(NumericLimits<u32>::max()) + 1);
+ EXPECT(Media::ISOBMFF::Reader::parse_movie_box(streamer, header).is_error());
}
TEST_CASE(parses_nondefault_sample_description_index)
diff --git a/Tests/LibMedia/TestMediaCommon.h b/Tests/LibMedia/TestMediaCommon.h
index bacc946e67b..a9510a565a5 100644
--- a/Tests/LibMedia/TestMediaCommon.h
+++ b/Tests/LibMedia/TestMediaCommon.h
@@ -17,7 +17,7 @@
#include <LibMedia/Containers/Matroska/Reader.h>
#include <LibMedia/Containers/Matroska/Utilities.h>
#include <LibMedia/Demuxer.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
+#include <LibMedia/DemuxerRegistry.h>
#include <LibMedia/PipelineStatus.h>
#include <LibMedia/Producers/DecodedAudioProducer.h>
#include <LibMedia/Producers/VideoProducer.h>
@@ -92,12 +92,7 @@ static inline void decode_audio(StringView path, u32 sample_rate, u8 channel_cou
auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
- auto demuxer = MUST([&] -> Media::DecoderErrorOr<NonnullRefPtr<Media::Demuxer>> {
- auto matroska_result = Media::Matroska::MatroskaDemuxer::from_stream(stream);
- if (!matroska_result.is_error())
- return matroska_result.release_value();
- return Media::FFmpeg::FFmpegDemuxer::from_stream(stream);
- }());
+ auto demuxer = MUST(Media::create_demuxer(stream));
auto tracks = TRY_OR_FAIL(demuxer->get_tracks_for_type(Media::TrackType::Audio));
VERIFY(!tracks.is_empty());
auto producer = TRY_OR_FAIL(Media::DecodedAudioProducer::try_create(loop, demuxer, tracks[0]));
diff --git a/Tests/LibMedia/TestPipelineNodes.cpp b/Tests/LibMedia/TestPipelineNodes.cpp
index 8c61287c64d..9387ba45c8d 100644
--- a/Tests/LibMedia/TestPipelineNodes.cpp
+++ b/Tests/LibMedia/TestPipelineNodes.cpp
@@ -8,8 +8,7 @@
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
#include <LibCore/System.h>
-#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
+#include <LibMedia/DemuxerRegistry.h>
#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMedia/MediaClock.h>
#include <LibMedia/MonotonicMediaClock.h>
@@ -34,10 +33,7 @@ static NonnullRefPtr<Media::IncrementallyPopulatedStream> load_test_file(StringV
static NonnullRefPtr<Media::Demuxer> create_demuxer(NonnullRefPtr<Media::IncrementallyPopulatedStream> const& stream)
{
- auto matroska_result = Media::Matroska::MatroskaDemuxer::from_stream(stream);
- if (!matroska_result.is_error())
- return matroska_result.release_value();
- return MUST(Media::FFmpeg::FFmpegDemuxer::from_stream(stream));
+ return MUST(Media::create_demuxer(stream));
}
template<typename Condition>
diff --git a/Tests/LibMedia/TestRemoteVideoNode.cpp b/Tests/LibMedia/TestRemoteVideoNode.cpp
index acc07fa78c3..553bc82e27b 100644
--- a/Tests/LibMedia/TestRemoteVideoNode.cpp
+++ b/Tests/LibMedia/TestRemoteVideoNode.cpp
@@ -15,9 +15,8 @@
#include <LibCore/System.h>
#include <LibGfx/YUVData.h>
#include <LibIPC/Transport.h>
-#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
#include <LibMedia/Demuxer.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
+#include <LibMedia/DemuxerRegistry.h>
#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMedia/MediaTime.h>
#include <LibMedia/PlaybackManager.h>
@@ -50,10 +49,7 @@ NonnullRefPtr<IncrementallyPopulatedStream> load_test_file(StringView path)
NonnullRefPtr<Demuxer> create_demuxer(NonnullRefPtr<IncrementallyPopulatedStream> const& stream)
{
- auto matroska_result = Matroska::MatroskaDemuxer::from_stream(stream);
- if (!matroska_result.is_error())
- return matroska_result.release_value();
- return MUST(FFmpeg::FFmpegDemuxer::from_stream(stream));
+ return MUST(Media::create_demuxer(stream));
}
NonnullRefPtr<DecodedVideoProducer> make_decoder(Core::EventLoop& loop, StringView path)