rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,668 @@
|
||||
--!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/audio/Alac), AAC-LC (codecs/audio/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. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported:
|
||||
-- other compressed formats (UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Chunks = require("@rosetta/containers/Chunks")
|
||||
local Pcm = require("@rosetta/codecs/audio/Pcm")
|
||||
local Stream = require("@rosetta/codecs/audio/Stream")
|
||||
local Aac = require("@rosetta/codecs/audio/Aac")
|
||||
local Alac = require("@rosetta/codecs/audio/Alac")
|
||||
local Adpcm = require("@rosetta/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Caf = {
|
||||
name = "caf",
|
||||
category = "audio",
|
||||
extensions = { "caf", "caff" },
|
||||
mime = { "audio/x-caf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
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
|
||||
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
|
||||
local haveData = false
|
||||
-- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file
|
||||
for _, ch in Chunks.walk(r.buf, r.base + 8, r.limit, { bigEndian = true, sizeBytes = 8, openEnded = { data = true } }) do
|
||||
local typ, start = ch.id, ch.offset
|
||||
if ch.truncated and typ ~= "data" then
|
||||
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", ch.start)
|
||||
end
|
||||
local stop = start + ch.avail
|
||||
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 string.lower(k)] = v
|
||||
end
|
||||
end
|
||||
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 or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none
|
||||
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 :: { number }), 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 pp = p :: Parsed
|
||||
if pp.desc.format == "ima4" then
|
||||
-- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets
|
||||
local ch = pp.desc.channels
|
||||
local packets = (pp.dataEnd - pp.dataStart) // (34 * ch)
|
||||
local frames = packets * 64
|
||||
if pp.validFrames and pp.validFrames >= 0 then
|
||||
frames = math.min(frames, pp.validFrames)
|
||||
end
|
||||
local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 }
|
||||
local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames })
|
||||
if d then
|
||||
d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64)
|
||||
end
|
||||
return d, derr
|
||||
end
|
||||
local s, serr = source(r, pp)
|
||||
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 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,
|
||||
}
|
||||
return Stream.packets(dec, {
|
||||
count = src.packetCount,
|
||||
start = function(i: number): number
|
||||
return starts[i]
|
||||
end,
|
||||
decode = src.decode,
|
||||
pcm = function(): { number }
|
||||
return src.pcm
|
||||
end,
|
||||
reset = src.reset,
|
||||
skip = skip,
|
||||
stop = stopAt,
|
||||
preroll = if src.codec == "aac" then 1 else 0,
|
||||
})
|
||||
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
|
||||
return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample })
|
||||
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: EncodeOptions = 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
|
||||
Reference in new issue
Block a user