747 lines
21 KiB
Luau
747 lines
21 KiB
Luau
--!strict
|
|
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
|
|
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
|
|
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
|
|
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
|
|
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Aac = require("@formats/codecs/Aac")
|
|
local Alac = require("@formats/codecs/Alac")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Caf = {
|
|
name = "caf",
|
|
category = "audio",
|
|
extensions = { "caf", "caff" },
|
|
mime = { "audio/x-caf" },
|
|
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
|
|
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ types
|
|
export type DecodeOptions = {
|
|
maxPackets: number?, -- packet table limit (default 2^24)
|
|
}
|
|
export type EncodeOptions = {
|
|
codec: ("pcm" | "alac")?, -- default "alac"
|
|
bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24
|
|
tags: Types.Tags?, -- default: the audio's tags
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ constants
|
|
local INFO_TAGS: { [string]: string } = {
|
|
title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track",
|
|
comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist",
|
|
["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm",
|
|
}
|
|
local TAG_INFO: { [string]: string } = {}
|
|
for k, v in INFO_TAGS do
|
|
TAG_INFO[v] = k
|
|
end
|
|
|
|
-- mu-law / A-law -> linear 16-bit
|
|
local ULAW, ALAW = table.create(256, 0), table.create(256, 0)
|
|
for i = 0, 255 do
|
|
local u = 255 - i
|
|
local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7)
|
|
ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132
|
|
local a = bit32.bxor(i, 0x55)
|
|
local seg = bit32.band(bit32.rshift(a, 4), 7)
|
|
local m = bit32.band(a, 15) * 16 + 8
|
|
if seg > 0 then
|
|
m = (m + 256) * 2 ^ (seg - 1)
|
|
end
|
|
ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function Caf.sniff(r: Bytes.Reader): number
|
|
local h = r:peek(8)
|
|
if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then
|
|
return 1
|
|
end
|
|
return 0
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number }
|
|
type Parsed = {
|
|
desc: Desc,
|
|
dataStart: number, -- absolute offset of the audio data
|
|
dataEnd: number,
|
|
cookie: buffer?,
|
|
packets: { number }?, -- sizes (pakt)
|
|
packetFrames: { number }?,
|
|
priming: number,
|
|
remainder: number,
|
|
validFrames: number?,
|
|
tags: Types.Tags,
|
|
}
|
|
|
|
-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo
|
|
local function esdsConfig(b: buffer): buffer?
|
|
local r = Bytes.reader(b)
|
|
if r:peekU8() ~= 3 then
|
|
r:skip(4) -- the esds atom's version / flags
|
|
end
|
|
local function len(): number
|
|
local n = 0
|
|
for _ = 1, 4 do
|
|
local c = r:u8()
|
|
n = n * 128 + bit32.band(c, 127)
|
|
if c < 128 then
|
|
break
|
|
end
|
|
end
|
|
return n
|
|
end
|
|
while not r:eof() and not r.err do
|
|
local tag = r:u8()
|
|
local n = len()
|
|
if tag == 3 then
|
|
r:skip(2)
|
|
local f = r:u8()
|
|
if bit32.band(f, 0x80) ~= 0 then
|
|
r:skip(2)
|
|
end
|
|
if bit32.band(f, 0x40) ~= 0 then
|
|
r:skip(r:u8())
|
|
end
|
|
if bit32.band(f, 0x20) ~= 0 then
|
|
r:skip(2)
|
|
end
|
|
elseif tag == 4 then
|
|
r:skip(13)
|
|
elseif tag == 5 then
|
|
if n > 0 and r:need(n) then
|
|
return r:bytes(n)
|
|
end
|
|
return nil
|
|
else
|
|
r:skip(n)
|
|
end
|
|
end
|
|
return nil
|
|
end
|
|
|
|
local function vlq(r: Bytes.Reader): number
|
|
local v = 0
|
|
for _ = 1, 8 do
|
|
local c = r:u8()
|
|
v = v * 128 + bit32.band(c, 127)
|
|
if c < 128 then
|
|
return v
|
|
end
|
|
end
|
|
r:fail(Err.CORRUPT, "bad packet table entry")
|
|
return 0
|
|
end
|
|
|
|
local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
|
|
if Caf.sniff(r) == 0 then
|
|
return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base)
|
|
end
|
|
r:seek(8)
|
|
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
|
|
local haveData = false
|
|
while r:remaining() >= 12 do
|
|
local typ = r:string(4)
|
|
local size = r:i64be()
|
|
local start = r.pos
|
|
if size == -1 and typ == "data" then
|
|
size = r.limit - start
|
|
end
|
|
if size < 0 then
|
|
return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12)
|
|
end
|
|
local stop = start + size
|
|
if stop > r.limit then
|
|
if typ ~= "data" then
|
|
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12)
|
|
end
|
|
stop = r.limit -- a truncated data chunk: play what is there
|
|
end
|
|
local c = Bytes.reader(r.buf, start, stop - start)
|
|
if typ == "desc" then
|
|
p.desc = {
|
|
rate = c:f64be(),
|
|
format = c:string(4),
|
|
flags = c:u32be(),
|
|
bytesPerPacket = c:u32be(),
|
|
framesPerPacket = c:u32be(),
|
|
channels = c:u32be(),
|
|
bits = c:u32be(),
|
|
}
|
|
if c.err then
|
|
return nil, c.err
|
|
end
|
|
elseif typ == "data" then
|
|
p.dataStart = start + 4 -- edit count
|
|
p.dataEnd = stop
|
|
haveData = true
|
|
elseif typ == "kuki" then
|
|
p.cookie = c:bytes(stop - start)
|
|
elseif typ == "pakt" then
|
|
local n = c:i64be()
|
|
p.validFrames = c:i64be()
|
|
p.priming = c:i32be()
|
|
p.remainder = c:i32be()
|
|
if c.err then
|
|
return nil, c.err
|
|
end
|
|
if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then
|
|
return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start)
|
|
end
|
|
local d = p.desc
|
|
if not d then
|
|
return nil, Err.new(Err.CORRUPT, "pakt before desc", start)
|
|
end
|
|
local sizes, frames = table.create(n, 0), nil
|
|
if d.framesPerPacket == 0 then
|
|
frames = table.create(n, 0)
|
|
end
|
|
for i = 1, n do
|
|
sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket
|
|
if frames then
|
|
frames[i] = vlq(c)
|
|
end
|
|
end
|
|
if c.err then
|
|
return nil, c.err
|
|
end
|
|
p.packets, p.packetFrames = sizes, frames
|
|
elseif typ == "info" then
|
|
local n = c:u32be()
|
|
for _ = 1, math.min(n, 1000) do
|
|
local k = c:cstring()
|
|
local v = c:cstring()
|
|
if c.err then
|
|
break
|
|
end
|
|
p.tags[INFO_TAGS[string.lower(k)] or k] = v
|
|
end
|
|
end
|
|
r.pos = stop
|
|
if typ == "data" and stop >= r.limit then
|
|
break
|
|
end
|
|
end
|
|
if not p.desc then
|
|
return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base)
|
|
end
|
|
if not haveData then
|
|
return nil, Err.new(Err.CORRUPT, "no data chunk", r.base)
|
|
end
|
|
local d = p.desc
|
|
if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then
|
|
return nil, Err.new(Err.CORRUPT, "bad stream description")
|
|
end
|
|
return p, nil
|
|
end
|
|
|
|
-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err
|
|
type Source = {
|
|
channels: number,
|
|
rate: number,
|
|
packetCount: number,
|
|
packetFrames: (number) -> number,
|
|
decode: (number) -> (number?, Err.Err?),
|
|
pcm: { number },
|
|
reset: () -> (),
|
|
codec: string,
|
|
bits: number?,
|
|
}
|
|
|
|
local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
|
|
local d = p.desc
|
|
local b = r.buf
|
|
local ch = d.channels
|
|
local fmt = d.format
|
|
if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then
|
|
local bits = if fmt == "lpcm" then d.bits else 8
|
|
local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0
|
|
local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0
|
|
local bpf = d.bytesPerPacket
|
|
if bpf == 0 then
|
|
bpf = ch * (bits // 8)
|
|
end
|
|
if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then
|
|
return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits")
|
|
end
|
|
local bps = bits // 8
|
|
if bpf < ch * bps then
|
|
return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame")
|
|
end
|
|
local total = (p.dataEnd - p.dataStart) // bpf
|
|
local per = 1024
|
|
local pcm = table.create(per * ch, 0)
|
|
local scale = 1 / 2 ^ (bits - 1)
|
|
local readu8, readi8 = buffer.readu8, buffer.readi8
|
|
local src: Source = {
|
|
channels = ch,
|
|
rate = d.rate,
|
|
packetCount = (total + per - 1) // per,
|
|
packetFrames = function(i: number): number
|
|
return math.min(per, total - (i - 1) * per)
|
|
end,
|
|
pcm = pcm,
|
|
reset = function() end,
|
|
codec = if fmt == "lpcm" then "pcm" else fmt,
|
|
bits = bits,
|
|
decode = function(i: number): (number?, Err.Err?)
|
|
local f0 = (i - 1) * per
|
|
local n = math.min(per, total - f0)
|
|
local k = 1
|
|
for f = f0, f0 + n - 1 do
|
|
local q = p.dataStart + f * bpf
|
|
for _ = 1, ch do
|
|
local v
|
|
if fmt == "ulaw" then
|
|
v = ULAW[readu8(b, q) + 1] / 32768
|
|
elseif fmt == "alaw" then
|
|
v = ALAW[readu8(b, q) + 1] / 32768
|
|
elseif float then
|
|
if bits == 32 then
|
|
v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be()
|
|
else
|
|
v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be()
|
|
end
|
|
elseif bits == 8 then
|
|
v = readi8(b, q) * scale
|
|
elseif bits == 16 then
|
|
v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1)
|
|
v *= scale
|
|
elseif bits == 24 then
|
|
if little then
|
|
v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q)
|
|
else
|
|
v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
|
|
end
|
|
v *= scale
|
|
else
|
|
if little then
|
|
v = buffer.readi32(b, q)
|
|
else
|
|
v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3)
|
|
end
|
|
v *= scale
|
|
end
|
|
pcm[k] = v
|
|
k += 1
|
|
q += bps
|
|
end
|
|
end
|
|
return n, nil
|
|
end,
|
|
}
|
|
return src, nil
|
|
end
|
|
-- packetised codecs
|
|
local sizes = p.packets
|
|
if not sizes then
|
|
if d.bytesPerPacket > 0 then
|
|
local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
|
|
sizes = table.create(n, d.bytesPerPacket)
|
|
else
|
|
return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table")
|
|
end
|
|
end
|
|
local offsets = table.create(#sizes, 0)
|
|
local o = p.dataStart
|
|
for i, s in sizes :: { number } do
|
|
offsets[i] = o
|
|
o += s
|
|
if o > p.dataEnd then
|
|
-- a truncated file: keep the whole packets
|
|
offsets[i] = nil :: any
|
|
sizes = table.move(sizes :: { number }, 1, i - 1, 1, {})
|
|
break
|
|
end
|
|
end
|
|
local count = #(sizes :: { number })
|
|
local fpp = d.framesPerPacket
|
|
local pf = p.packetFrames
|
|
local function framesOf(i: number): number
|
|
return if pf then pf[i] else fpp
|
|
end
|
|
local cookie = p.cookie
|
|
if fmt == "alac" then
|
|
if not cookie then
|
|
return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie")
|
|
end
|
|
local cfg, err = Alac.config(cookie :: buffer)
|
|
if not cfg then
|
|
return nil, err
|
|
end
|
|
local dec = Alac.decoder(cfg)
|
|
local pcm = table.create(cfg.frameLength * cfg.channels, 0)
|
|
local scale = 1 / 2 ^ (cfg.bitDepth - 1)
|
|
return {
|
|
channels = cfg.channels,
|
|
rate = d.rate,
|
|
packetCount = count,
|
|
packetFrames = framesOf,
|
|
pcm = pcm,
|
|
reset = function() end,
|
|
codec = "alac",
|
|
bits = cfg.bitDepth,
|
|
decode = function(i: number): (number?, Err.Err?)
|
|
local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i])
|
|
if not n then
|
|
return nil, e
|
|
end
|
|
local src = dec.pcm
|
|
for k = 1, n * cfg.channels do
|
|
pcm[k] = src[k] * scale
|
|
end
|
|
return n, nil
|
|
end,
|
|
}, nil
|
|
elseif fmt == "aac " then
|
|
local asc = if cookie then esdsConfig(cookie :: buffer) else nil
|
|
if not asc then
|
|
return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie")
|
|
end
|
|
local dec, err = Aac.decoder(asc :: buffer)
|
|
if not dec then
|
|
return nil, err
|
|
end
|
|
local ad = dec :: Aac.Decoder
|
|
return {
|
|
channels = ad.channels,
|
|
rate = d.rate,
|
|
packetCount = count,
|
|
packetFrames = framesOf,
|
|
pcm = ad.pcm,
|
|
reset = function()
|
|
ad:reset()
|
|
end,
|
|
codec = "aac",
|
|
decode = function(i: number): (number?, Err.Err?)
|
|
return ad:decode(b, offsets[i], (sizes :: { number })[i])
|
|
end,
|
|
}, nil
|
|
end
|
|
return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'")
|
|
end
|
|
|
|
function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
|
local p, err = parse(r, opts or {})
|
|
if not p then
|
|
return nil, err
|
|
end
|
|
local s, serr = source(r, p :: Parsed)
|
|
if not s then
|
|
return nil, serr
|
|
end
|
|
local src = s :: Source
|
|
local ch, rate = src.channels, src.rate
|
|
local starts = table.create(src.packetCount + 1, 0)
|
|
local total = 0
|
|
for i = 1, src.packetCount do
|
|
starts[i] = total
|
|
total += src.packetFrames(i)
|
|
end
|
|
starts[src.packetCount + 1] = total
|
|
local skip = math.max(0, p.priming)
|
|
local stopAt = total
|
|
if p.validFrames and p.validFrames >= 0 then
|
|
stopAt = math.min(total, skip + p.validFrames)
|
|
elseif p.remainder > 0 then
|
|
stopAt = math.max(skip, total - p.remainder)
|
|
end
|
|
local frames = math.max(0, stopAt - skip)
|
|
local nextPacket = 1
|
|
local decoded = 0
|
|
local pendPos, pendN = 0, 0
|
|
local dropUntil = skip
|
|
local pos = 0
|
|
local failed: Err.Err? = nil
|
|
local dec: any = {
|
|
sampleRate = rate,
|
|
channels = ch,
|
|
frames = frames,
|
|
duration = frames / rate,
|
|
bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0,
|
|
tags = p.tags,
|
|
codec = src.codec,
|
|
bitsPerSample = src.bits,
|
|
error = nil,
|
|
}
|
|
local function fill(): boolean
|
|
while true do
|
|
if nextPacket > src.packetCount or decoded >= stopAt then
|
|
return false
|
|
end
|
|
local i = nextPacket
|
|
nextPacket += 1
|
|
local start = starts[i]
|
|
local n, e = src.decode(i)
|
|
if not n then
|
|
failed = e
|
|
dec.error = e
|
|
return false
|
|
end
|
|
decoded = start + n
|
|
local a = math.max(start, dropUntil)
|
|
local b = math.min(decoded, stopAt)
|
|
if b > a then
|
|
pendPos, pendN = a - start, b - start
|
|
return true
|
|
end
|
|
end
|
|
end
|
|
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
|
|
local want = math.max(0, math.floor(n))
|
|
local need = want * ch * 4
|
|
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
|
|
local got = 0
|
|
local writef32 = buffer.writef32
|
|
while got < want do
|
|
if pendPos >= pendN then
|
|
if failed or not fill() then
|
|
break
|
|
end
|
|
end
|
|
local take = math.min(want - got, pendN - pendPos)
|
|
local q = got * ch * 4
|
|
local sidx = pendPos * ch
|
|
local pcm = src.pcm
|
|
for k = 1, take * ch do
|
|
writef32(ob, q, pcm[sidx + k])
|
|
q += 4
|
|
end
|
|
pendPos += take
|
|
got += take
|
|
end
|
|
pos += got
|
|
return ob, got
|
|
end
|
|
function dec.seek(_self: any, seconds: number)
|
|
local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip
|
|
local lo, hi, found = 1, src.packetCount, 1
|
|
while lo <= hi do
|
|
local mid = (lo + hi) // 2
|
|
if starts[mid] <= target then
|
|
found = mid
|
|
lo = mid + 1
|
|
else
|
|
hi = mid - 1
|
|
end
|
|
end
|
|
if src.codec == "aac" then
|
|
found = math.max(1, found - 1)
|
|
end
|
|
src.reset()
|
|
nextPacket = found
|
|
decoded = starts[found]
|
|
dropUntil = target
|
|
pendPos, pendN = 0, 0
|
|
failed = nil
|
|
pos = target - skip
|
|
end
|
|
function dec.position(_self: any): number
|
|
return pos / rate
|
|
end
|
|
if src.packetCount > 0 and frames > 0 and not fill() and failed then
|
|
return nil, failed
|
|
end
|
|
return dec, nil
|
|
end
|
|
|
|
function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
|
local dec, err = Caf.open(r, opts)
|
|
if not dec then
|
|
return nil, err
|
|
end
|
|
local d: any = dec
|
|
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
|
|
local done = 0
|
|
while done < d.frames do
|
|
local b, n = d:read(math.min(65536, d.frames - done))
|
|
if n == 0 then
|
|
break
|
|
end
|
|
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
|
|
done += n
|
|
end
|
|
if d.error then
|
|
return nil, d.error
|
|
end
|
|
audio.tags = d.tags
|
|
audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }
|
|
return audio, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
local function chunk(w: Bytes.Writer, typ: string, size: number)
|
|
w:string(typ)
|
|
w:i64be(size)
|
|
end
|
|
|
|
-- encode(audio | decoder, opts?) -> buffer | nil, Err
|
|
function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
local o = opts or {}
|
|
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
|
|
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
|
|
end
|
|
local codec = o.codec or "alac"
|
|
if codec ~= "alac" and codec ~= "pcm" then
|
|
return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'")
|
|
end
|
|
local sr, ch = value.sampleRate, value.channels
|
|
local depth = o.bitDepth or 16
|
|
if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then
|
|
return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)")
|
|
end
|
|
if ch < 1 or ch > 64 or sr <= 0 then
|
|
return nil, Err.new(Err.ARG, "bad sample rate / channels")
|
|
end
|
|
-- the source frames
|
|
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
|
|
if not isAudio and type(value.read) ~= "function" then
|
|
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
|
|
end
|
|
if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then
|
|
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
|
|
end
|
|
local done = 0
|
|
local chunkBuf: buffer? = nil
|
|
local function nextBlock(n: number): (buffer?, number, number)
|
|
if isAudio then
|
|
local k = math.min(n, value.frames - done)
|
|
local base = done * ch * 4
|
|
done += k
|
|
return value.samples, base, k
|
|
end
|
|
local b, got = value:read(n, chunkBuf)
|
|
chunkBuf = b
|
|
done += got
|
|
return b, 0, got
|
|
end
|
|
local readf32 = buffer.readf32
|
|
local data = Bytes.writer(65536)
|
|
local sizes: { number } = {}
|
|
local enc: Alac.Encoder? = nil
|
|
if codec == "alac" then
|
|
local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth })
|
|
if not e then
|
|
return nil, err
|
|
end
|
|
enc = e
|
|
local ints = table.create(4096 * ch, 0)
|
|
local peak = 2 ^ (depth - 1)
|
|
while true do
|
|
local b, base, n = nextBlock(4096)
|
|
if not b or n <= 0 then
|
|
break
|
|
end
|
|
for i = 0, n * ch - 1 do
|
|
local v = math.floor(readf32(b, base + i * 4) * peak + 0.5)
|
|
ints[i + 1] = math.clamp(v, -peak, peak - 1)
|
|
end
|
|
local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n)
|
|
if not pkt then
|
|
return nil, perr
|
|
end
|
|
data:bytes(pkt)
|
|
table.insert(sizes, buffer.len(pkt))
|
|
end
|
|
else
|
|
local peak = 2 ^ (depth - 1)
|
|
while true do
|
|
local b, base, n = nextBlock(4096)
|
|
if not b or n <= 0 then
|
|
break
|
|
end
|
|
for i = 0, n * ch - 1 do
|
|
local f = readf32(b, base + i * 4)
|
|
if depth == 32 then
|
|
data:f32be(f)
|
|
else
|
|
local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1)
|
|
if depth == 16 then
|
|
data:u16be(v % 65536)
|
|
else
|
|
data:u24be(v % 16777216)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
local frames = done
|
|
local w = Bytes.writer(data:tell() + 1024)
|
|
w:string("caff")
|
|
w:u16be(1)
|
|
w:u16be(0)
|
|
chunk(w, "desc", 32)
|
|
w:f64be(sr)
|
|
if codec == "alac" then
|
|
w:string("alac")
|
|
w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1)
|
|
w:u32be(0)
|
|
w:u32be(4096)
|
|
w:u32be(ch)
|
|
w:u32be(0)
|
|
else
|
|
w:string("lpcm")
|
|
w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer
|
|
w:u32be(ch * depth // 8)
|
|
w:u32be(1)
|
|
w:u32be(ch)
|
|
w:u32be(depth)
|
|
end
|
|
local tags = o.tags or value.tags or {}
|
|
local keys = {}
|
|
for k, v in tags do
|
|
if type(v) == "string" then
|
|
table.insert(keys, k)
|
|
end
|
|
end
|
|
table.sort(keys)
|
|
if #keys > 0 then
|
|
local info = Bytes.writer(256)
|
|
info:u32be(#keys)
|
|
for _, k in keys do
|
|
info:cstring(TAG_INFO[k] or k)
|
|
info:cstring(tags[k])
|
|
end
|
|
chunk(w, "info", info:tell())
|
|
w:bytes(info.buf, 0, info:tell())
|
|
end
|
|
if enc then
|
|
local cookie = Alac.cookie(enc.config)
|
|
chunk(w, "kuki", buffer.len(cookie))
|
|
w:bytes(cookie)
|
|
local pk = Bytes.writer(64 + #sizes * 2)
|
|
pk:i64be(#sizes)
|
|
pk:i64be(frames)
|
|
pk:u32be(0)
|
|
pk:u32be(#sizes * 4096 - frames)
|
|
for _, s in sizes do
|
|
-- BER variable-length integer
|
|
local bytes = { s % 128 }
|
|
local v = s // 128
|
|
while v > 0 do
|
|
table.insert(bytes, 1, 128 + v % 128)
|
|
v //= 128
|
|
end
|
|
for _, x in bytes do
|
|
pk:u8(x)
|
|
end
|
|
end
|
|
chunk(w, "pakt", pk:tell())
|
|
w:bytes(pk.buf, 0, pk:tell())
|
|
end
|
|
chunk(w, "data", data:tell() + 4)
|
|
w:u32be(0) -- edit count
|
|
w:bytes(data.buf, 0, data:tell())
|
|
return w:finish(), nil
|
|
end
|
|
|
|
return Caf
|