Skip to content

Truly independent web browser

LibMedia: Ensure that MP3 and ADTS demuxers reproduce aborted frames

Zaggy10241317f4dc8b3f
diff --git a/Libraries/LibMedia/Containers/ADTS/ADTSDemuxer.cpp b/Libraries/LibMedia/Containers/ADTS/ADTSDemuxer.cpp
index 55916f1258a..b1d68635462 100644
--- a/Libraries/LibMedia/Containers/ADTS/ADTSDemuxer.cpp
+++ b/Libraries/LibMedia/Containers/ADTS/ADTSDemuxer.cpp
@@ -20,24 +20,30 @@ public:
{
FrameIterator iterator { NonnullRefPtr { cursor }, position, FrameIterator::Resynchronize::Yes };
auto frame = iterator.next();
- if (!frame.has_value())
+ if (frame.is_error() || !frame.value().has_value())
return {};
return Frame {
- .position = frame->position,
- .byte_size = frame->header.frame_byte_size,
- .duration = { frame->header.sample_count, frame->header.sample_rate },
+ .position = frame.value()->position,
+ .byte_size = frame.value()->header.frame_byte_size,
+ .duration = { frame.value()->header.sample_count, frame.value()->header.sample_rate },
};
}
virtual Optional<size_t> find_boundary_at_or_after(MediaStreamCursor& cursor, size_t start_byte, size_t upper_bound) const override
{
- return Reader::find_frame_boundary_at_or_after(NonnullRefPtr { cursor }, start_byte, upper_bound);
+ auto boundary = Reader::find_frame_boundary_at_or_after(NonnullRefPtr { cursor }, start_byte, upper_bound);
+ if (boundary.is_error())
+ return {};
+ return boundary.release_value();
}
virtual Optional<size_t> find_boundary_at_or_before(MediaStreamCursor& cursor, size_t target_byte, size_t lower_bound, size_t upper_bound) const override
{
- return Reader::find_frame_boundary_at_or_before(NonnullRefPtr { cursor }, target_byte, lower_bound, upper_bound);
+ auto boundary = Reader::find_frame_boundary_at_or_before(NonnullRefPtr { cursor }, target_byte, lower_bound, upper_bound);
+ if (boundary.is_error())
+ return {};
+ return boundary.release_value();
}
};
@@ -88,7 +94,7 @@ static DecoderErrorOr<Track> create_track(Reader const& reader, ReadonlyBytes co
DecoderErrorOr<NonnullRefPtr<Demuxer>> ADTSDemuxer::from_stream(NonnullRefPtr<MediaStream> const& stream)
{
- auto reader = Reader::from_stream(stream->create_cursor());
+ auto reader = TRY(Reader::from_stream(stream->create_cursor()));
if (!reader.has_value())
return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Found no ADTS frames in the stream"sv);
@@ -184,14 +190,10 @@ DecoderErrorOr<CodedFrame> ADTSDemuxer::get_next_sample_for_track(Track const& t
VERIFY(track == m_track);
auto& status = track_status();
- auto frame = status.iterator.next();
- if (!frame.has_value()) {
- if (status.iterator.cursor().is_aborted())
- return DecoderError::with_description(DecoderErrorCategory::Aborted, "Read aborted"sv);
+ auto frame = TRY(status.iterator.read_next_frame());
+ if (!frame.has_value())
return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "End of stream"sv);
- }
- auto data = TRY(status.iterator.read_frame_data(*frame));
auto duration = AK::Duration::from_time_units(frame->header.sample_count, 1, frame->header.sample_rate);
auto timestamp = status.next_timestamp;
status.next_timestamp += duration;
@@ -203,7 +205,7 @@ DecoderErrorOr<CodedFrame> ADTSDemuxer::get_next_sample_for_track(Track const& t
}
// Every frame can begin decoding, so every frame is a keyframe to seek to.
- return CodedFrame(CodecID::AAC, timestamp, timestamp, duration, FrameFlags::Keyframe, move(data), move(codec_configuration));
+ return CodedFrame(CodecID::AAC, timestamp, timestamp, duration, FrameFlags::Keyframe, move(frame->data), move(codec_configuration));
}
AK::Duration ADTSDemuxer::select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode)
diff --git a/Libraries/LibMedia/Containers/ADTS/Reader.cpp b/Libraries/LibMedia/Containers/ADTS/Reader.cpp
index dabf3c8ad62..9af81105d14 100644
--- a/Libraries/LibMedia/Containers/ADTS/Reader.cpp
+++ b/Libraries/LibMedia/Containers/ADTS/Reader.cpp
@@ -15,45 +15,47 @@ static constexpr size_t FRAME_COUNT_RULING_OUT_A_FALSE_SYNC_CODE = 3;
static constexpr size_t BITRATE_ESTIMATION_SCAN_BYTE_COUNT = 32 * KiB;
-static size_t read_available(MediaStreamCursor& cursor, size_t position, Bytes buffer)
+static DecoderErrorOr<size_t> read_available(MediaStreamCursor& cursor, size_t position, Bytes buffer)
{
- if (cursor.seek_to_position(position).is_error())
+ auto result = [&]() -> DecoderErrorOr<size_t> {
+ TRY(cursor.seek_to_position(position));
+ return cursor.read_into(buffer);
+ }();
+ // Data that ends early reads short, but an aborted read has to reach the reader that will retry it.
+ if (result.is_error() && result.error().category() != DecoderErrorCategory::Aborted)
return 0;
- auto result = cursor.read_into(buffer);
- if (result.is_error())
- return 0;
- return result.value();
+ return result;
}
-static bool read_exact(MediaStreamCursor& cursor, size_t position, Bytes buffer)
+static DecoderErrorOr<bool> read_exact(MediaStreamCursor& cursor, size_t position, Bytes buffer)
{
- return read_available(cursor, position, buffer) == buffer.size();
+ return TRY(read_available(cursor, position, buffer)) == buffer.size();
}
-Optional<FrameIterator::Frame> FrameIterator::read_frame()
+DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::read_frame()
{
Array<u8, FrameHeader::SIZE> frame_header_data;
- if (!read_exact(*m_cursor, m_position, frame_header_data))
- return {};
+ if (!TRY(read_exact(*m_cursor, m_position, frame_header_data)))
+ return Optional<Frame> {};
auto header = FrameHeader::parse(frame_header_data);
if (!header.has_value())
- return {};
+ return Optional<Frame> {};
Frame frame { m_position, *header };
m_position += header->frame_byte_size;
return frame;
}
-Optional<FrameIterator::Frame> FrameIterator::next()
+DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::next()
{
- auto frame = read_frame();
+ auto frame = TRY(read_frame());
if (frame.has_value() || m_resynchronize == Resynchronize::No)
return frame;
- auto boundary = Reader::find_frame_boundary_at_or_after(m_cursor, m_position + 1, NumericLimits<size_t>::max());
+ auto boundary = TRY(Reader::find_frame_boundary_at_or_after(m_cursor, m_position + 1, NumericLimits<size_t>::max()));
if (!boundary.has_value())
- return {};
+ return Optional<Frame> {};
m_position = *boundary;
return read_frame();
@@ -68,12 +70,25 @@ DecoderErrorOr<FixedArray<u8>> FrameIterator::read_frame_data(Frame const& frame
return TRY(m_cursor->read_bytes(frame.header.frame_byte_size - payload_offset));
}
-static size_t skip_identification_tags(MediaStreamCursor& cursor)
+DecoderErrorOr<Optional<FrameIterator::FrameWithData>> FrameIterator::read_next_frame()
+{
+ auto frame = TRY(next());
+ if (!frame.has_value())
+ return Optional<FrameWithData> {};
+ auto data = read_frame_data(*frame);
+ if (data.is_error()) {
+ m_position = frame->position;
+ return data.release_error();
+ }
+ return FrameWithData { frame->header, data.release_value() };
+}
+
+static DecoderErrorOr<size_t> skip_identification_tags(MediaStreamCursor& cursor)
{
size_t position = 0;
while (true) {
Array<u8, ID3::VERSION_2_HEADER_SIZE> tag_header;
- if (!read_exact(cursor, position, tag_header))
+ if (!TRY(read_exact(cursor, position, tag_header)))
break;
auto tag_size = ID3::version_2_tag_size(tag_header);
if (!tag_size.has_value())
@@ -91,13 +106,13 @@ struct FrameScan {
size_t byte_count { 0 };
};
-static Optional<FrameScan> scan_frames_at(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
+static DecoderErrorOr<Optional<FrameScan>> scan_frames_at(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
FrameIterator iterator { cursor, position, FrameIterator::Resynchronize::No };
FrameScan scan;
while (scan.frame_count < FRAME_COUNT_RULING_OUT_A_FALSE_SYNC_CODE || scan.byte_count < BITRATE_ESTIMATION_SCAN_BYTE_COUNT) {
- auto frame = iterator.next();
+ auto frame = TRY(iterator.next());
if (!frame.has_value())
break;
if (scan.frame_count == 0) {
@@ -110,7 +125,7 @@ static Optional<FrameScan> scan_frames_at(NonnullRefPtr<MediaStreamCursor> const
}
if (scan.frame_count == 0)
- return {};
+ return Optional<FrameScan> {};
return scan;
}
@@ -124,18 +139,18 @@ static bool headers_describe_the_same_stream(FrameHeader const& first, FrameHead
&& first.channel_count == second.channel_count;
}
-static bool begins_a_frame(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
+static DecoderErrorOr<bool> begins_a_frame(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
- return FrameIterator { cursor, position, FrameIterator::Resynchronize::No }.next().has_value();
+ return TRY(FrameIterator(cursor, position, FrameIterator::Resynchronize::No).next()).has_value();
}
-static bool begins_a_frame_sequence(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
+static DecoderErrorOr<bool> begins_a_frame_sequence(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
FrameIterator iterator { cursor, position, FrameIterator::Resynchronize::No };
Optional<FrameHeader> previous_header;
for (size_t frame_count = 0; frame_count < FRAME_COUNT_RULING_OUT_A_FALSE_SYNC_CODE; frame_count++) {
- auto frame = iterator.next();
+ auto frame = TRY(iterator.next());
if (!frame.has_value())
return false;
if (previous_header.has_value() && !headers_describe_the_same_stream(*previous_header, frame->header))
@@ -152,22 +167,22 @@ static bool has_sync_code_at(ReadonlyBytes bytes, size_t index)
return FrameHeader::has_sync_code(static_cast<u16>((bytes[index] << 8) | bytes[index + 1]));
}
-Optional<size_t> Reader::find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t start_byte, size_t upper_bound)
+DecoderErrorOr<Optional<size_t>> Reader::find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t start_byte, size_t upper_bound)
{
auto scan_position = start_byte;
Array<u8, SYNC_SCAN_CHUNK_SIZE> buffer;
while (scan_position + FrameHeader::SIZE <= upper_bound) {
auto chunk = buffer.span().trim(min(SYNC_SCAN_CHUNK_SIZE, upper_bound - scan_position));
- chunk = chunk.trim(read_available(*cursor, scan_position, chunk));
+ chunk = chunk.trim(TRY(read_available(*cursor, scan_position, chunk)));
if (chunk.size() < 2)
break;
for (size_t index = 0; index + 1 < chunk.size(); index++) {
if (!has_sync_code_at(chunk, index))
continue;
- if (begins_a_frame_sequence(cursor, scan_position + index))
- return scan_position + index;
+ if (TRY(begins_a_frame_sequence(cursor, scan_position + index)))
+ return Optional<size_t> { scan_position + index };
}
if (chunk.size() < SYNC_SCAN_CHUNK_SIZE)
@@ -175,10 +190,10 @@ Optional<size_t> Reader::find_frame_boundary_at_or_after(NonnullRefPtr<MediaStre
scan_position += chunk.size() - 1;
}
- return {};
+ return Optional<size_t> {};
}
-Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t target_byte, size_t lower_bound, size_t upper_bound)
+DecoderErrorOr<Optional<size_t>> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t target_byte, size_t lower_bound, size_t upper_bound)
{
VERIFY(target_byte <= upper_bound);
@@ -190,8 +205,8 @@ Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStr
chunk_start = max(chunk_start, lower_bound);
auto chunk = buffer.span().trim(chunk_end - chunk_start);
- if (!read_exact(*cursor, chunk_start, chunk))
- return {};
+ if (!TRY(read_exact(*cursor, chunk_start, chunk)))
+ return Optional<size_t> {};
for (size_t index = chunk.size(); index-- > 0;) {
if (!has_sync_code_at(chunk, index))
@@ -199,8 +214,8 @@ Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStr
auto candidate = chunk_start + index;
if (candidate > target_byte)
continue;
- if (begins_a_frame_sequence(cursor, candidate))
- return candidate;
+ if (TRY(begins_a_frame_sequence(cursor, candidate)))
+ return Optional<size_t> { candidate };
}
if (chunk_start == lower_bound)
@@ -208,26 +223,26 @@ Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStr
chunk_end = chunk_start + 1;
}
- return {};
+ return Optional<size_t> {};
}
-static Optional<size_t> find_first_frame_position(NonnullRefPtr<MediaStreamCursor> const& cursor)
+static DecoderErrorOr<Optional<size_t>> find_first_frame_position(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
- auto position = skip_identification_tags(*cursor);
- if (begins_a_frame(cursor, position))
- return position;
+ auto position = TRY(skip_identification_tags(*cursor));
+ if (TRY(begins_a_frame(cursor, position)))
+ return Optional<size_t> { position };
return Reader::find_frame_boundary_at_or_after(cursor, position, position + Reader::MAXIMUM_SYNC_SEARCH_BYTE_COUNT);
}
-Optional<Reader> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
+DecoderErrorOr<Optional<Reader>> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
- auto position = find_first_frame_position(cursor);
+ auto position = TRY(find_first_frame_position(cursor));
if (!position.has_value())
- return {};
+ return Optional<Reader> {};
- auto scan = scan_frames_at(cursor, *position);
+ auto scan = TRY(scan_frames_at(cursor, *position));
if (!scan.has_value())
- return {};
+ return Optional<Reader> {};
Reader reader;
reader.m_frame_header = scan->header;
diff --git a/Libraries/LibMedia/Containers/ADTS/Reader.h b/Libraries/LibMedia/Containers/ADTS/Reader.h
index 20e73ced07d..df46f76f058 100644
--- a/Libraries/LibMedia/Containers/ADTS/Reader.h
+++ b/Libraries/LibMedia/Containers/ADTS/Reader.h
@@ -24,6 +24,14 @@ public:
FrameHeader header;
};
+ struct FrameWithData {
+ FrameHeader header;
+ // The audio of the frame, without the framing that ADTS wraps it in. A decoder is configured
+ // from the configuration record the header implies, so it is handed the same access units that
+ // a stream carrying that record in its container would hand it.
+ FixedArray<u8> data;
+ };
+
// Whether to scan forward for a sync code upon finding an invalid frame.
enum class Resynchronize : bool {
No,
@@ -37,18 +45,16 @@ public:
{
}
- Optional<Frame> next();
-
- // The audio of the frame, without the framing that ADTS wraps it in. A decoder is configured
- // from the configuration record the header implies, so it is handed the same access units that
- // a stream carrying that record in its container would hand it.
- DecoderErrorOr<FixedArray<u8>> read_frame_data(Frame const&);
+ DecoderErrorOr<Optional<Frame>> next();
+ // Moves past the frame only once its data has been read, so an interrupted read can be retried.
+ DecoderErrorOr<Optional<FrameWithData>> read_next_frame();
size_t position() const { return m_position; }
MediaStreamCursor& cursor() { return *m_cursor; }
private:
- Optional<Frame> read_frame();
+ DecoderErrorOr<Optional<Frame>> read_frame();
+ DecoderErrorOr<FixedArray<u8>> read_frame_data(Frame const&);
NonnullRefPtr<MediaStreamCursor> m_cursor;
size_t m_position { 0 };
@@ -64,11 +70,11 @@ public:
// Finds the position of a frame that begins a run of valid frames, so that a false sync code in
// the middle of a stream is not mistaken for a frame boundary.
- static Optional<size_t> find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const&, size_t start_byte, size_t upper_bound);
- static Optional<size_t> find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const&, size_t target_byte, size_t lower_bound, size_t upper_bound);
+ static DecoderErrorOr<Optional<size_t>> find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const&, size_t start_byte, size_t upper_bound);
+ static DecoderErrorOr<Optional<size_t>> find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const&, size_t target_byte, size_t lower_bound, size_t upper_bound);
// Returns nothing until enough frames are available to tell audio apart from a false sync code.
- static Optional<Reader> from_stream(NonnullRefPtr<MediaStreamCursor> const&);
+ static DecoderErrorOr<Optional<Reader>> from_stream(NonnullRefPtr<MediaStreamCursor> const&);
size_t first_frame_position() const { return m_first_frame_position; }
FrameHeader const& frame_header() const { return m_frame_header; }
diff --git a/Libraries/LibMedia/Containers/MP3/MP3Demuxer.cpp b/Libraries/LibMedia/Containers/MP3/MP3Demuxer.cpp
index 566fba98e9a..c9d649c328c 100644
--- a/Libraries/LibMedia/Containers/MP3/MP3Demuxer.cpp
+++ b/Libraries/LibMedia/Containers/MP3/MP3Demuxer.cpp
@@ -19,24 +19,30 @@ public:
{
FrameIterator iterator { NonnullRefPtr { cursor }, position, FrameIterator::Resynchronize::Yes };
auto frame = iterator.next();
- if (!frame.has_value())
+ if (frame.is_error() || !frame.value().has_value())
return {};
return Frame {
- .position = frame->position,
- .byte_size = frame->header.frame_byte_size,
- .duration = { frame->header.sample_count, frame->header.sample_rate },
+ .position = frame.value()->position,
+ .byte_size = frame.value()->header.frame_byte_size,
+ .duration = { frame.value()->header.sample_count, frame.value()->header.sample_rate },
};
}
virtual Optional<size_t> find_boundary_at_or_after(MediaStreamCursor& cursor, size_t start_byte, size_t upper_bound) const override
{
- return Reader::find_frame_boundary_at_or_after(NonnullRefPtr { cursor }, start_byte, upper_bound);
+ auto boundary = Reader::find_frame_boundary_at_or_after(NonnullRefPtr { cursor }, start_byte, upper_bound);
+ if (boundary.is_error())
+ return {};
+ return boundary.release_value();
}
virtual Optional<size_t> find_boundary_at_or_before(MediaStreamCursor& cursor, size_t target_byte, size_t lower_bound, size_t upper_bound) const override
{
- return Reader::find_frame_boundary_at_or_before(NonnullRefPtr { cursor }, target_byte, lower_bound, upper_bound);
+ auto boundary = Reader::find_frame_boundary_at_or_before(NonnullRefPtr { cursor }, target_byte, lower_bound, upper_bound);
+ if (boundary.is_error())
+ return {};
+ return boundary.release_value();
}
};
@@ -63,7 +69,7 @@ static Track create_track(Reader const& reader)
DecoderErrorOr<NonnullRefPtr<Demuxer>> MP3Demuxer::from_stream(NonnullRefPtr<MediaStream> const& stream)
{
- auto reader = Reader::from_stream(stream->create_cursor());
+ auto reader = TRY(Reader::from_stream(stream->create_cursor()));
if (!reader.has_value())
return DecoderError::with_description(DecoderErrorCategory::UnrecognizedFormat, "Found no MPEG audio frames in the stream"sv);
@@ -152,14 +158,10 @@ DecoderErrorOr<CodedFrame> MP3Demuxer::get_next_sample_for_track(Track const& tr
VERIFY(track == m_track);
auto& status = track_status();
- auto frame = status.iterator.next();
- if (!frame.has_value()) {
- if (status.iterator.cursor().is_aborted())
- return DecoderError::with_description(DecoderErrorCategory::Aborted, "Read aborted"sv);
+ auto frame = TRY(status.iterator.read_next_frame());
+ if (!frame.has_value())
return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "End of stream"sv);
- }
- auto data = TRY(status.iterator.read_frame_data(*frame));
auto duration = AK::Duration::from_time_units(frame->header.sample_count, 1, frame->header.sample_rate);
auto timestamp = status.next_timestamp;
status.next_timestamp += duration;
@@ -173,7 +175,7 @@ DecoderErrorOr<CodedFrame> MP3Demuxer::get_next_sample_for_track(Track const& tr
}
// Every frame can begin decoding, so every frame is a keyframe to seek to.
- return CodedFrame(CodecID::MP3, timestamp, timestamp, duration, FrameFlags::Keyframe, move(data), move(codec_configuration));
+ return CodedFrame(CodecID::MP3, timestamp, timestamp, duration, FrameFlags::Keyframe, move(frame->data), move(codec_configuration));
}
AK::Duration MP3Demuxer::select_fast_seek_target_for_track(Track const&, AK::Duration target, SeekMode)
diff --git a/Libraries/LibMedia/Containers/MP3/Reader.cpp b/Libraries/LibMedia/Containers/MP3/Reader.cpp
index ca20b916d3f..1105aa04da1 100644
--- a/Libraries/LibMedia/Containers/MP3/Reader.cpp
+++ b/Libraries/LibMedia/Containers/MP3/Reader.cpp
@@ -14,45 +14,47 @@ static constexpr size_t SYNC_SCAN_CHUNK_SIZE = 4096;
static constexpr size_t BITRATE_SCAN_BYTE_COUNT = 4096;
static constexpr size_t FRAME_COUNT_RULING_OUT_A_FALSE_SYNC_CODE = 3;
-static size_t read_available(MediaStreamCursor& cursor, size_t position, Bytes buffer)
+static DecoderErrorOr<size_t> read_available(MediaStreamCursor& cursor, size_t position, Bytes buffer)
{
- if (cursor.seek_to_position(position).is_error())
+ auto result = [&]() -> DecoderErrorOr<size_t> {
+ TRY(cursor.seek_to_position(position));
+ return cursor.read_into(buffer);
+ }();
+ // Data that ends early reads short, but an aborted read has to reach the reader that will retry it.
+ if (result.is_error() && result.error().category() != DecoderErrorCategory::Aborted)
return 0;
- auto result = cursor.read_into(buffer);
- if (result.is_error())
- return 0;
- return result.value();
+ return result;
}
-static bool read_exact(MediaStreamCursor& cursor, size_t position, Bytes buffer)
+static DecoderErrorOr<bool> read_exact(MediaStreamCursor& cursor, size_t position, Bytes buffer)
{
- return read_available(cursor, position, buffer) == buffer.size();
+ return TRY(read_available(cursor, position, buffer)) == buffer.size();
}
-Optional<FrameIterator::Frame> FrameIterator::read_frame()
+DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::read_frame()
{
Array<u8, FrameHeader::SIZE> frame_header_data;
- if (!read_exact(*m_cursor, m_position, frame_header_data))
- return {};
+ if (!TRY(read_exact(*m_cursor, m_position, frame_header_data)))
+ return Optional<Frame> {};
auto header = FrameHeader::parse(frame_header_data);
if (!header.has_value())
- return {};
+ return Optional<Frame> {};
Frame frame { m_position, *header };
m_position += header->frame_byte_size;
return frame;
}
-Optional<FrameIterator::Frame> FrameIterator::next()
+DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::next()
{
- auto frame = read_frame();
+ auto frame = TRY(read_frame());
if (frame.has_value() || m_resynchronize == Resynchronize::No)
return frame;
- auto boundary = Reader::find_frame_boundary_at_or_after(m_cursor, m_position + 1, NumericLimits<size_t>::max());
+ auto boundary = TRY(Reader::find_frame_boundary_at_or_after(m_cursor, m_position + 1, NumericLimits<size_t>::max()));
if (!boundary.has_value())
- return {};
+ return Optional<Frame> {};
m_position = *boundary;
return read_frame();
@@ -64,12 +66,25 @@ DecoderErrorOr<FixedArray<u8>> FrameIterator::read_frame_data(Frame const& frame
return TRY(m_cursor->read_bytes(frame.header.frame_byte_size));
}
-static size_t skip_identification_tags(MediaStreamCursor& cursor)
+DecoderErrorOr<Optional<FrameIterator::FrameWithData>> FrameIterator::read_next_frame()
+{
+ auto frame = TRY(next());
+ if (!frame.has_value())
+ return Optional<FrameWithData> {};
+ auto data = read_frame_data(*frame);
+ if (data.is_error()) {
+ m_position = frame->position;
+ return data.release_error();
+ }
+ return FrameWithData { frame->header, data.release_value() };
+}
+
+static DecoderErrorOr<size_t> skip_identification_tags(MediaStreamCursor& cursor)
{
size_t position = 0;
while (true) {
Array<u8, ID3::VERSION_2_HEADER_SIZE> tag_header;
- if (!read_exact(cursor, position, tag_header))
+ if (!TRY(read_exact(cursor, position, tag_header)))
break;
auto tag_size = ID3::version_2_tag_size(tag_header);
if (!tag_size.has_value())
@@ -87,13 +102,13 @@ struct FrameScan {
size_t byte_count { 0 };
};
-static Optional<FrameScan> scan_frames_at(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
+static DecoderErrorOr<Optional<FrameScan>> scan_frames_at(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
FrameIterator iterator { cursor, position, FrameIterator::Resynchronize::No };
FrameScan scan;
while (scan.frame_count < FRAME_COUNT_RULING_OUT_A_FALSE_SYNC_CODE || scan.byte_count < BITRATE_SCAN_BYTE_COUNT) {
- auto frame = iterator.next();
+ auto frame = TRY(iterator.next());
if (!frame.has_value())
break;
if (scan.frame_count == 0) {
@@ -106,7 +121,7 @@ static Optional<FrameScan> scan_frames_at(NonnullRefPtr<MediaStreamCursor> const
}
if (scan.frame_count == 0)
- return {};
+ return Optional<FrameScan> {};
return scan;
}
@@ -120,18 +135,18 @@ static bool headers_describe_the_same_stream(FrameHeader const& first, FrameHead
&& first.channel_count == second.channel_count;
}
-static bool begins_a_frame(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
+static DecoderErrorOr<bool> begins_a_frame(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
- return FrameIterator { cursor, position, FrameIterator::Resynchronize::No }.next().has_value();
+ return TRY(FrameIterator(cursor, position, FrameIterator::Resynchronize::No).next()).has_value();
}
-static bool begins_a_frame_sequence(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
+static DecoderErrorOr<bool> begins_a_frame_sequence(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
FrameIterator iterator { cursor, position, FrameIterator::Resynchronize::No };
Optional<FrameHeader> previous_header;
for (size_t frame_count = 0; frame_count < FRAME_COUNT_RULING_OUT_A_FALSE_SYNC_CODE; frame_count++) {
- auto frame = iterator.next();
+ auto frame = TRY(iterator.next());
if (!frame.has_value())
return false;
if (previous_header.has_value() && !headers_describe_the_same_stream(*previous_header, frame->header))
@@ -148,22 +163,22 @@ static bool has_sync_code_at(ReadonlyBytes bytes, size_t index)
return FrameHeader::has_sync_code(static_cast<u16>((bytes[index] << 8) | bytes[index + 1]));
}
-Optional<size_t> Reader::find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t start_byte, size_t upper_bound)
+DecoderErrorOr<Optional<size_t>> Reader::find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t start_byte, size_t upper_bound)
{
auto scan_position = start_byte;
Array<u8, SYNC_SCAN_CHUNK_SIZE> buffer;
while (scan_position + FrameHeader::SIZE <= upper_bound) {
auto chunk = buffer.span().trim(min(SYNC_SCAN_CHUNK_SIZE, upper_bound - scan_position));
- chunk = chunk.trim(read_available(*cursor, scan_position, chunk));
+ chunk = chunk.trim(TRY(read_available(*cursor, scan_position, chunk)));
if (chunk.size() < 2)
break;
for (size_t index = 0; index + 1 < chunk.size(); index++) {
if (!has_sync_code_at(chunk, index))
continue;
- if (begins_a_frame_sequence(cursor, scan_position + index))
- return scan_position + index;
+ if (TRY(begins_a_frame_sequence(cursor, scan_position + index)))
+ return Optional<size_t> { scan_position + index };
}
if (chunk.size() < SYNC_SCAN_CHUNK_SIZE)
@@ -171,10 +186,10 @@ Optional<size_t> Reader::find_frame_boundary_at_or_after(NonnullRefPtr<MediaStre
scan_position += chunk.size() - 1;
}
- return {};
+ return Optional<size_t> {};
}
-Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t target_byte, size_t lower_bound, size_t upper_bound)
+DecoderErrorOr<Optional<size_t>> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t target_byte, size_t lower_bound, size_t upper_bound)
{
VERIFY(target_byte <= upper_bound);
@@ -186,8 +201,8 @@ Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStr
chunk_start = max(chunk_start, lower_bound);
auto chunk = buffer.span().trim(chunk_end - chunk_start);
- if (!read_exact(*cursor, chunk_start, chunk))
- return {};
+ if (!TRY(read_exact(*cursor, chunk_start, chunk)))
+ return Optional<size_t> {};
for (size_t index = chunk.size(); index-- > 0;) {
if (!has_sync_code_at(chunk, index))
@@ -195,8 +210,8 @@ Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStr
auto candidate = chunk_start + index;
if (candidate > target_byte)
continue;
- if (begins_a_frame_sequence(cursor, candidate))
- return candidate;
+ if (TRY(begins_a_frame_sequence(cursor, candidate)))
+ return Optional<size_t> { candidate };
}
if (chunk_start == lower_bound)
@@ -204,46 +219,46 @@ Optional<size_t> Reader::find_frame_boundary_at_or_before(NonnullRefPtr<MediaStr
chunk_end = chunk_start + 1;
}
- return {};
+ return Optional<size_t> {};
}
// A stream carries its frames from where its identification tags end, but one that was cut can have
// junk in between, so the frames are searched for when they do not begin there.
-static Optional<size_t> find_first_frame_position(NonnullRefPtr<MediaStreamCursor> const& cursor)
+static DecoderErrorOr<Optional<size_t>> find_first_frame_position(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
- auto position = skip_identification_tags(*cursor);
- if (begins_a_frame(cursor, position))
- return position;
+ auto position = TRY(skip_identification_tags(*cursor));
+ if (TRY(begins_a_frame(cursor, position)))
+ return Optional<size_t> { position };
return Reader::find_frame_boundary_at_or_after(cursor, position, position + Reader::MAXIMUM_SYNC_SEARCH_BYTE_COUNT);
}
-static Optional<FrameScan> scan_first_frames(NonnullRefPtr<MediaStreamCursor> const& cursor)
+static DecoderErrorOr<Optional<FrameScan>> scan_first_frames(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
- auto position = find_first_frame_position(cursor);
+ auto position = TRY(find_first_frame_position(cursor));
if (!position.has_value())
- return {};
+ return Optional<FrameScan> {};
return scan_frames_at(cursor, *position);
}
-static Optional<StreamInfo> read_stream_info(MediaStreamCursor& cursor, FrameScan const& scan)
+static DecoderErrorOr<Optional<StreamInfo>> read_stream_info(MediaStreamCursor& cursor, FrameScan const& scan)
{
Vector<u8> frame;
frame.resize(scan.header.frame_byte_size);
- if (!read_exact(cursor, scan.position, frame))
- return {};
+ if (!TRY(read_exact(cursor, scan.position, frame)))
+ return Optional<StreamInfo> {};
return StreamInfo::parse(frame, scan.header);
}
-Optional<Reader> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
+DecoderErrorOr<Optional<Reader>> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
- auto scan = scan_first_frames(cursor);
+ auto scan = TRY(scan_first_frames(cursor));
if (!scan.has_value())
- return {};
+ return Optional<Reader> {};
Reader reader;
reader.m_frame_header = scan->header;
reader.m_first_audio_frame_position = scan->position;
- reader.m_stream_info = read_stream_info(*cursor, scan.value());
+ reader.m_stream_info = TRY(read_stream_info(*cursor, scan.value()));
// A frame describing the stream carries no audio, so it counts towards neither the timeline nor
// the bitrate the remaining frames establish.
diff --git a/Libraries/LibMedia/Containers/MP3/Reader.h b/Libraries/LibMedia/Containers/MP3/Reader.h
index 59005971fc3..7fe7c2b4758 100644
--- a/Libraries/LibMedia/Containers/MP3/Reader.h
+++ b/Libraries/LibMedia/Containers/MP3/Reader.h
@@ -25,6 +25,11 @@ public:
FrameHeader header;
};
+ struct FrameWithData {
+ FrameHeader header;
+ FixedArray<u8> data;
+ };
+
// Whether to scan forward for a sync code upon finding an invalid frame.
enum class Resynchronize : bool {
No,
@@ -38,14 +43,16 @@ public:
{
}
- Optional<Frame> next();
- DecoderErrorOr<FixedArray<u8>> read_frame_data(Frame const&);
+ DecoderErrorOr<Optional<Frame>> next();
+ // Moves past the frame only once its data has been read, so an interrupted read can be retried.
+ DecoderErrorOr<Optional<FrameWithData>> read_next_frame();
size_t position() const { return m_position; }
MediaStreamCursor& cursor() { return *m_cursor; }
private:
- Optional<Frame> read_frame();
+ DecoderErrorOr<Optional<Frame>> read_frame();
+ DecoderErrorOr<FixedArray<u8>> read_frame_data(Frame const&);
NonnullRefPtr<MediaStreamCursor> m_cursor;
size_t m_position { 0 };
@@ -61,11 +68,11 @@ public:
// Finds the position of a frame that begins a run of valid frames, so that a false sync code in
// the middle of a stream is not mistaken for a frame boundary.
- static Optional<size_t> find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const&, size_t start_byte, size_t upper_bound);
- static Optional<size_t> find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const&, size_t target_byte, size_t lower_bound, size_t upper_bound);
+ static DecoderErrorOr<Optional<size_t>> find_frame_boundary_at_or_after(NonnullRefPtr<MediaStreamCursor> const&, size_t start_byte, size_t upper_bound);
+ static DecoderErrorOr<Optional<size_t>> find_frame_boundary_at_or_before(NonnullRefPtr<MediaStreamCursor> const&, size_t target_byte, size_t lower_bound, size_t upper_bound);
// Returns nothing until enough frames are available to tell audio apart from a false sync code.
- static Optional<Reader> from_stream(NonnullRefPtr<MediaStreamCursor> const&);
+ static DecoderErrorOr<Optional<Reader>> from_stream(NonnullRefPtr<MediaStreamCursor> const&);
size_t first_audio_frame_position() const { return m_first_audio_frame_position; }
FrameHeader const& frame_header() const { return m_frame_header; }
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index 1d9c8b68a13..9aa57250a41 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -63,7 +63,9 @@ target_link_libraries(TestAudioBlockTimingRing PRIVATE LibThreading)
target_link_libraries(TestDecodedAudioProducer PRIVATE LibGfx)
target_link_libraries(TestDisplayingVideoSink PRIVATE LibGfx)
target_link_libraries(TestVP9Decode PRIVATE LibGfx)
+target_link_libraries(TestADTSDemuxer PRIVATE LibThreading)
target_link_libraries(TestFFmpegDemuxer PRIVATE LibThreading)
+target_link_libraries(TestMP3Demuxer PRIVATE LibThreading)
target_link_libraries(TestWAVDemuxer PRIVATE LibThreading)
target_link_libraries(TestISOBMFF PRIVATE LibThreading)
target_link_libraries(TestMediaTime PRIVATE LibThreading)
diff --git a/Tests/LibMedia/TestADTSDemuxer.cpp b/Tests/LibMedia/TestADTSDemuxer.cpp
index a634c51d785..abc589ef4fb 100644
--- a/Tests/LibMedia/TestADTSDemuxer.cpp
+++ b/Tests/LibMedia/TestADTSDemuxer.cpp
@@ -12,6 +12,9 @@
#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMediaCodecs/CodedFrame.h>
#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+
+#include "TransientlyAbortingStream.h"
static constexpr size_t FRAME_BYTE_SIZE = 256;
@@ -52,6 +55,108 @@ static Media::Track audio_track(Media::Demuxer& demuxer)
return *track;
}
+static NonnullRefPtr<Media::Demuxer> create_demuxer_for(ReadonlyBytes bytes)
+{
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(ByteBuffer::copy(bytes)));
+ return MUST(Media::ADTS::ADTSDemuxer::from_stream(stream));
+}
+
+static Vector<AK::Duration> timestamps_of_every_frame(Media::Demuxer& demuxer, Media::Track const& track)
+{
+ Vector<AK::Duration> timestamps;
+ while (true) {
+ auto frame = demuxer.get_next_sample_for_track(track);
+ if (frame.is_error()) {
+ EXPECT_EQ(frame.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ timestamps.append(frame.value().presentation_timestamp());
+ }
+ return timestamps;
+}
+
+static void expect_a_transient_abort_to_resume_with_its_frame(ReadonlyBytes bytes, size_t aborted_read_position)
+{
+ Vector<AK::Duration> expected_timestamps;
+ {
+ auto demuxer = create_demuxer_for(bytes);
+ auto track = audio_track(*demuxer);
+ expected_timestamps = timestamps_of_every_frame(*demuxer, track);
+ }
+
+ auto stream = TransientlyAbortingStream::create(MUST(ByteBuffer::copy(bytes)), aborted_read_position);
+ auto demuxer = MUST(Media::ADTS::ADTSDemuxer::from_stream(stream));
+ auto track = audio_track(*demuxer);
+
+ Vector<AK::Duration> actual_timestamps;
+ 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_timestamps.append(frame.value().presentation_timestamp());
+ }
+ EXPECT(stream->has_aborted_a_read());
+ EXPECT_EQ(aborted_read_count, 1u);
+ EXPECT_EQ(actual_timestamps, expected_timestamps);
+}
+
+static void expect_an_aborted_read_to_resume_with_its_frame(ReadonlyBytes bytes, size_t initial_byte_count)
+{
+ Vector<AK::Duration> expected_timestamps;
+ {
+ auto demuxer = create_demuxer_for(bytes);
+ auto track = audio_track(*demuxer);
+ expected_timestamps = timestamps_of_every_frame(*demuxer, track);
+ }
+
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->set_expected_size(bytes.size());
+ stream->add_chunk_at(0, bytes.trim(initial_byte_count));
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::ADTS::ADTSDemuxer::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<AK::Duration> actual_timestamps;
+ 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_timestamps.append(frame.value().presentation_timestamp());
+ }
+ demuxer->reset_blocking_reads_aborted_for_track(track);
+ read_was_aborted = true;
+ actual_timestamps.extend(timestamps_of_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_byte_count, bytes.slice(initial_byte_count));
+ stream->close();
+ MUST(reader_thread->join());
+
+ EXPECT_EQ(actual_timestamps, expected_timestamps);
+}
+
TEST_CASE(demuxer_reads_a_stream_of_nothing_but_frames)
{
// Nine ADTS AAC-LC frames containing 48 kHz stereo silence, as an encoder wrote them. The first
@@ -237,3 +342,24 @@ TEST_CASE(the_registry_hands_a_stream_of_adts_frames_to_this_demuxer)
EXPECT_EQ(tracks[0].parsed_codec().codec_id(), Media::CodecID::AAC);
EXPECT_EQ(tracks[0].audio_data().sample_specification.sample_rate(), 44100u);
}
+
+TEST_CASE(demuxer_resumes_a_read_aborted_inside_a_frame_with_that_frame)
+{
+ Vector<u8> bytes;
+ append_frames(bytes, 400);
+ expect_an_aborted_read_to_resume_with_its_frame(bytes, (200 * FRAME_BYTE_SIZE) + 100);
+}
+
+TEST_CASE(demuxer_resumes_a_read_aborted_inside_a_frame_header_with_that_frame)
+{
+ Vector<u8> bytes;
+ append_frames(bytes, 400);
+ expect_an_aborted_read_to_resume_with_its_frame(bytes, (200 * FRAME_BYTE_SIZE) + 3);
+}
+
+TEST_CASE(demuxer_resumes_after_a_transient_abort)
+{
+ Vector<u8> bytes;
+ append_frames(bytes, 400);
+ expect_a_transient_abort_to_resume_with_its_frame(bytes, 200 * FRAME_BYTE_SIZE);
+}
diff --git a/Tests/LibMedia/TestADTSReader.cpp b/Tests/LibMedia/TestADTSReader.cpp
index e1722e1d853..99a9f474f46 100644
--- a/Tests/LibMedia/TestADTSReader.cpp
+++ b/Tests/LibMedia/TestADTSReader.cpp
@@ -36,7 +36,7 @@ static NonnullRefPtr<Media::ReadonlyBytesCursor> create_cursor(ReadonlyBytes byt
static Optional<Media::ADTS::Reader> read(Vector<u8> const& bytes)
{
- return Media::ADTS::Reader::from_stream(create_cursor(bytes));
+ return MUST(Media::ADTS::Reader::from_stream(create_cursor(bytes)));
}
static ByteBuffer read_fixture(StringView path)
@@ -80,7 +80,7 @@ TEST_CASE(frame_iterator_walks_every_frame_of_a_stream)
size_t frame_count = 0;
size_t expected_position = 0;
while (true) {
- auto frame = iterator.next();
+ auto frame = MUST(iterator.next());
if (!frame.has_value())
break;
EXPECT_EQ(frame->position, expected_position);
@@ -96,13 +96,12 @@ TEST_CASE(frame_iterator_reads_the_audio_without_the_framing_around_it)
append_frames(bytes, 2);
Media::ADTS::FrameIterator iterator { create_cursor(bytes), 0, Media::ADTS::FrameIterator::Resynchronize::No };
- auto frame = iterator.next();
+ auto frame = MUST(iterator.read_next_frame());
EXPECT(frame.has_value());
// The header frames the audio rather than describing it, and a decoder configured from the
// record the header implies expects the access unit alone.
- auto data = MUST(iterator.read_frame_data(*frame));
- EXPECT_EQ(data.size(), FRAME_BYTE_SIZE - Media::ADTS::FrameHeader::SIZE);
+ EXPECT_EQ(frame->data.size(), FRAME_BYTE_SIZE - Media::ADTS::FrameHeader::SIZE);
}
TEST_CASE(frame_iterator_resumes_at_the_frames_that_follow_damage)
@@ -115,7 +114,7 @@ TEST_CASE(frame_iterator_resumes_at_the_frames_that_follow_damage)
Media::ADTS::FrameIterator iterator { create_cursor(bytes), 0, Media::ADTS::FrameIterator::Resynchronize::Yes };
size_t frame_count = 0;
- while (iterator.next().has_value())
+ while (MUST(iterator.next()).has_value())
frame_count++;
EXPECT_EQ(frame_count, 5u);
}
@@ -129,7 +128,7 @@ TEST_CASE(frame_iterator_stops_where_a_frame_header_can_no_longer_be_read)
Media::ADTS::FrameIterator iterator { create_cursor(bytes), 0, Media::ADTS::FrameIterator::Resynchronize::No };
size_t frame_count = 0;
- while (iterator.next().has_value())
+ while (MUST(iterator.next()).has_value())
frame_count++;
EXPECT_EQ(frame_count, 2u);
}
@@ -143,12 +142,17 @@ TEST_CASE(frame_iterator_reports_a_frame_whose_audio_has_not_all_arrived)
bytes.resize(bytes.size() - 4);
Media::ADTS::FrameIterator iterator { create_cursor(bytes), 0, Media::ADTS::FrameIterator::Resynchronize::No };
- EXPECT(iterator.next().has_value());
+ EXPECT(MUST(iterator.next()).has_value());
- auto truncated = iterator.next();
+ auto truncated_frame_position = iterator.position();
+ auto truncated = MUST(iterator.next());
EXPECT(truncated.has_value());
EXPECT_EQ(truncated->header.frame_byte_size, FRAME_BYTE_SIZE);
- EXPECT(iterator.read_frame_data(*truncated).is_error());
+
+ // Its data cannot be read in full, so reading it leaves the iterator at the frame.
+ Media::ADTS::FrameIterator data_iterator { create_cursor(bytes), truncated_frame_position, Media::ADTS::FrameIterator::Resynchronize::No };
+ EXPECT(data_iterator.read_next_frame().is_error());
+ EXPECT_EQ(data_iterator.position(), truncated_frame_position);
}
TEST_CASE(reader_searches_past_bytes_that_precede_the_audio)
@@ -210,7 +214,7 @@ TEST_CASE(backward_search_reads_back_through_bytes_holding_no_frames)
bytes.resize(bytes.size() + 2000);
auto cursor = create_cursor(bytes);
- auto boundary = Media::ADTS::Reader::find_frame_boundary_at_or_before(cursor, bytes.size() - 1, 0, bytes.size());
+ auto boundary = MUST(Media::ADTS::Reader::find_frame_boundary_at_or_before(cursor, bytes.size() - 1, 0, bytes.size()));
EXPECT(boundary.has_value());
// The last frame that a run of frames reaches, not the bytes trailing them.
@@ -220,7 +224,7 @@ TEST_CASE(backward_search_reads_back_through_bytes_holding_no_frames)
TEST_CASE(reader_reads_a_stream_that_an_encoder_produced)
{
auto data = read_fixture("bbb.adts"sv);
- auto reader = Media::ADTS::Reader::from_stream(create_cursor(data));
+ auto reader = MUST(Media::ADTS::Reader::from_stream(create_cursor(data)));
EXPECT(reader.has_value());
EXPECT_EQ(reader->first_frame_position(), 0u);
EXPECT_EQ(reader->frame_header().sample_rate, 44100u);
@@ -231,7 +235,7 @@ TEST_CASE(reader_reads_a_stream_that_an_encoder_produced)
u64 sample_count = 0;
size_t byte_count = 0;
while (true) {
- auto frame = iterator.next();
+ auto frame = MUST(iterator.next());
if (!frame.has_value())
break;
frame_count++;
diff --git a/Tests/LibMedia/TestMP3Demuxer.cpp b/Tests/LibMedia/TestMP3Demuxer.cpp
index 9ad52e166e5..3bebaadddbc 100644
--- a/Tests/LibMedia/TestMP3Demuxer.cpp
+++ b/Tests/LibMedia/TestMP3Demuxer.cpp
@@ -9,6 +9,9 @@
#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMediaCodecs/CodedFrame.h>
#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+
+#include "TransientlyAbortingStream.h"
static NonnullRefPtr<Media::Demuxer> create_demuxer(StringView path)
{
@@ -31,6 +34,108 @@ static Media::Track audio_track(Media::Demuxer& demuxer)
return *track;
}
+static NonnullRefPtr<Media::Demuxer> create_demuxer_for(ReadonlyBytes bytes)
+{
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(ByteBuffer::copy(bytes)));
+ return MUST(Media::MP3::MP3Demuxer::from_stream(stream));
+}
+
+static Vector<AK::Duration> timestamps_of_every_frame(Media::Demuxer& demuxer, Media::Track const& track)
+{
+ Vector<AK::Duration> timestamps;
+ while (true) {
+ auto frame = demuxer.get_next_sample_for_track(track);
+ if (frame.is_error()) {
+ EXPECT_EQ(frame.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ timestamps.append(frame.value().presentation_timestamp());
+ }
+ return timestamps;
+}
+
+static void expect_a_transient_abort_to_resume_with_its_frame(ReadonlyBytes bytes, size_t aborted_read_position)
+{
+ Vector<AK::Duration> expected_timestamps;
+ {
+ auto demuxer = create_demuxer_for(bytes);
+ auto track = audio_track(*demuxer);
+ expected_timestamps = timestamps_of_every_frame(*demuxer, track);
+ }
+
+ auto stream = TransientlyAbortingStream::create(MUST(ByteBuffer::copy(bytes)), aborted_read_position);
+ auto demuxer = MUST(Media::MP3::MP3Demuxer::from_stream(stream));
+ auto track = audio_track(*demuxer);
+
+ Vector<AK::Duration> actual_timestamps;
+ 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_timestamps.append(frame.value().presentation_timestamp());
+ }
+ EXPECT(stream->has_aborted_a_read());
+ EXPECT_EQ(aborted_read_count, 1u);
+ EXPECT_EQ(actual_timestamps, expected_timestamps);
+}
+
+static void expect_an_aborted_read_to_resume_with_its_frame(ReadonlyBytes bytes, size_t initial_byte_count)
+{
+ Vector<AK::Duration> expected_timestamps;
+ {
+ auto demuxer = create_demuxer_for(bytes);
+ auto track = audio_track(*demuxer);
+ expected_timestamps = timestamps_of_every_frame(*demuxer, track);
+ }
+
+ auto stream = Media::IncrementallyPopulatedStream::create_empty();
+ stream->set_expected_size(bytes.size());
+ stream->add_chunk_at(0, bytes.trim(initial_byte_count));
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto demuxer = MUST(Media::MP3::MP3Demuxer::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<AK::Duration> actual_timestamps;
+ 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_timestamps.append(frame.value().presentation_timestamp());
+ }
+ demuxer->reset_blocking_reads_aborted_for_track(track);
+ read_was_aborted = true;
+ actual_timestamps.extend(timestamps_of_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_byte_count, bytes.slice(initial_byte_count));
+ stream->close();
+ MUST(reader_thread->join());
+
+ EXPECT_EQ(actual_timestamps, expected_timestamps);
+}
+
TEST_CASE(demuxer_describes_the_only_track_of_the_stream)
{
auto demuxer = create_demuxer("buffered-ranges/tone.mp3"sv);
@@ -155,3 +260,36 @@ TEST_CASE(demuxer_declines_a_stream_that_holds_no_frames)
EXPECT(demuxer.is_error());
EXPECT_EQ(demuxer.error().category(), Media::DecoderErrorCategory::UnrecognizedFormat);
}
+
+static Vector<u8> constant_bitrate_mp3_frames(size_t count)
+{
+ // 128 kbps 48 kHz stereo Layer III frames, which each occupy 384 bytes.
+ Vector<u8> bytes;
+ for (size_t index = 0; index < count; index++) {
+ bytes.append(0xFF);
+ bytes.append(0xFB);
+ bytes.append(0x94);
+ bytes.append(0x00);
+ for (size_t padding = 4; padding < 384; padding++)
+ bytes.append(0);
+ }
+ return bytes;
+}
+
+TEST_CASE(demuxer_resumes_a_read_aborted_inside_a_frame_with_that_frame)
+{
+ auto bytes = constant_bitrate_mp3_frames(80);
+ expect_an_aborted_read_to_resume_with_its_frame(bytes, (40 * 384) + 100);
+}
+
+TEST_CASE(demuxer_resumes_a_read_aborted_inside_a_frame_header_with_that_frame)
+{
+ auto bytes = constant_bitrate_mp3_frames(80);
+ expect_an_aborted_read_to_resume_with_its_frame(bytes, (40 * 384) + 2);
+}
+
+TEST_CASE(demuxer_resumes_after_a_transient_abort)
+{
+ auto bytes = constant_bitrate_mp3_frames(80);
+ expect_a_transient_abort_to_resume_with_its_frame(bytes, 40 * 384);
+}
diff --git a/Tests/LibMedia/TestMP3Reader.cpp b/Tests/LibMedia/TestMP3Reader.cpp
index 408127d100a..78d41ca072b 100644
--- a/Tests/LibMedia/TestMP3Reader.cpp
+++ b/Tests/LibMedia/TestMP3Reader.cpp
@@ -34,7 +34,7 @@ static NonnullRefPtr<Media::ReadonlyBytesCursor> create_cursor(ReadonlyBytes byt
static Optional<Media::MP3::Reader> read(Vector<u8> const& bytes)
{
- return Media::MP3::Reader::from_stream(create_cursor(bytes));
+ return MUST(Media::MP3::Reader::from_stream(create_cursor(bytes)));
}
static ByteBuffer read_fixture(StringView path)
@@ -46,7 +46,7 @@ static ByteBuffer read_fixture(StringView path)
TEST_CASE(reader_takes_an_exact_duration_from_a_stream_info_frame)
{
auto data = read_fixture("buffered-ranges/tone.mp3"sv);
- auto reader = Media::MP3::Reader::from_stream(create_cursor(data));
+ auto reader = MUST(Media::MP3::Reader::from_stream(create_cursor(data)));
EXPECT(reader.has_value());
EXPECT(reader->stream_info().has_value());
@@ -63,7 +63,7 @@ TEST_CASE(reader_takes_an_exact_duration_from_a_stream_info_frame)
TEST_CASE(reader_estimates_a_duration_without_a_stream_info_frame)
{
auto data = read_fixture("bbb_without_stream_info.mp3"sv);
- auto reader = Media::MP3::Reader::from_stream(create_cursor(data));
+ auto reader = MUST(Media::MP3::Reader::from_stream(create_cursor(data)));
EXPECT(reader.has_value());
EXPECT(!reader->stream_info().has_value());
@@ -84,7 +84,7 @@ TEST_CASE(frame_iterator_walks_every_frame_of_a_stream)
size_t frame_count = 0;
u64 sample_count = 0;
- for (auto frame = iterator.next(); frame.has_value(); frame = iterator.next()) {
+ for (auto frame = MUST(iterator.next()); frame.has_value(); frame = MUST(iterator.next())) {
frame_count++;
sample_count += frame->header.sample_count;
}
@@ -103,9 +103,9 @@ TEST_CASE(frame_iterator_stops_where_a_frame_header_can_no_longer_be_read)
// third frame is all that has to be missing for the walk to end.
auto truncated = bytes.span().trim(2 * FRAME_BYTE_SIZE + 2);
Media::MP3::FrameIterator iterator { create_cursor(truncated), 0, Media::MP3::FrameIterator::Resynchronize::No };
- EXPECT(iterator.next().has_value());
- EXPECT(iterator.next().has_value());
- EXPECT(!iterator.next().has_value());
+ EXPECT(MUST(iterator.next()).has_value());
+ EXPECT(MUST(iterator.next()).has_value());
+ EXPECT(!MUST(iterator.next()).has_value());
EXPECT_EQ(iterator.position(), 2u * FRAME_BYTE_SIZE);
}
@@ -121,7 +121,7 @@ TEST_CASE(reader_reports_what_it_scanned_of_a_stream_of_an_unknown_size)
cursor->set_is_blocking(false);
// Nothing says how long the stream is, so the frames the scan walked are all there is to go on.
- auto reader = Media::MP3::Reader::from_stream(cursor);
+ auto reader = MUST(Media::MP3::Reader::from_stream(cursor));
EXPECT(reader.has_value());
EXPECT(reader->duration_is_estimated());
EXPECT_EQ(reader->duration(), AK::Duration::from_time_units(3 * 1152, 1, 48'000));
@@ -211,10 +211,10 @@ TEST_CASE(backward_search_reads_back_through_bytes_holding_no_frames)
auto target = bytes.size() - 1;
// The last two frames lack the run of frames after them that would rule out a false sync code.
- auto boundary = Media::MP3::Reader::find_frame_boundary_at_or_before(create_cursor(bytes), target, 0, bytes.size());
+ auto boundary = MUST(Media::MP3::Reader::find_frame_boundary_at_or_before(create_cursor(bytes), target, 0, bytes.size()));
EXPECT_EQ(boundary.value_or(0), 7 * FRAME_BYTE_SIZE);
// The search goes no further back than its lower bound.
- boundary = Media::MP3::Reader::find_frame_boundary_at_or_before(create_cursor(bytes), target, audio_end, bytes.size());
+ boundary = MUST(Media::MP3::Reader::find_frame_boundary_at_or_before(create_cursor(bytes), target, audio_end, bytes.size()));
EXPECT(!boundary.has_value());
}
diff --git a/Tests/LibMedia/TransientlyAbortingStream.h b/Tests/LibMedia/TransientlyAbortingStream.h
new file mode 100644
index 00000000000..93e98ef16c1
--- /dev/null
+++ b/Tests/LibMedia/TransientlyAbortingStream.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Atomic.h>
+#include <AK/ByteBuffer.h>
+#include <LibMedia/MediaStream.h>
+#include <LibMedia/ReadonlyBytesCursor.h>
+
+// Fails the first blocking read that starts at or after a position the way an abort would, but leaves no abort flag
+// set behind it, as when the abort is reset before the reading thread could look at it.
+class TransientlyAbortingStream final : public Media::MediaStream {
+public:
+ static NonnullRefPtr<TransientlyAbortingStream> create(ByteBuffer data, size_t aborted_read_position)
+ {
+ return adopt_ref(*new TransientlyAbortingStream(move(data), aborted_read_position));
+ }
+
+ virtual NonnullRefPtr<Media::MediaStreamCursor> create_cursor() override { return make_ref_counted<Cursor>(*this); }
+ virtual Availability availability() const override { return { { { 0, m_data.size() } }, m_data.size(), true }; }
+ virtual Optional<u64> expected_size() const override { return m_data.size(); }
+ virtual bool is_closed() const override { return true; }
+
+ bool has_aborted_a_read() const { return m_has_aborted_a_read.load(); }
+
+private:
+ class Cursor final : public Media::MediaStreamCursor {
+ public:
+ explicit Cursor(TransientlyAbortingStream& stream)
+ : m_stream(stream)
+ , m_bytes(make_ref_counted<Media::ReadonlyBytesCursor>(stream.m_data.bytes()))
+ {
+ }
+
+ virtual void set_is_blocking(bool is_blocking) override { m_is_blocking = is_blocking; }
+ virtual Media::DecoderErrorOr<void> seek(i64 offset, AK::SeekMode mode) override { return m_bytes->seek(offset, mode); }
+
+ virtual Media::DecoderErrorOr<size_t> read_into(Bytes bytes) override
+ {
+ TRY(abort_if_reading_the_aborted_position());
+ return m_bytes->read_into(bytes);
+ }
+
+ virtual Media::DecoderErrorOr<FixedArray<u8>> read_bytes(size_t size) override
+ {
+ TRY(abort_if_reading_the_aborted_position());
+ return m_bytes->read_bytes(size);
+ }
+
+ virtual size_t position() const override { return m_bytes->position(); }
+ virtual Optional<u64> size() const override { return m_bytes->size(); }
+ virtual size_t blocking_size() const override { return m_bytes->blocking_size(); }
+
+ private:
+ Media::DecoderErrorOr<void> abort_if_reading_the_aborted_position()
+ {
+ if (!m_is_blocking || position() < m_stream->m_aborted_read_position || m_stream->m_has_aborted_a_read.exchange(true))
+ return {};
+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::Aborted, "Read aborted"sv);
+ }
+
+ NonnullRefPtr<TransientlyAbortingStream> m_stream;
+ NonnullRefPtr<Media::ReadonlyBytesCursor> m_bytes;
+ bool m_is_blocking { true };
+ };
+
+ TransientlyAbortingStream(ByteBuffer data, size_t aborted_read_position)
+ : m_data(move(data))
+ , m_aborted_read_position(aborted_read_position)
+ {
+ }
+
+ ByteBuffer m_data;
+ size_t m_aborted_read_position { 0 };
+ Atomic<bool> m_has_aborted_a_read { false };
+};