|
| 1 | +/* |
| 2 | + * Copyright (c) 2026-present, the Ladybird developers. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: BSD-2-Clause |
| 5 | + */ |
| 6 | + |
| 7 | +#include <AK/Math.h> |
| 8 | +#include <LibMedia/Codecs/Vorbis.h> |
| 9 | + |
| 10 | +extern "C" { |
| 11 | +#include <libavcodec/vorbis_parser.h> |
| 12 | +} |
| 13 | + |
| 14 | +namespace Media::Codecs { |
| 15 | + |
| 16 | +Optional<Vorbis::Parser> Vorbis::Parser::create(ReadonlyBytes codec_initialization_data) |
| 17 | +{ |
| 18 | + if (codec_initialization_data.is_empty()) |
| 19 | + return {}; |
| 20 | + |
| 21 | + auto* parser = av_vorbis_parse_init(codec_initialization_data.data(), AK::clamp_to<int>(codec_initialization_data.size())); |
| 22 | + if (!parser) |
| 23 | + return {}; |
| 24 | + return Parser { parser }; |
| 25 | +} |
| 26 | + |
| 27 | +Vorbis::Parser::Parser(AVVorbisParseContext* context) |
| 28 | + : m_context(context) |
| 29 | +{ |
| 30 | + VERIFY(m_context); |
| 31 | +} |
| 32 | + |
| 33 | +Vorbis::Parser::Parser(Parser&& other) |
| 34 | + : m_context(exchange(other.m_context, nullptr)) |
| 35 | +{ |
| 36 | +} |
| 37 | + |
| 38 | +Vorbis::Parser& Vorbis::Parser::operator=(Parser&& other) |
| 39 | +{ |
| 40 | + if (this == &other) |
| 41 | + return *this; |
| 42 | + |
| 43 | + if (m_context) |
| 44 | + av_vorbis_parse_free(&m_context); |
| 45 | + m_context = exchange(other.m_context, nullptr); |
| 46 | + return *this; |
| 47 | +} |
| 48 | + |
| 49 | +Vorbis::Parser::~Parser() |
| 50 | +{ |
| 51 | + if (m_context) |
| 52 | + av_vorbis_parse_free(&m_context); |
| 53 | +} |
| 54 | + |
| 55 | +void Vorbis::Parser::reset() const |
| 56 | +{ |
| 57 | + av_vorbis_parse_reset(m_context); |
| 58 | +} |
| 59 | + |
| 60 | +Optional<u32> Vorbis::Parser::parse_packet_duration_in_samples(ReadonlyBytes packet) const |
| 61 | +{ |
| 62 | + int flags = 0; |
| 63 | + auto duration = av_vorbis_parse_frame_flags(m_context, packet.data(), AK::clamp_to<int>(packet.size()), &flags); |
| 64 | + if (duration < 0) |
| 65 | + return {}; |
| 66 | + return duration; |
| 67 | +} |
| 68 | + |
| 69 | +Optional<AK::Duration> Vorbis::Parser::parse_packet_duration(ReadonlyBytes packet, u32 sample_rate) const |
| 70 | +{ |
| 71 | + auto duration = parse_packet_duration_in_samples(packet); |
| 72 | + if (!duration.has_value()) |
| 73 | + return {}; |
| 74 | + return AK::Duration::from_time_units(duration.value(), 1, sample_rate); |
| 75 | +} |
| 76 | + |
| 77 | +} |
0 commit comments