Files
audio/audio/mp3/mp3.sakura
T
2026-11-14 15:37:01 -06:00

276 lines
9.8 KiB
Plaintext

#! Contains `decoder`, which reads an MP3 stream's frames as it's asked for
#! them, so a long one plays without being held decoded, and from anywhere it's
#! sought, and `decode`, which reads one whole.
#!
#! MPEG-1, MPEG-2, and MPEG-2.5's Layer III is read, of one channel or two, of
#! any bit rate but the free format, as `layer3.sakura` decodes it. Its frames
#! are found as it's opened, each where the one before ends, or, past what
#! isn't one, at the next of the same stream, so it's sought to any frame. An
#! ID3v2 tag before them is skipped. A Xing or Info frame first, as LAME and
#! FFmpeg write, isn't sound; where it says how much silence the encoder added
#! before the sound and after, those frames are cut, as FFmpeg cuts them, the
#! decoder's own delay of 529 frames with the first, so a stream gives the
#! frames it was encoded from.
import std::math;
module malunal::audio::mp3;
# How many frames of MP3's are decoded before one sought, so its main data's
# reservoir and its filters are as they'd be had it been decoded from the start.
const preroll: u64 = 10;
# The frames a decoder's output lags its sound by.
const decoder_delay: u64 = 529;
#! Reads an MP3 stream's frames as it's asked for them. Its bytes must stay
#! where they are while it reads them.
pub struct decoder {
var bytes: span<u8>;
var starts: vector<u64>; # Where each frame of MP3's begins.
var width: u32; # Its channels.
var stream_rate: u32;
var per: u64; # The frames of sound each gives.
var skip: u64; # Those decoded before the sound begins.
var total: u64; # How many frames of sound it has.
var state: layer3;
var next: u64; # The frame of MP3's decoded next.
var clock: u64; # The frame of what's decoded `next` begins at, before `skip`.
var pcm: vector<f32>; # A frame's sound.
var pending: vector<f32>; # Frames decoded and not yet read, a frame's together.
var taken: u64;
var from: u64; # The frame, before `skip`, a seek asked for.
}
#! Opens an MP3 stream, finding its frames.
#! @param bytes The file's bytes, which must stay where they are while the
#! decoder reads them.
#! @returns The decoder, or why the stream can't be read: `unrecognized` where
#! no run of frames of Layer III is found.
pub def decoder::open(bytes: span<u8>): result<decoder, audio_error> {
var made := decoder{
bytes = bytes, starts = vector::<u64>::new(), state = layer3::new(), pcm = vector::<f32>::new(),
pending = vector::<f32>::new(),
};
val first := first_frame(bytes, audio::past_id3(bytes)) else { return audio_error::unrecognized; };
val head := bytes[first:4];
made.width = is_mono(head) ? 1 : 2;
made.stream_rate = sample_rate(head);
made.per = frame_samples(head) as u64;
# Every frame of the stream, past what isn't one.
var at := first;
while at + 4 <= bytes.length {
val here := bytes[at:4];
if same_stream(head, here) && at + frame_length(here) <= bytes.length {
made.starts.append(at);
at += frame_length(here);
continue;
}
at++;
while at + 4 <= bytes.length && !(bytes[at] == 0xFF && same_stream(head, bytes[at:4])) {
at++;
}
}
# A Xing or Info frame first: no sound, but maybe what the encoder added.
if made.info_frame() is some(&gap) {
made.starts.remove_at(0);
made.skip = gap[0] + decoder_delay;
val all := made.starts.length as u64 * made.per;
made.total = all > gap[0] + gap[1] ? all - gap[0] - gap[1] : 0u;
if gap[0] == 0 && gap[1] == 0 {
made.skip = 0;
made.total = all;
}
} else {
made.total = made.starts.length as u64 * made.per;
}
return audio_error::unrecognized if made.starts.empty;
made.pcm.resize(made.per * made.width as u64);
return made;
}
# The first frame of a run of three of the same stream, each where the one
# before ends, from a place on.
def first_frame(bytes: span<u8>, from: u64): maybe<u64> {
var at := from;
while at + 4 <= bytes.length {
if bytes[at] == 0xFF && header_valid(bytes[at:4]) {
val head := bytes[at:4];
var p := at;
var run: u32 = 0;
while run < 3 && p + 4 <= bytes.length && same_stream(head, bytes[p:4]) {
p += frame_length(bytes[p:4]);
run++;
}
# A file of fewer frames than that, whole.
return at if run == 3 || (run > 0 && p >= bytes.length);
}
at++;
}
return nothing {};
}
# Where the first frame is of Xing's or Info's, what the encoder added before
# the sound and after, as its LAME tag says, or none where it says nothing.
def decoder::info_frame(&this): maybe<u64[2]> {
return nothing {} if this.starts.empty;
val at := this.starts[0];
val head := this.bytes[at:4];
val side: u64 = is_mpeg1(head) ? (is_mono(head) ? 17 : 32) : (is_mono(head) ? 9 : 17);
var p := at + 4 + side + (has_crc(head) ? 2u : 0u);
val end := at + frame_length(head);
return nothing {} if p + 8 > end;
val tag := this.bytes[p:4];
val xing := tag[0] == 'X' && tag[1] == 'i' && tag[2] == 'n' && tag[3] == 'g';
val info := tag[0] == 'I' && tag[1] == 'n' && tag[2] == 'f' && tag[3] == 'o';
return nothing {} if !xing && !info;
val flags := this.bytes[p + 7] as u32;
p += 8;
if (flags & 1) != 0 {
p += 4;
}
if (flags & 2) != 0 {
p += 4;
}
if (flags & 4) != 0 {
p += 100;
}
if (flags & 8) != 0 {
p += 4;
}
var gap: u64[2] = [0, 0];
# LAME's tag, or FFmpeg's of the same layout: its delays 21 bytes in.
if p + 24 <= end {
val name := this.bytes[p:4];
val lame := name[0] == 'L' && ((name[1] == 'A' && name[2] == 'M' && name[3] == 'E') || (name[1] == 'a' && name[2] == 'v'));
if lame {
val v := (this.bytes[p + 21] as u64) << 16 | (this.bytes[p + 22] as u64) << 8 | this.bytes[p + 23] as u64;
gap = [v >> 12, v & 4095];
}
}
return gap;
}
#! How many channels the frames read have: one, or two.
pub val decoder::channels: u32 {
get => this.width;
}
#! Frames a second.
pub val decoder::rate: u32 {
get => this.stream_rate;
}
#! How many frames the stream has.
pub val decoder::frames: u64 {
get => this.total;
}
#! Where the stream says a voice playing it loops: MP3 says nothing, so all of
#! it.
pub val decoder::loop_points: loop_range {
get => loop_range{};
}
#! Reads frames.
#! @param into Where they go, a frame's `channels` floats together.
#! @returns How many frames were read: fewer than fit only once the stream
#! ends; or why the stream couldn't be read.
pub def decoder::read(&mut this, into: slice<f32>): result<u64, audio_error> {
val width := this.width as u64;
val wanted := into.length / width;
var given: u64 = 0;
while given < wanted {
val held := (this.pending.length - this.taken) / width;
if held > 0 {
val count := held < wanted - given ? held : wanted - given;
for i in 0..count * width {
into[given * width + i] = this.pending[this.taken + i];
}
this.taken += count * width;
given += count;
continue;
}
this.pending.clear();
this.taken = 0;
break if !this.next_frame();
}
return given;
}
#! Reads the stream again from its first frame.
pub def decoder::rewind(&mut this): void {
this.state.reset();
this.next = 0;
this.clock = 0;
this.from = 0;
this.pending.clear();
this.taken = 0;
}
#! Reads on from a frame of the stream: from a few frames of MP3's before it,
#! decoded so what's sought is as it'd be from the start, those left out.
#! @param frame The frame, past the end where the stream ends there.
#! @returns Nothing: every frame was found as the stream was opened.
pub def decoder::seek(&mut this, frame: u64): result<void, audio_error> {
this.rewind();
val wanted := (frame < this.total ? frame : this.total) + this.skip;
val holding := wanted / this.per;
this.next = holding > preroll ? holding - preroll : 0u;
this.clock = this.next * this.per;
this.from = wanted;
return;
}
# Decodes the next frame of MP3's into what's pending: but those frames of
# sound before where the sound begins, or a seek asked for, or past where it
# ends.
# @returns Whether there was one.
def decoder::next_frame(&mut this): bool {
val end := this.skip + this.total;
while true {
return false if this.next >= this.starts.length as u64 || this.clock >= end;
val at := this.starts[this.next];
val frame := this.bytes[at:frame_length(this.bytes[at:4])];
_ = this.state.decode_frame(frame, this.pcm.slice);
this.next++;
val begins := this.clock;
this.clock += this.per;
# The frames of sound of it kept.
val low := math::max(begins, math::max(this.from, this.skip));
val high := math::min(this.clock, end);
continue if low >= high;
val width := this.width as u64;
for i in (low - begins) * width..(high - begins) * width {
this.pending.append(this.pcm[i]);
}
return true;
}
return false;
}
#! Whether bytes begin a frame of MP3's, of Layer III.
#! @param bytes The bytes, past any ID3v2 tag.
pub def begins(bytes: span<u8>): bool {
return bytes.length >= 4 && header_valid(bytes[0:4]);
}
#! Reads an MP3 file whole.
#! @param bytes The file's bytes.
#! @returns The sound, or why it couldn't be read: as `decoder::open` says, and
#! `too_large` where it has more frames than `max_frames`.
pub def decode(bytes: span<u8>): result<sound, audio_error> {
var reading := decoder::open(bytes) else (e) { return e; };
return audio_error::too_large if reading.frames > max_frames;
val width := reading.channels as u64;
var samples := vector::<f32>::new();
samples.reserve(reading.frames * width);
var chunk := vector::<f32>::new();
chunk.resize(4096 * width);
while true {
val count := reading.read(chunk.slice) else (e) { return e; };
break if count == 0;
samples.extend(span::<f32>::over(chunk.data, count * width));
}
return sound{ rate = reading.rate, channels = reading.channels, samples = move(samples) };
}