Skip to content

Truly independent web browser

LibMedia: Build a FLAC demuxer to replace libavformat's

Zaggy102455d21fff9807
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txt
index 44694258ecf..d4391210ea5 100644
--- a/Libraries/LibMedia/CMakeLists.txt
+++ b/Libraries/LibMedia/CMakeLists.txt
@@ -11,7 +11,8 @@ set(SOURCES
Containers/ADTS/ADTSDemuxer.cpp
Containers/ADTS/FrameHeader.cpp
Containers/ADTS/Reader.cpp
- Containers/FLACNavigator.cpp
+ Containers/FLAC/FLACDemuxer.cpp
+ Containers/FLAC/Reader.cpp
Containers/FrameScanTimeline.cpp
Containers/ID3.cpp
Containers/IndexedContainerNavigator.cpp
diff --git a/Libraries/LibMedia/Codecs/FLAC.cpp b/Libraries/LibMedia/Codecs/FLAC.cpp
index 0c297d8014d..164e4011caa 100644
--- a/Libraries/LibMedia/Codecs/FLAC.cpp
+++ b/Libraries/LibMedia/Codecs/FLAC.cpp
@@ -30,37 +30,46 @@ DecoderErrorOr<FixedArray<u8>> FLAC::codec_initialization_data_from_isobmff_conf
return initialization_data;
}
+static DecoderErrorOr<bool> propagate_abort(DecoderErrorOr<void> result)
+{
+ if (!result.is_error())
+ return true;
+ if (result.error().category() == DecoderErrorCategory::Aborted)
+ return result.release_error();
+ return false;
+}
+
template<Integral T>
-static Optional<T> read_big_endian_value(MediaStreamCursor& cursor)
+static DecoderErrorOr<Optional<T>> read_big_endian_value(MediaStreamCursor& cursor)
{
- auto value = cursor.read_value<T>();
- if (value.is_error())
- return {};
- return value.release_value();
+ T value = 0;
+ if (!TRY(propagate_abort(cursor.read_until_filled({ &value, sizeof(value) }))))
+ return Optional<T> {};
+ return AK::convert_between_host_and_big_endian(value);
}
-static Optional<u64> read_coded_number(MediaStreamCursor& cursor)
+static DecoderErrorOr<Optional<u64>> read_coded_number(MediaStreamCursor& cursor)
{
- auto first_byte = read_big_endian_value<u8>(cursor);
+ auto first_byte = TRY(read_big_endian_value<u8>(cursor));
if (!first_byte.has_value())
- return {};
+ return Optional<u64> {};
u64 value = first_byte.value();
auto length = count_leading_zeroes_safe(static_cast<u8>(~value));
if (length == 0)
return value;
if (length == 1)
- return {};
+ return Optional<u64> {};
if (length > 7)
- return {};
+ return Optional<u64> {};
value &= (1 << (8 - (length + 1))) - 1;
while (--length > 0) {
- auto continuation_byte = read_big_endian_value<u8>(cursor);
+ auto continuation_byte = TRY(read_big_endian_value<u8>(cursor));
if (!continuation_byte.has_value())
- return {};
+ return Optional<u64> {};
if (continuation_byte.value() >> 6 != 0b10)
- return {};
+ return Optional<u64> {};
value <<= 6;
value |= continuation_byte.value() & 0b111111;
}
@@ -68,7 +77,7 @@ static Optional<u64> read_coded_number(MediaStreamCursor& cursor)
return value;
}
-static bool verify_header_crc(MediaStreamCursor& cursor, size_t header_start)
+static DecoderErrorOr<bool> verify_header_crc(MediaStreamCursor& cursor, size_t header_start)
{
constexpr auto lookup_table = [] {
Array<u8, 256> result;
@@ -88,16 +97,16 @@ static bool verify_header_crc(MediaStreamCursor& cursor, size_t header_start)
if (header_size > buffer.size())
return false;
- auto crc = read_big_endian_value<u8>(cursor);
+ auto crc = TRY(read_big_endian_value<u8>(cursor));
if (!crc.has_value())
return false;
- if (cursor.seek_to_position(header_start).is_error())
+ if (!TRY(propagate_abort(cursor.seek_to_position(header_start))))
return false;
auto header_data = buffer.span().trim(header_size);
- if (cursor.read_until_filled(header_data).is_error())
+ if (!TRY(propagate_abort(cursor.read_until_filled(header_data))))
return false;
- if (cursor.skip(1).is_error())
+ if (!TRY(propagate_abort(cursor.skip(1))))
return false;
u8 actual_crc = 0;
@@ -106,22 +115,41 @@ static bool verify_header_crc(MediaStreamCursor& cursor, size_t header_start)
return crc.value() == actual_crc;
}
+u16 FLAC::compute_frame_crc(ReadonlyBytes bytes)
+{
+ constexpr auto lookup_table = [] {
+ Array<u16, 256> result;
+ for (size_t i = 0; i < result.size(); i++) {
+ u16 value = static_cast<u16>(i << 8);
+ for (auto j = 0; j < 8; j++)
+ value = static_cast<u16>((value << 1) ^ ((value & 0x8000) ? 0x8005 : 0));
+ result[i] = value;
+ }
+ return result;
+ }();
+
+ u16 crc = 0;
+ for (auto const& byte : bytes)
+ crc = static_cast<u16>((crc << 8) ^ lookup_table[((crc >> 8) ^ byte) & 0xFF]);
+ return crc;
+}
+
bool FLAC::is_sync_code(u16 value)
{
return (value >> 1) == 0b111111111111100;
}
-Optional<FLAC::FrameInfo> FLAC::parse_frame_header(MediaStreamCursor& cursor, u16 sync_code, u16 fixed_block_size)
+DecoderErrorOr<Optional<FLAC::FrameInfo>> FLAC::parse_frame_header(MediaStreamCursor& cursor, u16 sync_code, u16 fixed_block_size)
{
auto header_start = cursor.position();
Array<u8, 4> header;
- if (cursor.read_until_filled(header).is_error())
- return {};
+ if (!TRY(propagate_abort(cursor.read_until_filled(header))))
+ return Optional<FrameInfo> {};
BitReader reader { header };
if (reader.read_bits<u16>(16) != sync_code)
- return {};
+ return Optional<FrameInfo> {};
bool variable_block_size = (sync_code & 1) != 0;
auto block_size_bits = reader.read_bits<u8>(4);
@@ -131,48 +159,48 @@ Optional<FLAC::FrameInfo> FLAC::parse_frame_header(MediaStreamCursor& cursor, u1
auto reserved_bit_is_set = reader.read_bit();
if (reserved_bit_is_set)
- return {};
+ return Optional<FrameInfo> {};
- auto coded_number = read_coded_number(cursor);
+ auto coded_number = TRY(read_coded_number(cursor));
if (!coded_number.has_value())
- return {};
+ return Optional<FrameInfo> {};
u16 block_size = 0;
if (block_size_bits == 0b0000)
- return {};
+ return Optional<FrameInfo> {};
if (block_size_bits == 0b0001) {
block_size = 192;
} else if (block_size_bits <= 0b0101) {
block_size = 144 * (1 << block_size_bits);
} else if (block_size_bits == 0b0110) {
- auto uncommon_block_size_minus_1 = read_big_endian_value<u8>(cursor);
+ auto uncommon_block_size_minus_1 = TRY(read_big_endian_value<u8>(cursor));
if (!uncommon_block_size_minus_1.has_value())
- return {};
+ return Optional<FrameInfo> {};
block_size = uncommon_block_size_minus_1.value() + 1;
} else if (block_size_bits == 0b0111) {
- auto uncommon_block_size_minus_1 = read_big_endian_value<u16>(cursor);
+ auto uncommon_block_size_minus_1 = TRY(read_big_endian_value<u16>(cursor));
if (!uncommon_block_size_minus_1.has_value())
- return {};
+ return Optional<FrameInfo> {};
block_size = uncommon_block_size_minus_1.value() + 1;
} else if (block_size_bits >= 0b1000) {
block_size = 1 << block_size_bits;
}
- if (sample_rate_bits == 0b1100 && cursor.skip(1).is_error())
- return {};
- if ((sample_rate_bits == 0b1101 || sample_rate_bits == 0b1110) && cursor.skip(2).is_error())
- return {};
+ if (sample_rate_bits == 0b1100 && !TRY(propagate_abort(cursor.skip(1))))
+ return Optional<FrameInfo> {};
+ if ((sample_rate_bits == 0b1101 || sample_rate_bits == 0b1110) && !TRY(propagate_abort(cursor.skip(2))))
+ return Optional<FrameInfo> {};
if (sample_rate_bits == 0b1111)
- return {};
+ return Optional<FrameInfo> {};
if (channels_bits >= 0b1011)
- return {};
+ return Optional<FrameInfo> {};
if (bit_depth_bits == 0b011)
- return {};
+ return Optional<FrameInfo> {};
- if (!verify_header_crc(cursor, header_start))
- return {};
+ if (!TRY(verify_header_crc(cursor, header_start)))
+ return Optional<FrameInfo> {};
u64 sample_number = coded_number.value();
if (!variable_block_size)
@@ -181,4 +209,27 @@ Optional<FLAC::FrameInfo> FLAC::parse_frame_header(MediaStreamCursor& cursor, u1
return FrameInfo { sample_number, block_size };
}
+Audio::ChannelMap FLAC::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::FrontRight, Channel::FrontCenter);
+ case 4:
+ return Audio::ChannelMap::quadrophonic();
+ case 5:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontRight, Channel::FrontCenter, Channel::BackLeft, Channel::BackRight);
+ case 6:
+ return Audio::ChannelMap::surround_5_1();
+ case 7:
+ return Audio::ChannelMap(Channel::FrontLeft, Channel::FrontRight, Channel::FrontCenter, Channel::LowFrequency, Channel::BackCenter, Channel::SideLeft, Channel::SideRight);
+ default:
+ return Audio::ChannelMap::surround_7_1();
+ }
+}
+
}
diff --git a/Libraries/LibMedia/Codecs/FLAC.h b/Libraries/LibMedia/Codecs/FLAC.h
index a7d76bf0a7b..0fffbde2ecb 100644
--- a/Libraries/LibMedia/Codecs/FLAC.h
+++ b/Libraries/LibMedia/Codecs/FLAC.h
@@ -9,6 +9,7 @@
#include <AK/FixedArray.h>
#include <AK/Optional.h>
#include <AK/Span.h>
+#include <LibAudio/ChannelMap.h>
#include <LibMedia/Export.h>
#include <LibMedia/Forward.h>
#include <LibMediaCodecs/DecoderError.h>
@@ -24,7 +25,11 @@ public:
static MEDIA_API DecoderErrorOr<FixedArray<u8>> codec_initialization_data_from_isobmff_configuration(ReadonlyBytes);
static bool is_sync_code(u16);
- static Optional<FrameInfo> parse_frame_header(MediaStreamCursor&, u16 sync_code, u16 fixed_block_size);
+ static DecoderErrorOr<Optional<FrameInfo>> parse_frame_header(MediaStreamCursor&, u16 sync_code, u16 fixed_block_size);
+ // The CRC a frame ends with, over every byte of the frame before it.
+ static u16 compute_frame_crc(ReadonlyBytes);
+ // The format assigns these positions to the channels of each count.
+ static MEDIA_API Audio::ChannelMap channel_map(u8 channel_count);
};
}
diff --git a/Libraries/LibMedia/Containers/CachedByteRanges.h b/Libraries/LibMedia/Containers/CachedByteRanges.h
new file mode 100644
index 00000000000..65d4e3eec9d
--- /dev/null
+++ b/Libraries/LibMedia/Containers/CachedByteRanges.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/EnumBits.h>
+#include <AK/Vector.h>
+#include <LibMedia/MediaStream.h>
+
+namespace Media {
+
+enum class CachedRangeChange : u8 {
+ Start = 1 << 0,
+ End = 1 << 1,
+};
+
+AK_ENUM_BITWISE_OPERATORS(CachedRangeChange);
+
+struct CachedByteRange {
+ size_t byte_start { 0 };
+ size_t byte_end { 0 };
+
+ constexpr CachedByteRange(size_t start, size_t end)
+ : byte_start(start)
+ , byte_end(end)
+ {
+ }
+};
+
+// Keeps one entry per buffered byte range from one scan to the next, so that a scan only looks again at the ends
+// a range grew or shrank at.
+template<typename CachedRange>
+class CachedByteRanges {
+public:
+ // Reconciles the incoming byte ranges with the cached ranges in lockstep; both are sorted by position.
+ template<typename OnChanged>
+ void update(Vector<MediaStream::ByteRange> const& byte_ranges, OnChanged on_changed)
+ {
+ size_t cached_index = 0;
+ size_t byte_index = 0;
+ while (byte_index < byte_ranges.size()) {
+ auto const& byte_range = byte_ranges[byte_index];
+ if (cached_index < m_ranges.size()) {
+ auto& cached = m_ranges[cached_index];
+ // If the cached range doesn't have the same start byte as the incoming range, then we need to update
+ // the start of the cached range if possible. If that's not possible, then we discard the cached range
+ // if it's earlier, or insert a new one if it's later.
+ if (cached.byte_start != byte_range.start) {
+ if (cached.byte_end == byte_range.end) {
+ cached.byte_start = byte_range.start;
+ on_changed(cached, CachedRangeChange::Start);
+ cached_index++;
+ byte_index++;
+ continue;
+ }
+ if (cached.byte_end < byte_range.end) {
+ cached = CachedRange { byte_range.start, byte_range.end };
+ on_changed(cached, CachedRangeChange::Start | CachedRangeChange::End);
+ cached_index++;
+ byte_index++;
+ continue;
+ }
+ if (cached.byte_start < byte_range.start) {
+ m_ranges.remove(cached_index);
+ } else {
+ m_ranges.insert(cached_index, CachedRange { byte_range.start, byte_range.end });
+ auto& inserted = m_ranges[cached_index];
+ on_changed(inserted, CachedRangeChange::Start | CachedRangeChange::End);
+ cached_index++;
+ byte_index++;
+ }
+ continue;
+ }
+
+ // If we're here, the cached range's start matches the incoming one, so we only need to update the end.
+ if (cached.byte_end != byte_range.end) {
+ cached.byte_end = byte_range.end;
+ on_changed(cached, CachedRangeChange::End);
+ }
+ cached_index++;
+ byte_index++;
+ } else {
+ // We have new byte ranges on the end with no equivalent cached ranges, append them.
+ m_ranges.append(CachedRange { byte_range.start, byte_range.end });
+ auto& appended = m_ranges.last();
+ on_changed(appended, CachedRangeChange::Start | CachedRangeChange::End);
+ cached_index++;
+ byte_index++;
+ }
+ }
+
+ // Remove any leftover cached ranges past the end.
+ if (cached_index < m_ranges.size())
+ m_ranges.remove(cached_index, m_ranges.size() - cached_index);
+ }
+
+ Vector<CachedRange> const& ranges() const { return m_ranges; }
+
+private:
+ Vector<CachedRange> m_ranges;
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/FLAC/FLACDemuxer.cpp b/Libraries/LibMedia/Containers/FLAC/FLACDemuxer.cpp
new file mode 100644
index 00000000000..5280d8a66a1
--- /dev/null
+++ b/Libraries/LibMedia/Containers/FLAC/FLACDemuxer.cpp
@@ -0,0 +1,336 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Checked.h>
+#include <AK/Math.h>
+#include <LibMedia/Codecs/FLAC.h>
+#include <LibMedia/Containers/FLAC/FLACDemuxer.h>
+#include <LibMediaCodecs/CodedFrame.h>
+
+namespace Media::FLAC {
+
+// Probing is capped so that a stream whose frames defy every estimate still gets walked to its target.
+static constexpr size_t MAXIMUM_SEEK_PROBE_COUNT = 16;
+// A scan looks for a frame within this distance of a range's ends, which bounds the work a range of junk costs on
+// every change to the buffered data. Any frame of the format heads within it.
+static constexpr size_t SCAN_WINDOW_BYTE_COUNT = 4 * MiB;
+
+bool FLACDemuxer::supports_container_mime_type(ContainerMimeType mime_type)
+{
+ return mime_type.container_id == ContainerID::FLAC && mime_type.media_type == ContainerMediaType::Audio;
+}
+
+bool FLACDemuxer::supports_codec_in_container(ContainerID container_id, CodecID codec_id)
+{
+ return container_id == ContainerID::FLAC && codec_id == CodecID::FLAC;
+}
+
+static Track create_track(Reader const& reader)
+{
+ auto const& stream_info = reader.stream_info();
+ Track track { TrackType::Audio, 0, Track::Kind::Main, {}, {} };
+ track.set_audio_data({ .sample_specification = Audio::SampleSpecification(stream_info.sample_rate, Codecs::FLAC::channel_map(stream_info.channel_count)) });
+ track.set_parsed_codec(ParsedCodec { CodecID::FLAC });
+ return track;
+}
+
+DecoderErrorOr<NonnullRefPtr<Demuxer>> FLACDemuxer::from_stream(NonnullRefPtr<MediaStream> const& stream)
+{
+ auto reader = TRY(Reader::from_stream(stream->create_cursor()));
+ auto demuxer = make_ref_counted<FLACDemuxer>(stream, reader, create_track(reader));
+ demuxer->start_buffered_scan_thread();
+ return demuxer;
+}
+
+FLACDemuxer::FLACDemuxer(NonnullRefPtr<MediaStream> const& stream, Reader reader, Track track)
+ : m_stream(stream)
+ , m_reader(move(reader))
+ , m_track(move(track))
+{
+}
+
+FLACDemuxer::~FLACDemuxer()
+{
+ if (m_buffered_scan_thread != nullptr)
+ m_buffered_scan_thread->shutdown();
+}
+
+void FLACDemuxer::start_buffered_scan_thread()
+{
+ auto scan_cursor = m_stream->create_cursor();
+ scan_cursor->set_is_blocking(false);
+
+ DemuxerScanState initial_state;
+ initial_state.duration = m_reader.duration();
+
+ m_buffered_scan_thread = DemuxerScanThread<BufferedScanPayload>::start(m_stream, move(initial_state),
+ BufferedScanPayload {
+ .scanner = FrameIterator { move(scan_cursor), m_reader.frame_sync(), m_reader.first_frame_position(), FrameIterator::Resynchronize::Yes },
+ .scanned_ranges = {},
+ .anchors = m_scanned_anchors,
+ },
+ [reader = m_reader](MediaStream::Availability const& availability, BufferedScanPayload& payload) {
+ auto const& stream_info = reader.stream_info();
+ payload.scanned_ranges.update(availability.byte_ranges, [&](ScannedByteRange& range, CachedRangeChange change) {
+ auto scan_start = max(range.byte_start, reader.first_frame_position());
+ auto reaches_stream_end = availability.expected_size.has_value() && range.byte_end >= *availability.expected_size;
+ if (has_flag(change, CachedRangeChange::Start) || !range.first_frame.has_value()) {
+ range.first_frame = {};
+ payload.scanner.set_position(scan_start);
+ auto resynced = payload.scanner.resync_forward(min(range.byte_end, scan_start + SCAN_WINDOW_BYTE_COUNT));
+ if (!resynced.is_error() && resynced.value()) {
+ if (auto frame = payload.scanner.read_next_frame(); !frame.is_error())
+ range.first_frame = SeekAnchor { frame.value().header.position, frame.value().header.sample_number };
+ }
+ }
+ if (has_flag(change, CachedRangeChange::End) || !range.end.has_value()) {
+ range.end = {};
+ auto search_start = max(scan_start, range.byte_end > SCAN_WINDOW_BYTE_COUNT ? range.byte_end - SCAN_WINDOW_BYTE_COUNT : 0);
+ // The last frame of a range is complete only when the stream ends with it.
+ if (auto header = payload.scanner.find_last_header_before(range.byte_end, search_start); header.has_value()) {
+ if (reaches_stream_end)
+ range.end = SeekAnchor { range.byte_end, header->sample_number + header->block_size };
+ else
+ range.end = SeekAnchor { header->position, header->sample_number };
+ }
+ // A sample past the stream's last is a false sync code.
+ if (stream_info.total_sample_count != 0 && range.end.has_value() && range.end->sample > stream_info.total_sample_count)
+ range.end = {};
+ }
+ });
+
+ auto time_of = [&](u64 sample) { return AK::Duration::from_time_units(AK::clamp_to<i64>(sample), 1, stream_info.sample_rate); };
+ BufferedRangesScan scan;
+ Vector<SeekAnchor> anchors;
+ for (auto const& range : payload.scanned_ranges.ranges()) {
+ auto has_samples = range.first_frame.has_value() && range.end.has_value() && range.first_frame->sample < range.end->sample;
+ scan.last_byte_range_has_samples = has_samples;
+ if (!has_samples)
+ continue;
+ scan.time_ranges.add_range(time_of(range.first_frame->sample), time_of(range.end->sample));
+ anchors.append(*range.first_frame);
+ anchors.append(*range.end);
+ }
+ {
+ MutexLocker locker { payload.anchors->mutex };
+ payload.anchors->anchors = move(anchors);
+ }
+ return DemuxerScanState::create_from_track_scans({ move(scan) }, reader.duration(), availability.closing_bytes_are_available());
+ });
+}
+
+FLACDemuxer::TrackStatus& FLACDemuxer::track_status()
+{
+ MutexLocker locker { m_track_status_mutex };
+ VERIFY(m_track_status.has_value());
+ return *m_track_status;
+}
+
+DecoderErrorOr<void> FLACDemuxer::create_context_for_track(Track const& track)
+{
+ VERIFY(track == m_track);
+
+ auto cursor = m_stream->create_cursor();
+ cursor->set_is_blocking(true);
+
+ MutexLocker locker { m_track_status_mutex };
+ VERIFY(!m_track_status.has_value());
+ m_track_status = TrackStatus { FrameIterator { move(cursor), m_reader.frame_sync(), m_reader.first_frame_position(), FrameIterator::Resynchronize::Yes }, true };
+ return {};
+}
+
+DecoderErrorOr<Vector<Track>> FLACDemuxer::get_tracks_for_type(TrackType type)
+{
+ Vector<Track> tracks;
+ if (type == TrackType::Audio)
+ tracks.append(m_track);
+ return tracks;
+}
+
+DecoderErrorOr<Optional<Track>> FLACDemuxer::get_preferred_track_for_type(TrackType type)
+{
+ if (type != TrackType::Audio)
+ return Optional<Track> {};
+ return Optional<Track> { m_track };
+}
+
+DecoderErrorOr<CodedFrame> FLACDemuxer::get_next_sample_for_track(Track const& track)
+{
+ VERIFY(track == m_track);
+ auto& status = track_status();
+ auto sample_rate = m_reader.stream_info().sample_rate;
+
+ auto frame = TRY(status.iterator.read_next_frame());
+
+ Optional<FixedArray<u8>> codec_configuration;
+ if (status.needs_codec_configuration) {
+ status.needs_codec_configuration = false;
+ codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(m_reader.codec_initialization_data()));
+ }
+
+ auto timestamp = AK::Duration::from_time_units(AK::clamp_to<i64>(frame.header.sample_number), 1, sample_rate);
+ auto duration = AK::Duration::from_time_units(frame.header.block_size, 1, sample_rate);
+ return CodedFrame(CodecID::FLAC, timestamp, timestamp, duration, FrameFlags::Keyframe, move(frame.data), move(codec_configuration));
+}
+
+AK::Duration FLACDemuxer::select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode)
+{
+ return target;
+}
+
+static DecoderErrorOr<Optional<FrameIterator::Frame>> read_frame_at_or_after(FrameIterator const& iterator, size_t position)
+{
+ FrameIterator probe = iterator;
+ probe.set_position(position);
+ if (!TRY(probe.resync_forward()))
+ return Optional<FrameIterator::Frame> {};
+ auto frame = probe.read_next_frame();
+ if (frame.is_error()) {
+ if (frame.error().category() == DecoderErrorCategory::EndOfStream)
+ return Optional<FrameIterator::Frame> {};
+ return frame.release_error();
+ }
+ return frame.release_value();
+}
+
+DecoderErrorOr<size_t> FLACDemuxer::find_frame_position_for_sample(FrameIterator& iterator, u64 target_sample)
+{
+ auto const& stream_info = m_reader.stream_info();
+ auto stream_size = m_stream->expected_size();
+
+ // The anchors are the frames known to lie closest to the target on either side.
+ SeekAnchor low { m_reader.first_frame_position(), 0 };
+ Optional<SeekAnchor> high;
+ auto consider = [&](SeekAnchor anchor) {
+ if (stream_size.has_value() && anchor.byte > *stream_size)
+ return;
+ if (anchor.sample <= target_sample) {
+ if (anchor.sample >= low.sample)
+ low = anchor;
+ } else if (!high.has_value() || anchor.sample < high->sample) {
+ high = anchor;
+ }
+ };
+ if (stream_size.has_value() && stream_info.total_sample_count != 0)
+ consider({ static_cast<size_t>(*stream_size), stream_info.total_sample_count });
+ for (auto const& point : m_reader.seek_points()) {
+ Checked<size_t> byte = m_reader.first_frame_position();
+ byte += point.byte_offset;
+ if (!byte.has_overflow())
+ consider({ byte.value(), point.sample_number });
+ }
+ {
+ MutexLocker locker { m_scanned_anchors->mutex };
+ for (auto const& anchor : m_scanned_anchors->anchors)
+ consider(anchor);
+ }
+ if (high.has_value() && high->byte <= low.byte)
+ high = {};
+
+ u64 underestimate_target_by = stream_info.sample_rate / 2;
+ Optional<FrameIterator::Frame> overshot_frame;
+ for (size_t probe = 0; probe < MAXIMUM_SEEK_PROBE_COUNT && target_sample - low.sample > underestimate_target_by; probe++) {
+ if (high.has_value() && high->byte <= low.byte + 1)
+ break;
+ auto aim = target_sample - underestimate_target_by;
+ size_t guess;
+ if (overshot_frame.has_value()) {
+ // If we overshot the target, jump back based on the found frame's bitrate.
+ auto const& header = overshot_frame->header;
+ auto bytes_per_sample = static_cast<double>(overshot_frame->data.size()) / header.block_size;
+ auto step_back = static_cast<size_t>(static_cast<double>(header.sample_number - aim) * bytes_per_sample);
+ guess = header.position > step_back ? header.position - step_back : 0;
+ } else if (high.has_value() && high->sample > low.sample) {
+ auto sample_fraction = static_cast<double>(aim - low.sample) / static_cast<double>(high->sample - low.sample);
+ guess = low.byte + static_cast<size_t>(static_cast<double>(high->byte - low.byte) * sample_fraction);
+ } else {
+ break;
+ }
+ guess = clamp(guess, low.byte + 1, high.has_value() ? high->byte - 1 : NumericLimits<size_t>::max());
+
+ auto frame = TRY(read_frame_at_or_after(iterator, guess));
+ if (!frame.has_value())
+ break;
+
+ auto const& header = frame->header;
+ if (header.sample_number <= target_sample && target_sample < header.sample_number + header.block_size)
+ return header.position;
+ if (header.sample_number < target_sample) {
+ low = SeekAnchor { frame->end_position(), header.sample_number + header.block_size };
+ overshot_frame = {};
+ } else {
+ high = SeekAnchor { header.position, header.sample_number };
+ overshot_frame = frame.release_value();
+ underestimate_target_by *= 2;
+ }
+ }
+
+ FrameIterator walker = iterator;
+ walker.set_position(low.byte);
+ while (true) {
+ auto frame = walker.read_next_frame();
+ if (frame.is_error()) {
+ if (frame.error().category() == DecoderErrorCategory::EndOfStream)
+ return walker.position();
+ return frame.release_error();
+ }
+ if (frame.value().header.sample_number + frame.value().header.block_size > target_sample)
+ return frame.value().header.position;
+ }
+}
+
+DecoderErrorOr<DemuxerSeekResult> FLACDemuxer::seek_to_most_recent_keyframe(Track const& track, AK::Duration timestamp, DemuxerSeekOptions options)
+{
+ VERIFY(track == m_track);
+ auto& status = track_status();
+
+ if (has_flag(options, DemuxerSeekOptions::NeedCodecConfiguration))
+ status.needs_codec_configuration = true;
+
+ auto target_sample = static_cast<u64>(max<i64>(0, timestamp.to_time_units(1, m_reader.stream_info().sample_rate)));
+ status.iterator.set_position(TRY(find_frame_position_for_sample(status.iterator, target_sample)));
+ return DemuxerSeekResult::MovedPosition;
+}
+
+DecoderErrorOr<AK::Duration> FLACDemuxer::total_duration()
+{
+ return m_reader.duration();
+}
+
+DecoderErrorOr<AK::Duration> FLACDemuxer::duration_of_track(Track const&)
+{
+ return total_duration();
+}
+
+DemuxerScanState const& FLACDemuxer::scan_state() const
+{
+ return m_buffered_scan_thread->main_thread_state();
+}
+
+void FLACDemuxer::set_scan_state_change_handler(ScanStateChangeHandler handler)
+{
+ m_buffered_scan_thread->set_change_handler([handler = move(handler)] {
+ if (handler)
+ handler(TimeRanges {});
+ });
+}
+
+void FLACDemuxer::set_blocking_reads_aborted_for_track(Track const&)
+{
+ track_status().iterator.cursor().abort();
+}
+
+void FLACDemuxer::reset_blocking_reads_aborted_for_track(Track const&)
+{
+ track_status().iterator.cursor().reset_abort();
+}
+
+void FLACDemuxer::set_read_blocked_change_handler_for_track(Track const&, ReadBlockedChangeHandler handler)
+{
+ track_status().iterator.cursor().set_blocked_change_handler(move(handler));
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/FLAC/FLACDemuxer.h b/Libraries/LibMedia/Containers/FLAC/FLACDemuxer.h
new file mode 100644
index 00000000000..cd726791692
--- /dev/null
+++ b/Libraries/LibMedia/Containers/FLAC/FLACDemuxer.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Mutex.h>
+#include <LibMedia/ContainerID.h>
+#include <LibMedia/Containers/CachedByteRanges.h>
+#include <LibMedia/Containers/FLAC/Reader.h>
+#include <LibMedia/Demuxer.h>
+#include <LibMedia/DemuxerScanThread.h>
+#include <LibMedia/Export.h>
+#include <LibMedia/Forward.h>
+
+namespace Media::FLAC {
+
+class MEDIA_API FLACDemuxer 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);
+
+ FLACDemuxer(NonnullRefPtr<MediaStream> const&, Reader, Track);
+ ~FLACDemuxer();
+
+ 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 SeekAnchor {
+ size_t byte { 0 };
+ u64 sample { 0 };
+ };
+
+ // Frame positions the scan has seen, so that a seek into buffered data probes close by and fetches nothing.
+ struct ScannedAnchors : public AtomicRefCounted<ScannedAnchors> {
+ Mutex mutex;
+ Vector<SeekAnchor> anchors;
+ };
+
+ struct ScannedByteRange : public CachedByteRange {
+ using CachedByteRange::CachedByteRange;
+
+ Optional<SeekAnchor> first_frame;
+ Optional<SeekAnchor> end;
+ };
+
+ struct BufferedScanPayload {
+ FrameIterator scanner;
+ CachedByteRanges<ScannedByteRange> scanned_ranges;
+ NonnullRefPtr<ScannedAnchors> anchors;
+ };
+
+ struct TrackStatus {
+ FrameIterator iterator;
+ bool needs_codec_configuration { true };
+ };
+
+ void start_buffered_scan_thread();
+ TrackStatus& track_status();
+ DecoderErrorOr<size_t> find_frame_position_for_sample(FrameIterator&, u64 target_sample);
+
+ NonnullRefPtr<MediaStream> m_stream;
+ Reader m_reader;
+ Track m_track;
+ RefPtr<DemuxerScanThread<BufferedScanPayload>> m_buffered_scan_thread;
+ NonnullRefPtr<ScannedAnchors> m_scanned_anchors { make_ref_counted<ScannedAnchors>() };
+ Mutex m_track_status_mutex;
+ Optional<TrackStatus> m_track_status;
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/FLAC/Reader.cpp b/Libraries/LibMedia/Containers/FLAC/Reader.cpp
new file mode 100644
index 00000000000..1b535e8c282
--- /dev/null
+++ b/Libraries/LibMedia/Containers/FLAC/Reader.cpp
@@ -0,0 +1,345 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Math.h>
+#include <LibMedia/Codecs/FLAC.h>
+#include <LibMedia/Containers/FLAC/Reader.h>
+#include <LibMedia/Containers/ID3.h>
+#include <LibMediaCodecs/BitReader.h>
+
+namespace Media::FLAC {
+
+static constexpr size_t SCAN_CHUNK_SIZE = 4 * KiB;
+// No frame of the largest block, channel count and bit depth the format allows comes near this.
+static constexpr size_t MAXIMUM_FRAME_SIZE = 4 * MiB;
+// Junk between the metadata and the first frame is covered within this distance.
+static constexpr size_t MAXIMUM_SYNC_SEARCH_BYTE_COUNT = 64 * KiB;
+static constexpr size_t STREAM_INFO_BLOCK_SIZE = 34;
+static constexpr size_t SEEK_POINT_SIZE = 18;
+// A seek point a second for eighteen hours; a table claiming more is not read any further.
+static constexpr size_t MAXIMUM_SEEK_POINT_COUNT = 64 * KiB;
+static constexpr u64 PLACEHOLDER_SEEK_POINT_SAMPLE_NUMBER = NumericLimits<u64>::max();
+static constexpr size_t ID3_VERSION_1_TAG_SIZE = 128;
+
+namespace {
+
+enum class MetadataBlockType : u8 {
+ StreamInfo = 0,
+ SeekTable = 3,
+};
+
+}
+
+DecoderErrorOr<Optional<FrameHeader>> FrameIterator::parse_header_at(size_t position)
+{
+ if (m_cursor->seek_to_position(position).is_error())
+ return Optional<FrameHeader> {};
+ auto frame_info = TRY(Codecs::FLAC::parse_frame_header(*m_cursor, m_sync.sync_code, m_sync.fixed_block_size));
+ if (!frame_info.has_value())
+ return Optional<FrameHeader> {};
+ return FrameHeader { position, m_cursor->position() - position, frame_info->sample_number, frame_info->block_size };
+}
+
+DecoderErrorOr<Optional<FrameHeader>> FrameIterator::find_header_at_or_after(size_t position, size_t bound)
+{
+ u8 sync_low_byte = m_sync.sync_code & 0xFF;
+ // The chunks overlap by a byte so that a sync code split between two is seen.
+ Array<u8, SCAN_CHUNK_SIZE + 1> chunk;
+ auto chunk_start = position;
+ while (chunk_start + 1 < bound) {
+ auto chunk_size = min(chunk.size(), bound - chunk_start);
+ TRY(m_cursor->seek_to_position(chunk_start));
+ auto read_count = TRY(m_cursor->read_into(chunk.span().trim(chunk_size)));
+ if (read_count < 2)
+ return Optional<FrameHeader> {};
+ for (size_t i = 0; i + 1 < read_count; i++) {
+ if (chunk[i] != 0xFF || chunk[i + 1] != sync_low_byte)
+ continue;
+ if (auto header = TRY(parse_header_at(chunk_start + i)); header.has_value())
+ return header;
+ }
+ chunk_start += read_count - 1;
+ }
+ return Optional<FrameHeader> {};
+}
+
+DecoderErrorOr<Optional<FrameHeader>> FrameIterator::find_header_before(size_t bound, size_t lower_bound)
+{
+ u8 sync_low_byte = m_sync.sync_code & 0xFF;
+ Array<u8, SCAN_CHUNK_SIZE + 1> chunk;
+ auto chunk_end = bound;
+ while (chunk_end > lower_bound + 1) {
+ auto chunk_start = chunk_end - lower_bound > chunk.size() ? chunk_end - chunk.size() : lower_bound;
+ auto chunk_size = chunk_end - chunk_start;
+ TRY(m_cursor->seek_to_position(chunk_start));
+ auto read_count = TRY(m_cursor->read_into(chunk.span().trim(chunk_size)));
+ if (read_count != chunk_size)
+ return Optional<FrameHeader> {};
+ for (size_t i = chunk_size - 1; i-- > 0;) {
+ if (chunk[i] != 0xFF || chunk[i + 1] != sync_low_byte)
+ continue;
+ auto header = TRY(parse_header_at(chunk_start + i));
+ if (header.has_value() && header->position + header->byte_size <= bound)
+ return header;
+ }
+ if (chunk_start == lower_bound)
+ break;
+ chunk_end = chunk_start + 1;
+ }
+ return Optional<FrameHeader> {};
+}
+
+// A damaged frame fails its CRC, so the frame after it is told by its place in the sequence instead, with the frame
+// after that confirming it.
+DecoderErrorOr<bool> FrameIterator::frame_follows(FrameHeader const& header, FrameHeader const& candidate)
+{
+ if (candidate.sample_number <= header.sample_number)
+ return false;
+ if (candidate.sample_number == header.sample_number + header.block_size)
+ return true;
+ auto following = TRY(find_header_at_or_after(candidate.position + candidate.byte_size, candidate.position + MAXIMUM_FRAME_SIZE));
+ return following.has_value() && following->sample_number == candidate.sample_number + candidate.block_size;
+}
+
+DecoderErrorOr<bool> FrameIterator::resync_forward(size_t bound)
+{
+ auto header_or_error = find_header_at_or_after(m_position, bound);
+ if (header_or_error.is_error()) {
+ if (header_or_error.error().category() == DecoderErrorCategory::EndOfStream)
+ return false;
+ return header_or_error.release_error();
+ }
+ if (!header_or_error.value().has_value())
+ return false;
+ m_position = header_or_error.value()->position;
+ return true;
+}
+
+DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::read_frame_at(FrameHeader const& header)
+{
+ u8 sync_low_byte = m_sync.sync_code & 0xFF;
+ auto frame_start = header.position;
+ auto limit = frame_start + MAXIMUM_FRAME_SIZE;
+
+ ByteBuffer frame_bytes;
+ // The next frame's header cannot begin inside this frame's header or its two CRC bytes.
+ auto scan_offset = max<size_t>(header.byte_size, 2);
+ while (true) {
+ auto read_position = frame_start + frame_bytes.size();
+ if (read_position >= limit)
+ return Optional<Frame> {};
+
+ auto chunk_size = min<size_t>(SCAN_CHUNK_SIZE, limit - read_position);
+ auto scanned_size = frame_bytes.size();
+ DECODER_TRY_ALLOC(frame_bytes.try_resize(scanned_size + chunk_size));
+ TRY(m_cursor->seek_to_position(read_position));
+ auto read_result = m_cursor->read_into(frame_bytes.span().slice(scanned_size));
+ if (read_result.is_error()) {
+ if (read_result.error().category() != DecoderErrorCategory::EndOfStream || scanned_size < header.byte_size)
+ return read_result.release_error();
+ frame_bytes.trim(scanned_size, true);
+ break;
+ }
+ auto read_count = read_result.value();
+ frame_bytes.trim(scanned_size + read_count, true);
+ if (read_count == 0)
+ return Optional<Frame> {};
+
+ for (size_t i = scan_offset; i + 1 < frame_bytes.size(); i++) {
+ if (frame_bytes[i] != 0xFF || frame_bytes[i + 1] != sync_low_byte)
+ continue;
+ auto candidate = TRY(parse_header_at(frame_start + i));
+ if (!candidate.has_value())
+ continue;
+ u16 frame_crc = (frame_bytes[i - 2] << 8) | frame_bytes[i - 1];
+ auto frame_is_intact = Codecs::FLAC::compute_frame_crc(frame_bytes.span().trim(i - 2)) == frame_crc;
+ if (!frame_is_intact && !TRY(frame_follows(header, *candidate)))
+ continue;
+ return Frame { header, DECODER_TRY_ALLOC(FixedArray<u8>::create(frame_bytes.span().trim(i))) };
+ }
+ scan_offset = frame_bytes.size() - 1;
+ }
+
+ // The last frame of a stream runs to its end, less a tag written after the audio.
+ if (frame_bytes.size() >= header.byte_size + ID3_VERSION_1_TAG_SIZE) {
+ auto tag = frame_bytes.span().slice(frame_bytes.size() - ID3_VERSION_1_TAG_SIZE);
+ if (StringView { tag.data(), 3 } == "TAG"sv)
+ frame_bytes.trim(frame_bytes.size() - ID3_VERSION_1_TAG_SIZE, true);
+ }
+ return Frame { header, DECODER_TRY_ALLOC(FixedArray<u8>::create(frame_bytes.span())) };
+}
+
+Optional<FrameHeader> FrameIterator::find_last_header_before(size_t bound, size_t lower_bound)
+{
+ auto header_or_error = find_header_before(bound, lower_bound);
+ if (header_or_error.is_error())
+ return {};
+ return header_or_error.release_value();
+}
+
+DecoderErrorOr<FrameIterator::Frame> FrameIterator::read_next_frame()
+{
+ auto position = m_position;
+ while (true) {
+ Optional<Frame> frame;
+ if (auto header = TRY(parse_header_at(position)); header.has_value())
+ frame = TRY(read_frame_at(*header));
+ if (frame.has_value()) {
+ m_position = frame->end_position();
+ return frame.release_value();
+ }
+
+ // No frame heads the position, or what heads it has no end within a frame's reach, so it was not a header.
+ if (m_resynchronize == Resynchronize::No)
+ return DecoderError::corrupted("No FLAC frame at the expected position"sv);
+ auto next_header = TRY(find_header_at_or_after(position + 1, NumericLimits<size_t>::max()));
+ if (!next_header.has_value())
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "End of stream"sv);
+ position = next_header->position;
+ }
+}
+
+static DecoderErrorOr<StreamInfo> parse_stream_info(ReadonlyBytes bytes)
+{
+ BitReader reader { bytes };
+ StreamInfo stream_info;
+ stream_info.minimum_block_size = reader.read_bits<u16>(16);
+ stream_info.maximum_block_size = reader.read_bits<u16>(16);
+ stream_info.minimum_frame_size = reader.read_bits<u32>(24);
+ stream_info.maximum_frame_size = reader.read_bits<u32>(24);
+ stream_info.sample_rate = reader.read_bits<u32>(20);
+ stream_info.channel_count = reader.read_bits<u8>(3) + 1;
+ stream_info.bits_per_sample = reader.read_bits<u8>(5) + 1;
+ stream_info.total_sample_count = reader.read_bits<u64>(36);
+ if (stream_info.sample_rate == 0 || stream_info.maximum_block_size == 0)
+ return DecoderError::corrupted("FLAC STREAMINFO declares no sample rate or block size"sv);
+ return stream_info;
+}
+
+// Finds the first frame, which follows the metadata directly unless a writer left junk between them.
+static DecoderErrorOr<FrameHeader> find_first_frame(MediaStreamCursor& cursor, size_t position, StreamInfo const& stream_info, FrameSync& frame_sync)
+{
+ auto header_at = [&](size_t candidate) -> DecoderErrorOr<Optional<FrameHeader>> {
+ if (cursor.seek_to_position(candidate).is_error())
+ return Optional<FrameHeader> {};
+ auto sync_code_or_error = cursor.read_value<u16>();
+ if (sync_code_or_error.is_error() || !Codecs::FLAC::is_sync_code(sync_code_or_error.value()))
+ return Optional<FrameHeader> {};
+ auto sync_code = sync_code_or_error.value();
+ u16 fixed_block_size = (sync_code & 1) != 0 ? 0 : stream_info.maximum_block_size;
+ if (cursor.seek_to_position(candidate).is_error())
+ return Optional<FrameHeader> {};
+ auto frame_info = TRY(Codecs::FLAC::parse_frame_header(cursor, sync_code, fixed_block_size));
+ if (!frame_info.has_value())
+ return Optional<FrameHeader> {};
+ frame_sync = FrameSync { sync_code, fixed_block_size };
+ return FrameHeader { candidate, cursor.position() - candidate, frame_info->sample_number, frame_info->block_size };
+ };
+
+ if (auto header = TRY(header_at(position)); header.has_value())
+ return header.release_value();
+
+ Array<u8, SCAN_CHUNK_SIZE + 1> chunk;
+ auto chunk_start = position;
+ auto bound = position + MAXIMUM_SYNC_SEARCH_BYTE_COUNT;
+ while (chunk_start + 1 < bound) {
+ TRY(cursor.seek_to_position(chunk_start));
+ auto read_count = TRY(cursor.read_into(chunk.span().trim(min(chunk.size(), bound - chunk_start))));
+ if (read_count < 2)
+ break;
+ for (size_t i = 0; i + 1 < read_count; i++) {
+ if (chunk[i] != 0xFF || (chunk[i + 1] & 0xFE) != 0xF8)
+ continue;
+ if (auto header = TRY(header_at(chunk_start + i)); header.has_value())
+ return header.release_value();
+ }
+ chunk_start += read_count - 1;
+ }
+ return DecoderError::corrupted("No FLAC frame follows the metadata"sv);
+}
+
+DecoderErrorOr<Reader> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
+{
+ size_t position = 0;
+ Array<u8, ID3::VERSION_2_HEADER_SIZE> tag_header;
+ TRY(cursor->seek_to_position(0));
+ auto tag_header_read = cursor->read_into(tag_header.span());
+ if (tag_header_read.is_error() || tag_header_read.value() != tag_header.size())
+ return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Stream is too short to be FLAC"sv);
+ if (auto tag_size = ID3::version_2_tag_size(tag_header); tag_size.has_value())
+ position = *tag_size;
+
+ Array<u8, 4> marker;
+ TRY(cursor->seek_to_position(position));
+ auto marker_read = cursor->read_into(marker.span());
+ if (marker_read.is_error() || marker_read.value() != marker.size() || StringView { marker.data(), marker.size() } != "fLaC"sv)
+ return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Stream does not begin with the FLAC marker"sv);
+ position += marker.size();
+
+ ByteBuffer codec_initialization_data;
+ DECODER_TRY_ALLOC(codec_initialization_data.try_append("fLaC"sv.bytes()));
+ Optional<StreamInfo> stream_info;
+ Vector<SeekPoint> seek_points;
+ while (true) {
+ TRY(cursor->seek_to_position(position));
+ auto block_header = TRY(cursor->read_value<u32>());
+ auto is_last_block = (block_header >> 31) != 0;
+ auto block_type = static_cast<MetadataBlockType>((block_header >> 24) & 0x7F);
+ size_t block_size = block_header & 0xFFFFFF;
+ auto block_body = position + sizeof(u32);
+
+ if (!stream_info.has_value()) {
+ if (block_type != MetadataBlockType::StreamInfo || block_size != STREAM_INFO_BLOCK_SIZE)
+ return DecoderError::corrupted("FLAC stream does not begin with STREAMINFO"sv);
+ Array<u8, STREAM_INFO_BLOCK_SIZE> block;
+ TRY(cursor->read_until_filled(block.span()));
+ stream_info = TRY(parse_stream_info(block));
+ // The decoder's copy stands alone, so it is the last block.
+ DECODER_TRY_ALLOC(codec_initialization_data.try_append(Array<u8, 4> { 0x80, 0x00, 0x00, STREAM_INFO_BLOCK_SIZE }.span()));
+ DECODER_TRY_ALLOC(codec_initialization_data.try_append(block.span()));
+ } else if (block_type == MetadataBlockType::SeekTable && seek_points.is_empty()) {
+ if (block_size % SEEK_POINT_SIZE != 0)
+ return DecoderError::corrupted("FLAC SEEKTABLE has a partial seek point"sv);
+ auto seek_point_count = min(block_size / SEEK_POINT_SIZE, MAXIMUM_SEEK_POINT_COUNT);
+ for (size_t i = 0; i < seek_point_count; i++) {
+ auto sample_number = TRY(cursor->read_value<u64>());
+ auto byte_offset = TRY(cursor->read_value<u64>());
+ TRY(cursor->read_value<u16>()); // The samples in the frame, which the frame itself tells.
+ if (sample_number != PLACEHOLDER_SEEK_POINT_SAMPLE_NUMBER)
+ DECODER_TRY_ALLOC(seek_points.try_append({ sample_number, byte_offset }));
+ }
+ }
+
+ position = block_body + block_size;
+ if (is_last_block)
+ break;
+ }
+
+ FrameSync frame_sync { 0xFFF8, stream_info->maximum_block_size };
+ auto first_frame_position = position;
+ auto first_frame = find_first_frame(*cursor, position, *stream_info, frame_sync);
+ if (!first_frame.is_error())
+ first_frame_position = first_frame.value().position;
+ else if (first_frame.error().category() != DecoderErrorCategory::EndOfStream)
+ return first_frame.release_error();
+ return Reader { *stream_info, frame_sync, first_frame_position, move(seek_points), move(codec_initialization_data) };
+}
+
+Reader::Reader(StreamInfo stream_info, FrameSync frame_sync, size_t first_frame_position, Vector<SeekPoint> seek_points, ByteBuffer codec_initialization_data)
+ : m_stream_info(stream_info)
+ , m_frame_sync(frame_sync)
+ , m_first_frame_position(first_frame_position)
+ , m_seek_points(move(seek_points))
+ , m_codec_initialization_data(move(codec_initialization_data))
+{
+}
+
+AK::Duration Reader::duration() const
+{
+ return AK::Duration::from_time_units(AK::clamp_to<i64>(m_stream_info.total_sample_count), 1, m_stream_info.sample_rate);
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/FLAC/Reader.h b/Libraries/LibMedia/Containers/FLAC/Reader.h
new file mode 100644
index 00000000000..b0d00280c2e
--- /dev/null
+++ b/Libraries/LibMedia/Containers/FLAC/Reader.h
@@ -0,0 +1,127 @@
+/*
+ * 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/Vector.h>
+#include <LibMedia/Export.h>
+#include <LibMedia/MediaStream.h>
+#include <LibMediaCodecs/DecoderError.h>
+
+namespace Media::FLAC {
+
+struct StreamInfo {
+ u16 minimum_block_size { 0 };
+ u16 maximum_block_size { 0 };
+ u32 minimum_frame_size { 0 };
+ u32 maximum_frame_size { 0 };
+ u32 sample_rate { 0 };
+ u8 channel_count { 0 };
+ u8 bits_per_sample { 0 };
+ // Zero when the stream does not say.
+ u64 total_sample_count { 0 };
+};
+
+struct SeekPoint {
+ u64 sample_number { 0 };
+ // From the first frame.
+ u64 byte_offset { 0 };
+};
+
+// What telling the frames of a stream apart takes.
+struct FrameSync {
+ u16 sync_code { 0 };
+ // Zero for a stream whose frames vary in size and number their first sample instead.
+ u16 fixed_block_size { 0 };
+};
+
+struct FrameHeader {
+ size_t position { 0 };
+ size_t byte_size { 0 };
+ u64 sample_number { 0 };
+ u16 block_size { 0 };
+};
+
+// Frames carry no size, so a frame ends where the next one begins, which the CRC every frame ends with confirms.
+class MEDIA_API FrameIterator {
+public:
+ struct Frame {
+ FrameHeader header;
+ FixedArray<u8> data;
+
+ size_t end_position() const { return header.position + data.size(); }
+ };
+
+ // Whether to look for the next frame upon finding none at the position.
+ enum class Resynchronize : bool {
+ No,
+ Yes,
+ };
+
+ FrameIterator(NonnullRefPtr<MediaStreamCursor> cursor, FrameSync sync, size_t position, Resynchronize resynchronize)
+ : m_cursor(move(cursor))
+ , m_sync(sync)
+ , m_position(position)
+ , m_resynchronize(resynchronize)
+ {
+ }
+
+ // Moves to the first header at or after the position, which an estimated position has to be brought to before
+ // frames are read from it. False when the stream ends, or the bound is reached, first.
+ DecoderErrorOr<bool> resync_forward(size_t bound = NumericLimits<size_t>::max());
+ // Reads the frame at the position and moves past it. Nothing moves until the whole frame has been read.
+ DecoderErrorOr<Frame> read_next_frame();
+
+ // The last frame heading before the bound, without moving.
+ Optional<FrameHeader> find_last_header_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<Optional<FrameHeader>> parse_header_at(size_t position);
+ DecoderErrorOr<Optional<FrameHeader>> find_header_at_or_after(size_t position, size_t bound);
+ DecoderErrorOr<Optional<FrameHeader>> find_header_before(size_t bound, size_t lower_bound);
+ DecoderErrorOr<bool> frame_follows(FrameHeader const& header, FrameHeader const& candidate);
+ DecoderErrorOr<Optional<Frame>> read_frame_at(FrameHeader const&);
+
+ NonnullRefPtr<MediaStreamCursor> m_cursor;
+ FrameSync m_sync;
+ size_t m_position { 0 };
+ Resynchronize m_resynchronize { Resynchronize::No };
+};
+
+// Reads the metadata blocks ahead of a stream's frames.
+class MEDIA_API Reader {
+public:
+ static DecoderErrorOr<Reader> from_stream(NonnullRefPtr<MediaStreamCursor> const&);
+
+ StreamInfo const& stream_info() const { return m_stream_info; }
+ FrameSync const& frame_sync() const { return m_frame_sync; }
+ size_t first_frame_position() const { return m_first_frame_position; }
+ Vector<SeekPoint> const& seek_points() const { return m_seek_points; }
+ // The stream's marker and STREAMINFO block, which is what a decoder is configured with.
+ ReadonlyBytes codec_initialization_data() const { return m_codec_initialization_data; }
+ // Zero when the stream does not say.
+ AK::Duration duration() const;
+
+private:
+ Reader(StreamInfo, FrameSync, size_t first_frame_position, Vector<SeekPoint>, ByteBuffer codec_initialization_data);
+
+ StreamInfo m_stream_info;
+ FrameSync m_frame_sync;
+ size_t m_first_frame_position { 0 };
+ Vector<SeekPoint> m_seek_points;
+ ByteBuffer m_codec_initialization_data;
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/FLACNavigator.cpp b/Libraries/LibMedia/Containers/FLACNavigator.cpp
deleted file mode 100644
index 0007c352f62..00000000000
--- a/Libraries/LibMedia/Containers/FLACNavigator.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibMedia/ReadonlyBytesCursor.h>
-
-#include "FLACNavigator.h"
-
-namespace Media {
-
-OwnPtr<FLACNavigator> FLACNavigator::create(ReadonlyBytes first_frame, NonnullRefPtr<MediaStreamCursor> cursor, u32 sample_rate)
-{
- if (first_frame.size() < 2)
- return {};
- u16 sync_code = (static_cast<u16>(first_frame[0]) << 8) | first_frame[1];
- if (!Codecs::FLAC::is_sync_code(sync_code))
- return {};
-
- bool is_fixed_blocksize = (sync_code & 1) == 0;
-
- auto frame_cursor = make_ref_counted<ReadonlyBytesCursor>(first_frame);
- auto navigator = adopt_own(*new (nothrow) FLACNavigator(move(cursor), sample_rate, sync_code, 0));
- auto frame_info = Codecs::FLAC::parse_frame_header(frame_cursor, sync_code, 0);
- if (!frame_info.has_value())
- return {};
-
- if (is_fixed_blocksize)
- navigator->m_fixed_block_size = frame_info->block_size;
-
- return navigator;
-}
-
-static constexpr size_t SCAN_CHUNK_SIZE = 4096;
-
-Optional<Codecs::FLAC::FrameInfo> FLACNavigator::find_first_frame(MediaStreamCursor& cursor, size_t search_start, size_t search_end) const
-{
- VERIFY(search_start <= search_end);
-
- Array<u8, SCAN_CHUNK_SIZE> chunk;
- auto chunk_start = search_start;
-
- while (chunk_start < search_end) {
- if (cursor.seek_to_position(chunk_start).is_error())
- return {};
- auto read_result = cursor.read_into(chunk);
- if (read_result.is_error())
- return {};
- auto bytes_read = read_result.value();
- if (bytes_read < 2)
- return {};
-
- for (size_t i = 0; i + 1 < bytes_read; i++) {
- if (chunk[i] != 0xFF)
- continue;
- u16 maybe_sync_code = (static_cast<u16>(chunk[i]) << 8) | chunk[i + 1];
- if (maybe_sync_code != m_sync_code)
- continue;
-
- auto sync_position = chunk_start + i;
- if (cursor.seek_to_position(sync_position).is_error())
- return {};
- auto frame_info = Codecs::FLAC::parse_frame_header(cursor, m_sync_code, m_fixed_block_size);
- if (frame_info.has_value())
- return frame_info;
- }
-
- chunk_start += bytes_read - 1;
- }
- return {};
-}
-
-Optional<Codecs::FLAC::FrameInfo> FLACNavigator::find_last_frame(MediaStreamCursor& cursor, size_t search_start, size_t search_end) const
-{
- VERIFY(search_start <= search_end);
-
- Array<u8, SCAN_CHUNK_SIZE> chunk;
- auto chunk_end = search_end;
-
- while (chunk_end > search_start) {
- auto chunk_start = chunk_end > SCAN_CHUNK_SIZE ? chunk_end - SCAN_CHUNK_SIZE : 0;
- chunk_start = max(chunk_start, search_start);
- VERIFY(chunk_start <= chunk_end);
- auto chunk_size = chunk_end - chunk_start;
- if (chunk_size < 2)
- return {};
-
- if (cursor.seek_to_position(chunk_start).is_error())
- return {};
- if (cursor.read_until_filled(chunk.span().trim(chunk_size)).is_error())
- return {};
-
- for (size_t i = chunk_size - 1; i-- > 0;) {
- if (chunk[i] != 0xFF)
- continue;
- u16 maybe_sync_code = (static_cast<u16>(chunk[i]) << 8) | chunk[i + 1];
- if (maybe_sync_code != m_sync_code)
- continue;
-
- auto sync_position = chunk_start + i;
- if (cursor.seek_to_position(sync_position).is_error())
- return {};
- auto frame_info = Codecs::FLAC::parse_frame_header(cursor, m_sync_code, m_fixed_block_size);
- if (frame_info.has_value())
- return frame_info;
- }
-
- chunk_end = chunk_start + 1;
- }
-
- return {};
-}
-
-AK::Duration FLACNavigator::sample_to_duration(u64 sample) const
-{
- return AK::Duration::from_time_units(static_cast<i64>(sample), 1, m_sample_rate);
-}
-
-Optional<AK::Duration> FLACNavigator::scan_forward_for_timestamp(size_t search_start, size_t search_end) const
-{
- auto first = find_first_frame(*m_cursor, search_start, search_end);
- if (!first.has_value())
- return {};
- return sample_to_duration(first->sample_number);
-}
-
-Optional<AK::Duration> FLACNavigator::scan_backward_for_end_timestamp(size_t search_start, size_t search_end) const
-{
- auto last = find_last_frame(*m_cursor, search_start, search_end);
- if (!last.has_value())
- return {};
- return sample_to_duration(last->sample_number + last->block_size);
-}
-
-void FLACNavigator::on_cached_range_changed(FLACCachedRange& 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 = scan_forward_for_timestamp(cached.byte_start, cached.byte_end);
- if (rescan_end)
- cached.time_end = scan_backward_for_end_timestamp(cached.byte_start, cached.byte_end);
-}
-
-void FLACNavigator::append_time_range(FLACCachedRange 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/FLACNavigator.h b/Libraries/LibMedia/Containers/FLACNavigator.h
deleted file mode 100644
index 5c9200880c8..00000000000
--- a/Libraries/LibMedia/Containers/FLACNavigator.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/OwnPtr.h>
-#include <LibMedia/Codecs/FLAC.h>
-
-#include "ScanningContainerNavigator.h"
-
-namespace Media {
-
-struct FLACCachedRange : CachedByteRange {
- using CachedByteRange::CachedByteRange;
-
- // Empty means "we scanned but didn't find a valid frame at this boundary".
- Optional<AK::Duration> time_start;
- Optional<AK::Duration> time_end;
-};
-
-class FLACNavigator final : public ScanningContainerNavigator<FLACNavigator, FLACCachedRange> {
-public:
- static OwnPtr<FLACNavigator> create(ReadonlyBytes first_frame, NonnullRefPtr<MediaStreamCursor> cursor, u32 sample_rate);
-
- void on_cached_range_changed(FLACCachedRange& cached_range, CachedRangeChange change) const;
- static void append_time_range(FLACCachedRange const& cached_range, TimeRanges& to);
-
- Optional<AK::Duration> scan_forward_for_timestamp(size_t search_start, size_t search_end) const;
- Optional<AK::Duration> scan_backward_for_end_timestamp(size_t search_start, size_t search_end) const;
-
-private:
- FLACNavigator(NonnullRefPtr<MediaStreamCursor> cursor, u32 sample_rate, u16 sync_code, u16 fixed_block_size)
- : m_cursor(move(cursor))
- , m_sample_rate(sample_rate)
- , m_sync_code(sync_code)
- , m_fixed_block_size(fixed_block_size)
- {
- }
-
- Optional<Codecs::FLAC::FrameInfo> find_first_frame(MediaStreamCursor& cursor, size_t search_start, size_t search_end) const;
- Optional<Codecs::FLAC::FrameInfo> find_last_frame(MediaStreamCursor& cursor, size_t search_start, size_t search_end) const;
-
- AK::Duration sample_to_duration(u64 sample) const;
-
- NonnullRefPtr<MediaStreamCursor> m_cursor;
- u32 m_sample_rate;
- u16 m_sync_code;
- u16 m_fixed_block_size;
-};
-
-}
diff --git a/Libraries/LibMedia/Containers/OggNavigator.cpp b/Libraries/LibMedia/Containers/OggNavigator.cpp
index 5d5d40a7fac..d43d011daa8 100644
--- a/Libraries/LibMedia/Containers/OggNavigator.cpp
+++ b/Libraries/LibMedia/Containers/OggNavigator.cpp
@@ -45,12 +45,12 @@ OwnPtr<OggNavigator> OggNavigator::create(ReadonlyBytes first_packet, NonnullRef
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.has_value())
+ 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->block_size;
+ fixed_block_size = frame_info.value()->block_size;
return adopt_own(*new (nothrow) OggNavigator(move(cursor), FLAC { sync_code, fixed_block_size, sample_rate }));
}
@@ -154,9 +154,9 @@ Optional<u64> OggNavigator::read_packet_duration_in_granules(ReadonlyBytes packe
},
[&](FLAC const& codec) -> Optional<u64> {
auto frame = Codecs::FLAC::parse_frame_header(packet_cursor, codec.sync_code, codec.fixed_block_size);
- if (!frame.has_value())
+ if (frame.is_error() || !frame.value().has_value())
return {};
- return frame->block_size;
+ return frame.value()->block_size;
},
[&](Vorbis const& codec) -> Optional<u64> {
auto packet_duration = codec.parser.parse_packet_duration_in_samples(packet);
diff --git a/Libraries/LibMedia/Containers/ScanningContainerNavigator.h b/Libraries/LibMedia/Containers/ScanningContainerNavigator.h
index 070f9eb8e0f..df386dc51d6 100644
--- a/Libraries/LibMedia/Containers/ScanningContainerNavigator.h
+++ b/Libraries/LibMedia/Containers/ScanningContainerNavigator.h
@@ -6,117 +6,40 @@
#pragma once
-#include <AK/EnumBits.h>
-
+#include "CachedByteRanges.h"
#include "ContainerNavigator.h"
namespace Media {
-enum class CachedRangeChange : u8 {
- Start = 1 << 0,
- End = 1 << 1,
-};
-AK_ENUM_BITWISE_OPERATORS(CachedRangeChange);
-
-struct CachedByteRange {
- size_t byte_start { 0 };
- size_t byte_end { 0 };
-
- constexpr CachedByteRange(size_t start, size_t end)
- : byte_start(start)
- , byte_end(end)
- {
- }
-};
-
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);
-
- // Reconcile incoming byte ranges with cached ranges in lockstep. Both are sorted by position.
- size_t cached_index = 0;
- size_t byte_index = 0;
-
- while (byte_index < byte_ranges.size()) {
- auto const& byte_range = byte_ranges[byte_index];
-
- if (cached_index < m_cached_ranges.size()) {
- auto& cached = m_cached_ranges[cached_index];
-
- // If the cached range doesn't have the same start byte as the incoming range, then we need to update
- // the start of the cached range if possible. If that's not possible, then we discard the cached range
- // if it's earlier, or insert a new one if it's later.
- if (cached.byte_start != byte_range.start) {
- if (cached.byte_end == byte_range.end) {
- cached.byte_start = byte_range.start;
- self.on_cached_range_changed(cached, CachedRangeChange::Start);
- cached_index++;
- byte_index++;
- continue;
- }
-
- if (cached.byte_end < byte_range.end) {
- cached = CachedRange { byte_range.start, byte_range.end };
- self.on_cached_range_changed(cached, CachedRangeChange::Start | CachedRangeChange::End);
- cached_index++;
- byte_index++;
- continue;
- }
-
- if (cached.byte_start < byte_range.start) {
- m_cached_ranges.remove(cached_index);
- } else {
- m_cached_ranges.insert(cached_index, CachedRange { byte_range.start, byte_range.end });
- auto& inserted = m_cached_ranges[cached_index];
- self.on_cached_range_changed(inserted, CachedRangeChange::Start | CachedRangeChange::End);
- cached_index++;
- byte_index++;
- }
- continue;
- }
-
- // If we're here, the cached range's start matches the incoming one, so we only need to update the end.
- if (cached.byte_end != byte_range.end) {
- cached.byte_end = byte_range.end;
- self.on_cached_range_changed(cached, CachedRangeChange::End);
- }
-
- cached_index++;
- byte_index++;
- } else {
- // We have new byte ranges on the end with no equivalent cached ranges, append them.
- m_cached_ranges.append(CachedRange { byte_range.start, byte_range.end });
- auto& appended = m_cached_ranges.last();
- self.on_cached_range_changed(appended, CachedRangeChange::Start | CachedRangeChange::End);
- cached_index++;
- byte_index++;
- }
- }
-
- // Remove any leftover cached ranges past the end.
- if (cached_index < m_cached_ranges.size())
- m_cached_ranges.remove(cached_index, m_cached_ranges.size() - cached_index);
+ m_cached_ranges.update(byte_ranges, [&](CachedRange& range, CachedRangeChange change) {
+ self.on_cached_range_changed(range, change);
+ });
BufferedRangesScan scan;
- if (m_cached_ranges.is_empty())
+ auto const& cached_ranges = m_cached_ranges.ranges();
+ if (cached_ranges.is_empty())
return scan;
- for (size_t i = 0; i + 1 < m_cached_ranges.size(); i++)
- self.append_time_range(m_cached_ranges[i], scan.time_ranges);
+ 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(m_cached_ranges.last(), 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 Vector<CachedRange> m_cached_ranges;
+ mutable CachedByteRanges<CachedRange> m_cached_ranges;
};
}
diff --git a/Libraries/LibMedia/DemuxerRegistry.cpp b/Libraries/LibMedia/DemuxerRegistry.cpp
index bc114c45c91..2445f6fb69a 100644
--- a/Libraries/LibMedia/DemuxerRegistry.cpp
+++ b/Libraries/LibMedia/DemuxerRegistry.cpp
@@ -6,6 +6,7 @@
#include <AK/Array.h>
#include <LibMedia/Containers/ADTS/ADTSDemuxer.h>
+#include <LibMedia/Containers/FLAC/FLACDemuxer.h>
#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>
#include <LibMedia/Containers/MP3/MP3Demuxer.h>
#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
@@ -30,6 +31,7 @@ static constexpr Array demuxers_in_priority_order {
DemuxerRegistration { ISOBMFF::ISOBMFFDemuxer::from_stream, ISOBMFF::ISOBMFFDemuxer::supports_container_mime_type, ISOBMFF::ISOBMFFDemuxer::supports_codec_in_container },
DemuxerRegistration { Matroska::MatroskaDemuxer::from_stream, Matroska::MatroskaDemuxer::supports_container_mime_type, Matroska::MatroskaDemuxer::supports_codec_in_container },
DemuxerRegistration { 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 { 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
index af497a37614..31b837e6c31 100644
--- a/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
+++ b/Libraries/LibMedia/FFmpeg/FFmpegDemuxer.cpp
@@ -15,7 +15,6 @@
#include <AK/Stream.h>
#include <AK/StringBuilder.h>
#include <AK/Time.h>
-#include <LibMedia/Containers/FLACNavigator.h>
#include <LibMedia/Containers/IndexedContainerNavigator.h>
#include <LibMedia/Containers/OggNavigator.h>
#include <LibMedia/FFmpeg/FFmpegChannelLayout.h>
@@ -38,13 +37,12 @@ bool FFmpegDemuxer::supports_container_mime_type(ContainerMimeType mime_type)
return true;
case ContainerID::ISOBMFF:
return mime_type.media_type != ContainerMediaType::Application;
- case ContainerID::FLAC:
- return mime_type.media_type == ContainerMediaType::Audio;
case ContainerID::Matroska:
case ContainerID::WebM:
case ContainerID::ADTS:
case ContainerID::MPEGAudio:
case ContainerID::WAV:
+ case ContainerID::FLAC:
return false;
}
VERIFY_NOT_REACHED();
@@ -57,13 +55,12 @@ bool FFmpegDemuxer::supports_codec_in_container(ContainerID container_id, CodecI
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::FLAC:
- return codec_id == 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();
@@ -145,7 +142,7 @@ static DecoderErrorOr<void> initialize_format_context(AVFormatContext*& format_c
AVDictionary* options = nullptr;
ScopeGuard free_options = [&] { av_dict_free(&options); };
- if (av_dict_set(&options, "format_whitelist", "flac,ogg", 0) < 0)
+ 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();
@@ -350,22 +347,6 @@ OwnPtr<ContainerNavigator> FFmpegDemuxer::create_single_track_container_navigato
{
auto format_name = StringView(context.iformat->name, strlen(context.iformat->name));
- if (format_name == "flac"sv && context.nb_streams == 1) {
- auto& av_stream = *context.streams[0];
- if (av_stream.codecpar->sample_rate > 0) {
- auto sample_rate = static_cast<u32>(av_stream.codecpar->sample_rate);
- AVPacket* packet = av_packet_alloc();
- ScopeGuard free_packet = [&] { av_packet_free(&packet); };
-
- if (av_read_frame(&context, packet) >= 0) {
- VERIFY(packet->size >= 0);
- auto cursor = stream->create_cursor();
- cursor->set_is_blocking(false);
- return FLACNavigator::create({ packet->data, static_cast<size_t>(packet->size) }, move(cursor), sample_rate);
- }
- }
- }
-
if (format_name == "ogg"sv) {
if (context.nb_streams != 1)
return nullptr;
diff --git a/Meta/CMake/flatpak/org.ladybird.Ladybird.json b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
index 67a6f0079cc..b03cf802f68 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,flac --disable-optimizations",
+ "./configure --prefix=/app --libdir=/app/lib --enable-shared --disable-static --enable-pic --disable-doc --enable-debug --enable-runtime-cpudetect --disable-autodetect --build-suffix=-ladybird --disable-everything --disable-network --disable-ffmpeg --disable-ffplay --disable-ffprobe --enable-avcodec --disable-avdevice --enable-avformat --disable-avfilter --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",
"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 85d5dc28779..82911a72bcc 100644
--- a/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
+++ b/Meta/CMake/vcpkg/overlay-ports/ffmpeg/portfile.cmake
@@ -281,7 +281,7 @@ if("ladybird-components" IN_LIST FEATURES)
set(OPTIONS "${OPTIONS} --disable-everything --disable-network")
set(OPTIONS "${OPTIONS} --enable-decoder=vp8,vp9,libdav1d,theora,vorbis,opus,flac,mp3float,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_alaw,pcm_mulaw")
set(OPTIONS "${OPTIONS} --enable-parser=vp8,vp9,av1,flac,mpegaudio")
- set(OPTIONS "${OPTIONS} --enable-demuxer=ogg,flac")
+ set(OPTIONS "${OPTIONS} --enable-demuxer=ogg")
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 4fc0a4be769..645f7688cdf 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": 2,
+ "port-version": 3,
"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 9aa57250a41..e40070bfd2e 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -17,6 +17,7 @@ set(TEST_SOURCES
TestDisplayingVideoSink.cpp
TestFFmpegAudioNormalization.cpp
TestFFmpegDemuxer.cpp
+ TestFLACDemuxer.cpp
TestID3.cpp
TestIncrementallyPopulatedStream.cpp
TestISOBMFF.cpp
@@ -65,6 +66,7 @@ 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(TestWAVDemuxer PRIVATE LibThreading)
target_link_libraries(TestISOBMFF PRIVATE LibThreading)
diff --git a/Tests/LibMedia/FLAC/silence_then_noise_8000_mono.flac b/Tests/LibMedia/FLAC/silence_then_noise_8000_mono.flac
new file mode 100644
index 00000000000..ac31016f368
Binary files /dev/null and b/Tests/LibMedia/FLAC/silence_then_noise_8000_mono.flac differ
diff --git a/Tests/LibMedia/FLAC/tone_8000_mono_seekpoints.flac b/Tests/LibMedia/FLAC/tone_8000_mono_seekpoints.flac
new file mode 100644
index 00000000000..23d5c9cd6de
Binary files /dev/null and b/Tests/LibMedia/FLAC/tone_8000_mono_seekpoints.flac differ
diff --git a/Tests/LibMedia/TestBufferedRanges.cpp b/Tests/LibMedia/TestBufferedRanges.cpp
index e0f2379b990..80babfd5c40 100644
--- a/Tests/LibMedia/TestBufferedRanges.cpp
+++ b/Tests/LibMedia/TestBufferedRanges.cpp
@@ -192,8 +192,8 @@ static Array fixtures {
},
Fixture {
"buffered-ranges/tone.flac"sv,
- { 32 * KiB, 87552, 0, 48000 },
- { 68 * KiB, 221184, 0, 48000 },
+ { 32 * KiB, 82944, 4608, 48000 },
+ { 68 * KiB, 216576, 4608, 48000 },
},
Fixture {
"buffered-ranges/tone_opus.ogg"sv,
diff --git a/Tests/LibMedia/TestFFmpegDemuxer.cpp b/Tests/LibMedia/TestFFmpegDemuxer.cpp
index 8ff9ccf7115..5c67d2610dd 100644
--- a/Tests/LibMedia/TestFFmpegDemuxer.cpp
+++ b/Tests/LibMedia/TestFFmpegDemuxer.cpp
@@ -15,7 +15,7 @@
TEST_CASE(rejects_formats_handled_by_other_demuxers)
{
- for (auto path : { "./vfr.mkv"sv, "./avc.mp4"sv, "./buffered-ranges/tone.wav"sv }) {
+ 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());
@@ -32,18 +32,17 @@ TEST_CASE(read_after_aborted_blocking_read)
// The fix was to only return AVERROR_EOF from the IO context callbacks, and then determine whether to change
// the error to an Aborted error within the FFmpegDemuxer on top of the avformat context that used the IO.
- auto file = MUST(Core::File::open("./buffered-ranges/tone.flac"sv, Core::File::OpenMode::Read));
+ auto file = MUST(Core::File::open("./buffered-ranges/tone_vorbis.ogg"sv, Core::File::OpenMode::Read));
auto file_data = MUST(file->read_until_eof());
- // Feed only a portion of the file into the stream so that the demuxer will eventually block
- // waiting for more data.
- auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ // 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;
- stream->set_expected_size(file_data.size());
- stream->add_chunk_at(0, file_data.bytes().trim(initial_chunk_size));
+ auto tail_start = file_data.size() / 4 * 3;
- // Create the demuxer from the partial stream.
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();
@@ -100,8 +99,7 @@ TEST_CASE(read_after_aborted_blocking_read)
// 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));
- stream->close();
+ 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.
diff --git a/Tests/LibMedia/TestFLACDemuxer.cpp b/Tests/LibMedia/TestFLACDemuxer.cpp
new file mode 100644
index 00000000000..53e77235468
--- /dev/null
+++ b/Tests/LibMedia/TestFLACDemuxer.cpp
@@ -0,0 +1,499 @@
+/*
+ * 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/FLAC/FLACDemuxer.h>
+#include <LibMedia/DecoderRegistrations.h>
+#include <LibMedia/IncrementallyPopulatedStream.h>
+#include <LibMediaCodecs/CodedFrame.h>
+#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+
+#include "TestMediaCommon.h"
+#include "TransientlyAbortingStream.h"
+
+namespace {
+
+TEST_SETUP
+{
+ Media::install_video_decoders({ Media::hardware_video_decoders(), Media::ffmpeg_video_decoders() });
+ Media::install_audio_decoders({ Media::audio_decoders() });
+}
+
+// tone.flac: 48 kHz stereo, 84 frames of 4608 samples with a last frame of 1536, no seek table.
+constexpr u32 TONE_SAMPLE_RATE = 48000;
+constexpr u64 TONE_BLOCK_SIZE = 4608;
+constexpr u64 TONE_SAMPLE_COUNT = 384000;
+constexpr size_t TONE_FRAME_COUNT = 84;
+
+// tone_8000_mono_seekpoints.flac: 8 kHz mono, frames of 4096 samples, a seek point every second.
+constexpr u32 SEEKPOINTS_SAMPLE_RATE = 8000;
+constexpr u64 SEEKPOINTS_BLOCK_SIZE = 4096;
+
+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::FLAC::FLACDemuxer::from_stream(Media::IncrementallyPopulatedStream::create_from_buffer(data));
+}
+
+Media::Track audio_track(Media::Demuxer& demuxer)
+{
+ auto track = MUST(demuxer.get_preferred_track_for_type(Media::TrackType::Audio));
+ VERIFY(track.has_value());
+ MUST(demuxer.create_context_for_track(*track));
+ return *track;
+}
+
+AK::Duration time_of_sample(u64 sample, u32 sample_rate = TONE_SAMPLE_RATE)
+{
+ return AK::Duration::from_time_units(static_cast<i64>(sample), 1, sample_rate);
+}
+
+struct FrameIdentity {
+ AK::Duration timestamp;
+ size_t byte_count { 0 };
+ bool operator==(FrameIdentity const&) const = default;
+};
+
+Vector<FrameIdentity> read_every_frame(Media::Demuxer& demuxer, Media::Track const& track)
+{
+ Vector<FrameIdentity> 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.value().presentation_timestamp(), frame.value().data().size() });
+ }
+ return frames;
+}
+
+Vector<Media::FLAC::FrameHeader> frame_headers_of(ByteBuffer const& data)
+{
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
+ auto reader = MUST(Media::FLAC::Reader::from_stream(stream->create_cursor()));
+ Media::FLAC::FrameIterator iterator { stream->create_cursor(), reader.frame_sync(), reader.first_frame_position(), Media::FLAC::FrameIterator::Resynchronize::No };
+ Vector<Media::FLAC::FrameHeader> headers;
+ while (true) {
+ auto frame = iterator.read_next_frame();
+ if (frame.is_error())
+ break;
+ headers.append(frame.value().header);
+ }
+ return headers;
+}
+
+TEST_CASE(demuxer_describes_the_only_track_of_the_stream)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone.flac"sv)));
+
+ EXPECT(MUST(demuxer->get_tracks_for_type(Media::TrackType::Video)).is_empty());
+
+ auto tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio));
+ EXPECT_EQ(tracks.size(), 1u);
+ EXPECT_EQ(tracks[0].audio_data().sample_specification.sample_rate(), TONE_SAMPLE_RATE);
+ EXPECT_EQ(tracks[0].audio_data().sample_specification.channel_map(), Audio::ChannelMap::stereo());
+ EXPECT_EQ(tracks[0].parsed_codec().codec_id(), Media::CodecID::FLAC);
+
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::from_seconds(8));
+}
+
+TEST_CASE(demuxer_reads_every_frame_with_its_sample_number)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone.flac"sv)));
+ auto track = audio_track(*demuxer);
+
+ u64 expected_sample = 0;
+ size_t frame_count = 0;
+ while (true) {
+ auto frame = demuxer->get_next_sample_for_track(track);
+ if (frame.is_error()) {
+ EXPECT_EQ(frame.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ EXPECT_EQ(frame.value().presentation_timestamp(), time_of_sample(expected_sample));
+ EXPECT(frame.value().is_keyframe());
+ // STREAMINFO states the frame sizes of this stream as 478 to 1303 bytes.
+ EXPECT(frame.value().data().size() >= 478 && frame.value().data().size() <= 1303);
+
+ auto const& configuration = frame.value().new_codec_configuration();
+ EXPECT_EQ(configuration.has_value(), frame_count == 0);
+ if (configuration.has_value()) {
+ EXPECT_EQ(configuration->size(), 42u);
+ EXPECT(configuration->trim(4) == "fLaC"sv.bytes());
+ }
+
+ expected_sample += frame.value().duration().to_time_units(1, TONE_SAMPLE_RATE);
+ frame_count++;
+ }
+
+ EXPECT_EQ(frame_count, TONE_FRAME_COUNT);
+ EXPECT_EQ(expected_sample, TONE_SAMPLE_COUNT);
+}
+
+TEST_CASE(demuxer_seeks_to_the_frame_holding_a_timestamp)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone.flac"sv)));
+ auto track = audio_track(*demuxer);
+
+ auto expect_seek_to_land_on_frame = [&](AK::Duration target, u64 frame_index) {
+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, target)), Media::DemuxerSeekResult::MovedPosition);
+ auto frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(frame.presentation_timestamp(), time_of_sample(frame_index * TONE_BLOCK_SIZE));
+ EXPECT(frame.presentation_timestamp() <= target);
+ EXPECT(frame.presentation_timestamp() + frame.duration() > target);
+ };
+ expect_seek_to_land_on_frame(AK::Duration::from_milliseconds(3'500), 36);
+ expect_seek_to_land_on_frame(AK::Duration::from_milliseconds(7'990), TONE_FRAME_COUNT - 1);
+ expect_seek_to_land_on_frame(AK::Duration::from_milliseconds(96), 1);
+
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_seconds(10)));
+ EXPECT_EQ(demuxer->get_next_sample_for_track(track).error().category(), Media::DecoderErrorCategory::EndOfStream);
+
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::zero(), Media::DemuxerSeekOptions::NeedCodecConfiguration));
+ auto first_frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(first_frame.presentation_timestamp(), AK::Duration::zero());
+ EXPECT(first_frame.new_codec_configuration().has_value());
+}
+
+TEST_CASE(demuxer_seeks_through_the_seek_table)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("FLAC/tone_8000_mono_seekpoints.flac"sv)));
+ auto track = audio_track(*demuxer);
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::from_seconds(5));
+
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(3'200)));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).presentation_timestamp(), time_of_sample(6 * SEEKPOINTS_BLOCK_SIZE, SEEKPOINTS_SAMPLE_RATE));
+
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(4'900)));
+ auto last_frame = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(last_frame.presentation_timestamp(), time_of_sample(9 * SEEKPOINTS_BLOCK_SIZE, SEEKPOINTS_SAMPLE_RATE));
+ EXPECT_EQ(last_frame.presentation_timestamp() + last_frame.duration(), AK::Duration::from_seconds(5));
+}
+
+// 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.flac"sv);
+
+ Vector<FrameIdentity> expected_frames;
+ {
+ auto demuxer = MUST(demuxer_for(file_data));
+ auto track = audio_track(*demuxer);
+ expected_frames = read_every_frame(*demuxer, track);
+ }
+
+ // The data ends inside a frame, so the read that blocks has part of its frame.
+ auto initial_chunk_size = (file_data.size() / 3) + 1000;
+ 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));
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::FLAC::FLACDemuxer::from_stream(stream));
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto track = audio_track(*demuxer);
+
+ 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(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;
+ }
+ }
+}
+
+// An abort that is reset before the reading thread looks at it still has to leave the frame it cut short to be read.
+TEST_CASE(demuxer_resumes_after_a_transient_abort)
+{
+ auto file_data = read_fixture("buffered-ranges/tone.flac"sv);
+ auto headers = frame_headers_of(file_data);
+ VERIFY(headers.size() > 40);
+
+ Vector<FrameIdentity> expected_frames;
+ {
+ auto demuxer = MUST(demuxer_for(file_data));
+ auto track = audio_track(*demuxer);
+ expected_frames = read_every_frame(*demuxer, track);
+ }
+
+ auto stream = TransientlyAbortingStream::create(file_data, headers[40].position);
+ auto demuxer = MUST(Media::FLAC::FLACDemuxer::from_stream(stream));
+ auto track = audio_track(*demuxer);
+
+ Vector<FrameIdentity> actual_frames;
+ size_t aborted_read_count = 0;
+ while (true) {
+ auto frame = demuxer->get_next_sample_for_track(track);
+ if (frame.is_error()) {
+ if (frame.error().category() != Media::DecoderErrorCategory::Aborted) {
+ EXPECT_EQ(frame.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ aborted_read_count++;
+ continue;
+ }
+ actual_frames.append({ frame.value().presentation_timestamp(), frame.value().data().size() });
+ }
+ EXPECT(stream->has_aborted_a_read());
+ EXPECT_EQ(aborted_read_count, 1u);
+ EXPECT_EQ(actual_frames, expected_frames);
+}
+
+// A frame whose body is damaged is still delivered, since the frame after it is where its header says. A frame whose
+// header is damaged is lost, and the frame before it runs on to the next header.
+TEST_CASE(demuxer_reads_on_past_damaged_frames)
+{
+ auto file_data = read_fixture("buffered-ranges/tone.flac"sv);
+ auto headers = frame_headers_of(file_data);
+ EXPECT_EQ(headers.size(), TONE_FRAME_COUNT);
+
+ auto damaged_body_start = headers[10].position + headers[10].byte_size + 50;
+ file_data.bytes().slice(damaged_body_start, 100).fill(0);
+ file_data.bytes().slice(headers[20].position, 4).fill(0);
+
+ auto demuxer = MUST(demuxer_for(file_data));
+ auto track = audio_track(*demuxer);
+ auto frames = read_every_frame(*demuxer, track);
+
+ EXPECT_EQ(frames.size(), TONE_FRAME_COUNT - 1);
+ size_t index = 0;
+ for (u64 frame_index = 0; frame_index < TONE_FRAME_COUNT; frame_index++) {
+ if (frame_index == 20)
+ continue;
+ if (index < frames.size())
+ EXPECT_EQ(frames[index].timestamp, time_of_sample(frame_index * TONE_BLOCK_SIZE));
+ index++;
+ }
+}
+
+TEST_CASE(demuxer_skips_the_tags_around_a_stream)
+{
+ auto plain_data = read_fixture("buffered-ranges/tone.flac"sv);
+ Vector<FrameIdentity> expected_frames;
+ {
+ auto demuxer = MUST(demuxer_for(plain_data));
+ auto track = audio_track(*demuxer);
+ expected_frames = read_every_frame(*demuxer, track);
+ }
+
+ // An ID3v2 tag of 100 bytes ahead of the stream, and an ID3v1 tag after it.
+ ByteBuffer tagged_data;
+ MUST(tagged_data.try_append(Array<u8, 10> { 'I', 'D', '3', 3, 0, 0, 0, 0, 0, 100 }.span()));
+ MUST(tagged_data.try_resize(tagged_data.size() + 100));
+ MUST(tagged_data.try_append(plain_data.bytes()));
+ MUST(tagged_data.try_append("TAG"sv.bytes()));
+ MUST(tagged_data.try_resize(tagged_data.size() + 125));
+
+ auto demuxer = MUST(demuxer_for(tagged_data));
+ auto track = audio_track(*demuxer);
+ EXPECT_EQ(read_every_frame(*demuxer, track), expected_frames);
+}
+
+TEST_CASE(demuxer_declines_what_it_cannot_read)
+{
+ auto not_flac = demuxer_for(MUST(ByteBuffer::create_zeroed(4096)));
+ EXPECT_EQ(not_flac.error().category(), Media::DecoderErrorCategory::UnrecognizedFormat);
+
+ ByteBuffer padding_first;
+ MUST(padding_first.try_append("fLaC"sv.bytes()));
+ MUST(padding_first.try_append(Array<u8, 4> { 0x81, 0, 0, 10 }.span()));
+ MUST(padding_first.try_resize(padding_first.size() + 10));
+ EXPECT_EQ(demuxer_for(padding_first).error().category(), Media::DecoderErrorCategory::Corrupted);
+
+ ByteBuffer marker_only;
+ MUST(marker_only.try_append("fLaC"sv.bytes()));
+ EXPECT(demuxer_for(marker_only).is_error());
+}
+
+TEST_CASE(demuxer_grows_the_duration_of_a_stream_that_does_not_state_its_length)
+{
+ auto file_data = read_fixture("buffered-ranges/tone.flac"sv);
+ // The total sample count is the 36 bits that end STREAMINFO's fixed fields, 8 bytes into the stream.
+ file_data[8 + 13] &= 0xF0;
+ file_data.bytes().slice(8 + 14, 4).fill(0);
+
+ auto& loop = never_destroyed_event_loop();
+ auto demuxer = MUST(demuxer_for(file_data));
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::zero());
+
+ demuxer->set_scan_state_change_handler([](auto const&) { });
+ auto deadline_expired = false;
+ auto deadline_timer = Core::Timer::create_single_shot(AK::Duration::from_seconds(1), [&] { deadline_expired = true; });
+ deadline_timer->start();
+ loop.spin_until([&] { return demuxer->scan_state().duration == AK::Duration::from_seconds(8) || deadline_expired; });
+ demuxer->set_scan_state_change_handler(nullptr);
+ EXPECT_EQ(demuxer->scan_state().duration, AK::Duration::from_seconds(8));
+
+ auto track = audio_track(*demuxer);
+ EXPECT_EQ(read_every_frame(*demuxer, track).size(), TONE_FRAME_COUNT);
+}
+
+// Over a network, a probe that lands past the target starts a request from an earlier position, so a seek into
+// data that is not buffered should land before the target with as few probes as the stream's layout allows, then
+// walk forward. This stream's first half is silence in tiny frames and its second half noise in large ones, so
+// interpolating between the stream's ends overshoots a target in the first half by seconds. Only the metadata and
+// the first frame are buffered, so that no scanned frame narrows the probing down.
+TEST_CASE(demuxer_seeks_into_unbuffered_data_with_few_requests)
+{
+ auto file_data = read_fixture("FLAC/silence_then_noise_8000_mono.flac"sv);
+ auto& loop = never_destroyed_event_loop();
+
+ constexpr size_t head_size = 100;
+ 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>(2 * 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();
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::FLAC::FLACDemuxer::from_stream(stream));
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto track = audio_track(*demuxer);
+
+ // The player stopped the fetch once its buffer was full and lets it go again for the seek, so every read of
+ // data that is not buffered asks for a request from its own position.
+ stream->set_may_idle(true);
+ stream->set_may_idle(false);
+
+ // 2.5 seconds falls in frame 4, well inside the silence.
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto target = AK::Duration::from_milliseconds(2'500);
+ 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));
+ landed_timestamp = MUST(demuxer->get_next_sample_for_track(track)).presentation_timestamp();
+ seek_finished = true;
+ return 0;
+ });
+ seeker_thread->start();
+
+ 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 seek_finished.load() || deadline_expired; });
+ if (deadline_expired)
+ FAIL(ByteString::formatted("The seek did not finish: {} requests, serving at {}", requested_offsets.size(), serving_position));
+ server->stop();
+ stream->set_data_request_callback(nullptr);
+ if (!deadline_expired)
+ MUST(seeker_thread->join());
+
+ EXPECT_EQ(landed_timestamp, time_of_sample(4 * SEEKPOINTS_BLOCK_SIZE, SEEKPOINTS_SAMPLE_RATE));
+ // One probe overshoots into the noise, and one step back by the noise's byte rate lands at the head.
+ EXPECT(requested_offsets.size() <= 2);
+}
+
+// A header that nothing follows within a frame's reach was not a header, so the stream ends rather than delivering
+// everything after it as one frame.
+TEST_CASE(demuxer_gives_up_on_a_frame_that_never_ends)
+{
+ auto file_data = read_fixture("buffered-ranges/tone.flac"sv);
+ auto first_header = frame_headers_of(file_data)[0];
+
+ auto headerless_data = MUST(ByteBuffer::copy(file_data.bytes().trim(first_header.position + first_header.byte_size)));
+ MUST(headerless_data.try_resize(headerless_data.size() + (5 * MiB), ByteBuffer::ZeroFillNewElements::Yes));
+
+ auto demuxer = MUST(demuxer_for(headerless_data));
+ auto track = audio_track(*demuxer);
+ EXPECT(read_every_frame(*demuxer, track).is_empty());
+}
+
+TEST_CASE(demuxer_reads_no_more_of_a_seek_table_than_it_can_use)
+{
+ auto file_data = read_fixture("buffered-ranges/tone.flac"sv);
+ auto headers = frame_headers_of(file_data);
+ auto first_frame_position = headers[0].position;
+
+ // The stream's STREAMINFO, then a seek table of 70,000 points of which only the first 84 are real, then its frames.
+ constexpr size_t seek_point_count = 70'000;
+ ByteBuffer tabled_data;
+ MUST(tabled_data.try_append(file_data.bytes().trim(4 + 4 + 34)));
+ tabled_data[4] = 0x00;
+ u32 table_size = seek_point_count * 18;
+ MUST(tabled_data.try_append(Array<u8, 4> { 0x83, static_cast<u8>(table_size >> 16), static_cast<u8>(table_size >> 8), static_cast<u8>(table_size) }.span()));
+ for (size_t index = 0; index < seek_point_count; index++) {
+ u64 sample_number = NumericLimits<u64>::max();
+ u64 byte_offset = 0;
+ if (index < headers.size()) {
+ sample_number = headers[index].sample_number;
+ byte_offset = headers[index].position - first_frame_position;
+ }
+ MUST(tabled_data.try_append(Array<u8, 18> { static_cast<u8>(sample_number >> 56), static_cast<u8>(sample_number >> 48), static_cast<u8>(sample_number >> 40), static_cast<u8>(sample_number >> 32), static_cast<u8>(sample_number >> 24), static_cast<u8>(sample_number >> 16), static_cast<u8>(sample_number >> 8), static_cast<u8>(sample_number), static_cast<u8>(byte_offset >> 56), static_cast<u8>(byte_offset >> 48), static_cast<u8>(byte_offset >> 40), static_cast<u8>(byte_offset >> 32), static_cast<u8>(byte_offset >> 24), static_cast<u8>(byte_offset >> 16), static_cast<u8>(byte_offset >> 8), static_cast<u8>(byte_offset), 0x12, 0x00 }.span()));
+ }
+ MUST(tabled_data.try_append(file_data.bytes().slice(first_frame_position)));
+
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(tabled_data);
+ auto reader = MUST(Media::FLAC::Reader::from_stream(stream->create_cursor()));
+ EXPECT_EQ(reader.seek_points().size(), headers.size());
+
+ auto demuxer = MUST(Media::FLAC::FLACDemuxer::from_stream(stream));
+ auto track = audio_track(*demuxer);
+ MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(3'500)));
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).presentation_timestamp(), time_of_sample(36 * TONE_BLOCK_SIZE));
+}
+
+TEST_CASE(demuxer_feeds_a_decoder_to_the_end)
+{
+ decode_audio("buffered-ranges/tone.flac"sv, TONE_SAMPLE_RATE, 2, TONE_SAMPLE_COUNT);
+ decode_audio("FLAC/tone_8000_mono_seekpoints.flac"sv, SEEKPOINTS_SAMPLE_RATE, 1, 40000);
+}
+
+}