ws-h264: merge ws/video; codecs/Video registers h264 (avc1/avc3/H264/... FourCCs, V_MPEG4/ISO/AVC) via H264.newVideoDecoder; video/h264 raw Annex B format (demux by access unit, copy-writer from MP4/MKV samples); MMCO 5 resets frame_num (JVT MR2/MR4/MR5); meta.yuv from the VUI

This commit is contained in:
4DBug committed 2026-10-31 10:29:56 -05:00
commit d4486dccce
211 files changed
+43039 -552

No files matched your search

+903
View File
@@ -0,0 +1,903 @@
--!strict
--!native
--!optimize 2
-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity
-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo,
-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four
-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message.
local Mdct = require("@formats/codecs/Mdct")
local Tables = require("@formats/codecs/Aac/Tables")
local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band
local floor, sqrt, abs = math.floor, math.sqrt, math.abs
local Decode = {}
local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3
local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15
-- ------------------------------------------------------------------------------------------------ bit reader
-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields)
local B: buffer = buffer.create(16)
local BP = 0 -- bit position
local BL = 0 -- bit limit
local OVER = false
local function getBits(n: number): number -- 1 .. 25
local p = BP
BP = p + n
if p > BL then
OVER = true
return 0
end
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
end
local function peekBits(n: number): number
local p = BP
if p > BL then
return 0
end
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
end
local function getLong(n: number): number
if n > 24 then
local hi = getBits(n - 16)
return hi * 65536 + getBits(16)
end
return getBits(n)
end
-- ------------------------------------------------------------------------------------------------ Huffman
local PEEK = 10
type Book = { tab: { number }, map: { [number]: number }, maxLen: number }
local function book(codes: { number }, bits: { number }): Book
local tab = table.create(2 ^ PEEK, 0)
local map = {}
local maxLen = 0
for s = 1, #codes do
local c, l = codes[s], bits[s]
maxLen = math.max(maxLen, l)
if l <= PEEK then
local shift = 2 ^ (PEEK - l)
for k = 0, shift - 1 do
tab[c * shift + k + 1] = (s - 1) * 32 + l
end
else
map[l * 2 ^ 20 + c] = s - 1
end
end
return { tab = tab, map = map, maxLen = maxLen }
end
local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS)
local SPEC_BOOK: { Book } = {}
for i = 1, 11 do
SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i])
end
-- the next symbol of a book, -1 for an invalid code
local function huff(bk: Book): number
local e = bk.tab[peekBits(PEEK) + 1]
if e > 0 then
BP += band(e, 31)
return rshift(e, 5)
end
-- a code longer than PEEK bits
local code = getBits(PEEK)
local map = bk.map
for l = PEEK + 1, bk.maxLen do
code = code * 2 + getBits(1)
local s = map[l * 1048576 + code]
if s then
return s
end
end
return -1
end
-- per codebook: dimension, unsigned, modulus, offset
local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 }
local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true }
local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 }
local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 }
-- |q|^(4/3)
local POW43 = table.create(8192, 0)
for i = 0, 8191 do
POW43[i + 1] = i ^ (4 / 3)
end
-- ------------------------------------------------------------------------------------------------ windows
local SINE_LONG = Mdct.window("sine", 2048) :: { number }
local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number }
local SINE_SHORT = Mdct.window("sine", 256) :: { number }
local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number }
local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan
local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan
-- ------------------------------------------------------------------------------------------------ state
export type Channel = {
spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows)
overlap: { number }, -- 1024 samples carried to the next frame
prevShape: number,
-- this frame's ics
windowSequence: number,
windowShape: number,
maxSfb: number,
numGroups: number,
groupLen: { number },
bandType: { number }, -- [g * maxSfb + sfb + 1]
sf: { number },
-- tns
tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter
}
export type State = {
sfIndex: number,
channels: number, -- configured channels (0: as found)
frameLength: number,
ch: { Channel },
pcm: { number }, -- interleaved output floats
random: number, -- PNS generator state
time: { number }, -- 2048 IMDCT scratch
frame: { number }, -- 2048 windowed frame scratch
short: { number }, -- 256 scratch
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
extensions: number, -- extension payloads seen (SBR / PS / ...)
sbr: boolean, -- an SBR payload was seen
map: { number }?, -- element channel order -> output channel (1-based)
}
local function newChannel(): Channel
return {
spec = table.create(1024, 0),
overlap = table.create(1024, 0),
prevShape = 0,
windowSequence = 0,
windowShape = 0,
maxSfb = 0,
numGroups = 1,
groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 },
bandType = table.create(8 * 64, 0),
sf = table.create(8 * 64, 0),
tnsFilters = {},
}
end
Decode.newChannel = newChannel
-- ------------------------------------------------------------------------------------------------ ics
local function icsInfo(st: State, c: Channel): string?
if getBits(1) ~= 0 then
return "reserved ics bit set"
end
c.windowSequence = getBits(2)
c.windowShape = getBits(1)
if c.windowSequence == EIGHT_SHORT then
c.maxSfb = getBits(4)
local grouping = getBits(7)
local ng = 1
local gl = c.groupLen
gl[1] = 1
for w = 1, 7 do
if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then
gl[ng] += 1
else
ng += 1
gl[ng] = 1
end
end
c.numGroups = ng
if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then
return "max_sfb over the short band count"
end
else
c.maxSfb = getBits(6)
c.numGroups = 1
c.groupLen[1] = 1
if getBits(1) ~= 0 then
return "prediction (AAC Main / LTP) is not supported"
end
if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then
return "max_sfb over the long band count"
end
end
return nil
end
local function sectionData(c: Channel): string?
local long = c.windowSequence ~= EIGHT_SHORT
local bits = if long then 5 else 3
local esc = 2 ^ bits - 1
local maxSfb = c.maxSfb
local bt = c.bandType
for g = 0, c.numGroups - 1 do
local k = 0
while k < maxSfb do
local cb = getBits(4)
if cb == 12 then
return "reserved codebook 12"
end
local len = 0
while true do
local inc = getBits(bits)
len += inc
if inc ~= esc then
break
end
if OVER then
return "section data runs past the end"
end
end
if k + len > maxSfb then
return "section runs past max_sfb"
end
for s = k, k + len - 1 do
bt[g * maxSfb + s + 1] = cb
end
k += len
if OVER then
return "section data runs past the end"
end
end
end
return nil
end
local function scaleFactors(c: Channel, globalGain: number): string?
local sfv = globalGain
local noise = globalGain - 90
local is = 0
local firstNoise = true
local maxSfb = c.maxSfb
local bt, sf = c.bandType, c.sf
for g = 0, c.numGroups - 1 do
for s = 0, maxSfb - 1 do
local i = g * maxSfb + s + 1
local cb = bt[i]
if cb == ZERO_HCB then
sf[i] = 0
elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
is += d - 60
sf[i] = math.clamp(is, -155, 100)
elseif cb == NOISE_HCB then
if firstNoise then
noise += getBits(9) - 256
firstNoise = false
else
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
noise += d - 60
end
sf[i] = math.clamp(noise, -100, 155)
else
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
sfv += d - 60
if sfv < 0 or sfv > 255 then
return "scalefactor out of range"
end
sf[i] = sfv
end
end
end
return nil
end
local function tnsData(st: State, c: Channel): string?
local short = c.windowSequence == EIGHT_SHORT
local nw = if short then 8 else 1
local filters = {}
for w = 1, nw do
local list = {}
local nFilt = getBits(if short then 1 else 2)
if nFilt > 0 then
local coefRes = getBits(1)
for _ = 1, nFilt do
local length = getBits(if short then 4 else 6)
local order = getBits(if short then 3 else 5)
local f = { length, order, 0 }
if order > (if short then 7 else 12) then
return "TNS order too high"
end
if order > 0 then
f[3] = getBits(1)
local compress = getBits(1)
local resBits = coefRes + 3
local nb = resBits - compress
local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2)
local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2)
local tmp = table.create(order, 0)
for k = 1, order do
local v = getBits(nb)
if v >= 2 ^ (nb - 1) then
v -= 2 ^ nb
end
tmp[k] = math.sin(v / (if v >= 0 then iq else iqm))
end
-- parcor -> LPC
local a = table.create(order + 1, 0)
local b = table.create(order + 1, 0)
a[1] = 1
for m = 1, order do
for i = 1, m - 1 do
b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1]
end
for i = 1, m - 1 do
a[i + 1] = b[i + 1]
end
a[m + 1] = tmp[m]
end
for k = 1, order do
f[3 + k] = a[k + 1]
end
end
table.insert(list, f)
end
end
filters[w] = list
end
c.tnsFilters = filters
local _ = st
return nil
end
local function applyTns(st: State, c: Channel)
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1]
local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1]
local mmm = math.min(maxBands, c.maxSfb)
if mmm == 0 then
return
end
local spec = c.spec
for w, list in c.tnsFilters do
local bottom = numSwb
for _, f in list do
local top = bottom
bottom = math.max(0, top - f[1])
local order = f[2]
if order > 0 then
local start = swb[math.min(bottom, mmm) + 1]
local stop = swb[math.min(top, mmm) + 1]
local size = stop - start
if size > 0 then
local inc = 1
local p = (w - 1) * 128 + start + 1
if f[3] == 1 then
inc = -1
p = (w - 1) * 128 + stop
end
for m = 0, size - 1 do
local y = spec[p]
local lim = if m < order then m else order
for i = 1, lim do
y -= spec[p - i * inc] * f[3 + i]
end
spec[p] = y
p += inc
end
end
end
end
end
end
-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros)
local function spectralData(st: State, c: Channel, pulses: { number }?): string?
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local spec = c.spec
for i = 1, 1024 do
spec[i] = 0
end
local maxSfb = c.maxSfb
local bt, sf = c.bandType, c.sf
local win = 0
for g = 0, c.numGroups - 1 do
local glen = c.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
local cb = bt[idx]
local lo, hi = swb[s + 1], swb[s + 2]
local width = hi - lo
if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
-- zeros (intensity bands are filled from the other channel later)
continue
elseif cb == NOISE_HCB then
local scale = 2 ^ (0.25 * sf[idx])
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
local energy = 0
local r = st.random
for k = 1, width do
r = (r * 1664525 + 1013904223) % 4294967296
local v = if r >= 2147483648 then r - 4294967296 else r
spec[base + k] = v
energy += v * v
end
st.random = r
local m = if energy > 0 then scale / sqrt(energy) else 0
for k = 1, width do
spec[base + k] *= m
end
end
continue
end
local bk = SPEC_BOOK[cb]
local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb]
local gain = 2 ^ (0.25 * (sf[idx] - 100))
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
local k = 0
while k < width do
local sym = huff(bk)
if sym < 0 then
return "bad spectral code"
end
-- unpack the symbol into dim values (first value most significant)
local vals1, vals2, vals3, vals4
if dim == 4 then
vals4 = sym % mod - off
sym = (sym - (sym % mod)) / mod
vals3 = sym % mod - off
sym = (sym - (sym % mod)) / mod
vals2 = sym % mod - off
sym = (sym - (sym % mod)) / mod
vals1 = sym % mod - off
else
vals2 = sym % mod - off
vals1 = (sym - (sym % mod)) / mod - off
end
if uns then
if vals1 ~= 0 and getBits(1) == 1 then
vals1 = -vals1
end
if vals2 ~= 0 and getBits(1) == 1 then
vals2 = -vals2
end
if dim == 4 then
if vals3 ~= 0 and getBits(1) == 1 then
vals3 = -vals3
end
if vals4 ~= 0 and getBits(1) == 1 then
vals4 = -vals4
end
end
if cb == ESC_HCB then
for e = 1, 2 do
local v = if e == 1 then vals1 else vals2
if v == 16 or v == -16 then
local n = 0
while getBits(1) == 1 do
n += 1
if n > 8 or OVER then
return "bad escape"
end
end
local esc = 2 ^ (n + 4) + getBits(n + 4)
if v < 0 then
esc = -esc
end
if e == 1 then
vals1 = esc
else
vals2 = esc
end
end
end
end
end
local p = base + k + 1
spec[p] = vals1
spec[p + 1] = vals2
if dim == 4 then
spec[p + 2] = vals3
spec[p + 3] = vals4
end
k += dim
end
if OVER then
return "spectral data runs past the end"
end
end
-- dequantise (pulses are added to the quantised values first: long windows only, applied below)
if not pulses then
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
for k = 1, width do
local q = spec[base + k]
if q ~= 0 then
local aq = if q < 0 then -q else q
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
spec[base + k] = if q < 0 then -v else v
end
end
end
end
end
win += glen
end
if pulses then
-- long window: add the pulses to the quantised values, then dequantise every band
for i = 1, #pulses, 2 do
local pos = pulses[i] + 1
if pos <= 1024 then
local q = spec[pos]
spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1]
end
end
for s = 0, maxSfb - 1 do
local idx = s + 1
local cb = bt[idx]
if cb ~= ZERO_HCB and cb < NOISE_HCB then
local gain = 2 ^ (0.25 * (sf[idx] - 100))
for k = swb[s + 1] + 1, swb[s + 2] do
local q = spec[k]
if q ~= 0 then
local aq = if q < 0 then -q else q
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
spec[k] = if q < 0 then -v else v
end
end
end
end
end
return nil
end
-- individual_channel_stream
local function ics(st: State, c: Channel, commonWindow: boolean): string?
local globalGain = getBits(8)
if not commonWindow then
local e = icsInfo(st, c)
if e then
return e
end
end
local e = sectionData(c)
if e then
return e
end
e = scaleFactors(c, globalGain)
if e then
return e
end
local pulses: { number }? = nil
if getBits(1) == 1 then
if c.windowSequence == EIGHT_SHORT then
return "pulse data in a short window"
end
local n = getBits(2) + 1
local startSfb = getBits(6)
if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then
return "bad pulse start band"
end
local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1]
local list = {}
for _ = 1, n do
pos += getBits(5)
table.insert(list, pos)
table.insert(list, getBits(4))
end
pulses = list
end
c.tnsFilters = {}
if getBits(1) == 1 then
e = tnsData(st, c)
if e then
return e
end
end
if getBits(1) == 1 then
return "gain control (AAC SSR) is not supported"
end
if OVER then
return "channel stream runs past the end"
end
return spectralData(st, c, pulses)
end
-- ------------------------------------------------------------------------------------------------ stereo
local function msStereo(st: State, l: Channel, r: Channel, mask: { number })
local short = l.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local maxSfb = l.maxSfb
local a, b = l.spec, r.spec
local win = 0
for g = 0, l.numGroups - 1 do
local glen = l.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then
for w = 0, glen - 1 do
local base = (win + w) * 128
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
local m, sd = a[k], b[k]
a[k], b[k] = m + sd, m - sd
end
end
end
end
win += glen
end
end
local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number)
local short = r.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local maxSfb = r.maxSfb
local a, b = l.spec, r.spec
local win = 0
for g = 0, r.numGroups - 1 do
local glen = r.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
local cb = r.bandType[idx]
if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
local sign = if cb == INTENSITY_HCB then 1 else -1
if msPresent ~= 0 and mask[idx] == 1 then
sign = -sign
end
local scale = sign * 0.5 ^ (0.25 * r.sf[idx])
for w = 0, glen - 1 do
local base = (win + w) * 128
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
b[k] = a[k] * scale
end
end
end
end
win += glen
end
end
-- ------------------------------------------------------------------------------------------------ filterbank
local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number)
local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape
local spec, overlap = c.spec, c.overlap
local frame = st.frame
local scale = 1 / 32768
if seq == EIGHT_SHORT then
for i = 1, 2048 do
frame[i] = 0
end
local tmp = st.short
local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT
local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT
for w = 0, 7 do
Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256)
local rise = if w == 0 then rise0 else wcur
local base = 448 + w * 128
for n = 1, 128 do
frame[base + n] += tmp[n] * rise[n]
frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n]
end
end
else
local t = st.time
Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048)
-- left half
if seq == LONG_STOP then
local rise = if prev == 1 then KBD_SHORT else SINE_SHORT
for n = 1, 448 do
frame[n] = 0
end
for n = 1, 128 do
frame[448 + n] = t[448 + n] * rise[n]
end
for n = 577, 1024 do
frame[n] = t[n]
end
else
local rise = if prev == 1 then KBD_LONG else SINE_LONG
for n = 1, 1024 do
frame[n] = t[n] * rise[n]
end
end
-- right half
if seq == LONG_START then
local fall = if shape == 1 then KBD_SHORT else SINE_SHORT
for n = 1025, 1472 do
frame[n] = t[n]
end
for n = 1, 128 do
frame[1472 + n] = t[1472 + n] * fall[128 + n]
end
for n = 1601, 2048 do
frame[n] = 0
end
else
local fall = if shape == 1 then KBD_LONG else SINE_LONG
for n = 1025, 2048 do
frame[n] = t[n] * fall[n]
end
end
end
local p = offset
for n = 1, 1024 do
out[p] = (frame[n] + overlap[n]) * scale
overlap[n] = frame[1024 + n]
p += stride
end
c.prevShape = shape
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved.
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if buffer.len(B) < len + 16 then
B = buffer.create(len + 256)
end
buffer.copy(B, 0, buf, off, len)
buffer.fill(B, len, 0, 16)
BP, BL, OVER = 0, len * 8, false
local chans = st.ch
local nextCh = 1
local order: { Channel } = {}
local lastElement = -1
while true do
if BP + 3 > BL then
break -- tolerate a missing END
end
local id = getBits(3)
if id == 7 then
break
end
if id == 0 or id == 3 then -- SCE / LFE
getBits(4)
local c = chans[nextCh]
if not c then
c = newChannel()
chans[nextCh] = c
end
local e = ics(st, c, false)
if e then
return nil, e
end
applyTns(st, c)
table.insert(order, c)
nextCh += 1
lastElement = id
elseif id == 1 then -- CPE
getBits(4)
local l, r = chans[nextCh], chans[nextCh + 1]
if not l then
l = newChannel()
chans[nextCh] = l
end
if not r then
r = newChannel()
chans[nextCh + 1] = r
end
local common = getBits(1) == 1
local msPresent = 0
local mask = table.create(8 * 64, 0)
if common then
local e = icsInfo(st, l)
if e then
return nil, e
end
r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups
for i = 1, 8 do
r.groupLen[i] = l.groupLen[i]
end
msPresent = getBits(2)
if msPresent == 1 then
for i = 1, l.numGroups * l.maxSfb do
mask[i] = getBits(1)
end
elseif msPresent == 2 then
for i = 1, l.numGroups * l.maxSfb do
mask[i] = 1
end
elseif msPresent == 3 then
return nil, "reserved ms_mask_present"
end
end
local e = ics(st, l, common)
if e then
return nil, e
end
e = ics(st, r, common)
if e then
return nil, e
end
if common and msPresent ~= 0 then
msStereo(st, l, r, mask)
end
if common then
intensity(st, l, r, mask, msPresent)
end
applyTns(st, l)
applyTns(st, r)
table.insert(order, l)
table.insert(order, r)
nextCh += 2
lastElement = id
elseif id == 2 then
return nil, "coupling channel elements are not supported"
elseif id == 4 then -- DSE
getBits(4)
local align = getBits(1)
local count = getBits(8)
if count == 255 then
count += getBits(8)
end
if align == 1 then
BP = (BP + 7) // 8 * 8
end
BP += count * 8
elseif id == 5 then -- PCE: skipped here (parsed from the configuration)
return nil, "program config element inside the stream is not supported"
elseif id == 6 then -- FIL
local count = getBits(4)
if count == 15 then
count += getBits(8) - 1
end
if count > 0 then
local start = BP
local kind = getBits(4)
if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC
st.sbr = true
end
st.extensions += 1
local hook = st.onExtension
if hook then
hook(kind, lastElement, B, start, count * 8)
end
BP = start + count * 8
end
end
if OVER or BP > BL then
return nil, "frame runs past the end"
end
if nextCh > 9 then
return nil, "more than 8 channels"
end
end
local n = #order
if n == 0 then
return 0, nil
end
local pcm = st.pcm
local map = st.map
for i, c in order do
local o = if map and map[i] then map[i] else i
filterbank(st, c, pcm, n, o)
end
return n, nil
end
function Decode.state(sfIndex: number): State
return {
sfIndex = sfIndex,
channels = 0,
frameLength = 1024,
ch = {},
pcm = table.create(1024 * 8, 0),
random = 0x1f2e3d4c,
time = table.create(2048, 0),
frame = table.create(2048, 0),
short = table.create(256, 0),
onExtension = nil,
extensions = 0,
sbr = false,
map = nil,
}
end
local _ = abs
local _2 = floor
return Decode
+335
View File
@@ -0,0 +1,335 @@
--!strict
-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
-- see licenses/NOTICE.md). Generated; do not edit.
local Tables = {}
Tables.SF_CODES = {
262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279,
524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759,
16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015,
1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27,
57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085,
4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253,
524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256,
524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275,
}
Tables.SF_BITS = {
18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16,
15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3,
1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15,
18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19,
}
Tables.SPEC_CODES = {
{
2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491,
108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23,
111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484,
107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011,
106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503,
2036,
},
{
499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110,
40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10,
39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100,
30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238,
34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109,
502,
},
{
0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493,
487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117,
1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188,
242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241,
1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089,
32762,
},
{
7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240,
112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4,
229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014,
110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233,
109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013,
2044,
},
{
8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006,
2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8,
25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239,
24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086,
2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091,
8190,
},
{
2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240,
486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4,
6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43,
7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016,
484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019,
2044,
},
{
0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501,
54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018,
243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044,
1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095,
},
{
14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248,
15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250,
113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020,
504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023,
},
{
0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53,
114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481,
975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994,
2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071,
8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485,
983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009,
4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059,
8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371,
16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072,
2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063,
8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767,
},
{
34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1,
9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40,
91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221,
460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989,
1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94,
90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215,
219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470,
977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022,
2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034,
974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993,
996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095,
},
{
0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094,
910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973,
2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918,
958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929,
913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444,
927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442,
451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431,
447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420,
440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419,
433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429,
435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434,
439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906,
452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917,
925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446,
448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957,
924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093,
988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413,
450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399,
4,
},
}
Tables.SPEC_BITS = {
{
11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9,
7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9,
11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11,
},
{
9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7,
6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8,
8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9,
},
{
1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10,
6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15,
13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15,
},
{
4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8,
4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10,
11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11,
},
{
13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8,
5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8,
9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13,
},
{
11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6,
4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6,
6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11,
},
{
1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9,
10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10,
11, 11, 12, 12,
},
{
5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7,
8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8,
9, 9, 9, 10,
},
{
1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8,
8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11,
11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13,
13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11,
11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13,
13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
},
{
6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5,
6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8,
8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10,
11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9,
9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10,
10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12,
},
{
4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10,
10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8,
9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7,
8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9,
8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10,
10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10,
10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12,
12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5,
},
}
Tables.SWB_LONG = {
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
960, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
960, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100,
112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704,
744, 784, 824, 864, 904, 944, 984, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
600, 652, 704, 768, 832, 896, 960, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
600, 652, 704, 768, 832, 896, 960, 1024,
},
{
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
832, 896, 960, 1024,
},
{
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
832, 896, 960, 1024,
},
{
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
832, 896, 960, 1024,
},
{
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
1024,
},
{
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
1024,
},
}
Tables.SWB_SHORT = {
{
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
},
{
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
},
{
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
},
{
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
},
}
Tables.NUM_SWB_LONG = {
41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40,
}
Tables.NUM_SWB_SHORT = {
12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15,
}
Tables.TNS_MAX_BANDS_LONG = {
31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39,
}
Tables.TNS_MAX_BANDS_SHORT = {
9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
}
return Tables
+336
View File
@@ -0,0 +1,336 @@
--!strict
-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/Aac/Tables); no third-party code.
-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
--
-- local Aac = require("@formats/codecs/Aac")
-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bits = require("@formats/core/Bits")
local Decode = require("@formats/codecs/Aac/Decode")
local Aac = {}
Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 }
-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7
local CONFIG_MAP: { [number]: { number } } = {
[3] = { 3, 1, 2 },
[4] = { 3, 1, 2, 4 },
[5] = { 3, 1, 2, 4, 5 },
[6] = { 3, 1, 2, 5, 6, 4 },
[7] = { 3, 7, 8, 1, 2, 5, 6, 4 },
}
export type Config = {
objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled)
sfIndex: number,
sampleRate: number, -- the core rate
channelConfig: number,
channels: number,
sbr: boolean, -- SBR signalled (explicitly or backward-compatibly)
ps: boolean,
extensionRate: number?, -- the SBR output rate
frameLength: number,
}
local function rateIndex(rate: number): number
-- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies)
local best, bi = math.huge, 4
for i, r in Aac.RATES do
if math.abs(r - rate) < best then
best, bi = math.abs(r - rate), i - 1
end
end
return bi
end
local function objectType(br: Bits.BitReader): number
local t = br:read(5)
if t == 31 then
t = 32 + br:read(6)
end
return t
end
local function frequency(br: Bits.BitReader): (number, number)
local i = br:read(4)
if i == 15 then
local f = br:read(24)
return rateIndex(f), f
end
return i, Aac.RATES[i + 1] or 0
end
-- pce(br) -> channels (program_config_element)
local function pce(br: Bits.BitReader): number
br:read(4 + 2 + 4)
local front, side, back = br:read(4), br:read(4), br:read(4)
local lfe, assoc, cc = br:read(2), br:read(3), br:read(4)
if br:read(1) == 1 then
br:read(4)
end
if br:read(1) == 1 then
br:read(4)
end
if br:read(1) == 1 then
br:read(3)
end
local channels = 0
for _ = 1, front + side + back do
channels += if br:read(1) == 1 then 2 else 1
br:read(4)
end
channels += lfe
br:skip(lfe * 4 + assoc * 4 + cc * 5)
br:align()
br:skip(br:read(8) * 8)
return channels
end
-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig
function Aac.config(asc: buffer): (Config?, Err.Err?)
if type(asc) ~= "buffer" or buffer.len(asc) < 2 then
return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes")
end
local br = Bits.msbReader(asc)
local aot = objectType(br)
local sfi, rate = frequency(br)
local chcfg = br:read(4)
local sbr, ps = false, false
local extRate: number? = nil
if aot == 5 or aot == 29 then
sbr = true
ps = aot == 29
local _, er = frequency(br)
extRate = er
aot = objectType(br)
if aot == 22 then
br:read(4)
end
end
if aot ~= 2 and aot ~= 1 and aot ~= 4 then
if aot == 0 or br.err then
return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig")
end
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)")
end
if aot ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP")
end
-- GASpecificConfig
local frameLengthFlag = br:read(1)
if br:read(1) == 1 then
br:read(14)
end
local ext = br:read(1)
local channels = CONFIG_CHANNELS[chcfg] or 0
if chcfg == 0 then
channels = pce(br)
elseif chcfg > 7 then
return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg)
end
if ext == 1 then
br:read(1) -- extensionFlag3
end
-- backward-compatible SBR signalling
if not sbr and br:bitsLeft() >= 16 then
if br:read(11) == 0x2b7 then
local et = objectType(br)
if et == 5 and br:read(1) == 1 then
sbr = true
local _, er = frequency(br)
extRate = er
if br:bitsLeft() >= 12 and br:read(11) == 0x548 then
ps = br:read(1) == 1
end
end
end
end
if br.err and channels == 0 then
return nil, br.err
end
if sfi > 12 or rate <= 0 then
return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi)
end
if frameLengthFlag == 1 then
return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames")
end
if channels < 1 or channels > 8 then
return nil, Err.new(Err.UNSUPPORTED, channels .. " channels")
end
return {
objectType = aot,
sfIndex = sfi,
sampleRate = rate,
channelConfig = chcfg,
channels = channels,
sbr = sbr,
ps = ps,
extensionRate = extRate,
frameLength = 1024,
}, nil
end
-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig
function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer
local b = buffer.create(2)
local v = aot * 2048 + sfIndex * 128 + channelConfig * 8
buffer.writeu8(b, 0, bit32.rshift(v, 8))
buffer.writeu8(b, 1, bit32.band(v, 255))
return b
end
export type Adts = {
headerSize: number, -- 7, or 9 with a CRC
frameSize: number, -- the whole frame, header included
objectType: number,
sfIndex: number,
sampleRate: number,
channelConfig: number,
blocks: number, -- raw_data_blocks in the frame (1 .. 4)
protected: boolean,
}
-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset)
function Aac.adts(b: buffer, o: number, limit: number): Adts?
if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then
return nil
end
local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6)
if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0
return nil
end
local protected = bit32.band(b1, 1) == 0
local profile = bit32.rshift(b2, 6)
local sfi = bit32.band(bit32.rshift(b2, 2), 15)
local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6)
local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5)
local blocks = bit32.band(b6, 3) + 1
local hs = if protected then 9 else 7
if sfi > 12 or size < hs then
return nil
end
return {
headerSize = hs,
frameSize = size,
objectType = profile + 1,
sfIndex = sfi,
sampleRate = Aac.RATES[sfi + 1],
channelConfig = ch,
blocks = blocks,
protected = protected,
}
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
config: Config,
channels: number,
sampleRate: number,
frameLength: number,
pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order
sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
reset: (self: Decoder) -> (),
state: Decode.State,
}
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
local o = offset or 0
local n = length or (buffer.len(buf) - o)
if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then
return nil, Err.new(Err.ARG, "packet range out of the buffer")
end
local st = self.state
st.onExtension = self.onExtension
local chans, msg = Decode.frame(st, buf, o, n)
if not chans then
return nil, Err.new(Err.CORRUPT, msg or "bad frame", o)
end
if st.sbr then
self.sbr = true
end
if chans == 0 then
-- an empty frame (only fill elements): silence
for i = 1, 1024 * self.channels do
st.pcm[i] = 0
end
return 1024, nil
end
if chans ~= self.channels then
return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o)
end
return 1024, nil
end
local function reset(self: Decoder)
for _, c in self.state.ch do
for i = 1, 1024 do
c.overlap[i] = 0
end
c.prevShape = 0
end
end
-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err
function Aac.decoder(asc: any): (Decoder?, Err.Err?)
local cfg: Config
if type(asc) == "buffer" then
local c, err = Aac.config(asc)
if not c then
return nil, err
end
cfg = c
elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then
local sfi = asc.sfIndex
if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then
return nil, Err.new(Err.ARG, "bad sampling index / channels")
end
if (asc.objectType or 2) ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)")
end
cfg = {
objectType = 2,
sfIndex = sfi,
sampleRate = Aac.RATES[sfi + 1],
channelConfig = asc.channelConfig or asc.channels,
channels = asc.channels,
sbr = false,
ps = false,
frameLength = 1024,
}
else
return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer")
end
local st = Decode.state(cfg.sfIndex)
st.channels = cfg.channels
if cfg.channelConfig >= 3 then
st.map = CONFIG_MAP[cfg.channelConfig]
end
return {
config = cfg,
channels = cfg.channels,
sampleRate = cfg.sampleRate,
frameLength = 1024,
pcm = st.pcm,
sbr = cfg.sbr,
onExtension = nil,
decode = decode,
reset = reset,
state = st,
}, nil
end
return Aac
+427
View File
@@ -0,0 +1,427 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
local readu32, readu8 = buffer.readu32, buffer.readu8
local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot
local floor = math.floor
local Decode = {}
export type State = {
frameLength: number,
bitDepth: number,
pb: number,
mb: number,
kb: number,
channels: number,
maxRun: number,
scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked)
pred: { { number } }, -- per element channel (0, 1): residuals / predictor output
mix: { { number } },
shift: { number },
out: { number }, -- interleaved output samples (integers), frames * channels
}
local POW = table.create(64, 0)
for i = 0, 63 do
POW[i + 1] = 2 ^ i
end
-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25.
local function bitsAt(b: buffer, pos: number, n: number): number
local w = byteswap(readu32(b, rshift(pos, 3)))
return rshift(lshift(w, band(pos, 7)), 32 - n)
end
local function signExtend(v: number, bits: number): number
local m = POW[bits + 1]
v = v % m
if v >= m / 2 then
v -= m
end
return v
end
-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits
local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number)
local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7))
local pre = countlz(bnot(w))
if pre >= 9 then
pos += 9
local v
if bps > 25 then
v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16)
else
v = bitsAt(b, pos, bps)
end
return v, pos + bps
end
pos += pre + 1
if k == 1 then
return pre, pos
end
local v = bitsAt(b, pos, k)
local x = pre * m
if v > 1 then
return x + v - 1, pos + k
end
return x, pos + k - 1
end
-- residuals: n values into out[1..n]; returns the new bit position or -1
local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number
local history = st.mb
local kb = st.kb
local signMod = 0
local i = 1
while i <= n do
if pos > limit then
return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes
end
local k = 31 - countlz(floor(history / 512) + 3)
if k > kb then
k = kb
end
local x
x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps)
x += signMod
signMod = 0
out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2
if x > 0xFFFF then
history = 0xFFFF
else
history += x * mult - floor(history * mult / 512)
end
if history < 128 and i < n then
if pos > limit then
return -1
end
local lg = if history > 0 then 31 - countlz(history) else 0
k = 7 - lg + floor((history + 16) / 64)
if k > kb then
k = kb
end
local run
run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16)
if run > 0 then
if run > n - i then
return -1
end
for j = i + 1, i + run do
out[j] = 0
end
i += run
end
if run < 0xFFFF then
signMod = 1 -- the next value is not 0 (unless the run hit its maximum)
end
history = 0
end
i += 1
end
return pos
end
-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place
local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
out[1] = err[1]
if n <= 1 then
return
end
if order == 0 then
if out ~= err then
for i = 2, n do
out[i] = err[i]
end
end
return
end
if order == 31 then
for i = 2, n do
out[i] = signExtend(out[i - 1] + err[i], bps)
end
return
end
local i = 2
while i <= order + 1 and i <= n do
out[i] = signExtend(out[i - 1] + err[i], bps)
i += 1
end
local half = if quant > 0 then POW[quant] else 0
local qd = POW[quant + 1]
-- coefs[1] multiplies the most recent sample
while i <= n do
local d = out[i - order - 1]
local val = 0
for j = 1, order do
val += (out[i - j] - d) * coefs[j]
end
val = floor((val + half) / qd)
local e = err[i]
out[i] = signExtend(val + d + e, bps)
if e ~= 0 then
local es = if e > 0 then 1 else -1
-- adapt from the oldest sample to the newest while the error keeps its sign
for j = order, 1, -1 do
if e * es <= 0 then
break
end
local v = d - out[i - j]
local sgn = if v > 0 then es elseif v < 0 then -es else 0
coefs[j] -= sgn
e -= floor(v * sgn / qd) * (order - j + 1)
end
end
i += 1
end
end
-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the
-- ALAC element order.
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if len <= 0 then
return nil, "empty packet"
end
local b = st.scratch
if buffer.len(b) < len + 16 then
b = buffer.create(len + 64)
st.scratch = b
end
buffer.copy(b, 0, buf, off, len)
buffer.fill(b, len, 0, 16)
local limit = len * 8
local pos = 0
local channels = st.channels
local ch = 0 -- next output channel
local frames = -1
local out = st.out
while true do
if pos + 3 > limit then
return nil, "frame runs past the end"
end
local tag = bitsAt(b, pos, 3)
pos += 3
if tag == 7 then -- END
break
elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE
local nch = if tag == 1 then 2 else 1
if ch + nch > channels then
return nil, "more channels than the configuration"
end
pos += 4 -- element instance tag
if bitsAt(b, pos, 12) ~= 0 then
return nil, "bad element header"
end
pos += 12
local h = bitsAt(b, pos, 4)
pos += 4
local partial = rshift(h, 3)
local shiftBytes = band(rshift(h, 1), 3)
local escape = band(h, 1)
if shiftBytes == 3 then
return nil, "bad shift"
end
local n = st.frameLength
if partial == 1 then
n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16)
pos += 32
end
if n < 1 or n > st.frameLength then
return nil, "bad frame length " .. n
end
if frames >= 0 and n ~= frames then
return nil, "elements of different lengths"
end
frames = n
if #out < n * channels then
for k = #out + 1, n * channels do
out[k] = 0
end
end
local shift = shiftBytes * 8
local bps = st.bitDepth - shift + nch - 1
if bps > 32 or bps < 1 then
return nil, "bad sample size"
end
if pos > limit then
return nil, "frame runs past the end"
end
local mixBits, mixRes = 0, 0
local p0, p1 = st.pred[1], st.pred[2]
local m0, m1 = st.mix[1], st.mix[2]
local shiftBuf = st.shift
if escape == 0 then
mixBits = bitsAt(b, pos, 8)
mixRes = bitsAt(b, pos + 8, 8)
pos += 16
if mixRes >= 128 then
mixRes -= 256
end
local mode, denShift, pbFactor, order = {}, {}, {}, {}
local coefs = { {}, {} }
for c = 1, nch do
local x = bitsAt(b, pos, 8)
local y = bitsAt(b, pos + 8, 8)
pos += 16
mode[c], denShift[c] = rshift(x, 4), band(x, 15)
pbFactor[c], order[c] = rshift(y, 5), band(y, 31)
if pos + order[c] * 16 > limit then
return nil, "frame runs past the end"
end
for j = 1, order[c] do
local v = bitsAt(b, pos, 16)
pos += 16
coefs[c][j] = if v >= 32768 then v - 65536 else v
end
end
if pos > limit then
return nil, "frame runs past the end"
end
local shiftPos = pos
if shift > 0 then
pos += shift * n * nch
end
for c = 1, nch do
local p = if c == 1 then p0 else p1
local mb = if c == 1 then m0 else m1
pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st)
if pos < 0 or pos > limit then
return nil, "bad residuals"
end
if mode[c] == 15 then
predict(p, p, n, bps, {}, 31, 0)
elseif mode[c] ~= 0 then
return nil, "unknown prediction mode " .. mode[c]
end
predict(p, mb, n, bps, coefs[c], order[c], denShift[c])
end
if shift > 0 then
local sp = shiftPos
for i = 1, n * nch do
shiftBuf[i] = bitsAt(b, sp, shift)
sp += shift
end
end
else
-- uncompressed: interleaved samples of bitDepth bits
local bits = st.bitDepth
if pos + n * nch * bits > limit then
return nil, "frame runs past the end"
end
for i = 1, n do
for c = 1, nch do
local v
if bits > 25 then
v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16)
else
v = bitsAt(b, pos, bits)
end
pos += bits
v = signExtend(v, bits)
if c == 1 then
m0[i] = v
else
m1[i] = v
end
end
end
shift = 0
end
-- unmix + shifted bytes -> interleaved output
local sm = POW[shift + 1]
if nch == 2 then
local den = POW[mixBits + 1]
for i = 1, n do
local u, v = m0[i], m1[i]
local l, r
if mixRes ~= 0 then
l = u + v - floor(mixRes * v / den)
r = l - v
else
l, r = u, v
end
if shift > 0 then
l = l * sm + shiftBuf[2 * i - 1]
r = r * sm + shiftBuf[2 * i]
end
local o = (i - 1) * channels + ch + 1
out[o] = l
out[o + 1] = r
end
else
for i = 1, n do
local v = m0[i]
if shift > 0 then
v = v * sm + shiftBuf[i]
end
out[(i - 1) * channels + ch + 1] = v
end
end
ch += nch
elseif tag == 4 then -- DSE
pos += 4
local align = bitsAt(b, pos, 1)
local count = bitsAt(b, pos + 1, 8)
pos += 9
if count == 255 then
count += bitsAt(b, pos, 8)
pos += 8
end
if align == 1 then
pos = (pos + 7) // 8 * 8
end
pos += count * 8
elseif tag == 6 then -- FIL
local count = bitsAt(b, pos, 4)
pos += 4
if count == 15 then
count += bitsAt(b, pos, 8) - 1
pos += 8
end
pos += count * 8
else
return nil, "unsupported element " .. tag
end
if pos > limit then
return nil, "frame runs past the end"
end
end
if frames < 0 then
return 0, nil
end
if ch < channels then
-- missing channels: silence
for i = 1, frames do
for c = ch + 1, channels do
out[(i - 1) * channels + c] = 0
end
end
end
return frames, nil
end
-- the scratch state for a configuration
function Decode.state(cfg: any): State
local n = cfg.frameLength
return {
frameLength = n,
bitDepth = cfg.bitDepth,
pb = cfg.pb,
mb = cfg.mb,
kb = cfg.kb,
channels = cfg.channels,
maxRun = cfg.maxRun,
scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64),
pred = { table.create(n, 0), table.create(n, 0) },
mix = { table.create(n, 0), table.create(n, 0) },
shift = table.create(n * 2, 0),
out = table.create(n * cfg.channels, 0),
}
end
local _ = readu8
return Decode
+427
View File
@@ -0,0 +1,427 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
-- input. Written for this library from the ALAC format; no third-party code. Never throws.
local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local floor, abs = math.floor, math.abs
local Encode = {}
local POW = table.create(64, 0)
for i = 0, 63 do
POW[i + 1] = 2 ^ i
end
local DENSHIFT = 9
local PB_FACTOR = 4
export type State = {
frameLength: number,
bitDepth: number,
pb: number,
mb: number,
kb: number,
channels: number,
out: buffer, -- packet scratch
pos: number, -- bit position in out
cap: number, -- bits available
u: { number },
v: { number },
err: { number },
work: { number },
}
-- ------------------------------------------------------------------------------------------------ bit writer
local function put(st: State, v: number, n: number)
local pos = st.pos
if pos + n > st.cap then
st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame
return
end
local b = st.out
while n > 0 do
local byte = rshift(pos, 3)
local free = 8 - band(pos, 7)
local take = if n < free then n else free
local bits = band(rshift(v, n - take), POW[take + 1] - 1)
writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take)))
pos += take
n -= take
end
st.pos = pos
end
local function putBig(st: State, v: number, n: number)
if n > 24 then
local lo = v % 65536
put(st, (v - lo) / 65536, n - 16)
put(st, lo, 16)
else
put(st, v, n)
end
end
-- ------------------------------------------------------------------------------------------------ rice code
local function signExtend(v: number, bits: number): number
local m = POW[bits + 1]
v = v % m
if v >= m / 2 then
v -= m
end
return v
end
-- the bits of one scalar (no writing)
local function scalarBits(x: number, k: number, m: number, bps: number): number
local pre = if k == 1 then x else floor(x / m)
if pre >= 9 then
return 9 + bps
end
if k == 1 then
return pre + 1
end
local r = x - pre * m
return pre + 1 + (if r == 0 then k - 1 else k)
end
local function scalar(st: State, x: number, k: number, m: number, bps: number)
local pre = if k == 1 then x else floor(x / m)
if pre >= 9 then
put(st, 511, 9)
putBig(st, x, bps)
return
end
-- pre ones and a zero
put(st, POW[pre + 2] - 2, pre + 1)
if k ~= 1 then
local r = x - pre * m
if r == 0 then
put(st, 0, k - 1)
else
put(st, r + 1, k)
end
end
end
-- code the residuals e[1..n] (write = false: just count the bits)
local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number
local history = st.mb
local kb = st.kb
local signMod = 0
local bits = 0
local i = 1
while i <= n do
local k = 31 - countlz(floor(history / 512) + 3)
if k > kb then
k = kb
end
local v = e[i]
local zz = if v >= 0 then 2 * v else -2 * v - 1
local x = zz - signMod
signMod = 0
local m = POW[k + 1] - 1
if write then
scalar(st, x, k, m, bps)
else
bits += scalarBits(x, k, m, bps)
end
if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back
history = 0xFFFF
else
history += zz * mult - floor(history * mult / 512)
end
if history < 128 and i < n then
local lg = if history > 0 then 31 - countlz(history) else 0
k = 7 - lg + floor((history + 16) / 64)
if k > kb then
k = kb
end
local run = 0
while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do
run += 1
end
m = POW[k + 1] - 1
if write then
scalar(st, run, k, m, 16)
else
bits += scalarBits(run, k, m, 16)
end
i += run
if run < 0xFFFF then
signMod = 1
end
history = 0
end
i += 1
end
return bits
end
-- ------------------------------------------------------------------------------------------------ prediction
-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder)
local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
e[1] = x[1]
if n <= 1 then
return
end
local i = 2
while i <= order + 1 and i <= n do
e[i] = signExtend(x[i] - x[i - 1], bps)
i += 1
end
local half = POW[quant]
local qd = POW[quant + 1]
while i <= n do
local d = x[i - order - 1]
local val = 0
for j = 1, order do
val += (x[i - j] - d) * coefs[j]
end
val = floor((val + half) / qd)
local r = signExtend(x[i] - val - d, bps)
e[i] = r
if r ~= 0 then
local es = if r > 0 then 1 else -1
for j = order, 1, -1 do
if r * es <= 0 then
break
end
local v = d - x[i - j]
local sgn = if v > 0 then es elseif v < 0 then -es else 0
coefs[j] -= sgn
r -= floor(v * sgn / qd) * (order - j + 1)
end
end
i += 1
end
end
-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised
local function lpc(x: { number }, n: number, order: number, work: { number }): { number }
local ac = table.create(order + 1, 0)
for i = 1, n do
local t = (2 * (i - 1) - (n - 1)) / (n + 1)
work[i] = x[i] * (1 - t * t)
end
for lag = 0, order do
local s = 0
for i = lag + 1, n do
s += work[i] * work[i - lag]
end
ac[lag + 1] = s
end
local coefs = table.create(order, 0)
if ac[1] <= 0 then
return coefs
end
ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable
local a = table.create(order + 1, 0)
local tmp = table.create(order + 1, 0)
local errv = ac[1]
for i = 1, order do
local acc = ac[i + 1]
for j = 1, i - 1 do
acc -= a[j] * ac[i - j + 1]
end
local kc = acc / errv
for j = 1, i - 1 do
tmp[j] = a[j] - kc * a[i - j]
end
for j = 1, i - 1 do
a[j] = tmp[j]
end
a[i] = kc
errv *= (1 - kc * kc)
if errv <= 0 then
break
end
end
local scale = POW[DENSHIFT + 1]
for j = 1, order do
coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767)
end
return coefs
end
-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits
local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number)
local mult = floor(st.pb * PB_FACTOR / 4)
local bestOrder, bestCoefs, bestBits = 0, {}, math.huge
for _, order in { 4, 8 } do
if order >= n then
continue
end
local coefs = lpc(x, n, order, st.work)
local trial = table.clone(coefs)
residuals(x, st.err, n, bps, trial, order, DENSHIFT)
local bits = rice(st, st.err, n, bps, mult, false) + order * 16
if bits < bestBits then
bestOrder, bestCoefs, bestBits = order, coefs, bits
end
end
if bestBits == math.huge then
-- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction)
for i = 1, n do
st.err[i] = x[i]
end
return 0, {}, rice(st, st.err, n, bps, mult, false)
end
return bestOrder, bestCoefs, bestBits
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index
-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts
function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer
local channels, depth = st.channels, st.bitDepth
local n = frames
local partial = n ~= st.frameLength
local rawBits = n * channels * depth
local need = rawBits + 64 * #elements + 64
if st.cap < need + 8 * 32 * 2 * #elements * 16 then
local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16
st.out = buffer.create(bytes)
st.cap = bytes * 8
end
buffer.fill(st.out, 0, 0)
st.pos = 0
local u, v = st.u, st.v
local mult = floor(st.pb * PB_FACTOR / 4)
local compressed = true
local ch = 1
for _, nch in elements do
local a, b = map[ch], map[ch + 1]
local bps = depth + nch - 1
local mixRes = 0
if nch == 2 then
-- the mix with the smallest first-difference energy
local best = math.huge
for res = 0, 4 do
local cost = 0
local pu, pv = 0, 0
for i = 0, n - 1 do
local l = samples[first + i * channels + a - 1]
local r = samples[first + i * channels + b - 1]
local uu, vv
if res == 0 then
uu, vv = l, r
else
uu, vv = floor((res * l + (4 - res) * r) / 4), l - r
end
cost += abs(uu - pu) + abs(vv - pv)
pu, pv = uu, vv
end
if cost < best then
best, mixRes = cost, res
end
end
for i = 1, n do
local l = samples[first + (i - 1) * channels + a - 1]
local r = samples[first + (i - 1) * channels + b - 1]
if mixRes == 0 then
u[i], v[i] = l, r
else
u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r
end
end
else
for i = 1, n do
u[i] = samples[first + (i - 1) * channels + a - 1]
end
end
-- header
put(st, if nch == 2 then 1 else 0, 3)
put(st, 0, 4)
put(st, 0, 12)
put(st, if partial then 1 else 0, 1)
put(st, 0, 2)
put(st, 0, 1)
if partial then
putBig(st, n, 32)
end
put(st, if mixRes == 0 then 0 else 2, 8)
put(st, mixRes, 8)
local orders, coefsList = {}, {}
for c = 1, nch do
local x = if c == 1 then u else v
local order, coefs = analyse(st, x, n, bps)
orders[c], coefsList[c] = order, coefs
put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift
put(st, PB_FACTOR * 32 + order, 8)
for j = 1, order do
put(st, coefs[j] % 65536, 16)
end
end
for c = 1, nch do
local x = if c == 1 then u else v
local order = orders[c]
if order == 0 then
for i = 1, n do
st.err[i] = x[i]
end
else
residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT)
end
rice(st, st.err, n, bps, mult, true)
end
ch += nch
if st.pos > rawBits + 64 * #elements then
compressed = false
break
end
end
if not compressed then
-- uncompressed frame
buffer.fill(st.out, 0, 0)
st.pos = 0
ch = 1
for _, nch in elements do
put(st, if nch == 2 then 1 else 0, 3)
put(st, 0, 4)
put(st, 0, 12)
put(st, if partial then 1 else 0, 1)
put(st, 0, 2)
put(st, 1, 1)
if partial then
putBig(st, n, 32)
end
for i = 0, n - 1 do
for c = 0, nch - 1 do
putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth)
end
end
ch += nch
end
end
put(st, 7, 3) -- END
local bytes = (st.pos + 7) // 8
local pkt = buffer.create(bytes)
buffer.copy(pkt, 0, st.out, 0, bytes)
return pkt
end
function Encode.state(cfg: any): State
local n = cfg.frameLength
return {
frameLength = n,
bitDepth = cfg.bitDepth,
pb = cfg.pb,
mb = cfg.mb,
kb = cfg.kb,
channels = cfg.channels,
out = buffer.create(16),
pos = 0,
cap = 0,
u = table.create(n, 0),
v = table.create(n, 0),
err = table.create(n, 0),
work = table.create(n, 0),
}
end
return Encode
+251
View File
@@ -0,0 +1,251 @@
--!strict
-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
--
-- local Alac = require("@formats/codecs/Alac")
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
-- local dec = Alac.decoder(cfg)
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })
-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096)
-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled
--
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Alac/Decode")
local Encode = require("@formats/codecs/Alac/Encode")
local Alac = {}
export type Config = {
frameLength: number, -- samples per packet (4096)
compatibleVersion: number,
bitDepth: number,
pb: number, -- 40
mb: number, -- 10
kb: number, -- 14
channels: number,
maxRun: number, -- 255
maxFrameBytes: number,
avgBitRate: number,
sampleRate: number,
}
-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count
local TO_WAV: { { number } } = {
{ 1 },
{ 1, 2 },
{ 3, 1, 2 },
{ 3, 1, 2, 4 },
{ 3, 1, 2, 4, 5 },
{ 3, 1, 2, 5, 6, 4 },
{ 3, 1, 2, 5, 6, 7, 4 },
{ 3, 7, 8, 1, 2, 5, 6, 4 },
}
-- the element layout (channels per element) the encoder writes
local ELEMENTS: { { number } } = {
{ 1 },
{ 2 },
{ 1, 2 },
{ 1, 2, 1 },
{ 1, 2, 2 },
{ 1, 2, 2, 1 },
{ 1, 2, 2, 1, 1 },
{ 1, 2, 2, 2, 1 },
}
Alac.TO_WAV = TO_WAV
-- config(buf, offset?, length?) -> Config | nil, Err
function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?)
local r = Bytes.reader(buf, offset, length)
-- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie
for _ = 1, 2 do
local typ = r:peek(4, 4)
if typ == "frma" then
r:skip(12)
elseif typ == "alac" then
r:skip(12)
end
end
if r:remaining() < 24 then
return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes")
end
local c: Config = {
frameLength = r:u32be(),
compatibleVersion = r:u8(),
bitDepth = r:u8(),
pb = r:u8(),
mb = r:u8(),
kb = r:u8(),
channels = r:u8(),
maxRun = r:u16be(),
maxFrameBytes = r:u32be(),
avgBitRate = r:u32be(),
sampleRate = r:u32be(),
}
if c.compatibleVersion ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion)
end
if c.frameLength < 1 or c.frameLength > 65536 then
return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength)
end
if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth)
end
if c.channels < 1 or c.channels > 8 then
return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels")
end
if c.kb < 1 or c.kb > 24 then
return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb)
end
return c, nil
end
-- cookie(cfg) -> the 24-byte ALACSpecificConfig
function Alac.cookie(c: Config): buffer
local w = Bytes.writer(24)
w:u32be(c.frameLength)
w:u8(0)
w:u8(c.bitDepth)
w:u8(c.pb)
w:u8(c.mb)
w:u8(c.kb)
w:u8(c.channels)
w:u16be(c.maxRun)
w:u32be(c.maxFrameBytes)
w:u32be(c.avgBitRate)
w:u32be(c.sampleRate)
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
config: Config,
pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits)
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
state: Decode.State,
}
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
local o = offset or 0
local n = length or (buffer.len(buf) - o)
if o < 0 or n < 0 or o + n > buffer.len(buf) then
return nil, Err.new(Err.ARG, "packet range out of the buffer")
end
local frames, msg = Decode.frame(self.state, buf, o, n)
if not frames then
return nil, Err.new(Err.CORRUPT, msg or "bad packet", o)
end
local ch = self.config.channels
local src, dst = self.state.out, self.pcm
if ch <= 2 then
for i = 1, frames * ch do
dst[i] = src[i]
end
else
local map = TO_WAV[ch]
for f = 0, frames - 1 do
local base = f * ch
for k = 1, ch do
dst[base + map[k]] = src[base + k]
end
end
end
return frames, nil
end
-- decoder(cfg) -> Decoder
function Alac.decoder(cfg: Config): Decoder
return {
config = cfg,
pcm = table.create(cfg.frameLength * cfg.channels, 0),
decode = decode,
state = Decode.state(cfg),
}
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Encoder = {
config: Config,
encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?),
state: Encode.State,
bytes: number,
frames: number,
}
local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?)
local cfg = self.config
if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples")
end
if first < 1 or first + frames * cfg.channels - 1 > #samples then
return nil, Err.new(Err.ARG, "encode: the samples end early")
end
local ch = cfg.channels
local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch])
local n = buffer.len(pkt)
self.bytes += n
self.frames += frames
if n > cfg.maxFrameBytes then
cfg.maxFrameBytes = n
end
if self.frames > 0 then
cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames)
end
return pkt, nil
end
export type EncoderOptions = {
sampleRate: number,
channels: number, -- 1 .. 8
bitDepth: number?, -- 16 (default), 20 or 24
frameLength: number?, -- default 4096
}
-- encoder(opts) -> Encoder | nil, Err
function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?)
if type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "encoder: expected options")
end
local depth = opts.bitDepth or 16
local ch = opts.channels
if depth ~= 16 and depth ~= 20 and depth ~= 24 then
return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24")
end
if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels")
end
local sr = opts.sampleRate
if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encoder: bad sampleRate")
end
local fl = opts.frameLength or 4096
if fl < 16 or fl > 16384 or fl % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384")
end
local cfg: Config = {
frameLength = fl,
compatibleVersion = 0,
bitDepth = depth,
pb = 40,
mb = 10,
kb = 14,
channels = ch,
maxRun = 255,
maxFrameBytes = 0,
avgBitRate = 0,
sampleRate = sr,
}
return {
config = cfg,
encode = encode,
state = Encode.state(cfg),
bytes = 0,
frames = 0,
}, nil
end
return Alac
+3
View File
@@ -152,6 +152,7 @@ local function emit(self: any, p: any)
if sps.sarW and sps.sarH then
img.meta.sar = { sps.sarW, sps.sarH }
end
img.meta.yuv = { range = if sps.fullRange then "full" else "limited", matrix = if sps.matrix == 1 then "bt709" else "bt601" }
table.insert(self.out, { image = img, pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr })
release(self, p)
end
@@ -743,9 +744,11 @@ local function finishPicture(self: any)
bump(self, 0)
end
if mmco5 then
-- 8.2.1: after MMCO 5 the picture counts as frame_num 0 with its POC moved to 0
local t = p.poc
p.topPoc -= t
p.poc = 0
p.frameNum = 0
end
-- POC / frame_num state for the next pictures
if sh.nalRefIdc ~= 0 then
+191
View File
@@ -27,6 +27,7 @@ local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Bitstream = require("@formats/codecs/H264/Bitstream")
local Decoder = require("@formats/codecs/H264/Decoder")
local Params = require("@formats/codecs/H264/Params")
local H264 = {}
@@ -195,6 +196,196 @@ function H264.parseAvcC(data: any): (any, Err.Err?)
return cfg, nil
end
-- ------------------------------------------------------------------------------------------------ video layer
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/Video registry entry for "h264"):
-- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264).
-- Pictures come out in display order with the pts of the packet that carried them; a track with
-- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead.
function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay }
local function make(): (H264Decoder?, Err.Err?)
local d, err = H264.newDecoder(o)
if d and track.config then
local ok, e = d:configure(track.config)
if not ok then
return nil, e
end
end
return d, err
end
local dec, err = make()
if not dec then
return nil, err
end
local queue: { any } = {}
local outIndex: number? = if track.ptsInOutputOrder then 0 else nil
local self: any = {}
local function push(frames: { Frame })
for _, f in frames do
local pts = f.pts
if track.ptsInOutputOrder then
pts = outIndex or 0
outIndex = pts + 1
end
table.insert(queue, { f.image, pts, f.keyframe })
end
end
function self.decode(_: any, packet: Types.Packet): Err.Err?
if not dec then
return Err.new(Err.CORRUPT, "decoder not available")
end
if outIndex == nil and track.ptsInOutputOrder then
outIndex = packet.pts
end
local frames, e = (dec :: H264Decoder):decode(packet.data, packet.pts)
if not frames then
return e
end
push(frames)
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil
end
function self.flush(_: any)
if dec then
push((dec :: H264Decoder):flush())
end
end
function self.reset(_: any)
dec = make()
table.clear(queue)
if track.ptsInOutputOrder then
outIndex = nil
end
end
return self, nil
end
-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units
-- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0
-- after a slice). keyframe: the unit holds an IDR slice.
function H264.accessUnits(data: any, off: number?, len: number?): { any }
local b = toBuffer(data)
local out = {}
if not b then
return out
end
local n = buffer.len(b)
local o = math.clamp(off or 0, 0, n)
local l = math.clamp(len or (n - o), 0, n - o)
local nals = Bitstream.splitAnnexB(b, o, l)
local start, hasSlice, key = o, false, false
for i = 1, #nals, 2 do
local p, nl = nals[i], nals[i + 1]
local t = buffer.readu8(b, p) % 32
local isSlice = t == 1 or t == 5
local boundary = false
if hasSlice then
if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then
boundary = true
elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then
boundary = true
end
end
if boundary then
-- the unit ends where this NAL's start code begins
local s = p
while s > start and buffer.readu8(b, s - 1) ~= 1 do
s -= 1
end
s -= 1
while s > start and buffer.readu8(b, s - 1) == 0 do
s -= 1
end
table.insert(out, start)
table.insert(out, s - start)
table.insert(out, key)
start, hasSlice, key = s, false, false
end
if isSlice then
hasSlice = true
if t == 5 then
key = true
end
end
end
if hasSlice and o + l > start then
table.insert(out, start)
table.insert(out, o + l - start)
table.insert(out, key)
end
return out
end
-- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the
-- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample
function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
local parts = {}
local lengthSize = 4
if config then
local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config))
if not cfg then
return nil, Err.new(Err.CORRUPT, err or "bad avcC")
end
lengthSize = cfg.lengthSize
for i = 1, #cfg.nals, 2 do
table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1]))
end
end
local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize)
if not nals then
return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample")
end
for i = 1, #nals, 2 do
table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1]))
end
return buffer.fromstring(table.concat(parts)), nil
end
-- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil
function H264.info(data: any): any
local b = toBuffer(data)
if not b then
return nil
end
local nals
if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then
local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b))
nals = if cfg then cfg.nals else {}
else
nals = Bitstream.splitAnnexB(b, 0, buffer.len(b))
end
for i = 1, #nals, 2 do
if buffer.readu8(b, nals[i]) % 32 == 7 then
local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1))
if sps then
local fps = nil
if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then
fps = sps.timeScale / (2 * sps.unitsInTick)
end
return {
width = sps.width,
height = sps.height,
profile = sps.profile,
level = sps.level,
chromaFormat = sps.chromaFormat,
bitDepth = sps.bitDepth,
interlaced = not sps.frameMbsOnly,
frameRate = fps,
maxRefFrames = sps.maxRefFrames,
numReorderFrames = sps.numReorderFrames,
}
end
end
end
return nil
end
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
function H264.planes(img: Types.Image): (number, number, number, number, number)
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
+414
View File
@@ -0,0 +1,414 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
--
-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded);
-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a
-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of
-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5
-- bin at [1280].
local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
local band, bxor = bit32.band, bit32.bxor
local Arith = {}
-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS
local TAB = buffer.create(114 * 4)
do
local raw = {
{ 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 },
{ 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 },
{ 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 },
{ 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 },
{ 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 },
{ 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 },
{ 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 },
{ 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 },
{ 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 },
{ 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 },
{ 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 },
{ 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 },
{ 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 },
{ 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 },
{ 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 },
{ 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 },
{ 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 },
{ 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 },
{ 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 },
{ 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 },
{ 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 },
{ 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 },
{ 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 },
}
for i, e in raw do
buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe
writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS
writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS
end
end
local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG)
local STATS = 1281
local POW2 = buffer.create(8)
for i = 0, 7 do
writeu8(POW2, i, 2 ^ i)
end
local FIXED = 1280
-- decoder state (one scan at a time; never yields)
local D: buffer = buffer.create(0)
local P = 0 -- next byte
local SEGEND = 0 -- reads at or past this return 0
local OVER = 0 -- zero bytes supplied past the end
local C, A, CT = 0, 0, -16
local st: buffer = buffer.create(STATS)
local function decode(s: number): number
while A < 0x8000 do
CT -= 1
if CT < 0 then
local data = 0
if P < SEGEND then
data = readu8(D, P)
P += 1
else
OVER += 1
end
C = C * 256 + data
CT += 8
if CT < 0 then
CT += 1
if CT == 0 then
A = 0x8000
end
end
end
A *= 2
end
local sv = readu8(st, s)
local t = band(sv, 0x7F) * 4
local qe = buffer.readu16(TAB, t)
local nl = readu8(TAB, t + 2)
local nm = readu8(TAB, t + 3)
local temp = A - qe
A = temp
temp *= readu8(POW2, CT)
if C >= temp then
C -= temp
if A < qe then
A = qe
writeu8(st, s, bxor(band(sv, 0x80), nm))
else
A = qe
writeu8(st, s, bxor(band(sv, 0x80), nl))
sv = bxor(sv, 0x80)
end
elseif A < 0x8000 then
if A < qe then
writeu8(st, s, bxor(band(sv, 0x80), nl))
sv = bxor(sv, 0x80)
else
writeu8(st, s, bxor(band(sv, 0x80), nm))
end
end
return if sv >= 0x80 then 1 else 0
end
local function i16(v: number): number
v = band(v, 0xFFFF)
return if v >= 0x8000 then v - 0x10000 else v
end
export type ArithComp = {
coef: buffer,
bpl: number,
h: number,
v: number,
bw: number,
bh: number,
dcTbl: number, -- 0..3
acTbl: number,
pred: number,
ctx: number,
}
export type ArithParams = {
comps: { ArithComp },
mcusX: number,
mcusY: number,
ri: number,
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
ss: number,
se: number,
al: number,
dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1
dcU: { number },
acK: { number },
}
-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code
local function dcDiff(c: ArithComp, L: number, U: number): number?
local base = c.dcTbl * 64
local s = base + c.ctx
if decode(s) == 0 then
c.ctx = 0
return c.pred
end
local sign = decode(s + 1)
s = s + 2 + sign
local m = decode(s)
if m ~= 0 then
s = base + 20
while decode(s) ~= 0 do
m *= 2
if m == 0x8000 then
return nil
end
s += 1
end
end
if m < 2 ^ L // 2 then
c.ctx = 0
elseif m > 2 ^ U // 2 then
c.ctx = 12 + sign * 4
else
c.ctx = 4 + sign * 4
end
local v = m
s += 14
m = m // 2
while m > 0 do
if decode(s) ~= 0 then
v += m
end
m = m // 2
end
v += 1
if sign ~= 0 then
v = -v
end
return band(c.pred + v, 0xFFFF)
end
-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code
local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean
local base = 256 + tbl * 256
local k = ss
while k <= se do
local s = base + 3 * (k - 1)
if decode(s) ~= 0 then
break -- EOB
end
while decode(s + 1) == 0 do
s += 3
k += 1
if k > se then
return false
end
end
local sign = decode(FIXED)
s += 2
local m = decode(s)
if m ~= 0 then
if decode(s) ~= 0 then
m *= 2
s = base + (if k <= K then 189 else 217)
while decode(s) ~= 0 do
m *= 2
if m == 0x8000 then
return false
end
s += 1
end
end
end
local v = m
s += 14
m = m // 2
while m > 0 do
if decode(s) ~= 0 then
v += m
end
m = m // 2
end
v += 1
if sign ~= 0 then
v = -v
end
writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul))
k += 1
end
return true
end
local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean
local base = 256 + tbl * 256
local p1 = 2 ^ al
local m1 = -p1
local kex = se
while kex > 0 do
if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then
break
end
kex -= 1
end
local k = ss
while k <= se do
local s = base + 3 * (k - 1)
if k > kex then
if decode(s) ~= 0 then
break
end
end
while true do
local o = off + readu8(ZZ, k) * 2
local cv = readi16(coef, o)
if cv ~= 0 then
if decode(s + 2) ~= 0 then
writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1))
end
break
end
if decode(s + 1) ~= 0 then
writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1))
break
end
s += 3
k += 1
if k > se then
return false
end
end
k += 1
end
return true
end
function Arith.init(zigzag: buffer)
ZZ = zigzag
end
-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout)
function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean
local comps = Pm.comps
local nc = #comps
local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri
local units, ux
if nc == 1 then
ux = comps[1].bw
units = ux * comps[1].bh
else
ux = Pm.mcusX
units = ux * Pm.mcusY
end
local resetDc = mode == 0 or mode == 1
local resetAc = mode == 0 or mode == 3 or mode == 4
local function reset()
for i = 1, nc do
local c = comps[i]
if resetDc then
buffer.fill(st, c.dcTbl * 64, 0, 64)
c.pred = 0
c.ctx = 0
end
if resetAc then
buffer.fill(st, 256 + c.acTbl * 256, 0, 256)
end
end
C, A, CT = 0, 0, -16
end
D = d
P = 0
SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen
OVER = 0
writeu8(st, FIXED, 113)
reset()
local rstIdx = 0
local bad = false
local truncated = false
local mul = 2 ^ al
for u = 0, units - 1 do
if ri > 0 and u > 0 and u % ri == 0 then
rstIdx += 1
if rstIdx <= nrst then
P = math.min(rst[rstIdx], cleanLen)
SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen
bad = false
else
truncated = true
break
end
reset()
end
if not bad then
local my, mx = u // ux, u % ux
for ci = 1, nc do
local c = comps[ci]
local bh, bw, by0, bx0
if nc == 1 then
bh, bw, by0, bx0 = 1, 1, my, mx
else
bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
end
local coef, bpl = c.coef, c.bpl
for by = by0, by0 + bh - 1 do
for bx = bx0, bx0 + bw - 1 do
local off = (by * bpl + bx) * 128
if mode == 0 then
local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
if not pred then
bad = true
else
c.pred = pred
writei16(coef, off, i16(pred))
if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then
bad = true
end
end
elseif mode == 1 then
local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
if not pred then
bad = true
else
c.pred = pred
writei16(coef, off, i16(pred * mul))
end
elseif mode == 2 then
if decode(FIXED) ~= 0 then
local cv = readi16(coef, off)
if band(cv, mul) == 0 then
writei16(coef, off, i16(cv + mul))
end
end
elseif mode == 3 then
if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then
bad = true
end
else
if not acRefine(coef, off, c.acTbl, ss, se, al) then
bad = true
end
end
if bad then
break
end
end
if bad then
break
end
end
if bad then
break
end
end
end
end
D = buffer.create(0)
return truncated
end
return Arith
+229
View File
@@ -0,0 +1,229 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
--
-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults:
-- FULL the component is at output resolution
-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4
-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16
-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row)
-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample
-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows.
-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and
-- YCCK (Adobe inverted CMYK: R = C * K / 255).
local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32
local clamp, min, max = math.clamp, math.min, math.max
local Color = {}
Color.FULL = 0
Color.REPLICATE = 1
Color.H2V1 = 2
Color.H2V2 = 3
Color.H1V2 = 4
Color.GRAY = 0
Color.YCC = 1
Color.RGB = 2
Color.CMYK = 3
Color.YCCK = 4
Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
export type Comp = {
plane: buffer, -- u16 samples, stride per row
stride: number,
rows: number, -- plane height
downW: number, -- real samples across / down (the rest is block padding)
downH: number,
method: number,
hIn: number,
hOut: number,
vIn: number,
vOut: number,
row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples)
}
export type Params = {
comps: { Comp },
space: number,
outW: number,
outH: number,
maxv: number,
pixels: buffer,
-- YCbCr tables (maxv + 1 i32 entries)
crr: buffer,
cbb: buffer,
crg: buffer,
cbg: buffer,
toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit
}
-- jdcolor.c build_ycc_rgb_table
function Color.tables(maxv: number): (buffer, buffer, buffer, buffer)
local n = maxv + 1
local center = n // 2
local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4)
local function fix(x: number): number
return math.floor(x * 65536 + 0.5)
end
for i = 0, maxv do
local x = i - center
buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536)
buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536)
buffer.writei32(crg, i * 4, -fix(0.71414) * x)
buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768)
end
return crr, cbb, crg, cbg
end
-- fills c.row with output row y; returns the buffer and byte offset of the row's samples
local function fetch(c: Comp, y: number, outW: number): (buffer, number)
local method = c.method
local plane, stride, row = c.plane, c.stride, c.row
if method == 0 then
return plane, min(y, c.rows - 1) * stride * 2
elseif method == 2 then
local w = c.downW
local b = min(y, c.rows - 1) * stride * 2
local cur = readu16(plane, b)
writeu16(row, 0, cur)
local nxt = readu16(plane, b + 2)
writeu16(row, 2, (cur * 3 + nxt + 2) // 4)
local prev = cur
cur = nxt
for i = 1, w - 2 do
nxt = readu16(plane, b + (i + 1) * 2)
local v3 = cur * 3
writeu16(row, i * 4, (v3 + prev + 1) // 4)
writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4)
prev = cur
cur = nxt
end
writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4)
writeu16(row, (w - 1) * 4 + 2, cur)
return row, 0
elseif method == 3 then
local w = c.downW
local iy = min(y // 2, c.downH - 1)
local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1)
local b0, b1 = iy * stride * 2, oy * stride * 2
local this = readu16(plane, b0) * 3 + readu16(plane, b1)
local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2)
writeu16(row, 0, (this * 4 + 8) // 16)
writeu16(row, 2, (this * 3 + nxt + 7) // 16)
local last = this
this = nxt
for i = 1, w - 2 do
nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2)
local t3 = this * 3
writeu16(row, i * 4, (t3 + last + 8) // 16)
writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16)
last = this
this = nxt
end
writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16)
writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16)
return row, 0
elseif method == 4 then
local iy = min(y // 2, c.downH - 1)
local oy, bias
if y % 2 == 0 then
oy, bias = max(iy - 1, 0), 1
else
oy, bias = min(iy + 1, c.downH - 1), 2
end
local b0, b1 = iy * stride * 2, oy * stride * 2
for x = 0, outW - 1 do
writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4)
end
return row, 0
else
local hIn, hOut = c.hIn, c.hOut
local iy = min((y * c.vIn) // c.vOut, c.rows - 1)
local b = iy * stride * 2
local last = stride - 1
for x = 0, outW - 1 do
writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2))
end
return row, 0
end
end
function Color.run(P: Params)
local comps = P.comps
local nc = #comps
local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels
local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg
local toByte = P.toByte
local o = 0
for y = 0, outH - 1 do
local s0, b0 = fetch(comps[1], y, outW)
if space == 0 or nc < 3 then
for x = 0, outW - 1 do
local v = readu16(s0, b0 + x * 2)
if toByte then
v = readu8(toByte, v)
end
writeu32(out, o, 0xFF000000 + v * 0x10101)
o += 4
end
else
local s1, b1 = fetch(comps[2], y, outW)
local s2, b2 = fetch(comps[3], y, outW)
local s3, b3 = s0, b0
if nc >= 4 then
s3, b3 = fetch(comps[4], y, outW)
end
if space == 1 and not toByte then
-- the common case: 8-bit YCbCr
for x = 0, outW - 1 do
local i = x * 2
local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
local r = clamp(yv + readi32(crr, cr * 4), 0, 255)
local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255)
local b = clamp(yv + readi32(cbb, cb * 4), 0, 255)
writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
o += 4
end
continue
end
for x = 0, outW - 1 do
local i = x * 2
local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
local r, g, b
if space == 2 then
r, g, b = c0, c1, c2
elseif space == 3 or space == 5 then
local k = readu16(s3, b3 + i)
if space == 5 then
c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k
end
r = (c0 * k + maxv // 2) // maxv
g = (c1 * k + maxv // 2) // maxv
b = (c2 * k + maxv // 2) // maxv
else
r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv)
g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv)
b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv)
if space == 4 then
-- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored
local k = readu16(s3, b3 + i)
r = ((maxv - r) * k + maxv // 2) // maxv
g = ((maxv - g) * k + maxv // 2) // maxv
b = ((maxv - b) * k + maxv // 2) // maxv
end
end
if toByte then
r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b)
end
writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
o += 4
end
end
end
end
return Color
+762
View File
@@ -0,0 +1,762 @@
--!strict
-- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a
-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats.
local Scan = require("@formats/codecs/Jpeg/Scan")
local Arith = require("@formats/codecs/Jpeg/Arith")
local Color = require("@formats/codecs/Jpeg/Color")
local Tables = require("@formats/codecs/Jpeg/Tables")
local Yuv = require("@formats/codecs/Jpeg/Yuv")
local Dct = require("@formats/codecs/Dct")
local readu8 = buffer.readu8
local band, rshift = bit32.band, bit32.rshift
local Decode = {}
Arith.init(Scan.ZIGZAG)
local function be16(b: buffer, p: number): number
return readu8(b, p) * 256 + readu8(b, p + 1)
end
local stdBuilt: { [string]: buffer } = {}
local function stdTable(class: string, slot: number): buffer?
local key = class .. slot
if not stdBuilt[key] then
local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1]
if not def then
return nil
end
stdBuilt[key] = Scan.buildTable(def.counts, def.symbols)
end
return stdBuilt[key]
end
-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e)
local function exif(b: buffer, p: number, e: number): (number?, number?)
if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then
return nil, nil
end
local t = p + 6
local le
local bo = buffer.readstring(b, t, 2)
if bo == "II" then
le = true
elseif bo == "MM" then
le = false
else
return nil, nil
end
local function r16(at: number): number
if le then
return readu8(b, at) + readu8(b, at + 1) * 256
end
return readu8(b, at) * 256 + readu8(b, at + 1)
end
local function r32(at: number): number
if le then
return r16(at) + r16(at + 2) * 65536
end
return r16(at) * 65536 + r16(at + 2)
end
local ifd = t + r32(t + 4)
if ifd + 2 > e then
return t, nil
end
local count = r16(ifd)
for i = 0, count - 1 do
local en = ifd + 2 + i * 12
if en + 12 > e then
return t, nil
end
if r16(en) == 0x0112 then
local v = r16(en + 8)
return t, if v >= 1 and v <= 8 then v else nil
end
end
return t, nil
end
type Comp = {
id: number,
h: number,
v: number,
tq: number,
bpl: number,
bpc: number,
bw: number,
bh: number,
coef: buffer?,
quant: buffer?, -- latched at the component's first scan
dct: buffer?,
act: buffer?,
dcTbl: number,
acTbl: number,
pred: number,
ctx: number,
}
type Frame = {
width: number,
height: number,
precision: number,
progressive: boolean,
arithmetic: boolean,
comps: { Comp },
hmax: number,
vmax: number,
mcusX: number,
mcusY: number,
}
local SOF_REFUSED = {
[0xC3] = "lossless",
[0xC5] = "hierarchical",
[0xC6] = "hierarchical",
[0xC7] = "hierarchical",
[0xCB] = "lossless arithmetic-coded",
[0xCD] = "hierarchical arithmetic-coded",
[0xCE] = "hierarchical arithmetic-coded",
[0xCF] = "hierarchical arithmetic-coded",
}
-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated"
local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?)
if e - p < 6 then
return nil, "corrupt", "short SOF"
end
local prec = readu8(b, p)
local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5)
if prec ~= 8 and prec ~= 12 then
return nil, "unsupported", "sample precision " .. prec
end
if width == 0 or height == 0 then
if height == 0 and width > 0 then
return nil, "unsupported", "DNL (height 0 in the frame header)"
end
return nil, "corrupt", "bad size " .. width .. "x" .. height
end
if nf ~= 1 and nf ~= 3 and nf ~= 4 then
return nil, "unsupported", "component count " .. nf
end
if e - p < 6 + nf * 3 then
return nil, "corrupt", "short SOF"
end
local comps = {}
local hmax, vmax = 1, 1
for i = 0, nf - 1 do
local q = p + 6 + i * 3
local hv = readu8(b, q + 1)
local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2)
if h < 1 or h > 4 or v < 1 or v > 4 then
return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v
end
if tq > 3 then
return nil, "corrupt", "bad quantisation table selector " .. tq
end
local id = readu8(b, q)
for _, c in comps do
if c.id == id then
return nil, "corrupt", "duplicate component id " .. id
end
end
hmax, vmax = math.max(hmax, h), math.max(vmax, v)
table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp)
end
local mcusX = math.ceil(width / (8 * hmax))
local mcusY = math.ceil(height / (8 * vmax))
for _, c in comps do
c.bpl = mcusX * c.h
c.bpc = mcusY * c.v
c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8)
c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8)
end
return {
width = width,
height = height,
precision = prec,
progressive = m == 0xC2 or m == 0xCA,
arithmetic = m == 0xC9 or m == 0xCA,
comps = comps,
hmax = hmax,
vmax = vmax,
mcusX = mcusX,
mcusY = mcusY,
}
end
local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string
local n = #frame.comps
if n == 1 then
return "gray"
elseif n == 3 then
if adobe ~= nil then
return if adobe == 0 then "rgb" else "ycbcr"
end
local c = frame.comps
if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then
return "rgb"
end
return "ycbcr"
end
return if adobe == 2 then "ycck" else "cmyk"
end
Decode.colorSpaceOf = colorSpaceOf
-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT
-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions).
local function idctSize(f: Frame, c: Comp, scale: number): number
local minSize = 8 // scale
local ssize = minSize
while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do
ssize *= 2
end
return ssize
end
export type State = {
frame: any,
adobe: number?,
jfif: boolean,
density: { unit: number, x: number, y: number }?,
orientation: number,
exif: buffer?,
icc: buffer?,
comments: { string },
truncated: boolean,
scale: number,
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
endPos: number, -- the byte after the EOI marker (or the end of the data)
}
-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with
-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients.
function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?)
if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then
return nil, "corrupt", "not a JPEG file (no SOI marker)"
end
local scale = (opts and opts.scale) or 1
if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then
return nil, "arg", "scale must be 1, 2, 4 or 8"
end
local maxPixels = (opts and opts.maxPixels) or 2 ^ 26
local quant: { [number]: buffer } = {}
local dcT: { [number]: buffer } = {}
local acT: { [number]: buffer } = {}
local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 }
local frame: Frame? = nil
local st: State = {
frame = nil,
adobe = nil,
jfif = false,
density = nil,
orientation = 1,
exif = nil,
icc = nil,
comments = {},
truncated = false,
scale = scale,
avi1 = nil,
endPos = n,
}
local iccChunks: { buffer } = {}
local ri = 0
local scans = 0
local clean: buffer? = nil
local rst = {}
local pos = base + 2
while pos < n do
-- find the next marker (tolerate garbage and fill bytes)
if readu8(b, pos) ~= 0xFF then
pos += 1
continue
end
while pos < n and readu8(b, pos) == 0xFF do
pos += 1
end
if pos >= n then
break
end
local m = readu8(b, pos)
pos += 1
if m == 0xD9 then
st.endPos = pos
break -- EOI
elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then
continue -- standalone markers (or stray stuffing)
end
if pos + 2 > n then
st.truncated = true
break
end
local len = be16(b, pos)
if len < 2 then
return nil, "corrupt", string.format("bad segment length for marker %02X", m)
end
local p, e = pos + 2, pos + len
if e > n then
if m == 0xDA and frame and not headerOnly then
e = n -- a truncated SOS header still fails below
else
st.truncated = true
break
end
end
pos = e
if m == 0xE0 then
if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
st.jfif = true
st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then
st.avi1 = readu8(b, p + 4)
end
elseif m == 0xE1 then
local t, o = exif(b, p, e)
if t and not st.exif then
local x = buffer.create(e - t)
buffer.copy(x, 0, b, t, e - t)
st.exif = x
end
if o then
st.orientation = o
end
elseif m == 0xE2 then
-- ICC_PROFILE\0, sequence number, count, data
if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then
local seq = readu8(b, p + 12)
local x = buffer.create(e - p - 14)
buffer.copy(x, 0, b, p + 14, e - p - 14)
if seq >= 1 then
iccChunks[seq] = x
end
end
elseif m == 0xEE then
if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then
st.adobe = readu8(b, p + 11)
end
elseif m == 0xFE then
table.insert(st.comments, buffer.readstring(b, p, e - p))
elseif m == 0xDB then
-- DQT
while p < e do
local pt = readu8(b, p)
local pq, tq = rshift(pt, 4), band(pt, 15)
local size = if pq == 0 then 64 else 128
if tq > 3 or pq > 1 or p + 1 + size > e then
return nil, "corrupt", "bad DQT segment"
end
local q = buffer.create(128)
for k = 0, 63 do
local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2)
buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v)
end
quant[tq] = q
p += 1 + size
end
elseif m == 0xC4 then
-- DHT
while p < e do
if p + 17 > e then
return nil, "corrupt", "bad DHT segment"
end
local tc = readu8(b, p)
local class, slot = rshift(tc, 4), band(tc, 15)
if class > 1 or slot > 3 then
return nil, "corrupt", "bad DHT table class / slot"
end
local counts, total = {}, 0
for l = 1, 16 do
counts[l] = readu8(b, p + l)
total += counts[l]
end
if total > 256 or p + 17 + total > e then
return nil, "corrupt", "bad DHT segment"
end
local syms = {}
for i = 1, total do
syms[i] = readu8(b, p + 16 + i)
end
local t = Scan.buildTable(counts, syms)
if class == 0 then
dcT[slot] = t
else
acT[slot] = t
end
p += 17 + total
end
elseif m == 0xCC then
-- DAC: arithmetic conditioning
while p + 2 <= e do
local tc, v = readu8(b, p), readu8(b, p + 1)
local class, slot = rshift(tc, 4), band(tc, 15)
if class > 1 or slot > 3 then
return nil, "corrupt", "bad DAC segment"
end
if class == 0 then
local L, U = band(v, 15), rshift(v, 4)
if L > U then
return nil, "corrupt", "bad DAC value"
end
dcL[slot + 1], dcU[slot + 1] = L, U
else
if v < 1 or v > 63 then
return nil, "corrupt", "bad DAC value"
end
acK[slot + 1] = v
end
p += 2
end
elseif m == 0xDD then
if e - p < 2 then
return nil, "corrupt", "bad DRI segment"
end
ri = be16(b, p)
elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then
if frame then
return nil, "corrupt", "more than one frame header"
end
local f, code, err = parseSof(b, p, e, m)
if not f then
return nil, code, err
end
if f.width * f.height > maxPixels then
return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels)
end
frame = f
st.frame = f
if headerOnly then
return st
end
elseif SOF_REFUSED[m] then
return nil, "unsupported", SOF_REFUSED[m] .. " JPEG"
elseif m == 0xDA then
if headerOnly then
break
end
if not frame then
return nil, "corrupt", "scan before the frame header"
end
local f = frame :: Frame
local ns = if p < e then readu8(b, p) else 0
if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then
return nil, "corrupt", "bad SOS segment"
end
local sc = {}
local blocks = 0
for i = 0, ns - 1 do
local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2)
local comp = nil
for _, c in f.comps do
if c.id == id then
comp = c
end
end
if not comp or table.find(sc, comp) then
return nil, "corrupt", "scan names an unknown component " .. id
end
local td, ta = rshift(t, 4), band(t, 15)
if td > 3 or ta > 3 then
return nil, "corrupt", "bad entropy table selector"
end
comp.dcTbl, comp.acTbl = td, ta
if not f.arithmetic then
comp.dct = dcT[td] or stdTable("dc", td)
comp.act = acT[ta] or stdTable("ac", ta)
end
blocks += comp.h * comp.v
table.insert(sc, comp)
end
local q = p + 1 + ns * 2
local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
local ah, al = rshift(a, 4), band(a, 15)
if ns > 1 and blocks > 10 then
return nil, "corrupt", "more than 10 blocks per MCU"
end
local mode
if not f.progressive then
mode = 0
ss, se, ah, al = 0, 63, 0, 0
else
if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then
return nil, "corrupt", "bad progressive scan parameters"
end
if ss == 0 then
mode = if ah == 0 then 1 else 2
else
mode = if ah == 0 then 3 else 4
end
end
for _, c in sc do
if not f.arithmetic then
if (mode == 0 or mode == 1) and not c.dct then
return nil, "corrupt", "missing DC Huffman table"
end
if (mode == 0 or mode == 3 or mode == 4) and not c.act then
return nil, "corrupt", "missing AC Huffman table"
end
end
if not c.coef then
c.coef = buffer.create(c.bpl * c.bpc * 128)
end
if not c.quant then
c.quant = quant[c.tq]
end
end
if not clean then
clean = buffer.create(n - base + Scan.PAD)
end
local cb = clean :: buffer
local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst)
if nextPos >= n then
st.truncated = true -- no EOI
end
-- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans
if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then
local params = {
comps = sc :: any,
mcusX = f.mcusX,
mcusY = f.mcusY,
ri = ri,
mode = mode,
ss = ss,
se = se,
al = al,
dcL = dcL,
dcU = dcU,
acK = acK,
}
local short
if f.arithmetic then
short = Arith.run(cb, cleanLen, rst, nrst, params)
else
local _
_, short = Scan.run(cb, cleanLen, rst, nrst, params)
end
st.truncated = st.truncated or short
end
scans += 1
pos = nextPos
end
end
if not frame then
return nil, if st.truncated then "truncated" else "corrupt", "no frame header"
end
if #iccChunks > 0 then
local total = 0
for _, c in iccChunks do
total += buffer.len(c)
end
local icc = buffer.create(total)
local o = 0
for _, c in iccChunks do
buffer.copy(icc, o, c)
o += buffer.len(c)
end
st.icc = icc
end
if headerOnly then
return st
end
if scans == 0 then
return nil, "truncated", "no image data"
end
return st
end
local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK }
local tableCache: { [number]: { buffer } } = {}
local function yccTables(maxv: number): { buffer }
local t = tableCache[maxv]
if not t then
local a, b, c, d = Color.tables(maxv)
t = { a, b, c, d }
tableCache[maxv] = t
end
return t
end
local toByte12: buffer? = nil
-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message
function Decode.output(st: State): (number?, any, any, string?)
local f: Frame = st.frame
local scale = st.scale
local minSize = 8 // scale
local maxv = if f.precision == 12 then 4095 else 255
local center = (maxv + 1) // 2
local p1 = if f.precision == 12 then 1 else 2
local outW = math.ceil(f.width * minSize / 8)
local outH = math.ceil(f.height * minSize / 8)
local fancy = minSize > 1
local ccomps = {}
local zeroQ = buffer.create(128)
for _, c in f.comps do
local ssize = idctSize(f, c, scale)
local stride, rows = c.bpl * ssize, c.bpc * ssize
local plane = buffer.create(stride * rows * 2)
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
local q = c.quant
if not q then
if c.coef then
return nil, "corrupt", "missing quantisation table " .. c.tq
end
q = zeroQ -- the component never appeared in a scan: mid grey
end
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv)
local hIn, hOut = c.h * ssize // minSize, f.hmax
local vIn, vOut = c.v * ssize // minSize, f.vmax
local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8))
local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8))
local method
if hIn == hOut and vIn == vOut then
method = Color.FULL
elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then
method = Color.H2V2
elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then
method = Color.H2V1
elseif hIn == hOut and vIn * 2 == vOut and fancy then
method = Color.H1V2
else
method = Color.REPLICATE
end
table.insert(ccomps, {
plane = plane,
stride = stride,
rows = rows,
downW = downW,
downH = downH,
method = method,
hIn = hIn,
hOut = hOut,
vIn = vIn,
vOut = vOut,
row = buffer.create((math.max(outW, 2 * stride) + 8) * 2),
})
c.coef = nil -- free the coefficients early
end
local space = colorSpaceOf(f, st.adobe, st.jfif)
local spaceId = SPACE_IDS[space]
if space == "cmyk" and st.adobe == nil then
spaceId = Color.CMYK_PLAIN
end
local t = yccTables(maxv)
local tb = nil
if maxv == 4095 then
if not toByte12 then
local tbuf = buffer.create(4096)
for v = 0, 4095 do
buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095)
end
toByte12 = tbuf
end
tb = toByte12
end
local pixels = buffer.create(outW * outH * 4)
Color.run({
comps = ccomps,
space = spaceId,
outW = outW,
outH = outH,
maxv = maxv,
pixels = pixels,
crr = t[1],
cbb = t[2],
crg = t[3],
cbg = t[4],
toByte = tb,
})
return outW, outH, pixels, space
end
-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the
-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion
-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half
-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma
-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray":
-- chroma 128). Full scale only (opts.scale = 1).
-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes
-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame
local scratch: buffer? = nil
local function scratchPlane(n: number): buffer
local sc = scratch
if sc and buffer.len(sc) >= n then
return sc
end
local b = buffer.create(n)
if n <= 4 * 1024 * 1024 then
scratch = b
end
return b
end
function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
local f: Frame = st.frame
if st.scale ~= 1 or f.precision ~= 8 then
return nil
end
local comps = f.comps
local space = colorSpaceOf(f, st.adobe, st.jfif)
local mode = nil
if space == "gray" then
mode = "gray"
elseif space == "ycbcr" then
-- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere)
local l, cb, cr = comps[1], comps[2], comps[3]
if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then
local rh, rv = f.hmax // cb.h, f.vmax // cb.v
if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then
mode = nil
elseif rh == 2 and rv == 2 then
mode = "420"
elseif rh == 2 and rv == 1 then
mode = "422"
elseif rh == 1 and rv == 1 then
mode = "444"
end
end
end
if not mode then
return nil
end
for _, c in comps do
if c.coef and not c.quant then
return nil -- output() reports the missing table
end
end
local w, h = f.width, f.height
local cw, ch = (w + 1) // 2, (h + 1) // 2
local out = buffer.create(w * h + 2 * cw * ch)
local zeroQ: buffer? = nil
for i, c in comps do
local stride, rows = c.bpl * 8, c.bpc * 8
local plane = scratchPlane(stride * rows * 2)
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
local q = c.quant
if not q then
zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey
q = zeroQ
end
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255)
if i == 1 then
Yuv.crop(plane, stride, w, h, out, 0)
elseif mode == "420" then
Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch)
elseif mode == "422" then
Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch)
else
Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch)
end
c.coef = nil
end
if mode == "gray" then
buffer.fill(out, w * h, 128, 2 * cw * ch)
end
return w, h, out, mode
end
return Decode
+899
View File
@@ -0,0 +1,899 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. It follows libjpeg-turbo's
-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c
-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication),
-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
local Dct = require("@formats/codecs/Dct")
local Tables = require("@formats/codecs/Jpeg/Tables")
local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
local band, countlz = bit32.band, bit32.countlz
local Encode = {}
-- natural order index of zigzag position k
local ZZ = buffer.create(64)
do
local i = 0
for s = 0, 14 do
local lo, hi = math.max(0, s - 7), math.min(s, 7)
if s % 2 == 0 then
for r = hi, lo, -1 do
writeu8(ZZ, i, r * 8 + (s - r))
i += 1
end
else
for r = lo, hi do
writeu8(ZZ, i, r * 8 + (s - r))
i += 1
end
end
end
end
Encode.ZIGZAG = ZZ
-- ------------------------------------------------------------------------------------------------ output
local OUT = buffer.create(0)
local OP = 0
local CAP = 0
local ACC, NB = 0, 0
local GATHER = false
local function grow(n: number)
if OP + n > CAP then
local c = math.max(CAP * 2, OP + n + 1024)
local nb = buffer.create(c)
buffer.copy(nb, 0, OUT, 0, OP)
OUT = nb
CAP = c
end
end
local function byte(v: number)
grow(1)
writeu8(OUT, OP, v)
OP += 1
end
local function u16be(v: number)
byte(v // 256)
byte(v % 256)
end
-- n bits of v (n <= 16), MSB first, with 0xFF stuffing
local function bits(v: number, n: number)
if GATHER or n == 0 then
return
end
local p = 2 ^ n
ACC = ACC * p + band(v, p - 1)
NB += n
while NB >= 8 do
NB -= 8
local d = 2 ^ NB
local b = ACC // d
ACC -= b * d
grow(2)
writeu8(OUT, OP, b)
OP += 1
if b == 0xFF then
writeu8(OUT, OP, 0)
OP += 1
end
end
end
local function flushBits()
if NB > 0 then
bits(0x7F, 8 - NB) -- pad with ones
end
ACC, NB = 0, 0
end
local function nbits(v: number): number
return if v == 0 then 0 else 32 - countlz(v)
end
-- ------------------------------------------------------------------------------------------------ Huffman tables
-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl)
export type Derived = { code: buffer, size: buffer }
local function derive(counts: { number }, symbols: { number }): Derived
local code, size = buffer.create(512), buffer.create(256)
local c, k = 0, 1
for l = 1, 16 do
for _ = 1, counts[l] or 0 do
local s = symbols[k]
if s then
writeu16(code, s * 2, c)
writeu8(size, s, l)
end
k += 1
c += 1
end
c *= 2
end
return { code = code, size = size }
end
-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols
local function optimal(freqIn: { number }): ({ number }, { number })
local freq = table.create(257, 0)
local bitsT = table.create(34, 0)
local codesize = table.create(257, 0)
local others = table.create(257, -1)
local nz = table.create(257, 0)
local n = 0
for i = 0, 256 do
local f = if i == 256 then 1 else freqIn[i + 1]
if f > 0 then
n += 1
nz[n] = i
freq[n] = f
end
end
while true do
local c1, c2 = -1, -1
local v, v2 = 1e9, 1e9
for i = 1, n do
local f = freq[i]
if f <= v2 then
if f <= v then
c2 = c1
v2 = v
v = f
c1 = i
else
v2 = f
c2 = i
end
end
end
if c2 < 0 then
break
end
freq[c1] += freq[c2]
freq[c2] = 1000000001
codesize[c1] += 1
while others[c1] >= 0 do
c1 = others[c1]
codesize[c1] += 1
end
others[c1] = c2
codesize[c2] += 1
while others[c2] >= 0 do
c2 = others[c2]
codesize[c2] += 1
end
end
for i = 1, n do
local cs = math.min(codesize[i], 32)
bitsT[cs + 1] += 1
end
local bitPos = table.create(34, 0)
local p = 0
for i = 1, 32 do
bitPos[i + 1] = p
p += bitsT[i + 1]
end
local i = 32
while i > 16 do
while bitsT[i + 1] > 0 do
local j = i - 2
while bitsT[j + 1] == 0 do
j -= 1
end
bitsT[i + 1] -= 2
bitsT[i] += 1
bitsT[j + 2] += 2
bitsT[j + 1] -= 1
end
i -= 1
end
while bitsT[i + 1] == 0 do
i -= 1
end
bitsT[i + 1] -= 1
local counts = table.create(16, 0)
for l = 1, 16 do
counts[l] = bitsT[l + 1]
end
local symbols = table.create(n, 0)
for k = 1, n - 1 do
local cs = math.min(codesize[k], 32)
symbols[bitPos[cs + 1] + 1] = nz[k]
bitPos[cs + 1] += 1
end
local total = 0
for l = 1, 16 do
total += counts[l]
end
local out = table.create(total, 0)
for k = 1, total do
out[k] = symbols[k]
end
return counts, out
end
Encode.optimal = optimal
-- ------------------------------------------------------------------------------------------------ entropy coding state
local dcTab: { Derived } = {}
local acTab: { Derived } = {}
local dcFreq: { { number } } = {}
local acFreq: { { number } } = {}
local function symbol(t: Derived, freq: { number }, s: number)
if GATHER then
freq[s + 1] += 1
else
bits(readu16(t.code, s * 2), readu8(t.size, s))
end
end
export type Comp = {
id: number,
h: number,
v: number,
tq: number,
td: number, -- DC table slot
ta: number, -- AC table slot
bw: number, -- real blocks across / down
bh: number,
bpl: number, -- MCU-padded block grid
bpc: number,
coef: buffer, -- i16, 64 per block, natural order
last: number, -- DC predictor
}
local function dcDiff(c: Comp, diff: number)
local t = diff
local t2 = diff
if t < 0 then
t = -t
t2 -= 1
end
local n = nbits(t)
symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n)
if n > 0 then
bits(t2, n)
end
end
-- jchuff.c encode_one_block
local function blockSeq(c: Comp, off: number)
local coef = c.coef
local dc = readi16(coef, off)
dcDiff(c, dc - c.last)
c.last = dc
local at, af = acTab[c.ta + 1], acFreq[c.ta + 1]
local r = 0
for k = 1, 63 do
local v = readi16(coef, off + readu8(ZZ, k) * 2)
if v == 0 then
r += 1
else
while r > 15 do
symbol(at, af, 0xF0)
r -= 16
end
local t, t2 = v, v
if t < 0 then
t = -t
t2 -= 1
end
local n = nbits(t)
symbol(at, af, r * 16 + n)
bits(t2, n)
r = 0
end
end
if r > 0 then
symbol(at, af, 0)
end
end
-- progressive state (jcphuff.c)
local EOBRUN = 0
local BE = 0
local CORR: { number } = table.create(1000, 0)
local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) }
local curAcFreq: { number } = {}
local function emitEobrun()
if EOBRUN > 0 then
local n = nbits(EOBRUN) - 1
symbol(curAc, curAcFreq, n * 16)
if n > 0 then
bits(EOBRUN, n)
end
EOBRUN = 0
if not GATHER then
for i = 1, BE do
bits(CORR[i], 1)
end
end
BE = 0
end
end
local function blockDcFirst(c: Comp, off: number, al: number)
local t2 = readi16(c.coef, off) // 2 ^ al
dcDiff(c, t2 - c.last)
c.last = t2
end
local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number)
local coef = c.coef
local d = 2 ^ al
local r = 0
for k = ss, se do
local v = readi16(coef, off + readu8(ZZ, k) * 2)
local t, t2
if v < 0 then
t = (-v) // d
t2 = -t - 1 -- ~t
else
t = v // d
t2 = t
end
if t == 0 then
r += 1
else
emitEobrun()
while r > 15 do
symbol(curAc, curAcFreq, 0xF0)
r -= 16
end
local n = nbits(t)
symbol(curAc, curAcFreq, r * 16 + n)
bits(t2, n)
r = 0
end
end
if r > 0 then
EOBRUN += 1
if EOBRUN == 0x7FFF then
emitEobrun()
end
end
end
local absv = table.create(64, 0)
local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number)
local coef = c.coef
local d = 2 ^ al
local eob = 0
for k = ss, se do
local v = readi16(coef, off + readu8(ZZ, k) * 2)
local t = (if v < 0 then -v else v) // d
absv[k + 1] = t
if t == 1 then
eob = k
end
end
local r = 0
local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..]
local brStart = BE
for k = ss, se do
local t = absv[k + 1]
if t == 0 then
r += 1
continue
end
while r > 15 and k <= eob do
emitEobrun()
symbol(curAc, curAcFreq, 0xF0)
r -= 16
if not GATHER then
for i = 1, br do
bits(CORR[brStart + i], 1)
end
end
brStart = 0
br = 0
end
if t > 1 then
br += 1
CORR[brStart + br] = t % 2
continue
end
emitEobrun()
symbol(curAc, curAcFreq, r * 16 + 1)
bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1)
if not GATHER then
for i = 1, br do
bits(CORR[brStart + i], 1)
end
end
brStart = 0
br = 0
r = 0
end
if r > 0 or br > 0 then
EOBRUN += 1
BE += br
if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then
emitEobrun()
end
end
end
-- ------------------------------------------------------------------------------------------------ scans
export type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number }
-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0
local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ())
local nc = #comps
local units, ux
if nc == 1 then
ux = comps[1].bw
units = ux * comps[1].bh
else
ux = mcusX
units = ux * mcusY
end
local rn = 0
for u = 0, units - 1 do
if ri > 0 and u > 0 and u % ri == 0 then
onRestart(rn)
rn = (rn + 1) % 8
end
local my, mx = u // ux, u % ux
for ci = 1, nc do
local c = comps[ci]
if nc == 1 then
fn(c, (my * c.bpl + mx) * 128)
else
for by = my * c.v, my * c.v + c.v - 1 do
for bx = mx * c.h, mx * c.h + c.h - 1 do
fn(c, (by * c.bpl + bx) * 128)
end
end
end
end
end
end
local function dht(class: number, slot: number, counts: { number }, symbols: { number })
byte(0xFF)
byte(0xC4)
u16be(2 + 17 + #symbols)
byte(class * 16 + slot)
for l = 1, 16 do
byte(counts[l])
end
for _, s in symbols do
byte(s)
end
end
local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean)
byte(0xFF)
byte(0xDA)
u16be(6 + 2 * #comps)
byte(#comps)
for _, c in comps do
byte(c.id)
local td = if acOnly then 0 else c.td
local ta = if dcOnly then 0 else c.ta
byte(td * 16 + ta)
end
byte(ss)
byte(se)
byte(ah * 16 + al)
end
-- ------------------------------------------------------------------------------------------------ planes
-- jccolor.c rgb_ycc_start tables (16-bit fixed point)
local function fix(x: number): number
return math.floor(x * 65536 + 0.5)
end
local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400)
local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5)
local CRG, CRB = fix(0.41869), fix(0.08131)
local OFF = 128 * 65536 + 32768 - 1
-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output)
local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?)
local n = w * h
local Y = buffer.create(n)
if bpp == 1 then
buffer.copy(Y, 0, px, 0, n)
if gray then
return Y, nil, nil
end
local Cb = buffer.create(n)
buffer.fill(Cb, 0, 128, n)
local Cr = buffer.create(n)
buffer.fill(Cr, 0, 128, n)
return Y, Cb, Cr
end
if gray then
for i = 0, n - 1 do
local o = i * bpp
local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
end
return Y, nil, nil
end
local Cb, Cr = buffer.create(n), buffer.create(n)
for i = 0, n - 1 do
local o = i * bpp
local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536)
writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536)
end
return Y, Cb, Cr
end
-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf
-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row
local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer
local out = buffer.create(outW * outH)
for oy = 0, outH - 1 do
local r0 = math.min(oy * vf, h - 1) * w
local r1 = math.min(oy * vf + vf - 1, h - 1) * w
local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0)
for ox = 0, outW - 1 do
local x0 = math.min(ox * hf, w - 1)
local x1 = math.min(ox * hf + hf - 1, w - 1)
local v
if hf == 2 and vf == 2 then
v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4
bias = 3 - bias
elseif hf == 2 then
v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2
bias = 1 - bias
else
v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2
bias = 1 - bias
end
writeu8(out, oy * outW + ox, v)
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ encode
export type Options = {
quality: number, -- 1..100
sampling: string, -- "444" | "422" | "420"
progressive: boolean,
optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises)
gray: boolean,
restart: number, -- MCUs per restart interval (0 = none)
segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header
jfif: boolean,
density: { unit: number, x: number, y: number }?,
}
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0:
-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The
-- caller validated sizes (1..65535), the buffer length and options.
function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
OUT = buffer.create(math.max(1024, w * h // 2))
CAP = buffer.len(OUT)
OP = 0
ACC, NB = 0, 0
GATHER = false
EOBRUN, BE = 0, 0
local yuv = bpp == 0
local Y, Cb, Cr
if yuv then
local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2)
Y = px
if not o.gray then
Cb, Cr = buffer.create(cn), buffer.create(cn)
buffer.copy(Cb :: buffer, 0, px, n, cn)
buffer.copy(Cr :: buffer, 0, px, n + cn, cn)
end
else
Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
end
local hs, vs = 1, 1
if not o.gray then
if o.sampling == "420" then
hs, vs = 2, 2
elseif o.sampling == "422" then
hs, vs = 2, 1
end
end
local mcusX = math.ceil(w / (8 * hs))
local mcusY = math.ceil(h / (8 * vs))
local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) }
local qdiv = {}
for t = 1, 2 do
local b = buffer.create(128)
for i = 1, 64 do
writeu16(b, (i - 1) * 2, qt[t][i])
end
qdiv[t] = b
end
-- components and their quantised coefficients
local comps: { Comp } = {}
local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer }
for i, src in srcs do
local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1
local cw = math.ceil(w * ch / hs)
local chh = math.ceil(h * cv / vs)
local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
local bpl, bpc = mcusX * ch, mcusY * cv
local plane, pw, ph = src, w, h
if yuv and i > 1 then
pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does
elseif ch < hs or cv < vs then
pw, ph = bw * 8, chh
plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
end
local coef = buffer.create(bpl * bpc * 128)
local c: Comp = {
id = i,
h = ch,
v = cv,
tq = if i == 1 then 0 else 1,
td = if i == 1 then 0 else 1,
ta = if i == 1 then 0 else 1,
bw = bw,
bh = bh,
bpl = bpl,
bpc = bpc,
coef = coef,
last = 0,
}
local div = qdiv[c.tq + 1]
for by = 0, bpc - 1 do
for bx = 0, bpl - 1 do
local off = (by * bpl + bx) * 128
if by < bh and bx < bw then
Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off)
elseif by < bh then
writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC
else
-- bottom: the DC of the MCU's last block in the row above
local lb = (bx // ch) * ch + ch - 1
writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128))
end
end
end
comps[i] = c
end
-- headers
byte(0xFF)
byte(0xD8)
if o.jfif then
local d = o.density or { unit = 0, x = 1, y = 1 }
byte(0xFF)
byte(0xE0)
u16be(16)
for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do
byte(ch)
end
byte(1)
byte(1)
byte(d.unit)
u16be(d.x)
u16be(d.y)
byte(0)
byte(0)
end
for _, s in o.segments do
local n = buffer.len(s.data)
byte(0xFF)
byte(s.marker)
u16be(n + 2)
grow(n)
buffer.copy(OUT, OP, s.data, 0, n)
OP += n
end
for t = 1, (if o.gray then 1 else 2) do
byte(0xFF)
byte(0xDB)
u16be(67)
byte(t - 1)
for k = 0, 63 do
byte(qt[t][readu8(ZZ, k) + 1])
end
end
byte(0xFF)
byte(if o.progressive then 0xC2 else 0xC0)
u16be(8 + 3 * #comps)
byte(8)
u16be(h)
u16be(w)
byte(#comps)
for _, c in comps do
byte(c.id)
byte(c.h * 16 + c.v)
byte(c.tq)
end
local ntab = if o.gray then 1 else 2
local function restartMarker(n: number)
flushBits()
byte(0xFF)
byte(0xD0 + n)
end
if not o.progressive then
if o.optimize then
GATHER = true
for t = 1, ntab do
dcFreq[t] = table.create(257, 0)
acFreq[t] = table.create(257, 0)
end
for _, c in comps do
c.last = 0
end
walk(comps, mcusX, mcusY, o.restart, function()
for _, c in comps do
c.last = 0
end
end, blockSeq)
GATHER = false
end
for t = 1, ntab do
local dcC, dcS, acC, acS
if o.optimize then
dcC, dcS = optimal(dcFreq[t])
acC, acS = optimal(acFreq[t])
else
local d, a = Tables.DC[t], Tables.AC[t]
dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols
end
dcTab[t] = derive(dcC, dcS)
acTab[t] = derive(acC, acS)
dcFreq[t] = table.create(257, 0)
acFreq[t] = table.create(257, 0)
-- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1
dht(0, t - 1, dcC, dcS)
dht(1, t - 1, acC, acS)
end
if o.restart > 0 then
byte(0xFF)
byte(0xDD)
u16be(4)
u16be(o.restart)
end
sos(comps, 0, 63, 0, 0, false, false)
for _, c in comps do
c.last = 0
end
walk(comps, mcusX, mcusY, o.restart, function(n: number)
restartMarker(n)
for _, c in comps do
c.last = 0
end
end, blockSeq)
flushBits()
else
local script: { ScanSpec }
if o.gray then
script = {
{ comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 },
{ comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
{ comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
{ comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
{ comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 },
{ comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
}
else
script = {
{ comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 },
{ comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
{ comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 },
{ comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 },
{ comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
{ comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
{ comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 },
{ comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 },
{ comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 },
{ comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
}
end
local driSent = false
for _, sc in script do
local sComps = {}
for _, ci in sc.comps do
table.insert(sComps, comps[ci])
end
local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al
local isDc = ss == 0
local blockFn: (Comp, number) -> ()
if isDc and ah == 0 then
blockFn = function(c: Comp, off: number)
blockDcFirst(c, off, al)
end
elseif isDc then
blockFn = function(c: Comp, off: number)
bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1)
end
elseif ah == 0 then
blockFn = function(c: Comp, off: number)
blockAcFirst(c, off, ss, se, al)
end
else
blockFn = function(c: Comp, off: number)
blockAcRefine(c, off, ss, se, al)
end
end
local function onRestart(n: number)
emitEobrun()
if not GATHER then
restartMarker(n)
end
for _, c in sComps do
c.last = 0
end
EOBRUN, BE = 0, 0
end
local function pass()
for _, c in sComps do
c.last = 0
end
EOBRUN, BE = 0, 0
walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn)
emitEobrun()
end
-- gather statistics, then emit the optimal tables this scan uses
if not (isDc and ah > 0) then
GATHER = true
for t = 1, ntab do
dcFreq[t] = table.create(257, 0)
acFreq[t] = table.create(257, 0)
end
if not isDc then
curAcFreq = acFreq[sComps[1].ta + 1]
end
pass()
GATHER = false
local sent = {}
for _, c in sComps do
local slot = if isDc then c.td else c.ta
if not sent[slot] then
sent[slot] = true
local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1])
dht(if isDc then 0 else 1, slot, counts, syms)
if isDc then
dcTab[slot + 1] = derive(counts, syms)
else
acTab[slot + 1] = derive(counts, syms)
end
end
end
if not isDc then
curAc = acTab[sComps[1].ta + 1]
end
end
if o.restart > 0 and not driSent then
driSent = true
byte(0xFF)
byte(0xDD)
u16be(4)
u16be(o.restart)
end
sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg)
pass()
flushBits()
end
end
byte(0xFF)
byte(0xD9)
local res = buffer.create(OP)
buffer.copy(res, 0, OUT, 0, OP)
OUT = buffer.create(0)
CAP = 0
return res
end
return Encode
+456
View File
@@ -0,0 +1,456 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
--
-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least
-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a
-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser)
-- can consume PAD bytes. So every buffer index stays in range, even on garbage data.
--
-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it.
-- Huffman tables (built by `buildTable`) are buffers:
-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code
-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits
-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l]
-- [1168, 1424) symbols
-- [1424, 1426) symbol count
-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code
-- and its extra bits fit in 9 bits (0 otherwise)
local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16
local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16
local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap
local Scan = {}
Scan.PAD = 4096
Scan.TABLE_SIZE = 3476
local T_MAX = 1024
local T_DELTA = 1096
local T_VAL = 1168
local T_COUNT = 1424
local T_FASTAC = 1428
-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range
local ZZ = buffer.create(80)
do
local i = 0
for s = 0, 14 do
local lo, hi = math.max(0, s - 7), math.min(s, 7)
if s % 2 == 0 then
for r = hi, lo, -1 do
writeu8(ZZ, i, r * 8 + (s - r))
i += 1
end
else
for r = lo, hi do
writeu8(ZZ, i, r * 8 + (s - r))
i += 1
end
end
end
for j = 64, 79 do
writeu8(ZZ, j, 63)
end
end
Scan.ZIGZAG = ZZ
-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An
-- over-subscribed table keeps the codes that fit; the rest decode as invalid.
function Scan.buildTable(counts: { number }, symbols: { number }): buffer
local t = buffer.create(Scan.TABLE_SIZE)
local code, k = 0, 0
local nsym = #symbols
local codes, sizes = {}, {}
local broken = false
for l = 1, 16 do
writei32(t, T_DELTA + l * 4, k - code)
local n = counts[l] or 0
for _ = 1, n do
if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then
broken = true
break
end
k += 1
codes[k] = code
sizes[k] = l
code += 1
end
writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l))
code *= 2
end
writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF)
for i = 1, k do
writeu8(t, T_VAL + i - 1, symbols[i])
end
writeu16(t, T_COUNT, k)
-- fast lookups
for i = 1, k do
local l = sizes[i]
if l <= 9 then
local sym = symbols[i]
local base = lshift(codes[i], 9 - l)
for j = 0, lshift(1, 9 - l) - 1 do
local idx = base + j
writeu16(t, idx * 2, l * 256 + sym)
local r, s = rshift(sym, 4), band(sym, 15)
if s ~= 0 and l + s <= 9 then
local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1)
if v < lshift(1, s - 1) then
v = v - lshift(1, s) + 1
end
writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s)
end
end
end
end
return t
end
-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed,
-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n),
-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed.
function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number)
local o, nr = 0, 0
while pos < n do
local b = readu8(src, pos)
if b ~= 0xFF then
writeu8(dst, o, b)
o += 1
pos += 1
else
local q = pos + 1
while q < n and readu8(src, q) == 0xFF do
q += 1
end
if q >= n then
pos = n
break
end
local m = readu8(src, q)
if m == 0 then
writeu8(dst, o, 0xFF)
o += 1
pos = q + 1
elseif m >= 0xD0 and m <= 0xD7 then
nr += 1
rst[nr] = o
pos = q + 1
else
pos = q - 1
break
end
end
end
buffer.fill(dst, o, 0, Scan.PAD)
return pos, o, nr
end
local function huff(d: buffer, pos: number, t: buffer): (number, number)
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
local f = readu16(t, rshift(w, 23) * 2)
if f ~= 0 then
return band(f, 255), pos + rshift(f, 8)
end
local c = rshift(w, 16)
local l = 10
while c >= readu32(t, T_MAX + l * 4) do
l += 1
end
if l > 16 then
return 0, pos + 16 -- invalid code
end
local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4)
if idx < 0 or idx >= readu16(t, T_COUNT) then
return 0, pos + l
end
return readu8(t, T_VAL + idx), pos + l
end
-- the next s bits (1 <= s <= 16) as an unsigned number
local function bits(d: buffer, pos: number, s: number): number
return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s)
end
local function extend(v: number, s: number): number
if v < lshift(1, s - 1) then
return v - lshift(1, s) + 1
end
return v
end
-- sequential (baseline / extended) block: returns pos, DC predictor
local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number)
local s
s, pos = huff(d, pos, dct)
if s ~= 0 then
if s > 16 then
s = 16
end
pred += extend(bits(d, pos, s), s)
pos += s
end
writei16(coef, off, pred)
local k = 1
while k < 64 do
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
if fa ~= 0 then
local low = fa % 256
k += low // 16
pos += low % 16
if k > 63 then
break
end
writei16(coef, off + readu8(ZZ, k) * 2, fa // 256)
k += 1
else
local rs
rs, pos = huff(d, pos, act)
local r, sz = rshift(rs, 4), band(rs, 15)
if sz == 0 then
if r ~= 15 then
break
end
k += 16
else
k += r
if k > 63 then
break
end
writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz))
pos += sz
k += 1
end
end
end
return pos, pred
end
local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number)
local s
s, pos = huff(d, pos, dct)
if s ~= 0 then
if s > 16 then
s = 16
end
pred += extend(bits(d, pos, s), s)
pos += s
end
writei16(coef, off, pred * lshift(1, al))
return pos, pred
end
local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
if eobrun > 0 then
return pos, eobrun - 1
end
local mul = lshift(1, al)
local k = ss
while k <= se do
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
if fa ~= 0 then
local low = fa % 256
k += low // 16
pos += low % 16
if k > se then
break
end
writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul)
k += 1
else
local rs
rs, pos = huff(d, pos, act)
local r, s = rshift(rs, 4), band(rs, 15)
if s == 0 then
if r < 15 then
eobrun = lshift(1, r) - 1
if r > 0 then
eobrun += bits(d, pos, r)
pos += r
end
break
end
k += 16
else
k += r
if k > se then
break
end
writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul)
pos += s
k += 1
end
end
end
return pos, eobrun
end
-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine)
local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
local bit = lshift(1, al)
if eobrun > 0 then
for k = ss, se do
local o = off + readu8(ZZ, k) * 2
local p = readi16(coef, o)
if p ~= 0 then
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
pos += 1
if b ~= 0 and band(p, bit) == 0 then
writei16(coef, o, if p > 0 then p + bit else p - bit)
end
end
end
return pos, eobrun - 1
end
local k = ss
while k <= se do
local rs
rs, pos = huff(d, pos, act)
local s, r = band(rs, 15), rshift(rs, 4)
local val = 0
if s == 0 then
if r < 15 then
eobrun = lshift(1, r) - 1
if r > 0 then
eobrun += bits(d, pos, r)
pos += r
end
r = 64 -- the rest of the block only refines
end
else
-- s must be 1; anything else is corrupt and treated as 1
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
pos += 1
val = if b ~= 0 then bit else -bit
end
while k <= se do
local o = off + readu8(ZZ, k) * 2
k += 1
local p = readi16(coef, o)
if p ~= 0 then
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
pos += 1
if b ~= 0 and band(p, bit) == 0 then
writei16(coef, o, if p > 0 then p + bit else p - bit)
end
else
if r == 0 then
if val ~= 0 then
writei16(coef, o, val)
end
break
end
r -= 1
end
end
end
-- an EOB run that started in this block counts it already (eobrun = run length - 1)
return pos, eobrun
end
export type ScanComp = {
coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid
bpl: number,
h: number,
v: number,
bw: number, -- blocks across / down the component itself (non-interleaved scans)
bh: number,
dct: buffer?,
act: buffer?,
pred: number,
}
export type ScanParams = {
comps: { ScanComp },
mcusX: number,
mcusY: number,
ri: number, -- restart interval in MCUs (0 = none)
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
ss: number,
se: number,
al: number,
}
-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and
-- whether the data ran out (or overran) before the last MCU.
function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean)
local comps = P.comps
local nc = #comps
local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri
local endBits = cleanLen * 8
local units, ux
if nc == 1 then
ux = comps[1].bw
units = ux * comps[1].bh
else
ux = P.mcusX
units = ux * P.mcusY
end
for i = 1, nc do
comps[i].pred = 0
end
local pos, eobrun, rstIdx = 0, 0, 0
local truncated, skipping = false, false
local bit = lshift(1, al)
for u = 0, units - 1 do
if ri > 0 and u > 0 and u % ri == 0 then
rstIdx += 1
if rstIdx <= nrst then
pos = rst[rstIdx] * 8
skipping = false
end
for i = 1, nc do
comps[i].pred = 0
end
eobrun = 0
end
if pos > endBits then
truncated = true
if ri == 0 or rstIdx >= nrst then
break
end
skipping = true
end
if not skipping then
local my, mx = u // ux, u % ux
for ci = 1, nc do
local c = comps[ci]
local bh, bw, by0, bx0
if nc == 1 then
bh, bw, by0, bx0 = 1, 1, my, mx
else
bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
end
local coef, bpl = c.coef, c.bpl
for by = by0, by0 + bh - 1 do
for bx = bx0, bx0 + bw - 1 do
local off = (by * bpl + bx) * 128
if mode == 0 then
pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred)
elseif mode == 1 then
pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al)
elseif mode == 2 then
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
pos += 1
if b ~= 0 then
writei16(coef, off, bor(readi16(coef, off), bit))
end
elseif mode == 3 then
pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
else
pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
end
end
end
end
end
end
return pos, truncated
end
return Scan
+77
View File
@@ -0,0 +1,77 @@
--!strict
-- codecs/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
local Tables = {}
local function range(t: { number }, a: number, b: number)
for v = a, b do
table.insert(t, v)
end
end
-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2]
local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }
local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }
local dcv = {}
range(dcv, 0, 11)
local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }
local aclv = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a,
}
range(aclv, 0x34, 0x3a)
for hi = 4, 8 do
range(aclv, hi * 16 + 3, hi * 16 + 10)
end
for hi = 9, 13 do
range(aclv, hi * 16 + 2, hi * 16 + 10)
end
range(aclv, 0xe1, 0xea)
range(aclv, 0xf1, 0xfa)
local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }
local accv = {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a,
}
range(accv, 0x35, 0x3a)
for hi = 4, 7 do
range(accv, hi * 16 + 3, hi * 16 + 10)
end
for hi = 8, 14 do
range(accv, hi * 16 + 2, hi * 16 + 10)
end
range(accv, 0xf2, 0xfa)
export type Spec = { counts: { number }, symbols: { number } }
Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec }
Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec }
-- K.1, natural (row-major) order
Tables.LUMA = {
16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29,
51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121,
120, 101, 72, 92, 95, 98, 112, 100, 103, 99,
}
Tables.CHROMA = {
17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
}
-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline)
function Tables.quant(base: { number }, quality: number): { number }
local q = math.clamp(math.floor(quality), 1, 100)
local scale = if q < 50 then 5000 // q else 200 - q * 2
local out = table.create(64, 1)
for i = 1, 64 do
out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255)
end
return out
end
return Tables
+76
View File
@@ -0,0 +1,76 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4
-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG).
-- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes.
local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32
local Yuv = {}
-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8
-- samples at dst[doff], w per row
function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
local quads = w // 4
local rest = w - quads * 4
for y = 0, h - 1 do
local s = y * stride * 2
local d = doff + y * w
-- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write
for _ = 1, quads do
local a, b = readu32(src, s), readu32(src, s + 4)
writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216)
s += 8
d += 4
end
for k = 0, rest - 1 do
writeu8(dst, d + k, readu16(src, s + k * 2))
end
end
end
-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output
-- row the rounded mean of two source rows (the last row alone when h is odd)
function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
local oh = (h + 1) // 2
for y = 0, oh - 1 do
local a = 2 * y * stride * 2
local b = if 2 * y + 1 < h then a + stride * 2 else a
local d = doff + y * w
for x = 0, w - 1 do
writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2)
end
end
end
-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2),
-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column)
function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
local ow, oh = (w + 1) // 2, (h + 1) // 2
for y = 0, oh - 1 do
local a = 2 * y * stride * 2
local b = if 2 * y + 1 < h then a + stride * 2 else a
local d = doff + y * ow
for x = 0, ow - 1 do
local x0 = 2 * x * 2
local x1 = if 2 * x + 1 < w then x0 + 2 else x0
writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4)
end
end
end
-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field
-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2)
function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number)
for y = 0, rows - 1 do
local k = y // 2
if y % 2 == 0 then
buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes)
else
buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes)
end
end
end
return Yuv
+387
View File
@@ -0,0 +1,387 @@
--!strict
-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and
-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's
-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
--
-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image
-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes
-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer
-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header
--
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation
-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go
-- (meta.truncated = true).
-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field
-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame
-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even
-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field
-- leaves the first field alone (meta.source.fields = 1).
-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour
-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera
-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other
-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format).
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments
-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion).
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding.
-- Never throws: bad data or arguments return nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/Jpeg/Decode")
local Encode = require("@formats/codecs/Jpeg/Encode")
local Yuv = require("@formats/codecs/Jpeg/Yuv")
local Jpeg = {}
export type DecodeOptions = {
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8)
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0)
progressive: boolean?, -- default false
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
gray: boolean?, -- a one-component file (default: true for gray8 images)
restart: number?, -- restart interval in MCUs (default 0 = none)
jfif: boolean?, -- write the JFIF APP0 header (default true)
density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1)
segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header
}
export type Info = {
width: number,
height: number,
components: number,
progressive: boolean,
arithmetic: boolean,
precision: number,
colorSpace: string,
sampling: { { number } }, -- { h, v } per component
orientation: number,
adobe: number?,
jfif: boolean,
avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header
}
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
local function range(buf: buffer, off: number?, len: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(math.floor(tonumber(off) or 0), 0, n)
return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o)
end
-- the marker parser over [o, o + l): State | nil, Err
local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
end
if not st then
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o)
end
return st, nil
end
local function samplingOf(f: any): { { number } }
local sampling = {}
for _, c in f.comps do
table.insert(sampling, { c.h, c.v })
end
return sampling
end
-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header)
function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected a buffer")
end
local o, l = range(buf, off, len)
local st, err = parse(buf, o, l, nil, true)
if not st then
return nil, err
end
local f = st.frame
return {
width = f.width,
height = f.height,
components = #f.comps,
progressive = f.progressive,
arithmetic = f.arithmetic,
precision = f.precision,
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
sampling = samplingOf(f),
orientation = st.orientation,
adobe = st.adobe,
jfif = st.jfif,
avi1 = st.avi1,
},
nil
end
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
if o <= 1 or o > 8 then
return px, w, h
end
local swap = o >= 5
local ow, oh = if swap then h else w, if swap then w else h
local out = buffer.create(ow * oh * 4)
local readu32, writeu32 = buffer.readu32, buffer.writeu32
for y = 0, oh - 1 do
for x = 0, ow - 1 do
local col, row
if o == 2 then
col, row = w - 1 - x, y
elseif o == 3 then
col, row = w - 1 - x, h - 1 - y
elseif o == 4 then
col, row = x, h - 1 - y
elseif o == 5 then
col, row = y, x
elseif o == 6 then
col, row = y, h - 1 - x
elseif o == 7 then
col, row = w - 1 - y, h - 1 - x
else
col, row = w - 1 - y, x
end
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
end
end
return out, ow, oh
end
-- one JPEG at [o, o + l): Image, State | nil, Err
local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any)
local st, err = parse(buf, o, l, opts, false)
if not st then
return nil, err
end
local s = st :: Decode.State
local img = Types.Image.new(0, 0)
local space, mode = nil, nil
if opts and opts.yuv then
local ok, w, h, px, m = pcall(Decode.outputYuv, s)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
end
if w then
img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p"
mode = m
space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif)
end
end
if not mode then
local ok, w, h, px, sp = pcall(Decode.output, s)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
end
if not w then
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o)
end
space = sp
if opts and opts.orient then
px, w, h = orient(px, w, h, s.orientation)
end
img.width, img.height, img.pixels = w, h, px
if opts and opts.native and space == "gray" then
local g = buffer.create(w * h)
for i = 0, w * h - 1 do
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
end
img.pixels, img.format = g, "gray8"
end
end
local f = s.frame
local meta = img.meta
meta.orientation = s.orientation
meta.oriented = (opts and opts.orient and not mode) or false
meta.exif = s.exif
meta.icc = s.icc
if #s.comments > 0 then
meta.text = { comment = table.concat(s.comments, "\n") }
end
if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then
local k = if s.density.unit == 2 then 2.54 else 1
meta.dpi = { x = s.density.x * k, y = s.density.y * k }
end
meta.truncated = s.truncated
meta.source = {
format = "jpeg",
bitDepth = f.precision,
colorType = space,
components = #f.comps,
progressive = f.progressive,
arithmetic = f.arithmetic,
sampling = samplingOf(f),
scale = s.scale,
adobe = s.adobe,
jfif = s.jfif,
avi1 = s.avi1,
yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv)
range = if mode then "full" else nil,
fields = 1,
}
return img, s
end
-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none
local function nextSoi(buf: buffer, p: number, e: number): number
local readu8 = buffer.readu8
while p + 3 <= e do
if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then
return p
end
p += 1
end
return -1
end
-- two fields (same size and format) -> one frame of twice the height, field a on the even rows
local function weave(a: Types.Image, b: Types.Image): Types.Image
local w, hf = a.width, a.height
local h = hf * 2
local out = Types.Image.new(w, h, a.format)
local dst = out.pixels
if a.format == "yuv420p" then
local cw, chf = (w + 1) // 2, (hf + 1) // 2
local ch = (h + 1) // 2 -- = hf
Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0)
for k = 0, 1 do
Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch)
end
else
local bpp = Types.Image.bpp(a.format) or 4
Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0)
end
out.meta = a.meta
return out
end
-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len)
function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected a buffer")
end
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
local o, l = range(buf, off, len)
local img, st = decodeOne(buf, o, l, opts)
if not img then
return nil, st
end
local s = st :: Decode.State
local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2)
if wantFields and not (opts and opts.orient) then
local e = o + l
local p = nextSoi(buf, s.endPos, e)
if p >= 0 then
local o2 = table.clone(opts or {}) :: any
if o2.maxPixels then
o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height)
end
local b = decodeOne(buf, p, e - p, o2)
if b and b.width == img.width and b.height == img.height and b.format == img.format then
local truncated = img.meta.truncated or b.meta.truncated
img = weave(img, b)
img.meta.truncated = truncated
local source: any = img.meta.source
source.fields = 2
end
end
end
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 }
-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local bpp = BPP[img.format]
if not bpp then
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")")
end
local w, h = img.width, img.height
local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
end
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
local o: any = opts or {}
local quality = o.quality or 90
if type(quality) ~= "number" or quality < 1 or quality > 100 then
return nil, Err.new(Err.ARG, "quality must be 1..100")
end
local sub = o.subsampling or "420"
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
end
if bpp == 0 then
sub = "420"
end
local restart = o.restart or 0
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
end
local gray = o.gray
if gray == nil then
gray = img.format == "gray8"
end
local segments = {}
if o.segments ~= nil then
if type(o.segments) ~= "table" then
return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }")
end
for _, sg in o.segments do
if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then
return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)")
end
if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then
return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)")
end
table.insert(segments, sg)
end
end
local density = o.density
if density ~= nil then
if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then
return nil, Err.new(Err.ARG, "bad density")
end
density = {
unit = math.clamp(math.floor(density.unit), 0, 2),
x = math.clamp(math.floor(density.x), 1, 65535),
y = math.clamp(math.floor(density.y), 1, 65535),
}
end
local out = Encode.run(img.pixels, w, h, bpp, {
quality = quality,
sampling = sub,
progressive = o.progressive == true,
optimize = o.optimize == true,
gray = gray,
restart = restart,
segments = segments,
jfif = o.jfif ~= false,
density = density,
})
return out, nil
end
return Jpeg
+211
View File
@@ -0,0 +1,211 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK /
-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code).
-- Data are separate real / imaginary arrays, 1-based. Never throws.
local Fft = {}
export type Plan = {
n: number,
factors: { number },
-- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1]
twr: { { number } },
twi: { { number } },
-- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1
rr: { { number } },
ri: { { number } },
sre: { number }, -- scratch
sim: { number },
}
local cos, sin, pi = math.cos, math.sin, math.pi
-- new(n) -> Plan | nil (n < 1 or not an integer)
function Fft.new(n: number): Plan?
if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then
return nil
end
local factors = {}
local m = n
while m % 4 == 0 do
table.insert(factors, 4)
m //= 4
end
while m % 2 == 0 do
table.insert(factors, 2)
m //= 2
end
local f = 3
while m > 1 do
while m % f == 0 do
table.insert(factors, f)
m //= f
end
f += 2
if f * f > m and m > 1 then
table.insert(factors, m)
m = 1
end
end
local twr, twi, rr, ri = {}, {}, {}, {}
local l1 = 1
for k, p in factors do
local ido = n // (l1 * p)
local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0)
for u = 1, p - 1 do
for i = 0, ido - 1 do
local a = -2 * pi * u * i * l1 / n
tr[(u - 1) * ido + i + 1] = cos(a)
ti[(u - 1) * ido + i + 1] = sin(a)
end
end
twr[k], twi[k] = tr, ti
local cr, ci = table.create(p, 0), table.create(p, 0)
for j = 0, p - 1 do
cr[j + 1] = cos(-2 * pi * j / p)
ci[j + 1] = sin(-2 * pi * j / p)
end
rr[k], ri[k] = cr, ci
l1 *= p
end
return {
n = n,
factors = factors,
twr = twr,
twi = twi,
rr = rr,
ri = ri,
sre = table.create(n, 0),
sim = table.create(n, 0),
}
end
-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)]
local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number })
local lp = ido * l1
if p == 4 then
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * 4 * k
local a0r, a0i = ar[s], ai[s]
local a1r, a1i = ar[s + ido], ai[s + ido]
local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido]
local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido]
local t0r, t0i = a0r + a2r, a0i + a2i
local t1r, t1i = a0r - a2r, a0i - a2i
local t2r, t2i = a1r + a3r, a1i + a3i
local t3r, t3i = a1r - a3r, a1i - a3i
local d = 1 + i + ido * k
br[d], bi[d] = t0r + t2r, t0i + t2i
local y1r, y1i = t1r + t3i, t1i - t3r
local y2r, y2i = t0r - t2r, t0i - t2i
local y3r, y3i = t1r - t3i, t1i + t3r
if i == 0 then
br[d + lp], bi[d + lp] = y1r, y1i
br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i
br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i
else
local w1r, w1i = tr[i + 1], ti[i + 1]
local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1]
local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1]
br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r
br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r
br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r
end
end
end
elseif p == 2 then
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * 2 * k
local a0r, a0i = ar[s], ai[s]
local a1r, a1i = ar[s + ido], ai[s + ido]
local d = 1 + i + ido * k
br[d], bi[d] = a0r + a1r, a0i + a1i
local yr, yi = a0r - a1r, a0i - a1i
if i == 0 then
br[d + lp], bi[d + lp] = yr, yi
else
local wr, wi = tr[i + 1], ti[i + 1]
br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr
end
end
end
elseif p == 3 then
local c = 0.86602540378443864676 -- sin(pi / 3)
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * 3 * k
local a0r, a0i = ar[s], ai[s]
local a1r, a1i = ar[s + ido], ai[s + ido]
local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido]
local tr_, ti_ = a1r + a2r, a1i + a2i
local sr, si = a1r - a2r, a1i - a2i
local d = 1 + i + ido * k
br[d], bi[d] = a0r + tr_, a0i + ti_
local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_
local y1r, y1i = mr + c * si, mi - c * sr
local y2r, y2i = mr - c * si, mi + c * sr
if i == 0 then
br[d + lp], bi[d + lp] = y1r, y1i
br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i
else
local w1r, w1i = tr[i + 1], ti[i + 1]
local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1]
br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r
br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r
end
end
end
else
-- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * p * k
local d = 1 + i + ido * k
for u = 0, p - 1 do
local yr, yi = 0, 0
local j = 0
for v = 0, p - 1 do
local xr, xi = ar[s + v * ido], ai[s + v * ido]
local wr, wi = cr[j + 1], ci[j + 1]
yr += xr * wr - xi * wi
yi += xr * wi + xi * wr
j += u
if j >= p then
j -= p
end
end
if u > 0 and i > 0 then
local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1]
yr, yi = yr * wr - yi * wi, yr * wi + yi * wr
end
br[d + u * lp], bi[d + u * lp] = yr, yi
end
end
end
end
end
-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n].
-- The inverse (without the 1 / n) is forward(plan, im, re).
function Fft.forward(plan: Plan, re: { number }, im: { number })
local n = plan.n
local ar, ai, br, bi = re, im, plan.sre, plan.sim
local l1 = 1
for k, p in plan.factors do
local ido = n // (l1 * p)
pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k])
ar, ai, br, bi = br, bi, ar, ai
l1 *= p
end
if ar ~= re then
for j = 1, n do
re[j], im[j] = ar[j], ai[j]
end
end
end
return Fft
+203
View File
@@ -0,0 +1,203 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders).
-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT
-- with pre / post twiddles); no third-party code.
--
-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1
-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1
--
-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley
-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays
-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT
-- interleaves its short blocks).
--
-- local Mdct = require("@formats/codecs/Mdct")
-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4
-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients
-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples
-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values
--
-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller
-- sizes them).
local Fft = require("@formats/codecs/Mdct/Fft")
local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt
local Mdct = {}
Mdct.Fft = Fft
export type Plan = {
n: number, -- window length N
m: number, -- coefficients N / 2
fft: Fft.Plan, -- N / 4 points
twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1
tws: { number },
re: { number }, -- scratch
im: { number },
c: { number }, -- DCT-IV output scratch (M)
}
-- new(N) -> Plan | nil
function Mdct.new(n: number): Plan?
if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then
return nil
end
local m = n // 2
local q = n // 4
local fft = Fft.new(q)
if not fft then
return nil
end
local twc, tws = table.create(q, 0), table.create(q, 0)
for p = 0, q - 1 do
local a = pi * (p + 0.125) / m
twc[p + 1], tws[p + 1] = cos(a), sin(a)
end
return {
n = n,
m = m,
fft = fft,
twc = twc,
tws = tws,
re = table.create(q, 0),
im = table.create(q, 0),
c = table.create(m, 0),
}
end
-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os]
local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number)
local q, m = plan.n // 4, plan.m
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
Fft.forward(plan.fft, re, im)
for k = 0, q - 1 do
local c, s = twc[k + 1], tws[k + 1]
local tr, ti = re[k + 1], im[k + 1]
out[oi + 2 * k * os] = (tr * c + ti * s) * scale
out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale
end
end
-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the
-- plan's M = N / 2 (its own inverse up to 2 / M)
function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?)
local q, m = plan.n // 4, plan.m
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
for p = 0, q - 1 do
local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us]
local c, s = twc[p + 1], tws[p + 1]
re[p + 1] = a * c + b * s
im[p + 1] = b * c - a * s
end
dct4Post(plan, out, oi, os, scale or 1)
end
-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs]
function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?)
local q, m = plan.n // 4, plan.m
local h = m // 2 -- N / 4
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
-- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2)
local b3 = xi + 3 * h
for p = 0, q - 1 do
local j = 2 * p
local a
if j < h then
a = -x[b3 - 1 - j] - x[b3 + j]
else
a = x[xi + j - h] - x[b3 - 1 - j]
end
j = m - 1 - 2 * p
local b
if j < h then
b = -x[b3 - 1 - j] - x[b3 + j]
else
b = x[xi + j - h] - x[b3 - 1 - j]
end
local c, s = twc[p + 1], tws[p + 1]
re[p + 1] = a * c + b * s
im[p + 1] = b * c - a * s
end
dct4Post(plan, out, oi, os or 1, scale or 1)
end
-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window)
function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?)
local m = plan.m
local h = m // 2
local c = plan.c
Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale)
-- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1)
for j = 0, h - 1 do
y[yi + j] = c[h + j + 1]
y[yi + h + j] = -c[m - j]
y[yi + m + j] = -c[h - j]
y[yi + 3 * h + j] = -c[j + 1]
end
end
-- ------------------------------------------------------------------------------------------------ windows
local function besselI0(x: number): number
local sum, term = 1, 1
local k = 1
while k < 200 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-17 then
break
end
k += 1
end
return sum
end
Mdct.besselI0 = besselI0
-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4
-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1.
function Mdct.window(kind: string, n: number, alpha: number?): { number }?
if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then
return nil
end
local w = table.create(n, 0)
if kind == "sine" then
for i = 0, n - 1 do
w[i + 1] = sin(pi * (i + 0.5) / n)
end
elseif kind == "vorbis" then
for i = 0, n - 1 do
local s = sin(pi * (i + 0.5) / n)
w[i + 1] = sin(pi / 2 * s * s)
end
elseif kind == "kbd" then
local half = n // 2
local a = alpha or 4
local kais = table.create(half + 1, 0)
local total = 0
for i = 0, half do
local r = 2 * i / half - 1
kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r)))
total += kais[i + 1]
end
local acc = 0
for i = 0, half - 1 do
acc += kais[i + 1]
local v = sqrt(acc / total)
w[i + 1] = v
w[n - i] = v
end
else
return nil
end
return w
end
-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place)
function Mdct.fft(n: number): Fft.Plan?
return Fft.new(n)
end
return Mdct
File diff suppressed because it is too large. Load diff
+117
View File
@@ -0,0 +1,117 @@
--!strict
-- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from
-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays.
local T = {}
T.PICTURE_RATE = { [0] = 0.0,
23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
}
T.ZIG_ZAG = { [0] = 0,
1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58,
59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
}
T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8,
16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22,
22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26,
27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83,
}
T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
}
T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3,
6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0,
0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0,
0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99,
102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135,
138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1,
144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1,
186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0,
0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0,
0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0,
0, 24, 0, 0, 23, 0, 0, 22,
}
T.MACROBLOCK_TYPE_INTRA = { [0] = 3,
6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17,
}
T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3,
6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33,
36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17,
}
T.MACROBLOCK_TYPE_B = { [0] = 3,
6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36,
33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0,
0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26,
}
T.CODE_BLOCK_PATTERN = { [0] = 6,
3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54,
48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132,
144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129,
102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0,
0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171,
174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0,
0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0,
0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264,
246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0,
0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270,
276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336,
333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0,
0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0,
0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0,
0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0,
0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31,
}
T.MOTION = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36,
33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51,
57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108,
105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0,
0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156,
141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0,
0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0,
0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0,
0, -15, 0, 0, -11, 0, 0, -13,
}
T.DCT_DC_SIZE_LUMINANCE = { [0] = 6,
3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36,
33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6,
3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0,
0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_COEFF = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0,
0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81,
75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0,
0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120,
123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0,
0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0,
0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201,
210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273,
240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0,
0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333,
342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339,
309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417,
420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411,
399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0,
0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0,
0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510,
483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549,
546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0,
0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0,
0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0,
0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0,
0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0,
0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654,
633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657,
624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0,
0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0,
0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0,
0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842,
}
return T
+116
View File
@@ -0,0 +1,116 @@
--!strict
-- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
--
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level
-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF,
-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the
-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but
-- for this header and the require.
local T = require("@formats/codecs/Mpeg1/Tables")
local V = {}
type Leaf = { code: number, len: number, value: number }
local function leaves(tree: { [number]: number }): { Leaf }
local out: { Leaf } = {}
local function walk(state: number, code: number, len: number)
if tree[state] == 0 and len > 0 then
table.insert(out, { code = code, len = len, value = tree[state + 2] })
return
end
for bit = 0, 1 do
local nxt = tree[state + bit]
if nxt ~= nil and nxt > 0 then
walk(nxt, code * 2 + bit, len + 1)
end
end
end
walk(0, 0, 0)
return out
end
local function flat(tree: { [number]: number }): (buffer, number)
local ls = leaves(tree)
local k = 0
for _, l in ls do
k = math.max(k, l.len)
end
local lut = buffer.create(4 * 2 ^ k)
for _, l in ls do
local shift = k - l.len
local first = l.code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768)
end
end
return lut, k
end
V.SUB = 0x1000000
V.ESC = 0xFFFF
V.EOB = 0xFFFE
-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits
local function twoLevel(ls: { Leaf }): buffer
local subs: { [number]: number } = {}
local nsub = 0
for _, l in ls do
if l.len > 8 then
local prefix = l.code // 2 ^ (l.len - 8)
if subs[prefix] == nil then
nsub += 1
subs[prefix] = nsub
end
end
end
local lut = buffer.create(4 * 256 * (1 + nsub))
for _, l in ls do
if l.len <= 8 then
local shift = 8 - l.len
local first = l.code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value)
end
else
local prefix = l.code // 2 ^ (l.len - 8)
local s = subs[prefix]
buffer.writeu32(lut, prefix * 4, V.SUB + s)
local rest = l.code % 2 ^ (l.len - 8)
local shift = 16 - l.len
local first = rest * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value)
end
end
end
return lut
end
V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape
V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA)
V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE)
V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B)
V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN)
V.MOTION, V.MOTION_BITS = flat(T.MOTION)
V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE)
V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE)
do
local ls = leaves(T.DCT_COEFF)
V.DCT_FIRST = twoLevel(ls)
local nextLs: { Leaf } = {}
for _, l in ls do
if l.len == 1 and l.code == 1 then
table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10"
table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11"
else
table.insert(nextLs, l)
end
end
V.DCT_NEXT = twoLevel(nextLs)
end
return V
+262
View File
@@ -0,0 +1,262 @@
--!strict
-- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures,
-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage.
-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom
-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display
-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau).
-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding.
--
-- local dec = Mpeg1.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... }
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@formats/Types")
local D = require("@formats/codecs/Mpeg1/Decoder")
local Mpeg1 = {}
Mpeg1.PICTURE_I = 1
Mpeg1.PICTURE_P = 2
Mpeg1.PICTURE_B = 3
export type Frame = {
width: number,
height: number,
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based)
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
-- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth,
-- chroma stride codedWidth / 2
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
}
export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
-- display order for streams without B-frames.
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
_core: D.Core,
_reorder: boolean,
_rgba: boolean,
_held: D.Store?,
_pixels: buffer?,
_count: number,
width: number,
height: number,
frameRate: number,
bitRate: number,
stats: { pictures: number, errors: number, skipped: number },
},
Decoder
))
function Mpeg1.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local core = D.new(o.maxPixels)
return setmetatable({
_core = core,
_reorder = o.reorder == true,
_rgba = o.rgba ~= false,
_held = nil,
_pixels = nil,
_count = 0,
width = 0,
height = 0,
frameRate = 0,
bitRate = 0,
stats = { pictures = 0, errors = 0, skipped = 0 },
}, Decoder)
end
local function emit(self: Decoder, s: D.Store): Frame
local core = self._core
local pixels: buffer? = nil
if self._rgba then
local need = s.w * s.h * 4
local px = self._pixels
if px == nil or buffer.len(px) ~= need then
px = buffer.create(need)
self._pixels = px
end
core.toRgba(s, px :: buffer)
pixels = px
end
self._count += 1
return {
width = s.w,
height = s.h,
pixels = pixels,
pictureType = s.ptype,
temporalReference = s.tref,
index = self._count,
tag = s.tag,
y = s.y,
cb = s.cb,
cr = s.cr,
codedWidth = s.cw,
}
end
local function sync(self: Decoder)
local st = self._core.state
self.width = st.width
self.height = st.height
self.frameRate = st.frameRate
self.bitRate = st.bitRate
self.stats.pictures = st.pictures
self.stats.errors = st.errors
self.stats.skipped = st.skipped
end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s)
end
local prev = self._held
self._held = s
if prev then
return emit(self, prev)
end
return nil
end
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
local core = self._core
while true do
local s, needData = core.nextPicture(atEnd, tag)
sync(self)
if s then
local f = handle(self, s)
if f then
return f
end
elseif needData then
return nil
end
end
end
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
src = buffer.fromstring(data)
elseif type(data) == "buffer" then
src = data
else
return false
end
local total = buffer.len(src)
local off = math.floor(tonumber(offset) or 0)
if off < 0 or off > total then
return false
end
local n = math.floor(tonumber(len) or (total - off))
if n < 0 or off + n > total then
return false
end
self._core.write(src, off, n)
return true
end
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then
return nil
end
return run(self, true, tag)
end
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
-- for reordering. Call until it returns nil.
function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil)
if f then
return f
end
local held = self._held
if held then
self._held = nil
return emit(self, held)
end
return nil
end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8
-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame.
function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil
end
local w, h, cw = frame.width, frame.height, frame.codedWidth
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
return nil
end
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
for y = 0, h - 1 do
buffer.copy(px, y * w, frame.y, y * cw, w)
end
local o = w * h
for y = 0, oh - 1 do
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
end
end
img.meta.source = {
format = "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
range = if rgba then nil else "limited",
}
return img
end
return Mpeg1
+308
View File
@@ -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
+234
View File
@@ -0,0 +1,234 @@
--!strict
-- 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
--
-- 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,
channels: number,
frames: number, -- total frames, 0 = unknown (a streaming decoder without an index)
tags: Types.Tags,
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end)
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
err: Err.Err?, -- set when the underlying decoder failed mid-stream
}
local function audioRead(self: any, n: number, out: buffer?): (buffer, number)
local a = self._audio
local ch = a.channels
local left = a.frames - self._pos
if n > left then
n = left
end
if n <= 0 then
return out or buffer.create(0), 0
end
local bytes = n * ch * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes)
self._pos += n
return b, n
end
local function decoderRead(self: any, n: number, out: buffer?): (buffer, number)
if self._done then
return out or buffer.create(0), 0
end
local ok, b, got = pcall(self._dec.read, self._dec, n, out)
if not ok then
self._done = true
self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b))
return out or buffer.create(0), 0
end
if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then
self._done = true
return out or buffer.create(0), 0
end
local ch = self.channels
if buffer.len(b) < got * ch * 4 then
got = buffer.len(b) // (ch * 4)
end
return b, got
end
-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read)
function Pcm.source(v: any): (Source?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
local sr, ch = v.sampleRate, v.channels
if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
end
if v.kind == "audio" and type(v.samples) == "buffer" then
local frames = v.frames
if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4")
end
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil
end
if type(v.read) == "function" then
local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil
end
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames)
function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
local ch = src.channels
local cap = math.max(src.frames, 4096)
local data = buffer.create(cap * ch * 4)
local total = 0
local limit = maxFrames or 2 ^ 31
local tmp: buffer? = nil
while true do
local b, n = src:read(16384, tmp)
if n <= 0 then
break
end
tmp = b
if total + n > limit then
return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit))
end
if total + n > cap then
cap = math.max(cap * 2, total + n)
local nd = buffer.create(cap * ch * 4)
buffer.copy(nd, 0, data, 0, total * ch * 4)
data = nd
end
buffer.copy(data, total * ch * 4, b, 0, n * ch * 4)
total += n
end
if src.err then
return nil, src.err
end
local a = Types.Audio.new(src.sampleRate, ch, 0)
a.frames = total
if buffer.len(data) == total * ch * 4 then
a.samples = data
else
a.samples = buffer.create(total * ch * 4)
buffer.copy(a.samples, 0, data, 0, total * ch * 4)
end
a.tags = table.clone(src.tags)
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)
local v = math.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
-- fromInt(v, bits) -> v / 2^(bits-1)
function Pcm.fromInt(v: number, bits: number): number
return v / 2 ^ (bits - 1)
end
return Pcm
+149
View File
@@ -0,0 +1,149 @@
--!strict
-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a
-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass,
-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes,
-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with
-- an exclusive class, cymbals). Written for this library (no third-party code).
local Parse = require("@formats/codecs/SoundFont/Parse")
local Fallback = {}
local CYCLE = 256
local NOISE = 32768
local C4 = 261.6255653005986
local function hzToCents(hz: number): number
return 1200 * math.log(hz / 8.176, 2)
end
local cached: any = nil
-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it)
function Fallback.build(): any
if cached then
return cached
end
local waves = { "sine", "triangle", "square", "saw" }
local count = #waves * CYCLE + NOISE
local samples = buffer.create((count + 1) * 4)
local starts: { [string]: number } = {}
for w, name in waves do
local base = (w - 1) * CYCLE
starts[name] = base
for i = 0, CYCLE - 1 do
local ph = i / CYCLE
local v
if name == "sine" then
v = math.sin(2 * math.pi * ph)
elseif name == "triangle" then
v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4
elseif name == "square" then
v = if ph < 0.5 then 0.6 else -0.6
else
v = (1 - 2 * ph) * 0.7
end
buffer.writef32(samples, (base + i) * 4, v)
end
end
local noiseStart = #waves * CYCLE
starts.noise = noiseStart
local seed = 12345
for i = 0, NOISE - 1 do
seed = (seed * 1103515245 + 12345) % 2147483648
buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7)
end
local function region(wave: string, fields: { [string]: number }): { [string]: number }
local r = Parse.defaultRegion()
local s = starts[wave]
r.offset = s
r.loopMode = 1
r.loopStart = s
if wave == "noise" then
r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60
else
r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60
end
r.aRelease = 0.08
for k, v in fields do
r[k] = v
end
return r
end
-- the 16 GM families: wave + envelope / filter / vibrato
local families: { { any } } = {
{ "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } },
{ "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } },
{ "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } },
{ "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } },
{ "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } },
{ "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } },
{ "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } },
{ "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } },
{ "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } },
{ "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } },
{ "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } },
{ "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } },
{ "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } },
{ "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } },
{ "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } },
{ "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } },
}
local presets = {}
for program = 0, 127 do
local f = families[program // 8 + 1]
table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } })
end
-- the drum kit (bank 128, every program): one region per key
local kit = {}
-- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0
local function drum(lo: number, hi: number, wave: string, fields: { [string]: number })
local r = region(wave, fields)
r.lokey, r.hikey = lo, hi
r.sampleRate *= 2 ^ ((fields.semis or 0) / 12)
r.semis = nil :: any
table.insert(kit, r)
end
local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 }
local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number }
local c = table.clone(a)
for k, v in b do
c[k] = v
end
return c
end
drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) })
drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 }))
drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) })
drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) })
drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) })
drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) })
for _, k in { 41, 43, 45, 47, 48, 50 } do
drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 }))
end
drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 })
drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) })
drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 })
drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) })
table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit })
cached = {
kind = "soundfont",
info = { name = "formats-luau fallback" },
samples = samples,
sampleCount = count,
presets = presets,
sampleHeaders = {},
instruments = {},
meta = { source = { format = "fallback" } },
}
return cached
end
return Fallback
+523
View File
@@ -0,0 +1,523 @@
--!strict
-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened
-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's
-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt)
-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped
-- so the synth never reads outside the sample buffer.
-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01);
-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h).
-- Never throws: a bad file returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Parse = {}
-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level
export type Region = { [string]: number }
export type Preset = { name: string, preset: number, bank: number, regions: { Region } }
export type SoundFont = {
kind: "soundfont",
info: { [string]: string },
samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end)
sampleCount: number,
presets: { Preset }, -- sorted by bank, then preset number
sampleHeaders: { { [string]: any } },
instruments: { { name: string, zones: number } },
meta: { [string]: any },
}
local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53
-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address
-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key)
local LIM12K5K = { 1, -12000, 5000 }
local LIM12K8K = { 1, -12000, 8000 }
local LIM1200 = { 1, -1200, 1200 }
local GEN: { [number]: { any } } = {
[0] = { "offset", "a" },
[1] = { "stop", "a" },
[2] = { "loopStart", "a" },
[3] = { "loopEnd", "a" },
[4] = { "offset", "a15" },
[5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } },
[6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } },
[7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } },
[8] = { "filterFc", "i", { 1, 1500, 13500 } },
[9] = { "filterQ", "i", { 1, 0, 960 } },
[10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } },
[11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } },
[12] = { "stop", "a15" },
[13] = { "modLfoToVolume", "i", { 1, -960, 960 } },
[17] = { "pan", "f", { 0.001, -0.5, 0.5 } },
[21] = { "delayModLFO", "f", LIM12K5K },
[22] = { "freqModLFO", "i", { 1, -16000, 4500 } },
[23] = { "delayVibLFO", "f", LIM12K5K },
[24] = { "freqVibLFO", "i", { 1, -16000, 4500 } },
[25] = { "mDelay", "f", LIM12K5K },
[26] = { "mAttack", "f", LIM12K8K },
[27] = { "mHold", "f", LIM12K5K },
[28] = { "mDecay", "f", LIM12K8K },
[29] = { "mSustain", "f", { 1, 0, 1000 } },
[30] = { "mRelease", "f", LIM12K8K },
[31] = { "mKeyHold", "f", LIM1200 },
[32] = { "mKeyDecay", "f", LIM1200 },
[33] = { "aDelay", "f", LIM12K5K },
[34] = { "aAttack", "f", LIM12K8K },
[35] = { "aHold", "f", LIM12K5K },
[36] = { "aDecay", "f", LIM12K8K },
[37] = { "aSustain", "f", { 1, 0, 1440 } },
[38] = { "aRelease", "f", LIM12K8K },
[39] = { "aKeyHold", "f", LIM1200 },
[40] = { "aKeyDecay", "f", LIM1200 },
[43] = { "", "kr" },
[44] = { "", "vr" },
[45] = { "loopStart", "a15" },
[48] = { "attenuation", "f", { 0.04, 0, 57.6 } },
[50] = { "loopEnd", "a15" },
[51] = { "transpose", "i" },
[52] = { "tune", "i" },
[54] = { "loopMode", "loop" },
[56] = { "keytrack", "i" },
[57] = { "group", "group" },
[58] = { "keycenter", "key" },
}
-- the merged fields: value generators once each (several ops share a field), then the four address fields
local MERGE: { { any } } = {}
do
local seen: { [string]: boolean } = {}
for op = 0, 58 do
local g = GEN[op]
if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then
seen[g[1]] = true
table.insert(MERGE, g)
end
end
end
local FIELDS = {
"loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd",
"transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch",
"modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch",
"delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease",
"aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay",
"sampleIndex",
}
-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's)
local function clear(relative: boolean): Region
local r: Region = {}
for _, f in FIELDS do
r[f] = 0
end
r.hikey, r.hivel, r.keycenter = 127, 127, 60
if relative then
return r
end
r.keytrack = 100
r.keycenter = -1
for _, p in { "a", "m" } do
for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do
r[p .. s] = -12000
end
end
r.filterFc = 13500
r.delayModLFO, r.delayVibLFO = -12000, -12000
return r
end
local function copy(r: Region): Region
local c: Region = {}
for k, v in r do
c[k] = v
end
return c
end
-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from
function Parse.defaultRegion(): Region
local r = clear(false)
r.keycenter = 60
for _, p in { "a", "m" } do
for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do
r[p .. s] = 0
end
end
r.aSustain, r.mSustain = 1, 1
r.delayModLFO, r.delayVibLFO = 0, 0
return r
end
-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16
local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number)
local g = GEN[op]
if not g then
return
end
local mode = g[2]
if mode == "f" or mode == "i" then
r[g[1]] = s
elseif mode == "a" then
r[g[1]] += s
elseif mode == "a15" then
r[g[1]] += s * 32768
elseif mode == "kr" then
r.lokey, r.hikey = lo, hi
elseif mode == "vr" then
r.lovel, r.hivel = lo, hi
elseif mode == "loop" then
local m = w % 4
r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0
elseif mode == "group" then
r.group = w
elseif mode == "key" then
r.keycenter = s
end
end
-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount)
local function merge(z: Region, p: Region)
for _, g in MERGE do
local f = g[1]
local v = z[f] + p[f]
local lim = g[3]
if lim then
v *= lim[1]
v = math.clamp(v, lim[2], lim[3])
end
z[f] = v
end
end
local function tc2s(tc: number): number
return 2 ^ (tc / 1200)
end
-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key
local function envToSecs(r: Region, p: string, sustainIsGain: boolean)
for _, s in { "Delay", "Attack", "Release" } do
local v = r[p .. s]
r[p .. s] = if v < -11950 then 0 else tc2s(v)
end
if r[p .. "KeyHold"] == 0 then
local v = r[p .. "Hold"]
r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v)
end
if r[p .. "KeyDecay"] == 0 then
local v = r[p .. "Decay"]
r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v)
end
local sus = r[p .. "Sustain"]
if sus < 0 then
sus = 0
elseif sustainIsGain then
sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0
else
sus = 1 - sus / 1000
end
r[p .. "Sustain"] = sus
end
-- ------------------------------------------------------------------------------------------------ RIFF
type Hydra = { [string]: { { number } } }
-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte)
local LAYOUT: { [string]: { number } } = {
phdr = { 20, 2, 2, 2, 4, 4, 4 },
pbag = { 2, 2 },
pmod = { 2, 2, -2, 2, 2 },
pgen = { 2, 2 },
inst = { 20, 2 },
ibag = { 2, 2 },
imod = { 2, 2, -2, 2, 2 },
igen = { 2, 2 },
shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 },
}
local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 }
local INFO_NAMES = {
isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product",
ICOP = "copyright", ICMT = "comment", ISFT = "software",
}
export type Options = { maxRegions: number?, maxSamples: number? }
-- parse(r, opts?) -> SoundFont | nil, Err
function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
local maxRegions = opts and opts.maxRegions or 1000000
local maxSamples = opts and opts.maxSamples or 2 ^ 28
if r:string(4) ~= "RIFF" then
return r:fail(Err.CORRUPT, "not a RIFF file")
end
local riffSize = r:u32le()
if r:string(4) ~= "sfbk" then
return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)")
end
if r.err then
return nil, r.err
end
local body = r:sub(12, math.max(0, riffSize - 4))
local info: { [string]: string } = {}
local hydra: Hydra = {}
local smpl: Bytes.Reader? = nil
local sm24: Bytes.Reader? = nil
local version = ""
while body:remaining() >= 8 do
local id, size = body:string(4), body:u32le()
local chunk = body:slice(size)
if size % 2 == 1 and body:remaining() > 0 then
body:skip(1)
end
if id == "LIST" and chunk:remaining() >= 4 then
local kind = chunk:string(4)
while chunk:remaining() >= 8 do
local sid, ssize = chunk:string(4), chunk:u32le()
local sub = chunk:slice(ssize)
if ssize % 2 == 1 and chunk:remaining() > 0 then
chunk:skip(1)
end
if kind == "INFO" then
if sid == "ifil" and sub:remaining() >= 4 then
local major, minor = sub:u16le(), sub:u16le()
version = string.format("%d.%02d", major, minor)
elseif INFO_NAMES[sid] then
info[INFO_NAMES[sid]] = sub:fixed(sub:remaining())
end
elseif kind == "sdta" then
if sid == "smpl" and not smpl then
smpl = sub
elseif sid == "sm24" then
sm24 = sub
end
elseif kind == "pdta" then
local layout = LAYOUT[sid]
if layout and not hydra[sid] then
local rs = RECSIZE[sid]
local n = sub:remaining() // rs
local recs: { { number } } = table.create(n)
for i = 1, n do
local rec = {}
for _, w in layout do
if w == 20 then
table.insert(rec, 0) -- the name is read separately
sub:skip(20)
elseif w == 4 then
table.insert(rec, sub:u32le())
elseif w == 2 then
table.insert(rec, sub:u16le())
elseif w == -2 then
table.insert(rec, sub:i16le())
elseif w == 1 then
table.insert(rec, sub:u8())
else
table.insert(rec, sub:i8())
end
end
recs[i] = rec
end
hydra[sid] = recs
if sid == "phdr" or sid == "inst" or sid == "shdr" then
local names = table.create(n)
for i = 0, n - 1 do
names[i + 1] = sub:sub(i * rs, 20):fixed(20)
end
hydra[sid .. "Names"] = names :: any
end
end
end
end
end
end
if not smpl then
return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)")
end
for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do
if not hydra[k] or #hydra[k] == 0 then
return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records")
end
end
-- samples
local sr = smpl :: Bytes.Reader
local count = sr:remaining() // 2
if count > maxSamples then
return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples))
end
local samples = buffer.create((count + 1) * 4)
do
local b, p = sr.buf, sr.pos
local readi16, writef32 = buffer.readi16, buffer.writef32
local s24 = sm24
if s24 and s24:remaining() >= count then
local q = s24.pos
local readu8 = buffer.readu8
for i = 0, count - 1 do
writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607)
end
else
s24 = nil
for i = 0, count - 1 do
writef32(samples, i * 4, readi16(b, p + i * 2) / 32767)
end
end
sm24 = s24
end
-- presets (tsf_load_presets)
local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen
local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr
local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames
local nInst = #inst - 1 -- the last record of each list is the terminal one
local nShdr = #shdr - 1
local function range(list: { { number } }, i: number, field: number, limit: number): (number, number)
-- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes)
local a = list[i][field] + 1
local b = if list[i + 1] then list[i + 1][field] + 1 else a
return math.max(1, a), math.min(b, limit + 1)
end
local presets: { Preset } = {}
local regionTotal = 0
for pi = 1, #phdr - 1 do
local ph = phdr[pi]
local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} }
local globalRegion = clear(true)
local b0, b1 = range(phdr, pi, 4, #pbag)
for bi = b0, b1 - 1 do
local presetRegion = copy(globalRegion)
local hadInstrument = false
local g0, g1 = range(pbag, bi, 1, #pgen)
for gi = g0, g1 - 1 do
local pg = pgen[gi]
local op, amount = pg[1], pg[2]
local lo, hi = amount % 256, amount // 256
local s = if amount >= 32768 then amount - 65536 else amount
if op == GEN_INSTRUMENT then
hadInstrument = true
if amount < nInst then
local instRegion = clear(false)
local ib0, ib1 = range(inst, amount + 1, 2, #ibag)
for ibi = ib0, ib1 - 1 do
local zone = copy(instRegion)
local hadSample = false
local ig0, ig1 = range(ibag, ibi, 1, #igen)
for igi = ig0, ig1 - 1 do
local ig = igen[igi]
local iop, iamt = ig[1], ig[2]
if iop == GEN_SAMPLEID then
hadSample = true
if iamt >= nShdr then
break
end
local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey)
and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel)
if ok then
local z = copy(zone)
z.lokey = math.max(z.lokey, presetRegion.lokey)
z.hikey = math.min(z.hikey, presetRegion.hikey)
z.lovel = math.max(z.lovel, presetRegion.lovel)
z.hivel = math.min(z.hivel, presetRegion.hivel)
merge(z, presetRegion)
envToSecs(z, "a", true)
envToSecs(z, "m", false)
z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO)
z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO)
local sh = shdr[iamt + 1]
local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5]
z.offset = math.clamp(z.offset + sStart, 0, count)
local stop = z.stop + sEnd
if stop > 0 and stop < count then
stop += 1
else
stop = count
end
z.stop = math.clamp(stop, 0, count)
z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count)
local le = z.loopEnd + sLoopEnd
if sLoopEnd > 0 then
le -= 1
end
z.loopEnd = math.clamp(le, 0, count)
if z.keycenter == -1 then
z.keycenter = sh[7]
end
z.tune += sh[8]
z.sampleRate = sh[6]
z.sampleIndex = iamt
regionTotal += 1
if regionTotal > maxRegions then
return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions")
end
table.insert(preset.regions, z)
end
break -- sampleID ends a zone's generator list
else
local ilo, ihi = iamt % 256, iamt // 256
operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt)
end
end
if ibi == ib0 and not hadSample then
instRegion = zone -- the instrument's global zone
end
end
end
break -- instrument ends a preset zone's generator list
else
operator(presetRegion, op, lo, hi, s, amount)
end
end
if bi == b0 and not hadInstrument then
globalRegion = presetRegion -- the preset's global zone
end
end
table.insert(presets, preset)
end
-- sorted by bank, then preset, then file order (tsf's sortedIndex)
for i, p in presets do
(p :: any)._order = i
end
table.sort(presets, function(a: Preset, b: Preset): boolean
if a.bank ~= b.bank then
return a.bank < b.bank
end
if a.preset ~= b.preset then
return a.preset < b.preset
end
return (a :: any)._order < (b :: any)._order
end)
for _, p in presets do
(p :: any)._order = nil
end
local headers: { { [string]: any } } = table.create(nShdr)
for i = 1, nShdr do
local sh = shdr[i]
headers[i] = {
name = shdrNames[i],
start = sh[2],
stop = sh[3],
loopStart = sh[4],
loopEnd = sh[5],
sampleRate = sh[6],
originalPitch = sh[7],
pitchCorrection = sh[8],
link = sh[9],
type = sh[10],
}
end
local instruments: { { name: string, zones: number } } = table.create(nInst)
for i = 1, nInst do
instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) }
end
local sf: SoundFont = {
kind = "soundfont",
info = info,
samples = samples,
sampleCount = count,
presets = presets,
sampleHeaders = headers,
instruments = instruments,
meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } },
}
return sf, nil
end
return Parse
+803
View File
@@ -0,0 +1,803 @@
--!strict
--!native
-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt):
-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter
-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear
-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with
-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume,
-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not
-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer.
-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only.
-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback,
-- the sample buffer has a zero pad sample, the output range is checked before mixing).
local Synth = {}
local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len
local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor
local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7
local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block
local FASTRELEASE = 0.01
local PI = math.pi
local LOOP_NONE, LOOP_SUSTAIN = 0, 2
type Env = {
segment: number,
isExp: boolean,
isAmp: boolean,
vel: number,
level: number,
slope: number,
untilNext: number,
delay: number,
attack: number,
hold: number,
decay: number,
sustain: number,
release: number,
}
type Lfo = { untilStart: number, level: number, delta: number }
export type Voice = {
preset: number, -- 1-based preset index, -1 = idle
key: number,
channel: number,
held: boolean, -- note off while sustain was down
region: { [string]: number },
pitchIn: number, -- timecents
pitchOut: number,
pos: number,
gainDB: number,
panL: number,
panR: number,
playIndex: number,
loopStart: number,
loopEnd: number,
amp: Env,
mod: Env,
lpActive: boolean,
qinv: number,
a0: number,
a1: number,
b1: number,
b2: number,
z1: number,
z2: number,
modlfo: Lfo,
viblfo: Lfo,
}
export type Channel = {
preset: number,
bank: number,
pitchWheel: number,
midiPan: number,
midiVolume: number,
midiExpression: number,
midiRPN: number,
midiData: number,
sustain: boolean,
panOffset: number,
gainDB: number,
pitchRange: number,
tuning: number,
}
export type State = {
presets: { { regions: { { [string]: number } }, preset: number, bank: number } },
lookup: { [number]: number }, -- bank * 128 + preset -> preset index
samples: buffer,
rate: number,
gainDB: number,
voices: { Voice },
maxVoices: number,
playIndex: number,
channels: { Channel }, -- [1..16] = MIDI channels 0..15
}
local function tc2s(tc: number): number
return 2 ^ (tc / 1200)
end
local function cents2Hz(c: number): number
return 8.176 * 2 ^ (c / 1200)
end
local function db2gain(db: number): number
return if db > -100 then 10 ^ (db * 0.05) else 0
end
local function gain2db(g: number): number
return if g <= 0.00001 then -100 else 20 * math.log10(g)
end
-- ------------------------------------------------------------------------------------------------ envelope
local function releaseSamples(e: Env, rate: number): number
return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate)
end
local function nextSegment(e: Env, active: number, rate: number)
local seg = active
if seg == NONE then
e.untilNext = floor(e.delay * rate)
if e.untilNext > 0 then
e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0
return
end
seg = DELAY
end
if seg == DELAY then
e.untilNext = floor(e.attack * rate)
if e.untilNext > 0 then
if not e.isAmp then
-- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x)
e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate)
end
e.segment, e.isExp, e.level = ATTACK, false, 0
e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1
return
end
seg = ATTACK
end
if seg == ATTACK then
e.untilNext = floor(e.hold * rate)
if e.untilNext > 0 then
e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0
return
end
seg = HOLD
end
if seg == HOLD then
e.untilNext = floor(e.decay * rate)
if e.untilNext > 0 then
e.segment, e.level = DECAY, 1
if e.isAmp then
local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h)
e.slope = exp(mystery)
e.isExp = true
if e.sustain > 0 then
e.untilNext = floor(log(e.sustain) / mystery)
end
else
e.slope = -1 / e.untilNext
e.untilNext = floor(e.decay * (1 - e.sustain) * rate)
e.isExp = false
end
return
end
seg = DECAY
end
if seg == DECAY then
e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false
return
end
if seg == SUSTAIN then
e.segment = RELEASE
e.untilNext = math.max(1, releaseSamples(e, rate))
if e.isAmp then
e.slope = exp(-9.226 / e.untilNext)
e.isExp = true
else
e.slope = -e.level / e.untilNext
e.isExp = false
end
return
end
e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF
end
local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number)
e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"]
e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"]
local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"]
if kh ~= 0 then
local h = e.hold + kh * (60 - key)
e.hold = if h < -10000 then 0 else tc2s(h)
end
if kd ~= 0 then
local d = e.decay + kd * (60 - key)
e.decay = if d < -10000 then 0 else tc2s(d)
end
e.vel, e.isAmp = vel, isAmp
nextSegment(e, NONE, rate)
end
local function envProcess(e: Env, n: number, rate: number)
local slope = e.slope
if slope ~= 0 then
if e.isExp then
e.level *= slope ^ n
else
e.level += slope * n
end
end
e.untilNext -= n
if e.untilNext <= 0 then
nextSegment(e, e.segment, rate)
end
end
local function newEnv(): Env
return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 }
end
-- ------------------------------------------------------------------------------------------------ filter / lfo
local function lowpassSetup(v: Voice, fc: number)
-- the biquad from earlevel.com (as tsf.h)
local k = tan(PI * fc)
local kk = k * k
local norm = 1 / (1 + k * v.qinv + kk)
v.a0 = kk * norm
v.a1 = 2 * v.a0
v.b1 = 2 * (kk - 1) * norm
v.b2 = (1 - k * v.qinv + kk) * norm
end
local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number)
l.untilStart = floor(delay * rate)
l.delta = 4 * cents2Hz(freqCents) / rate
l.level = 0
end
local function lfoProcess(l: Lfo, n: number)
if l.untilStart > n then
l.untilStart -= n
return
end
l.level += l.delta * n
if l.level > 1 then
l.delta = -l.delta
l.level = 2 - l.level
elseif l.level < -1 then
l.delta = -l.delta
l.level = -2 - l.level
end
end
-- ------------------------------------------------------------------------------------------------ voices
local function calcPitch(v: Voice, shift: number, rate: number)
local r = v.region
local note = v.key + r.transpose + r.tune / 100
local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift
v.pitchIn = adjusted * 100
v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate)
end
local function setPan(v: Voice, pan: number)
if pan <= -0.5 then
v.panL, v.panR = 1, 0
elseif pan >= 0.5 then
v.panL, v.panR = 0, 1
else
v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan)
end
end
local function channelShift(c: Channel): number
return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning
end
local function voiceEnd(s: State, v: Voice)
nextSegment(v.amp, SUSTAIN, s.rate)
nextSegment(v.mod, SUSTAIN, s.rate)
if v.region.loopMode == LOOP_SUSTAIN then
v.loopEnd = v.loopStart -- keep playing, stop looping
end
end
local function voiceEndQuick(s: State, v: Voice)
v.amp.release = 0
nextSegment(v.amp, SUSTAIN, s.rate)
v.mod.release = 0
nextSegment(v.mod, SUSTAIN, s.rate)
end
local function newVoice(): Voice
return {
preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0,
panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(),
lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0,
modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 },
}
end
local function newChannel(): Channel
return {
preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383,
midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0,
}
end
-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build).
-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256)
function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State
local lookup: { [number]: number } = {}
for i, p in sf.presets do
local k = p.bank * 128 + p.preset
if lookup[k] == nil then
lookup[k] = i
end
end
local s: State = {
presets = sf.presets,
lookup = lookup,
samples = sf.samples,
rate = rate,
gainDB = gain2db(gain or 0.5),
voices = {},
maxVoices = maxVoices or 256,
playIndex = 0,
channels = {},
}
for ch = 1, 16 do
s.channels[ch] = newChannel()
end
for ch = 0, 15 do
Synth.program(s, ch, 0)
end
return s
end
local function presetIndex(s: State, bank: number, preset: number): number
return s.lookup[bank * 128 + preset] or -1
end
-- noteOn(s, channel, key, velocity 0..127)
function Synth.noteOn(s: State, ch: number, key: number, velocity: number)
local c = s.channels[ch + 1]
if not c then
return
end
if velocity <= 0 then
Synth.noteOff(s, ch, key)
return
end
local pi = c.preset
local preset = s.presets[pi]
if not preset then
return
end
local vel = math.min(velocity, 127) / 127
local midiVel = floor(vel * 127)
local rate = s.rate
local voices = s.voices
local playIndex = s.playIndex
s.playIndex += 1
for _, region in preset.regions do
if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then
continue
end
local voice: Voice? = nil
if region.group ~= 0 then
for _, v in voices do
if v.preset == pi and v.region.group == region.group then
voiceEndQuick(s, v)
elseif v.preset == -1 and not voice then
voice = v
end
end
else
for _, v in voices do
if v.preset == -1 then
voice = v
break
end
end
end
if not voice then
if #voices < s.maxVoices then
local v = newVoice()
table.insert(voices, v)
voice = v
else
local best = -1e18
for _, v in voices do
if v.amp.segment == RELEASE then
local done = releaseSamples(v.amp, rate) - v.amp.untilNext
if done > best then
best, voice = done, v
end
end
end
if not voice then
continue
end
end
end
local v = voice :: Voice
v.region = region
v.preset = pi
v.key = key
v.channel = ch
v.playIndex = playIndex
v.held = false
v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB
calcPitch(v, channelShift(c), rate)
setPan(v, region.pan + c.panOffset)
v.pos = region.offset
local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd
v.loopStart = if doLoop then region.loopStart else 0
v.loopEnd = if doLoop then region.loopEnd else 0
envSetup(v.amp, region, "a", key, midiVel, true, rate)
envSetup(v.mod, region, "m", key, midiVel, false, rate)
local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1
v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20)
v.z1, v.z2 = 0, 0
v.lpActive = fc < 0.499
if v.lpActive then
lowpassSetup(v, fc)
end
lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate)
lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate)
end
end
-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down
function Synth.noteOff(s: State, ch: number, key: number)
local c = s.channels[ch + 1]
if not c then
return
end
local first = -1
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then
if first == -1 or v.playIndex < first then
first = v.playIndex
end
end
end
if first == -1 then
return
end
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then
if c.sustain then
v.held = true
else
voiceEnd(s, v)
end
end
end
end
local function applyPitch(s: State, ch: number, c: Channel)
local shift = channelShift(c)
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch then
calcPitch(v, shift, s.rate)
end
end
end
local function setVolume(s: State, ch: number, c: Channel, volume: number)
local db = gain2db(volume)
if db == c.gainDB then
return
end
local change = db - c.gainDB
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch then
v.gainDB += change
end
end
c.gainDB = db
end
local function setChannelPan(s: State, ch: number, c: Channel, pan: number)
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch then
setPan(v, v.region.pan + pan - 0.5)
end
end
c.panOffset = pan - 0.5
end
local function setTuning(s: State, ch: number, c: Channel, tuning: number)
if c.tuning ~= tuning then
c.tuning = tuning
applyPitch(s, ch, c)
end
end
local function setPitchRange(s: State, ch: number, c: Channel, range: number)
if c.pitchRange ~= range then
c.pitchRange = range
if c.pitchWheel ~= 8192 then
applyPitch(s, ch, c)
end
end
end
local function setSustain(s: State, ch: number, c: Channel, on: boolean)
if c.sustain == on then
return
end
c.sustain = on
if on then
return
end
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then
voiceEnd(s, v)
end
end
end
-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128)
function Synth.program(s: State, ch: number, program: number)
local c = s.channels[ch + 1]
if not c then
return
end
local bank = c.bank % 32768
local idx
if ch == 9 then
idx = presetIndex(s, 128 + bank, program)
if idx == -1 then
idx = presetIndex(s, 128, program)
end
if idx == -1 then
idx = presetIndex(s, 128, 0)
end
if idx == -1 then
idx = presetIndex(s, bank, program)
end
else
idx = presetIndex(s, bank, program)
end
if idx == -1 then
idx = presetIndex(s, 0, program)
end
if idx ~= -1 then
c.preset = idx
end
end
-- pitchBend(s, channel, 0..16383)
function Synth.pitchBend(s: State, ch: number, value: number)
local c = s.channels[ch + 1]
if not c or c.pitchWheel == value then
return
end
c.pitchWheel = value
applyPitch(s, ch, c)
end
-- control(s, channel, controller, value 0..127)
function Synth.control(s: State, ch: number, cc: number, value: number)
local c = s.channels[ch + 1]
if not c then
return
end
local volume, pan, data = false, false, false
if cc == 7 then
c.midiVolume = c.midiVolume % 128 + value * 128
volume = true
elseif cc == 39 then
c.midiVolume = c.midiVolume - c.midiVolume % 128 + value
volume = true
elseif cc == 11 then
c.midiExpression = c.midiExpression % 128 + value * 128
volume = true
elseif cc == 43 then
c.midiExpression = c.midiExpression - c.midiExpression % 128 + value
volume = true
elseif cc == 10 then
c.midiPan = c.midiPan % 128 + value * 128
pan = true
elseif cc == 42 then
c.midiPan = c.midiPan - c.midiPan % 128 + value
pan = true
elseif cc == 6 then
c.midiData = c.midiData % 128 + value * 128
data = true
elseif cc == 38 then
c.midiData = c.midiData - c.midiData % 128 + value
data = true
elseif cc == 0 then
c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h)
elseif cc == 32 then
c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value
elseif cc == 101 then
local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN
c.midiRPN = rpn % 128 + value * 128
elseif cc == 100 then
local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN
c.midiRPN = rpn - rpn % 128 + value
elseif cc == 98 or cc == 99 then
c.midiRPN = 0xFFFF
elseif cc == 64 then
setSustain(s, ch, c, value >= 64)
elseif cc == 120 then
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then
voiceEndQuick(s, v)
end
end
elseif cc == 123 then
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then
voiceEnd(s, v)
end
end
elseif cc == 121 then
c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0
setVolume(s, ch, c, 1)
setChannelPan(s, ch, c, 0.5)
setPitchRange(s, ch, c, 2)
setTuning(s, ch, c, 0)
end
if volume then
-- the cube gives a decent MIDI volume curve (tsf.h)
setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3)
elseif pan then
setChannelPan(s, ch, c, c.midiPan / 16383)
elseif data then
if c.midiRPN == 0 then
setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128))
elseif c.midiRPN == 1 then
local t = c.tuning
setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192)
elseif c.midiRPN == 2 and cc == 6 then
local t = c.tuning
setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t))))
end
end
end
-- midi(s, status, d1, d2): one channel message
function Synth.midi(s: State, status: number, d1: number, d2: number)
local kind, ch = status // 16, status % 16
if kind == 9 then
Synth.noteOn(s, ch, d1, d2)
elseif kind == 8 then
Synth.noteOff(s, ch, d1)
elseif kind == 11 then
Synth.control(s, ch, d1, d2)
elseif kind == 12 then
Synth.program(s, ch, d1)
elseif kind == 14 then
Synth.pitchBend(s, ch, d1 + d2 * 128)
end
end
-- reset(s): all voices off, channels back to their defaults
function Synth.reset(s: State)
for _, v in s.voices do
v.preset = -1
end
for ch = 1, 16 do
s.channels[ch] = newChannel()
end
for ch = 0, 15 do
Synth.program(s, ch, 0)
end
end
-- active(s) -> the number of sounding voices
function Synth.active(s: State): number
local n = 0
for _, v in s.voices do
if v.preset ~= -1 then
n += 1
end
end
return n
end
-- ------------------------------------------------------------------------------------------------ render
local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number)
local region = v.region
local input = s.samples
local rate = s.rate
local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc
local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume
local vibLfoToPitch = region.vibLfoToPitch
local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0
local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0)
local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0
local loopStart, loopEnd = v.loopStart, v.loopEnd
local isLooping = loopStart < loopEnd
local endD = region.stop
local loopEndD = loopEnd + 1
local loopLen = loopEnd - loopStart + 1
local pos = v.pos
local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2
local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0
local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0
local dynamicGain = modLfoToVolume ~= 0
local filterFc = region.filterFc
local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut
local noteGain = if dynamicGain then 0 else db2gain(v.gainDB)
local o = frame * 8
while numSamples > 0 do
local block = if numSamples > BLOCK then BLOCK else numSamples
numSamples -= block
if dynamicLowpass then
local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc
local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1
lpActive = fc < 0.499
if lpActive then
lowpassSetup(v, fc)
a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2
end
end
if dynamicPitch then
pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut
end
if dynamicGain then
noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1)
end
local gainMono = noteGain * v.amp.level
envProcess(v.amp, block, rate)
if updateModEnv then
envProcess(v.mod, block, rate)
end
if updateModLfo then
lfoProcess(v.modlfo, block)
end
if updateVibLfo then
lfoProcess(v.viblfo, block)
end
-- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise)
local gainNext = noteGain * v.amp.level
local step = (gainNext - gainMono) / block
local panL, panR = v.panL, v.panR
local g = gainMono
local k = block
while k > 0 and pos < endD do
k -= 1
local ip = floor(pos)
local np = if ip >= loopEnd and isLooping then loopStart else ip + 1
local s0 = readf32(input, ip * 4)
local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip)
if lpActive then
local y = val * a0 + z1
z1 = val * a1 + z2 - b1 * y
z2 = val * a0 - b2 * y
val = y
end
val *= g
g += step
writef32(out, o, readf32(out, o) + val * panL)
writef32(out, o + 4, readf32(out, o + 4) + val * panR)
o += 8
pos += pitchRatio
if pos >= loopEndD and isLooping then
pos -= loopLen
end
end
o += k * 8
if not (pos < endD) or v.amp.segment == DONE then
v.preset = -1
return
end
end
v.pos = pos
v.lpActive, v.z1, v.z2 = lpActive, z1, z2
end
-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range
-- requests are clipped to the buffer
function Synth.render(s: State, out: buffer, frame: number, n: number)
local room = blen(out) // 8 - frame
if frame < 0 or room <= 0 then
return
end
if n > room then
n = room
end
if n <= 0 then
return
end
-- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here
-- once so a hand-made SoundFont cannot index outside it)
local count = blen(s.samples) // 4 - 1
for _, v in s.voices do
if v.preset ~= -1 then
local r = v.region
if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then
v.preset = -1
else
voiceRender(s, v, out, frame, n)
end
end
end
end
return Synth
+69
View File
@@ -0,0 +1,69 @@
--!strict
-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT,
-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered.
-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw /
-- noise) with a drum kit.
--
-- local SoundFont = require("@formats/codecs/SoundFont")
-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err
-- local sf = SoundFont.fallback() -- the built-in waveform set
-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100)
-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Parse = require("@formats/codecs/SoundFont/Parse")
local Synth = require("@formats/codecs/SoundFont/Synth")
local Fallback = require("@formats/codecs/SoundFont/Fallback")
local SoundFont = {}
export type SoundFont = Parse.SoundFont
export type State = Synth.State
SoundFont.Synth = Synth
SoundFont.defaultRegion = Parse.defaultRegion
-- sniff(r) -> true when r starts with RIFF....sfbk
function SoundFont.sniff(r: Bytes.Reader): boolean
return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk"
end
-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6),
-- opts.maxSamples (default 2^28)
function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?)
local r: Bytes.Reader
if type(src) == "string" then
r = Bytes.reader(buffer.fromstring(src))
elseif type(src) == "buffer" then
r = Bytes.reader(src)
elseif type(src) == "table" and type(src.buf) == "buffer" then
r = Bytes.reader(src.buf, src.pos, src.limit - src.pos)
else
return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader")
end
local ok, sf, err = pcall(Parse.parse, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf))
end
return sf, err
end
-- fallback() -> the built-in General MIDI waveform set
function SoundFont.fallback(): SoundFont
return Fallback.build()
end
-- isSoundFont(v) -> true for a parsed / fallback SoundFont value
function SoundFont.isSoundFont(v: any): boolean
return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table"
end
-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256)
function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State
return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices)
end
return SoundFont
+173
View File
@@ -0,0 +1,173 @@
--!strict
--!native
-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
--
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker)
-- validates the sample buffers' sizes.
local floor, ceil, min = math.floor, math.ceil, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
local Mixer = {}
-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance)
local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number)
local data: buffer = v.data
local nch = v.nch
local inc = v.inc
if not (inc > 0 and inc < 1e6) then
return
end
local len = v.len
local hi = len - 1
local i = 0
local guard = 0
while i < n do
guard += 1
if guard > n + 64 then
return
end
local s, e, t
if v.keyOn and v.susT > 0 then
s, e, t = v.susS, v.susE, v.susT
elseif v.loopT > 0 then
s, e, t = v.loopS, v.loopE, v.loopT
else
s, e, t = 0, len, 0
end
local p = v.p
local dir = v.dir
local count
if dir > 0 then
local lim = if t == 2 then e - 1 else e
if p >= lim then
if t == 0 then
v.active = false
return
elseif t == 1 then
p = s + (p - e) % (e - s)
else
p = 2 * (e - 1) - p
if p < s then
p = s
end
v.dir = -1
end
v.p = p
continue
end
count = ceil((lim - p) / inc)
else
if p < s then
p = 2 * s - p
if p > e - 1 then
p = e - 1
end
v.p = p
v.dir = 1
continue
end
count = floor((p - s) / inc) + 1
end
if count < 1 then
count = 1
end
local m = min(n - i, count)
local step = inc * dir
if out == nil then
v.p = p + step * m
i += m
continue
end
local wrapJ = if t == 1 then s else e - 1
local gl, gr = v.gl, v.gr
local rl = v.rampN
local dl, dr = 0, 0
local tl, tr = v.tl, v.tr
if rl > 0 then
dl, dr = (tl - gl) / rl, (tr - gr) / rl
end
local fOn = v.fOn
local fa, fb0, fb1 = v.fa, v.fb0, v.fb1
local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r
local o = (off + i) * 8
for _ = 1, m do
local idx = floor(p)
if idx > hi then
idx = hi
elseif idx < 0 then
idx = 0
end
local j = idx + 1
if j >= e then
j = wrapJ
end
if j > hi then
j = hi
end
local xl, xr
if nch == 1 then
local a = readf32(data, idx * 4)
if linear then
local b = readf32(data, j * 4)
xl = a + (b - a) * (p - idx)
else
xl = a
end
if fOn then
local y = xl * fa + y1l * fb0 + y2l * fb1
y2l, y1l = y1l, y
xl = y
end
xr = xl
else
local al = readf32(data, idx * 8)
local ar = readf32(data, idx * 8 + 4)
if linear then
local f = p - idx
xl = al + (readf32(data, j * 8) - al) * f
xr = ar + (readf32(data, j * 8 + 4) - ar) * f
else
xl, xr = al, ar
end
if fOn then
local y = xl * fa + y1l * fb0 + y2l * fb1
y2l, y1l = y1l, y
xl = y
y = xr * fa + y1r * fb0 + y2r * fb1
y2r, y1r = y1r, y
xr = y
end
end
if rl > 0 then
gl += dl
gr += dr
rl -= 1
if rl == 0 then
gl, gr = tl, tr
end
end
writef32(out, o, readf32(out, o) + xl * gl)
writef32(out, o + 4, readf32(out, o + 4) + xr * gr)
o += 8
p += step
end
v.p = p
v.gl, v.gr, v.rampN = gl, gr, rl
v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r
i += m
end
local _ = ramp
end
-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions
function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean)
for _, v in st.voices do
if v.active and v.data then
mixVoice(v, out, off, n, linear, 0)
end
end
end
return Mixer
+132
View File
@@ -0,0 +1,132 @@
--!strict
--!native
-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
--
-- Never throws: reads past the source are refused up front (decode returns nil).
local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16
local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16
local floor = math.floor
local Pcm = {}
export type Spec = {
bits: number, -- 8 | 16
signed: boolean,
delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag)
channels: number?, -- 1 (default) | 2
planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved
bigEndian: boolean?,
}
-- bytes(frames, spec) -> the size of the raw data
function Pcm.bytes(frames: number, spec: Spec): number
return frames * (spec.channels or 1) * (spec.bits // 8)
end
-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short
function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer?
local nch = spec.channels or 1
local bps = spec.bits // 8
local total = frames * nch
if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then
return nil
end
local out = buffer.create(total * 4)
local planar = spec.planar and nch == 2
for c = 0, nch - 1 do
local acc = 0
for i = 0, frames - 1 do
local k = if planar then c * frames + i else i * nch + c
local v
if bps == 1 then
if spec.signed then
v = readi8(buf, off + k)
else
v = readu8(buf, off + k) - 128
end
if spec.delta then
acc = (acc + v + 128) % 256 - 128
v = acc
end
writef32(out, (i * nch + c) * 4, v / 128)
else
local p = off + k * 2
if spec.bigEndian then
v = readu8(buf, p) * 256 + readu8(buf, p + 1)
if spec.signed and v >= 32768 then
v -= 65536
end
elseif spec.signed then
v = readi16(buf, p)
else
v = readu16(buf, p)
end
if not spec.signed then
v -= 32768
end
if spec.delta then
acc = (acc + v + 32768) % 65536 - 32768
v = acc
end
writef32(out, (i * nch + c) * 4, v / 32768)
end
end
end
return out
end
-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar)
function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
local nch = spec.channels or 1
local bps = spec.bits // 8
local out = buffer.create(frames * nch * bps)
local planar = spec.planar and nch == 2
local avail = buffer.len(samples) // 4
for c = 0, nch - 1 do
local prev = 0
for i = 0, frames - 1 do
local si = i * nch + c
local x = if si < avail then readf32(samples, si * 4) else 0
local k = if planar then c * frames + i else i * nch + c
if bps == 1 then
local v = math.clamp(floor(x * 128 + 0.5), -128, 127)
local w = v
if spec.delta then
w = (v - prev) % 256
prev = v
else
w = if spec.signed then v % 256 else v + 128
end
writeu8(out, k, w)
else
local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767)
local w = v
if spec.delta then
w = (v - prev + 32768) % 65536 - 32768
prev = v
elseif not spec.signed then
w = v + 32768
if w >= 32768 then
w -= 65536
end
end
writei16(out, k * 2, w)
end
end
end
return out
end
-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16
function Pcm.bitsNeeded(samples: buffer): number
for i = 0, buffer.len(samples) // 4 - 1 do
local x = readf32(samples, i * 4) * 128
if x ~= floor(x) then
return 16
end
end
return 8
end
return Pcm
File diff suppressed because it is too large. Load diff
+113
View File
@@ -0,0 +1,113 @@
--!strict
--!native
-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
local Tables = {}
-- the ProTracker half-sine (32 steps, 0..255)
local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 }
-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic)
local RANDOM: { number } = {}
do
local s = 12345
for i = 1, 64 do
s = (s * 1103515245 + 12345) % 2147483648
RANDOM[i] = (s // 65536) % 511 - 255
end
end
function Tables.wave64(kind: number, pos: number): number
local p = pos % 64
if kind == 1 then
return 255 - p * 8
elseif kind == 2 then
return if p < 32 then 255 else -255
elseif kind == 3 then
return RANDOM[p + 1]
end
local v = SINE32[(p % 32) + 1]
return if p >= 32 then -v else v
end
-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up.
-- IT: 0 sine, 1 ramp down, 2 square, 3 random.
local SINE256: { number } = {}
for i = 0, 255 do
SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5)
end
function Tables.autoWave(kind: number, pos: number, it: boolean): number
local p = pos % 256
if it then
if kind == 1 then
return 64 - (p + 1) // 2
elseif kind == 2 then
return if p < 128 then 64 else -64
elseif kind == 3 then
return RANDOM[(p % 64) + 1] // 4
end
return SINE256[p + 1]
end
if kind == 1 then
return if p < 128 then 64 else -64
elseif kind == 2 then
return 64 - (p + 1) // 2
elseif kind == 3 then
return (p + 1) // 2 - 64
end
return SINE256[p + 1]
end
-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers:
-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at
-- its base rate (8363 Hz).
local PERIODS = {
3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812,
1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113,
107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56,
}
Tables.PERIODS = PERIODS
Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1)
-- periodToNote(period) -> note (1..120), 0 for period 0
function Tables.periodToNote(period: number): number
if period <= 0 then
return 0
end
-- exact match first, then the nearest note on a log scale
for i = 1, #PERIODS do
if PERIODS[i] == period then
return i + Tables.PERIOD_FIRST_NOTE - 1
end
end
local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5)
return math.clamp(n, 1, 120)
end
-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends
function Tables.noteToPeriod(note: number): number
local i = note - Tables.PERIOD_FIRST_NOTE + 1
if i >= 1 and i <= #PERIODS then
return PERIODS[i]
end
return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5))
end
-- IT volume column "g" (tone portamento) speeds
Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }
-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value
Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 }
Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 }
-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate
-- (FT2 / ST3 period units, 4x ProTracker's)
Tables.AMIGA = 8363 * 1712
-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz)
Tables.AMIGA_PAL = 7093789.2 / 2 * 4
return Tables
+516
View File
@@ -0,0 +1,516 @@
--!strict
-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
--
-- local Tracker = require("@formats/codecs/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
--
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks
-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s)
-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume)
-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index)
-- linear linear frequency slides (XM / IT flag) or Amiga periods
-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column
-- is a sample number (MOD, S3M, IT sample mode)
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) }
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 =
-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5
-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the
-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored;
-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1
-- (0 = none). Tracker.cell / Tracker.setCell read and write cells.
-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16,
-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong),
-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil),
-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth /
-- vibRate (IT auto-vibrato) }
-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note },
-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut,
-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off,
-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre),
-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) }
-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart,
-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) }
--
-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768).
-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add
-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT:
-- base = c5speed, ref 61.
--
-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Player = require("@formats/codecs/Tracker/Player")
local Mixer = require("@formats/codecs/Tracker/Mixer")
local Pcm = require("@formats/codecs/Tracker/Pcm")
local Tables = require("@formats/codecs/Tracker/Tables")
local Tracker = {}
Tracker.Pcm = Pcm
Tracker.Tables = Tables
export type Envelope = {
enabled: boolean,
ticks: { number },
values: { number },
loop: boolean,
loopStart: number,
loopEnd: number,
sustain: boolean,
susStart: number,
susEnd: number,
carry: boolean?,
filter: boolean?,
raw: any?, -- format-specific fields kept for a faithful re-save (XM)
}
export type Pattern = { rows: number, data: buffer }
export type RenderOptions = {
sampleRate: number?, -- default 44100
interpolation: ("linear" | "none")?, -- default "linear"
stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre)
loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false
maxDuration: number?, -- seconds; the render stops there (default 3600)
}
local CELL = 5
-- ------------------------------------------------------------------------------------------------ constructors
-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults
function Tracker.newModule(format: string, channels: number): any
local m = {
kind = "music",
format = format,
title = "",
channels = channels,
speed = 6,
tempo = 125,
globalVolume = 128,
mixVolume = 48,
order = {},
restart = 0,
linear = format == "xm" or format == "it",
instrumentMode = format == "xm" or format == "it",
flags = {},
channelPan = {},
channelVolume = {},
channelMute = {},
patterns = {},
instruments = {},
samples = {},
meta = {},
render = Tracker.renderMethod,
}
for i = 1, channels do
m.channelVolume[i] = 64
if format == "mod" then
local k = (i - 1) % 4
m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width
else
m.channelPan[i] = 128
end
end
return m
end
-- newPattern(rows, channels) -> an empty Pattern
function Tracker.newPattern(rows: number, channels: number): Pattern
return { rows = rows, data = buffer.create(rows * channels * CELL) }
end
-- newSample() -> an empty Sample
function Tracker.newSample(name: string?): any
return {
name = name or "",
data = buffer.create(0),
length = 0,
channels = 1,
bits = 8,
loopStart = 0,
loopEnd = 0,
loopType = 0,
susStart = 0,
susEnd = 0,
susType = 0,
volume = 64,
globalVolume = 64,
pan = nil :: number?,
c5speed = 8363,
relativeNote = 0,
finetune = 0,
vibType = 0,
vibSweep = 0,
vibDepth = 0,
vibRate = 0,
}
end
function Tracker.newEnvelope(): Envelope
return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 }
end
-- newInstrument() -> an Instrument mapping every note to sample 0 (none)
function Tracker.newInstrument(name: string?): any
local sm, nm = table.create(120, 0), table.create(120, 0)
for i = 1, 120 do
nm[i] = i
end
return {
name = name or "",
sampleMap = sm,
noteMap = nm,
volEnv = nil :: Envelope?,
panEnv = nil :: Envelope?,
pitchEnv = nil :: Envelope?,
fadeout = 0,
nna = 0,
dct = 0,
dca = 0,
globalVolume = 128,
pan = nil :: number?,
pps = 0,
ppc = 60,
cutoff = nil :: number?,
resonance = nil :: number?,
vibType = 0,
vibSweep = 0,
vibDepth = 0,
vibRate = 0,
}
end
-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based,
-- channel 1-based); nil when out of range
function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number)
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
return nil, 0, 0, 0, 0
end
local o = (row * m.channels + channel - 1) * CELL
local d = p.data
return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
end
-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range)
function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
return false
end
local o = (row * m.channels + channel - 1) * CELL
local d = p.data
buffer.writeu8(d, o, note % 256)
buffer.writeu8(d, o + 1, ins % 256)
buffer.writeu8(d, o + 2, vol % 256)
buffer.writeu8(d, o + 3, fx % 256)
buffer.writeu8(d, o + 4, param % 256)
return true
end
-- ------------------------------------------------------------------------------------------------ validation
local function num(v: any, lo: number, hi: number): boolean
return type(v) == "number" and v == v and v >= lo and v <= hi
end
local function fixEnvelope(e: any): (any, string?)
if e == nil then
return nil
end
if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then
return nil, "bad envelope"
end
local n = math.min(#e.ticks, #e.values)
local last = -1
for i = 1, n do
local t, v = e.ticks[i], e.values[i]
if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then
-- points must go forward: keep the valid prefix
n = i - 1
break
end
last = t
end
for i = #e.ticks, n + 1, -1 do
e.ticks[i] = nil
end
for i = #e.values, n + 1, -1 do
e.values[i] = nil
end
if n == 0 then
e.enabled = false
end
local function idx(v: any): number
return if num(v, 1, math.max(1, n)) then math.floor(v) else 1
end
e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd)
e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd)
if e.loopEnd < e.loopStart then
e.loop = false
end
if e.susEnd < e.susStart then
e.sustain = false
end
return e
end
local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number)
if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then
return 0, 0, 0
end
local s: number = math.floor(math.clamp(s0, 0, len))
local e: number = math.floor(math.clamp(e0, 0, len))
local t: number = math.floor(t0)
if e - s < 1 or t == 0 then
return 0, 0, 0
end
if t == 2 and e - s < 2 then
t = 1
end
return s, e, t
end
-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and
-- numbers into range (in place)
function Tracker.validate(m: any): (boolean?, Err.Err?)
if type(m) ~= "table" then
return nil, Err.new(Err.ARG, "not a module")
end
if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format))
end
if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then
return nil, Err.new(Err.ARG, "bad channel count")
end
if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then
return nil, Err.new(Err.ARG, "module without order / patterns / samples")
end
m.instruments = if type(m.instruments) == "table" then m.instruments else {}
m.flags = if type(m.flags) == "table" then m.flags else {}
m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {}
m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {}
m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {}
for i = 1, m.channels do
local p = m.channelPan[i]
if p ~= 512 and not num(p, 0, 256) then
m.channelPan[i] = 128
end
if not num(m.channelVolume[i], 0, 64) then
m.channelVolume[i] = 64
end
end
m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6
m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125
m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128
m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48
m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0
for i, o in m.order do
if not num(o, 0, 255) then
return nil, Err.new(Err.ARG, "bad order entry " .. i)
end
end
for i, p in m.patterns do
if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then
return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1))
end
end
for i, s in m.samples do
if type(s) ~= "table" then
return nil, Err.new(Err.ARG, "bad sample " .. i)
end
local nch = if s.channels == 2 then 2 else 1
s.channels = nch
if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then
return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length")
end
s.length = math.floor(s.length)
s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length)
s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length)
s.volume = if num(s.volume, 0, 64) then s.volume else 64
s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64
if s.pan ~= nil and not num(s.pan, 0, 256) then
s.pan = nil
end
s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363
s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0
s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0
end
for i, ins in m.instruments do
if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then
return nil, Err.new(Err.ARG, "bad instrument " .. i)
end
for n = 1, 120 do
if not num(ins.sampleMap[n], 0, 1e6) then
ins.sampleMap[n] = 0
end
if not num(ins.noteMap[n], 1, 120) then
ins.noteMap[n] = n
end
end
local err
ins.volEnv, err = fixEnvelope(ins.volEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.panEnv, err = fixEnvelope(ins.panEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.pitchEnv, err = fixEnvelope(ins.pitchEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0
ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128
if ins.pan ~= nil and not num(ins.pan, 0, 256) then
ins.pan = nil
end
if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then
ins.cutoff = nil
end
if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then
ins.resonance = nil
end
end
return true, nil
end
-- ------------------------------------------------------------------------------------------------ rendering
local Decoder = {}
Decoder.__index = Decoder
-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err
function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?)
local ok, err = Tracker.validate(m)
if not ok then
return nil, err
end
local sr = opts and opts.sampleRate or 44100
local maxFrames = (opts and opts.maxDuration or 3600) * sr
local st = Player.new(m, sr, { stereoSeparation = 100 })
local frames = 0
while frames < maxFrames do
local f = Player.tick(st)
if f == 0 and st.ended then
break
end
frames += f
end
return math.min(frames, maxFrames) / sr, nil
end
local function newPlayer(self: any)
self.st = Player.new(self.module, self.sampleRate, self.opts)
self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015))
self.left = 0
self.pos = 0
end
-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err
function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
local o: RenderOptions = opts or {}
local sr = o.sampleRate or 44100
if type(sr) ~= "number" or sr < 1000 or sr > 384000 then
return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000")
end
local seconds, err = Tracker.duration(m, o)
if not seconds then
return nil, err
end
local frames = math.floor(seconds * sr + 0.5)
local self = setmetatable({
sampleRate = sr,
channels = 2,
frames = frames,
duration = frames / sr,
bitrate = 0,
tags = { title = m.title or "" },
module = m,
opts = o,
linear = o.interpolation ~= "none",
maxFrames = (o.maxDuration or 3600) * sr,
st = nil :: any,
left = 0,
pos = 0,
}, Decoder)
newPlayer(self)
return self :: any, nil
end
-- the Module method: module:render(opts)
function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder
local dec = Tracker.render(self, opts)
return dec :: any
end
-- run(self, out?, n) -> frames produced (out nil: advance without mixing)
local function run(self: any, out: buffer?, n: number): number
local st = self.st
local done = 0
while done < n do
if self.left <= 0 then
if self.pos + done >= self.maxFrames then
break
end
local f = Player.tick(st)
if f == 0 and st.ended then
break
end
self.left = f
if f == 0 then
continue
end
end
local k = math.min(self.left, n - done)
Mixer.mix(st, out, done, k, self.linear)
self.left -= k
done += k
end
self.pos += done
return done
end
-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end)
function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
n = math.max(0, math.floor(tonumber(n) or 0))
local o = out
if o == nil or buffer.len(o) < n * 8 then
o = buffer.create(n * 8)
else
buffer.fill(o, 0, 0, n * 8)
end
local got = run(self, o, n)
return o :: buffer, got
end
-- seek(seconds): replays the song silently up to the position (sample positions included)
function Decoder.seek(self: any, seconds: number)
local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate))
newPlayer(self)
local chunk = 65536
while self.pos < target do
local got = run(self, nil, math.min(chunk, target - self.pos))
if got == 0 then
break
end
end
-- the gains ramp in from silence after a seek
for _, v in self.st.voices do
v.gl, v.gr = 0, 0
end
end
function Decoder.position(self: any): number
return self.pos / self.sampleRate
end
return Tracker
+305
View File
@@ -0,0 +1,305 @@
--!strict
-- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given:
-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either
-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM,
-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw
-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau.
--
-- local streams, err = Source.streams(value, opts, {
-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any)
-- audio = { copy = { opus = true, vorbis = true }, pcm = true },
-- })
-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config,
-- -- track, packets = { { pts, duration (seconds), keyframe, data } } }
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Yuv = require("@formats/codecs/Yuv")
local Source = {}
export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer }
export type Stream = {
kind: "video" | "audio",
codec: string,
copied: boolean,
width: number?,
height: number?,
frameRate: number?,
sampleRate: number?,
channels: number?,
bitsPerSample: number?,
config: buffer?,
track: Types.Track?,
packets: { OutPacket },
}
export type Want = {
video: { copy: { [string]: boolean }?, encode: string? }?,
audio: { copy: { [string]: boolean }?, pcm: boolean? }?,
}
local function allows(set: { [string]: boolean }?, codec: string): boolean
return set ~= nil and (set[codec] == true or set["*"] == true)
end
-- the packets of a source track, times in seconds
local function copyPackets(dmx: any, track: Types.Track): { OutPacket }
local out = {}
local scale = if track.timescale and track.timescale > 0 then track.timescale else 1
local n = dmx:count(track.id)
for k = 1, n do
local p = dmx:get(track.id, k)
if p then
table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data })
end
end
return out
end
local function trackStream(track: Types.Track, packets: { OutPacket }): Stream
return {
kind = track.kind :: any,
codec = track.codec,
copied = true,
width = track.width,
height = track.height,
frameRate = track.frameRate,
sampleRate = track.sampleRate,
channels = track.channels,
bitsPerSample = track.bitsPerSample,
config = track.config,
track = track,
packets = packets,
}
end
-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo":
-- yuv420p planes)
local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?)
local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil
if codec ~= "rawvideo" then
local Video = require("@formats/codecs/Video")
local e = Video.entry(codec)
encode = e and e.encode
if not encode then
return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder")
end
end
if type(v.reset) == "function" then
v:reset()
end
local packets: { OutPacket } = {}
local w, h = v.width, v.height
local maxFrames = opts.maxFrames or math.huge
while #packets < maxFrames do
local f, err = v:nextFrame()
if not f then
if err then
return nil, err
end
break
end
local img: Types.Image = f.image
if (w == 0 or h == 0) and #packets == 0 then
w, h = img.width, img.height
end
if img.width ~= w or img.height ~= h then
return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")")
end
local data: buffer?
if codec == "rawvideo" then
local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601")
if not y then
return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format)
end
data = y.pixels
else
local e2
data, e2 = (encode :: any)(img, opts)
if not data then
return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode")
end
end
table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer })
end
if #packets == 0 then
return nil, Err.new(Err.ARG, "no frames to write")
end
local fr = v.frameRate
if not fr or fr <= 0 then
local d = packets[1].duration
fr = if d > 0 then 1 / d else 25
end
return {
kind = "video",
codec = codec,
copied = false,
width = w,
height = h,
frameRate = fr,
packets = packets,
} :: Stream, nil
end
-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096)
local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
local ch, rate = dec.channels, dec.sampleRate
if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then
return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate")
end
pcall(dec.seek, dec, 0)
local chunk = opts.audioChunk or 4096
local packets: { OutPacket } = {}
local pos = 0
local tmp: buffer? = nil
while true do
local ok, out, n = pcall(dec.read, dec, chunk, tmp)
if not ok or not out or not n or n <= 0 then
break
end
tmp = out
local data = buffer.create(n * ch * 2)
for i = 0, n * ch - 1 do
local s = buffer.readf32(out, i * 4)
local v = math.floor(s * 32768 + 0.5)
if v > 32767 then
v = 32767
elseif v < -32768 then
v = -32768
elseif v ~= v then
v = 0
end
buffer.writei16(data, i * 2, v)
end
table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data })
pos += n
end
return {
kind = "audio",
codec = "pcm_s16le",
copied = false,
sampleRate = rate,
channels = ch,
bitsPerSample = 16,
packets = packets,
} :: Stream, nil
end
-- streams(value, opts, want) -> { Stream } | nil, Err
function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then
return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer")
end
local dmx = if value.kind == "demuxer" then value else value.demuxer
local out: { Stream } = {}
-- video
local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video"))
local wv = want.video
if wv and o.video ~= false then
if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then
table.insert(out, trackStream(vt, copyPackets(dmx, vt)))
elseif value.kind == "video" and wv.encode then
local s, err = encodeFrames(value, wv.encode, o)
if not s then
return nil, err
end
table.insert(out, s)
elseif vt then
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)"))
end
end
-- audio
local wa = want.audio
if wa and o.audio ~= false then
local at: Types.Track? = dmx and dmx:track("audio")
if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then
table.insert(out, trackStream(at, copyPackets(dmx, at)))
elseif wa.pcm and value.kind == "video" and value.audio then
local s, err = pcmFrom(value.audio, o)
if not s then
return nil, err
end
if #s.packets > 0 then
table.insert(out, s)
end
elseif at and o.audio == true then
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container")
end
end
if #out == 0 then
return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)")
end
return out, nil
end
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
function Source.rational(fps: number): (number, number)
if fps ~= fps or fps <= 0 then
return 25, 1
end
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
return math.floor(fps + 0.5), 1
end
local ntsc = fps * 1001 / 1000
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
return math.floor(ntsc + 0.5) * 1000, 1001
end
return math.floor(fps * 1000 + 0.5), 1000
end
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
local fd = math.huge
for _, p in s.packets do
if p.duration and p.duration > 0 and p.duration < fd then
fd = p.duration
end
end
if fd == math.huge then
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
end
fd = math.max(fd, 1 / (maxFps or 100))
local num, den = Source.rational(1 / fd)
local step = den / num
local out: { OutPacket } = {}
local slots = 0
local t0 = if s.packets[1] then s.packets[1].pts else 0
for _, p in s.packets do
local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step)
local n = math.max(1, math.floor(stop / step + 0.5) - slots)
for _ = 1, n do
table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data })
slots += 1
end
end
return num, den, out
end
-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its
-- own order
function Source.interleave(streams: { Stream }): { { any } }
local order = {}
local pos = table.create(#streams, 1)
while true do
local best, bt = 0, math.huge
for si, s in streams do
local p = s.packets[pos[si]]
if p then
local t = p.dts or p.pts
if best == 0 or t < bt then
best, bt = si, t
end
end
end
if best == 0 then
break
end
table.insert(order, { best, streams[best].packets[pos[best]] })
pos[best] += 1
end
return order
end
return Source
+584
View File
@@ -0,0 +1,584 @@
--!strict
-- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
--
-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them
-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a
-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc /
-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs
-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry).
--
-- local Video = require("@formats/codecs/Video")
-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8"
-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder)
-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open())
-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP)
--
-- Never throws: bad data / missing codecs come back as nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Yuv = require("@formats/codecs/Yuv")
local Video = {}
export type Entry = {
id: string, -- our codec id
name: string, -- a human name
fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs
matroska: { string }?, -- Matroska / WebM CodecIDs
-- new(track, opts) -> a decoder instance (nil = decode not supported)
new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?,
[string]: any,
}
-- ------------------------------------------------------------------------------------------------ simple decoders
-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no
-- picture to show, such as a hidden VP8 altref frame)
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
local queue: { any } = {}
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, img, err = pcall(decodeOne, packet.data, packet)
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img))
end
if img then
table.insert(queue, { img, packet.pts, packet.keyframe })
end
return err
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(queue)
if resetFn then
resetFn()
end
end
return self :: any
end
-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged
-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 /
-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows)
local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image
local img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
local cw, ch = (w + 1) // 2, (h + 1) // 2
local bps = if bits > 8 then 2 else 1
local shift = 2 ^ (bits - 8)
local function sample(o: number): number
if bps == 1 then
return buffer.readu8(data, o)
end
return math.min(255, buffer.readu16(data, o) // shift)
end
for i = 0, w * h - 1 do
buffer.writeu8(px, i, sample(i * bps))
end
local scw, sch = w, h -- source chroma plane size
if pf == "yuv420p" then
scw, sch = cw, ch
elseif pf == "yuv422p" then
scw, sch = cw, h
end
local uo, vo = w * h * bps, (w * h + scw * sch) * bps
for cy = 0, ch - 1 do
for cx = 0, cw - 1 do
local i = cy * cw + cx
local u, v
if pf == "gray" then
u, v = 128, 128
elseif pf == "yuv420p" then
u, v = sample(uo + i * bps), sample(vo + i * bps)
elseif pf == "yuv422p" then
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2
v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2
else
local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1)
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps
u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4
v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4
end
buffer.writeu8(px, w * h + i, u)
buffer.writeu8(px, w * h + cw * ch + i, v)
end
end
return img
end
local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = {
yuv420p = function(w, h, cw, ch)
return w * h + 2 * cw * ch
end,
yv12 = function(w, h, cw, ch)
return w * h + 2 * cw * ch
end,
yuv422p = function(w, h, cw, _ch)
return w * h + 2 * cw * h
end,
yuv444p = function(w, h)
return w * h * 3
end,
yuva444p = function(w, h)
return w * h * 4
end,
gray = function(w, h)
return w * h
end,
}
local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local w, h = track.width or 0, track.height or 0
if w <= 0 or h <= 0 or w * h > 2 ^ 26 then
return nil, Err.new(Err.CORRUPT, "raw video without a valid size")
end
local pf = track.pixelFormat or "yuv420p"
local bits = track.bitDepth or 8
local cw, ch = (w + 1) // 2, (h + 1) // 2
local flip = track.flip == true
local planar = PLANAR_SIZE[pf]
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local n = buffer.len(data)
if planar then
local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1)
if n < need then
return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes")
end
if pf == "yuv420p" and bits == 8 then
local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, need)
return img
elseif pf == "yv12" then
local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, w * h)
buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch)
buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch)
return img
end
return rawPlanar(data, pf, bits, w, h)
end
local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3
local stride = if track.stride then track.stride else w * bpp
if n < stride * (h - 1) + w * bpp then
return nil, Err.new(Err.TRUNCATED, "raw frame too short")
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
local bgr = pf == "bgr24" or pf == "bgra"
for y = 0, h - 1 do
local s = (if flip then h - 1 - y else y) * stride
local o = y * w * 4
for x = 0, w - 1 do
local p = s + x * bpp
local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2)
if bgr then
a, c = c, a
end
buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000)
end
end
return img
end)
end
local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Vp8 = require("@formats/codecs/Vp8")
local dec = Vp8.newDecoder()
local o = { maxPixels = opts and opts.maxPixels }
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local img, err = dec:decodeFrame(data, 0, buffer.len(data), o)
if not img then
return nil, err
end
local src = img.meta.source
if type(src) == "table" and src.show == false then
return nil, nil
end
img.meta.yuv = { range = "limited", matrix = "bt601" }
return img, nil
end, function()
if dec.reset then
dec:reset()
else
dec = Vp8.newDecoder()
end
end)
end
-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout
-- allows, else rgba8
local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Jpeg = require("@formats/codecs/Jpeg")
local o = { yuv = true, maxPixels = opts and opts.maxPixels }
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local img, err = Jpeg.decode(data, 0, buffer.len(data), o)
if img and img.format == "yuv420p" then
img.meta.yuv = { range = "full", matrix = "bt601" }
end
return img, err
end)
end
-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first
local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
local Jpeg = require("@formats/codecs/Jpeg")
local src = img
if img.format == "yuv420p" then
local range = Yuv.info(img)
if range ~= "full" then
src = Yuv.toFullRange(img)
end
end
return Jpeg.encode(src, { quality = opts and opts.quality or 90 })
end
-- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture)
local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Mpeg1 = require("@formats/codecs/Mpeg1")
local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
local function push(f: any)
local img = Mpeg1.frameImage(f)
if img then
img.meta.yuv = { range = "limited", matrix = "bt601" }
local tag = f.tag
table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 })
end
end
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts })
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
if f then
push(f)
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil
end
function self.flush(_: any)
for _ = 1, 4 do
local f = dec:flush()
if not f then
break
end
push(f)
end
end
function self.reset(_: any)
dec:reset()
table.clear(queue)
end
return self :: any, nil
end
-- H.264 / AVC (codecs/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264);
-- pictures in display order with the pts of their packet
local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local H264 = require("@formats/codecs/H264")
return H264.newVideoDecoder(track, opts)
end
-- ------------------------------------------------------------------------------------------------ registry
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
local BUILTIN: { Entry } = {
{ id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder },
{ id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode },
{ id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder },
{ id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder },
{ id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } },
{ id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } },
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder },
{ id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } },
{ id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } },
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" } },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
}
local byId: { [string]: Entry } = {}
local byFourcc: { [string]: string } = {}
local byMatroska: { [string]: string } = {}
-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it
function Video.register(entry: Entry): (boolean, Err.Err?)
if type(entry) ~= "table" or type(entry.id) ~= "string" then
return false, Err.new(Err.ARG, "register: needs an entry with an id")
end
local old = byId[entry.id]
if old and entry.new == nil then
entry.new = old.new
end
byId[entry.id] = entry
for _, f in entry.fourcc or {} do
byFourcc[f] = entry.id
end
for _, m in entry.matroska or {} do
byMatroska[m] = entry.id
end
return true
end
for _, e in BUILTIN do
Video.register(e)
end
-- the registry (read only by convention): id -> Entry
Video.codecs = byId
-- fromFourcc(fourcc) -> codec id | nil
function Video.fromFourcc(fcc: string): string?
return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)]
end
-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...)
function Video.fromMatroska(id: string): string?
return byMatroska[id]
end
-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil
function Video.entry(id: string): Entry?
return byId[id]
end
-- canDecode(codecId) -> boolean
function Video.canDecode(id: string): boolean
local e = byId[id]
return e ~= nil and e.new ~= nil
end
-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered)
function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local e = byId[track.codec]
if not e or not e.new then
return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec))
end
local ok, dec, err = pcall(e.new :: any, track, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec))
end
return dec, err
end
-- ------------------------------------------------------------------------------------------------ VideoDecoder
local function toRGBA(_self: any, f: any): Types.Image
local img = if type(f) == "table" and f.image then f.image else f
local out = Yuv.imageToRgba(img)
return out or img
end
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p)
track: number?, -- the video track id (default: the first video track)
maxPixels: number?,
openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook
audio: boolean?, -- false: do not open the audio track
[string]: any,
}
-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through
-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and
-- the demuxer (remuxing) and audio work.
function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local o: OpenOptions = opts or {}
local track: Types.Track? = nil
if o.track then
for _, t in demuxer.tracks do
if t.id == o.track then
track = t
end
end
if not track then
return nil, Err.new(Err.ARG, "no track " .. tostring(o.track))
end
else
track = demuxer:track("video")
end
local codec: Types.VideoCodecDecoder? = nil
local codecErr: Err.Err? = nil
if track then
codec, codecErr = Video.decoder(track, o)
else
codecErr = Err.new(Err.UNSUPPORTED, "no video track")
end
local v: any = {
kind = "video",
format = demuxer.format,
codec = if track then track.codec else "none",
width = if track then track.width or 0 else 0,
height = if track then track.height or 0 else 0,
frameRate = if track then track.frameRate or 0 else 0,
frames = if track then track.frames or 0 else 0,
duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration,
track = track,
demuxer = demuxer,
meta = demuxer.meta or {},
decodeError = codecErr,
toRGBA = toRGBA,
}
if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then
v.frames = math.floor(v.duration * v.frameRate + 0.5)
end
-- audio
if o.audio ~= false then
local at = demuxer:track("audio")
if at then
if o.openAudio then
local ok, dec, err = pcall(o.openAudio, demuxer, at)
if ok and dec then
v.audio = dec
else
v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec))
end
else
v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)")
end
end
end
local index, flushed, skipUntil = 0, false, -math.huge
local tid = if track then track.id else -1
local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000
local start = demuxer.startTime or 0
v.startTime = start
local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0
local lastPts = nil :: number?
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
if not codec then
return nil, codecErr
end
local dec = codec :: Types.VideoCodecDecoder
while true do
local img, pts, key = dec:receive()
if img then
local t = (pts or 0) / scale - start
if t + 1e-9 >= skipUntil then
index += 1
local d = defaultDur
if lastPts and t > lastPts and defaultDur == 0 then
d = t - lastPts
end
lastPts = t
if o.rgba then
img = Yuv.imageToRgba(img) or img
end
return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil
end
else
local p = demuxer:read(tid)
if p == nil then
if flushed then
return nil, nil
end
flushed = true
dec:flush()
else
local err = dec:decode(p)
if err then
return nil, err
end
end
end
end
end
function v.seek(self: any, seconds: number)
demuxer:seek(seconds + start)
if codec then
codec:reset()
end
flushed = false
skipUntil = seconds
lastPts = nil
if self.audio then
pcall(self.audio.seek, self.audio, seconds)
end
end
function v.reset(self: any)
self:seek(0)
skipUntil = -math.huge
index = 0
end
return v, nil
end
-- ------------------------------------------------------------------------------------------------ frames-backed
-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after
-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded.
function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?)
if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then
return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images")
end
local w, h = images[1].width, images[1].height
local pts: { number } = {}
local durs: { number } = {}
local t = 0
for i, img in images do
if type(img) ~= "table" or img.width ~= w or img.height ~= h then
return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image")
end
local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1)
if type(d) ~= "number" or d ~= d or d < 0 then
d = 0.1
end
pts[i] = t
durs[i] = d
t += d
end
local n = #images
local o = opts or {}
local v: any = {
kind = "video",
format = o.format or "frames",
codec = "frames",
width = w,
height = h,
frameRate = if t > 0 then n / t else 10,
frames = n,
duration = t,
loops = o.loops,
meta = o.meta or {},
toRGBA = toRGBA,
images = images,
}
local i = 0
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
i += 1
if i > n then
i = n
return nil, nil
end
local img = images[i]
if o.rgba then
img = Yuv.imageToRgba(img) or img
end
return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil
end
function v.seek(self: any, seconds: number)
local k = 0
for j = 1, n do
if pts[j] <= seconds + 1e-9 then
k = j - 1
end
end
i = k
end
function v.reset(self: any)
i = 0
end
return v, nil
end
return Video
File diff suppressed because it is too large. Load diff
+274
View File
@@ -0,0 +1,274 @@
--!strict
--!native
--!optimize 2
-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
local Tables = require("@formats/codecs/Vp8/Tables")
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local rshift, band = bit32.rshift, bit32.band
local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR
local Predict = {}
local BORDER = 32
Predict.BORDER = BORDER
-- the work buffer stride (codecs/Vp8/Decode: BPS)
local BPS = 32
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter
-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads
-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator).
local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local k = f * 6
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
for _ = 1, h do
for i = so - 2, so + w - 3 do
local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3
+ readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64
writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
end
so += ss
d += ds
end
end
-- the six-tap filter along columns
local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local k = f * 6
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
local s1, s2, s3 = ss, 2 * ss, 3 * ss
for _ = 1, h do
local p = so - s2
for i = 0, w - 1 do
local q = p + i
local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3
+ readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64
writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
end
so += ss
d += ds
end
end
-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7
local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
for _ = 1, h do
for i = 0, w - 1 do
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7))
end
so += ss
d += ds
end
end
local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
for _ = 1, h do
for i = 0, w - 1 do
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7))
end
so += ss
d += ds
end
end
-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel
-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax,
-- hmax: the last pixel column / row of the (macroblock aligned) plane.
local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean)
local fx, fy = band(mvx, 7), band(mvy, 7)
local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8
local sb, so, ss = src, 0, stride
if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then
so = base + py * stride + px
else
for r = 0, h + 4 do
local sy = py - 2 + r
if sy < 0 then
sy = 0
elseif sy > hmax then
sy = hmax
end
local row = base + sy * stride
local o = r * 32
for c = 0, w + 4 do
local sx = px - 2 + c
if sx < 0 then
sx = 0
elseif sx > wmax then
sx = wmax
end
writeu8(emu, o + c, readu8(src, row + sx))
end
end
sb, so, ss = emu, 66, 32
end
if fx == 0 then
if fy == 0 then
for _ = 1, h do
for i = 0, w - 4, 4 do
writeu32(dst, d + i, readu32(sb, so + i))
end
so += ss
d += BPS
end
elseif bil then
bilV(sb, so, ss, dst, d, BPS, w, h, fy)
else
sixV(sb, so, ss, dst, d, BPS, w, h, fy)
end
elseif fy == 0 then
if bil then
bilH(sb, so, ss, dst, d, BPS, w, h, fx)
else
sixH(sb, so, ss, dst, d, BPS, w, h, fx)
end
elseif bil then
bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx)
bilV(tmp, 0, 32, dst, d, BPS, w, h, fy)
else
sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx)
sixV(tmp, 64, 32, dst, d, BPS, w, h, fy)
end
end
local function chroma16(v: number): number
-- the chroma vector of a whole macroblock: half the luma one, rounded away from zero
if v < 0 then
return -((1 - v) // 2)
end
return (v + 1) // 2
end
local function chroma4(s: number): number
-- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero
if s < 0 then
return -((4 - s) // 8)
end
return (s + 4) // 8
end
export type Planes = {
Y: buffer,
U: buffer,
V: buffer,
ys: number, -- luma stride
uvs: number, -- chroma stride
yb: number, -- offset of luma pixel (0, 0)
uvb: number,
mbw: number,
mbh: number,
}
-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter
-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels;
-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them).
function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb
local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1
local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1
local x, y = mbx * 16, mby * 16
local cx, cy = mbx * 8, mby * 8
if part < 0 then
block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil)
local cr, cc = chroma16(mvr), chroma16(mvc)
if full then
cr -= band(cr, 7)
cc -= band(cc, 7)
end
block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil)
block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil)
return
end
if part < 3 then
for q = 0, 3 do
local bx, by = (q % 2) * 8, (q // 2) * 8
local k = sb + by + bx // 4 + 1
block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil)
end
else
for b = 0, 15, 2 do
local k = sb + b + 1
local bx, by = (b % 4) * 4, (b // 4) * 4
local r0, c0 = subR[k], subC[k]
if r0 == subR[k + 1] and c0 == subC[k + 1] then
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil)
else
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil)
block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil)
end
end
end
for i = 0, 1 do
local rr, rc = 0, 0
for j = 0, 1 do
local k = sb + i * 8 + j * 2 + 1
local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5])
local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5])
if full then
cr -= band(cr, 7)
cc -= band(cc, 7)
end
if j == 0 then
rr, rc = cr, cc
elseif cr == rr and cc == rc then
-- both 4x4 chroma blocks of the row share one vector: one 8x4 block
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil)
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil)
else
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil)
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil)
block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil)
block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil)
end
end
end
end
-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the
-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo;
-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder).
function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
for mbx = 0, mbw - 1 do
local rf = ref[mbx + 1]
if rf > 0 then
local mi = mi0 + mbx + 1
local o = mbx * chunk
Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full)
end
end
end
-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels
local function extend(P: buffer, stride: number, base: number, w: number, h: number)
for r = 0, h - 1 do
local o = base + r * stride
bfill(P, o - BORDER, readu8(P, o), BORDER)
bfill(P, o + w, readu8(P, o + w - 1), BORDER)
end
local top = base - BORDER
local bottom = base + (h - 1) * stride - BORDER
for r = 1, BORDER do
bcopy(P, top - r * stride, P, top, stride)
bcopy(P, bottom + r * stride, P, bottom, stride)
end
end
function Predict.extend(ref: Planes)
extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16)
extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
end
return Predict
+70 -1
View File
@@ -1,6 +1,9 @@
--!strict
-- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays.
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables
-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from
-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c;
-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays.
local Tables = {}
-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1
@@ -177,4 +180,70 @@ Tables.CAT4 = { 176, 155, 140, 135 }
Tables.CAT5 = { 180, 157, 141, 134, 130 }
Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }
-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones
Tables.YMODE_PROB = { 112, 86, 140, 37 }
Tables.UVMODE_PROB = { 162, 101, 204 }
Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 }
-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10)
Tables.MV_DEFAULT = {
162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254,
164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254,
}
Tables.MV_UPDATE = {
237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254,
231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254,
}
-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1
Tables.MODE_CONTEXTS = {
7, 1, 1, 143,
14, 18, 14, 107,
135, 64, 57, 68,
60, 56, 128, 65,
159, 134, 128, 34,
234, 188, 128, 28,
}
-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3]
Tables.SUB_MV_REF_PROB = {
147, 136, 18,
223, 1, 34,
106, 145, 1,
208, 1, 1,
179, 121, 1,
223, 1, 34,
179, 121, 1,
208, 1, 1,
}
-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each
-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition
Tables.SPLIT_OFFSET = {
0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
}
Tables.SPLIT_FILL = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
}
Tables.SPLIT_COUNT = { 8, 8, 4, 1 }
-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3)
Tables.SIXTAP = {
0, 0, 128, 0, 0, 0,
0, -6, 123, 12, -1, 0,
2, -11, 108, 36, -8, 1,
0, -9, 93, 50, -6, 0,
3, -16, 77, 77, -16, 3,
0, -6, 50, 93, -9, 0,
1, -8, 36, 108, -11, 2,
0, -1, 12, 123, -6, 0,
}
Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 }
return Tables
+30 -14
View File
@@ -1,16 +1,23 @@
--!strict
-- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
-- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause,
-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause,
-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`.
-- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions,
-- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object
-- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does).
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause,
-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams.
-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear;
-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with
-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save /
-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error
-- concealment (a damaged frame returns an Err).
-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace
-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps).
--
-- local Vp8 = require("@formats/codecs/Vp8")
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header)
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image
-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
-- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM)
-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames
-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame
-- dec:reset() -- after a seek: the next frame must be a key frame
--
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
local Err = require("@formats/core/Err")
@@ -67,7 +74,9 @@ function Vp8.newDecoder(): Decoder
return setmetatable({ state = Decode.new() }, DecoderMeta)
end
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames;
-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed),
-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT.
function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
if type(buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer")
@@ -79,14 +88,18 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
end
local img = Types.Image.new(f.width, f.height, "yuv420p")
local ny = f.width * f.height
local nc = buffer.len(f.u)
buffer.copy(img.pixels, 0, f.y, 0, ny)
buffer.copy(img.pixels, ny, f.u, 0, nc)
buffer.copy(img.pixels, ny + nc, f.v, 0, nc)
img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile }
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc)
local h = f.header
img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height }
return img, nil
end
-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame
function DecoderMeta.reset(self: Decoder)
Decode.reset(self.state)
end
-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame)
function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
return Vp8.newDecoder():decodeFrame(buf, off, len, opts)
@@ -102,7 +115,10 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options
if not f then
return nil, fail(err, o)
end
return f.y, f.u, f.v, f.width, f.height
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc)
Decode.cropTo(f, y, 0, u, 0, v, 0)
return y, u, v, f.width, f.height
end
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
+225
View File
@@ -0,0 +1,225 @@
--!strict
--!native
--!optimize 2
-- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range.
-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the
-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma
-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this).
--
-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255)
-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2))
-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image
local Types = require("@formats/Types")
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
local bcreate = buffer.create
local floor = math.floor
local Yuv = {}
-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u
-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224
local MATRIX = {
bt601 = { kr = 0.299, kb = 0.114 },
bt709 = { kr = 0.2126, kb = 0.0722 },
}
type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number }
local cache: { [string]: Coeffs } = {}
local function coeffs(range: string?, matrix: string?): Coeffs
local key = (range or "limited") .. (matrix or "bt601")
local c = cache[key]
if c then
return c
end
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
local kr, kb = m.kr, m.kb
local kg = 1 - kr - kb
local full = range == "full"
local ys = if full then 1 else 255 / 219
local cs = if full then 1 else 255 / 224
c = {
ys = floor(ys * 65536 + 0.5),
yo = if full then 0 else 16,
crv = floor(2 * (1 - kr) * cs * 65536 + 0.5),
cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5),
cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5),
cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5),
cs = cs,
}
cache[key] = c
return c
end
-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279
local CLIP = bcreate(2304)
for i = 0, 2303 do
writeu8(CLIP, i, math.clamp(i - 1024, 0, 255))
end
-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with
-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2))
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer
local dst = out or bcreate(w * h * 4)
local c = coeffs(range, matrix)
local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu
local ch = (h + 1) // 2
if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then
return dst
end
for y = 0, h - 1 do
local yrow = y * w
local crow = (y // 2) * cw
local o = yrow * 4
for x = 0, w - 1, 2 do
local ci = crow + (x // 2)
local u = readu8(src, uo + ci) - 128
local v = readu8(src, vo + ci) - 128
local rv = (crv * v + 32768) // 65536
local gv = (cgu * u + cgv * v + 32768) // 65536
local bu = (cbu * u + 32768) // 65536
local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024
writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
if x + 1 < w then
yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024
writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
end
o += 8
end
end
return dst
end
-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p
function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer
local cw, ch = (w + 1) // 2, (h + 1) // 2
local uo, vo = w * h, w * h + cw * ch
local dst = out or bcreate(w * h + 2 * cw * ch)
if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then
return dst
end
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
local kr, kb = m.kr, m.kb
local kg = 1 - kr - kb
local full = range == "full"
local ysc = if full then 1 else 219 / 255
local csc = if full then 1 else 224 / 255
local yof = if full then 0.5 else 16.5
-- fixed point x 65536
local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5)
local yoff = floor(yof * 65536)
local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5)
local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5)
local ub = floor(0.5 * csc * 65536 + 0.5)
local vr = ub
local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5)
local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5)
local coff4 = floor(128.5 * 65536) * 4
for i = 0, w * h - 1 do
local o = i * 4
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024))
end
for cy = 0, ch - 1 do
local y0 = cy * 2
local y1 = if y0 + 1 < h then y0 + 1 else y0
for cx = 0, cw - 1 do
local x0 = cx * 2
local x1 = if x0 + 1 < w then x0 + 1 else x0
local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4
local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d)
local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1)
local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2)
local i = cy * cw + cx
writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024))
writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024))
end
end
return dst
end
-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent
local function info(img: Types.Image): (string, string)
local m = img.meta
local y = m and m.yuv
if type(y) == "table" then
return y.range or "limited", y.matrix or "bt601"
end
local src = m and m.source
if type(src) == "table" and src.range == "full" then
return "full", "bt601"
end
return "limited", "bt601"
end
Yuv.info = info
-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer
function Yuv.planes(w: number, h: number): (number, number, number, number)
local cw, ch = (w + 1) // 2, (h + 1) // 2
return w * h, w * h + cw * ch, cw, ch
end
-- FULL_Y / FULL_C: limited -> full range sample maps
local FULL_Y = bcreate(256)
local FULL_C = bcreate(256)
for v = 0, 255 do
writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255))
writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255))
end
-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned)
function Yuv.toFullRange(img: Types.Image): Types.Image
if img.format ~= "yuv420p" or info(img) == "full" then
return img
end
local w, h = img.width, img.height
local out = Types.Image.new(w, h, "yuv420p")
local src, dst = img.pixels, out.pixels
local ny = w * h
local n = math.min(buffer.len(src), buffer.len(dst))
for i = 0, math.min(ny, n) - 1 do
writeu8(dst, i, readu8(FULL_Y, readu8(src, i)))
end
for i = ny, n - 1 do
writeu8(dst, i, readu8(FULL_C, readu8(src, i)))
end
out.meta.yuv = { range = "full", matrix = select(2, info(img)) }
out.meta.source = img.meta.source
return out
end
-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats)
function Yuv.imageToRgba(img: Types.Image): Types.Image?
if img.format == "rgba8" then
return img
end
if img.format ~= "yuv420p" then
return nil
end
local w, h = img.width, img.height
local uo, vo, cw = Yuv.planes(w, h)
local range, matrix = info(img)
local out = Types.Image.new(w, h, "rgba8")
Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels)
out.meta.source = img.meta.source
return out
end
-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix)
function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image?
if img.format == "yuv420p" then
return img
end
if img.format ~= "rgba8" then
return nil
end
local out = Types.Image.new(img.width, img.height, "yuv420p")
Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels)
out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" }
out.meta.source = img.meta.source
return out
end
return Yuv