Files
rosetta/src/Formats/audio/mp3/Stream.luau
T

234 lines
6.4 KiB
Luau

--!strict
--!optimize 2
-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact
-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws.
local Core = require("@formats/codecs/audio/Mpa/Core")
local Index = require("@formats/audio/mp3/Index")
local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT
local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32
local band = bit32.band
local min, max, floor = math.min, math.max, math.floor
local Stream = {}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
sampleRate: number,
channels: number,
frames: number,
duration: number,
bitrate: number,
tags: { [string]: string },
id3: any,
layer: number,
version: number,
vbr: boolean,
delay: number,
padding: number,
mpegFrames: number,
_buf: buffer,
_idx: any,
_st: any,
_pcm: buffer,
_cur: number,
_pcmPos: number,
_pcmEnd: number,
_minAbs: number,
_endAbs: number,
_pos: number,
},
Decoder
))
-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build)
function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder
local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels
-- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count
local delay = 0
local total = idx.outTotal
if idx.vbrTag > 0 then
delay = idx.delay
local detected = spf * idx.tagFrames
if detected >= delay then
detected -= delay
end
if idx.padding > 0 and detected >= idx.padding then
detected -= idx.padding
end
total = max(0, total - delay)
total = min(total, detected)
end
delay = min(delay, idx.outTotal)
local self = setmetatable({
sampleRate = hz,
channels = nch,
frames = total,
duration = total / hz,
bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s
tags = tags,
id3 = id3,
layer = idx.layer,
version = idx.version,
vbr = idx.vbrTag ~= 0,
delay = delay,
padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0,
mpegFrames = idx.n,
_buf = b,
_idx = idx,
_st = Core.newState(),
_pcm = buffer.create(1152 * 2 * 4),
_cur = 0,
_pcmPos = 0,
_pcmEnd = 0,
_minAbs = delay,
_endAbs = delay + total,
_pos = 0,
}, Decoder)
return self
end
-- decodes frames until one has samples inside [minAbs, endAbs); false at the end
local function fill(self: Decoder): boolean
local idx = self._idx
local n = idx.n
local spf = idx.spf
local st = self._st
while self._cur < n do
local f = self._cur
self._cur = f + 1
local flags = ru8(idx.flags, f)
if band(flags, FLAG_RESET) ~= 0 then
Core.reset(st)
end
local a = ru32(idx.out, f * 4)
if a >= self._endAbs then
self._cur = n
return false
end
local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm)
if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then
if Core.lastChannels < self.channels then
Core.upmix(self._pcm, got)
end
local lo = max(a, self._minAbs)
local hi = min(a + spf, self._endAbs)
if hi > lo then
self._pcmPos = lo - a
self._pcmEnd = hi - a
return true
end
end
end
return false
end
-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream.
-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a
-- smaller out is ignored.
function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number)
local ch = self.channels
local want = tonumber(maxFrames) or 4096
if want ~= want then
want = 0
end
want = floor(max(0, min(want, self.frames - self._pos)))
if out and buffer.len(out) < want * ch * 4 then
out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough)
end
local dst = out or buffer.create(want * ch * 4)
local got = 0
local pcm = self._pcm
while got < want do
if self._pcmPos >= self._pcmEnd then
if not fill(self) then
break
end
end
local k = min(want - got, self._pcmEnd - self._pcmPos)
buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4)
got += k
self._pcmPos += k
end
self._pos += got
if not out and got < want then
local r = buffer.create(got * ch * 4)
buffer.copy(r, 0, dst, 0, got * ch * 4)
dst = r
end
return dst, got
end
-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier
-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped.
function Decoder.seek(self: Decoder, seconds: number)
local hz = self.sampleRate
local target = floor((tonumber(seconds) or 0) * hz + 0.5)
target = max(0, min(target, self.frames))
self:seekFrame(target)
end
-- Seeks to a sample frame (0 .. frames).
function Decoder.seekFrame(self: Decoder, target: number)
target = tonumber(target) or 0
if target ~= target then
target = 0
end
target = max(0, min(floor(target), self.frames))
local idx = self._idx
local abs = self.delay + target
self._pos = target
self._minAbs = abs
self._pcmPos, self._pcmEnd = 0, 0
Core.reset(self._st)
local n = idx.n
if abs >= self._endAbs or n == 0 then
self._cur = n
return
end
-- last frame starting at or before abs
local lo, hi = 0, n - 1
while lo < hi do
local mid = (lo + hi + 1) // 2
if ru32(idx.out, mid * 4) <= abs then
lo = mid
else
hi = mid - 1
end
end
local j = lo
-- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data
-- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets
local need = if idx.layer == 3 then 511 else 0
local s, back, acc = j, 0, 0
while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do
if back >= 2 and acc >= need then
break
end
s -= 1
back += 1
if back >= 2 then
acc += ru16(idx.main, s * 2)
end
end
self._cur = s
end
-- Current position: (seconds, sample frame)
function Decoder.position(self: Decoder): (number, number)
return self._pos / self.sampleRate, self._pos
end
-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames)
function Decoder.readAll(self: Decoder): (buffer, number)
return self:read(max(0, self.frames - self._pos))
end
Stream.Decoder = Decoder
return Stream