ws-audio: audio/aiff (AIFF/AIFC incl. sowt/fl32/fl64/ulaw/alaw), audio/au, audio/voc: decode/open/encode; codecs/Pcm folder (+ Convert: raw sample formats <-> f32, G.711, rawDecoder/audioDecoder/encode); fixtures vs ffmpeg/sox, encoder outputs decoded by ffmpeg in the fixture step
This commit is contained in:
1 parent
bff4999208
commit
0f395e3833
14 files changed
+1940
-6
No files matched your search
@@ -26,6 +26,42 @@ local list: { Entry } = {
|
||||
return require("@formats/image/png")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "aiff",
|
||||
category = "audio",
|
||||
path = "audio/aiff",
|
||||
extensions = { "aiff", "aif", "aifc", "afc" },
|
||||
mime = { "audio/aiff", "audio/x-aiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
load = function()
|
||||
return require("@formats/audio/aiff")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "au",
|
||||
category = "audio",
|
||||
path = "audio/au",
|
||||
extensions = { "au", "snd" },
|
||||
mime = { "audio/basic", "audio/x-au" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
load = function()
|
||||
return require("@formats/audio/au")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "voc",
|
||||
category = "audio",
|
||||
path = "audio/voc",
|
||||
extensions = { "voc" },
|
||||
mime = { "audio/x-voc" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
|
||||
load = function()
|
||||
return require("@formats/audio/voc")
|
||||
end,
|
||||
},
|
||||
}
|
||||
|
||||
return list
|
||||
@@ -0,0 +1,384 @@
|
||||
--!strict
|
||||
-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs.
|
||||
-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw
|
||||
-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated
|
||||
-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 /
|
||||
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 /
|
||||
-- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Aiff = {
|
||||
name = "aiff",
|
||||
category = "audio",
|
||||
extensions = { "aiff", "aif", "aifc", "afc" },
|
||||
mime = { "audio/aiff", "audio/x-aiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- refuse more sample frames (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
|
||||
littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only
|
||||
-- take 16-bit sowt, so other formats return Err.ARG)
|
||||
aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" }
|
||||
local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } }
|
||||
local AIFC_VERSION = 0xA2805140
|
||||
|
||||
-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian)
|
||||
local function ext80(b: buffer, o: number): number
|
||||
local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
|
||||
local hi = bit32.byteswap(buffer.readu32(b, o + 2))
|
||||
local lo = bit32.byteswap(buffer.readu32(b, o + 6))
|
||||
local e = bit32.band(se, 0x7FFF)
|
||||
if e == 0 and hi == 0 and lo == 0 then
|
||||
return 0
|
||||
end
|
||||
if e == 0x7FFF then
|
||||
return math.huge
|
||||
end
|
||||
local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63)
|
||||
return if se >= 0x8000 then -v else v
|
||||
end
|
||||
|
||||
-- the 10 bytes of x (> 0) as an 80-bit extended float
|
||||
local function writeExt80(w: Bytes.Writer, x: number)
|
||||
if x <= 0 or x ~= x then
|
||||
w:fill(0, 10)
|
||||
return
|
||||
end
|
||||
local e = 0
|
||||
while x >= 2 ^ (e + 1) do
|
||||
e += 1
|
||||
end
|
||||
while x < 2 ^ e do
|
||||
e -= 1
|
||||
end
|
||||
local m = x * 2 ^ (63 - e) -- in [2^63, 2^64)
|
||||
local hi = math.floor(m / 4294967296)
|
||||
local lo = m - hi * 4294967296
|
||||
w:u16be(e + 16383)
|
||||
w:u32be(hi)
|
||||
w:u32be(math.floor(lo))
|
||||
end
|
||||
|
||||
-- the sample format of a COMM chunk: Pcm format name | nil, message
|
||||
local function sampleFormat(comp: string, bits: number): (string?, string?)
|
||||
if comp == "NONE" or comp == "twos" or comp == "" then
|
||||
if bits >= 1 and bits <= 8 then
|
||||
return "s8"
|
||||
elseif bits <= 16 then
|
||||
return "s16be"
|
||||
elseif bits <= 24 then
|
||||
return "s24be"
|
||||
elseif bits <= 32 then
|
||||
return "s32be"
|
||||
end
|
||||
return nil, "bad sample size " .. bits
|
||||
elseif comp == "sowt" then
|
||||
if bits >= 1 and bits <= 8 then
|
||||
return "s8"
|
||||
elseif bits <= 16 then
|
||||
return "s16le"
|
||||
elseif bits <= 24 then
|
||||
return "s24le"
|
||||
elseif bits <= 32 then
|
||||
return "s32le"
|
||||
end
|
||||
return nil, "bad sample size " .. bits
|
||||
elseif comp == "raw " then
|
||||
return "u8"
|
||||
elseif comp == "in24" then
|
||||
return "s24be"
|
||||
elseif comp == "in32" then
|
||||
return "s32be"
|
||||
elseif comp == "42ni" then
|
||||
return "s32le"
|
||||
elseif comp == "fl32" or comp == "FL32" then
|
||||
return "f32be"
|
||||
elseif comp == "fl64" or comp == "FL64" then
|
||||
return "f64be"
|
||||
elseif comp == "ulaw" or comp == "ULAW" then
|
||||
return "ulaw"
|
||||
elseif comp == "alaw" or comp == "ALAW" then
|
||||
return "alaw"
|
||||
end
|
||||
return nil, "compression " .. string.format("%q", comp)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Aiff.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 12 or r:peek(4) ~= "FORM" then
|
||||
return 0
|
||||
end
|
||||
local form = buffer.readstring(r.buf, r.pos + 8, 4)
|
||||
return if form == "AIFF" or form == "AIFC" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Info = {
|
||||
channels: number,
|
||||
frames: number,
|
||||
sampleRate: number,
|
||||
bits: number,
|
||||
format: string,
|
||||
compression: string,
|
||||
aifc: boolean,
|
||||
dataOffset: number, -- absolute in r.buf
|
||||
truncated: boolean,
|
||||
tags: Types.Tags,
|
||||
}
|
||||
|
||||
-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples)
|
||||
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b = r.buf
|
||||
local base, limit = r.base, r.limit
|
||||
if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a FORM file", base)
|
||||
end
|
||||
local form = buffer.readstring(b, base + 8, 4)
|
||||
if form ~= "AIFF" and form ~= "AIFC" then
|
||||
return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8)
|
||||
end
|
||||
local aifc = form == "AIFC"
|
||||
local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4)))
|
||||
local info: Info? = nil
|
||||
local comm = false
|
||||
local ssnd: number? = nil
|
||||
local ssndLen = 0
|
||||
local tags: Types.Tags = {}
|
||||
local p = base + 12
|
||||
while p + 8 <= formEnd do
|
||||
local id = buffer.readstring(b, p, 4)
|
||||
local len = bit32.byteswap(buffer.readu32(b, p + 4))
|
||||
local d = p + 8
|
||||
local avail = math.min(len, limit - d)
|
||||
if id == "COMM" then
|
||||
if avail < 18 or (aifc and avail < 22) then
|
||||
return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p)
|
||||
end
|
||||
local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1)
|
||||
local frames = bit32.byteswap(buffer.readu32(b, d + 2))
|
||||
local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7)
|
||||
local rate = ext80(b, d + 8)
|
||||
local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE"
|
||||
if ch < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "no channels", d)
|
||||
end
|
||||
if not (rate > 0 and rate < 2 ^ 31) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8)
|
||||
end
|
||||
local fmt, why = sampleFormat(comp, bits)
|
||||
if not fmt then
|
||||
return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18)
|
||||
end
|
||||
info = {
|
||||
channels = ch,
|
||||
frames = frames,
|
||||
sampleRate = rate,
|
||||
bits = bits,
|
||||
format = fmt,
|
||||
compression = comp,
|
||||
aifc = aifc,
|
||||
dataOffset = 0,
|
||||
truncated = false,
|
||||
tags = tags,
|
||||
}
|
||||
comm = true
|
||||
elseif id == "SSND" then
|
||||
if avail < 8 then
|
||||
return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p)
|
||||
end
|
||||
local off = bit32.byteswap(buffer.readu32(b, d))
|
||||
ssnd = d + 8 + off
|
||||
ssndLen = math.max(0, avail - 8 - off)
|
||||
if len >= 8 + off then
|
||||
ssndLen = math.min(ssndLen, len - 8 - off)
|
||||
end
|
||||
elseif TEXT_TAGS[id] 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
|
||||
local key = TEXT_TAGS[id]
|
||||
tags[key] = if tags[key] then tags[key] .. "\n" .. s else s
|
||||
end
|
||||
if len > formEnd - d then
|
||||
break
|
||||
end
|
||||
p = d + len + len % 2
|
||||
end
|
||||
if not comm or not info then
|
||||
return nil, Err.new(Err.CORRUPT, "no COMM chunk", base)
|
||||
end
|
||||
local fi = info :: Info
|
||||
if fi.frames > 0 and not ssnd then
|
||||
return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base)
|
||||
end
|
||||
local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format]
|
||||
local present = if ssnd then ssndLen // frameBytes else 0
|
||||
if present < fi.frames then
|
||||
fi.frames = present
|
||||
fi.truncated = true
|
||||
end
|
||||
fi.dataOffset = ssnd or base
|
||||
return fi, nil
|
||||
end
|
||||
|
||||
-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err
|
||||
function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
return parse(r)
|
||||
end
|
||||
|
||||
function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Aiff.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local a = Types.Audio.new(d.sampleRate, d.channels, d.frames)
|
||||
d:read(d.frames, a.samples)
|
||||
a.tags = d.tags
|
||||
a.meta.source = d.source
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local FORMATS = {
|
||||
s8 = { "s8", 8, "NONE" },
|
||||
s16 = { "s16be", 16, "NONE" },
|
||||
s24 = { "s24be", 24, "NONE" },
|
||||
s32 = { "s32be", 32, "NONE" },
|
||||
f32 = { "f32be", 32, "fl32" },
|
||||
f64 = { "f64be", 64, "fl64" },
|
||||
ulaw = { "ulaw", 16, "ulaw" },
|
||||
alaw = { "alaw", 16, "alaw" },
|
||||
}
|
||||
local LE = { s16be = "s16le" }
|
||||
local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" }
|
||||
|
||||
function Aiff.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 = FORMATS[o.sampleFormat or "s16"]
|
||||
if not spec then
|
||||
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
|
||||
end
|
||||
local fmt, bits, comp = spec[1], spec[2], spec[3]
|
||||
if o.littleEndian then
|
||||
if not LE[fmt] then
|
||||
return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples")
|
||||
end
|
||||
fmt, comp = LE[fmt], "sowt"
|
||||
end
|
||||
if src.channels > 65535 then
|
||||
return nil, Err.new(Err.ARG, "too many channels")
|
||||
end
|
||||
local aifc = o.aifc or comp ~= "NONE"
|
||||
local w = Bytes.writer(65536)
|
||||
w:string("FORM")
|
||||
w:u32be(0) -- patched
|
||||
w:string(if aifc then "AIFC" else "AIFF")
|
||||
if aifc then
|
||||
w:string("FVER")
|
||||
w:u32be(4)
|
||||
w:u32be(AIFC_VERSION)
|
||||
end
|
||||
-- text chunks from the tags
|
||||
for _, pair in TEXT_ORDER do
|
||||
local id, key = pair[1], pair[2]
|
||||
local s = src.tags[key]
|
||||
if type(s) == "string" and #s > 0 then
|
||||
w:string(id)
|
||||
w:u32be(#s)
|
||||
w:string(s)
|
||||
if #s % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
local commAt = w:tell()
|
||||
w:string("COMM")
|
||||
if aifc then
|
||||
local name = COMP_NAMES[comp] or ""
|
||||
local plen = 1 + #name
|
||||
plen += plen % 2
|
||||
w:u32be(22 + plen)
|
||||
else
|
||||
w:u32be(18)
|
||||
end
|
||||
w:u16be(src.channels)
|
||||
w:u32be(0) -- frames, patched
|
||||
w:u16be(bits)
|
||||
writeExt80(w, src.sampleRate)
|
||||
if aifc then
|
||||
w:string(comp)
|
||||
local name = COMP_NAMES[comp] or ""
|
||||
w:u8(#name)
|
||||
w:string(name)
|
||||
if (1 + #name) % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
end
|
||||
local ssndAt = w:tell()
|
||||
w:string("SSND")
|
||||
w:u32be(0) -- patched
|
||||
w:u32be(0) -- offset
|
||||
w:u32be(0) -- block size
|
||||
local frames, perr = Pcm.encode(src, fmt, w)
|
||||
if not frames then
|
||||
return nil, perr
|
||||
end
|
||||
local dataLen = w:tell() - ssndAt - 16
|
||||
if dataLen % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
w:setU32be(ssndAt + 4, dataLen + 8)
|
||||
w:setU32be(commAt + 10, frames)
|
||||
w:setU32be(4, w:tell() - 8)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
||||
local info, err = parse(r)
|
||||
if not info then
|
||||
return nil, err
|
||||
end
|
||||
local maxFrames = opts and opts.maxFrames or 2 ^ 28
|
||||
if info.frames > maxFrames then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames))
|
||||
end
|
||||
local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
|
||||
if not dec then
|
||||
return nil, derr
|
||||
end
|
||||
local d = dec :: any
|
||||
d.source = {
|
||||
format = "aiff",
|
||||
aifc = info.aifc,
|
||||
compression = info.compression,
|
||||
bitDepth = info.bits,
|
||||
sampleFormat = info.format,
|
||||
truncated = info.truncated or nil,
|
||||
}
|
||||
return dec, nil
|
||||
end
|
||||
|
||||
return Aiff
|
||||
@@ -0,0 +1,166 @@
|
||||
--!strict
|
||||
-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description.
|
||||
-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear),
|
||||
-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file);
|
||||
-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit).
|
||||
-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Au = {
|
||||
name = "au",
|
||||
category = "audio",
|
||||
extensions = { "au", "snd" },
|
||||
mime = { "audio/basic", "audio/x-au" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- refuse more sample frames (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local ENCODINGS: { [number]: string } = {
|
||||
[1] = "ulaw",
|
||||
[2] = "s8",
|
||||
[3] = "s16be",
|
||||
[4] = "s24be",
|
||||
[5] = "s32be",
|
||||
[6] = "f32be",
|
||||
[7] = "f64be",
|
||||
[27] = "alaw",
|
||||
}
|
||||
local WRITE = {
|
||||
ulaw = { 1, "ulaw" },
|
||||
s8 = { 2, "s8" },
|
||||
s16 = { 3, "s16be" },
|
||||
s24 = { 4, "s24be" },
|
||||
s32 = { 5, "s32be" },
|
||||
f32 = { 6, "f32be" },
|
||||
f64 = { 7, "f64be" },
|
||||
alaw = { 27, "alaw" },
|
||||
}
|
||||
local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 }
|
||||
|
||||
local function be32(b: buffer, o: number): number
|
||||
return bit32.byteswap(buffer.readu32(b, o))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Au.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == ".snd" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Au.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local a = Types.Audio.new(d.sampleRate, d.channels, d.frames)
|
||||
d:read(d.frames, a.samples)
|
||||
a.tags = d.tags
|
||||
a.meta.source = d.source
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Au.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.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
|
||||
-- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires)
|
||||
local note = if type(src.tags.comment) == "string" then src.tags.comment else ""
|
||||
local alen = #note + 1
|
||||
alen = math.max(8, alen + (8 - alen % 8) % 8)
|
||||
local w = Bytes.writer(65536)
|
||||
w:string(".snd")
|
||||
w:u32be(24 + alen)
|
||||
w:u32be(0xFFFFFFFF) -- patched
|
||||
w:u32be(spec[1])
|
||||
w:u32be(src.sampleRate)
|
||||
w:u32be(src.channels)
|
||||
w:string(note)
|
||||
w:fill(0, alen - #note)
|
||||
local frames, perr = Pcm.encode(src, spec[2], w)
|
||||
if not frames then
|
||||
return nil, perr
|
||||
end
|
||||
w:setU32be(8, w:tell() - 24 - alen)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", base)
|
||||
end
|
||||
local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20)
|
||||
local fmt = ENCODINGS[enc]
|
||||
if not fmt then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12)
|
||||
end
|
||||
if ch < 1 or ch > 65535 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20)
|
||||
end
|
||||
if rate < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16)
|
||||
end
|
||||
if off < 24 or off > limit - base then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4)
|
||||
end
|
||||
local tags: Types.Tags = {}
|
||||
if off > 24 then
|
||||
local s = buffer.readstring(b, base + 24, off - 24)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
if z then
|
||||
s = string.sub(s, 1, z - 1)
|
||||
end
|
||||
if #s > 0 then
|
||||
tags.comment = s
|
||||
end
|
||||
end
|
||||
local avail = limit - base - off
|
||||
local truncated = false
|
||||
if size == 0xFFFFFFFF then
|
||||
size = avail
|
||||
elseif size > avail then
|
||||
size = avail
|
||||
truncated = true
|
||||
end
|
||||
local frameBytes = ch * Pcm.Convert.SIZE[fmt]
|
||||
local frames = size // frameBytes
|
||||
local maxFrames = opts and opts.maxFrames or 2 ^ 28
|
||||
if frames > maxFrames then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames))
|
||||
end
|
||||
local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags)
|
||||
if not dec then
|
||||
return nil, derr
|
||||
end
|
||||
local d = dec :: any
|
||||
d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil }
|
||||
return dec, nil
|
||||
end
|
||||
|
||||
return Au
|
||||
@@ -0,0 +1,278 @@
|
||||
--!strict
|
||||
-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description.
|
||||
-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence),
|
||||
-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit
|
||||
-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played
|
||||
-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version
|
||||
-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM
|
||||
-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Voc = {
|
||||
name = "voc",
|
||||
category = "audio",
|
||||
extensions = { "voc" },
|
||||
mime = { "audio/x-voc" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- refuse more sample frames (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
|
||||
-- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames)
|
||||
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 -- silence: the buffer is already zero
|
||||
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) -- patched
|
||||
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
|
||||
@@ -0,0 +1,308 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to
|
||||
-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the
|
||||
-- classic Sun g711.c algorithm, written from the spec).
|
||||
--
|
||||
-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary).
|
||||
-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling.
|
||||
local Convert = {}
|
||||
|
||||
local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32
|
||||
local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64
|
||||
local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32
|
||||
local floor = math.floor
|
||||
local byteswap = bit32.byteswap
|
||||
|
||||
local SIZE: { [string]: number } = {
|
||||
u8 = 1,
|
||||
s8 = 1,
|
||||
s16le = 2,
|
||||
s16be = 2,
|
||||
s24le = 3,
|
||||
s24be = 3,
|
||||
s32le = 4,
|
||||
s32be = 4,
|
||||
f32le = 4,
|
||||
f32be = 4,
|
||||
f64le = 8,
|
||||
f64be = 8,
|
||||
alaw = 1,
|
||||
ulaw = 1,
|
||||
}
|
||||
Convert.SIZE = SIZE
|
||||
-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion)
|
||||
Convert.BITS = {
|
||||
u8 = 8,
|
||||
s8 = 8,
|
||||
s16le = 16,
|
||||
s16be = 16,
|
||||
s24le = 24,
|
||||
s24be = 24,
|
||||
s32le = 32,
|
||||
s32be = 32,
|
||||
f32le = 32,
|
||||
f32be = 32,
|
||||
f64le = 64,
|
||||
f64be = 64,
|
||||
alaw = 16,
|
||||
ulaw = 16,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ G.711
|
||||
local ALAW = table.create(256, 0) -- code -> linear s16
|
||||
local ULAW = table.create(256, 0)
|
||||
for code = 0, 255 do
|
||||
-- A-law
|
||||
local a = bit32.bxor(code, 0x55)
|
||||
local t = bit32.band(a, 0x0F) * 16
|
||||
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
|
||||
if seg == 0 then
|
||||
t += 8
|
||||
elseif seg == 1 then
|
||||
t += 0x108
|
||||
else
|
||||
t = (t + 0x108) * 2 ^ (seg - 1)
|
||||
end
|
||||
ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t
|
||||
-- mu-law
|
||||
local u = bit32.bxor(code, 0xFF)
|
||||
local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4)
|
||||
ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
|
||||
end
|
||||
|
||||
local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF }
|
||||
local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF }
|
||||
local function segment(v: number, ends: { number }): number
|
||||
for i = 1, 8 do
|
||||
if v <= ends[i] then
|
||||
return i - 1
|
||||
end
|
||||
end
|
||||
return 8
|
||||
end
|
||||
|
||||
-- linear s16 -> A-law code
|
||||
local function alawEncode(pcm: number): number
|
||||
local mask
|
||||
local v = floor(pcm / 8) -- 13-bit magnitude domain
|
||||
if v >= 0 then
|
||||
mask = 0xD5
|
||||
else
|
||||
mask = 0x55
|
||||
v = -v - 1
|
||||
end
|
||||
local seg = segment(v, SEG_AEND)
|
||||
local aval
|
||||
if seg >= 8 then
|
||||
aval = 0x7F
|
||||
else
|
||||
aval = seg * 16
|
||||
if seg < 2 then
|
||||
aval += bit32.band(floor(v / 2), 0x0F)
|
||||
else
|
||||
aval += bit32.band(floor(v / 2 ^ seg), 0x0F)
|
||||
end
|
||||
end
|
||||
return bit32.bxor(aval, mask)
|
||||
end
|
||||
|
||||
-- linear s16 -> mu-law code
|
||||
local function ulawEncode(pcm: number): number
|
||||
local v = floor(pcm / 4) -- 14-bit
|
||||
local mask
|
||||
if v < 0 then
|
||||
v = -v
|
||||
mask = 0x7F
|
||||
else
|
||||
mask = 0xFF
|
||||
end
|
||||
if v > 8159 then
|
||||
v = 8159
|
||||
end
|
||||
v += 0x21
|
||||
local seg = segment(v, SEG_UEND)
|
||||
local uval
|
||||
if seg >= 8 then
|
||||
uval = 0x7F
|
||||
else
|
||||
uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F)
|
||||
end
|
||||
return bit32.bxor(uval, mask)
|
||||
end
|
||||
Convert.alawEncode = alawEncode
|
||||
Convert.ulawEncode = ulawEncode
|
||||
Convert.ALAW = ALAW
|
||||
Convert.ULAW = ULAW
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_]
|
||||
function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean
|
||||
if fmt == "s16le" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768)
|
||||
end
|
||||
elseif fmt == "s16be" then
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 2
|
||||
local v = readu8(src, p) * 256 + readu8(src, p + 1)
|
||||
if v >= 32768 then
|
||||
v -= 65536
|
||||
end
|
||||
writef32(dst, d + i * 4, v / 32768)
|
||||
end
|
||||
elseif fmt == "u8" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128)
|
||||
end
|
||||
elseif fmt == "s8" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readi8(src, so + i) / 128)
|
||||
end
|
||||
elseif fmt == "s24le" then
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 3
|
||||
local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536
|
||||
writef32(dst, d + i * 4, v / 8388608)
|
||||
end
|
||||
elseif fmt == "s24be" then
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 3
|
||||
local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2)
|
||||
writef32(dst, d + i * 4, v / 8388608)
|
||||
end
|
||||
elseif fmt == "s32le" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648)
|
||||
end
|
||||
elseif fmt == "s32be" then
|
||||
for i = 0, count - 1 do
|
||||
local v = byteswap(readu32(src, so + i * 4))
|
||||
if v >= 2147483648 then
|
||||
v -= 4294967296
|
||||
end
|
||||
writef32(dst, d + i * 4, v / 2147483648)
|
||||
end
|
||||
elseif fmt == "f32le" then
|
||||
buffer.copy(dst, d, src, so, count * 4)
|
||||
elseif fmt == "f32be" then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4)))
|
||||
end
|
||||
elseif fmt == "f64le" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readf64(src, so + i * 8))
|
||||
end
|
||||
elseif fmt == "f64be" then
|
||||
local tmp = buffer.create(8)
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 8
|
||||
writeu32(tmp, 0, byteswap(readu32(src, p + 4)))
|
||||
writeu32(tmp, 4, byteswap(readu32(src, p)))
|
||||
writef32(dst, d + i * 4, readf64(tmp, 0))
|
||||
end
|
||||
elseif fmt == "alaw" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768)
|
||||
end
|
||||
elseif fmt == "ulaw" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768)
|
||||
end
|
||||
else
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function q(x: number, s: number): number
|
||||
local v = floor(x * s + 0.5)
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
if v >= s then
|
||||
return s - 1
|
||||
elseif v < -s then
|
||||
return -s
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_]
|
||||
function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean
|
||||
if fmt == "s16le" then
|
||||
for i = 0, count - 1 do
|
||||
writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768))
|
||||
end
|
||||
elseif fmt == "s16be" then
|
||||
for i = 0, count - 1 do
|
||||
local v = q(readf32(src, so + i * 4), 32768) % 65536
|
||||
writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256)
|
||||
end
|
||||
elseif fmt == "u8" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128)
|
||||
end
|
||||
elseif fmt == "s8" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256)
|
||||
end
|
||||
elseif fmt == "s24le" then
|
||||
for i = 0, count - 1 do
|
||||
local v = q(readf32(src, so + i * 4), 8388608) % 16777216
|
||||
local p = d + i * 3
|
||||
writeu8(dst, p, v % 256)
|
||||
writeu8(dst, p + 1, (v // 256) % 256)
|
||||
writeu8(dst, p + 2, v // 65536)
|
||||
end
|
||||
elseif fmt == "s24be" then
|
||||
for i = 0, count - 1 do
|
||||
local v = q(readf32(src, so + i * 4), 8388608) % 16777216
|
||||
local p = d + i * 3
|
||||
writeu8(dst, p, v // 65536)
|
||||
writeu8(dst, p + 1, (v // 256) % 256)
|
||||
writeu8(dst, p + 2, v % 256)
|
||||
end
|
||||
elseif fmt == "s32le" then
|
||||
for i = 0, count - 1 do
|
||||
writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648))
|
||||
end
|
||||
elseif fmt == "s32be" then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296))
|
||||
end
|
||||
elseif fmt == "f32le" then
|
||||
buffer.copy(dst, d, src, so, count * 4)
|
||||
elseif fmt == "f32be" then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4)))
|
||||
end
|
||||
elseif fmt == "f64le" then
|
||||
for i = 0, count - 1 do
|
||||
writef64(dst, d + i * 8, readf32(src, so + i * 4))
|
||||
end
|
||||
elseif fmt == "f64be" then
|
||||
local tmp = buffer.create(8)
|
||||
for i = 0, count - 1 do
|
||||
writef64(tmp, 0, readf32(src, so + i * 4))
|
||||
local p = d + i * 8
|
||||
writeu32(dst, p, byteswap(readu32(tmp, 4)))
|
||||
writeu32(dst, p + 4, byteswap(readu32(tmp, 0)))
|
||||
end
|
||||
elseif fmt == "alaw" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768)))
|
||||
end
|
||||
elseif fmt == "ulaw" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768)))
|
||||
end
|
||||
else
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
return Convert
|
||||
@@ -1,20 +1,28 @@
|
||||
--!strict
|
||||
-- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples.
|
||||
-- An encoder accepts a Types.Audio (fully decoded) or a
|
||||
-- Types.Decoder (streamed); Pcm.source turns either into one pull interface, so encoders stream in blocks without
|
||||
-- caring which they got. Also the float <-> integer sample conversions (the same rounding and clipping everywhere).
|
||||
-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
|
||||
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
|
||||
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
|
||||
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
|
||||
--
|
||||
-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else
|
||||
-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read
|
||||
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
|
||||
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
|
||||
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
|
||||
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
|
||||
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert)
|
||||
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
|
||||
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
|
||||
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
|
||||
--
|
||||
-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw.
|
||||
-- Never throws (a decoder's read that throws is caught and ends the stream).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Convert = require("@formats/codecs/Pcm/Convert")
|
||||
|
||||
local Pcm = {}
|
||||
Pcm.Convert = Convert
|
||||
|
||||
export type Source = {
|
||||
sampleRate: number,
|
||||
@@ -128,6 +136,81 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoders
|
||||
-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming
|
||||
-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf)
|
||||
function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?)
|
||||
local size = Convert.SIZE[fmt]
|
||||
if not size then
|
||||
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
|
||||
end
|
||||
if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then
|
||||
return nil, Err.new(Err.ARG, "bad raw PCM layout")
|
||||
end
|
||||
local pos = 0
|
||||
local frameBytes = channels * size
|
||||
local dec = {
|
||||
sampleRate = sampleRate,
|
||||
channels = channels,
|
||||
frames = frames,
|
||||
duration = frames / sampleRate,
|
||||
bitrate = sampleRate * frameBytes * 8,
|
||||
tags = tags or {},
|
||||
}
|
||||
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
n = math.clamp(math.floor(n), 0, frames - pos)
|
||||
local bytes = n * channels * 4
|
||||
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
|
||||
if n > 0 then
|
||||
Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0)
|
||||
pos += n
|
||||
end
|
||||
return b, n
|
||||
end
|
||||
function dec.seek(_self: any, seconds: number)
|
||||
local f = math.floor(seconds * sampleRate + 0.5)
|
||||
pos = if f ~= f then 0 else math.clamp(f, 0, frames)
|
||||
end
|
||||
function dec.position(_self: any): number
|
||||
return pos / sampleRate
|
||||
end
|
||||
return dec :: any, nil
|
||||
end
|
||||
|
||||
-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples)
|
||||
function Pcm.audioDecoder(a: Types.Audio): Types.Decoder
|
||||
local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any
|
||||
d.bitrate = a.sampleRate * a.channels * 32
|
||||
return d
|
||||
end
|
||||
|
||||
-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples
|
||||
function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?)
|
||||
local size = Convert.SIZE[fmt]
|
||||
if not size then
|
||||
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
|
||||
end
|
||||
local ch = src.channels
|
||||
local total = 0
|
||||
local tmp: buffer? = nil
|
||||
while true do
|
||||
local b, n = src:read(8192, tmp)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = b
|
||||
local at = w:reserve(n * ch * size)
|
||||
Convert.encode(b, 0, n * ch, fmt, w.buf, at)
|
||||
w.pos = at + n * ch * size
|
||||
total += n
|
||||
end
|
||||
if src.err then
|
||||
return nil, src.err
|
||||
end
|
||||
return total, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ conversions
|
||||
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
|
||||
function Pcm.toInt(x: number, bits: number): number
|
||||
local s = 2 ^ (bits - 1)
|
||||
Reference in new issue
Block a user