Skip to content

Truly independent web browser

LibMedia: Make a WAV demuxer and drop it from libavformat

Zaggy10245460b766c15e
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txt
index 7db1dafe8b5..44694258ecf 100644
--- a/Libraries/LibMedia/CMakeLists.txt
+++ b/Libraries/LibMedia/CMakeLists.txt
@@ -11,7 +11,6 @@ set(SOURCES
Containers/ADTS/ADTSDemuxer.cpp
Containers/ADTS/FrameHeader.cpp
Containers/ADTS/Reader.cpp
- Containers/ConstantBitrateContainerNavigator.cpp
Containers/FLACNavigator.cpp
Containers/FrameScanTimeline.cpp
Containers/ID3.cpp
@@ -31,6 +30,8 @@ set(SOURCES
Containers/MP3/Reader.cpp
Containers/MP3/StreamInfo.cpp
Containers/OggNavigator.cpp
+ Containers/WAV/Reader.cpp
+ Containers/WAV/WAVDemuxer.cpp
DecodeAudioStream.cpp
DecoderRegistrations.cpp
DemuxerRegistry.cpp
diff --git a/Libraries/LibMedia/Containers/ConstantBitrateContainerNavigator.cpp b/Libraries/LibMedia/Containers/ConstantBitrateContainerNavigator.cpp
deleted file mode 100644
index 9b1bfc47185..00000000000
--- a/Libraries/LibMedia/Containers/ConstantBitrateContainerNavigator.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-
-#include "ConstantBitrateContainerNavigator.h"
-
-namespace Media {
-
-BufferedRangesScan ConstantBitrateContainerNavigator::buffered_time_ranges(Vector<MediaStream::ByteRange> const& byte_ranges) const
-{
- if (byte_ranges.is_empty())
- return {};
-
- BufferedRangesScan scan;
-
- for (auto const& byte_range : byte_ranges) {
- if (byte_range.end <= m_first_sample_position)
- continue;
-
- auto data_start = (byte_range.start > m_first_sample_position) ? byte_range.start - m_first_sample_position : 0;
- auto data_end = byte_range.end - m_first_sample_position;
-
- auto time_start = AK::Duration::from_time_units(AK::clamp_to<i64>(data_start), 1, m_bytes_per_second);
- auto time_end = AK::Duration::from_time_units(AK::clamp_to<i64>(data_end), 1, m_bytes_per_second);
-
- scan.time_ranges.add_range(max(AK::Duration::zero(), time_start), time_end);
- }
-
- scan.last_byte_range_has_samples = byte_ranges.last().end > m_first_sample_position;
- return scan;
-}
-
-DecoderErrorOr<SeekResult> ConstantBitrateContainerNavigator::seek_to_timestamp(AK::Duration timestamp) const
-{
- timestamp = max(timestamp, AK::Duration::zero());
- auto byte_offset = timestamp.to_time_units(1, m_bytes_per_second);
- byte_offset -= byte_offset % static_cast<i64>(m_block_align);
- auto byte_position = static_cast<i64>(m_first_sample_position) + byte_offset;
- auto resolved_timestamp = AK::Duration::from_time_units(byte_offset, 1, m_bytes_per_second);
- return SeekedPosition { byte_position, resolved_timestamp };
-}
-
-}
diff --git a/Libraries/LibMedia/Containers/ConstantBitrateContainerNavigator.h b/Libraries/LibMedia/Containers/ConstantBitrateContainerNavigator.h
deleted file mode 100644
index b469ce07635..00000000000
--- a/Libraries/LibMedia/Containers/ConstantBitrateContainerNavigator.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include "ContainerNavigator.h"
-
-namespace Media {
-
-class ConstantBitrateContainerNavigator final : public SingleTrackContainerNavigator {
-public:
- ConstantBitrateContainerNavigator(size_t first_sample_position, u32 bytes_per_second, u32 block_align)
- : m_first_sample_position(first_sample_position)
- , m_bytes_per_second(bytes_per_second)
- , m_block_align(block_align)
- {
- }
-
- BufferedRangesScan buffered_time_ranges(Vector<MediaStream::ByteRange> const& byte_ranges) const override;
- virtual DecoderErrorOr<SeekResult> seek_to_timestamp(AK::Duration timestamp) const override;
-
-private:
- size_t m_first_sample_position;
- size_t m_bytes_per_second;
- size_t m_block_align;
-};
-
-}
diff --git a/Libraries/LibMedia/Containers/WAV/Reader.cpp b/Libraries/LibMedia/Containers/WAV/Reader.cpp
new file mode 100644
index 00000000000..212d4edef70
--- /dev/null
+++ b/Libraries/LibMedia/Containers/WAV/Reader.cpp
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Checked.h>
+#include <AK/Math.h>
+#include <AK/Vector.h>
+#include <LibMedia/Containers/WAV/Reader.h>
+
+namespace Media::WAV {
+
+static constexpr size_t RIFF_HEADER_SIZE = 12;
+static constexpr size_t CHUNK_HEADER_SIZE = 8;
+static constexpr u32 FORMAT_CHUNK_SIZE = 16;
+static constexpr u32 EXTENSIBLE_FORMAT_CHUNK_SIZE = 40;
+
+static constexpr u16 FORMAT_TAG_PCM = 0x0001;
+static constexpr u16 FORMAT_TAG_IEEE_FLOAT = 0x0003;
+static constexpr u16 FORMAT_TAG_ALAW = 0x0006;
+static constexpr u16 FORMAT_TAG_MULAW = 0x0007;
+static constexpr u16 FORMAT_TAG_EXTENSIBLE = 0xFFFE;
+
+// The subformat GUIDs of the extensible header begin with a format tag and share this tail.
+static constexpr Array<u8, 14> MEDIA_SUBTYPE_GUID_TAIL { 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 };
+
+using ChunkType = Array<u8, 4>;
+
+static bool chunk_type_is(ReadonlyBytes type, StringView name)
+{
+ return StringView { type.data(), type.size() } == name;
+}
+
+static DecoderErrorOr<CodecID> codec_id_for(u16 format_tag, u16 bits_per_sample)
+{
+ if (format_tag == FORMAT_TAG_PCM) {
+ if (bits_per_sample == 8)
+ return CodecID::U8;
+ if (bits_per_sample == 16)
+ return CodecID::S16LE;
+ if (bits_per_sample == 24)
+ return CodecID::S24LE;
+ if (bits_per_sample == 32)
+ return CodecID::S32LE;
+ } else if (format_tag == FORMAT_TAG_IEEE_FLOAT) {
+ if (bits_per_sample == 32)
+ return CodecID::F32LE;
+ } else if (format_tag == FORMAT_TAG_ALAW) {
+ if (bits_per_sample == 8)
+ return CodecID::ALaw;
+ } else if (format_tag == FORMAT_TAG_MULAW) {
+ if (bits_per_sample == 8)
+ return CodecID::MuLaw;
+ }
+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "WAVE format {:#x} with {} bits per sample is not supported", format_tag, bits_per_sample);
+}
+
+// The speaker position bits of the extensible header follow the order of Audio::Channel after Unknown.
+static Audio::ChannelMap channel_map_for(u16 channel_count, u32 speaker_position_mask)
+{
+ Vector<Audio::Channel, Audio::ChannelMap::capacity()> channels;
+ for (u8 position = 1; position < to_underlying(Audio::Channel::Count); position++) {
+ if ((speaker_position_mask >> (position - 1)) & 1)
+ channels.append(static_cast<Audio::Channel>(position));
+ }
+ if (channels.size() == channel_count)
+ return Audio::ChannelMap(channels);
+
+ switch (channel_count) {
+ case 1:
+ return Audio::ChannelMap::mono();
+ case 2:
+ return Audio::ChannelMap::stereo();
+ case 4:
+ return Audio::ChannelMap::quadrophonic();
+ case 6:
+ return Audio::ChannelMap::surround_5_1();
+ case 8:
+ return Audio::ChannelMap::surround_7_1();
+ default:
+ break;
+ }
+ channels.clear();
+ channels.resize(channel_count);
+ return Audio::ChannelMap(channels);
+}
+
+static DecoderErrorOr<SampleFormat> parse_format_chunk(MediaStreamCursor& cursor, u32 chunk_size)
+{
+ if (chunk_size < FORMAT_CHUNK_SIZE)
+ return DecoderError::corrupted("WAVE fmt chunk is too small"sv);
+
+ auto format_tag = TRY(cursor.read_value<u16>(AK::Endianness::Little));
+ auto channel_count = TRY(cursor.read_value<u16>(AK::Endianness::Little));
+ auto sample_rate = TRY(cursor.read_value<u32>(AK::Endianness::Little));
+ TRY(cursor.read_value<u32>(AK::Endianness::Little)); // Average bytes per second, which the fields around it determine.
+ auto bytes_per_frame = TRY(cursor.read_value<u16>(AK::Endianness::Little));
+ auto bits_per_sample = TRY(cursor.read_value<u16>(AK::Endianness::Little));
+
+ u32 speaker_position_mask = 0;
+ if (format_tag == FORMAT_TAG_EXTENSIBLE) {
+ if (chunk_size < EXTENSIBLE_FORMAT_CHUNK_SIZE)
+ return DecoderError::corrupted("WAVE extensible fmt chunk is too small"sv);
+ TRY(cursor.read_value<u16>(AK::Endianness::Little)); // Extension size.
+ TRY(cursor.read_value<u16>(AK::Endianness::Little)); // Valid bits per sample, within the container size above.
+ speaker_position_mask = TRY(cursor.read_value<u32>(AK::Endianness::Little));
+ format_tag = TRY(cursor.read_value<u16>(AK::Endianness::Little));
+ Array<u8, MEDIA_SUBTYPE_GUID_TAIL.size()> subformat_guid_tail;
+ TRY(cursor.read_until_filled(subformat_guid_tail.span()));
+ if (subformat_guid_tail.span() != MEDIA_SUBTYPE_GUID_TAIL.span())
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "WAVE subformat is not a media subtype"sv);
+ }
+
+ if (channel_count == 0 || sample_rate == 0)
+ return DecoderError::corrupted("WAVE fmt chunk declares no channels or no sample rate"sv);
+ if (channel_count > Audio::ChannelMap::capacity())
+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "WAVE stream has {} channels", channel_count);
+
+ auto codec_id = TRY(codec_id_for(format_tag, bits_per_sample));
+
+ auto bytes_per_frame_of_samples = channel_count * ((bits_per_sample + 7) / 8);
+ if (bytes_per_frame == 0)
+ bytes_per_frame = bytes_per_frame_of_samples;
+ else if (bytes_per_frame != bytes_per_frame_of_samples)
+ return DecoderError::corrupted("WAVE block alignment disagrees with its channels and sample size"sv);
+
+ Checked<u32> bytes_per_second = sample_rate;
+ bytes_per_second *= bytes_per_frame;
+ if (bytes_per_second.has_overflow())
+ return DecoderError::corrupted("WAVE stream's byte rate does not fit in 32 bits"sv);
+
+ return SampleFormat { codec_id, sample_rate, bytes_per_frame, bytes_per_second.value(), channel_map_for(channel_count, speaker_position_mask) };
+}
+
+DecoderErrorOr<Reader> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
+{
+ Array<u8, RIFF_HEADER_SIZE> riff_header;
+ TRY(cursor->seek_to_position(0));
+ auto riff_header_read = cursor->read_into(riff_header.span());
+ if (riff_header_read.is_error() || riff_header_read.value() != riff_header.size()
+ || !chunk_type_is(riff_header.span().trim(4), "RIFF"sv) || !chunk_type_is(riff_header.span().slice(8), "WAVE"sv)) {
+ return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Stream does not begin with a RIFF WAVE header"sv);
+ }
+
+ auto stream_size = cursor->size();
+ Optional<SampleFormat> sample_format;
+ u64 chunk_position = RIFF_HEADER_SIZE;
+ while (true) {
+ if (stream_size.has_value() && chunk_position + CHUNK_HEADER_SIZE > *stream_size)
+ return DecoderError::corrupted("WAVE header has no data chunk"sv);
+ TRY(cursor->seek_to_position(chunk_position));
+ ChunkType chunk_type;
+ TRY(cursor->read_until_filled(chunk_type.span()));
+ auto chunk_size = TRY(cursor->read_value<u32>(AK::Endianness::Little));
+ auto chunk_body = chunk_position + CHUNK_HEADER_SIZE;
+
+ if (chunk_type_is(chunk_type.span(), "fmt "sv)) {
+ sample_format = TRY(parse_format_chunk(*cursor, chunk_size));
+ } else if (chunk_type_is(chunk_type.span(), "data"sv)) {
+ if (!sample_format.has_value())
+ return DecoderError::corrupted("WAVE data chunk precedes its fmt chunk"sv);
+ // Writers that stream leave the size unset or at its maximum, and no size is trusted past the stream's end.
+ Optional<u64> sample_data_end;
+ if (chunk_size != 0 && chunk_size != NumericLimits<u32>::max())
+ sample_data_end = chunk_body + chunk_size;
+ if (stream_size.has_value() && (!sample_data_end.has_value() || *sample_data_end > *stream_size))
+ sample_data_end = *stream_size;
+ return Reader { sample_format.release_value(), static_cast<size_t>(chunk_body), sample_data_end };
+ }
+
+ // Chunks are padded to even sizes.
+ chunk_position = chunk_body + chunk_size + (chunk_size & 1);
+ }
+}
+
+Reader::Reader(SampleFormat sample_format, size_t sample_data_offset, Optional<u64> sample_data_end)
+ : m_sample_format(sample_format)
+ , m_sample_data_offset(sample_data_offset)
+ , m_sample_data_end(sample_data_end)
+{
+}
+
+AK::Duration Reader::duration() const
+{
+ if (!m_sample_data_end.has_value() || *m_sample_data_end <= m_sample_data_offset)
+ return AK::Duration::zero();
+ auto frame_count = (*m_sample_data_end - m_sample_data_offset) / m_sample_format.bytes_per_frame;
+ return AK::Duration::from_time_units(AK::clamp_to<i64>(frame_count), 1, m_sample_format.sample_rate);
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/WAV/Reader.h b/Libraries/LibMedia/Containers/WAV/Reader.h
new file mode 100644
index 00000000000..b5e6c8880ee
--- /dev/null
+++ b/Libraries/LibMedia/Containers/WAV/Reader.h
@@ -0,0 +1,47 @@
+/*
+ * 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/Time.h>
+#include <LibAudio/ChannelMap.h>
+#include <LibMedia/Export.h>
+#include <LibMedia/MediaStream.h>
+#include <LibMediaCodecs/CodecID.h>
+#include <LibMediaCodecs/DecoderError.h>
+
+namespace Media::WAV {
+
+struct SampleFormat {
+ CodecID codec_id;
+ u32 sample_rate;
+ u16 bytes_per_frame;
+ u32 bytes_per_second;
+ Audio::ChannelMap channel_map;
+};
+
+// Reads the RIFF header of a WAVE stream up to its sample data.
+class MEDIA_API Reader {
+public:
+ static DecoderErrorOr<Reader> from_stream(NonnullRefPtr<MediaStreamCursor> const&);
+
+ SampleFormat const& sample_format() const { return m_sample_format; }
+ size_t sample_data_offset() const { return m_sample_data_offset; }
+ // Unknown when the header leaves the size open, as writers that stream do, and the stream's size is unknown too.
+ Optional<u64> sample_data_end() const { return m_sample_data_end; }
+ AK::Duration duration() const;
+
+private:
+ Reader(SampleFormat, size_t sample_data_offset, Optional<u64> sample_data_end);
+
+ SampleFormat m_sample_format;
+ size_t m_sample_data_offset { 0 };
+ Optional<u64> m_sample_data_end;
+};
+
+}
diff --git a/Libraries/LibMedia/Containers/WAV/WAVDemuxer.cpp b/Libraries/LibMedia/Containers/WAV/WAVDemuxer.cpp
new file mode 100644
index 00000000000..4dce4f8a4dd
--- /dev/null
+++ b/Libraries/LibMedia/Containers/WAV/WAVDemuxer.cpp
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Checked.h>
+#include <AK/GenericShorthands.h>
+#include <AK/Math.h>
+#include <LibMedia/Containers/WAV/WAVDemuxer.h>
+#include <LibMediaCodecs/CodedFrame.h>
+
+namespace Media::WAV {
+
+// Packets hold whole sample frames up to this size, a few milliseconds of audio at common rates.
+static constexpr size_t TARGET_PACKET_BYTE_COUNT = 4096;
+
+bool WAVDemuxer::supports_container_mime_type(ContainerMimeType mime_type)
+{
+ return mime_type.container_id == ContainerID::WAV && mime_type.media_type == ContainerMediaType::Audio;
+}
+
+bool WAVDemuxer::supports_codec_in_container(ContainerID container_id, CodecID codec_id)
+{
+ return container_id == ContainerID::WAV && first_is_one_of(codec_id, CodecID::U8, CodecID::S16LE, CodecID::S24LE, CodecID::S32LE, CodecID::F32LE, CodecID::ALaw, CodecID::MuLaw);
+}
+
+static Track create_track(Reader const& reader)
+{
+ Track track { TrackType::Audio, 0, Track::Kind::Main, {}, {} };
+ track.set_audio_data({ .sample_specification = Audio::SampleSpecification(reader.sample_format().sample_rate, reader.sample_format().channel_map) });
+ track.set_parsed_codec(ParsedCodec { reader.sample_format().codec_id });
+ return track;
+}
+
+DecoderErrorOr<NonnullRefPtr<Demuxer>> WAVDemuxer::from_stream(NonnullRefPtr<MediaStream> const& stream)
+{
+ auto reader = TRY(Reader::from_stream(stream->create_cursor()));
+ auto demuxer = make_ref_counted<WAVDemuxer>(stream, reader, create_track(reader));
+ demuxer->start_buffered_scan_thread();
+ return demuxer;
+}
+
+WAVDemuxer::WAVDemuxer(NonnullRefPtr<MediaStream> const& stream, Reader reader, Track track)
+ : m_stream(stream)
+ , m_reader(reader)
+ , m_track(move(track))
+{
+ auto bytes_per_frame = m_reader.sample_format().bytes_per_frame;
+ m_packet_byte_count = max<size_t>(bytes_per_frame, TARGET_PACKET_BYTE_COUNT / bytes_per_frame * bytes_per_frame);
+}
+
+WAVDemuxer::~WAVDemuxer()
+{
+ if (m_buffered_scan_thread != nullptr)
+ m_buffered_scan_thread->shutdown();
+}
+
+static BufferedRangesScan buffered_time_ranges(Reader const& reader, Vector<MediaStream::ByteRange> const& byte_ranges)
+{
+ u64 sample_data_start = reader.sample_data_offset();
+ auto sample_data_end = reader.sample_data_end().value_or(NumericLimits<u64>::max());
+ auto time_at = [&](u64 position) {
+ return AK::Duration::from_time_units(AK::clamp_to<i64>(position - sample_data_start), 1, reader.sample_format().bytes_per_second);
+ };
+
+ BufferedRangesScan scan;
+ for (auto const& byte_range : byte_ranges) {
+ auto start = max(byte_range.start, sample_data_start);
+ auto end = min(byte_range.end, sample_data_end);
+ if (start < end)
+ scan.time_ranges.add_range(time_at(start), time_at(end));
+ }
+ if (!byte_ranges.is_empty())
+ scan.last_byte_range_has_samples = byte_ranges.last().end > sample_data_start && byte_ranges.last().start < sample_data_end;
+ return scan;
+}
+
+void WAVDemuxer::start_buffered_scan_thread()
+{
+ DemuxerScanState initial_state;
+ initial_state.duration = m_reader.duration();
+
+ m_buffered_scan_thread = DemuxerScanThread<Reader>::start(m_stream, move(initial_state), m_reader,
+ [](MediaStream::Availability const& availability, Reader& reader) {
+ return DemuxerScanState::create_from_track_scans({ buffered_time_ranges(reader, availability.byte_ranges) }, reader.duration(), availability.closing_bytes_are_available());
+ });
+}
+
+WAVDemuxer::TrackStatus& WAVDemuxer::track_status()
+{
+ MutexLocker locker { m_track_status_mutex };
+ VERIFY(m_track_status.has_value());
+ return *m_track_status;
+}
+
+DecoderErrorOr<void> WAVDemuxer::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 { move(cursor), m_reader.sample_data_offset(), true };
+ return {};
+}
+
+DecoderErrorOr<Vector<Track>> WAVDemuxer::get_tracks_for_type(TrackType type)
+{
+ Vector<Track> tracks;
+ if (type == TrackType::Audio)
+ tracks.append(m_track);
+ return tracks;
+}
+
+DecoderErrorOr<Optional<Track>> WAVDemuxer::get_preferred_track_for_type(TrackType type)
+{
+ if (type != TrackType::Audio)
+ return Optional<Track> {};
+ return Optional<Track> { m_track };
+}
+
+DecoderErrorOr<CodedFrame> WAVDemuxer::get_next_sample_for_track(Track const& track)
+{
+ VERIFY(track == m_track);
+ auto& status = track_status();
+ auto const& sample_format = m_reader.sample_format();
+
+ u64 byte_count = m_packet_byte_count;
+ if (auto sample_data_end = m_reader.sample_data_end(); sample_data_end.has_value()) {
+ if (status.position >= *sample_data_end)
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "End of stream"sv);
+ byte_count = min(byte_count, *sample_data_end - status.position);
+ }
+ auto frame_count = byte_count / sample_format.bytes_per_frame;
+ if (frame_count == 0)
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "End of stream"sv);
+
+ auto data = DECODER_TRY_ALLOC(FixedArray<u8>::create(frame_count * sample_format.bytes_per_frame));
+ TRY(status.cursor->seek_to_position(status.position));
+ auto read_byte_count = TRY(status.cursor->read_into(data.span()));
+ // A stream that ends before its header said, or never said, delivers what it has in whole frames.
+ auto read_frame_count = read_byte_count / sample_format.bytes_per_frame;
+ if (read_frame_count == 0)
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "End of stream"sv);
+ if (read_frame_count != frame_count)
+ data = DECODER_TRY_ALLOC(FixedArray<u8>::create(data.span().trim(read_frame_count * sample_format.bytes_per_frame)));
+
+ // A decoder needs no configuration beyond the frames themselves, but it does need one frame to be
+ // marked as the start of a decode sequence.
+ Optional<FixedArray<u8>> codec_configuration;
+ if (status.needs_codec_configuration) {
+ status.needs_codec_configuration = false;
+ codec_configuration = FixedArray<u8> {};
+ }
+
+ auto first_frame_index = (status.position - m_reader.sample_data_offset()) / sample_format.bytes_per_frame;
+ auto timestamp = AK::Duration::from_time_units(AK::clamp_to<i64>(first_frame_index), 1, sample_format.sample_rate);
+ auto duration = AK::Duration::from_time_units(AK::clamp_to<i64>(read_frame_count), 1, sample_format.sample_rate);
+ status.position += read_frame_count * sample_format.bytes_per_frame;
+
+ return CodedFrame(sample_format.codec_id, timestamp, timestamp, duration, FrameFlags::Keyframe, move(data), move(codec_configuration));
+}
+
+AK::Duration WAVDemuxer::select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode)
+{
+ return target;
+}
+
+DecoderErrorOr<DemuxerSeekResult> WAVDemuxer::seek_to_most_recent_keyframe(Track const& track, AK::Duration timestamp, DemuxerSeekOptions options)
+{
+ VERIFY(track == m_track);
+ auto& status = track_status();
+ auto const& sample_format = m_reader.sample_format();
+
+ if (has_flag(options, DemuxerSeekOptions::NeedCodecConfiguration))
+ status.needs_codec_configuration = true;
+
+ Checked<u64> position = static_cast<u64>(max<i64>(0, timestamp.to_time_units(1, sample_format.sample_rate)));
+ position *= sample_format.bytes_per_frame;
+ position += m_reader.sample_data_offset();
+ auto sample_data_end = m_reader.sample_data_end().value_or(NumericLimits<u64>::max());
+ if (position.has_overflow() || position.value() > sample_data_end)
+ status.position = sample_data_end;
+ else
+ status.position = position.value();
+ return DemuxerSeekResult::MovedPosition;
+}
+
+DecoderErrorOr<AK::Duration> WAVDemuxer::total_duration()
+{
+ return m_reader.duration();
+}
+
+DecoderErrorOr<AK::Duration> WAVDemuxer::duration_of_track(Track const&)
+{
+ return total_duration();
+}
+
+DemuxerScanState const& WAVDemuxer::scan_state() const
+{
+ return m_buffered_scan_thread->main_thread_state();
+}
+
+void WAVDemuxer::set_scan_state_change_handler(ScanStateChangeHandler handler)
+{
+ m_buffered_scan_thread->set_change_handler([handler = move(handler)] {
+ if (handler)
+ handler(TimeRanges {});
+ });
+}
+
+void WAVDemuxer::set_blocking_reads_aborted_for_track(Track const&)
+{
+ track_status().cursor->abort();
+}
+
+void WAVDemuxer::reset_blocking_reads_aborted_for_track(Track const&)
+{
+ track_status().cursor->reset_abort();
+}
+
+void WAVDemuxer::set_read_blocked_change_handler_for_track(Track const&, ReadBlockedChangeHandler handler)
+{
+ track_status().cursor->set_blocked_change_handler(move(handler));
+}
+
+}
diff --git a/Libraries/LibMedia/Containers/WAV/WAVDemuxer.h b/Libraries/LibMedia/Containers/WAV/WAVDemuxer.h
new file mode 100644
index 00000000000..20fbbd5643c
--- /dev/null
+++ b/Libraries/LibMedia/Containers/WAV/WAVDemuxer.h
@@ -0,0 +1,61 @@
+/*
+ * 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/WAV/Reader.h>
+#include <LibMedia/Demuxer.h>
+#include <LibMedia/DemuxerScanThread.h>
+#include <LibMedia/Export.h>
+#include <LibMedia/Forward.h>
+
+namespace Media::WAV {
+
+class MEDIA_API WAVDemuxer 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);
+
+ WAVDemuxer(NonnullRefPtr<MediaStream> const&, Reader, Track);
+ ~WAVDemuxer();
+
+ 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 TrackStatus {
+ NonnullRefPtr<MediaStreamCursor> cursor;
+ u64 position { 0 };
+ bool needs_codec_configuration { true };
+ };
+
+ void start_buffered_scan_thread();
+ TrackStatus& track_status();
+
+ NonnullRefPtr<MediaStream> m_stream;
+ Reader m_reader;
+ Track m_track;
+ size_t m_packet_byte_count { 0 };
+ RefPtr<DemuxerScanThread<Reader>> m_buffered_scan_thread;
+ Mutex m_track_status_mutex;
+ Optional<TrackStatus> m_track_status;
+};
+
+}
diff --git a/Libraries/LibMedia/DemuxerRegistry.cpp b/Libraries/LibMedia/DemuxerRegistry.cpp
index 7900b9c7856..bc114c45c91 100644
--- a/Libraries/LibMedia/DemuxerRegistry.cpp
+++ b/Libraries/LibMedia/DemuxerRegistry.cpp
@@ -9,6 +9,7 @@
#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>
#include <LibMedia/Containers/MP3/MP3Demuxer.h>
#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
+#include <LibMedia/Containers/WAV/WAVDemuxer.h>
#include <LibMedia/DemuxerRegistry.h>
#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
#include <LibMedia/MediaStream.h>
@@ -28,6 +29,7 @@ struct DemuxerRegistration {
static constexpr Array demuxers_in_priority_order {
DemuxerRegistration { ISOBMFF::ISOBMFFDemuxer::from_stream, ISOBMFF::ISOBMFFDemuxer::supports_container_mime_type, ISOBMFF::ISOBMFFDemuxer::supports_codec_in_container },
DemuxerRegistration { Matroska::MatroskaDemuxer::from_stream, Matroska::MatroskaDemuxer::supports_container_mime_type, Matroska::MatroskaDemuxer::supports_codec_in_container },
+ DemuxerRegistration { WAV::WAVDemuxer::from_stream, WAV::WAVDemuxer::supports_container_mime_type, WAV::WAVDemuxer::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 66294bec853..af497a37614 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/ConstantBitrateContainerNavigator.h>
#include <LibMedia/Containers/FLACNavigator.h>
#include <LibMedia/Containers/IndexedContainerNavigator.h>
#include <LibMedia/Containers/OggNavigator.h>
@@ -40,12 +39,12 @@ bool FFmpegDemuxer::supports_container_mime_type(ContainerMimeType mime_type)
case ContainerID::ISOBMFF:
return mime_type.media_type != ContainerMediaType::Application;
case ContainerID::FLAC:
- case ContainerID::WAV:
return mime_type.media_type == ContainerMediaType::Audio;
case ContainerID::Matroska:
case ContainerID::WebM:
case ContainerID::ADTS:
case ContainerID::MPEGAudio:
+ case ContainerID::WAV:
return false;
}
VERIFY_NOT_REACHED();
@@ -60,12 +59,11 @@ bool FFmpegDemuxer::supports_codec_in_container(ContainerID container_id, CodecI
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::WAV:
- return first_is_one_of(codec_id, CodecID::U8, CodecID::S16LE, CodecID::S24LE, CodecID::S32LE, CodecID::F32LE, CodecID::ALaw, CodecID::MuLaw);
case ContainerID::ADTS:
case ContainerID::Matroska:
case ContainerID::WebM:
case ContainerID::MPEGAudio:
+ case ContainerID::WAV:
return false;
}
VERIFY_NOT_REACHED();
@@ -147,16 +145,13 @@ 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,wav", 0) < 0)
+ if (av_dict_set(&options, "format_whitelist", "flac,ogg", 0) < 0)
return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg format whitelist"sv);
auto const& codecs = codec_whitelist();
if (av_dict_set(&options, "codec_whitelist", codecs.characters(), 0) < 0)
return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg codec whitelist"sv);
- // Reduce the maximum packet size for the WAV demuxer, so that playback begins sooner.
- av_dict_set(&options, "max_size", "4096", 0);
-
// The smallest probe FFmpeg allows, so a format it was built without fails here instead of a mebibyte in.
av_dict_set(&options, "formatprobesize", "2048", 0);
@@ -371,23 +366,6 @@ OwnPtr<ContainerNavigator> FFmpegDemuxer::create_single_track_container_navigato
}
}
- if (format_name == "wav"sv && context.nb_streams > 0) {
- auto* stream = context.streams[0];
- auto* codec_par = stream->codecpar;
- if (codec_par->block_align <= 0)
- return nullptr;
- if (codec_par->sample_rate <= 0)
- return nullptr;
- if (Checked<u32>::multiplication_would_overflow(static_cast<u32>(codec_par->block_align), codec_par->sample_rate))
- return nullptr;
- auto bytes_per_second = static_cast<u32>(codec_par->block_align) * codec_par->sample_rate;
- auto entry_count = avformat_index_get_entries_count(stream);
- if (entry_count <= 0)
- return nullptr;
- auto data_offset = avformat_index_get_entry(stream, 0)->pos;
- return make<ConstantBitrateContainerNavigator>(data_offset, bytes_per_second, codec_par->block_align);
- }
-
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 46a91d50f7e..67a6f0079cc 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,wav --disable-optimizations",
+ "./configure --prefix=/app --libdir=/app/lib --enable-shared --disable-static --enable-pic --disable-doc --enable-debug --enable-runtime-cpudetect --disable-autodetect --build-suffix=-ladybird --disable-everything --disable-network --disable-ffmpeg --disable-ffplay --disable-ffprobe --enable-avcodec --disable-avdevice --enable-avformat --disable-avfilter --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",
"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 0fcc0ac2522..85d5dc28779 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,wav")
+ set(OPTIONS "${OPTIONS} --enable-demuxer=ogg,flac")
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 c01ceba2cc7..4fc0a4be769 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": 1,
+ "port-version": 2,
"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 a4eef4394b1..1d9c8b68a13 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -39,6 +39,7 @@ set(TEST_SOURCES
TestVorbisDecode.cpp
TestVP9Decode.cpp
TestWav.cpp
+ TestWAVDemuxer.cpp
)
if (APPLE)
@@ -63,6 +64,7 @@ target_link_libraries(TestDecodedAudioProducer PRIVATE LibGfx)
target_link_libraries(TestDisplayingVideoSink PRIVATE LibGfx)
target_link_libraries(TestVP9Decode PRIVATE LibGfx)
target_link_libraries(TestFFmpegDemuxer PRIVATE LibThreading)
+target_link_libraries(TestWAVDemuxer PRIVATE LibThreading)
target_link_libraries(TestISOBMFF PRIVATE LibThreading)
target_link_libraries(TestMediaTime PRIVATE LibThreading)
target_link_libraries(TestVideoFramePool PRIVATE LibThreading)
diff --git a/Tests/LibMedia/TestFFmpegAudioNormalization.cpp b/Tests/LibMedia/TestFFmpegAudioNormalization.cpp
index d173151ac50..c372e3851a6 100644
--- a/Tests/LibMedia/TestFFmpegAudioNormalization.cpp
+++ b/Tests/LibMedia/TestFFmpegAudioNormalization.cpp
@@ -9,8 +9,8 @@
#include <AK/StringView.h>
#include <AK/Time.h>
#include <LibCore/EventLoop.h>
+#include <LibMedia/Containers/WAV/WAVDemuxer.h>
#include <LibMedia/DecoderRegistrations.h>
-#include <LibMedia/FFmpeg/FFmpegDemuxer.h>
#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMedia/PipelineStatus.h>
#include <LibMedia/Producers/DecodedAudioProducer.h>
@@ -84,7 +84,7 @@ static void decode_and_expect()
constexpr size_t sample_count = 2048;
auto wav_data = make_square_wav<Sample>(sample_count);
auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(wav_data);
- auto demuxer = MUST(Media::FFmpeg::FFmpegDemuxer::from_stream(stream));
+ auto demuxer = MUST(Media::WAV::WAVDemuxer::from_stream(stream));
auto tracks = TRY_OR_FAIL(demuxer->get_tracks_for_type(Media::TrackType::Audio));
VERIFY(!tracks.is_empty());
diff --git a/Tests/LibMedia/TestFFmpegDemuxer.cpp b/Tests/LibMedia/TestFFmpegDemuxer.cpp
index b6bfb81d81a..8ff9ccf7115 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 }) {
+ for (auto path : { "./vfr.mkv"sv, "./avc.mp4"sv, "./buffered-ranges/tone.wav"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,7 +32,7 @@ TEST_CASE(read_after_aborted_blocking_read)
// The fix was to only return AVERROR_EOF from the IO context callbacks, and then determine whether to change
// the error to an Aborted error within the FFmpegDemuxer on top of the avformat context that used the IO.
- auto file = MUST(Core::File::open("./buffered-ranges/tone.wav"sv, Core::File::OpenMode::Read));
+ auto file = MUST(Core::File::open("./buffered-ranges/tone.flac"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
diff --git a/Tests/LibMedia/TestWAVDemuxer.cpp b/Tests/LibMedia/TestWAVDemuxer.cpp
new file mode 100644
index 00000000000..0088f5d2653
--- /dev/null
+++ b/Tests/LibMedia/TestWAVDemuxer.cpp
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Atomic.h>
+#include <AK/Endian.h>
+#include <AK/MemoryStream.h>
+#include <LibCore/File.h>
+#include <LibMedia/Containers/WAV/WAVDemuxer.h>
+#include <LibMedia/IncrementallyPopulatedStream.h>
+#include <LibMediaCodecs/CodedFrame.h>
+#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+
+namespace {
+
+struct WaveLayout {
+ u16 format_tag { 1 };
+ u16 channel_count { 2 };
+ u32 sample_rate { 48000 };
+ u16 bits_per_sample { 16 };
+ // Writes the extensible form of the header.
+ Optional<u32> speaker_position_mask {};
+ u32 sample_data_size { 48000 * 4 };
+ Optional<u32> declared_sample_data_size {};
+ // An odd size checks that chunks are padded to even sizes.
+ u32 list_chunk_size { 0 };
+};
+
+ByteBuffer make_wave(WaveLayout const& layout)
+{
+ static constexpr Array<u8, 14> media_subtype_guid_tail { 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 };
+ auto padded = [](u32 size) { return size + (size & 1); };
+ auto bytes_per_frame = static_cast<u16>(layout.channel_count * ((layout.bits_per_sample + 7) / 8));
+ u32 format_chunk_size = layout.speaker_position_mask.has_value() ? 40 : 16;
+ u32 list_chunk_total_size = layout.list_chunk_size > 0 ? 8 + padded(layout.list_chunk_size) : 0;
+
+ AllocatingMemoryStream wave;
+ auto write_chunk_header = [&](StringView type, u32 size) {
+ MUST(wave.write_until_depleted(type.bytes()));
+ MUST(wave.write_value<LittleEndian<u32>>(size));
+ };
+ write_chunk_header("RIFF"sv, 4 + 8 + format_chunk_size + list_chunk_total_size + 8 + layout.sample_data_size);
+ MUST(wave.write_until_depleted("WAVE"sv.bytes()));
+
+ write_chunk_header("fmt "sv, format_chunk_size);
+ MUST(wave.write_value<LittleEndian<u16>>(layout.speaker_position_mask.has_value() ? 0xFFFE : layout.format_tag));
+ MUST(wave.write_value<LittleEndian<u16>>(layout.channel_count));
+ MUST(wave.write_value<LittleEndian<u32>>(layout.sample_rate));
+ MUST(wave.write_value<LittleEndian<u32>>(layout.sample_rate * bytes_per_frame));
+ MUST(wave.write_value<LittleEndian<u16>>(bytes_per_frame));
+ MUST(wave.write_value<LittleEndian<u16>>(layout.bits_per_sample));
+ if (layout.speaker_position_mask.has_value()) {
+ MUST(wave.write_value<LittleEndian<u16>>(22));
+ MUST(wave.write_value<LittleEndian<u16>>(layout.bits_per_sample));
+ MUST(wave.write_value<LittleEndian<u32>>(*layout.speaker_position_mask));
+ MUST(wave.write_value<LittleEndian<u16>>(layout.format_tag));
+ MUST(wave.write_until_depleted(media_subtype_guid_tail.span()));
+ }
+
+ auto silence = MUST(ByteBuffer::create_zeroed(max(layout.sample_data_size, list_chunk_total_size)));
+ if (layout.list_chunk_size > 0) {
+ write_chunk_header("LIST"sv, layout.list_chunk_size);
+ MUST(wave.write_until_depleted(silence.bytes().trim(padded(layout.list_chunk_size))));
+ }
+
+ write_chunk_header("data"sv, layout.declared_sample_data_size.value_or(layout.sample_data_size));
+ MUST(wave.write_until_depleted(silence.bytes().trim(layout.sample_data_size)));
+ return MUST(wave.read_until_eof());
+}
+
+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::WAV::WAVDemuxer::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;
+}
+
+struct PacketIdentity {
+ AK::Duration timestamp;
+ size_t byte_count { 0 };
+ bool operator==(PacketIdentity const&) const = default;
+};
+
+Vector<PacketIdentity> read_every_packet(Media::Demuxer& demuxer, Media::Track const& track)
+{
+ Vector<PacketIdentity> packets;
+ while (true) {
+ auto packet = demuxer.get_next_sample_for_track(track);
+ if (packet.is_error()) {
+ EXPECT_EQ(packet.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ packets.append({ packet.value().presentation_timestamp(), packet.value().data().size() });
+ }
+ return packets;
+}
+
+TEST_CASE(demuxer_describes_the_only_track_of_the_stream)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone.wav"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(), 48000u);
+ EXPECT_EQ(tracks[0].audio_data().sample_specification.channel_map(), Audio::ChannelMap::stereo());
+ EXPECT_EQ(tracks[0].parsed_codec().codec_id(), Media::CodecID::S16LE);
+
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::from_seconds(8));
+}
+
+TEST_CASE(demuxer_reads_every_sample_frame_with_exact_timestamps)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone.wav"sv)));
+ auto track = audio_track(*demuxer);
+
+ size_t packet_count = 0;
+ i64 frame_count = 0;
+ while (true) {
+ auto packet = demuxer->get_next_sample_for_track(track);
+ if (packet.is_error()) {
+ EXPECT_EQ(packet.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ EXPECT_EQ(packet.value().presentation_timestamp(), AK::Duration::from_time_units(frame_count, 1, 48000));
+ EXPECT_EQ(packet.value().data().size(), 4096u);
+ EXPECT(packet.value().is_keyframe());
+ EXPECT_EQ(packet.value().new_codec_configuration().has_value(), packet_count == 0);
+ frame_count += static_cast<i64>(packet.value().data().size() / 4);
+ packet_count++;
+ }
+
+ EXPECT_EQ(packet_count, 375u);
+ EXPECT_EQ(frame_count, 384000);
+}
+
+TEST_CASE(demuxer_seeks_to_the_sample_frame_holding_a_timestamp)
+{
+ auto demuxer = MUST(demuxer_for(read_fixture("buffered-ranges/tone.wav"sv)));
+ auto track = audio_track(*demuxer);
+
+ EXPECT_EQ(MUST(demuxer->seek_to_most_recent_keyframe(track, AK::Duration::from_milliseconds(3'500))), Media::DemuxerSeekResult::MovedPosition);
+ EXPECT_EQ(MUST(demuxer->get_next_sample_for_track(track)).presentation_timestamp(), AK::Duration::from_milliseconds(3'500));
+
+ // A target between two sample frames lands on the earlier one.
+ auto target = AK::Duration::from_microseconds(1'000'010);
+ MUST(demuxer->seek_to_most_recent_keyframe(track, target));
+ auto packet = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(packet.presentation_timestamp(), AK::Duration::from_seconds(1));
+ EXPECT(packet.presentation_timestamp() + AK::Duration::from_time_units(1, 1, 48000) > target);
+
+ 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));
+ packet = MUST(demuxer->get_next_sample_for_track(track));
+ EXPECT_EQ(packet.presentation_timestamp(), AK::Duration::zero());
+ EXPECT(packet.new_codec_configuration().has_value());
+}
+
+// An aborted read is retried by the next call, which delivers the packet the aborted read was after, so a pass
+// interrupted anywhere delivers the same packets as one that was not.
+TEST_CASE(demuxer_resumes_an_aborted_read_with_the_packet_it_was_reading)
+{
+ auto file_data = read_fixture("buffered-ranges/tone.wav"sv);
+
+ Vector<PacketIdentity> expected_packets;
+ {
+ auto demuxer = MUST(demuxer_for(file_data));
+ auto track = audio_track(*demuxer);
+ expected_packets = read_every_packet(*demuxer, track);
+ }
+
+ // The data ends inside a packet, so the read that blocks has part of its packet.
+ 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::WAV::WAVDemuxer::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<PacketIdentity> actual_packets;
+ auto reader_thread = Threading::Thread::construct("TestReader"sv, [&]() -> intptr_t {
+ while (true) {
+ auto packet = demuxer->get_next_sample_for_track(track);
+ if (packet.is_error()) {
+ EXPECT_EQ(packet.error().category(), Media::DecoderErrorCategory::Aborted);
+ break;
+ }
+ actual_packets.append({ packet.value().presentation_timestamp(), packet.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_packets.extend(read_every_packet(*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_packets.size(), expected_packets.size());
+ for (size_t index = 0; index < min(actual_packets.size(), expected_packets.size()); index++) {
+ if (actual_packets[index] != expected_packets[index]) {
+ FAIL(ByteString::formatted("Packet {} differs after the abort: {}ms/{} bytes instead of {}ms/{} bytes", index, actual_packets[index].timestamp.to_milliseconds(), actual_packets[index].byte_count, expected_packets[index].timestamp.to_milliseconds(), expected_packets[index].byte_count));
+ break;
+ }
+ }
+}
+
+Audio::ChannelMap channel_map_of(WaveLayout const& layout)
+{
+ auto demuxer = MUST(demuxer_for(make_wave(layout)));
+ return MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio))[0].audio_data().sample_specification.channel_map();
+}
+
+TEST_CASE(demuxer_reads_speaker_positions_from_an_extensible_header)
+{
+ using Audio::Channel;
+ constexpr u32 front_left = 1 << 0;
+ constexpr u32 front_right = 1 << 1;
+ constexpr u32 side_left = 1 << 9;
+ constexpr u32 side_right = 1 << 10;
+
+ EXPECT_EQ(channel_map_of({ .channel_count = 4, .speaker_position_mask = front_left | front_right | side_left | side_right }), Audio::ChannelMap(Channel::FrontLeft, Channel::FrontRight, Channel::SideLeft, Channel::SideRight));
+ EXPECT_EQ(channel_map_of({ .channel_count = 6, .speaker_position_mask = 0x3F }), Audio::ChannelMap::surround_5_1());
+
+ // Positions that do not account for every channel are ignored in favour of the usual layout for the count.
+ EXPECT_EQ(channel_map_of({ .channel_count = 6, .speaker_position_mask = front_left | front_right }), Audio::ChannelMap::surround_5_1());
+ EXPECT_EQ(channel_map_of({ .channel_count = 6 }), Audio::ChannelMap::surround_5_1());
+ EXPECT_EQ(channel_map_of({ .channel_count = 1 }), Audio::ChannelMap::mono());
+
+ auto unplaced = channel_map_of({ .channel_count = 3 });
+ EXPECT_EQ(unplaced.channel_count(), 3);
+ EXPECT_EQ(unplaced.channel_at(0), Channel::Unknown);
+}
+
+Media::CodecID codec_id_of(WaveLayout const& layout)
+{
+ auto demuxer = MUST(demuxer_for(make_wave(layout)));
+ return MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio))[0].parsed_codec().codec_id();
+}
+
+TEST_CASE(demuxer_identifies_every_sample_format_it_supports)
+{
+ EXPECT_EQ(codec_id_of({ .bits_per_sample = 8 }), Media::CodecID::U8);
+ EXPECT_EQ(codec_id_of({ .bits_per_sample = 16 }), Media::CodecID::S16LE);
+ EXPECT_EQ(codec_id_of({ .bits_per_sample = 24 }), Media::CodecID::S24LE);
+ EXPECT_EQ(codec_id_of({ .bits_per_sample = 32 }), Media::CodecID::S32LE);
+ EXPECT_EQ(codec_id_of({ .format_tag = 3, .bits_per_sample = 32 }), Media::CodecID::F32LE);
+ EXPECT_EQ(codec_id_of({ .format_tag = 6, .bits_per_sample = 8 }), Media::CodecID::ALaw);
+ EXPECT_EQ(codec_id_of({ .format_tag = 7, .bits_per_sample = 8 }), Media::CodecID::MuLaw);
+ EXPECT_EQ(codec_id_of({ .format_tag = 3, .bits_per_sample = 32, .speaker_position_mask = 0x3 }), Media::CodecID::F32LE);
+}
+
+TEST_CASE(demuxer_declines_what_it_cannot_read)
+{
+ auto not_a_wave = demuxer_for(MUST(ByteBuffer::create_zeroed(4096)));
+ EXPECT_EQ(not_a_wave.error().category(), Media::DecoderErrorCategory::UnrecognizedFormat);
+
+ auto adpcm = demuxer_for(make_wave({ .format_tag = 0x11, .bits_per_sample = 4 }));
+ EXPECT_EQ(adpcm.error().category(), Media::DecoderErrorCategory::NotImplemented);
+
+ auto double_precision = demuxer_for(make_wave({ .format_tag = 3, .bits_per_sample = 64 }));
+ EXPECT_EQ(double_precision.error().category(), Media::DecoderErrorCategory::NotImplemented);
+
+ auto header_without_data = make_wave({});
+ header_without_data.resize(12 + 8 + 16);
+ auto no_data_chunk = demuxer_for(header_without_data);
+ EXPECT_EQ(no_data_chunk.error().category(), Media::DecoderErrorCategory::Corrupted);
+}
+
+TEST_CASE(demuxer_reads_to_the_end_of_a_stream_whose_data_size_is_left_open)
+{
+ constexpr u32 frame_count = 2500;
+ auto demuxer = MUST(demuxer_for(make_wave({ .sample_data_size = frame_count * 4, .declared_sample_data_size = NumericLimits<u32>::max(), .list_chunk_size = 7 })));
+ auto track = audio_track(*demuxer);
+
+ EXPECT_EQ(MUST(demuxer->total_duration()), AK::Duration::from_time_units(frame_count, 1, 48000));
+
+ auto packets = read_every_packet(*demuxer, track);
+ size_t byte_count = 0;
+ for (auto const& packet : packets)
+ byte_count += packet.byte_count;
+ EXPECT_EQ(byte_count, frame_count * 4u);
+ EXPECT_EQ(packets.last().timestamp, AK::Duration::from_time_units(frame_count - (packets.last().byte_count / 4), 1, 48000));
+}
+
+}