Skip to content

Truly independent web browser

10.9 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Array.h>
#include <LibMedia/Containers/ID3.h>
#include <LibMedia/Containers/MP3/Reader.h>

namespace Media::MP3 {

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 DecoderErrorOr<size_t> read_available(MediaStreamCursor& cursor, size_t position, Bytes buffer)
{
    auto result = [&]() -> DecoderErrorOr<size_t> {
        TRY(cursor.seek_to_position(position));
        return cursor.read_into(buffer);
    }();
    if (result.is_error() && !is_stream_control_flow(result.error().category()))
        return 0;
    return result;
}

static DecoderErrorOr<bool> read_exact(MediaStreamCursor& cursor, size_t position, Bytes buffer)
{
    return TRY(read_available(cursor, position, buffer)) == buffer.size();
}

DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::read_frame()
{
    Array<u8, FrameHeader::SIZE> frame_header_data;
    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 Optional<Frame> {};

    Frame frame { m_position, *header };
    m_position += header->frame_byte_size;
    return frame;
}

DecoderErrorOr<Optional<FrameIterator::Frame>> FrameIterator::next()
{
    auto frame = TRY(read_frame());
    if (frame.has_value() || m_resynchronize == Resynchronize::No)
        return frame;

    auto boundary = TRY(Reader::find_frame_boundary_at_or_after(m_cursor, m_position + 1, NumericLimits<size_t>::max()));
    if (!boundary.has_value())
        return Optional<Frame> {};

    m_position = *boundary;
    return read_frame();
}

DecoderErrorOr<FixedArray<u8>> FrameIterator::read_frame_data(Frame const& frame)
{
    TRY(m_cursor->seek_to_position(frame.position));
    return TRY(m_cursor->read_bytes(frame.header.frame_byte_size));
}

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 (!TRY(read_exact(cursor, position, tag_header)))
            break;
        auto tag_size = ID3::version_2_tag_size(tag_header);
        if (!tag_size.has_value())
            break;
        position += *tag_size;
    }
    return position;
}

struct FrameScan {
    size_t position { 0 };
    FrameHeader header;
    size_t frame_count { 0 };
    u64 sample_count { 0 };
    size_t byte_count { 0 };
};

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 = TRY(iterator.next());
        if (!frame.has_value())
            break;
        if (scan.frame_count == 0) {
            scan.position = frame->position;
            scan.header = frame->header;
        }
        scan.frame_count++;
        scan.sample_count += frame->header.sample_count;
        scan.byte_count += frame->header.frame_byte_size;
    }

    if (scan.frame_count == 0)
        return Optional<FrameScan> {};
    return scan;
}

// Bitrate and padding differ from one frame to the next, and so does the mode extension of a joint
// stereo stream, but the rest of what a header describes holds for all the frames of a stream.
static bool headers_describe_the_same_stream(FrameHeader const& first, FrameHeader const& second)
{
    return first.version == second.version
        && first.layer == second.layer
        && first.sample_rate == second.sample_rate
        && first.channel_count == second.channel_count;
}

static DecoderErrorOr<bool> begins_a_frame(NonnullRefPtr<MediaStreamCursor> const& cursor, size_t position)
{
    return TRY(FrameIterator(cursor, position, FrameIterator::Resynchronize::No).next()).has_value();
}

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 = TRY(iterator.next());
        if (!frame.has_value())
            return false;
        if (previous_header.has_value() && !headers_describe_the_same_stream(*previous_header, frame->header))
            return false;
        previous_header = frame->header;
    }
    return true;
}

static bool has_sync_code_at(ReadonlyBytes bytes, size_t index)
{
    if (index + 2 > bytes.size())
        return false;
    return FrameHeader::has_sync_code(static_cast<u16>((bytes[index] << 8) | bytes[index + 1]));
}

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(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 (TRY(begins_a_frame_sequence(cursor, scan_position + index)))
                return Optional<size_t> { scan_position + index };
        }

        if (chunk.size() < SYNC_SCAN_CHUNK_SIZE)
            break;
        scan_position += chunk.size() - 1;
    }

    return Optional<size_t> {};
}

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);

    auto chunk_end = min(target_byte + 2, upper_bound);

    Array<u8, SYNC_SCAN_CHUNK_SIZE> buffer;
    while (chunk_end >= lower_bound + 2) {
        auto chunk_start = chunk_end > SYNC_SCAN_CHUNK_SIZE ? chunk_end - SYNC_SCAN_CHUNK_SIZE : 0;
        chunk_start = max(chunk_start, lower_bound);

        auto chunk = buffer.span().trim(chunk_end - chunk_start);
        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))
                continue;
            auto candidate = chunk_start + index;
            if (candidate > target_byte)
                continue;
            if (TRY(begins_a_frame_sequence(cursor, candidate)))
                return Optional<size_t> { candidate };
        }

        if (chunk_start == lower_bound)
            break;
        chunk_end = chunk_start + 1;
    }

    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 DecoderErrorOr<Optional<size_t>> find_first_frame_position(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
    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 DecoderErrorOr<Optional<FrameScan>> scan_first_frames(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
    auto position = TRY(find_first_frame_position(cursor));
    if (!position.has_value())
        return Optional<FrameScan> {};
    return scan_frames_at(cursor, *position);
}

static DecoderErrorOr<Optional<StreamInfo>> read_stream_info(MediaStreamCursor& cursor, FrameScan const& scan)
{
    Vector<u8> frame;
    frame.resize(scan.header.frame_byte_size);
    if (!TRY(read_exact(cursor, scan.position, frame)))
        return Optional<StreamInfo> {};
    return StreamInfo::parse(frame, scan.header);
}

DecoderErrorOr<Optional<Reader>> Reader::from_stream(NonnullRefPtr<MediaStreamCursor> const& cursor)
{
    auto scan = TRY(scan_first_frames(cursor));
    if (!scan.has_value())
        return Optional<Reader> {};

    Reader reader;
    reader.m_frame_header = scan->header;
    reader.m_first_audio_frame_position = scan->position;
    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.
    if (reader.m_stream_info.has_value()) {
        reader.m_first_audio_frame_position += scan->header.frame_byte_size;
        scan->frame_count--;
        scan->sample_count -= scan->header.sample_count;
        scan->byte_count -= scan->header.frame_byte_size;
    }

    auto sample_rate = scan->header.sample_rate;
    if (reader.m_stream_info.has_value()) {
        if (auto sample_count = reader.m_stream_info->total_sample_count(scan->header); sample_count.has_value()) {
            reader.m_duration = AK::Duration::from_time_units(static_cast<i64>(*sample_count), 1, sample_rate);
            return reader;
        }
    }

    reader.m_duration_is_estimated = true;
    if (scan->byte_count == 0)
        return reader;

    auto audio_byte_count = scan->byte_count;
    if (auto stream_byte_count = cursor->size(); stream_byte_count.has_value() && stream_byte_count.value() > reader.m_first_audio_frame_position)
        audio_byte_count = max(audio_byte_count, static_cast<size_t>(*stream_byte_count) - reader.m_first_audio_frame_position);

    // Prioritize the size indicated by the metadata, as that will exclude trailing garbage.
    if (reader.m_stream_info.has_value() && reader.m_stream_info->byte_count.has_value()) {
        auto declared_byte_count = *reader.m_stream_info->byte_count;
        if (declared_byte_count > scan->header.frame_byte_size)
            audio_byte_count = max(scan->byte_count, declared_byte_count - scan->header.frame_byte_size);
    }

    auto estimated_sample_count = static_cast<u64>(audio_byte_count) * scan->sample_count / scan->byte_count;
    reader.m_duration = AK::Duration::from_time_units(static_cast<i64>(estimated_sample_count), 1, sample_rate);
    return reader;
}

}