ws-polish: Flash ADPCM (FLV SoundFormat 1) decodes through codecs/audio/Adpcm.swf

Adpcm.swf / swfFrames: the SWF ADPCM bit stream (2..5-bit codes, 4096-frame blocks), bit-exact with
ffmpeg's adpcm_swf (mono and stereo FLV fixtures). containers/AudioWrap decodes adpcm_swf tracks into a
float WAV, so FLV audio opens through the api hook.
This commit is contained in:
4DBug committed 2026-10-31 17:10:51 -05:00
1 parent c0412f76cb
commit c420eab820
7 files changed
+181 -12

No files matched your search

+3 -2
View File
@@ -318,8 +318,9 @@ assert(F.video.open(mkv).codec == "theora")
FLV (Flash Video) opens like any other container. Its onMetaData script tag is `v.meta.metadata` (duration, width,
height, framerate, codec ids, encoder, ...). Sorenson Spark (FLV1) and H.263 (in 3GP / MP4 `s263`, AVI `H263`)
decode bit-exactly as ffmpeg decodes them; H.264 tracks carry their avcC in `track.config` and their B-frame
composition times in the pts. VP6, screen video, Flash ADPCM, Nellymoser and Speex tracks are known (and remuxable)
but not decoded: `nextFrame` / `v.audioError` say UNSUPPORTED. Writing FLV copies H.264 + AAC / MP3 from MP4,
composition times in the pts. Flash ADPCM audio decodes (bit-exact with ffmpeg's `adpcm_swf`) next to MP3, AAC and
PCM. VP6, screen video, Nellymoser and Speex tracks are known (and remuxable) but not decoded: `nextFrame` /
`v.audioError` say UNSUPPORTED. Writing FLV copies H.264 + AAC / MP3 from MP4,
Matroska or FLV sources (FLV has no codec here that encodes).
```luau
+111
View File
@@ -20,6 +20,8 @@
-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples
-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples
-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples)
-- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length
-- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes
-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each)
--
-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are
@@ -704,4 +706,113 @@ function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: nu
end
end
-- ------------------------------------------------------------------------------------------------ Flash ADPCM
-- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of
-- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step
-- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in
-- the top bit, the magnitude bits adding step, step/2, ... and the final step/2^(bits-1) (as ffmpeg's adpcm_swf and
-- the spec's reference decoder do); the step index moves by SWF_INDEX[bits]. The last block may be short.
local SWF_INDEX: { { number } } = {
{ -1, 2 },
{ -1, -1, 2, 4 },
{ -1, -1, -1, -1, 2, 4, 6, 8 },
{ -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 },
}
-- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1)
function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number
if n < 1 or ch < 1 then
return 0
end
local bits = rshift(readu8(src, p), 6) + 2
local total = n * 8 - 2
local hdr = 22 * ch
local block = hdr + bits * ch * 4095
local blocks = total // block
local left = total - blocks * block
local frames = blocks * 4096
if left >= hdr then
frames += 1 + (left - hdr) // (bits * ch)
end
return frames
end
-- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0
local function msb(src: buffer, p: number, e: number, pos: number, k: number): number
local q = p + rshift(pos, 3)
local v = readu8(src, q) * 65536
if q + 1 < e then
v += readu8(src, q + 1) * 256
end
if q + 2 < e then
v += readu8(src, q + 2)
end
return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1)
end
-- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns
-- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only.
function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number
local frames = Adpcm.swfFrames(src, p, n, ch)
if frames == 0 then
return 0
end
local e = p + n
local bits = rshift(readu8(src, p), 6) + 2
local tab = SWF_INDEX[bits - 1]
local k0 = lshift(1, bits - 2)
local sign = lshift(1, bits - 1)
local mask = sign - 1
local pred = table.create(ch, 0)
local index = table.create(ch, 0)
local pos = 2
local o = d * 4
local done = 0
while done < frames do
for c = 1, ch do
local v = msb(src, p, e, pos, 16)
if v >= 32768 then
v -= 65536
end
pred[c] = v
index[c] = msb(src, p, e, pos + 16, 6)
pos += 22
writef32(dst, o, v / 32768)
o += 4
end
done += 1
local m = math.min(4095, frames - done)
for _ = 1, m do
for c = 1, ch do
local code = msb(src, p, e, pos, bits)
pos += bits
local step = IMA_STEP[math.clamp(index[c], 0, 88) + 1]
local diff = 0
local k = k0
while k > 0 do
if band(code, k) ~= 0 then
diff += step
end
step = rshift(step, 1)
k = rshift(k, 1)
end
diff += step
local v = pred[c]
if band(code, sign) ~= 0 then
v -= diff
else
v += diff
end
v = math.clamp(v, -32768, 32767)
pred[c] = v
index[c] = math.clamp(index[c] + tab[band(code, mask) + 1], 0, 88)
writef32(dst, o, v / 32768)
o += 4
end
end
done += m
end
return frames
end
return Adpcm
+32
View File
@@ -4,6 +4,7 @@
-- format). New in formats-luau.
-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped);
-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk;
-- adpcm_swf (Flash ADPCM, FLV SoundFormat 1) -> decoded through codecs/audio/Adpcm into a float WAV;
-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3");
-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames;
-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations);
@@ -16,6 +17,7 @@ local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Mux = require("@formats/containers/Ogg/Mux")
local Adpcm = require("@formats/codecs/audio/Adpcm")
local AudioWrap = {}
@@ -131,6 +133,32 @@ local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?,
return wav(f:finish(), data), nil
end
-- Flash ADPCM packets decode on their own (each starts with its code size and block headers): f32 samples in a WAV
local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
local ch = track.channels or 1
local rate = math.floor((track.sampleRate or 0) + 0.5)
if ch < 1 or ch > 2 or rate <= 0 then
return nil, Err.new(Err.CORRUPT, "Flash ADPCM track without channels / sample rate")
end
local frames = 0
for _, pk in packets do
frames += Adpcm.swfFrames(pk.data, 0, buffer.len(pk.data), ch)
end
local data = buffer.create(frames * ch * 4)
local d = 0
for _, pk in packets do
d += Adpcm.swf(pk.data, 0, buffer.len(pk.data), ch, data, d) * ch
end
local f = Bytes.writer(16)
f:u16le(3)
f:u16le(ch)
f:u32le(rate)
f:u32le(rate * ch * 4)
f:u16le(ch * 4)
f:u16le(32)
return wav(f:finish(), data), nil
end
-- ------------------------------------------------------------------------------------------------ Ogg
-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1)
local function opusSamples(b: buffer): number
@@ -401,6 +429,10 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er
if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then
return wav(track.waveFormat, concat(packets)), "wav", nil
end
if codec == "adpcm_swf" then
local b, err = swfWav(track, packets)
return b, if b then "wav" else nil, err
end
if PCM[codec] then
local b, err = pcmWav(track, packets)
return b, if b then "wav" else nil, err
+2 -2
View File
@@ -7,8 +7,8 @@
-- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks
-- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets
-- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config),
-- linear PCM (platform-endian read as little-endian), A-law / mu-law; Flash ADPCM, Nellymoser and Speex are known
-- tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer.
-- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through
-- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer.
-- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 /
-- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at
-- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data
+24 -1
View File
@@ -2,7 +2,8 @@
-- (tools/fixtures/adpcm.py: ADX from ffmpeg and PS-ADPCM / DSP from our Python encoders decoded by vgmstream, Apple
-- ima4 from ffmpeg, IMA nibble streams decoded by ffmpeg); ADX coefficients; the encoders (IMA nibbles, IMA WAV
-- blocks, MS blocks) decoded back with a signal-to-noise floor; the Decoder layouts (seeking matches a straight
-- read); a fuzz pass of random bytes through every kernel (ranges valid, contents random) and the layouts.
-- read); Flash ADPCM by hand; a fuzz pass of random bytes through every kernel (ranges valid, contents random) and
-- the layouts.
local T = require("@tests/T")
local Adpcm = require("@formats/codecs/audio/Adpcm")
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
@@ -88,6 +89,25 @@ do
end
end
-- Flash ADPCM (bit-exact with ffmpeg's adpcm_swf in tests/video/flv.luau): a hand-made 2-bit packet of 4 bytes:
-- code size 0 (2-bit codes), first sample 100, step index 0, then the codes 01 11 00 00
do
local bits = "00" .. "0000000001100100" .. "000000" .. "01110000"
local src = buffer.create(4)
for i = 0, 3 do
buffer.writeu8(src, i, tonumber(string.sub(bits, i * 8 + 1, i * 8 + 8), 2) :: number)
end
t:eq(Adpcm.swfFrames(src, 0, 4, 1), 5, "swf: frames in a 4-byte packet")
local out = buffer.create(20)
t:eq(Adpcm.swf(src, 0, 4, 1, out, 0), 5, "swf: frames decoded")
-- 01: +7 + 7/2 = 110 (index 0 + 2: step 9); 11: -(9 + 4) = 97 (index 4: step 11); 00: +5 = 102 (index 3: step
-- 10); 00: +5 = 107
local want = { 100, 110, 97, 102, 107 }
for i, v in want do
t:eq(buffer.readf32(out, (i - 1) * 4) * 32768, v, "swf sample " .. i)
end
end
-- ------------------------------------------------------------------------------------------------ encoders
local function snr(x: buffer, y: buffer, count: number): number
local sig, err = 0, 0
@@ -235,6 +255,9 @@ t:fuzz("kernels", function(b: buffer)
if n >= 17 then
Adpcm.modplug(b, 0, math.min((n - 16) * 2, 1000), out, 0)
end
if n >= 1 then
Adpcm.swf(b, 0, math.min(n, 600), 1 + n % 2, buffer.create(Adpcm.swfFrames(b, 0, math.min(n, 600), 1 + n % 2) * 8 + 8), 0)
end
Adpcm.imaWav(b, 0, n, 2, 1017, buffer.create(1017 * 2 * 4), 0)
Adpcm.msBlock(b, 0, n, 2, 1012, buffer.create(1012 * 2 * 4), 0, coefs, 8, buffer.create(40))
local dec = Decoder.interleaved({ sampleRate = 8000, channels = 2, tags = {} }, { kind = "adx", buf = b, offset = 0, size = n, interleave = 18, c1 = 7334, c2 = -3283 })
+6 -5
View File
@@ -1,9 +1,10 @@
-- video/flv tests: FLV files from ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / ADPCM / Nellymoser / Speex /
-- A-law, H.264 with B-frames + AAC, Flash screen video, audio only): tracks and every packet against ffprobe
-- (composition times in the pts, keyframes), onMetaData, frames against ffmpeg (Sorenson bit-exact, H.264 PSNR), audio
-- through the api hook (PCM exact; ADPCM / Nellymoser / Speex known but UNSUPPORTED), seeking; crafted VP6 /
-- enhanced FourCC / encrypted / truncated files; our writer (FLV, MP4, Matroska sources) read back by ffprobe and
-- ffmpeg (tools/fixtures/flv.py) and by our demuxer with the source's packets; fuzz. Fixtures: tools/fixtures/flv.py.
-- through the api hook (PCM and Flash ADPCM mono / stereo exact against ffmpeg's adpcm_swf; Nellymoser / Speex known
-- but UNSUPPORTED), seeking; crafted VP6 / enhanced FourCC / encrypted / truncated files; our writer (FLV, MP4,
-- Matroska sources) read back by ffprobe and ffmpeg (tools/fixtures/flv.py) and by our demuxer with the source's
-- packets; fuzz. Fixtures: tools/fixtures/flv.py.
local T = require("@tests/T")
local C = require("@tests/video/_common")
local F = require("@formats")
@@ -19,8 +20,8 @@ local t = T.suite("flv")
t:eq(Flv.name, "flv", "name")
t:eq(Flv.category, "video", "category")
local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, pcm_alaw = true }
local NO_AUDIO_FORMAT = { adpcm_swf = true, nellymoser = true, speex = true }
local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, adpcm_swf = true }
local NO_AUDIO_FORMAT = { nellymoser = true, speex = true }
local byName = {}
for _, c in Fx do
byName[c.name] = c
+3 -2
View File
@@ -1,4 +1,4 @@
# FLV fixtures (tools/fixtures.py): files made by ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / Flash ADPCM /
# FLV fixtures (tools/fixtures.py): files made by ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / Flash ADPCM mono + stereo /
# Nellymoser / Speex / A-law, H.264 with B-frames + AAC, Flash screen video), with ffprobe's streams and packets,
# ffmpeg's frames (CRC-32 of `-flags +bitexact -idct int` decoding; the first two raw) and audio (f32); then our FLV
# writer (tools/fixtures/_flv_encode.luau) remuxes FLV, MP4, Matroska and MPEG-TS sources and each output is probed,
@@ -49,13 +49,14 @@ def generate(ctx):
ff(*SRC, *aud(22050, 2), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_s16le", "sorenson_pcm.flv")
ff(*SRC, *aud(11025), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_u8", "sorenson_pcm8.flv")
ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "adpcm_swf", "sorenson_adpcm.flv")
ff(*SRC, *aud(44100, 2), "-t", "0.5", "-c:v", "flv", "-c:a", "adpcm_swf", "sorenson_adpcm2.flv")
ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "nellymoser", "sorenson_nelly.flv")
ff(*SRC, *aud(16000), "-t", "0.5", "-c:v", "flv", "-c:a", "libspeex", "sorenson_speex.flv")
ff(*SRC, *aud(8000), "-t", "0.5", "-c:v", "flv", "-c:a", "pcm_alaw", "sorenson_alaw.flv")
ff("-f", "lavfi", "-i", "testsrc2=size=64x48:rate=10", "-t", "0.5", "-c:v", "flashsv", "screen.flv")
ff(*aud(44100, 2), "-t", "0.5", "-c:a", "libmp3lame", "audio_only.flv")
names = ["sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "sorenson_pcm8.flv", "sorenson_adpcm.flv",
"sorenson_nelly.flv", "sorenson_speex.flv", "sorenson_alaw.flv", "screen.flv", "audio_only.flv"]
"sorenson_adpcm2.flv", "sorenson_nelly.flv", "sorenson_speex.flv", "sorenson_alaw.flv", "screen.flv", "audio_only.flv"]
cases = [case(tmp, n) for n in names]
ctx.emit("flv_cases", cases)