ws-audio2: TTA: codecs/audio/Tta (written from the TTA1 format description; no libtta / ffmpeg code) + audio/tta

TTA1 format 1, 8/16/24 bits, any channel count, header / seek table / frame CRC-32s, seeking, ID3v2 skipped, APEv2
tags; password-protected files -> UNSUPPORTED. 20 fixtures (ttaenc 3.4.1, the FATE inside.tta sample) bit-exact
against ttaenc -d. Branch-free filter steps (LuaJIT: no register-coalescing aborts, 7 -> 40 MB/s).
WavPack: the unary / gamma counts a byte at a time (LuaJIT traces). APE: the predictor rotations as single
assignments. docs/guide/audio.md: the lossless section (+ tools/fixtures/docs_lossless.py inputs) and the Formats
table.
This commit is contained in:
4DBug committed 2026-10-31 15:08:47 -05:00
1 parent ae8ff9d6bf
commit 085e385674
12 files changed
+857 -20

No files matched your search

+2
View File
@@ -25,6 +25,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` |
| audio | tta | .tta | yes | - | streaming: true, seek: true, lossless: true, depths: 8, 16, 24 | `tests/audio/tta.luau` |
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
@@ -101,6 +102,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part
- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description
- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), - codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup),
- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec - codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec
+35 -1
View File
@@ -189,7 +189,7 @@ Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the f
| Read and write | Read only | | Read and write | Read only |
|---|---| |---|---|
| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC | | wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC, wavpack (.wv + .wvc), ape, tta |
Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as
Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see
@@ -243,6 +243,40 @@ end
Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or
visualisers. visualisers.
### Lossless: WavPack, Monkey's Audio, TTA
WavPack (`.wv`), Monkey's Audio (`.ape`) and TTA (`.tta`) open and load like FLAC. Their tags (APEv2) come out in
`tags` with lower-case keys. Integer streams also have `readInt`, which returns the exact samples as i32. Every
frame of these formats is independent, so `seek` lands on the exact sample.
```luau
local wv = assert(F.audio.open(wvBytes))
assert(wv.bitsPerSample == 16 and wv.lossless and wv.tags.title == "Docs Tone")
local exact, n = wv:readInt(1024) -- i32 samples, as wvunpack writes them
assert(n == 1024 and buffer.readi32(exact, 0) == 0)
local ape = assert(F.audio.load(apeBytes)) -- any level, fast .. insane
assert(ape.meta.source.format == "ape" and ape.tags.artist == "formats-luau")
local tta = assert(F.audio.open(ttaBytes))
tta:seek(0.5)
assert(math.abs(tta:position() - 0.5) < 1e-6)
```
A hybrid WavPack file holds a lossy stream. Its `.wvc` correction file makes it lossless again. Pass the correction
file as `correction`. When you load a file by path, the `.wvc` next to it is found automatically. Without it, the
file decodes lossy.
```luau
local lossy = assert(F.audio.open(hybridWvBytes))
local full = assert(F.audio.open(hybridWvBytes, { correction = hybridWvcBytes }))
assert(lossy.hybrid and not lossy.lossless and full.lossless)
```
<!-- doc:files -->
```luau
local song = assert(F.audio.load("assets/tone_hybrid.wv")) -- reads assets/tone_hybrid.wvc too
assert(song.meta.source.correction == true)
```
## Gotchas ## Gotchas
- `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. - `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono.
+12
View File
@@ -254,6 +254,18 @@ local list: { Entry } = {
return require("@formats/audio/opus") return require("@formats/audio/opus")
end, end,
}, },
{
name = "tta",
category = "audio",
path = "audio/tta",
extensions = { "tta" },
mime = { "audio/x-tta", "audio/tta" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
load = function()
return require("@formats/audio/tta")
end,
},
{ {
name = "voc", name = "voc",
category = "audio", category = "audio",
+123
View File
@@ -0,0 +1,123 @@
--!strict
-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the
-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag).
-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count.
-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding.
--
-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt
-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local ApeTag = require("@formats/codecs/audio/ApeTag")
local TtaCodec = require("@formats/codecs/audio/Tta")
-- ------------------------------------------------------------------------------------------------ contract
local Tta = {
name = "tta",
category = "audio",
extensions = { "tta" },
mime = { "audio/x-tta", "audio/tta" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
-- the size of an ID3v2 tag at the reader's start (0 when none)
local function id3Size(r: Bytes.Reader): number
if r:peek(3) ~= "ID3" then
return 0
end
local sz = 0
for i = 6, 9 do
local v = r:peekU8(i)
if v < 0 then
return 0
end
sz = sz * 128 + bit32.band(v, 127)
end
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
return 10 + sz + (if footer then 10 else 0)
end
function Tta.sniff(r: Bytes.Reader): number
return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Tta.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, d.source, limit)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local buf, base, limit = r.buf, r.base, r.limit
local at = base + id3Size(r)
local tags, tagInfo = ApeTag.find(buf, at, limit)
local stop = if tagInfo then tagInfo.start else limit
local info, err = TtaCodec.info(buf, at, stop)
if not info then
return nil, err
end
if info.channels * info.frameLength > 2 ^ 26 then
return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames")
end
local codec = TtaCodec.decoder(info, stop)
local frames = info.samples
local dec: any = {
sampleRate = info.sampleRate,
channels = info.channels,
frames = frames,
duration = frames / info.sampleRate,
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
tags = tags or {},
bitsPerSample = info.bitsPerSample,
float = false,
source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items },
}
local fl, count = info.frameLength, info.frames
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return if i > count then frames else (i - 1) * fl
end,
decode = function(i: number): (number?, Err.Err?)
return codec:frame(buf, i)
end,
pcm = function(): { number }
return codec.pcm
end,
reset = function() end,
stop = frames,
scale = 1 / 2 ^ (info.bitsPerSample - 1),
ints = true,
})
end
return Tta
+31 -11
View File
@@ -277,7 +277,10 @@ local function values(st: State, q: number, lim: number, n: number, order: { num
value = x1 + rcBits(rc, S, k - 16) * 65536 value = x1 + rcBits(rc, S, k - 16) * 65536
end end
value += ov * 2 ^ k value += ov * 2 ^ k
q, low, range, prev = rc.q, rc.low, rc.range, rc.prev q = rc.q
low = rc.low
range = rc.range
prev = rc.prev
end end
ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32 ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32
ksum[ci] = ks ksum[ci] = ks
@@ -437,7 +440,9 @@ local function predictOne(st: State, v: { number }, n: number)
for t = 1, n do for t = 1, n do
local nA = v[t] local nA = v[t]
local A0 = lastA local A0 = lastA
A3, A2, A1 = A2, A1, A0 - prevA0 A3 = A2
A2 = A1
A1 = A0 - prevA0
prevA0 = A0 prevA0 = A0
local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3
local cur local cur
@@ -487,11 +492,16 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
-- Y -- Y
local nA = Y[t] local nA = Y[t]
local A0 = yLast local A0 = yLast
yA3, yA2, yA1 = yA2, yA1, A0 - yPrev yA3 = yA2
yA2 = yA1
yA1 = A0 - yPrev
yPrev = A0 yPrev = A0
local B0 = lastX - (yBin * 31) // 32 local B0 = lastX - (yBin * 31) // 32
yBin = lastX yBin = lastX
yB4, yB3, yB2, yB1 = yB3, yB2, yB1, B0 - yBprev yB4 = yB3
yB3 = yB2
yB2 = yB1
yB1 = B0 - yBprev
yBprev = B0 yBprev = B0
local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3
local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4
@@ -532,11 +542,16 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
-- X -- X
nA = X[t] nA = X[t]
A0 = xLast A0 = xLast
xA3, xA2, xA1 = xA2, xA1, A0 - xPrev xA3 = xA2
xA2 = xA1
xA1 = A0 - xPrev
xPrev = A0 xPrev = A0
B0 = yv - (xBin * 31) // 32 B0 = yv - (xBin * 31) // 32
xBin = yv xBin = yv
xB4, xB3, xB2, xB1 = xB3, xB2, xB1, B0 - xBprev xB4 = xB3
xB3 = xB2
xB2 = xB1
xB1 = B0 - xBprev
xBprev = B0 xBprev = B0
predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3
predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4
@@ -627,15 +642,19 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num
local mode -- "silence", "pseudo", "stereo", "mono", "multi" local mode -- "silence", "pseudo", "stereo", "mono", "multi"
if C == 1 then if C == 1 then
if band(special, 1) ~= 0 then if band(special, 1) ~= 0 then
mode, order = "silence", {} mode = "silence"
order = {}
else else
mode, order = "mono", { 1 } mode = "mono"
order = { 1 }
end end
elseif C == 2 then elseif C == 2 then
if band(special, 3) == 3 then if band(special, 3) == 3 then
mode, order = "silence", {} mode = "silence"
order = {}
elseif band(special, 4) ~= 0 then elseif band(special, 4) ~= 0 then
mode, order = "pseudo", { 1 } mode = "pseudo"
order = { 1 }
else else
mode, order = "stereo", { 2, 1 } mode, order = "stereo", { 2, 1 }
end end
@@ -696,7 +715,8 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num
local a: number, b2: number = 0, 0 local a: number, b2: number = 0, 0
local pair = paired[c] local pair = paired[c]
if mode == "silence" then if mode == "silence" then
a, b2 = 0, 0 a = 0
b2 = 0
elseif mono then elseif mono then
a = X[t] a = X[t]
b2 = a b2 = a
+259
View File
@@ -0,0 +1,259 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio
-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the
-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked
-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message.
local Crc32 = require("@formats/core/Crc32")
local readu8, readu32 = buffer.readu8, buffer.readu32
local band, rshift = bit32.band, bit32.rshift
local min, max, floor = math.min, math.max, math.floor
local Decode = {}
local TWO31, TWO32 = 2147483648, 4294967296
local INV31 = 1 / TWO31
local PAD = 16
local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k
for i = 0, 39 do
P2[i + 1] = 2 ^ i
end
-- ONES[b + 1]: the trailing 1 bits of the byte b
local ONES: { number } = table.create(256, 0)
for b = 0, 255 do
local n, v = 0, b
while v % 2 == 1 do
n += 1
v //= 2
end
ONES[b + 1] = n
end
-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim)
local function longUnary(S: buffer, pos: number, lim: number): (number?, number)
local unary = 0
while pos <= lim do
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
local ones = ONES[band(w, 255) + 1]
if ones < 8 then
return unary + ones, pos + ones + 1
end
unary += 8
pos += 8
end
return nil, pos
end
export type State = {
channels: number,
bytes: number, -- 1 .. 3
S: buffer, -- the frame's bits (+ PAD zeros)
-- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value
R: { number },
Q: { number },
X: { number },
L: { number },
E: { number },
last: { number },
cur: { number },
}
function Decode.state(channels: number, bytes: number): State
return {
channels = channels,
bytes = bytes,
S = buffer.create(4096),
R = table.create(channels * 4, 0),
Q = table.create(channels * 8, 0),
X = table.create(channels * 8, 0),
L = table.create(channels * 8, 0),
E = table.create(channels, 0),
last = table.create(channels, 0),
cur = table.create(channels, 0),
}
end
-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per
-- channel, into P (interleaved integers)
function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?)
if len < 4 then
return nil, "truncated frame"
end
local dlen = len - 4
if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then
return nil, "checksum: frame CRC mismatch"
end
local S = st.S
if buffer.len(S) < dlen + PAD then
S = buffer.create(dlen + PAD + 4096)
st.S = S
end
buffer.copy(S, 0, buf, o, dlen)
buffer.fill(S, dlen, 0, PAD)
local C, bytes = st.channels, st.bytes
local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size
local fdiv = 2 ^ shift
local round = fdiv // 2
local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk
local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur
for c = 0, C - 1 do
R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384
E[c + 1], last[c + 1] = 0, 0
for i = 1, 8 do
Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0
end
end
local pos = 0 -- bit position
local lim = dlen * 8
local c = 0 -- the channel of the sample at idx
for idx = 1, n * C do
do
if pos > lim then
return nil, "truncated frame"
end
-- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary)
local unary
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
local ones = ONES[band(w, 255) + 1]
if ones < 8 then
unary = ones
pos += ones + 1
else
local u, p2 = longUnary(S, pos, lim)
if not u then
return nil, "truncated frame"
end
unary, pos = u, p2
end
local rb = c * 4
local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4]
local deep = unary > 0
local k
if deep then
k = k1
unary -= 1
else
k = k0
end
local value = unary
if k > 0 then
local bits
if k <= 24 then
bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1)
else
local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF)
local p2 = pos + 16
bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536
end
pos += k
value = unary * P2[k + 1] + bits
end
if deep then
s1 += value - s1 // 16
if k1 > 0 and s1 < P2[k1 + 5] then
k1 -= 1
elseif s1 > P2[k1 + 6] then
k1 += 1
end
value += P2[k0 + 1]
end
s0 += value - s0 // 16
if k0 > 0 and s0 < P2[k0 + 5] then
k0 -= 1
elseif s0 > P2[k0 + 6] then
k0 += 1
end
R[rb + 1] = math.min(k0, 31)
R[rb + 2] = math.min(k1, 31)
R[rb + 3] = s0
R[rb + 4] = s1
local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free)
value = (value + odd) // 2 * (2 * odd - 1)
-- the adaptive filter: the weights step toward the sign of the last residual
local fb = c * 8
local err = E[c + 1]
-- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments)
local dq = max(-1, min(1, err))
local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4]
local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8]
local q1 = Q[fb + 1] + x1 * dq
local q2 = Q[fb + 2] + x2 * dq
local q3 = Q[fb + 3] + x3 * dq
local q4 = Q[fb + 4] + x4 * dq
local q5 = Q[fb + 5] + x5 * dq
local q6 = Q[fb + 6] + x6 * dq
local q7 = Q[fb + 7] + x7 * dq
local q8 = Q[fb + 8] + x8 * dq
Q[fb + 1] = q1
Q[fb + 2] = q2
Q[fb + 3] = q3
Q[fb + 4] = q4
Q[fb + 5] = q5
Q[fb + 6] = q6
Q[fb + 7] = q7
Q[fb + 8] = q8
local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5]
local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8]
local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8
if sum >= TWO31 or sum < -TWO31 then
sum = (sum + TWO31) % TWO32 - TWO31
end
-- the steps follow the delay line's signs (x 1, 2, 2, 4)
X[fb + 1] = x2
X[fb + 2] = x3
X[fb + 3] = x4
X[fb + 4] = x5
X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free)
X[fb + 6] = 2 + 4 * floor(l6 * INV31)
X[fb + 7] = 2 + 4 * floor(l7 * INV31)
X[fb + 8] = 4 + 8 * floor(l8 * INV31)
E[c + 1] = value
value += sum // fdiv
-- the delay line: the last value and its first and second differences
local n7 = value - l8
local n6 = n7 - l7
L[fb + 1] = l2
L[fb + 2] = l3
L[fb + 3] = l4
L[fb + 4] = l5
L[fb + 5] = n6 - l6
L[fb + 6] = n6
L[fb + 7] = n7
L[fb + 8] = value
-- the fixed predictor
value += (last[c + 1] * (pk - 1)) // pk
last[c + 1] = value
cur[c + 1] = value
end
c += 1
if c == C then
-- inter-channel decorrelation: the last channel carries half the previous one, the others are differences
c = 0
local o = idx - C
if C == 1 then
P[idx] = cur[1]
elseif C == 2 then
local a = cur[1]
local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2))
P[o + 1], P[o + 2] = b - a, b
else
local a = cur[C - 1]
cur[C] += if a >= 0 then a // 2 else -((-a) // 2)
for r = C - 1, 1, -1 do
cur[r] = cur[r + 1] - cur[r]
end
for k = 1, C do
P[o + k] = cur[k]
end
end
end
end
if pos > lim then
return nil, "truncated frame"
end
return n, nil
end
return Decode
+126
View File
@@ -0,0 +1,126 @@
--!strict
-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description
-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds);
-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain
-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2
-- (password-protected: UNSUPPORTED), TTA2.
--
-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table
-- local dec = Tta.decoder(info)
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers)
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Decode = require("@formats/codecs/audio/Tta/Decode")
local Tta = {}
export type Info = {
format: number,
channels: number,
bitsPerSample: number,
sampleRate: number,
samples: number, -- per channel
frameLength: number, -- samples per frame (256 * rate / 245)
frames: number,
offsets: { number }, -- each frame's byte offset
sizes: { number },
}
-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at`
function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?)
if at + 22 > limit then
return nil, Err.new(Err.TRUNCATED, "truncated header")
end
if buffer.readstring(buf, at, 4) ~= "TTA1" then
return nil, Err.new(Err.CORRUPT, "no TTA1 header")
end
if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then
return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at)
end
local format = buffer.readu16(buf, at + 4)
local info: Info = {
format = format,
channels = buffer.readu16(buf, at + 6),
bitsPerSample = buffer.readu16(buf, at + 8),
sampleRate = buffer.readu32(buf, at + 10),
samples = buffer.readu32(buf, at + 14),
frameLength = 0,
frames = 0,
offsets = {},
sizes = {},
}
if format == 2 then
return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA")
elseif format ~= 1 then
return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format)
end
local bits = info.bitsPerSample
if bits ~= 8 and bits ~= 16 and bits ~= 24 then
return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA")
end
if info.channels < 1 or info.sampleRate < 1 then
return nil, Err.new(Err.CORRUPT, "bad header")
end
info.frameLength = (256 * info.sampleRate) // 245
if info.frameLength < 1 then
return nil, Err.new(Err.CORRUPT, "bad sample rate")
end
local frames = (info.samples + info.frameLength - 1) // info.frameLength
info.frames = frames
local st = at + 22
if st + frames * 4 + 4 > limit then
return nil, Err.new(Err.TRUNCATED, "truncated seek table")
end
if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then
return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st)
end
local o = st + frames * 4 + 4
for i = 1, frames do
local size = buffer.readu32(buf, st + (i - 1) * 4)
info.offsets[i] = o
info.sizes[i] = size
o += size
end
return info, nil
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
info: Info,
pcm: { number },
limit: number,
frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?),
state: Decode.State,
}
local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
local info = self.info
if i < 1 or i > info.frames then
return nil, Err.new(Err.ARG, "no frame " .. i)
end
local o, size = info.offsets[i], info.sizes[i]
if o + size > self.limit then
return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o)
end
local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength
local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm)
if not got then
return nil, Err.from(msg, o)
end
return got, nil
end
-- decoder(info, limit) -> Decoder (limit: the end of the file data)
function Tta.decoder(info: Info, limit: number): Decoder
return {
info = info,
pcm = table.create(info.frameLength * info.channels, 0),
limit = limit,
frame = frame,
state = Decode.state(info.channels, info.bitsPerSample // 8),
}
end
return Tta
+30 -8
View File
@@ -170,12 +170,37 @@ local function bit(R: Reader): number
return bits(R, 1) return bits(R, 1)
end end
-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0
-- after them when fewer than max
local function trailing(R: Reader, max: number): number
local c = 0
while c < max do
local p = R.p
local byte = rshift(p, 3)
if byte + 8 > R.n then
R.p = R.e + 1
return max
end
local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1]
if ones < 8 then
if c + ones >= max then
R.p = p + (max - c)
return max
end
R.p = p + ones + 1
return c + ones
end
c += 8
R.p = p + 8
end
-- (max reached inside a run of 8: give back the extra ones)
R.p -= c - max
return max
end
-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) -- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones)
local function gamma(R: Reader): number? local function gamma(R: Reader): number?
local c = 0 local c = trailing(R, 33)
while c < 33 and bits(R, 1) == 1 do
c += 1
end
if c == 33 then if c == 33 then
return nil return nil
end end
@@ -201,10 +226,7 @@ end
-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) -- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker)
local function onesCount(R: Reader): number? local function onesCount(R: Reader): number?
local c = 0 local c = trailing(R, 17)
while c < 17 and bits(R, 1) == 1 do
c += 1
end
if c == 17 then if c == 17 then
return nil return nil
end end
+100
View File
@@ -0,0 +1,100 @@
-- audio/tta tests: every fixture from tools/fixtures/tta.py (ttaenc 3.4.1: 8 / 16 / 24 bits, 1 - 6 channels, odd
-- rates and lengths, several frames, silence, noise; the FATE sample inside.tta cut mid-file) decoded bit-exact
-- against `ttaenc -d`; seeking; f32 scaling and output reuse; decode() from a sub-range Reader; an ID3v2 tag in front
-- and an APEv2 tag at the end; password-protected files (UNSUPPORTED); header / seek table / frame CRCs; sniff; the
-- api; the fuzz pass. Fixtures: tools/fixtures/tta.py.
local T = require("@tests/T")
local Tta = require("@formats/audio/tta")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local F = require("@formats")
local Cases = require("@tests/gen/tta_cases")
local L = require("@tests/audio/_lossless")
local t = T.suite("tta")
local byName = {}
for _, c in Cases do
byName[c.name] = c
end
local function open(b: any, opts: any?): (any, any)
return L.open(Tta, b, opts)
end
t:eq(Tta.name, "tta", "name")
t:check(Tta.caps.decode and not Tta.caps.encode, "caps")
local seekChecks = L.cases(t, Tta, Cases)
t:note("%d fixtures bit-exact against ttaenc -d, %d seeks", #Cases, seekChecks)
for _, name in { "s16", "s24", "ch6", "u8" } do
L.subrange(t, Tta, byName[name], "tta")
end
local function u32(v: number): string
return string.char(v % 256, (v // 256) % 256, (v // 65536) % 256, (v // 16777216) % 256)
end
-- an ID3v2 tag in front, an APEv2 tag at the end
do
local fx = byName.s16
local id3 = "ID3\4\0\0\0\0\0\20" .. "TIT2\0\0\0\10\0\0\3hello id3"
local item = u32(5) .. u32(0) .. "Title\0" .. "Hello"
local tail = item .. "APETAGEX" .. u32(2000) .. u32(#item + 32) .. u32(1) .. u32(0) .. string.rep("\0", 8)
local b = buffer.fromstring(id3 .. fx.data .. tail)
t:eq(Tta.sniff(Bytes.reader(b)), 1, "sniff ID3 + TTA1")
local dec = open(b)
t:check(dec and (L.all(dec, fx)) == fx.crc, "ID3v2 + APEv2 around the file")
t:eq(dec.tags.title, "Hello", "APEv2 title")
end
-- errors: password protection, CRCs
do
local fx = byName.s16
local b = buffer.fromstring(fx.data)
buffer.writeu16(b, 4, 2)
buffer.writeu32(b, 18, Crc32.of(b, 0, 18))
local _, e1 = open(b)
t:check(e1 and e1.code == Err.UNSUPPORTED, "password-protected: " .. tostring(e1))
local h = buffer.fromstring(fx.data)
buffer.writeu8(h, 10, 0x45)
local _, e2 = open(h)
t:check(e2 and e2.code == Err.CHECKSUM, "header CRC: " .. tostring(e2))
local long = byName.s16_long
local d = buffer.fromstring(long.data)
local at = #long.data - 3000
buffer.writeu8(d, at, bit32.bxor(buffer.readu8(d, at), 1))
local dec = open(d)
local _, got = dec:read(long.frames)
t:check(dec.error and dec.error.code == Err.CHECKSUM and got == 2 * 46080, "frame CRC: " .. tostring(dec.error))
local _, e3 = open("TTA1")
t:check(e3 and Err.is(e3), "too short: " .. tostring(e3))
t:eq(Tta.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF")
end
-- the api
do
local fx = byName.s16
t:eq(F.detect(buffer.fromstring(fx.data)), "tta", "detect")
local a = F.audio.load(fx.data)
t:check(a and a.frames == fx.frames and a.meta.source.format == "tta", "F.audio.load")
end
-- the fuzz pass (the frame CRC rejects most mutations; the second set skips it to reach the decoder)
local samples = {}
for _, name in { "s16", "mono", "s24", "u8", "ch6" } do
table.insert(samples, buffer.fromstring(byName[name].data))
end
t:fuzz("decode", function(b: buffer)
return Tta.decode(Bytes.reader(b))
end, samples, { mutations = 150 })
local Decode = require("@formats/codecs/audio/Tta/Decode")
t:fuzz("frames without CRC", function(b: buffer)
local n = buffer.len(b)
local c = buffer.create(n + 4)
buffer.copy(c, 0, b)
buffer.writeu32(c, n, Crc32.of(b))
local st = Decode.state(2, 2)
return Decode.frame(st, c, 0, n + 4, 2000, table.create(4000, 0))
end, { buffer.fromstring(string.sub(byName.s16.data, 22 + 4 + 4 + 1, 22 + 4 + 4 + 3000)) }, { mutations = 300 })
t:done()
+6
View File
@@ -1100,4 +1100,10 @@ do
lossless("ape " .. c.name, ApeF, c.data) lossless("ape " .. c.name, ApeF, c.data)
end end
end end
local TtaF = require("@formats/audio/tta")
for _, c in require("@tests/gen/tta_cases") do
if c.name == "s16_long" or c.name == "s24" or c.name == "ch6" then
lossless("tta " .. c.name, TtaF, c.data)
end
end
end end
+40
View File
@@ -0,0 +1,40 @@
# Docs inputs for the guide's lossless audio section (tools/fixtures.py; tools/docs_check.py reads them): the docs
# stereo tone (tools/fixtures/docs_inputs.py) encoded by the reference encoders, with tags: WavPack lossless, WavPack
# hybrid (.wv + its .wvc correction file), Monkey's Audio (-c2000) and TTA.
# tests/gen/docs_lossless.luau { files = { [name] = bytes }, vars = { wvBytes = "tone.wv", ... } }
# tests/gen/docs_files/assets/<name> the same files, for the snippets that load by path
import importlib.util, os, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/docs_inputs.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_lossless_" + name.replace("/", "_"),
os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check")
di = load(ctx, "fixtures/docs_inputs")
files = {}
with tempfile.TemporaryDirectory() as d:
wav = os.path.join(d, "tone.wav")
with open(wav, "wb") as f:
f.write(di.tone(44100, 1.0))
tags = ["-w", "Title=Docs Tone", "-w", "Artist=formats-luau"]
ctx.nix("wavpack", ["wavpack", "-q", "-y", "-h"] + tags + [wav, "-o", os.path.join(d, "tone.wv")])
ctx.nix("wavpack", ["wavpack", "-q", "-y", "-b3", "-c"] + tags + [wav, "-o", os.path.join(d, "tone_hybrid.wv")])
ctx.nix("monkeys-audio", ["mac", wav, os.path.join(d, "tone.ape"), "-c2000", "-t", "Title=Docs Tone|Artist=formats-luau"])
ctx.nix("ttaenc", ["ttaenc", "-e", wav, "-o", os.path.join(d, "tone.tta")])
for name in ("tone.wv", "tone_hybrid.wv", "tone_hybrid.wvc", "tone.ape", "tone.tta"):
files[name] = open(os.path.join(d, name), "rb").read()
dc.emit_inputs(ctx, files, {
"wvBytes": "tone.wv",
"hybridWvBytes": "tone_hybrid.wv",
"hybridWvcBytes": "tone_hybrid.wvc",
"apeBytes": "tone.ape",
"ttaBytes": "tone.tta",
})
+93
View File
@@ -0,0 +1,93 @@
# TTA fixtures (tools/fixtures.py): audio/tta, codecs/audio/Tta.
# tests/gen/tta_cases.luau synthetic signals encoded by the reference encoder (ttaenc 3.4.1: 8 / 16 / 24 bits,
# 1 / 2 / 3 / 6 channels, odd rates, short and odd lengths, several frames, silence, noise,
# full scale) and the ffmpeg FATE sample inside.tta (downloaded at fixture time, cut after 2
# frames, not committed); each with the CRC-32 of `ttaenc -d`'s samples (i32 LE)
import importlib.util, os, struct, tempfile, urllib.request, zlib
_dir = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location("_wv", os.path.join(_dir, "wavpack.py"))
WV = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(WV)
_spec = importlib.util.spec_from_file_location("_ape", os.path.join(_dir, "ape.py"))
APE = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(APE)
CTX = None
TMP = None
CASES = []
FATE = "https://fate-suite.ffmpeg.org/lossless-audio/"
def emit(name, tta, note, partial=False, keep=None):
out = tta + ".out.wav"
try:
CTX.nix("ttaenc", ["ttaenc", "-d", tta, "-o", out])
except Exception:
if not partial:
raise
rate, ch, bits, fl, s = APE.wav_samples(out)
if keep is not None: # a cut file: ttaenc also writes the broken frame; keep the whole ones
s = s[:keep * ch]
CASES.append({"name": name, "note": note, "data": open(tta, "rb").read(), "rate": rate, "channels": ch,
"bits": bits, "float": False, "frames": len(s) // ch,
"crc": zlib.crc32(b"".join(struct.pack("<i", v) for v in s)), "partial": partial})
def plain_wav(path, vals, ch, rate, bits):
"""a plain PCM WAV (ttaenc reads WAVE_FORMAT_PCM)"""
w = bits // 8
top = (1 << (bits - 1)) - 1
data = bytearray()
for v in vals:
x = max(-top - 1, min(top, int(round(v * top))))
data += bytes([(x + 128) & 255]) if w == 1 else x.to_bytes(w, "little", signed=True)
fmt = struct.pack("<HHIIHH", 1, ch, rate, rate * ch * w, ch * w, bits)
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data)
open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body)
def case(name, secs=0.3, rate=44100, ch=2, bits=16, kind="music", seed=1, frames=None, note=None):
wav = os.path.join(TMP, name + ".wav")
tta = os.path.join(TMP, name + ".tta")
plain_wav(wav, WV.signal(secs, rate, ch, kind, seed, frames), ch, rate, bits)
CTX.nix("ttaenc", ["ttaenc", "-e", wav, "-o", tta])
emit(name, tta, note or "ttaenc -e, %d-bit, %d ch, %d Hz" % (bits, ch, rate))
def generate(ctx):
global CTX, TMP
CTX = ctx
APE.CTX = ctx
TMP = tempfile.mkdtemp()
CASES.clear()
case("s16")
case("s16_long", secs=3.0, seed=2, note="3 s, 3 frames (bench + seek)")
case("mono", ch=1)
case("u8", bits=8, ch=1, rate=8000, kind="mixed")
case("u8_stereo", bits=8, rate=11025)
case("s24", bits=24, rate=48000, secs=0.3)
case("s24_mixed", bits=24, rate=96000, secs=0.2, kind="mixed")
case("s24_mono", bits=24, ch=1, rate=48000)
case("ch3", ch=3, secs=0.2)
case("ch6", ch=6, rate=48000, secs=0.2)
case("noise", kind="noise", secs=0.2)
case("noise24", bits=24, kind="noise", secs=0.1)
case("silence", kind="silence")
case("mixed", kind="mixed", secs=0.4)
case("one_frame", frames=1)
case("seven_frames", frames=7, ch=1)
case("odd_len", frames=100001, rate=48000, seed=7, note="100001 frames: 3 TTA frames, a short last one")
case("rate37000", rate=37000, secs=0.2)
case("rate8000", rate=8000, secs=1.5, ch=1, note="8 kHz: 8359-sample frames")
path = os.path.join(TMP, "inside.tta")
try:
with urllib.request.urlopen(FATE + "inside.tta", timeout=60) as r:
data = r.read()
frames = (struct.unpack_from("<I", data, 18)[0] + 46079) // 46080
sizes = struct.unpack_from("<%dI" % frames, data, 22)
open(path, "wb").write(data[:22 + frames * 4 + 4 + sizes[0] + sizes[1] + 100])
emit("fate_inside", path, "ffmpeg FATE sample inside.tta (cut after 2 frames)", partial=True, keep=2 * 46080)
except OSError as e: # offline: skip the FATE sample
print("tta: skipping inside.tta (%s)" % e)
ctx.emit("tta_cases", CASES)