Files
rosetta/src/Rosetta/audio/voc/init.luau
T

275 lines
8.8 KiB
Luau

--!strict
--!optimize 2
-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9
-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9
-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Voc = {
name = "voc",
category = "audio",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16"
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "Creative Voice File\26"
local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" }
local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" }
local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } }
local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes)
local readu8 = buffer.readu8
local function u16(b: buffer, o: number): number
return readu8(b, o) + readu8(b, o + 1) * 256
end
local function u24(b: buffer, o: number): number
return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536
end
-- ------------------------------------------------------------------------------------------------ sniff
function Voc.sniff(r: Bytes.Reader): number
return if r:peek(20) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence
function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad magic", base)
end
local hsize = u16(b, base + 20)
local version = u16(b, base + 22)
if hsize < 26 or hsize > limit - base then
return nil, Err.new(Err.CORRUPT, "bad header size", base + 20)
end
local maxFrames = opts and opts.maxFrames or 2 ^ 28
local rate, channels = 0, 0
local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block
local lastFmt: string? = nil
local codec = -1
local segments: { Segment } = {}
local total = 0
local truncated = false
local tags: Types.Tags = {}
local p = base + hsize
local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err?
if channels == 0 then
channels, rate = ch, sr
elseif ch ~= channels then
return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at)
end
local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes
if frames > 0 then
total += frames
if total > maxFrames then
return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames))
end
table.insert(segments, { at = at, frames = frames, fmt = fmt })
end
return nil
end
while p < limit do
local t = readu8(b, p)
if t == 0 then
break
end
if p + 4 > limit then
truncated = true
break
end
local size = u24(b, p + 1)
local d = p + 4
local avail = math.min(size, limit - d)
if avail < size then
truncated = true
end
local err: Err.Err? = nil
if t == 1 then
if avail < 2 then
break
end
local div, c = readu8(b, d), readu8(b, d + 1)
local fmt = T1_CODECS[c]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1)
end
local ch, sr = 1, 1000000 // (256 - div)
if extChannels > 0 then
ch, sr = extChannels, extRate
extChannels = 0
end
lastFmt, codec = fmt, c
err = add(d + 2, avail - 2, fmt, ch, sr)
elseif t == 2 then
if lastFmt == nil then
return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p)
end
err = add(d, avail, lastFmt, channels, rate)
elseif t == 3 then
if avail < 3 then
break
end
local len, div = u16(b, d) + 1, readu8(b, d + 2)
err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div))
elseif t == 5 then
local s = buffer.readstring(b, d, avail)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
tags.comment = if tags.comment then tags.comment .. "\n" .. s else s
elseif t == 8 then
if avail < 4 then
break
end
local tc, mode = u16(b, d), readu8(b, d + 3)
extChannels = mode + 1
extRate = 256000000 // (extChannels * (65536 - tc))
elseif t == 9 then
if avail < 12 then
break
end
local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216
local ch, c = readu8(b, d + 5), u16(b, d + 6)
local fmt = T9_CODECS[c]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6)
end
if ch < 1 or sr < 1 then
return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d)
end
lastFmt, codec = fmt, c
err = add(d + 12, avail - 12, fmt, ch, sr)
end
if err then
return nil, err
end
p = d + size
end
if channels == 0 then
return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p)
end
local a = Types.Audio.new(rate, channels, total)
local o = 0
for _, s in segments do
local n = s.frames * channels
if s.fmt then
Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o)
end
o += n * 4
end
a.tags = tags
a.meta.source = {
format = "voc",
version = string.format("%d.%02d", version // 256, version % 256),
codec = codec,
sampleFormat = lastFmt,
bitDepth = if lastFmt == "s16le" then 16 else 8,
truncated = truncated or nil,
}
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = WRITE[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
if src.channels > 255 then
return nil, Err.new(Err.ARG, "at most 255 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer")
end
local w = Bytes.writer(65536)
w:string(MAGIC)
w:u16le(26)
w:u16le(0x0114)
w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234
if type(src.tags.comment) == "string" and #src.tags.comment > 0 then
local s = string.sub(src.tags.comment, 1, 0xFFFFFE)
w:u8(5)
w:u24le(#s + 1)
w:string(s)
w:u8(0)
end
local size = Pcm.Convert.SIZE[spec[2]]
local frameBytes = size * src.channels
local framesPerBlock = MAX_BLOCK // frameBytes
local blockAt, blockFrames = -1, 0
local tmp: buffer? = nil
while true do
local bf, n = src:read(math.min(8192, framesPerBlock), tmp)
if n <= 0 then
break
end
tmp = bf
local i = 0
while i < n do
if blockAt < 0 or blockFrames == framesPerBlock then
blockAt = w:tell()
blockFrames = 0
w:u8(9)
w:u24le(0)
w:u32le(src.sampleRate)
w:u8(spec[3])
w:u8(src.channels)
w:u16le(spec[1])
w:u32le(0)
end
local take = math.min(n - i, framesPerBlock - blockFrames)
local at = w:reserve(take * frameBytes)
Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at)
w.pos = at + take * frameBytes
blockFrames += take
i += take
local len = blockFrames * frameBytes + 12
w:setU8(blockAt + 1, len % 256)
w:setU8(blockAt + 2, (len // 256) % 256)
w:setU8(blockAt + 3, len // 65536)
end
end
if src.err then
return nil, src.err
end
w:u8(0) -- terminator
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local a, err = Voc.decode(r, opts)
if not a then
return nil, err
end
local dec = Pcm.audioDecoder(a) :: any
dec.source = a.meta.source
return dec, nil
end
return Voc