Skip to content

Truly independent web browser

LibMedia: Build an Ogg demuxer from its navigator and drop libavformat

Zaggy1024f4353c837c80
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txt
index d4391210ea5..bfcc7728576 100644
--- a/Libraries/LibMedia/CMakeLists.txt
+++ b/Libraries/LibMedia/CMakeLists.txt
@@ -15,7 +15,6 @@ set(SOURCES
Containers/FLAC/Reader.cpp
Containers/FrameScanTimeline.cpp
Containers/ID3.cpp
- Containers/IndexedContainerNavigator.cpp
Containers/ISOBMFF/FragmentSampleIterator.cpp
Containers/ISOBMFF/ISOBMFFDemuxer.cpp
Containers/ISOBMFF/SampleIterator.cpp
@@ -30,7 +29,8 @@ set(SOURCES
Containers/MP3/MP3Demuxer.cpp
Containers/MP3/Reader.cpp
Containers/MP3/StreamInfo.cpp
- Containers/OggNavigator.cpp
+ Containers/Ogg/OggDemuxer.cpp
+ Containers/Ogg/Reader.cpp
Containers/WAV/Reader.cpp
Containers/WAV/WAVDemuxer.cpp
DecodeAudioStream.cpp
@@ -98,13 +98,11 @@ target_sources(LibMedia PRIVATE
FFmpeg/FFmpegAudioConverter.cpp
FFmpeg/FFmpegAudioDecoder.cpp
FFmpeg/FFmpegChannelLayout.cpp
- FFmpeg/FFmpegDemuxer.cpp
- FFmpeg/FFmpegIOContext.cpp
FFmpeg/FFmpegVideoDecoder.cpp
)
if (NOT ANDROID)
- target_link_libraries(LibMedia PRIVATE PkgConfig::AVCODEC PkgConfig::AVFORMAT PkgConfig::AVUTIL PkgConfig::LIBSWRESAMPLE)
+ target_link_libraries(LibMedia PRIVATE PkgConfig::AVCODEC PkgConfig::AVUTIL PkgConfig::LIBSWRESAMPLE)
else()
target_include_directories(LibMedia PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_link_directories(LibMedia PRIVATE ${FFMPEG_LIBRARY_DIRS})
diff --git a/Libraries/LibMedia/Containers/IndexedContainerNavigator.cpp b/Libraries/LibMedia/Containers/IndexedContainerNavigator.cpp
deleted file mode 100644
index ac6b756e195..00000000000
--- a/Libraries/LibMedia/Containers/IndexedContainerNavigator.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "IndexedContainerNavigator.h"
-
-namespace Media {
-
-size_t IndexedContainerNavigator::lower_bound(Vector<IndexEntry> const& entries, size_t target)
-{
- size_t lo = 0;
- size_t hi = entries.size();
- while (lo < hi) {
- auto mid = lo + (hi - lo) / 2;
- if (entries[mid].position < target)
- lo = mid + 1;
- else
- hi = mid;
- }
- return lo;
-}
-
-Vector<BufferedRangesScan> IndexedContainerNavigator::buffered_time_ranges_by_track(Vector<MediaStream::ByteRange> const& byte_ranges) const
-{
- Vector<BufferedRangesScan> scans;
- for (auto const& track_index : m_track_indices) {
- auto const& entries = track_index.entries;
- auto entry_count = entries.size();
-
- BufferedRangesScan scan;
- scan.track_identifier = track_index.track_identifier;
- for (size_t i = 0; i < byte_ranges.size(); i++) {
- auto const& byte_range = byte_ranges[i];
-
- // Find the first entry at or after the start, and the first entry at or after the end.
- auto first = lower_bound(entries, byte_range.start);
- auto end = lower_bound(entries, byte_range.end);
- if (first >= end)
- continue;
-
- auto time_start = max(AK::Duration::zero(), entries[first].timestamp);
- auto time_end = (end < entry_count) ? entries[end].timestamp : m_duration;
- scan.time_ranges.add_range(time_start, time_end);
-
- if (i == byte_ranges.size() - 1)
- scan.last_byte_range_has_samples = true;
- }
-
- scans.append(move(scan));
- }
-
- return scans;
-}
-
-}
diff --git a/Libraries/LibMedia/Containers/IndexedContainerNavigator.h b/Libraries/LibMedia/Containers/IndexedContainerNavigator.h
deleted file mode 100644
index dc89ceec840..00000000000
--- a/Libraries/LibMedia/Containers/IndexedContainerNavigator.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Time.h>
-#include <AK/Vector.h>
-#include <LibMedia/Containers/IndexEntry.h>
-
-#include "ContainerNavigator.h"
-
-namespace Media {
-
-class IndexedContainerNavigator final : public ContainerNavigator {
-public:
- struct TrackIndex {
- u64 track_identifier;
- Vector<IndexEntry> entries;
- };
-
- IndexedContainerNavigator(Vector<TrackIndex>&& track_indices, AK::Duration duration)
- : m_track_indices(move(track_indices))
- , m_duration(duration)
- {
- }
-
- virtual Vector<BufferedRangesScan> buffered_time_ranges_by_track(Vector<MediaStream::ByteRange> const& byte_ranges) const override;
-
-private:
- static size_t lower_bound(Vector<IndexEntry> const& entries, size_t target);
-
- Vector<TrackIndex> m_track_indices;
- AK::Duration m_duration;
-};
-
-}
diff --git a/Libraries/LibMedia/Containers/Ogg/OggDemuxer.cpp b/Libraries/LibMedia/Containers/Ogg/OggDemuxer.cpp
new file mode 100644
index 00000000000..56aa31abd89
--- /dev/null
+++ b/Libraries/LibMedia/Containers/Ogg/OggDemuxer.cpp
@@ -0,0 +1,1068 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/GenericShorthands.h>
+#include <AK/Math.h>
+#include <AK/QuickSort.h>
+#include <LibMedia/Codecs/FLAC.h>
+#include <LibMedia/Codecs/Opus.h>
+#include <LibMedia/Containers/Ogg/OggDemuxer.h>
+#include <LibMedia/ReadonlyBytesCursor.h>
+#include <LibMediaCodecs/CodedFrame.h>
+
+namespace Media::Ogg {
+
+static constexpr size_t MAXIMUM_SEEK_PROBE_COUNT = 16;
+static constexpr size_t MAXIMUM_RESYNC_BYTES_PER_SCAN = 4 * MiB;
+// Header packets may contain large cover images.
+static constexpr size_t MAXIMUM_LINK_HEADER_BYTE_COUNT = 64 * MiB;
+static constexpr size_t MAXIMUM_LINK_STREAM_COUNT = 64;
+static constexpr size_t MAXIMUM_SCANNED_STREAM_COUNT = 16 * KiB;
+// The last pages of a file may belong to streams without a time, such as one we don't read, so a few are searched.
+static constexpr size_t MAXIMUM_TAIL_PROBE_WINDOW_COUNT = 4;
+// Opus needs this much audio decoded ahead of a position before its output converges there.
+static constexpr AK::Duration OPUS_SEEK_PREROLL = AK::Duration::from_milliseconds(80);
+static constexpr AK::Duration SEEK_LEAD = AK::Duration::from_milliseconds(500);
+
+bool OggDemuxer::supports_container_mime_type(ContainerMimeType mime_type)
+{
+ return mime_type.container_id == ContainerID::Ogg;
+}
+
+bool OggDemuxer::supports_codec_in_container(ContainerID container_id, CodecID codec_id)
+{
+ return container_id == ContainerID::Ogg && first_is_one_of(codec_id, CodecID::Vorbis, CodecID::Opus, CodecID::FLAC, CodecID::Theora);
+}
+
+DecoderErrorOr<OggDemuxer::Link> OggDemuxer::Link::clone() const
+{
+ Link link;
+ link.position = position;
+ for (auto const& stream : streams)
+ DECODER_TRY_ALLOC(link.streams.try_append({ { stream.serial_number, stream.identification }, stream.beginning_page, DECODER_TRY_ALLOC(stream.codec_initialization_data.clone()) }));
+ return link;
+}
+
+Optional<size_t> OggDemuxer::Link::index_of_serial_number(u32 serial_number) const
+{
+ for (size_t i = 0; i < streams.size(); i++) {
+ if (streams[i].serial_number == serial_number)
+ return i;
+ }
+ return {};
+}
+
+template<typename Streams>
+static Optional<size_t> index_of_stream_of_type(Streams const& streams, TrackType type, size_t index_within_type)
+{
+ size_t index = 0;
+ for (size_t i = 0; i < streams.size(); i++) {
+ auto const& identification = streams[i].identification;
+ if (!identification.has_value() || identification->type != type)
+ continue;
+ if (index++ == index_within_type)
+ return i;
+ }
+ return {};
+}
+
+Optional<size_t> OggDemuxer::Link::index_of_stream_for_track(TrackType type, size_t index_within_type) const
+{
+ return index_of_stream_of_type(streams, type, index_within_type);
+}
+
+Optional<size_t> OggDemuxer::ScannedLink::index_of_stream_for_track(TrackType type, size_t index_within_type) const
+{
+ return index_of_stream_of_type(streams, type, index_within_type);
+}
+
+DecoderErrorOr<void> OggDemuxer::StreamHeaderReader::consume(Page const& page)
+{
+ if (page.header.begins_stream()) {
+ stream.serial_number = page.header.serial_number;
+ stream.beginning_page = page.header;
+ if (auto packet = page.first_complete_packet(); packet.has_value()) {
+ auto identification = identify_stream(*packet);
+ if (identification.is_error()) {
+ if (identification.error().category() != DecoderErrorCategory::Corrupted)
+ return identification.release_error();
+ } else {
+ stream.identification = identification.release_value();
+ }
+ }
+ }
+ if (!needs_more_pages())
+ return {};
+
+ auto completed_packets = assembler.take_completed_packets(page);
+ if (completed_packets.is_error()) {
+ if (completed_packets.error().category() != DecoderErrorCategory::Corrupted)
+ return completed_packets.release_error();
+ stream.identification = {};
+ return {};
+ }
+ auto const& identification = *stream.identification;
+ for (auto& packet : completed_packets.value()) {
+ if (identification.header_packet_count == 0 && !is_header_packet(identification, packet.span())) {
+ complete = true;
+ break;
+ }
+ packets.append(move(packet));
+ if (identification.header_packet_count != 0 && packets.size() >= identification.header_packet_count) {
+ complete = true;
+ break;
+ }
+ }
+ if (complete) {
+ auto data = build_codec_initialization_data(identification, packets);
+ if (data.is_error()) {
+ if (data.error().category() != DecoderErrorCategory::Corrupted)
+ return data.release_error();
+ stream.identification = {};
+ } else {
+ stream.codec_initialization_data = data.release_value();
+ }
+ packets.clear();
+ assembler.reset();
+ }
+ return {};
+}
+
+DecoderErrorOr<OggDemuxer::Link> OggDemuxer::read_link(PageIterator& pages)
+{
+ Link link;
+ Vector<StreamHeaderReader> header_readers;
+ bool reading_stream_starts = true;
+ auto needs_more_headers = [&] {
+ return any_of(header_readers, [](auto const& reader) { return reader.needs_more_pages(); });
+ };
+ while (reading_stream_starts || needs_more_headers()) {
+ if (!header_readers.is_empty() && pages.position() - link.position >= MAXIMUM_LINK_HEADER_BYTE_COUNT)
+ break;
+ auto page_or_error = pages.read_next_page();
+ if (page_or_error.is_error()) {
+ if (page_or_error.error().category() == DecoderErrorCategory::EndOfStream && !header_readers.is_empty())
+ break;
+ return page_or_error.release_error();
+ }
+ auto page = page_or_error.release_value();
+ if (page.header.begins_stream()) {
+ if (!reading_stream_starts) {
+ pages.set_position(page.header.position);
+ break;
+ }
+ if (header_readers.is_empty())
+ link.position = page.header.position;
+ if (header_readers.size() == MAXIMUM_LINK_STREAM_COUNT || any_of(header_readers, [&](auto const& reader) { return reader.stream.serial_number == page.header.serial_number; }))
+ return DecoderError::corrupted("Ogg link announces too many streams"sv);
+ StreamHeaderReader reader;
+ TRY(reader.consume(page));
+ header_readers.append(move(reader));
+ } else {
+ reading_stream_starts = false;
+ for (auto& reader : header_readers) {
+ if (reader.stream.serial_number == page.header.serial_number && reader.needs_more_pages())
+ TRY(reader.consume(page));
+ }
+ }
+ }
+ if (header_readers.is_empty())
+ return DecoderError::corrupted("No Ogg stream begins here"sv);
+ for (auto& reader : header_readers) {
+ if (!reader.complete)
+ reader.stream.identification = {};
+ link.streams.append(move(reader.stream));
+ }
+ return link;
+}
+
+namespace {
+
+struct TailProbe {
+ AK::Duration duration;
+ Optional<u32> serial_number;
+ size_t position { 0 };
+ i64 end_units { 0 };
+};
+
+}
+
+// The duration is where the last page of the file ends. A page of a stream the first link never announced means the
+// file is chained, whose duration can only be learned by reading every link.
+template<typename Link>
+static DecoderErrorOr<TailProbe> probe_tail(MediaStreamCursor& cursor, Link const& link, size_t stream_size)
+{
+ // The last page ends the file, so it starts within a page's reach of the end. Each window is read in one go, so
+ // that a backward search through it asks for its data once.
+ auto bound = stream_size;
+ auto window_end = stream_size;
+ for (size_t window = 0; window < MAXIMUM_TAIL_PROBE_WINDOW_COUNT && window_end > link.position; window++) {
+ auto window_start = max(link.position, window_end > MAXIMUM_PAGE_SIZE ? window_end - MAXIMUM_PAGE_SIZE : 0);
+ auto window_data = DECODER_TRY_ALLOC(ByteBuffer::create_uninitialized(window_end - window_start));
+ TRY(cursor.seek_to_position(window_start));
+ if (auto result = cursor.read_into(window_data.bytes()); result.is_error() && result.error().category() != DecoderErrorCategory::EndOfStream)
+ return result.release_error();
+
+ PageIterator tail { cursor, window_start };
+ while (true) {
+ auto header = TRY(tail.find_last_page_before(bound, window_start));
+ if (!header.has_value())
+ break;
+ auto index = link.index_of_serial_number(header->serial_number);
+ if (!index.has_value())
+ return TailProbe {};
+ auto const& identification = link.streams[*index].identification;
+ if (identification.has_value() && header->has_granule_position()) {
+ auto end_units = identification->end_units_of_granule_position(header->granule_position);
+ return TailProbe { identification->time_of_units(end_units), header->serial_number, header->position, end_units };
+ }
+ bound = header->position;
+ }
+ window_end = window_start;
+ }
+ return TailProbe {};
+}
+
+DecoderErrorOr<NonnullRefPtr<Demuxer>> OggDemuxer::from_stream(NonnullRefPtr<MediaStream> const& stream)
+{
+ auto cursor = stream->create_cursor();
+ PageIterator pages { cursor, 0 };
+ auto first_page = TRY(pages.read_page_at(0));
+ if (!first_page.has_value() || !first_page->header.begins_stream())
+ return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Stream is not Ogg"sv);
+
+ auto link = TRY(read_link(pages));
+
+ Vector<TrackDescription> tracks;
+ for (auto const& link_stream : link.streams) {
+ if (!link_stream.identification.has_value())
+ continue;
+ auto type = link_stream.identification->type;
+ size_t index_within_type = 0;
+ for (auto const& track : tracks) {
+ if (track.track.type() == type)
+ index_within_type++;
+ }
+ tracks.append({ link_stream.identification->create_track(tracks.size()), index_within_type });
+ }
+ if (tracks.is_empty())
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "Ogg stream has no logical stream we can read"sv);
+
+ TailProbe tail;
+ if (auto stream_size = stream->expected_size(); stream_size.has_value())
+ tail = TRY(probe_tail(*cursor, link, *stream_size));
+ Optional<PageAnchor> tail_anchor;
+ if (tail.serial_number.has_value())
+ tail_anchor = PageAnchor { *tail.serial_number, tail.position, tail.end_units };
+
+ auto demuxer = adopt_ref(*new OggDemuxer(stream, move(link), move(tracks), tail.duration, tail_anchor));
+ demuxer->start_buffered_scan_thread();
+ return demuxer;
+}
+
+OggDemuxer::OggDemuxer(NonnullRefPtr<MediaStream> const& stream, Link first_link, Vector<TrackDescription> tracks, AK::Duration duration, Optional<PageAnchor> tail_anchor)
+ : m_stream(stream)
+ , m_first_link(move(first_link))
+ , m_tracks(move(tracks))
+ , m_duration(duration)
+ , m_tail_anchor(tail_anchor)
+{
+ m_track_statuses.resize(m_tracks.size());
+}
+
+OggDemuxer::~OggDemuxer()
+{
+ if (m_buffered_scan_thread != nullptr)
+ m_buffered_scan_thread->shutdown();
+}
+
+static i64 packet_duration_in_units(Codecs::Vorbis::Parser const* vorbis_parser, StreamIdentification const& identification, ReadonlyBytes packet)
+{
+ switch (identification.codec_id) {
+ case CodecID::Vorbis:
+ if (vorbis_parser == nullptr)
+ return 0;
+ return vorbis_parser->parse_packet_duration_in_samples(packet).value_or(0);
+ case CodecID::Opus: {
+ auto cursor = make_ref_counted<ReadonlyBytesCursor>(packet);
+ auto duration = Codecs::Opus::parse_frame_duration_in_samples(*cursor, packet.size());
+ return duration.is_error() ? 0 : duration.value();
+ }
+ case CodecID::FLAC: {
+ if (packet.size() < 2)
+ return 0;
+ auto sync_code = static_cast<u16>((packet[0] << 8) | packet[1]);
+ if (!Codecs::FLAC::is_sync_code(sync_code))
+ return 0;
+ auto cursor = make_ref_counted<ReadonlyBytesCursor>(packet);
+ auto frame = Codecs::FLAC::parse_frame_header(*cursor, sync_code, 0);
+ if (frame.is_error() || !frame.value().has_value())
+ return 0;
+ return frame.value()->block_size;
+ }
+ case CodecID::Theora:
+ return 1;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+}
+
+i64 OggDemuxer::BufferedScanPayload::start_units_of_page(PageHeader const& header, ScannedStream const& stream, i64 end_units)
+{
+ auto const& identification = *stream.description.identification;
+ auto const* vorbis_parser = stream.vorbis_parser.has_value() ? &*stream.vorbis_parser : nullptr;
+ if (identification.codec_id == CodecID::Vorbis) {
+ // Without the setup header, only the end of the page is known to be decodable.
+ if (vorbis_parser == nullptr)
+ return end_units;
+ vorbis_parser->reset();
+ }
+
+ auto page = walker.read_page_at(header.position);
+ if (page.is_error() || !page.value().has_value())
+ return end_units;
+
+ i64 duration_units = 0;
+ auto fragments = page.value()->packet_fragments();
+ for (auto fragment = fragments.next(); fragment.has_value(); fragment = fragments.next()) {
+ if (fragment->starts_packet && fragment->ends_packet && !is_header_packet(identification, fragment->bytes))
+ duration_units += packet_duration_in_units(vorbis_parser, identification, fragment->bytes);
+ }
+ return end_units - duration_units;
+}
+
+void OggDemuxer::BufferedScanPayload::scan_page(ScannedByteRange& range, PageHeader const& header)
+{
+ if (header.begins_stream()) {
+ auto stream = streams.find(header.serial_number);
+ if (stream == streams.end()) {
+ if (streams.size() >= MAXIMUM_SCANNED_STREAM_COUNT)
+ return;
+ ScannedStream scanned_stream {
+ .description = { header.serial_number, {} },
+ .beginning_page_position = header.position,
+ .pending_headers = StreamHeaderReader {},
+ .next_header_page_position = header.position,
+ };
+ streams.set(header.serial_number, move(scanned_stream));
+ stream = streams.find(header.serial_number);
+ }
+ if (stream->value.beginning_page_position == header.position && range.previous_page.has_value())
+ stream->value.preceding_page = range.previous_page;
+ return;
+ }
+ if (!header.has_granule_position())
+ return;
+ for (auto& extent : range.extents) {
+ if (extent.first_page.serial_number == header.serial_number) {
+ extent.last_page = header;
+ return;
+ }
+ }
+ if (range.extents.size() < MAXIMUM_SCANNED_STREAM_COUNT)
+ range.extents.append({ header, header });
+}
+
+void OggDemuxer::BufferedScanPayload::walk(ScannedByteRange& range)
+{
+ if (!range.next_page_position.has_value()) {
+ range.next_page_position = range.byte_start;
+ range.needs_resync = true;
+ range.previous_page = {};
+ }
+ while (*range.next_page_position < range.byte_end) {
+ walker.set_position(*range.next_page_position);
+ if (range.needs_resync) {
+ auto bound = min(range.byte_end, *range.next_page_position + MAXIMUM_RESYNC_BYTES_PER_SCAN);
+ auto found = walker.resync_forward(bound);
+ if (found.is_error())
+ return;
+ if (!found.value()) {
+ // Retain enough overlap to retry a page cut off by the buffered range.
+ if (bound == *range.next_page_position + MAXIMUM_RESYNC_BYTES_PER_SCAN)
+ range.next_page_position = bound - MAXIMUM_PAGE_SIZE;
+ return;
+ }
+ range.next_page_position = walker.position();
+ range.needs_resync = false;
+ range.previous_page = {};
+ }
+
+ auto result = walker.read_next_page_header();
+ if (result.is_error())
+ return;
+ if (auto const* failure = result.value().get_pointer<PageReadFailure>()) {
+ if (*failure == PageReadFailure::Incomplete)
+ return;
+ ++*range.next_page_position;
+ range.needs_resync = true;
+ continue;
+ }
+ auto const& header = result.value().get<PageHeader>();
+ if (header.end_position() > range.byte_end)
+ return;
+ scan_page(range, header);
+ range.previous_page = header;
+ range.next_page_position = header.end_position();
+ }
+}
+
+void OggDemuxer::BufferedScanPayload::read_pending_headers(ScannedStream& stream) const
+{
+ if (!stream.pending_headers.has_value())
+ return;
+ auto& reader = *stream.pending_headers;
+ PageIterator pages = walker;
+ pages.set_position(stream.next_header_page_position);
+ while (pages.position() - stream.beginning_page_position < MAXIMUM_LINK_HEADER_BYTE_COUNT) {
+ auto result = pages.read_next_page_header();
+ if (result.is_error())
+ return;
+ if (auto const* failure = result.value().get_pointer<PageReadFailure>()) {
+ if (*failure == PageReadFailure::Incomplete)
+ return;
+ break;
+ }
+ auto const& header = result.value().get<PageHeader>();
+ if (header.begins_stream() && header.position != stream.beginning_page_position && reader.stream.serial_number == header.serial_number)
+ break;
+ if (header.serial_number == stream.description.serial_number) {
+ auto page = pages.read_page_at(header.position);
+ if (page.is_error() || !page.value().has_value())
+ return;
+ if (reader.consume(*page.value()).is_error())
+ break;
+ if (!reader.needs_more_pages()) {
+ stream.description.identification = reader.stream.identification;
+ if (stream.description.identification.has_value() && stream.description.identification->codec_id == CodecID::Vorbis)
+ stream.vorbis_parser = Codecs::Vorbis::Parser::create(reader.stream.codec_initialization_data.span());
+ break;
+ }
+ }
+ stream.next_header_page_position = pages.position();
+ }
+ stream.pending_headers = {};
+}
+
+Vector<OggDemuxer::ScannedLink> OggDemuxer::BufferedScanPayload::assemble_links(size_t first_link_position) const
+{
+ Vector<ScannedStream const*> ordered_streams;
+ for (auto const& entry : streams)
+ ordered_streams.append(&entry.value);
+ quick_sort(ordered_streams, [](auto* a, auto* b) { return a->beginning_page_position < b->beginning_page_position; });
+
+ Vector<ScannedLink> links;
+ HashMap<u32, size_t> link_indices;
+ for (auto const* stream : ordered_streams) {
+ Optional<size_t> concurrent_link_index;
+ if (stream->preceding_page.has_value() && stream->preceding_page->begins_stream())
+ concurrent_link_index = link_indices.get(stream->preceding_page->serial_number);
+ if (!concurrent_link_index.has_value() || links[*concurrent_link_index].streams.size() >= MAXIMUM_LINK_STREAM_COUNT) {
+ ScannedLink link;
+ link.position = stream->beginning_page_position;
+ if (stream->preceding_page.has_value() && !stream->preceding_page->begins_stream())
+ link.preceding_stream_serial_number = stream->preceding_page->serial_number;
+ links.append(move(link));
+ concurrent_link_index = links.size() - 1;
+ }
+ auto& link = links[*concurrent_link_index];
+ link.streams.append(stream->description);
+ link_indices.set(stream->description.serial_number, *concurrent_link_index);
+ if (stream->description.identification.has_value() && stream->maximum_granule_position.has_value()) {
+ auto const& identification = *stream->description.identification;
+ auto end_time = identification.time_of_units(identification.end_units_of_granule_position(*stream->maximum_granule_position));
+ link.end_time = max(link.end_time.value_or(AK::Duration::zero()), end_time);
+ }
+ }
+ for (size_t i = 0; i < links.size(); i++) {
+ auto& link = links[i];
+ if (link.position == first_link_position) {
+ link.start_offset = AK::Duration::zero();
+ continue;
+ }
+ if (!link.preceding_stream_serial_number.has_value())
+ continue;
+ auto preceding_index = link_indices.get(*link.preceding_stream_serial_number);
+ if (!preceding_index.has_value() || *preceding_index >= i)
+ continue;
+ auto const& preceding = links[*preceding_index];
+ if (preceding.start_offset.has_value() && preceding.end_time.has_value())
+ link.start_offset = *preceding.start_offset + *preceding.end_time;
+ }
+ return links;
+}
+
+DemuxerScanState OggDemuxer::BufferedScanPayload::scan_available_ranges(MediaStream::Availability const& availability, ReadonlySpan<TrackDescription> tracks, size_t first_link_position, AK::Duration minimum_duration)
+{
+ scanned_ranges.update(availability.byte_ranges, [&](ScannedByteRange& range, CachedRangeChange change) {
+ if (has_flag(change, CachedRangeChange::Start) || range.next_page_position.value_or(range.byte_start) > range.byte_end) {
+ range.next_page_position = {};
+ range.extents.clear();
+ }
+ walk(range);
+ });
+ for (auto& entry : streams)
+ read_pending_headers(entry.value);
+ for (auto const& range : scanned_ranges.ranges()) {
+ for (auto const& extent : range.extents) {
+ auto stream = streams.find(extent.last_page.serial_number);
+ if (stream != streams.end())
+ stream->value.maximum_granule_position = max(stream->value.maximum_granule_position.value_or(0), extent.last_page.granule_position);
+ }
+ }
+ auto links = assemble_links(first_link_position);
+ HashMap<u32, size_t> link_indices;
+ for (size_t i = 0; i < links.size(); i++) {
+ for (auto const& stream : links[i].streams)
+ link_indices.set(stream.serial_number, i);
+ }
+
+ Vector<BufferedRangesScan> scans;
+ for (auto const& track : tracks)
+ scans.append({ .time_ranges = {}, .last_byte_range_has_samples = false, .track_identifier = track.track.identifier() });
+ Vector<PageAnchor> anchors;
+ for (auto const& range : scanned_ranges.ranges()) {
+ Vector<Optional<AK::Duration>> starts;
+ Vector<Optional<AK::Duration>> ends;
+ starts.resize(tracks.size());
+ ends.resize(tracks.size());
+ for (auto const& extent : range.extents) {
+ auto serial_number = extent.first_page.serial_number;
+ auto stream_entry = streams.find(serial_number);
+ if (stream_entry == streams.end() || !stream_entry->value.description.identification.has_value())
+ continue;
+ auto const& stream = stream_entry->value;
+ auto const& identification = *stream.description.identification;
+ auto const& link = links[link_indices.get(serial_number).value()];
+ auto first_end_units = identification.end_units_of_granule_position(extent.first_page.granule_position);
+ auto last_end_units = identification.end_units_of_granule_position(extent.last_page.granule_position);
+ anchors.append({ serial_number, extent.first_page.position, first_end_units });
+ anchors.append({ serial_number, extent.last_page.position, last_end_units });
+ if (!link.start_offset.has_value())
+ continue;
+ auto first_start_units = start_units_of_page(extent.first_page, stream, first_end_units);
+ for (size_t track_index = 0; track_index < tracks.size(); track_index++) {
+ auto const& track = tracks[track_index];
+ auto stream_index = link.index_of_stream_for_track(track.track.type(), track.index_within_type);
+ if (!stream_index.has_value() || link.streams[*stream_index].serial_number != serial_number)
+ continue;
+ auto start = *link.start_offset + max(identification.time_of_units(first_start_units), AK::Duration::zero());
+ auto end = *link.start_offset + identification.time_of_units(last_end_units);
+ if (!starts[track_index].has_value() || start < *starts[track_index])
+ starts[track_index] = start;
+ if (!ends[track_index].has_value() || end > *ends[track_index])
+ ends[track_index] = end;
+ }
+ }
+ for (size_t track_index = 0; track_index < tracks.size(); track_index++) {
+ auto& scan = scans[track_index];
+ auto has_samples = starts[track_index].has_value() && *starts[track_index] < *ends[track_index];
+ scan.last_byte_range_has_samples = has_samples;
+ if (has_samples)
+ scan.time_ranges.add_range(*starts[track_index], *ends[track_index]);
+ }
+ }
+
+ {
+ MutexLocker locker { published->mutex };
+ published->links = move(links);
+ published->anchors = move(anchors);
+ }
+ return DemuxerScanState::create_from_track_scans(move(scans), minimum_duration, availability.closing_bytes_are_available());
+}
+
+void OggDemuxer::start_buffered_scan_thread()
+{
+ HashMap<u32, ScannedStream> streams;
+ Optional<PageHeader> preceding_page;
+ for (auto const& stream : m_first_link.streams) {
+ ScannedStream scanned_stream {
+ .description = { stream.serial_number, stream.identification },
+ .beginning_page_position = stream.beginning_page.position,
+ .preceding_page = preceding_page,
+ };
+ if (stream.identification.has_value() && stream.identification->codec_id == CodecID::Vorbis)
+ scanned_stream.vorbis_parser = Codecs::Vorbis::Parser::create(stream.codec_initialization_data.span());
+ streams.set(stream.serial_number, move(scanned_stream));
+ preceding_page = stream.beginning_page;
+ }
+
+ auto scan_cursor = m_stream->create_cursor();
+ scan_cursor->set_is_blocking(false);
+ BufferedScanPayload payload {
+ .walker = PageIterator { move(scan_cursor), 0 },
+ .scanned_ranges = {},
+ .streams = move(streams),
+ .published = m_published_scan,
+ };
+ m_published_scan->links = payload.assemble_links(m_first_link.position);
+
+ DemuxerScanState initial_state;
+ initial_state.duration = m_duration;
+ m_buffered_scan_thread = DemuxerScanThread<BufferedScanPayload>::start(m_stream, move(initial_state), move(payload),
+ [tracks = m_tracks, duration = m_duration, first_link_position = m_first_link.position](MediaStream::Availability const& availability, BufferedScanPayload& payload) {
+ return payload.scan_available_ranges(availability, tracks, first_link_position, duration);
+ });
+}
+
+OggDemuxer::TrackDescription const& OggDemuxer::track_description(Track const& track) const
+{
+ VERIFY(track.identifier() < m_tracks.size());
+ auto const& description = m_tracks[track.identifier()];
+ VERIFY(description.track == track);
+ return description;
+}
+
+OggDemuxer::TrackStatus& OggDemuxer::track_status(Track const& track)
+{
+ MutexLocker locker { m_track_statuses_mutex };
+ VERIFY(track.identifier() < m_track_statuses.size());
+ auto& status = m_track_statuses[track.identifier()];
+ VERIFY(status != nullptr);
+ return *status;
+}
+
+DecoderErrorOr<void> OggDemuxer::enter_link(TrackStatus& status, TrackDescription const& description, Link link, AK::Duration start_offset)
+{
+ Optional<Codecs::Vorbis::Parser> vorbis_parser;
+ auto stream_index = link.index_of_stream_for_track(description.track.type(), description.index_within_type);
+ if (stream_index.has_value()) {
+ auto const& stream = link.streams[*stream_index];
+ if (stream.identification->codec_id == CodecID::Vorbis) {
+ vorbis_parser = Codecs::Vorbis::Parser::create(stream.codec_initialization_data.span());
+ if (!vorbis_parser.has_value())
+ return DecoderError::corrupted("Vorbis headers could not be parsed"sv);
+ }
+ }
+
+ status.link = move(link);
+ status.stream_index = stream_index;
+ status.link_start_offset = start_offset;
+ status.link_end_time = {};
+ status.vorbis_parser = move(vorbis_parser);
+ status.assembler.reset();
+ status.running_end_units = {};
+ status.needs_codec_configuration = true;
+ status.reading_seek_preroll_page = false;
+ status.ready_frames.clear();
+ return {};
+}
+
+DecoderErrorOr<void> OggDemuxer::create_context_for_track(Track const& track)
+{
+ auto const& description = track_description(track);
+ auto cursor = m_stream->create_cursor();
+ cursor->set_is_blocking(true);
+
+ auto status = make<TrackStatus>(PageIterator { move(cursor), m_first_link.position });
+ TRY(enter_link(*status, description, TRY(m_first_link.clone()), AK::Duration::zero()));
+
+ MutexLocker locker { m_track_statuses_mutex };
+ VERIFY(m_track_statuses[track.identifier()] == nullptr);
+ m_track_statuses[track.identifier()] = move(status);
+ return {};
+}
+
+DecoderErrorOr<Vector<Track>> OggDemuxer::get_tracks_for_type(TrackType type)
+{
+ Vector<Track> tracks;
+ for (auto const& description : m_tracks) {
+ if (description.track.type() == type)
+ tracks.append(description.track);
+ }
+ return tracks;
+}
+
+DecoderErrorOr<Optional<Track>> OggDemuxer::get_preferred_track_for_type(TrackType type)
+{
+ for (auto const& description : m_tracks) {
+ if (description.track.type() == type)
+ return Optional<Track> { description.track };
+ }
+ return Optional<Track> {};
+}
+
+DecoderErrorOr<void> OggDemuxer::queue_packets(TrackStatus& status, PageHeader const& header, Vector<FixedArray<u8>> packets)
+{
+ auto const& stream = status.link.streams[*status.stream_index];
+ auto const& identification = *stream.identification;
+
+ packets.remove_all_matching([&](auto const& packet) { return is_header_packet(identification, packet.span()); });
+
+ Vector<i64> durations;
+ for (auto const& packet : packets)
+ durations.append(packet_duration_in_units(status.vorbis_parser.has_value() ? &*status.vorbis_parser : nullptr, identification, packet.span()));
+
+ // A page's granule position is where its last packet ends, which places every packet that completes on it.
+ // The final page of a stream may end before its last packet does, trimming that packet's end, so it is placed
+ // from the packets before it where they are known.
+ Vector<i64> ends;
+ ends.resize(packets.size());
+ i64 trailing_trim_units = 0;
+ auto place_packet_ends_from_start_units = [&](i64 start) {
+ for (size_t i = 0; i < packets.size(); i++) {
+ start += durations[i];
+ ends[i] = start;
+ }
+ };
+ if (header.has_granule_position()) {
+ auto page_end = identification.end_units_of_granule_position(header.granule_position);
+ if (header.ends_stream() && status.running_end_units.has_value() && !packets.is_empty()) {
+ place_packet_ends_from_start_units(*status.running_end_units);
+ if (ends.last() > page_end)
+ trailing_trim_units = min(ends.last() - page_end, durations.last());
+ } else {
+ auto end = page_end;
+ for (size_t i = packets.size(); i-- > 0;) {
+ ends[i] = end;
+ end -= durations[i];
+ }
+ }
+ status.running_end_units = page_end;
+ } else if (status.running_end_units.has_value()) {
+ place_packet_ends_from_start_units(*status.running_end_units);
+ if (!packets.is_empty())
+ status.running_end_units = ends.last();
+ } else {
+ return {};
+ }
+ if (status.reading_seek_preroll_page) {
+ status.reading_seek_preroll_page = false;
+ return {};
+ }
+
+ for (size_t i = 0; i < packets.size(); i++) {
+ auto& packet = packets[i];
+ auto flags = FrameFlags::Keyframe;
+ if (identification.codec_id == CodecID::Theora) {
+ // An empty packet repeats the frame before it, which the sink holds anyway.
+ if (packet.is_empty())
+ continue;
+ if (!is_theora_keyframe(packet.span())) {
+ if (status.waiting_for_keyframe)
+ continue;
+ flags = FrameFlags::None;
+ }
+ status.waiting_for_keyframe = false;
+ }
+
+ auto start_time = identification.time_of_units(ends[i] - durations[i]);
+ auto full_end_time = identification.time_of_units(ends[i]);
+ auto end_time = full_end_time;
+ if (i == packets.size() - 1)
+ end_time = identification.time_of_units(ends[i] - trailing_trim_units);
+
+ // Audio before the start of the stream is decoded but not played. Opus decoders drop the pre-skip themselves,
+ // as they do for Matroska, so for Opus it is only left out of the frame's time.
+ auto presentation_time = start_time;
+ auto leading_discard = AK::Duration::zero();
+ if (identification.type == TrackType::Audio && start_time < AK::Duration::zero()) {
+ presentation_time = min(end_time, AK::Duration::zero());
+ if (identification.codec_id != CodecID::Opus)
+ leading_discard = presentation_time - start_time;
+ }
+
+ auto frame = CodedFrame(identification.codec_id, status.link_start_offset + presentation_time, status.link_start_offset + presentation_time, end_time - presentation_time, flags, move(packet), {});
+ frame.set_leading_discard(leading_discard);
+ frame.set_trailing_discard(full_end_time - end_time);
+ status.ready_frames.enqueue(move(frame));
+ }
+ return {};
+}
+
+DecoderErrorOr<void> OggDemuxer::handle_page(TrackStatus& status, TrackDescription const& description, Page page)
+{
+ auto const& header = page.header;
+ auto stream_index = status.link.index_of_serial_number(header.serial_number);
+ if (!stream_index.has_value()) {
+ if (!header.begins_stream())
+ return {};
+ // Keep header reads separate from playback so an interrupted link transition can be retried.
+ PageIterator link_reader = status.pages;
+ link_reader.set_position(header.position);
+ auto link = read_link(link_reader);
+ if (link.is_error()) {
+ status.pages.set_position(header.position);
+ return link.release_error();
+ }
+ auto start_offset = status.link_start_offset + status.link_end_time;
+ TRY(enter_link(status, description, link.release_value(), start_offset));
+ status.pages.set_position(header.position);
+ return {};
+ }
+
+ auto const& stream = status.link.streams[*stream_index];
+ if (stream.identification.has_value() && header.has_granule_position()) {
+ auto end_time = stream.identification->time_of_units(stream.identification->end_units_of_granule_position(header.granule_position));
+ status.link_end_time = max(status.link_end_time, end_time);
+ }
+ if (stream_index != status.stream_index)
+ return {};
+
+ auto packets = status.assembler.take_completed_packets(page);
+ if (packets.is_error()) {
+ if (packets.error().category() == DecoderErrorCategory::Corrupted)
+ return {};
+ return packets.release_error();
+ }
+ return queue_packets(status, header, packets.release_value());
+}
+
+DecoderErrorOr<CodedFrame> OggDemuxer::get_next_sample_for_track(Track const& track)
+{
+ auto const& description = track_description(track);
+ auto& status = track_status(track);
+
+ while (true) {
+ if (!status.ready_frames.is_empty()) {
+ auto frame = status.ready_frames.dequeue();
+ if (status.needs_codec_configuration) {
+ status.needs_codec_configuration = false;
+ auto const& stream = status.link.streams[*status.stream_index];
+ frame.set_new_codec_configuration(DECODER_TRY_ALLOC(stream.codec_initialization_data.clone()));
+ }
+ return frame;
+ }
+ if (!status.stream_index.has_value())
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "The track has no stream in this link"sv);
+ auto page = TRY(status.pages.read_next_page());
+ TRY(handle_page(status, description, move(page)));
+ }
+}
+
+AK::Duration OggDemuxer::select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode)
+{
+ return target;
+}
+
+namespace {
+
+struct TimedPage {
+ size_t position { 0 };
+ i64 end_units { 0 };
+};
+
+}
+
+static DecoderErrorOr<Optional<TimedPage>> read_timed_page_at_or_after(PageIterator const& iterator, size_t position, size_t bound, u32 serial_number, StreamIdentification const& identification)
+{
+ PageIterator probe = iterator;
+ probe.set_position(position);
+ if (!TRY(probe.resync_forward(bound)))
+ return Optional<TimedPage> {};
+ while (probe.position() < bound) {
+ auto result = TRY(probe.read_next_page_header());
+ auto const* header = result.get_pointer<PageHeader>();
+ if (header == nullptr)
+ break;
+ if (header->serial_number == serial_number && header->has_granule_position())
+ return TimedPage { header->position, identification.end_units_of_granule_position(header->granule_position) };
+ }
+ return Optional<TimedPage> {};
+}
+
+DecoderErrorOr<OggDemuxer::LandingPage> OggDemuxer::find_landing_page(PageIterator const& iterator, size_t link_position, Optional<size_t> link_end_position, u32 serial_number, StreamIdentification const& identification, i64 target_units, Vector<PageAnchor> const& anchors) const
+{
+ if (target_units <= 0)
+ return LandingPage { link_position, {} };
+
+ struct Anchor {
+ size_t byte { 0 };
+ i64 units { 0 };
+ };
+ Anchor low { link_position, 0 };
+ Optional<Anchor> high;
+ auto consider = [&](PageAnchor const& anchor) {
+ if (anchor.serial_number != serial_number || anchor.position < link_position)
+ return;
+ if (link_end_position.has_value() && anchor.position >= *link_end_position)
+ return;
+ if (anchor.end_units <= target_units) {
+ if (anchor.end_units >= low.units)
+ low = { anchor.position, anchor.end_units };
+ } else if (!high.has_value() || anchor.end_units < high->units) {
+ high = Anchor { anchor.position, anchor.end_units };
+ }
+ };
+ for (auto const& anchor : anchors)
+ consider(anchor);
+ if (m_tail_anchor.has_value())
+ consider(*m_tail_anchor);
+ if (high.has_value() && high->byte <= low.byte)
+ high = {};
+
+ // Aim before the target, so that a probe lands before it rather than closing in from one side, and then walk.
+ auto underestimate_target_by = max<i64>(identification.units_of_time(SEEK_LEAD), 1);
+ for (size_t probe = 0; probe < MAXIMUM_SEEK_PROBE_COUNT && target_units - low.units > underestimate_target_by; probe++) {
+ if (!high.has_value() || high->byte <= low.byte + 1 || high->units <= low.units)
+ break;
+ auto aim = target_units - underestimate_target_by;
+ auto units_fraction = static_cast<double>(aim - low.units) / static_cast<double>(high->units - low.units);
+ auto guess = low.byte + static_cast<size_t>(static_cast<double>(high->byte - low.byte) * units_fraction);
+ guess = clamp(guess, low.byte + 1, high->byte - 1);
+
+ auto page = TRY(read_timed_page_at_or_after(iterator, guess, high->byte, serial_number, identification));
+ if (!page.has_value()) {
+ // None of the stream's pages lie past the guess, so the one we know of is the closest.
+ high->byte = guess;
+ continue;
+ }
+ if (page->end_units <= target_units) {
+ low = { page->position, page->end_units };
+ } else {
+ high = Anchor { page->position, page->end_units };
+ underestimate_target_by *= 2;
+ }
+ }
+
+ // Walk to the last of the stream's pages that ends by the target. The packet it ends with starts no later than that.
+ LandingPage landing { low.byte, {} };
+ PageIterator walker = iterator;
+ walker.set_position(low.byte);
+ auto passed_stream_starts = false;
+ while (true) {
+ if (link_end_position.has_value() && walker.position() >= *link_end_position)
+ break;
+ auto result = TRY(walker.read_next_page_header());
+ auto const* header = result.get_pointer<PageHeader>();
+ if (header == nullptr) {
+ if (result.get<PageReadFailure>() == PageReadFailure::Incomplete)
+ break;
+ walker.set_position(walker.position() + 1);
+ if (!TRY(walker.resync_forward()))
+ break;
+ continue;
+ }
+ if (header->begins_stream()) {
+ if (passed_stream_starts)
+ break;
+ continue;
+ }
+ passed_stream_starts = true;
+ if (header->serial_number != serial_number || !header->has_granule_position())
+ continue;
+ if (identification.end_units_of_granule_position(header->granule_position) > target_units)
+ break;
+ landing = { header->position, header->granule_position };
+ }
+ return landing;
+}
+
+DecoderErrorOr<DemuxerSeekResult> OggDemuxer::seek_to_most_recent_keyframe(Track const& track, AK::Duration timestamp, DemuxerSeekOptions options)
+{
+ auto const& description = track_description(track);
+ auto& status = track_status(track);
+
+ Vector<ScannedLink> links;
+ Vector<PageAnchor> anchors;
+ {
+ MutexLocker locker { m_published_scan->mutex };
+ links = m_published_scan->links;
+ anchors = m_published_scan->anchors;
+ }
+
+ size_t link_position = m_first_link.position;
+ auto start_offset = AK::Duration::zero();
+ Optional<size_t> link_end_position;
+ for (size_t i = 0; i < links.size(); i++) {
+ auto const& link = links[i];
+ if (!link.start_offset.has_value() || *link.start_offset > timestamp)
+ continue;
+ if (!link.index_of_stream_for_track(description.track.type(), description.index_within_type).has_value())
+ continue;
+ link_position = link.position;
+ start_offset = *link.start_offset;
+ link_end_position = {};
+ if (i + 1 < links.size())
+ link_end_position = links[i + 1].position;
+ }
+
+ Link link;
+ if (link_position == status.link.position) {
+ link = TRY(status.link.clone());
+ } else if (link_position == m_first_link.position) {
+ link = TRY(m_first_link.clone());
+ } else {
+ PageIterator link_reader = status.pages;
+ link_reader.set_position(link_position);
+ link = TRY(read_link(link_reader));
+ }
+ auto stream_index = link.index_of_stream_for_track(description.track.type(), description.index_within_type);
+ if (!stream_index.has_value())
+ return DecoderError::corrupted("The link we seek into does not carry the track"sv);
+ auto const& stream = link.streams[*stream_index];
+ auto const& identification = *stream.identification;
+
+ auto local_target = timestamp - start_offset;
+ if (identification.codec_id == CodecID::Opus)
+ local_target -= OPUS_SEEK_PREROLL;
+ auto target_units = identification.units_of_time(local_target);
+ LandingPage landing;
+ if (identification.codec_id == CodecID::Theora) {
+ // Land on a page ending by the target frame, then on the page before the keyframe that frame depends on.
+ landing = TRY(find_landing_page(status.pages, link.position, link_end_position, stream.serial_number, identification, target_units + 1, anchors));
+ if (landing.granule_position.has_value()) {
+ auto keyframe_units = identification.theora_keyframe_start_units(*landing.granule_position);
+ landing = TRY(find_landing_page(status.pages, link.position, link_end_position, stream.serial_number, identification, keyframe_units, anchors));
+ }
+ } else {
+ landing = TRY(find_landing_page(status.pages, link.position, link_end_position, stream.serial_number, identification, target_units, anchors));
+ }
+
+ if (link.position != status.link.position)
+ TRY(enter_link(status, description, move(link), start_offset));
+ status.pages.set_position(landing.position);
+ status.assembler.reset();
+ status.running_end_units = {};
+ status.ready_frames.clear();
+ if (status.vorbis_parser.has_value())
+ status.vorbis_parser->reset();
+ status.waiting_for_keyframe = description.track.type() == TrackType::Video;
+ status.reading_seek_preroll_page = landing.granule_position.has_value();
+ if (has_flag(options, DemuxerSeekOptions::NeedCodecConfiguration))
+ status.needs_codec_configuration = true;
+ return DemuxerSeekResult::MovedPosition;
+}
+
+DecoderErrorOr<AK::Duration> OggDemuxer::total_duration()
+{
+ return m_duration;
+}
+
+DecoderErrorOr<AK::Duration> OggDemuxer::duration_of_track(Track const&)
+{
+ return total_duration();
+}
+
+DemuxerScanState const& OggDemuxer::scan_state() const
+{
+ return m_buffered_scan_thread->main_thread_state();
+}
+
+void OggDemuxer::set_scan_state_change_handler(ScanStateChangeHandler handler)
+{
+ m_buffered_scan_thread->set_change_handler([handler = move(handler)] {
+ if (handler)
+ handler(TimeRanges {});
+ });
+}
+
+void OggDemuxer::set_blocking_reads_aborted_for_track(Track const& track)
+{
+ track_status(track).pages.cursor().abort();
+}
+
+void OggDemuxer::reset_blocking_reads_aborted_for_track(Track const& track)
+{
+ track_status(track).pages.cursor().reset_abort();
+}
+
+void OggDemuxer::set_read_blocked_change_handler_for_track(Track const& track, ReadBlockedChangeHandler handler)
+{
+ track_status(track).pages.cursor().set_blocked_change_handler(move(handler));
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/Ogg/OggDemuxer.h b/Libraries/LibMedia/Containers/Ogg/OggDemuxer.h
new file mode 100644
index 00000000000..21735221daf
--- /dev/null
+++ b/Libraries/LibMedia/Containers/Ogg/OggDemuxer.h
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/HashMap.h>
+#include <AK/Mutex.h>
+#include <AK/OwnPtr.h>
+#include <AK/Queue.h>
+#include <LibMedia/Codecs/Vorbis.h>
+#include <LibMedia/ContainerID.h>
+#include <LibMedia/Containers/CachedByteRanges.h>
+#include <LibMedia/Containers/Ogg/Reader.h>
+#include <LibMedia/Demuxer.h>
+#include <LibMedia/DemuxerScanThread.h>
+#include <LibMedia/Export.h>
+#include <LibMedia/Forward.h>
+
+namespace Media::Ogg {
+
+class MEDIA_API OggDemuxer 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);
+
+ ~OggDemuxer();
+
+ 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 target, SeekMode) override;
+ virtual DecoderErrorOr<DemuxerSeekResult> seek_to_most_recent_keyframe(Track const&, AK::Duration timestamp, 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 StreamDescription {
+ u32 serial_number { 0 };
+ Optional<StreamIdentification> identification;
+ };
+
+ struct LinkStream : StreamDescription {
+ PageHeader beginning_page;
+ FixedArray<u8> codec_initialization_data;
+ };
+
+ struct StreamHeaderReader {
+ LinkStream stream;
+ PacketAssembler assembler;
+ Vector<FixedArray<u8>> packets;
+ bool complete { false };
+
+ bool needs_more_pages() const { return stream.identification.has_value() && !complete; }
+ DecoderErrorOr<void> consume(Page const&);
+ };
+
+ // A chained file contains successive links, each containing concurrent logical streams.
+ struct Link {
+ size_t position { 0 };
+ Vector<LinkStream> streams;
+
+ DecoderErrorOr<Link> clone() const;
+ Optional<size_t> index_of_serial_number(u32) const;
+ Optional<size_t> index_of_stream_for_track(TrackType, size_t index_within_type) const;
+ };
+
+ struct TrackDescription {
+ Track track;
+ size_t index_within_type { 0 };
+ };
+
+ struct ScannedLink {
+ size_t position { 0 };
+ Vector<StreamDescription> streams;
+ Optional<u32> preceding_stream_serial_number;
+ Optional<AK::Duration> end_time;
+ Optional<AK::Duration> start_offset;
+
+ Optional<size_t> index_of_stream_for_track(TrackType, size_t index_within_type) const;
+ };
+
+ struct PageAnchor {
+ u32 serial_number { 0 };
+ size_t position { 0 };
+ i64 end_units { 0 };
+ };
+
+ struct PublishedScan : public AtomicRefCounted<PublishedScan> {
+ Mutex mutex;
+ Vector<ScannedLink> links;
+ Vector<PageAnchor> anchors;
+ };
+
+ struct SerialExtent {
+ PageHeader first_page;
+ PageHeader last_page;
+ };
+
+ struct ScannedByteRange : public CachedByteRange {
+ using CachedByteRange::CachedByteRange;
+
+ Optional<size_t> next_page_position;
+ bool needs_resync { true };
+ Optional<PageHeader> previous_page;
+ Vector<SerialExtent> extents;
+ };
+
+ struct ScannedStream {
+ StreamDescription description;
+ size_t beginning_page_position { 0 };
+ Optional<PageHeader> preceding_page {};
+ Optional<i64> maximum_granule_position {};
+ Optional<StreamHeaderReader> pending_headers {};
+ size_t next_header_page_position { 0 };
+ Optional<Codecs::Vorbis::Parser> vorbis_parser {};
+ };
+
+ struct BufferedScanPayload {
+ PageIterator walker;
+ CachedByteRanges<ScannedByteRange> scanned_ranges;
+ HashMap<u32, ScannedStream> streams;
+ NonnullRefPtr<PublishedScan> published;
+
+ DemuxerScanState scan_available_ranges(MediaStream::Availability const&, ReadonlySpan<TrackDescription>, size_t first_link_position, AK::Duration minimum_duration);
+ void walk(ScannedByteRange&);
+ void scan_page(ScannedByteRange&, PageHeader const&);
+ void read_pending_headers(ScannedStream&) const;
+ Vector<ScannedLink> assemble_links(size_t first_link_position) const;
+ i64 start_units_of_page(PageHeader const&, ScannedStream const&, i64 end_units);
+ };
+
+ struct TrackStatus {
+ AK_ALLOC_WITH_KMALLOC;
+
+ PageIterator pages;
+ PacketAssembler assembler {};
+ Link link {};
+ Optional<size_t> stream_index {};
+ AK::Duration link_start_offset {};
+ AK::Duration link_end_time {};
+ Optional<Codecs::Vorbis::Parser> vorbis_parser {};
+ Optional<i64> running_end_units {};
+ bool needs_codec_configuration { true };
+ bool waiting_for_keyframe { false };
+ bool reading_seek_preroll_page { false };
+ Queue<CodedFrame> ready_frames {};
+ };
+
+ struct LandingPage {
+ size_t position { 0 };
+ Optional<i64> granule_position;
+ };
+
+ OggDemuxer(NonnullRefPtr<MediaStream> const&, Link, Vector<TrackDescription>, AK::Duration duration, Optional<PageAnchor> tail_anchor);
+
+ static DecoderErrorOr<Link> read_link(PageIterator&);
+
+ void start_buffered_scan_thread();
+ TrackStatus& track_status(Track const&);
+ TrackDescription const& track_description(Track const&) const;
+ static DecoderErrorOr<void> enter_link(TrackStatus&, TrackDescription const&, Link, AK::Duration start_offset);
+ static DecoderErrorOr<void> handle_page(TrackStatus&, TrackDescription const&, Page);
+ static DecoderErrorOr<void> queue_packets(TrackStatus&, PageHeader const&, Vector<FixedArray<u8>>);
+ DecoderErrorOr<LandingPage> find_landing_page(PageIterator const&, size_t link_position, Optional<size_t> link_end_position, u32 serial_number, StreamIdentification const&, i64 target_units, Vector<PageAnchor> const&) const;
+
+ NonnullRefPtr<MediaStream> m_stream;
+ Link m_first_link;
+ Vector<TrackDescription> m_tracks;
+ AK::Duration m_duration;
+ Optional<PageAnchor> m_tail_anchor;
+ NonnullRefPtr<PublishedScan> m_published_scan { make_ref_counted<PublishedScan>() };
+ RefPtr<DemuxerScanThread<BufferedScanPayload>> m_buffered_scan_thread;
+ Mutex m_track_statuses_mutex;
+ Vector<OwnPtr<TrackStatus>> m_track_statuses;
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/Ogg/Reader.cpp b/Libraries/LibMedia/Containers/Ogg/Reader.cpp
new file mode 100644
index 00000000000..1a5e17a1014
--- /dev/null
+++ b/Libraries/LibMedia/Containers/Ogg/Reader.cpp
@@ -0,0 +1,519 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/BitCast.h>
+#include <AK/Checked.h>
+#include <LibMedia/Codecs/FLAC.h>
+#include <LibMedia/Containers/Ogg/Reader.h>
+
+namespace Media::Ogg {
+
+static constexpr StringView CAPTURE_PATTERN = "OggS"sv;
+static constexpr size_t SCAN_CHUNK_SIZE = 4 * KiB;
+// A packet may span any number of pages, so a stream that never ends one must not grow it without bound. No frame of
+// the codecs we read comes near this.
+static constexpr size_t MAXIMUM_PACKET_SIZE = 32 * MiB;
+
+template<typename T>
+static T load_little_endian(ReadonlyBytes bytes, size_t offset)
+{
+ T value = 0;
+ for (size_t i = 0; i < sizeof(T); i++)
+ value |= static_cast<T>(bytes[offset + i]) << (8 * i);
+ return value;
+}
+
+template<typename T>
+static T load_big_endian(ReadonlyBytes bytes, size_t offset)
+{
+ T value = 0;
+ for (size_t i = 0; i < sizeof(T); i++)
+ value = static_cast<T>(value << 8) | bytes[offset + i];
+ return value;
+}
+
+static bool verify_page_crc(ReadonlyBytes header, ReadonlyBytes segment_sizes, ReadonlyBytes payload)
+{
+ constexpr size_t checksum_offset = 22;
+ constexpr auto lookup_table = [] {
+ Array<u32, 256> result;
+ for (u32 i = 0; i < result.size(); i++) {
+ u32 value = i << 24;
+ for (auto bit = 0; bit < 8; bit++)
+ value = (value << 1) ^ ((value & 0x80000000) != 0 ? 0x04C11DB7 : 0);
+ result[i] = value;
+ }
+ return result;
+ }();
+
+ u32 crc = 0;
+ auto add = [&](u8 byte) { crc = (crc << 8) ^ lookup_table[((crc >> 24) & 0xFF) ^ byte]; };
+ for (size_t i = 0; i < header.size(); i++)
+ add(i >= checksum_offset && i < checksum_offset + 4 ? 0 : header[i]);
+ for (auto byte : segment_sizes)
+ add(byte);
+ for (auto byte : payload)
+ add(byte);
+
+ auto expected_crc = static_cast<u32>(header[checksum_offset])
+ | (static_cast<u32>(header[checksum_offset + 1]) << 8)
+ | (static_cast<u32>(header[checksum_offset + 2]) << 16)
+ | (static_cast<u32>(header[checksum_offset + 3]) << 24);
+ return crc == expected_crc;
+}
+
+static DecoderErrorOr<bool> try_read_exactly_at(MediaStreamCursor& cursor, size_t position, Bytes bytes)
+{
+ if (bytes.is_empty())
+ return true;
+ TRY(cursor.seek_to_position(position));
+ auto read_count = cursor.read_into(bytes);
+ if (read_count.is_error()) {
+ if (read_count.error().category() == DecoderErrorCategory::EndOfStream)
+ return false;
+ return read_count.release_error();
+ }
+ return read_count.value() == bytes.size();
+}
+
+DecoderErrorOr<PageHeaderReadResult> PageIterator::read_header_at(size_t position, FixedArray<u8>* segment_sizes)
+{
+ Array<u8, PAGE_HEADER_SIZE> header;
+ if (!TRY(try_read_exactly_at(*m_cursor, position, header)))
+ return PageReadFailure::Incomplete;
+ if (!header.span().starts_with(CAPTURE_PATTERN.bytes()) || header[4] != 0)
+ return PageReadFailure::Invalid;
+
+ auto segment_count = header[26];
+ Array<u8, 255> segment_table;
+ auto segments = segment_table.span().trim(segment_count);
+ if (!TRY(try_read_exactly_at(*m_cursor, position + PAGE_HEADER_SIZE, segments)))
+ return PageReadFailure::Incomplete;
+
+ size_t payload_size = 0;
+ for (auto size : segments)
+ payload_size += size;
+
+ if (segment_sizes != nullptr)
+ *segment_sizes = DECODER_TRY_ALLOC(FixedArray<u8>::create(segments));
+
+ return PageHeader {
+ .position = position,
+ .byte_size = PAGE_HEADER_SIZE + segment_count + payload_size,
+ .flags = header[5],
+ .granule_position = bit_cast<i64>(load_little_endian<u64>(header, 6)),
+ .serial_number = load_little_endian<u32>(header, 14),
+ .sequence_number = load_little_endian<u32>(header, 18),
+ };
+}
+
+DecoderErrorOr<Optional<Page>> PageIterator::read_page_at(size_t position)
+{
+ FixedArray<u8> segment_sizes;
+ auto result = TRY(read_header_at(position, &segment_sizes));
+ auto const* header = result.get_pointer<PageHeader>();
+ if (header == nullptr)
+ return Optional<Page> {};
+
+ Array<u8, PAGE_HEADER_SIZE> header_bytes;
+ if (!TRY(try_read_exactly_at(*m_cursor, position, header_bytes)))
+ return Optional<Page> {};
+ auto payload_position = position + PAGE_HEADER_SIZE + segment_sizes.size();
+ auto payload = DECODER_TRY_ALLOC(FixedArray<u8>::create(header->end_position() - payload_position));
+ if (!TRY(try_read_exactly_at(*m_cursor, payload_position, payload.span())))
+ return Optional<Page> {};
+ if (!verify_page_crc(header_bytes, segment_sizes.span(), payload.span()))
+ return Optional<Page> {};
+
+ return Page { *header, move(segment_sizes), move(payload) };
+}
+
+DecoderErrorOr<bool> PageIterator::resync_forward(size_t bound)
+{
+ constexpr size_t capture_pattern_overlap = CAPTURE_PATTERN.length() - 1;
+ Array<u8, SCAN_CHUNK_SIZE + capture_pattern_overlap> chunk;
+ auto chunk_start = m_position;
+ while (chunk_start < bound) {
+ auto chunk_size = chunk.size();
+ if (bound - chunk_start < chunk_size - capture_pattern_overlap)
+ chunk_size = bound - chunk_start + capture_pattern_overlap;
+ TRY(m_cursor->seek_to_position(chunk_start));
+ auto read_count = m_cursor->read_into(chunk.span().trim(chunk_size));
+ if (read_count.is_error()) {
+ if (read_count.error().category() == DecoderErrorCategory::EndOfStream)
+ return false;
+ return read_count.release_error();
+ }
+ if (read_count.value() < CAPTURE_PATTERN.length())
+ return false;
+ auto bytes = chunk.span().trim(read_count.value());
+ for (size_t i = 0; i + CAPTURE_PATTERN.length() <= bytes.size() && chunk_start + i < bound; i++) {
+ if (!bytes.slice(i).starts_with(CAPTURE_PATTERN.bytes()))
+ continue;
+ if (!TRY(read_page_at(chunk_start + i)).has_value())
+ continue;
+ m_position = chunk_start + i;
+ return true;
+ }
+ chunk_start += bytes.size() - capture_pattern_overlap;
+ }
+ return false;
+}
+
+DecoderErrorOr<Optional<PageHeader>> PageIterator::find_last_page_before(size_t bound, size_t lower_bound)
+{
+ constexpr size_t capture_pattern_overlap = CAPTURE_PATTERN.length() - 1;
+ Array<u8, SCAN_CHUNK_SIZE + capture_pattern_overlap> chunk;
+ auto chunk_end = bound;
+ while (chunk_end > lower_bound) {
+ auto chunk_start = max(lower_bound, chunk_end > SCAN_CHUNK_SIZE ? chunk_end - SCAN_CHUNK_SIZE : 0);
+ auto chunk_size = min(chunk_end + capture_pattern_overlap, bound) - chunk_start;
+ TRY(m_cursor->seek_to_position(chunk_start));
+ auto read_count = m_cursor->read_into(chunk.span().trim(chunk_size));
+ if (read_count.is_error()) {
+ if (read_count.error().category() != DecoderErrorCategory::EndOfStream)
+ return read_count.release_error();
+ read_count = 0;
+ }
+ auto bytes = chunk.span().trim(read_count.value());
+ for (size_t i = bytes.size(); i-- > 0;) {
+ if (chunk_start + i >= chunk_end || !bytes.slice(i).starts_with(CAPTURE_PATTERN.bytes()))
+ continue;
+ auto page = TRY(read_page_at(chunk_start + i));
+ if (page.has_value() && page->header.end_position() <= bound)
+ return page->header;
+ }
+ chunk_end = chunk_start;
+ }
+ return Optional<PageHeader> {};
+}
+
+DecoderErrorOr<Page> PageIterator::read_next_page()
+{
+ while (true) {
+ if (auto page = TRY(read_page_at(m_position)); page.has_value()) {
+ m_position = page->header.end_position();
+ return page.release_value();
+ }
+ auto resync_iterator = *this;
+ resync_iterator.m_position++;
+ if (!TRY(resync_iterator.resync_forward()))
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "No page follows"sv);
+ m_position = resync_iterator.m_position;
+ }
+}
+
+DecoderErrorOr<PageHeaderReadResult> PageIterator::read_next_page_header()
+{
+ auto result = TRY(read_header_at(m_position, nullptr));
+ if (auto const* header = result.get_pointer<PageHeader>())
+ m_position = header->end_position();
+ return result;
+}
+
+Optional<PacketFragment> PacketFragmentIterator::next()
+{
+ if (m_segment_sizes.is_empty())
+ return {};
+ size_t byte_count = 0;
+ size_t segment_count = 0;
+ bool ends_packet = false;
+ for (auto segment_size : m_segment_sizes) {
+ byte_count += segment_size;
+ segment_count++;
+ if (segment_size < MAXIMUM_SEGMENT_SIZE) {
+ ends_packet = true;
+ break;
+ }
+ }
+ PacketFragment fragment { m_payload.trim(byte_count), m_starts_packet, ends_packet };
+ m_segment_sizes = m_segment_sizes.slice(segment_count);
+ m_payload = m_payload.slice(byte_count);
+ m_starts_packet = true;
+ return fragment;
+}
+
+Optional<ReadonlyBytes> Page::first_complete_packet() const
+{
+ auto fragment = packet_fragments().next();
+ if (fragment.has_value() && fragment->starts_packet && fragment->ends_packet)
+ return fragment->bytes;
+ return {};
+}
+
+void PacketAssembler::reset()
+{
+ m_partial_packet = {};
+ m_expected_sequence_number = {};
+}
+
+DecoderErrorOr<Vector<FixedArray<u8>>> PacketAssembler::take_completed_packets(Page const& page)
+{
+ if (m_expected_sequence_number != page.header.sequence_number || !page.header.continues_packet())
+ m_partial_packet = {};
+ m_expected_sequence_number = page.header.sequence_number + 1;
+
+ Vector<FixedArray<u8>> packets;
+ auto fragments = page.packet_fragments();
+ for (auto fragment = fragments.next(); fragment.has_value(); fragment = fragments.next()) {
+ if (fragment->starts_packet)
+ m_partial_packet = ByteBuffer {};
+ if (!m_partial_packet.has_value())
+ continue;
+ if (m_partial_packet->size() + fragment->bytes.size() > MAXIMUM_PACKET_SIZE) {
+ reset();
+ return DecoderError::corrupted("Packet is too large"sv);
+ }
+ DECODER_TRY_ALLOC(m_partial_packet->try_append(fragment->bytes));
+ if (fragment->ends_packet) {
+ DECODER_TRY_ALLOC(packets.try_append(DECODER_TRY_ALLOC(FixedArray<u8>::create(m_partial_packet->bytes()))));
+ m_partial_packet = {};
+ }
+ }
+ return packets;
+}
+
+static Audio::ChannelMap vorbis_channel_map(u8 channel_count)
+{
+ using Audio::Channel;
+ switch (channel_count) {
+ case 1:
+ return Audio::ChannelMap::mono();
+ case 2:
+ return Audio::ChannelMap::stereo();
+ case 3:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontCenter, Channel::FrontRight);
+ case 4:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontRight, Channel::BackLeft, Channel::BackRight);
+ case 5:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontCenter, Channel::FrontRight, Channel::BackLeft, Channel::BackRight);
+ case 6:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontCenter, Channel::FrontRight, Channel::BackLeft, Channel::BackRight, Channel::LowFrequency);
+ case 7:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontCenter, Channel::FrontRight, Channel::SideLeft, Channel::SideRight, Channel::BackCenter, Channel::LowFrequency);
+ case 8:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontCenter, Channel::FrontRight, Channel::SideLeft, Channel::SideRight, Channel::BackLeft, Channel::BackRight, Channel::LowFrequency);
+ default:
+ return Audio::ChannelMap::invalid();
+ }
+}
+
+Track StreamIdentification::create_track(size_t identifier) const
+{
+ Track track { type, identifier, Track::Kind::Main, {}, {} };
+ track.set_parsed_codec(ParsedCodec { codec_id });
+ if (type == TrackType::Video) {
+ track.set_video_data({ .pixel_width = pixel_width, .pixel_height = pixel_height, .cicp = {} });
+ return track;
+ }
+ auto channel_map = vorbis_channel_map(channel_count);
+ if (codec_id == CodecID::FLAC)
+ channel_map = Codecs::FLAC::channel_map(channel_count);
+ track.set_audio_data({ .sample_specification = Audio::SampleSpecification(sample_rate, channel_map) });
+ return track;
+}
+
+i64 StreamIdentification::end_units_of_granule_position(i64 granule_position) const
+{
+ VERIFY(granule_position >= 0);
+ if (codec_id == CodecID::Theora) {
+ auto keyframe_part = granule_position >> theora_keyframe_granule_shift;
+ auto frames_since_keyframe = granule_position & ((static_cast<i64>(1) << theora_keyframe_granule_shift) - 1);
+ auto frame_count = keyframe_part + frames_since_keyframe;
+ if (!theora_granule_counts_frames_from_one)
+ frame_count++;
+ return frame_count;
+ }
+ if (codec_id == CodecID::Opus)
+ return granule_position - opus_pre_skip;
+ return granule_position;
+}
+
+i64 StreamIdentification::theora_keyframe_start_units(i64 granule_position) const
+{
+ VERIFY(codec_id == CodecID::Theora && granule_position >= 0);
+ auto keyframe_part = granule_position >> theora_keyframe_granule_shift;
+ if (theora_granule_counts_frames_from_one)
+ return max<i64>(keyframe_part - 1, 0);
+ return keyframe_part;
+}
+
+AK::Duration StreamIdentification::time_of_units(i64 units) const
+{
+ if (type == TrackType::Video)
+ return AK::Duration::from_time_units(units, frame_rate_denominator, frame_rate_numerator);
+ return AK::Duration::from_time_units(units, 1, sample_rate);
+}
+
+i64 StreamIdentification::units_of_time(AK::Duration time) const
+{
+ if (type == TrackType::Video)
+ return time.to_time_units(frame_rate_denominator, frame_rate_numerator);
+ return time.to_time_units(1, sample_rate);
+}
+
+static DecoderErrorOr<StreamIdentification> identify_vorbis(ReadonlyBytes packet)
+{
+ if (packet.size() < 30 || load_little_endian<u32>(packet, 7) != 0)
+ return DecoderError::corrupted("Vorbis identification header is invalid"sv);
+ StreamIdentification identification;
+ identification.codec_id = CodecID::Vorbis;
+ identification.header_packet_count = 3;
+ identification.channel_count = packet[11];
+ identification.sample_rate = load_little_endian<u32>(packet, 12);
+ if (identification.channel_count == 0 || identification.sample_rate == 0)
+ return DecoderError::corrupted("Vorbis identification header is invalid"sv);
+ return identification;
+}
+
+static DecoderErrorOr<StreamIdentification> identify_opus(ReadonlyBytes packet)
+{
+ constexpr u8 major_version_mask = 0xF0;
+ if (packet.size() < 19 || (packet[8] & major_version_mask) != 0)
+ return DecoderError::corrupted("Opus identification header is invalid"sv);
+ StreamIdentification identification;
+ identification.codec_id = CodecID::Opus;
+ identification.header_packet_count = 2;
+ identification.channel_count = packet[9];
+ identification.opus_pre_skip = load_little_endian<u16>(packet, 10);
+ identification.sample_rate = 48'000;
+ if (identification.channel_count == 0)
+ return DecoderError::corrupted("Opus identification header is invalid"sv);
+ return identification;
+}
+
+static constexpr size_t OGG_FLAC_STREAM_INFO_OFFSET = 17;
+static constexpr size_t FLAC_STREAM_INFO_SIZE = 34;
+
+static DecoderErrorOr<StreamIdentification> identify_flac(ReadonlyBytes packet)
+{
+ // The mapping header, the native stream marker, then the STREAMINFO block with its own header.
+ if (packet.size() < OGG_FLAC_STREAM_INFO_OFFSET + FLAC_STREAM_INFO_SIZE || packet[5] != 1
+ || !packet.slice(9).starts_with("fLaC"sv.bytes()) || (packet[13] & 0x7F) != 0)
+ return DecoderError::corrupted("FLAC identification header is invalid"sv);
+ auto stream_info = packet.slice(OGG_FLAC_STREAM_INFO_OFFSET, FLAC_STREAM_INFO_SIZE);
+ StreamIdentification identification;
+ identification.codec_id = CodecID::FLAC;
+ auto following_header_count = load_big_endian<u16>(packet, 7);
+ if (following_header_count != 0)
+ identification.header_packet_count = following_header_count + 1;
+ identification.sample_rate = (static_cast<u32>(stream_info[10]) << 12) | (static_cast<u32>(stream_info[11]) << 4) | (stream_info[12] >> 4);
+ identification.channel_count = ((stream_info[12] >> 1) & 0x07) + 1;
+ if (identification.sample_rate == 0)
+ return DecoderError::corrupted("FLAC identification header is invalid"sv);
+ return identification;
+}
+
+static DecoderErrorOr<StreamIdentification> identify_theora(ReadonlyBytes packet)
+{
+ if (packet.size() < 42 || packet[7] != 3 || packet[8] != 2)
+ return DecoderError::corrupted("Theora identification header is invalid"sv);
+ auto load24 = [&](size_t offset) {
+ return (static_cast<u32>(packet[offset]) << 16) | (static_cast<u32>(packet[offset + 1]) << 8) | packet[offset + 2];
+ };
+ StreamIdentification identification;
+ identification.codec_id = CodecID::Theora;
+ identification.type = TrackType::Video;
+ identification.header_packet_count = 3;
+ identification.pixel_width = load24(14);
+ identification.pixel_height = load24(17);
+ identification.frame_rate_numerator = load_big_endian<u32>(packet, 22);
+ identification.frame_rate_denominator = load_big_endian<u32>(packet, 26);
+ identification.theora_keyframe_granule_shift = ((packet[40] & 0x03) << 3) | (packet[41] >> 5);
+ identification.theora_granule_counts_frames_from_one = packet[9] >= 1;
+ if (identification.pixel_width == 0 || identification.pixel_height == 0 || identification.frame_rate_numerator == 0 || identification.frame_rate_denominator == 0)
+ return DecoderError::corrupted("Theora identification header is invalid"sv);
+ return identification;
+}
+
+DecoderErrorOr<Optional<StreamIdentification>> identify_stream(ReadonlyBytes first_packet)
+{
+ if (first_packet.starts_with("\x01vorbis"sv.bytes()))
+ return TRY(identify_vorbis(first_packet));
+ if (first_packet.starts_with("OpusHead"sv.bytes()))
+ return TRY(identify_opus(first_packet));
+ if (first_packet.starts_with("\177FLAC"sv.bytes()))
+ return TRY(identify_flac(first_packet));
+ if (first_packet.starts_with("\x80theora"sv.bytes()))
+ return TRY(identify_theora(first_packet));
+ return Optional<StreamIdentification> {};
+}
+
+bool is_header_packet(StreamIdentification const& identification, ReadonlyBytes packet)
+{
+ switch (identification.codec_id) {
+ case CodecID::Vorbis:
+ return !packet.is_empty() && (packet[0] & 0x01) != 0;
+ case CodecID::Theora:
+ return !packet.is_empty() && (packet[0] & 0x80) != 0;
+ case CodecID::Opus:
+ return packet.starts_with("OpusHead"sv.bytes()) || packet.starts_with("OpusTags"sv.bytes());
+ case CodecID::FLAC:
+ // Metadata blocks begin with their type, and only frames begin with the first byte of their sync code.
+ return packet.is_empty() || packet[0] != 0xFF;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+}
+
+bool is_theora_keyframe(ReadonlyBytes packet)
+{
+ return !packet.is_empty() && (packet[0] & 0xC0) == 0;
+}
+
+DecoderErrorOr<FixedArray<u8>> build_codec_initialization_data(StreamIdentification const& identification, Vector<FixedArray<u8>> const& header_packets)
+{
+ VERIFY(!header_packets.is_empty());
+ switch (identification.codec_id) {
+ case CodecID::Opus:
+ return DECODER_TRY_ALLOC(FixedArray<u8>::create(header_packets[0].span()));
+ case CodecID::FLAC: {
+ // The native stream marker and a STREAMINFO block marked as the last, which is what FLAC streams start with.
+ auto stream_info = header_packets[0].span().slice(OGG_FLAC_STREAM_INFO_OFFSET, FLAC_STREAM_INFO_SIZE);
+ auto data = DECODER_TRY_ALLOC(FixedArray<u8>::create(8 + FLAC_STREAM_INFO_SIZE));
+ "fLaC"sv.bytes().copy_to(data.span());
+ data[4] = 0x80;
+ data[5] = 0;
+ data[6] = 0;
+ data[7] = FLAC_STREAM_INFO_SIZE;
+ stream_info.copy_to(data.span().slice(8));
+ return data;
+ }
+ case CodecID::Vorbis:
+ case CodecID::Theora: {
+ // The three headers in Xiph lacing: a count of all but the last, then all but the last one's sizes.
+ if (header_packets.size() != 3)
+ return DecoderError::corrupted("Stream does not have three header packets"sv);
+ Checked<size_t> size = 1;
+ for (size_t i = 0; i < 2; i++)
+ size += (header_packets[i].size() / 255) + 1;
+ for (auto const& packet : header_packets)
+ size += packet.size();
+ if (size.has_overflow())
+ return DecoderError::corrupted("Header packets are too large"sv);
+ auto data = DECODER_TRY_ALLOC(FixedArray<u8>::create(size.value()));
+ size_t offset = 0;
+ data[offset++] = 2;
+ for (size_t i = 0; i < 2; i++) {
+ auto remaining = header_packets[i].size();
+ while (remaining >= 255) {
+ data[offset++] = 255;
+ remaining -= 255;
+ }
+ data[offset++] = static_cast<u8>(remaining);
+ }
+ for (auto const& packet : header_packets) {
+ packet.span().copy_to(data.span().slice(offset));
+ offset += packet.size();
+ }
+ return data;
+ }
+ default:
+ VERIFY_NOT_REACHED();
+ }
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/Ogg/Reader.h b/Libraries/LibMedia/Containers/Ogg/Reader.h
new file mode 100644
index 00000000000..880e148d1b1
--- /dev/null
+++ b/Libraries/LibMedia/Containers/Ogg/Reader.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteBuffer.h>
+#include <AK/FixedArray.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/Time.h>
+#include <AK/Variant.h>
+#include <AK/Vector.h>
+#include <LibMedia/Export.h>
+#include <LibMedia/MediaStream.h>
+#include <LibMedia/Track.h>
+#include <LibMediaCodecs/CodecID.h>
+#include <LibMediaCodecs/DecoderError.h>
+
+namespace Media::Ogg {
+
+static constexpr i64 NO_GRANULE_POSITION = -1;
+static constexpr size_t PAGE_HEADER_SIZE = 27;
+static constexpr size_t MAXIMUM_SEGMENT_COUNT = 255;
+static constexpr size_t MAXIMUM_SEGMENT_SIZE = 255;
+static constexpr size_t MAXIMUM_PAGE_SIZE = PAGE_HEADER_SIZE + MAXIMUM_SEGMENT_COUNT + MAXIMUM_SEGMENT_COUNT * MAXIMUM_SEGMENT_SIZE;
+// Far beyond any real stream's length, and low enough that times and durations derived from it cannot overflow.
+static constexpr i64 MAXIMUM_GRANULE_POSITION = static_cast<i64>(1) << 62;
+
+struct PageHeader {
+ size_t position { 0 };
+ size_t byte_size { 0 };
+ u8 flags { 0 };
+ i64 granule_position { NO_GRANULE_POSITION };
+ u32 serial_number { 0 };
+ u32 sequence_number { 0 };
+
+ size_t end_position() const { return position + byte_size; }
+ bool continues_packet() const { return (flags & 0x01) != 0; }
+ bool begins_stream() const { return (flags & 0x02) != 0; }
+ bool ends_stream() const { return (flags & 0x04) != 0; }
+ // A granule position marks the end of the last packet that completes on the page.
+ bool has_granule_position() const { return granule_position >= 0 && granule_position <= MAXIMUM_GRANULE_POSITION; }
+};
+
+struct PacketFragment {
+ ReadonlyBytes bytes;
+ bool starts_packet { false };
+ bool ends_packet { false };
+};
+
+class MEDIA_API PacketFragmentIterator {
+public:
+ PacketFragmentIterator(ReadonlyBytes segment_sizes, ReadonlyBytes payload, bool continues_packet)
+ : m_segment_sizes(segment_sizes)
+ , m_payload(payload)
+ , m_starts_packet(!continues_packet)
+ {
+ }
+
+ Optional<PacketFragment> next();
+
+private:
+ ReadonlyBytes m_segment_sizes;
+ ReadonlyBytes m_payload;
+ bool m_starts_packet { false };
+};
+
+struct Page {
+ PageHeader header;
+ FixedArray<u8> segment_sizes;
+ FixedArray<u8> payload;
+
+ PacketFragmentIterator packet_fragments() const { return { segment_sizes.span(), payload.span(), header.continues_packet() }; }
+ Optional<ReadonlyBytes> first_complete_packet() const;
+};
+
+enum class PageReadFailure {
+ Incomplete,
+ Invalid,
+};
+
+using PageHeaderReadResult = Variant<PageHeader, PageReadFailure>;
+
+class MEDIA_API PageIterator {
+public:
+ PageIterator(NonnullRefPtr<MediaStreamCursor> cursor, size_t position)
+ : m_cursor(move(cursor))
+ , m_position(position)
+ {
+ }
+
+ DecoderErrorOr<bool> resync_forward(size_t bound = NumericLimits<size_t>::max());
+ // Resynchronizes after invalid pages. Interrupted reads leave the page available for retry.
+ DecoderErrorOr<Page> read_next_page();
+ // Header-only reads do not validate the payload or CRC.
+ DecoderErrorOr<PageHeaderReadResult> read_next_page_header();
+ DecoderErrorOr<Optional<Page>> read_page_at(size_t position);
+ DecoderErrorOr<Optional<PageHeader>> find_last_page_before(size_t bound, size_t lower_bound);
+
+ size_t position() const { return m_position; }
+ void set_position(size_t position) { m_position = position; }
+ MediaStreamCursor& cursor() { return *m_cursor; }
+
+private:
+ DecoderErrorOr<PageHeaderReadResult> read_header_at(size_t position, FixedArray<u8>* segment_sizes);
+
+ NonnullRefPtr<MediaStreamCursor> m_cursor;
+ size_t m_position { 0 };
+};
+
+class MEDIA_API PacketAssembler {
+public:
+ // The packets that complete on the page. A packet continued from a page that was not given is dropped.
+ DecoderErrorOr<Vector<FixedArray<u8>>> take_completed_packets(Page const&);
+ void reset();
+
+private:
+ Optional<ByteBuffer> m_partial_packet;
+ Optional<u32> m_expected_sequence_number;
+};
+
+struct StreamIdentification {
+ CodecID codec_id { CodecID::Unknown };
+ TrackType type { TrackType::Audio };
+ // Including the identification packet. Zero when the headers last until the first packet that is not one.
+ u32 header_packet_count { 0 };
+
+ u32 sample_rate { 0 };
+ u8 channel_count { 0 };
+ u16 opus_pre_skip { 0 };
+
+ u32 pixel_width { 0 };
+ u32 pixel_height { 0 };
+ u32 frame_rate_numerator { 0 };
+ u32 frame_rate_denominator { 0 };
+ u8 theora_keyframe_granule_shift { 0 };
+ bool theora_granule_counts_frames_from_one { false };
+
+ Track create_track(size_t identifier) const;
+
+ i64 end_units_of_granule_position(i64 granule_position) const;
+ i64 theora_keyframe_start_units(i64 granule_position) const;
+ AK::Duration time_of_units(i64 units) const;
+ i64 units_of_time(AK::Duration) const;
+};
+
+// Empty when the codec is not one we read.
+MEDIA_API DecoderErrorOr<Optional<StreamIdentification>> identify_stream(ReadonlyBytes first_packet);
+MEDIA_API bool is_header_packet(StreamIdentification const&, ReadonlyBytes packet);
+MEDIA_API DecoderErrorOr<FixedArray<u8>> build_codec_initialization_data(StreamIdentification const&, Vector<FixedArray<u8>> const& header_packets);
+MEDIA_API bool is_theora_keyframe(ReadonlyBytes packet);
+
+}
diff --git a/Libraries/LibMedia/Containers/OggNavigator.cpp b/Libraries/LibMedia/Containers/OggNavigator.cpp
deleted file mode 100644
index d43d011daa8..00000000000
--- a/Libraries/LibMedia/Containers/OggNavigator.cpp
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "OggNavigator.h"
-
-#include <AK/BitCast.h>
-#include <AK/Math.h>
-#include <LibMedia/Codecs/Opus.h>
-#include <LibMedia/ReadonlyBytesCursor.h>
-
-namespace Media {
-
-static constexpr StringView CAPTURE_PATTERN = "OggS"sv;
-static constexpr size_t CAPTURE_PATTERN_SIZE = CAPTURE_PATTERN.length();
-static constexpr size_t PAGE_HEADER_SIZE = 27;
-static constexpr size_t CHUNK_SIZE = 4096;
-
-static constexpr u8 CONTINUED_PACKET_FLAG = 1 << 0;
-static constexpr i64 UNSET_GRANULE_POSITION = -1;
-
-OggNavigator::OggNavigator(NonnullRefPtr<MediaStreamCursor> cursor, CodecData codec_data)
- : m_cursor(move(cursor))
- , m_codec_data(move(codec_data))
-{
-}
-
-OwnPtr<OggNavigator> OggNavigator::create(ReadonlyBytes first_packet, NonnullRefPtr<MediaStreamCursor> cursor, CodecID codec_id, u32 time_base_numerator, u32 time_base_denominator, u32 sample_rate, ReadonlyBytes codec_initialization_data)
-{
- VERIFY(time_base_numerator > 0);
- VERIFY(time_base_denominator > 0);
-
- switch (codec_id) {
- case CodecID::Opus:
- return adopt_own(*new (nothrow) OggNavigator(move(cursor), Opus { time_base_numerator, time_base_denominator }));
- case CodecID::FLAC: {
- if (sample_rate == 0 || first_packet.size() < 2)
- return {};
-
- u16 sync_code = (static_cast<u16>(first_packet[0]) << 8) | first_packet[1];
- if (!Codecs::FLAC::is_sync_code(sync_code))
- return {};
-
- auto frame_cursor = make_ref_counted<ReadonlyBytesCursor>(first_packet);
- auto frame_info = Codecs::FLAC::parse_frame_header(frame_cursor, sync_code, 0);
- if (frame_info.is_error() || !frame_info.value().has_value())
- return {};
-
- u16 fixed_block_size = 0;
- if ((sync_code & 1) == 0)
- fixed_block_size = frame_info.value()->block_size;
-
- return adopt_own(*new (nothrow) OggNavigator(move(cursor), FLAC { sync_code, fixed_block_size, sample_rate }));
- }
- case CodecID::Vorbis: {
- if (sample_rate == 0)
- return {};
- if (codec_initialization_data.is_empty())
- return {};
-
- auto parser = Codecs::Vorbis::Parser::create(codec_initialization_data);
- if (!parser.has_value())
- return {};
-
- return adopt_own(*new (nothrow) OggNavigator(move(cursor), Vorbis { parser.release_value(), sample_rate }));
- }
- default:
- return {};
- }
-}
-
-AK::Duration OggNavigator::granule_to_time(i64 granule_position) const
-{
- return m_codec_data.visit(
- [&](Opus const& codec) {
- return AK::Duration::from_time_units(max<i64>(0, granule_position), codec.time_base_numerator, codec.time_base_denominator);
- },
- [&](FLAC const& codec) {
- return AK::Duration::from_time_units(max<i64>(0, granule_position), 1, codec.sample_rate);
- },
- [&](Vorbis const& codec) {
- return AK::Duration::from_time_units(max<i64>(0, granule_position), 1, codec.sample_rate);
- });
-}
-
-void OggNavigator::reset_packet_parser_state() const
-{
- m_codec_data.visit(
- [](Opus const&) { },
- [](FLAC const&) { },
- [](Vorbis const& codec) {
- codec.parser.reset();
- });
-}
-
-static bool is_capture_pattern(ReadonlyBytes bytes)
-{
- return bytes.starts_with(CAPTURE_PATTERN.bytes());
-}
-
-static bool append_bytes(ByteBuffer& buffer, ReadonlyBytes bytes)
-{
- auto original_size = buffer.size();
- if (buffer.try_resize(original_size + bytes.size()).is_error())
- return false;
- bytes.copy_to(buffer.span().slice(original_size));
- return true;
-}
-
-static bool verify_page_crc(ReadonlyBytes page)
-{
- constexpr size_t checksum_start = 22;
- constexpr size_t checksum_end = checksum_start + 4;
- VERIFY(page.size() >= checksum_end);
-
- auto expected_crc = static_cast<u32>(page[checksum_start])
- | (static_cast<u32>(page[checksum_start + 1]) << 8)
- | (static_cast<u32>(page[checksum_start + 2]) << 16)
- | (static_cast<u32>(page[checksum_start + 3]) << 24);
-
- constexpr auto lookup_table = [] {
- Array<u32, 256> result;
- for (size_t i = 0; i < result.size(); i++) {
- u32 value = i << 24;
- for (auto bit = 0; bit < 8; bit++)
- value = (value << 1) ^ (value & 0x80000000 ? 0x04C11DB7 : 0);
- result[i] = value;
- }
- return result;
- }();
-
- u32 actual_crc = 0;
- for (size_t i = 0; i < page.size(); i++) {
- u8 byte = 0;
- if (i < checksum_start || i >= checksum_end)
- byte = page[i];
- actual_crc = (actual_crc << 8) ^ lookup_table[((actual_crc >> 24) & 0xFF) ^ byte];
- }
-
- return expected_crc == actual_crc;
-}
-
-Optional<u64> OggNavigator::read_packet_duration_in_granules(ReadonlyBytes packet) const
-{
- auto packet_cursor = make_ref_counted<ReadonlyBytesCursor>(packet);
- return m_codec_data.visit(
- [&](Opus const&) -> Optional<u64> {
- auto parsed_duration = Codecs::Opus::parse_frame_duration_in_samples(packet_cursor, packet.size());
- if (parsed_duration.is_error())
- return {};
- return parsed_duration.release_value();
- },
- [&](FLAC const& codec) -> Optional<u64> {
- auto frame = Codecs::FLAC::parse_frame_header(packet_cursor, codec.sync_code, codec.fixed_block_size);
- if (frame.is_error() || !frame.value().has_value())
- return {};
- return frame.value()->block_size;
- },
- [&](Vorbis const& codec) -> Optional<u64> {
- auto packet_duration = codec.parser.parse_packet_duration_in_samples(packet);
- if (!packet_duration.has_value())
- return {};
- return packet_duration.value();
- });
-}
-
-Optional<OggNavigator::PageScanResult> OggNavigator::parse_page_at(size_t page_start, size_t search_end, ByteBuffer* continued_packet) const
-{
- if (page_start + PAGE_HEADER_SIZE > search_end)
- return {};
- if (m_cursor->seek_to_position(page_start).is_error())
- return {};
-
- auto resize_page_buffer = [&](size_t size) {
- m_page_buffer.ensure_capacity(size);
- m_page_buffer.set_size(size);
- };
-
- resize_page_buffer(PAGE_HEADER_SIZE);
- if (m_cursor->read_until_filled(m_page_buffer.span()).is_error())
- return {};
- if (!is_capture_pattern(m_page_buffer))
- return {};
- auto version = m_page_buffer[4];
- if (version != 0)
- return {};
- auto header_type_flag = m_page_buffer[5];
- bool begins_with_continued_packet = (header_type_flag & CONTINUED_PACKET_FLAG) != 0;
-
- u64 granule_position_bits { 0 };
- for (size_t i = 0; i < sizeof(granule_position_bits); i++)
- granule_position_bits |= static_cast<u64>(m_page_buffer[6 + i]) << (8 * i);
- auto granule_position = bit_cast<i64>(granule_position_bits);
-
- auto page_segments = m_page_buffer[26];
- if (page_start + PAGE_HEADER_SIZE + page_segments > search_end)
- return {};
-
- resize_page_buffer(PAGE_HEADER_SIZE + page_segments);
- auto segment_table = m_page_buffer.span().slice(PAGE_HEADER_SIZE);
- if (m_cursor->read_until_filled(segment_table).is_error())
- return {};
-
- size_t payload_size = 0;
- for (auto segment_size : segment_table)
- payload_size += segment_size;
- auto payload_start = page_start + PAGE_HEADER_SIZE + page_segments;
- auto payload_end = payload_start + payload_size;
- if (payload_end > search_end)
- return {};
-
- auto page_size = PAGE_HEADER_SIZE + page_segments + payload_size;
- resize_page_buffer(page_size);
- segment_table = m_page_buffer.span().slice(PAGE_HEADER_SIZE, page_segments);
- auto payload = m_page_buffer.span().slice(PAGE_HEADER_SIZE + page_segments);
- if (m_cursor->read_until_filled(payload).is_error())
- return {};
- if (!verify_page_crc(m_page_buffer))
- return {};
-
- u64 parsed_packet_duration_in_granules { 0 };
- size_t packet_size = 0;
- size_t packet_start = 0;
- bool packet_started_before_page = begins_with_continued_packet;
- for (auto segment_size : segment_table) {
- packet_size += segment_size;
- if (segment_size == 255)
- continue;
-
- auto packet = payload.slice(packet_start, packet_size);
-
- if (packet_started_before_page) {
- if (continued_packet && !continued_packet->is_empty()) {
- if (!append_bytes(*continued_packet, packet))
- return {};
-
- auto packet_duration = read_packet_duration_in_granules(continued_packet->span());
- continued_packet->clear();
- if (!packet_duration.has_value())
- return {};
- parsed_packet_duration_in_granules += packet_duration.value();
- }
- packet_started_before_page = false;
- packet_start += packet_size;
- packet_size = 0;
- continue;
- }
-
- auto packet_duration = read_packet_duration_in_granules(packet);
- if (!packet_duration.has_value())
- return {};
- parsed_packet_duration_in_granules += packet_duration.value();
- packet_start += packet_size;
- packet_size = 0;
- }
-
- if (continued_packet && packet_size > 0 && (!packet_started_before_page || !continued_packet->is_empty())) {
- if (!append_bytes(*continued_packet, payload.slice(packet_start, packet_size)))
- return {};
- }
-
- if (granule_position == UNSET_GRANULE_POSITION)
- return PageScanResult { {}, parsed_packet_duration_in_granules, page_start, payload_end };
-
- return PageScanResult { granule_position, parsed_packet_duration_in_granules, page_start, payload_end };
-}
-
-Optional<AK::Duration> OggNavigator::find_start_timestamp(size_t search_start, size_t search_end) const
-{
- VERIFY(search_start <= search_end);
-
- Array<u8, CHUNK_SIZE> chunk;
- auto chunk_start = search_start;
-
- while (chunk_start + CAPTURE_PATTERN_SIZE <= search_end) {
- auto chunk_size = min(chunk.size(), search_end - chunk_start);
- if (m_cursor->seek_to_position(chunk_start).is_error())
- return {};
- auto read_result = m_cursor->read_into(chunk.span().trim(chunk_size));
- if (read_result.is_error())
- return {};
- auto bytes_read = read_result.value();
- if (bytes_read < CAPTURE_PATTERN_SIZE)
- return {};
-
- for (size_t i = 0; i + CAPTURE_PATTERN_SIZE <= bytes_read; i++) {
- if (!is_capture_pattern(chunk.span().slice(i)))
- continue;
- reset_packet_parser_state();
- auto page = parse_page_at(chunk_start + i, search_end);
- if (!page.has_value())
- continue;
- if (!page->granule_position.has_value())
- continue;
- auto parsed_packet_duration_in_granules = static_cast<i64>(page->parsed_packet_duration_in_granules);
- if (page->granule_position.value() <= parsed_packet_duration_in_granules)
- return AK::Duration::zero();
- return granule_to_time(page->granule_position.value() - parsed_packet_duration_in_granules);
- }
-
- chunk_start += bytes_read - (CAPTURE_PATTERN_SIZE - 1);
- }
-
- return {};
-}
-
-Optional<OggNavigator::PageScanResult> OggNavigator::find_last_page_with_valid_granule_position(size_t search_start, size_t search_end) const
-{
- VERIFY(search_start <= search_end);
-
- auto chunk_end = search_end;
- Array<u8, CHUNK_SIZE> chunk;
- while (chunk_end >= search_start + CAPTURE_PATTERN_SIZE) {
- auto chunk_start = chunk_end > chunk.size() ? chunk_end - chunk.size() : 0;
- chunk_start = max(chunk_start, search_start);
- auto chunk_size = chunk_end - chunk_start;
-
- if (m_cursor->seek_to_position(chunk_start).is_error())
- return {};
- if (m_cursor->read_until_filled(chunk.span().trim(chunk_size)).is_error())
- return {};
-
- for (size_t i = chunk_size - CAPTURE_PATTERN_SIZE + 1; i-- > 0;) {
- if (!is_capture_pattern(chunk.span().slice(i)))
- continue;
- reset_packet_parser_state();
- auto page = parse_page_at(chunk_start + i, search_end);
- if (page.has_value() && page->granule_position.has_value())
- return page;
- }
-
- if (chunk_start == search_start)
- break;
- chunk_end = chunk_start + CAPTURE_PATTERN_SIZE - 1;
- }
-
- return {};
-}
-
-Optional<AK::Duration> OggNavigator::find_end_timestamp(size_t search_start, size_t search_end) const
-{
- auto last_complete_page = find_last_page_with_valid_granule_position(search_start, search_end);
- if (!last_complete_page.has_value())
- return {};
-
- ByteBuffer continued_packet;
- reset_packet_parser_state();
- auto page = parse_page_at(last_complete_page->byte_start, search_end, &continued_packet);
- if (!page.has_value() || !page->granule_position.has_value())
- return granule_to_time(last_complete_page->granule_position.value());
-
- auto end_granule_position = page->granule_position.value();
- auto page_start = page->byte_end;
- while (page_start + CAPTURE_PATTERN_SIZE <= search_end) {
- page = parse_page_at(page_start, search_end, &continued_packet);
- if (!page.has_value())
- break;
- if (page->granule_position.has_value())
- end_granule_position = page->granule_position.value();
- else
- end_granule_position += static_cast<i64>(page->parsed_packet_duration_in_granules);
- if (page->byte_end >= search_end)
- break;
- page_start = page->byte_end;
- }
-
- return granule_to_time(end_granule_position);
-}
-
-void OggNavigator::on_cached_range_changed(OggCachedRange& cached, CachedRangeChange change) const
-{
- bool rescan_start = has_flag(change, CachedRangeChange::Start);
- bool rescan_end = has_flag(change, CachedRangeChange::End);
-
- if (rescan_start && !cached.time_end.has_value())
- rescan_end = true;
- if (rescan_end && !cached.time_start.has_value())
- rescan_start = true;
-
- if (rescan_start)
- cached.time_start = find_start_timestamp(cached.byte_start, cached.byte_end);
- if (rescan_end)
- cached.time_end = find_end_timestamp(cached.byte_start, cached.byte_end);
-}
-
-void OggNavigator::append_time_range(OggCachedRange const& cached_range, TimeRanges& to)
-{
- if (!cached_range.time_start.has_value() || !cached_range.time_end.has_value())
- return;
-
- auto time_start = max(cached_range.time_start.value(), AK::Duration::zero());
- auto time_end = cached_range.time_end.value();
- if (time_start >= time_end)
- return;
-
- to.add_range(time_start, time_end);
-}
-
-}
diff --git a/Libraries/LibMedia/Containers/OggNavigator.h b/Libraries/LibMedia/Containers/OggNavigator.h
deleted file mode 100644
index 5386c429d80..00000000000
--- a/Libraries/LibMedia/Containers/OggNavigator.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/OwnPtr.h>
-#include <AK/Variant.h>
-#include <LibMedia/Codecs/FLAC.h>
-#include <LibMedia/Codecs/Vorbis.h>
-#include <LibMediaCodecs/CodecID.h>
-
-#include "ScanningContainerNavigator.h"
-
-namespace Media {
-
-struct OggCachedRange : CachedByteRange {
- using CachedByteRange::CachedByteRange;
-
- Optional<AK::Duration> time_start;
- Optional<AK::Duration> time_end;
-};
-
-class OggNavigator final : public ScanningContainerNavigator<OggNavigator, OggCachedRange> {
-public:
- static OwnPtr<OggNavigator> create(ReadonlyBytes first_packet, NonnullRefPtr<MediaStreamCursor>, CodecID, u32 time_base_numerator, u32 time_base_denominator, u32 sample_rate, ReadonlyBytes codec_initialization_data);
-
- void on_cached_range_changed(OggCachedRange& cached_range, CachedRangeChange change) const;
- static void append_time_range(OggCachedRange const& cached_range, TimeRanges& to);
-
-private:
- struct Opus {
- u32 time_base_numerator { 1 };
- u32 time_base_denominator { 1 };
- };
-
- struct FLAC {
- u16 sync_code { 0 };
- u16 fixed_block_size { 0 };
- u32 sample_rate { 1 };
- };
-
- struct Vorbis {
- Codecs::Vorbis::Parser parser;
- u32 sample_rate { 1 };
- };
-
- using CodecData = Variant<Opus, FLAC, Vorbis>;
-
- struct PageScanResult {
- Optional<i64> granule_position;
- u64 parsed_packet_duration_in_granules;
- size_t byte_start;
- size_t byte_end;
- };
-
- OggNavigator(NonnullRefPtr<MediaStreamCursor>, CodecData);
-
- Optional<AK::Duration> find_start_timestamp(size_t search_start, size_t search_end) const;
- Optional<PageScanResult> find_last_page_with_valid_granule_position(size_t search_start, size_t search_end) const;
- Optional<AK::Duration> find_end_timestamp(size_t search_start, size_t search_end) const;
- Optional<PageScanResult> parse_page_at(size_t page_start, size_t search_end, ByteBuffer* continued_packet = nullptr) const;
- Optional<u64> read_packet_duration_in_granules(ReadonlyBytes) const;
- void reset_packet_parser_state() const;
-
- AK::Duration granule_to_time(i64 granule_position) const;
-
- NonnullRefPtr<MediaStreamCursor> m_cursor;
- CodecData m_codec_data;
- mutable ByteBuffer m_page_buffer;
-};
-
-}
diff --git a/Libraries/LibMedia/Containers/ScanningContainerNavigator.h b/Libraries/LibMedia/Containers/ScanningContainerNavigator.h
deleted file mode 100644
index df386dc51d6..00000000000
--- a/Libraries/LibMedia/Containers/ScanningContainerNavigator.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include "CachedByteRanges.h"
-#include "ContainerNavigator.h"
-
-namespace Media {
-
-template<typename Derived, typename CachedRange = CachedByteRange>
-class ScanningContainerNavigator : public SingleTrackContainerNavigator {
-public:
- BufferedRangesScan buffered_time_ranges(Vector<MediaStream::ByteRange> const& byte_ranges) const override
- {
- auto const& self = *static_cast<Derived const*>(this);
- m_cached_ranges.update(byte_ranges, [&](CachedRange& range, CachedRangeChange change) {
- self.on_cached_range_changed(range, change);
- });
-
- BufferedRangesScan scan;
- auto const& cached_ranges = m_cached_ranges.ranges();
- if (cached_ranges.is_empty())
- return scan;
-
- for (size_t i = 0; i + 1 < cached_ranges.size(); i++)
- self.append_time_range(cached_ranges[i], scan.time_ranges);
-
- TimeRanges last_byte_range_time_ranges;
- self.append_time_range(cached_ranges.last(), last_byte_range_time_ranges);
- scan.last_byte_range_has_samples = !last_byte_range_time_ranges.is_empty();
- for (auto const& range : last_byte_range_time_ranges)
- scan.time_ranges.add_range(range.start, range.end);
-
- return scan;
- }
-
-protected:
- mutable CachedByteRanges<CachedRange> m_cached_ranges;
-};
-
-}
diff --git a/Libraries/LibMedia/DemuxerRegistry.cpp b/Libraries/LibMedia/DemuxerRegistry.cpp
index 2445f6fb69a..f43f779b12a 100644
--- a/Libraries/LibMedia/DemuxerRegistry.cpp
+++ b/Libraries/LibMedia/DemuxerRegistry.cpp
@@ -10,9 +10,9 @@
#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>
#include <LibMedia/Containers/MP3/MP3Demuxer.h>
#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
+#include <LibMedia/Containers/Ogg/OggDemuxer.h>
#include <LibMedia/Containers/WAV/WAVDemuxer.h>
#include <LibMedia/DemuxerRegistry.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
#include <LibMedia/MediaStream.h>
namespace Media {
@@ -32,7 +32,7 @@ static constexpr Array demuxers_in_priority_order {
DemuxerRegistration { Matroska::MatroskaDemuxer::from_stream, Matroska::MatroskaDemuxer::supports_container_mime_type, Matroska::MatroskaDemuxer::supports_codec_in_container },
DemuxerRegistration { WAV::WAVDemuxer::from_stream, WAV::WAVDemuxer::supports_container_mime_type, WAV::WAVDemuxer::supports_codec_in_container },
DemuxerRegistration { FLAC::FLACDemuxer::from_stream, FLAC::FLACDemuxer::supports_container_mime_type, FLAC::FLACDemuxer::supports_codec_in_container },
- DemuxerRegistration { FFmpeg::FFmpegDemuxer::from_stream, FFmpeg::FFmpegDemuxer::supports_container_mime_type, FFmpeg::FFmpegDemuxer::supports_codec_in_container },
+ DemuxerRegistration { Ogg::OggDemuxer::from_stream, Ogg::OggDemuxer::supports_container_mime_type, Ogg::OggDemuxer::supports_codec_in_container },
DemuxerRegistration { MP3::MP3Demuxer::from_stream, MP3::MP3Demuxer::supports_container_mime_type, MP3::MP3Demuxer::supports_codec_in_container },
DemuxerRegistration { ADTS::ADTSDemuxer::from_stream, ADTS::ADTSDemuxer::supports_container_mime_type, ADTS::ADTSDemuxer::supports_codec_in_container },
};
diff --git a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp b/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
deleted file mode 100644
index 31b837e6c31..00000000000
--- a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
+++ /dev/null
@@ -1,677 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Gregory Bertilson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/AnyOf.h>
-#include <AK/Array.h>
-#include <AK/GenericShorthands.h>
-#include <AK/Math.h>
-#include <AK/MemoryStream.h>
-#include <AK/NeverDestroyed.h>
-#include <AK/QuickSort.h>
-#include <AK/Stream.h>
-#include <AK/StringBuilder.h>
-#include <AK/Time.h>
-#include <LibMedia/Containers/IndexedContainerNavigator.h>
-#include <LibMedia/Containers/OggNavigator.h>
-#include <LibMedia/FFmpeg/FFmpegChannelLayout.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
-#include <LibMedia/MediaStream.h>
-#include <LibMedia/SeekMode.h>
-#include <LibMediaCodecs/Codecs/AAC.h>
-#include <LibMediaCodecs/FFmpeg/FFmpegHelpers.h>
-
-extern "C" {
-#include <libavformat/avformat.h>
-}
-
-namespace Media::FFmpeg {
-
-bool FFmpegDemuxer::supports_container_mime_type(ContainerMimeType mime_type)
-{
- switch (mime_type.container_id) {
- case ContainerID::Ogg:
- return true;
- case ContainerID::ISOBMFF:
- return mime_type.media_type != ContainerMediaType::Application;
- case ContainerID::Matroska:
- case ContainerID::WebM:
- case ContainerID::ADTS:
- case ContainerID::MPEGAudio:
- case ContainerID::WAV:
- case ContainerID::FLAC:
- return false;
- }
- VERIFY_NOT_REACHED();
-}
-
-bool FFmpegDemuxer::supports_codec_in_container(ContainerID container_id, CodecID codec_id)
-{
- switch (container_id) {
- case ContainerID::ISOBMFF:
- return first_is_one_of(codec_id, CodecID::VP8, CodecID::VP9, CodecID::H264, CodecID::H265, CodecID::MP3, CodecID::AAC, CodecID::AV1, CodecID::Opus, CodecID::FLAC);
- case ContainerID::Ogg:
- return first_is_one_of(codec_id, CodecID::Theora, CodecID::Vorbis, CodecID::Opus, CodecID::FLAC);
- case ContainerID::ADTS:
- case ContainerID::Matroska:
- case ContainerID::WebM:
- case ContainerID::MPEGAudio:
- case ContainerID::WAV:
- case ContainerID::FLAC:
- return false;
- }
- VERIFY_NOT_REACHED();
-}
-
-static ByteString create_codec_whitelist()
-{
- static constexpr Array codec_ids {
- CodecID::VP8,
- CodecID::VP9,
- CodecID::H264,
- CodecID::H265,
- CodecID::MP3,
- CodecID::AAC,
- CodecID::AV1,
- CodecID::Theora,
- CodecID::Vorbis,
- CodecID::Opus,
- CodecID::FLAC,
- CodecID::U8,
- CodecID::S16LE,
- CodecID::S24LE,
- CodecID::S32LE,
- CodecID::F32LE,
- CodecID::ALaw,
- CodecID::MuLaw,
- };
-
- StringBuilder whitelist;
- void* iterator = nullptr;
- while (auto const* decoder = av_codec_iterate(&iterator)) {
- if (!av_codec_is_decoder(decoder))
- continue;
- if (!any_of(codec_ids, [&](auto codec_id) { return decoder->id == ffmpeg_codec_id_from_media_codec_id(codec_id); }))
- continue;
- if (!whitelist.is_empty())
- whitelist.append(',');
- whitelist.append(StringView(decoder->name, strlen(decoder->name)));
- }
- return MUST(whitelist.to_string()).to_byte_string();
-}
-
-static ByteString const& codec_whitelist()
-{
- static NeverDestroyed<ByteString> whitelist { create_codec_whitelist() };
- return *whitelist;
-}
-
-FFmpegDemuxer::FFmpegDemuxer(NonnullRefPtr<MediaStream> const& stream)
- : m_stream(stream)
-{
-}
-
-FFmpegDemuxer::~FFmpegDemuxer()
-{
- for (auto& [track, context] : m_track_contexts) {
- if (context->format_context != nullptr)
- avformat_close_input(&context->format_context);
- }
-
- if (m_buffered_scan_thread != nullptr)
- m_buffered_scan_thread->shutdown();
-}
-
-static DecoderErrorOr<void> initialize_format_context(AVFormatContext*& format_context, AVIOContext& io_context)
-{
- format_context = avformat_alloc_context();
- if (format_context == nullptr)
- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate format context"sv);
- format_context->pb = &io_context;
- format_context->flags |= AVFMT_FLAG_CUSTOM_IO;
- format_context->flags |= AVFMT_FLAG_DISCARD_CORRUPT;
- format_context->flags |= AVFMT_FLAG_FAST_SEEK;
-
- ArmedScopeGuard close_input = [&] {
- avformat_close_input(&format_context);
- };
-
- AVDictionary* options = nullptr;
- ScopeGuard free_options = [&] { av_dict_free(&options); };
-
- if (av_dict_set(&options, "format_whitelist", "ogg", 0) < 0)
- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg format whitelist"sv);
-
- auto const& codecs = codec_whitelist();
- if (av_dict_set(&options, "codec_whitelist", codecs.characters(), 0) < 0)
- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg codec whitelist"sv);
-
- // The smallest probe FFmpeg allows, so a format it was built without fails here instead of a mebibyte in.
- av_dict_set(&options, "formatprobesize", "2048", 0);
-
- auto open_result = avformat_open_input(&format_context, nullptr, nullptr, &options);
- if (open_result < 0)
- return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Failed to open input for format parsing"sv);
-
- // Read stream info; doing this is required for headerless formats like MPEG
- if (avformat_find_stream_info(format_context, nullptr) < 0)
- return DecoderError::with_description(DecoderErrorCategory::Corrupted, "Failed to find stream info"sv);
-
- close_input.disarm();
- return {};
-}
-
-static DecoderErrorOr<Track> create_track_from_stream(AVStream const& stream, StringView format_name, HashTable<TrackType>& seen_types)
-{
- auto type = track_type_from_ffmpeg_media_type(stream.codecpar->codec_type);
- auto get_string_metadata = [&](char const* key) {
- auto* name_entry = av_dict_get(stream.metadata, key, nullptr, 0);
- if (name_entry == nullptr)
- return Utf16String();
- return Utf16String::from_utf8(StringView(name_entry->value, strlen(name_entry->value)));
- };
-
- // https://dev.w3.org/html5/html-sourcing-inband-tracks/
- auto kind = [&] {
- auto is_first_of_type = seen_types.set(type) == HashSetResult::InsertedNewEntry;
- if (format_name.starts_with("mov"sv)) {
- // https://dev.w3.org/html5/html-sourcing-inband-tracks/#mpeg4avta
- // "main": first audio (video) track
- if (is_first_of_type)
- return Track::Kind::Main;
- // "translation": not first audio (video) track
- return Track::Kind::Translation;
- }
-
- // AD-HOC: For container formats not covered by the spec, default to "main".
- return Track::Kind::Main;
- }();
-
- auto name = get_string_metadata("title");
- auto language = get_string_metadata("language");
- Track track(type, stream.index, kind, name, language);
-
- if (type == TrackType::Video) {
- auto color_primaries = static_cast<ColorPrimaries>(stream.codecpar->color_primaries);
- auto transfer_characteristics = static_cast<TransferCharacteristics>(stream.codecpar->color_trc);
- auto matrix_coefficients = static_cast<MatrixCoefficients>(stream.codecpar->color_space);
- auto color_range = [&stream] {
- switch (stream.codecpar->color_range) {
- case AVColorRange::AVCOL_RANGE_MPEG:
- return VideoFullRangeFlag::Studio;
- case AVColorRange::AVCOL_RANGE_JPEG:
- return VideoFullRangeFlag::Full;
- default:
- return VideoFullRangeFlag::Unspecified;
- }
- }();
-
- track.set_video_data({
- .pixel_width = static_cast<u64>(stream.codecpar->width),
- .pixel_height = static_cast<u64>(stream.codecpar->height),
- .cicp = CodingIndependentCodePoints(color_primaries, transfer_characteristics, matrix_coefficients, color_range),
- });
- } else if (type == TrackType::Audio) {
- auto channel_map = Audio::ChannelMap::invalid();
-
- auto& channel_layout = stream.codecpar->ch_layout;
- if (channel_layout.nb_channels != 0) {
- auto channel_map_result = av_channel_layout_to_channel_map(FFmpegFunctions::bundled(), channel_layout);
- if (channel_map_result.is_error())
- return DecoderError::with_description(DecoderErrorCategory::Invalid, channel_map_result.error().string_literal());
- channel_map = channel_map_result.release_value();
- }
-
- auto sample_specification = Audio::SampleSpecification(stream.codecpar->sample_rate, channel_map);
-
- track.set_audio_data({
- .sample_specification = sample_specification,
- });
- }
-
- return track;
-}
-
-static DecoderErrorOr<ByteBuffer> synthesize_aac_configuration_record(AVStream const& stream)
-{
- auto channel_count = stream.codecpar->ch_layout.nb_channels;
- if (stream.codecpar->sample_rate <= 0 || channel_count <= 0 || channel_count > NumericLimits<u8>::max())
- return DecoderError::with_description(DecoderErrorCategory::Invalid, "An AAC track states no usable sample rate and channel count"sv);
-
- auto declared_sample_rate = static_cast<u32>(stream.codecpar->sample_rate);
-
- // Each frame encodes 1024 frames at the core sample rate, but AAC-HE can double that before output. Check the
- // time base to see whether it appears to match that core sample rate, and set the SBR rate to the doubled rate.
- auto core_sample_rate = declared_sample_rate;
- Optional<u32> spectral_band_replication_sample_rate;
- if (stream.time_base.num == 1 && stream.time_base.den > 0 && static_cast<u32>(stream.time_base.den) * 2 == declared_sample_rate) {
- core_sample_rate = static_cast<u32>(stream.time_base.den);
- spectral_band_replication_sample_rate = declared_sample_rate;
- }
-
- auto record = TRY(Codecs::AAC::create_configuration_record(Codecs::AAC::LOW_COMPLEXITY_AUDIO_OBJECT_TYPE, core_sample_rate, static_cast<u8>(channel_count), spectral_band_replication_sample_rate));
- return DECODER_TRY_ALLOC(ByteBuffer::copy(record.span()));
-}
-
-DecoderErrorOr<NonnullRefPtr<Demuxer>> FFmpegDemuxer::from_stream(NonnullRefPtr<MediaStream> const& stream)
-{
- auto io_context = DECODER_TRY_ALLOC(Media::FFmpeg::FFmpegIOContext::create(stream->create_cursor()));
-
- AVFormatContext* format_context = nullptr;
- TRY(initialize_format_context(format_context, *io_context->avio_context()));
- ScopeGuard close_input = [&] {
- avformat_close_input(&format_context);
- };
-
- auto demuxer = DECODER_TRY_ALLOC(adopt_nonnull_ref_or_enomem(new (nothrow) FFmpegDemuxer(stream)));
- demuxer->m_total_duration = AK::Duration::from_time_units(format_context->duration, 1, AV_TIME_BASE);
- if (format_context->start_time_realtime != AV_NOPTS_VALUE)
- demuxer->m_start_time_realtime = AK::UnixDateTime::from_microseconds_since_epoch(format_context->start_time_realtime);
-
- auto format_name = StringView(format_context->iformat->name, strlen(format_context->iformat->name));
- auto seen_types = HashTable<TrackType>();
-
- for (u32 i = 0; i < format_context->nb_streams; i++) {
- auto& stream = *format_context->streams[i];
-
- auto track = TRY(create_track_from_stream(stream, format_name, seen_types));
- auto codec_id = media_codec_id_from_ffmpeg_codec_id(stream.codecpar->codec_id);
- auto codec_initialization_data = DECODER_TRY_ALLOC(ByteBuffer::copy(stream.codecpar->extradata, stream.codecpar->extradata_size));
- if (codec_id == CodecID::AAC && codec_initialization_data.is_empty()) {
- auto synthesized = synthesize_aac_configuration_record(stream);
- if (synthesized.is_error())
- dbgln("FFmpegDemuxer: Could not describe an AAC track that carries no configuration: {}", synthesized.error().description());
- else
- codec_initialization_data = synthesized.release_value();
- }
-
- AK::Duration duration;
- if (stream.duration >= 0)
- duration = AK::Duration::from_time_units(stream.duration, stream.time_base.num, stream.time_base.den);
- else
- duration = demuxer->m_total_duration;
-
- DECODER_TRY_ALLOC(demuxer->m_stream_info.try_empend(StreamInfo {
- .track = move(track),
- .codec_id = codec_id,
- .codec_initialization_data = move(codec_initialization_data),
- .duration = duration,
- .time_base_numerator = stream.time_base.num,
- .time_base_denominator = stream.time_base.den,
- }));
- }
-
- demuxer->m_preferred_track_for_type.fill(-1);
- for (u32 i = 0; i < format_context->nb_streams; i++) {
- auto& stream = *format_context->streams[i];
- auto type = track_type_from_ffmpeg_media_type(stream.codecpar->codec_type);
- auto type_index = to_underlying(type);
- if (type_index >= demuxer->m_preferred_track_for_type.size())
- continue;
- if (demuxer->m_preferred_track_for_type[type_index] >= 0)
- continue;
- if (stream.disposition & AV_DISPOSITION_DEFAULT)
- demuxer->m_preferred_track_for_type[type_index] = static_cast<int>(i);
- }
-
- demuxer->start_buffered_scan_thread(*format_context);
-
- return demuxer;
-}
-
-static inline AK::Duration time_units_to_duration(i64 time_units, AVRational const& time_base)
-{
- VERIFY(time_base.num > 0);
- VERIFY(time_base.den > 0);
- return AK::Duration::from_time_units(time_units, time_base.num, time_base.den);
-}
-
-static AK::Duration frame_duration_from_frame_rate(AVRational const& frame_rate)
-{
- if (frame_rate.num <= 0 || frame_rate.den <= 0)
- return AK::Duration::zero();
- return AK::Duration::from_time_units(frame_rate.den, 1, frame_rate.num);
-}
-
-static inline i64 duration_to_time_units(AK::Duration duration, AVRational const& time_base)
-{
- VERIFY(time_base.num > 0);
- VERIFY(time_base.den > 0);
- return duration.to_time_units(time_base.num, time_base.den);
-}
-
-OwnPtr<ContainerNavigator> FFmpegDemuxer::create_single_track_container_navigator(AVFormatContext& context, NonnullRefPtr<MediaStream> const& stream)
-{
- auto format_name = StringView(context.iformat->name, strlen(context.iformat->name));
-
- if (format_name == "ogg"sv) {
- if (context.nb_streams != 1)
- return nullptr;
-
- auto& av_stream = *context.streams[0];
- if (av_stream.time_base.num <= 0 || av_stream.time_base.den <= 0)
- return nullptr;
-
- auto cursor = stream->create_cursor();
- cursor->set_is_blocking(false);
-
- auto codec_id = FFmpeg::media_codec_id_from_ffmpeg_codec_id(av_stream.codecpar->codec_id);
- ReadonlyBytes first_packet;
- AVPacket* packet = nullptr;
- ScopeGuard free_packet = [&] { av_packet_free(&packet); };
-
- if (codec_id == CodecID::FLAC) {
- if (av_stream.codecpar->sample_rate <= 0)
- return nullptr;
-
- packet = av_packet_alloc();
- VERIFY(packet);
- if (av_read_frame(&context, packet) >= 0 && packet->size >= 0)
- first_packet = { packet->data, static_cast<size_t>(packet->size) };
- }
-
- auto sample_rate = av_stream.codecpar->sample_rate > 0 ? static_cast<u32>(av_stream.codecpar->sample_rate) : 0;
- auto codec_initialization_data = ReadonlyBytes { av_stream.codecpar->extradata, static_cast<size_t>(av_stream.codecpar->extradata_size) };
- return OggNavigator::create(first_packet, move(cursor), codec_id, static_cast<u32>(av_stream.time_base.num), static_cast<u32>(av_stream.time_base.den), sample_rate, codec_initialization_data);
- }
-
- return nullptr;
-}
-
-void FFmpegDemuxer::start_buffered_scan_thread(AVFormatContext& context)
-{
- m_fallback_scan_state.duration = m_total_duration;
-
- if (m_stream_info.is_empty())
- return;
-
- OwnPtr<ContainerNavigator> navigator = create_single_track_container_navigator(context, m_stream);
- if (navigator == nullptr) {
- Vector<IndexedContainerNavigator::TrackIndex> track_indices;
- for (u32 i = 0; i < context.nb_streams; i++) {
- auto track_type = m_stream_info[i].track.type();
- if (track_type != TrackType::Audio && track_type != TrackType::Video)
- continue;
- auto* stream = context.streams[i];
- auto entry_count = avformat_index_get_entries_count(stream);
- Vector<IndexEntry> entries;
- MUST(entries.try_ensure_capacity(max(entry_count, 0)));
- for (int j = 0; j < entry_count; j++) {
- auto const* entry = avformat_index_get_entry(stream, j);
- entries.unchecked_append({
- .position = static_cast<size_t>(entry->pos),
- .timestamp = time_units_to_duration(entry->timestamp, stream->time_base),
- });
- }
-
- // Ensure monotonic ordering of both positions and timestamps.
- bool is_monotonic = true;
- for (size_t j = 1; j < entries.size(); j++) {
- if (entries[j - 1].position >= entries[j].position || entries[j - 1].timestamp > entries[j].timestamp) {
- is_monotonic = false;
- break;
- }
- }
- if (!is_monotonic)
- entries.clear();
-
- track_indices.empend(m_stream_info[i].track.identifier(), move(entries));
- }
- if (!track_indices.is_empty())
- navigator = make<IndexedContainerNavigator>(move(track_indices), m_total_duration);
- }
- if (navigator == nullptr)
- return;
-
- DemuxerScanState initial_state;
- initial_state.duration = m_total_duration;
- m_buffered_scan_thread = DemuxerScanThread<BufferedScanPayload>::start(m_stream, move(initial_state),
- BufferedScanPayload { navigator.release_nonnull(), m_total_duration },
- [](MediaStream::Availability const& availability, BufferedScanPayload& payload) {
- auto scans = payload.navigator->buffered_time_ranges_by_track(availability.byte_ranges);
- return DemuxerScanState::create_from_track_scans(move(scans), payload.initial_duration, availability.closing_bytes_are_available());
- });
-}
-
-DecoderErrorOr<void> FFmpegDemuxer::create_context_for_track(Track const& track)
-{
- auto cursor = m_stream->create_cursor();
- auto io_context = MUST(Media::FFmpeg::FFmpegIOContext::create(cursor));
-
- auto track_context = make<TrackContext>(move(cursor), move(io_context));
-
- // We've already initialized a format context, so the only way this can fail is OOM.
- MUST(initialize_format_context(track_context->format_context, *track_context->io_context->avio_context()));
-
- track_context->packet = av_packet_alloc();
- VERIFY(track_context->packet != nullptr);
-
- VERIFY(m_track_contexts.set(track, move(track_context)) == HashSetResult::InsertedNewEntry);
-
- return {};
-}
-
-FFmpegDemuxer::StreamInfo const& FFmpegDemuxer::get_track_info(Track const& track) const
-{
- return m_stream_info[track.identifier()];
-}
-
-FFmpegDemuxer::TrackContext& FFmpegDemuxer::get_track_context(Track const& track)
-{
- return *m_track_contexts.get(track).release_value();
-}
-
-DecoderErrorOr<AK::Duration> FFmpegDemuxer::total_duration()
-{
- return m_total_duration;
-}
-
-Optional<AK::UnixDateTime> FFmpegDemuxer::start_time_realtime() const
-{
- return m_start_time_realtime;
-}
-
-DemuxerScanState const& FFmpegDemuxer::scan_state() const
-{
- if (m_buffered_scan_thread == nullptr)
- return m_fallback_scan_state;
- return m_buffered_scan_thread->main_thread_state();
-}
-
-void FFmpegDemuxer::set_scan_state_change_handler(ScanStateChangeHandler handler)
-{
- if (m_buffered_scan_thread == nullptr)
- return;
- m_buffered_scan_thread->set_change_handler([handler = move(handler)] {
- if (handler)
- handler(TimeRanges {});
- });
-}
-
-DecoderErrorOr<AK::Duration> FFmpegDemuxer::duration_of_track(Track const& track)
-{
- auto const& track_info = get_track_info(track);
- return track_info.duration;
-}
-
-DecoderErrorOr<Vector<Track>> FFmpegDemuxer::get_tracks_for_type(TrackType type)
-{
- Vector<Track> tracks;
- for (auto const& info : m_stream_info) {
- if (info.track.type() == type)
- DECODER_TRY_ALLOC(tracks.try_append(info.track));
- }
- return tracks;
-}
-
-DecoderErrorOr<Optional<Track>> FFmpegDemuxer::get_preferred_track_for_type(TrackType type)
-{
- auto preferred_index = m_preferred_track_for_type[to_underlying(type)];
- if (preferred_index < 0)
- return OptionalNone();
-
- return m_stream_info[preferred_index].track;
-}
-
-AK::Duration FFmpegDemuxer::select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode)
-{
- // FIXME: We can do this using the index getter functions, but unfortunately FFmpeg's seek table is in
- // DTS -> byte position, so for files with reordered frames (H.264), seeking to a keyframe will often
- // result in the first frame back being at a later PTS than the seek target, so we would display a blank
- // frame. To avoid this being especially common, just always accurately seek.
- //
- // Note that we can end up showing a blank frame anyway by accurately seeking very close to a keyframe,
- // it's just much less likely to happen under normal usage.
- //
- // This FIXME can be dropped when MP4/MOV is demuxed separately from FFmpeg, and then inclusion of an
- // index scan here can be re-evaluated.
- return target;
-}
-
-DecoderErrorOr<DemuxerSeekResult> FFmpegDemuxer::seek_to_most_recent_keyframe(Track const& track, AK::Duration timestamp, DemuxerSeekOptions options)
-{
- auto& track_context = get_track_context(track);
- auto& format_context = *track_context.format_context;
-
- VERIFY(track.identifier() < format_context.nb_streams);
- auto& stream = *format_context.streams[track.identifier()];
- auto av_timestamp = duration_to_time_units(timestamp, stream.time_base);
-
- if (has_flag(options, DemuxerSeekOptions::NeedCodecConfiguration))
- track_context.needs_codec_configuration = true;
-
- auto seek_succeeded = false;
-
- // AVIOContext can skip calling through to the underlying seek callback if the new position lands in its buffer,
- // leaving us in EOF/error, so we need to clear these here.
- format_context.pb->eof_reached = 0;
- format_context.pb->error = 0;
-
- if (m_buffered_scan_thread != nullptr) {
- auto seek_result = TRY(m_buffered_scan_thread->payload().navigator->seek_to_timestamp(track.identifier(), timestamp));
- if (seek_result.has<SeekSkipped>()) {
- return DemuxerSeekResult::KeptCurrentPosition;
- }
- if (auto const* seeked = seek_result.get_pointer<SeekedPosition>()) {
- if (av_seek_frame(&format_context, stream.index, seeked->byte_position, AVSEEK_FLAG_BYTE) >= 0) {
- seek_succeeded = true;
- track_context.pending_timestamp_offset = seeked->timestamp;
- track_context.timestamp_offset = AK::Duration::zero();
- }
- }
- }
-
- if (!seek_succeeded) {
- track_context.pending_timestamp_offset.clear();
- track_context.timestamp_offset = AK::Duration::zero();
- }
-
- if (!seek_succeeded && track_context.is_seekable && av_seek_frame(&format_context, stream.index, av_timestamp, AVSEEK_FLAG_BACKWARD) >= 0)
- seek_succeeded = true;
- if (!seek_succeeded) {
- track_context.is_seekable = false;
- auto av_base_timestamp = duration_to_time_units(timestamp, AV_TIME_BASE_Q);
- if (av_seek_frame(&format_context, -1, av_base_timestamp, AVSEEK_FLAG_BACKWARD) < 0) {
- if (track_context.cursor->is_aborted())
- return DecoderError::format(DecoderErrorCategory::Aborted, "Seek aborted");
-
- return DecoderError::format(DecoderErrorCategory::Corrupted, "Failed to seek");
- }
- }
-
- return DemuxerSeekResult::MovedPosition;
-}
-
-DecoderErrorOr<CodedFrame> FFmpegDemuxer::get_next_sample_for_track(Track const& track)
-{
- auto& track_context = get_track_context(track);
- auto& format_context = *track_context.format_context;
- auto& packet = *track_context.packet;
-
- VERIFY(track.identifier() < format_context.nb_streams);
- auto& stream = *format_context.streams[track.identifier()];
-
- for (;;) {
- auto read_frame_error = av_read_frame(&format_context, &packet);
- if (read_frame_error < 0) {
- if (track_context.cursor->is_aborted())
- return DecoderError::format(DecoderErrorCategory::Aborted, "Read aborted");
-
- if (read_frame_error == AVERROR_EOF)
- return DecoderError::format(DecoderErrorCategory::EndOfStream, "End of stream");
-
- return DecoderError::with_description(DecoderErrorCategory::Corrupted, av_error_code_to_string(read_frame_error));
- }
- if (packet.stream_index != stream.index) {
- av_packet_unref(&packet);
- continue;
- }
- ScopeGuard clear_packet { [&] { av_packet_unref(&packet); } };
-
- auto packet_data = DECODER_TRY_ALLOC(FixedArray<u8>::create(ReadonlyBytes { packet.data, static_cast<size_t>(packet.size) }));
- Optional<FixedArray<u8>> new_codec_configuration;
- size_t new_extradata_size = 0;
- if (auto* new_extradata = av_packet_get_side_data(&packet, AV_PKT_DATA_NEW_EXTRADATA, &new_extradata_size); new_extradata && new_extradata_size > 0)
- new_codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(ReadonlyBytes { new_extradata, new_extradata_size }));
- if (!new_codec_configuration.has_value() && track_context.needs_codec_configuration)
- new_codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(get_track_info(track).codec_initialization_data.bytes()));
- track_context.needs_codec_configuration = false;
-
- if (track_context.pending_timestamp_offset.has_value() && packet.pts == 0)
- track_context.timestamp_offset = track_context.pending_timestamp_offset.release_value();
-
- auto flags = (packet.flags & AV_PKT_FLAG_KEY) != 0 ? FrameFlags::Keyframe : FrameFlags::None;
- auto duration = time_units_to_duration(packet.duration, stream.time_base);
- // FIXME: This is a hack to work around a bug in libavformat where the stts box of an MP4 track is ignored if
- // it also contains a ctts box. This should not be necessary when we move to our own MP4 demuxer.
- if (duration.is_zero() && track.type() == TrackType::Video)
- duration = frame_duration_from_frame_rate(av_guess_frame_rate(&format_context, &stream, nullptr));
-
- auto presentation_timestamp = track_context.timestamp_offset + time_units_to_duration(packet.pts, stream.time_base);
- auto decode_timestamp = presentation_timestamp;
- if (packet.dts != AV_NOPTS_VALUE)
- decode_timestamp = track_context.timestamp_offset + time_units_to_duration(packet.dts, stream.time_base);
-
- auto const& track_info = get_track_info(track);
-
- auto sample = CodedFrame(
- track_info.codec_id,
- presentation_timestamp,
- decode_timestamp,
- duration,
- flags,
- move(packet_data),
- move(new_codec_configuration));
-
- return sample;
- }
-}
-
-void FFmpegDemuxer::set_blocking_reads_aborted_for_track(Track const& track)
-{
- auto& track_context = get_track_context(track);
- track_context.cursor->abort();
-}
-
-void FFmpegDemuxer::reset_blocking_reads_aborted_for_track(Track const& track)
-{
- auto& track_context = get_track_context(track);
- track_context.cursor->reset_abort();
-}
-
-void FFmpegDemuxer::set_read_blocked_change_handler_for_track(Track const& track, ReadBlockedChangeHandler handler)
-{
- auto& track_context = get_track_context(track);
- track_context.cursor->set_blocked_change_handler(move(handler));
-}
-
-FFmpegDemuxer::TrackContext::~TrackContext()
-{
- av_packet_free(&packet);
- avformat_free_context(format_context);
-}
-
-}
diff --git a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.h b/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.h
deleted file mode 100644
index 0394af8a260..00000000000
--- a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Gregory Bertilson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <AK/Forward.h>
-#include <AK/HashMap.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/OwnPtr.h>
-#include <LibMedia/ContainerID.h>
-#include <LibMedia/Containers/ContainerNavigator.h>
-#include <LibMedia/Demuxer.h>
-#include <LibMedia/DemuxerScanThread.h>
-#include <LibMedia/Export.h>
-#include <LibMedia/FFmpeg/FFmpegIOContext.h>
-#include <LibMedia/Forward.h>
-#include <LibMediaCodecs/CodecID.h>
-#include <LibMediaCodecs/FFmpeg/FFmpegForward.h>
-
-namespace Media::FFmpeg {
-
-class MEDIA_API FFmpegDemuxer : 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);
-
- virtual ~FFmpegDemuxer() 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 AK::Duration select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode) override;
- virtual DecoderErrorOr<DemuxerSeekResult> seek_to_most_recent_keyframe(Track const&, AK::Duration timestamp, DemuxerSeekOptions) override;
-
- virtual DecoderErrorOr<AK::Duration> duration_of_track(Track const&) override;
- virtual DecoderErrorOr<AK::Duration> total_duration() override;
- virtual Optional<AK::UnixDateTime> start_time_realtime() const override;
-
- virtual DemuxerScanState const& scan_state() const LIFETIME_BOUND override;
- virtual void set_scan_state_change_handler(ScanStateChangeHandler) override;
-
- virtual DecoderErrorOr<CodedFrame> get_next_sample_for_track(Track const&) 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 StreamInfo {
- Track track;
- CodecID codec_id;
- ByteBuffer codec_initialization_data;
- AK::Duration duration;
- i32 time_base_numerator;
- i32 time_base_denominator;
- };
-
- struct TrackContext {
- AK_ALLOC_WITH_KMALLOC;
-
- TrackContext(NonnullRefPtr<MediaStreamCursor>&& cursor, NonnullOwnPtr<FFmpegIOContext>&& io_context)
- : cursor(move(cursor))
- , io_context(move(io_context))
- {
- }
- ~TrackContext();
- TrackContext(TrackContext&&) = default;
-
- NonnullRefPtr<MediaStreamCursor> cursor;
- NonnullOwnPtr<FFmpegIOContext> io_context;
- AVFormatContext* format_context { nullptr };
- AVPacket* packet { nullptr };
- bool is_seekable { true };
- bool peeked_packet_already { false };
- bool needs_codec_configuration { true };
- Optional<AK::Duration> pending_timestamp_offset;
- AK::Duration timestamp_offset;
- };
-
- struct BufferedScanPayload {
- NonnullOwnPtr<ContainerNavigator> navigator;
- AK::Duration initial_duration;
- };
-
- FFmpegDemuxer(NonnullRefPtr<MediaStream> const&);
-
- static OwnPtr<ContainerNavigator> create_single_track_container_navigator(AVFormatContext&, NonnullRefPtr<MediaStream> const&);
-
- void start_buffered_scan_thread(AVFormatContext&);
-
- StreamInfo const& get_track_info(Track const&) const;
- TrackContext& get_track_context(Track const&);
-
- NonnullRefPtr<MediaStream> m_stream;
- AK::Duration m_total_duration;
- Optional<AK::UnixDateTime> m_start_time_realtime;
- Vector<StreamInfo> m_stream_info;
- RefPtr<DemuxerScanThread<BufferedScanPayload>> m_buffered_scan_thread;
- DemuxerScanState m_fallback_scan_state;
- Array<int, to_underlying(TrackType::Unknown)> m_preferred_track_for_type;
-
- HashMap<Track, NonnullOwnPtr<TrackContext>> m_track_contexts;
-};
-
-}
diff --git a/Libraries/LibMedia/FFmpeg/FFmpegIOContext.cpp b/Libraries/LibMedia/FFmpeg/FFmpegIOContext.cpp
deleted file mode 100644
index 45191f9fc2b..00000000000
--- a/Libraries/LibMedia/FFmpeg/FFmpegIOContext.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Stream.h>
-#include <LibMedia/FFmpeg/FFmpegIOContext.h>
-#include <LibMedia/MediaStream.h>
-
-extern "C" {
-#include <libavformat/avformat.h>
-}
-
-namespace Media::FFmpeg {
-
-FFmpegIOContext::FFmpegIOContext(NonnullRefPtr<MediaStreamCursor> stream_cursor, AVIOContext* avio_context)
- : m_stream_cursor(move(stream_cursor))
- , m_avio_context(avio_context)
-{
-}
-
-FFmpegIOContext::~FFmpegIOContext()
-{
- // NOTE: free the buffer inside the AVIO context, since it might be changed since its initial allocation
- av_free(m_avio_context->buffer);
- avio_context_free(&m_avio_context);
-}
-
-ErrorOr<NonnullOwnPtr<FFmpegIOContext>> FFmpegIOContext::create(NonnullRefPtr<MediaStreamCursor> stream_cursor)
-{
- auto* avio_buffer = av_malloc(PAGE_SIZE);
- if (avio_buffer == nullptr)
- return Error::from_string_literal("Failed to allocate AVIO buffer");
-
- // This AVIOContext explains to avformat how to interact with our stream
- auto* avio_context = avio_alloc_context(
- static_cast<unsigned char*>(avio_buffer),
- PAGE_SIZE,
- 0,
- stream_cursor.ptr(),
- [](void* opaque, u8* buffer, int size) -> int {
- auto& stream_cursor = *static_cast<MediaStreamCursor*>(opaque);
- Bytes buffer_bytes { buffer, AK::min<size_t>(size, PAGE_SIZE) };
- auto buffer_bytes_or_error = stream_cursor.read_into(buffer_bytes);
- if (buffer_bytes_or_error.is_error() || buffer_bytes_or_error.value() == 0) {
- // We deliberately only return AVERROR_EOF here, because libavcodec's AVIOContext functions
- // will persist any non-EOF error permanently and return it any time it reaches EOF after that
- // point.
- return AVERROR_EOF;
- }
- return static_cast<int>(buffer_bytes_or_error.value());
- },
- nullptr,
- [](void* opaque, int64_t offset, int whence) -> int64_t {
- whence &= ~AVSEEK_FORCE;
-
- auto& stream_cursor = *static_cast<MediaStreamCursor*>(opaque);
- if (whence == AVSEEK_SIZE)
- return stream_cursor.blocking_size();
-
- auto seek_mode_from_whence = [](int origin) -> AK::SeekMode {
- if (origin == SEEK_CUR)
- return AK::SeekMode::FromCurrentPosition;
- if (origin == SEEK_END)
- return AK::SeekMode::FromEndPosition;
- return AK::SeekMode::SetPosition;
- };
-
- auto maybe_seek_error = stream_cursor.seek(offset, seek_mode_from_whence(whence));
- if (maybe_seek_error.is_error()) {
- // This is also deliberately only returning AVERROR_EOF, see the read_packet callback above.
- return AVERROR_EOF;
- }
- return stream_cursor.position();
- });
- if (avio_context == nullptr) {
- av_free(avio_buffer);
- return Error::from_string_literal("Failed to allocate AVIO context");
- }
-
- return make<FFmpegIOContext>(move(stream_cursor), avio_context);
-}
-
-}
diff --git a/Libraries/LibMedia/FFmpeg/FFmpegIOContext.h b/Libraries/LibMedia/FFmpeg/FFmpegIOContext.h
deleted file mode 100644
index f08c3efff34..00000000000
--- a/Libraries/LibMedia/FFmpeg/FFmpegIOContext.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/NonnullRefPtr.h>
-#include <LibMedia/Forward.h>
-#include <LibMediaCodecs/FFmpeg/FFmpegForward.h>
-
-namespace Media::FFmpeg {
-
-class FFmpegIOContext {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- explicit FFmpegIOContext(NonnullRefPtr<MediaStreamCursor>, AVIOContext*);
- ~FFmpegIOContext();
-
- static ErrorOr<NonnullOwnPtr<FFmpegIOContext>> create(NonnullRefPtr<MediaStreamCursor>);
-
- AVIOContext* avio_context() const { return m_avio_context; }
-
-private:
- NonnullRefPtr<MediaStreamCursor> m_stream_cursor;
- AVIOContext* m_avio_context { nullptr };
-};
-
-}
diff --git a/Meta/CMake/check_for_dependencies.cmake b/Meta/CMake/check_for_dependencies.cmake
index fb13aa74211..208c0e734fc 100644
--- a/Meta/CMake/check_for_dependencies.cmake
+++ b/Meta/CMake/check_for_dependencies.cmake
@@ -28,7 +28,6 @@ pkg_check_modules(WOFF2 REQUIRED IMPORTED_TARGET libwoff2dec)
# TODO: Figure out if we can do this the same way on all platforms
if (NOT ANDROID)
pkg_check_modules(AVCODEC REQUIRED IMPORTED_TARGET libavcodec-ladybird)
- pkg_check_modules(AVFORMAT REQUIRED IMPORTED_TARGET libavformat-ladybird)
pkg_check_modules(AVUTIL REQUIRED IMPORTED_TARGET libavutil-ladybird)
pkg_check_modules(LIBSWRESAMPLE REQUIRED IMPORTED_TARGET libswresample-ladybird)
else()
diff --git a/Meta/CMake/flatpak/org.ladybird.Ladybird.json b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
index b03cf802f68..a2ddb0f6554 100644
--- a/Meta/CMake/flatpak/org.ladybird.Ladybird.json
+++ b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
@@ -615,7 +615,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 --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 --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 --disable-avformat --disable-avfilter --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,mpegaudio --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 82911a72bcc..bb94499dd36 100644
--- a/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
+++ b/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
@@ -280,8 +280,7 @@ endif()
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")
+ set(OPTIONS "${OPTIONS} --enable-parser=vp8,vp9,av1,mpegaudio")
endif()
if("swscale" IN_LIST FEATURES)
diff --git a/Meta/CMake/vcpkg/overlay-ports/ffmpeg/vcpkg.json b/Meta/CMake/vcpkg/overlay-ports/ffmpeg/vcpkg.json
index 645f7688cdf..52cb8575903 100644
--- a/Meta/CMake/vcpkg/overlay-ports/ffmpeg/vcpkg.json
+++ b/Meta/CMake/vcpkg/overlay-ports/ffmpeg/vcpkg.json
@@ -1,7 +1,7 @@
{
"name": "ffmpeg",
"version": "9.0.2",
- "port-version": 3,
+ "port-version": 4,
"description": [
"A library to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created.",
"FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created. It supports the most obscure ancient formats up to the cutting edge. No matter if they were designed by some standards committee, the community or a corporation. It is also highly portable: FFmpeg compiles, runs, and passes our testing infrastructure FATE across Linux, Mac OS X, Microsoft Windows, the BSDs, Solaris, etc. under a wide variety of build environments, machine architectures, and configurations."
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index e40070bfd2e..67b75364e13 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -16,7 +16,6 @@ set(TEST_SOURCES
TestDemuxerRegistry.cpp
TestDisplayingVideoSink.cpp
TestFFmpegAudioNormalization.cpp
- TestFFmpegDemuxer.cpp
TestFLACDemuxer.cpp
TestID3.cpp
TestIncrementallyPopulatedStream.cpp
@@ -29,6 +28,7 @@ set(TEST_SOURCES
TestMP3StreamInfo.cpp
TestMediaSupport.cpp
TestMediaTime.cpp
+ TestOggDemuxer.cpp
TestParseMatroska.cpp
TestPipelineNodes.cpp
TestPlaybackManager.cpp
@@ -65,9 +65,9 @@ target_link_libraries(TestDecodedAudioProducer PRIVATE LibGfx)
target_link_libraries(TestDisplayingVideoSink PRIVATE LibGfx)
target_link_libraries(TestVP9Decode PRIVATE LibGfx)
target_link_libraries(TestADTSDemuxer PRIVATE LibThreading)
-target_link_libraries(TestFFmpegDemuxer PRIVATE LibThreading)
target_link_libraries(TestFLACDemuxer PRIVATE LibThreading)
target_link_libraries(TestMP3Demuxer PRIVATE LibThreading)
+target_link_libraries(TestOggDemuxer PRIVATE LibThreading LibGfx)
target_link_libraries(TestWAVDemuxer PRIVATE LibThreading)
target_link_libraries(TestISOBMFF PRIVATE LibThreading)
target_link_libraries(TestMediaTime PRIVATE LibThreading)
diff --git a/Tests/LibMedia/Ogg/chained_opus_then_vorbis.ogg b/Tests/LibMedia/Ogg/chained_opus_then_vorbis.ogg
new file mode 100644
index 00000000000..97bf74deb58
Binary files /dev/null and b/Tests/LibMedia/Ogg/chained_opus_then_vorbis.ogg differ
diff --git a/Tests/LibMedia/Ogg/sine_opus_1005ms.ogg b/Tests/LibMedia/Ogg/sine_opus_1005ms.ogg
new file mode 100644
index 00000000000..4c910d68a26
Binary files /dev/null and b/Tests/LibMedia/Ogg/sine_opus_1005ms.ogg differ
diff --git a/Tests/LibMedia/Ogg/theora_vorbis_10fps.ogg b/Tests/LibMedia/Ogg/theora_vorbis_10fps.ogg
new file mode 100644
index 00000000000..7d94796cab7
Binary files /dev/null and b/Tests/LibMedia/Ogg/theora_vorbis_10fps.ogg differ
diff --git a/Tests/LibMedia/TestBufferedRanges.cpp b/Tests/LibMedia/TestBufferedRanges.cpp
index 80babfd5c40..a21cdd42bb3 100644
--- a/Tests/LibMedia/TestBufferedRanges.cpp
+++ b/Tests/LibMedia/TestBufferedRanges.cpp
@@ -195,10 +195,11 @@ static Array fixtures {
{ 32 * KiB, 82944, 4608, 48000 },
{ 68 * KiB, 216576, 4608, 48000 },
},
+ // Opus times count from after the stream's pre-skip of 312 samples.
Fixture {
"buffered-ranges/tone_opus.ogg"sv,
- { 96 * KiB, 432000, 48000, 48000 },
- { 160 * KiB, 768000, 48000, 48000 },
+ { 96 * KiB, 432000 - 312, 48000, 48000 },
+ { 160 * KiB, 768000 - 312, 48000, 48000 },
},
Fixture {
"buffered-ranges/tone_flac.ogg"sv,
diff --git a/Tests/LibMedia/TestFFmpegDemuxer.cpp b/Tests/LibMedia/TestFFmpegDemuxer.cpp
deleted file mode 100644
index 5c67d2610dd..00000000000
--- a/Tests/LibMedia/TestFFmpegDemuxer.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2026, Gregory Bertilson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Atomic.h>
-#include <AK/Function.h>
-#include <LibCore/File.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
-#include <LibMedia/IncrementallyPopulatedStream.h>
-#include <LibMediaCodecs/CodedFrame.h>
-#include <LibTest/TestCase.h>
-#include <LibThreading/Thread.h>
-
-TEST_CASE(rejects_formats_handled_by_other_demuxers)
-{
- for (auto path : { "./vfr.mkv"sv, "./avc.mp4"sv, "./buffered-ranges/tone.wav"sv, "./buffered-ranges/tone.flac"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)
-{
- // This is a regression test for an issue that would occur when aborting a blocking read in the AVIOContext
- // underlying an FFmpegDemuxer. We would return AVERROR_EXIT when aborting reads, but libavformat holds onto
- // any non-EOF error and only returns that error upon subsequent EOF reads. This would cause our playback system
- // to encounter an unexpected error when playing to the end of a file after an aborted 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("./buffered-ranges/tone_vorbis.ogg"sv, Core::File::OpenMode::Read));
- auto file_data = MUST(file->read_until_eof());
-
- // Open the demuxer on the whole file, since opening an Ogg stream reads its end, then take the middle away so
- // that the demuxer will eventually block waiting for it.
- auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(file_data);
- auto initial_chunk_size = file_data.size() / 4;
- auto tail_start = file_data.size() / 4 * 3;
-
- IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::FFmpeg::FFmpegDemuxer::from_stream(stream));
- stream->remove_byte_range(initial_chunk_size, tail_start);
- 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.
- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> got_aborted { false };
- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> read_blocked { false };
-
- demuxer->set_read_blocked_change_handler_for_track(track, [&](Media::ReadBlocked blocked) {
- read_blocked = blocked == Media::ReadBlocked::Yes;
- });
-
- auto reader_thread = Threading::Thread::construct("TestReader"sv, [&]() -> intptr_t {
- // Read frames until a read blocks and is aborted.
- while (true) {
- auto sample_result = demuxer->get_next_sample_for_track(track);
- if (sample_result.is_error()) {
- EXPECT_EQ(sample_result.error().category(), Media::DecoderErrorCategory::Aborted);
- got_aborted = true;
- break;
- }
- }
-
- // After abort is reset and remaining data is added, read all remaining frames.
- // We must eventually get EndOfStream, not a stale error.
- while (true) {
- auto sample_result = demuxer->get_next_sample_for_track(track);
-
- // Ignore any spurious aborts. This could be avoided with another atomic bool, but it is going to be
- // a very short spin.
- if (sample_result.is_error() && sample_result.error().category() == Media::DecoderErrorCategory::Aborted)
- continue;
-
- if (sample_result.is_error()) {
- EXPECT_EQ(sample_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
- break;
- }
- }
-
- return 0;
- });
-
- reader_thread->start();
-
- // Wait for the reader thread to block on a read.
- while (!read_blocked.load()) { }
-
- // Abort the blocked read from the main thread.
- demuxer->set_blocking_reads_aborted_for_track(track);
-
- // Wait for the reader thread to observe the abort.
- while (!got_aborted.load()) { }
-
- // Reset the abort state and provide the rest of the file data.
- demuxer->reset_blocking_reads_aborted_for_track(track);
- stream->add_chunk_at(initial_chunk_size, file_data.bytes().slice(initial_chunk_size, tail_start - initial_chunk_size));
-
- // Wait for the reader thread to finish. It should successfully read all remaining frames
- // and then get EndOfStream.
- MUST(reader_thread->join());
-}
diff --git a/Tests/LibMedia/TestOggDemuxer.cpp b/Tests/LibMedia/TestOggDemuxer.cpp
new file mode 100644
index 00000000000..92c0697038a
--- /dev/null
+++ b/Tests/LibMedia/TestOggDemuxer.cpp
@@ -0,0 +1,660 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Atomic.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/File.h>
+#include <LibCore/Timer.h>
+#include <LibMedia/Containers/Ogg/OggDemuxer.h>
+#include <LibMedia/Containers/Ogg/Reader.h>
+#include <LibMedia/DecoderRegistrations.h>
+#include <LibMedia/IncrementallyPopulatedStream.h>
+#include <LibMedia/Producers/DecodedVideoProducer.h>
+#include <LibMediaCodecs/CodedFrame.h>
+#include <LibMediaCodecs/VideoFrame.h>
+#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+
+#include "TestMediaCommon.h"
+
+namespace {
+
+TEST_SETUP
+{
+ (void)never_destroyed_event_loop();
+ Media::install_video_decoders({ Media::hardware_video_decoders(), Media::ffmpeg_video_decoders() });
+ Media::install_audio_decoders({ Media::audio_decoders() });
+}
+
+// sine_opus_1005ms.ogg: 48 kHz mono Opus, 48240 samples after a pre-skip of 312, packets of 960 samples.
+constexpr i64 OPUS_PRE_SKIP = 312;
+constexpr i64 OPUS_SAMPLE_COUNT = 48240;
+// theora_vorbis_10fps.ogg: 64x48 Theora at 10 fps with a keyframe every 10 frames, beside 8 kHz mono Vorbis, 3 s.
+constexpr size_t THEORA_FRAME_COUNT = 30;
+
+ByteBuffer read_fixture(StringView path)
+{
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
+ return MUST(file->read_until_eof());
+}
+
+Media::DecoderErrorOr<NonnullRefPtr<Media::Demuxer>> demuxer_for(ByteBuffer const& data)
+{
+ return Media::Ogg::OggDemuxer::from_stream(Media::IncrementallyPopulatedStream::create_from_buffer(data));
+}
+
+Media::Track track_of_type(Media::Demuxer& demuxer, Media::TrackType type)
+{
+ auto track = MUST(demuxer.get_preferred_track_for_type(type));
+ VERIFY(track.has_value());
+ MUST(demuxer.create_context_for_track(*track));
+ return *track;
+}
+
+AK::Duration time_of_sample(i64 sample, u32 sample_rate = 48000)
+{
+ return AK::Duration::from_time_units(sample, 1, sample_rate);
+}
+
+struct FrameIdentity {
+ AK::Duration timestamp;
+ size_t byte_count { 0 };
+ bool operator==(FrameIdentity const&) const = default;
+};
+
+Vector<Media::CodedFrame> read_every_frame(Media::Demuxer& demuxer, Media::Track const& track)
+{
+ Vector<Media::CodedFrame> frames;
+ while (true) {
+ auto frame = demuxer.get_next_sample_for_track(track);
+ if (frame.is_error()) {
+ EXPECT_EQ(frame.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ frames.append(frame.release_value());
+ }
+ return frames;
+}
+
+Vector<FrameIdentity> identities_of(Vector<Media::CodedFrame> const& frames)
+{
+ Vector<FrameIdentity> identities;
+ for (auto const& frame : frames)
+ identities.append({ frame.presentation_timestamp(), frame.data().size() });
+ return identities;
+}
+
+bool spin_until(Function<bool()> condition)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto deadline_expired = false;
+ auto deadline_timer = Core::Timer::create_single_shot(AK::Duration::from_seconds(5), [&] { deadline_expired = true; });
+ deadline_timer->start();
+ loop.spin_until([&] { return condition() || deadline_expired; });
+ return !deadline_expired;
+}
+
+Vector<Media::Ogg::PageHeader> page_headers(ByteBuffer const& data)
+{
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
+ Media::Ogg::PageIterator pages { stream->create_cursor(), 0 };
+ Vector<Media::Ogg::PageHeader> headers;
+ while (pages.position() < data.size())
+ headers.append(MUST(pages.read_next_page()).header);
+ return headers;
+}
+
+Media::Ogg::Page packet_page(u32 sequence_number, bool continues_packet, ReadonlyBytes segment_sizes)
+{
+ size_t payload_size = 0;
+ for (auto size : segment_sizes)
+ payload_size += size;
+ auto payload = MUST(FixedArray<u8>::create(payload_size));
+ payload.span().fill(static_cast<u8>(sequence_number));
+ return {
+ .header = { .flags = static_cast<u8>(continues_packet ? 1 : 0), .sequence_number = sequence_number },
+ .segment_sizes = MUST(FixedArray<u8>::create(segment_sizes)),
+ .payload = move(payload),
+ };
+}
+
+TEST_CASE(packet_assembly_handles_empty_packets_and_continuations)
+{
+ Media::Ogg::PacketAssembler assembler;
+ auto first_page = packet_page(0, false, Array<u8, 4> { 0, 255, 0, 255 });
+ auto packets = MUST(assembler.take_completed_packets(first_page));
+ EXPECT_EQ(packets.size(), 2u);
+ EXPECT(packets[0].is_empty());
+ EXPECT_EQ(packets[1].size(), 255u);
+
+ auto middle_page = packet_page(1, true, Array<u8, 1> { 255 });
+ EXPECT(MUST(assembler.take_completed_packets(middle_page)).is_empty());
+ auto final_page = packet_page(2, true, Array<u8, 2> { 0, 1 });
+ packets = MUST(assembler.take_completed_packets(final_page));
+ EXPECT_EQ(packets.size(), 2u);
+ EXPECT_EQ(packets[0].size(), 510u);
+ EXPECT_EQ(packets[0][0], 0u);
+ EXPECT_EQ(packets[0][255], 1u);
+ EXPECT_EQ(packets[1].size(), 1u);
+ EXPECT_EQ(packets[1][0], 2u);
+}
+
+TEST_CASE(packet_assembly_discards_a_continuation_after_a_missing_page)
+{
+ Media::Ogg::PacketAssembler assembler;
+ EXPECT(MUST(assembler.take_completed_packets(packet_page(0, false, Array<u8, 1> { 255 }))).is_empty());
+ auto packets = MUST(assembler.take_completed_packets(packet_page(2, true, Array<u8, 2> { 1, 2 })));
+ EXPECT_EQ(packets.size(), 1u);
+ EXPECT_EQ(packets[0].size(), 2u);
+
+ assembler.reset();
+ packets = MUST(assembler.take_completed_packets(packet_page(2, true, Array<u8, 2> { 1, 2 })));
+ EXPECT_EQ(packets.size(), 1u);
+ EXPECT_EQ(packets[0].size(), 2u);
+}
+
+TEST_CASE(packet_assembly_preserves_continuity_across_sequence_number_wraparound)
+{
+ Media::Ogg::PacketAssembler assembler;
+ EXPECT(MUST(assembler.take_completed_packets(packet_page(NumericLimits<u32>::max(), false, Array<u8, 1> { 255 }))).is_empty());
+ auto packets = MUST(assembler.take_completed_packets(packet_page(0, true, Array<u8, 1> { 1 })));
+ EXPECT_EQ(packets.size(), 1u);
+ EXPECT_EQ(packets[0].size(), 256u);
+}
+
+TEST_CASE(buffered_scan_resynchronizes_after_an_invalid_header_near_the_end)
+{
+ auto data = read_fixture("buffered-ranges/tone_vorbis.ogg"sv);
+ auto headers = page_headers(data);
+ auto damaged_position = headers[headers.size() - 2].position;
+ VERIFY(data.size() - damaged_position < Media::Ogg::MAXIMUM_PAGE_SIZE);
+ data[damaged_position] = 'X';
+ auto demuxer = MUST(demuxer_for(data));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ auto expected_end = time_of_sample(headers.last().granule_position, 44100);
+ EXPECT(spin_until([&] { return demuxer->scan_state().buffered_ranges().highest_end_time() == expected_end; }));
+}
+
+TEST_CASE(buffered_scan_waits_for_a_partial_page_to_finish)
+{
+ auto data = read_fixture("buffered-ranges/tone_vorbis.ogg"sv);
+ auto headers = page_headers(data);
+ auto const& partial_page = headers[headers.size() - 2];
+ auto expected_end = time_of_sample(headers.last().granule_position, 44100);
+ for (auto split_position : { partial_page.position + 12, partial_page.position + partial_page.byte_size / 2 }) {
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->add_chunk_at(0, data.bytes().trim(split_position));
+ auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ auto preceding_page_end = time_of_sample(headers[headers.size() - 3].granule_position, 44100);
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == preceding_page_end; }));
+
+ stream->add_chunk_at(split_position, data.bytes().slice(split_position));
+ stream->close();
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == expected_end; }));
+ }
+}
+
+TEST_CASE(buffered_scan_connects_a_previously_isolated_link)
+{
+ auto data = read_fixture("Ogg/chained_opus_then_vorbis.ogg"sv);
+ auto headers = page_headers(data);
+ auto first_link_end_page = headers[3];
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->add_chunk_at(0, data.bytes().trim(first_link_end_page.position));
+ stream->add_chunk_at(first_link_end_page.end_position(), data.bytes().slice(first_link_end_page.end_position()));
+ auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ EXPECT(spin_until([&] { return !demuxer->scan_state().buffered_ranges().is_empty(); }));
+
+ stream->add_chunk_at(first_link_end_page.position, data.bytes().slice(first_link_end_page.position));
+ stream->close();
+ auto expected_end = time_of_sample(OPUS_SAMPLE_COUNT) + AK::Duration::from_seconds(1);
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == expected_end; }));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(1500), Media::DemuxerSeekOptions::None));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).codec_id(), Media::CodecID::Vorbis);
+}
+
+TEST_CASE(buffered_scan_merges_concurrent_streams_discovered_separately)
+{
+ auto data = read_fixture("buffered-ranges/tone_vorbis.ogg"sv);
+ auto first_link_headers = page_headers(data);
+ auto first_link_duration = time_of_sample(first_link_headers.last().granule_position, 44100);
+ auto second_link = read_fixture("Ogg/theora_vorbis_10fps.ogg"sv);
+ auto second_link_headers = page_headers(second_link);
+ auto missing_byte_position = data.size() + second_link_headers[0].end_position() - 1;
+ MUST(data.try_append(second_link));
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->add_chunk_at(0, data.bytes().trim(missing_byte_position));
+ stream->add_chunk_at(missing_byte_position + 1, data.bytes().slice(missing_byte_position + 1));
+ auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == first_link_duration; }));
+
+ stream->add_chunk_at(missing_byte_position, data.bytes().slice(missing_byte_position));
+ stream->close();
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == first_link_duration + AK::Duration::from_seconds(3); }));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ MUST(demuxer->seek_to_most_recent_keyframe(track, first_link_duration + AK::Duration::from_milliseconds(1500), Media::DemuxerSeekOptions::None));
+ auto frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT(frame.presentation_timestamp() >= first_link_duration);
+ EXPECT(frame.presentation_timestamp() <= first_link_duration + AK::Duration::from_milliseconds(1500));
+}
+
+TEST_CASE(buffered_scan_resolves_data_seen_before_its_stream_headers)
+{
+ auto data = read_fixture("Ogg/sine_opus_1005ms.ogg"sv);
+ auto second_link_position = data.size();
+ auto second_link = read_fixture("buffered-ranges/tone_vorbis.ogg"sv);
+ auto headers = page_headers(second_link);
+ auto second_link_header_end = second_link_position + headers[1].end_position();
+ auto tail_position = second_link_position + headers[headers.size() / 2].position;
+ MUST(data.try_append(second_link));
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->add_chunk_at(0, data.bytes().trim(second_link_position));
+ stream->add_chunk_at(tail_position, data.bytes().slice(tail_position));
+ auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == time_of_sample(OPUS_SAMPLE_COUNT); }));
+
+ stream->add_chunk_at(second_link_position, data.bytes().slice(second_link_position, second_link_header_end - second_link_position));
+ auto expected_end = time_of_sample(OPUS_SAMPLE_COUNT) + time_of_sample(headers.last().granule_position, 44100);
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == expected_end; }));
+ EXPECT_EQ(demuxer->scan_state().buffered_ranges().size(), 2u);
+}
+
+TEST_CASE(buffered_scan_resumes_reading_later_link_headers)
+{
+ auto data = read_fixture("Ogg/chained_opus_then_vorbis.ogg"sv);
+ auto headers = page_headers(data);
+ auto split_position = headers[5].position + headers[5].byte_size / 2;
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->add_chunk_at(0, data.bytes().trim(split_position));
+ stream->add_chunk_at(headers[6].position, data.bytes().slice(headers[6].position));
+ auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ auto first_link_duration = time_of_sample(OPUS_SAMPLE_COUNT);
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == first_link_duration; }));
+
+ stream->add_chunk_at(split_position, data.bytes().slice(split_position));
+ stream->close();
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == first_link_duration + AK::Duration::from_seconds(1); }));
+}
+
+TEST_CASE(buffered_scan_retains_later_vorbis_configuration_after_header_eviction)
+{
+ auto data = read_fixture("Ogg/chained_opus_then_vorbis.ogg"sv);
+ auto headers = page_headers(data);
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
+ auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ auto first_link_duration = time_of_sample(OPUS_SAMPLE_COUNT);
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == first_link_duration + AK::Duration::from_seconds(1); }));
+
+ stream->remove_byte_range(0, headers[6].position);
+ EXPECT(spin_until([&] { return !demuxer->scan_state().resource_is_complete; }));
+ auto ranges = demuxer->scan_state().buffered_ranges();
+ EXPECT_EQ(ranges.size(), 1u);
+ if (ranges.size() == 1) {
+ EXPECT(ranges[0].start >= first_link_duration);
+ EXPECT(ranges[0].start < first_link_duration + AK::Duration::from_milliseconds(50));
+ }
+}
+
+TEST_CASE(demuxer_describes_every_stream_of_the_file)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/theora_vorbis_10fps.ogg"sv)));
+
+ auto video_tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Video));
+ EXPECT_EQ(video_tracks.size(), 1u);
+ EXPECT_EQ(video_tracks[0].parsed_codec().codec_id(), Media::CodecID::Theora);
+ EXPECT_EQ(video_tracks[0].video_data().pixel_width, 64u);
+ EXPECT_EQ(video_tracks[0].video_data().pixel_height, 48u);
+
+ auto audio_tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio));
+ EXPECT_EQ(audio_tracks.size(), 1u);
+ EXPECT_EQ(audio_tracks[0].parsed_codec().codec_id(), Media::CodecID::Vorbis);
+ EXPECT_EQ(audio_tracks[0].audio_data().sample_specification.sample_rate(), 8000u);
+ EXPECT_EQ(audio_tracks[0].audio_data().sample_specification.channel_count(), 1u);
+
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::from_seconds(3));
+}
+
+// Pre-skip is dropped by the decoder, and the last page's granule position trims the last packet, so the packets
+// cover exactly the stream's samples.
+TEST_CASE(demuxer_leaves_opus_pre_skip_out_and_trims_the_last_packet)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/sine_opus_1005ms.ogg"sv)));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ EXPECT_EQ(MUST(demuxer->total_duration()), time_of_sample(OPUS_SAMPLE_COUNT));
+
+ auto frames = read_every_frame(*demuxer, track);
+ VERIFY(!frames.is_empty());
+ EXPECT(frames.first().new_codec_configuration().has_value());
+ EXPECT_EQ(frames.first().presentation_timestamp(), AK::Duration::zero());
+ EXPECT_EQ(frames.first().leading_discard(), AK::Duration::zero());
+ EXPECT_EQ(frames.first().duration(), time_of_sample(960 - OPUS_PRE_SKIP));
+
+ for (size_t i = 1; i < frames.size(); i++) {
+ auto const& previous = frames[i - 1];
+ EXPECT_EQ(frames[i].presentation_timestamp(), previous.presentation_timestamp() + previous.duration());
+ EXPECT(!frames[i].new_codec_configuration().has_value());
+ }
+ auto const& last = frames.last();
+ EXPECT(last.trailing_discard() > AK::Duration::zero());
+ EXPECT_EQ(last.presentation_timestamp() + last.duration(), time_of_sample(OPUS_SAMPLE_COUNT));
+}
+
+TEST_CASE(demuxer_feeds_decoders_to_the_end)
+{
+ decode_audio("Ogg/sine_opus_1005ms.ogg"sv, 48000, 1, OPUS_SAMPLE_COUNT);
+ decode_audio("buffered-ranges/tone_flac.ogg"sv, 44100, 1, 1323000);
+}
+
+TEST_CASE(demuxer_reads_theora_frames_and_their_keyframes)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/theora_vorbis_10fps.ogg"sv)));
+ auto track = track_of_type(*demuxer, Media::TrackType::Video);
+
+ auto frames = read_every_frame(*demuxer, track);
+ EXPECT_EQ(frames.size(), THEORA_FRAME_COUNT);
+ for (size_t i = 0; i < frames.size(); i++) {
+ EXPECT_EQ(frames[i].presentation_timestamp(), AK::Duration::from_milliseconds(static_cast<i64>(i) * 100));
+ EXPECT_EQ(frames[i].is_keyframe(), i % 10 == 0);
+ }
+}
+
+TEST_CASE(theora_frames_decode_to_the_end)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/theora_vorbis_10fps.ogg"sv)));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video));
+ auto producer = MUST(Media::DecodedVideoProducer::try_create(loop, demuxer, *track));
+ producer->set_error_handler([](Media::DecoderError&& error) {
+ FAIL(ByteString::formatted("Decoding failed: {}", error.description()));
+ });
+ producer->start();
+
+ Vector<AK::Duration> timestamps;
+ EXPECT(spin_until([&] {
+ while (true) {
+ auto output = producer->peek();
+ if (output.status == Media::PipelineStatus::HaveData) {
+ timestamps.append(output.frame->timestamp());
+ producer->consume();
+ continue;
+ }
+ return output.status == Media::PipelineStatus::EndOfStream;
+ }
+ }));
+ EXPECT_EQ(timestamps.size(), THEORA_FRAME_COUNT);
+ for (size_t i = 0; i < timestamps.size(); i++)
+ EXPECT_EQ(timestamps[i], AK::Duration::from_milliseconds(static_cast<i64>(i) * 100));
+}
+
+TEST_CASE(demuxer_seeks_video_to_the_keyframe_the_target_depends_on)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/theora_vorbis_10fps.ogg"sv)));
+ auto track = track_of_type(*demuxer, Media::TrackType::Video);
+
+ for (auto target_milliseconds : { 1550, 1000, 2950, 50 }) {
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(target_milliseconds), Media::DemuxerSeekOptions::None));
+ auto frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT(frame.is_keyframe());
+ EXPECT_EQ(frame.presentation_timestamp(), AK::Duration::from_milliseconds(static_cast<i64>(target_milliseconds / 1000) * 1000));
+ }
+}
+
+// A seek lands before its target, early enough for Opus to have converged by then, and no more than a page earlier.
+TEST_CASE(demuxer_seeks_audio_before_the_target)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone_opus.ogg"sv)));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+
+ for (auto target_milliseconds : { 20'000, 3'500, 29'900, 100 }) {
+ auto target = AK::Duration::from_milliseconds(target_milliseconds);
+ MUST(demuxer->seek_to_most_recent_keyframe(track, target, Media::DemuxerSeekOptions::None));
+ auto frame = MUST(demuxer->get_next_sample_for_track(track));
+ auto start = frame.presentation_timestamp() - frame.leading_discard();
+ EXPECT(start <= target - AK::Duration::from_milliseconds(80) || start <= AK::Duration::zero());
+ EXPECT(start >= target - AK::Duration::from_milliseconds(1'100));
+ }
+}
+
+TEST_CASE(demuxer_plays_through_a_chained_file)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/chained_opus_then_vorbis.ogg"sv)));
+ // A chained file's duration is learned by reading its links.
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::zero());
+
+ auto tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio));
+ EXPECT_EQ(tracks.size(), 1u);
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+
+ auto frames = read_every_frame(*demuxer, track);
+ Optional<size_t> second_link_start;
+ for (size_t i = 0; i < frames.size(); i++) {
+ if (frames[i].codec_id() == Media::CodecID::Vorbis) {
+ second_link_start = i;
+ break;
+ }
+ }
+ if (!second_link_start.has_value()) {
+ FAIL("The second link's frames were not delivered");
+ return;
+ }
+ auto const& first_vorbis_frame = frames[*second_link_start];
+ EXPECT(first_vorbis_frame.new_codec_configuration().has_value());
+ // The second link starts where the first ends.
+ auto first_link_end = time_of_sample(OPUS_SAMPLE_COUNT);
+ EXPECT(first_vorbis_frame.presentation_timestamp() >= first_link_end);
+ EXPECT(first_vorbis_frame.presentation_timestamp() <= first_link_end + AK::Duration::from_milliseconds(50));
+ for (size_t i = 1; i < frames.size(); i++)
+ EXPECT(frames[i].presentation_timestamp() >= frames[i - 1].presentation_timestamp());
+ auto end = frames.last().presentation_timestamp() + frames.last().duration();
+ EXPECT_EQ(end, first_link_end + AK::Duration::from_seconds(1));
+}
+
+TEST_CASE(demuxer_grows_buffered_ranges_and_seeks_across_a_chain)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("Ogg/chained_opus_then_vorbis.ogg"sv)));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ auto expected_end = time_of_sample(OPUS_SAMPLE_COUNT) + AK::Duration::from_seconds(1);
+ EXPECT(spin_until([&] { return demuxer->scan_state().duration == expected_end; }));
+ auto ranges = demuxer->scan_state().buffered_ranges();
+ EXPECT_EQ(ranges.size(), 1u);
+ if (ranges.size() == 1)
+ EXPECT_EQ(ranges[0].end, expected_end);
+
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(1'500), Media::DemuxerSeekOptions::None));
+ auto frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(frame.codec_id(), Media::CodecID::Vorbis);
+ EXPECT(frame.new_codec_configuration().has_value());
+ EXPECT(frame.presentation_timestamp() <= AK::Duration::from_milliseconds(1'500));
+
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(500), Media::DemuxerSeekOptions::None));
+ frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(frame.codec_id(), Media::CodecID::Opus);
+ EXPECT(frame.new_codec_configuration().has_value());
+ EXPECT(frame.presentation_timestamp() <= AK::Duration::from_milliseconds(500));
+}
+
+// An aborted read is retried by the next call, which delivers the frame the aborted read was after, so a pass
+// interrupted anywhere delivers the same frames as one that was not.
+TEST_CASE(demuxer_resumes_an_aborted_read_with_the_frame_it_was_reading)
+{
+ auto file_data = read_fixture("buffered-ranges/tone_vorbis.ogg"sv);
+
+ Vector<FrameIdentity> expected_frames;
+ {
+ auto demuxer = MUST(demuxer_for(file_data));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ expected_frames = identities_of(read_every_frame(*demuxer, track));
+ }
+
+ // The data ends inside a page, so the read that blocks has part of its page. The tail is there for the duration.
+ auto initial_chunk_size = (file_data.size() / 3) + 1000;
+ auto tail_start = file_data.size() - (2 * Media::Ogg::MAXIMUM_PAGE_SIZE);
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->set_expected_size(file_data.size());
+ stream->add_chunk_at(0, file_data.bytes().trim(initial_chunk_size));
+ stream->add_chunk_at(tail_start, file_data.bytes().slice(tail_start));
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> read_blocked { false };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> read_was_aborted { false };
+ demuxer->set_read_blocked_change_handler_for_track(track, [&](Media::ReadBlocked blocked) {
+ read_blocked = blocked == Media::ReadBlocked::Yes;
+ });
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA Vector<FrameIdentity> actual_frames;
+ auto reader_thread = Threading::Thread::construct("TestReader"sv, [&]() -> intptr_t {
+ while (true) {
+ auto frame = demuxer->get_next_sample_for_track(track);
+ if (frame.is_error()) {
+ EXPECT_EQ(frame.error().category(), Media::DecoderErrorCategory::Aborted);
+ break;
+ }
+ actual_frames.append({ frame.value().presentation_timestamp(), frame.value().data().size() });
+ }
+ // Like a producer, the reading thread allows reads again before it reads on.
+ demuxer->reset_blocking_reads_aborted_for_track(track);
+ read_was_aborted = true;
+ actual_frames.extend(identities_of(read_every_frame(*demuxer, track)));
+ return 0;
+ });
+ reader_thread->start();
+
+ while (!read_blocked.load()) { }
+ demuxer->set_blocking_reads_aborted_for_track(track);
+ while (!read_was_aborted.load()) { }
+
+ stream->add_chunk_at(initial_chunk_size, file_data.bytes().slice(initial_chunk_size));
+ stream->close();
+ MUST(reader_thread->join());
+
+ EXPECT_EQ(actual_frames.size(), expected_frames.size());
+ for (size_t index = 0; index < min(actual_frames.size(), expected_frames.size()); index++) {
+ if (actual_frames[index] != expected_frames[index]) {
+ FAIL(ByteString::formatted("Frame {} differs after the abort: {}ms/{} bytes instead of {}ms/{} bytes", index, actual_frames[index].timestamp.to_milliseconds(), actual_frames[index].byte_count, expected_frames[index].timestamp.to_milliseconds(), expected_frames[index].byte_count));
+ break;
+ }
+ }
+}
+
+// A page that fails its CRC is skipped, losing only the packets it completes, and the packets after it keep their
+// times since every page carries its own granule position.
+TEST_CASE(demuxer_reads_on_past_a_damaged_page)
+{
+ auto file_data = read_fixture("buffered-ranges/tone_opus.ogg"sv);
+ Vector<FrameIdentity> intact_frames;
+ {
+ auto demuxer = MUST(demuxer_for(file_data));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ intact_frames = identities_of(read_every_frame(*demuxer, track));
+ }
+
+ auto damaged_data = MUST(ByteBuffer::copy(file_data));
+ damaged_data[damaged_data.size() / 2] ^= 0xFF;
+ auto demuxer = MUST(demuxer_for(damaged_data));
+ auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ auto damaged_frames = identities_of(read_every_frame(*demuxer, track));
+
+ EXPECT(damaged_frames.size() < intact_frames.size());
+ EXPECT(damaged_frames.size() > intact_frames.size() - 100);
+ EXPECT_EQ(damaged_frames.last(), intact_frames.last());
+}
+
+TEST_CASE(demuxer_declines_what_it_cannot_read)
+{
+ auto not_ogg = demuxer_for(read_fixture("WAV/tone_8000_mono.wav"sv));
+ EXPECT(not_ogg.is_error());
+ if (not_ogg.is_error())
+ EXPECT_EQ(not_ogg.error().category(), Media::DecoderErrorCategory::UnrecognizedFormat);
+}
+
+// A seek into data that is not there yet asks for little more than the pages its probes land on.
+TEST_CASE(demuxer_seeks_into_unbuffered_data_with_few_requests)
+{
+ auto file_data = read_fixture("buffered-ranges/tone_opus.ogg"sv);
+ auto& loop = never_destroyed_event_loop();
+
+ constexpr size_t head_size = 4 * KiB;
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->set_expected_size(file_data.size());
+ stream->add_chunk_at(0, file_data.bytes().trim(head_size));
+
+ // Serve the way a server does once asked: each request starts delivery at its offset, delivery goes on from
+ // there a slice at a time, and a stopped request ends it.
+ Vector<u64> requested_offsets;
+ Optional<size_t> serving_position;
+ stream->set_data_request_callback([&](Optional<u64> offset) {
+ serving_position = offset.map([](u64 value) { return static_cast<size_t>(value); });
+ if (offset.has_value())
+ requested_offsets.append(*offset);
+ });
+ auto server = Core::Timer::create_repeating(AK::Duration::from_milliseconds(1), [&] {
+ if (!serving_position.has_value() || *serving_position >= file_data.size())
+ return;
+ auto slice_size = min<size_t>(8 * KiB, file_data.size() - *serving_position);
+ stream->add_chunk_at(*serving_position, file_data.bytes().slice(*serving_position, slice_size));
+ *serving_position += slice_size;
+ });
+ server->start();
+
+ // The fetch that delivered the head was stopped, so each read of data that is not there asks for a request from
+ // its own position, starting with the duration's read of the end of the file.
+ stream->set_may_idle(true);
+ stream->set_may_idle(false);
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA RefPtr<Media::Demuxer> demuxer;
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> loaded { false };
+ auto loader_thread = Threading::Thread::construct("TestLoader"sv, [&]() -> intptr_t {
+ demuxer = MUST(Media::Ogg::OggDemuxer::from_stream(stream));
+ loaded = true;
+ return 0;
+ });
+ loader_thread->start();
+ EXPECT(spin_until([&] { return loaded.load(); }));
+ MUST(loader_thread->join());
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto track = track_of_type(*demuxer, Media::TrackType::Audio);
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::from_seconds(30));
+
+ // The player stopped the fetch once its buffer was full and lets it go again for the seek.
+ stream->set_may_idle(true);
+ stream->set_may_idle(false);
+ serving_position = {};
+ auto requests_before_seeking = requested_offsets.size();
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto target = AK::Duration::from_seconds(20);
+ IGNORE_USE_IN_ESCAPING_LAMBDA AK::Duration landed_timestamp;
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> seek_finished { false };
+ auto seeker_thread = Threading::Thread::construct("TestSeeker"sv, [&]() -> intptr_t {
+ MUST(demuxer->seek_to_most_recent_keyframe(track, target, Media::DemuxerSeekOptions::None));
+ landed_timestamp = MUST(demuxer->get_next_sample_for_track(track)).presentation_timestamp();
+ seek_finished = true;
+ return 0;
+ });
+ seeker_thread->start();
+
+ if (!spin_until([&] { return seek_finished.load(); }))
+ FAIL(ByteString::formatted("The seek did not finish: {} requests, serving at {}", requested_offsets.size(), serving_position));
+ server->stop();
+ stream->set_data_request_callback(nullptr);
+ MUST(seeker_thread->join());
+ (void)loop;
+
+ EXPECT(landed_timestamp <= target);
+ EXPECT(landed_timestamp >= target - AK::Duration::from_seconds(2));
+ EXPECT(requested_offsets.size() - requests_before_seeking <= 3);
+}
+
+}
diff --git a/Tests/LibMedia/TestVorbisDecode.cpp b/Tests/LibMedia/TestVorbisDecode.cpp
index a39c227feaf..e57465b7778 100644
--- a/Tests/LibMedia/TestVorbisDecode.cpp
+++ b/Tests/LibMedia/TestVorbisDecode.cpp
@@ -18,8 +18,7 @@ TEST_SETUP
TEST_CASE(44_1Khz_stereo)
{
- // FIXME: 96 samples are marked to be discarded, but DecodedAudioProducer currently is not aware of this.
- decode_audio("vorbis/44_1Khz_stereo.ogg"sv, 44100, 2, 352800 + 96);
+ decode_audio("vorbis/44_1Khz_stereo.ogg"sv, 44100, 2, 352800);
}
TEST_CASE(input_after_the_end_of_stream_is_rejected_until_flushed)
diff --git a/vcpkg.json b/vcpkg.json
index c30fe01563f..14b321f1743 100644
--- a/vcpkg.json
+++ b/vcpkg.json
@@ -44,7 +44,6 @@
"default-features": false,
"features": [
"avcodec",
- "avformat",
"swresample",
"dav1d",
"zlib",