merge ws/video2

This commit is contained in:
4DBug committed 2026-10-31 15:31:56 -05:00
commit c65a66695f
63 files changed
+12207 -1509

No files matched your search

+3 -2
View File
@@ -26,7 +26,8 @@ Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err
**Roblox (Rojo).** `python3 -I tools/build.py roblox` writes `build/roblox/Formats` (requires turned into instance
paths); `default.project.json` mounts it, so `rojo build -o Formats.rbxm` (or `rojo serve`) gives a `Formats`
ModuleScript to put in ReplicatedStorage: `local F = require(game.ReplicatedStorage.Formats)`. There is no file system:
pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage.
pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage, `F.host.toEditableMesh(prim, page)` an
EditableMesh (a merged triangle primitive split by `F.host.meshPages`).
**LuaJIT / LÖVE.** `python3 -I tools/build.py luajit` writes `build/luajit/formats/` (Lua 5.1 + LuaJIT FFI; the Luau
standard library pieces come from `formats/_compat.lua`). Copy the `formats` folder into the game (or put
@@ -80,7 +81,7 @@ hands to formats (decodeImage / encodeImage / openAudio / plugins): [docs/API.md
| Host | Files | Bridges |
|---|---|---|
| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)` |
| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)`, `meshPages` / `toEditableMesh(prim, page)` |
| LÖVE | `love.filesystem`, then `io` | `toImageData`, `fromImageData`, `toSoundData` |
| LuaJIT | `io.open` | |
| luau CLI | none | |
+3 -1
View File
@@ -94,7 +94,9 @@ A format never requires another format, so the api passes these to decoders / en
## Host
`F.host` (`src/Formats/host`): `name` (`"roblox"`, `"love"`, `"luajit"`, `"luau"`), `hasFiles`, `readFile`,
`writeFile`, `exists`; Roblox `toEditableImage(img)`; LÖVE `toImageData(img)`, `fromImageData(imageData)`,
`writeFile`, `exists`; Roblox `toEditableImage(img)`, `meshPages(prim, opts?)`, `pageData(prim, page, opts?)`,
`toEditableMesh(prim, page?, opts?)` (a triangle primitive in pages of at most 20k triangles / 60k vertices, each an
EditableMesh; see the Hosts section of the guide); LÖVE `toImageData(img)`, `fromImageData(imageData)`,
`toSoundData(audioOrDecoder)`.
On LuaJIT the host raises the trace limits at load (`jit.opt.start("maxtrace=8000", "maxmcode=65536")`): the big
+13 -6
View File
@@ -27,12 +27,15 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` |
| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` |
| video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` |
| video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` |
| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` |
| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` |
| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` |
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` |
| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` |
| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` |
| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", "mpeg2", audio: true | `tests/video/mpegps.luau` |
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "mpeg2", "h264", audio: true | `tests/video/mpegts.luau` |
| video | ogv | .ogv .ogg | yes | yes | streaming: true, remux: true, video: "theora", audio: true | `tests/video/ogv.luau` |
| video | smk | .smk | yes | - | streaming: true, video: "smackvid", audio: "smackaudio", "pcm_u8", "pcm_s16le" | `tests/video/smk.luau` |
| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` |
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
@@ -144,6 +147,10 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
- **video**
- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder
- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
+28 -1
View File
@@ -275,7 +275,7 @@ single-stream archive such as `.tar.gz` loads as the archive inside. A music fil
| Host | Files | Bridges |
|---|---|---|
| Roblox | none: pass buffers or strings | `F.host.toEditableImage(img)` |
| Roblox | none: pass buffers or strings | `F.host.toEditableImage(img)`, `F.host.meshPages(prim)` / `F.host.toEditableMesh(prim, page)` |
| LÖVE | `love.filesystem` (the game folder and the save directory), then `io` | `F.host.toImageData(img)`, `F.host.fromImageData(imageData)`, `F.host.toSoundData(audioOrDecoder)` |
| LuaJIT | `io.open` | |
| luau CLI | none | |
@@ -304,6 +304,33 @@ label.ImageContent = Content.fromObject(editable)
label.Parent = script.Parent -- a ScreenGui
```
Meshes: one EditableMesh holds about 20k triangles and 60k vertices, and a client has only 8 growable ones at a time.
`F.host.meshPages(prim, opts?)` splits a triangle primitive (`F.ops.mesh.merge` output) into runs that fit;
`F.host.toEditableMesh(prim, page, opts?)` builds one page (positions relative to the returned centre, normals, uvs,
sRGB vertex colours from the linear `COLOR_0`) and returns `editableMesh, centre`. Freeze each page into what you keep
before building the next. Options: `scale` (number or `{ x, y, z }`), `doubleSided` (back faces, counted by
`meshPages` too), `texCoord`, `flipV`, `normals` / `uvs` / `colors = false`, `yield` (called every `yieldEvery` = 2000
triangles), `editableMesh` (append to an existing mesh). `F.host.pageData(prim, page, opts?)` is the same page as flat
number arrays, without engine calls. Roblox is y up like glTF: put z-up scenes (STL, VOX, CAD) through
`F.ops.mesh.setUp(scene, "y")` before merging.
<!-- doc:display needs Roblox -->
```luau
local AssetService = game:GetService("AssetService")
local scene = assert(F.model.load(glbBytes))
for _, prim in assert(F.ops.mesh.merge(scene, { byMaterial = true })) do
for _, page in assert(F.host.meshPages(prim)) do
local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs
local fixed = AssetService:CreateEditableMeshAsync(Content.fromObject(em), { FixedSize = true })
em:Destroy() -- frees the growable slot
local part = AssetService:CreateMeshPartAsync(Content.fromObject(fixed))
part.Position = Vector3.new(centre[1], centre[2], centre[3])
part.Anchored = true
part.Parent = workspace
end
end
```
**LÖVE.** `toImageData` copies an `rgba8` image into an `ImageData` (through the FFI), `fromImageData` copies back,
and `toSoundData` turns an `Audio` or a `Decoder` (read to its end) into 16-bit `SoundData`:
+126 -5
View File
@@ -2,7 +2,7 @@
A video file opens as a **VideoDecoder**: frames come out one at a time, as Images, with their presentation time.
Underneath sits a **Demuxer**: the container's tracks and their compressed packets. Video tracks decode through a
codec registry (H.264, VP8, MPEG-1, Motion-JPEG, raw), and the first audio track opens as an audio
codec registry (H.264, VP8, MPEG-1, MPEG-2, Motion-JPEG, raw), and the first audio track opens as an audio
[Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the
internals and how to add a codec.
@@ -183,6 +183,7 @@ Images and animated images save as videos too.
| Destination | Video | Audio |
|---|---|---|
| webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied |
| ogv | Theora copied (the source must be Theora: ogv or mkv) | Vorbis / Opus copied |
| mkv | any codec copied, else MJPEG | copied, else PCM s16 |
| mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only |
| avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 |
@@ -263,6 +264,54 @@ assert(C.register({
assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid"))
```
## MPEG-2 (DVD, broadcast TS)
MPEG-1 and MPEG-2 video decode through one decoder (`codecs/video/Mpeg2`; `codecs/video/Mpeg1` is the same module):
Main profile, progressive and interlaced, frame and field pictures, 4:2:0 and 4:2:2. It reads `.mpg` / `.vob`
program streams, transport streams (stream type 0x02, or a private type such as 0x80 carrying a video PES), raw
`.m2v` elementary streams, and MPEG-2 tracks of MP4 / MOV, Matroska and AVI. The output equals `ffmpeg -idct int`
sample for sample (the integer IDCT of the IJG; ffmpeg's default IDCT differs from it by at most a level or two).
```luau
local v = assert(F.video.open(tsBytes)) -- MPEG-TS: interlaced MPEG-2 + MP2
assert(v.format == "mpegts" and v.codec == "mpeg2")
local f = assert(v:nextFrame())
local src = f.image.meta.source
assert(src.format == "mpeg2" and src.interlaced and src.topFieldFirst)
assert(f.image.format == "yuv420p") -- both fields woven: the top field on the even lines
local a = assert(v.audio, tostring(v.audioError)) -- the MP2 track through the audio hook
assert(a.sampleRate == 44100)
```
Interlaced frames come out woven, as they were coded: deinterlace them yourself if needed (`src.interlaced`,
`src.topFieldFirst`). 4:2:2 streams (studio / XDCAM) are converted to 4:2:0 for the frame Image, averaging chroma
lines of the same field. A 720x576 interlaced stream decodes at about 130 frames per second in Luau on one desktop
core (`tools/bench.luau`): real time with room to spare on a PC, less so on phones.
## Ogg Theora
Ogg video (`.ogv`, or `.ogg` with a Theora stream) opens like any other container: the `ogv` format demuxes every
Ogg stream, Theora video decodes bit-exactly (as libtheora / ffmpeg) in all three pixel formats (4:2:2 and 4:4:4
chroma is averaged down to yuv420p), and a Vorbis, Opus or FLAC track becomes `v.audio`. Plain Ogg Vorbis / Opus /
FLAC files stay audio. Theora in Matroska (`V_THEORA`) decodes too, and an Ogg Theora video remuxes to ogv or mkv
(there is no Theora encoder).
```luau
local v = assert(F.video.open(ogvBytes)) -- Theora + Vorbis
assert(v.format == "ogv" and v.codec == "theora" and v.width == 64 and v.height == 48)
assert(v.frameRate == 10 and v.audio ~= nil)
local n = 0
while v:nextFrame() do n += 1 end -- dropped frames repeat the previous picture
assert(n == 10)
local Theora = F.format("ogv") -- the format module: sniff / demux / open / encode
local d = assert(Theora.demux(F.Bytes.reader(ogvBytes)))
local vt = d:track("video")
assert(vt.codec == "theora" and vt.timescale == 10) -- packet times are frame numbers here
v:reset()
local mkv = assert(F.save(v, nil, { format = "mkv" })) -- Theora + Vorbis copied into Matroska
assert(F.video.open(mkv).codec == "theora")
```
## Playing in a game loop
Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes
@@ -306,16 +355,88 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels)
| Format | Read | Write | Video codecs (decode) |
|---|---|---|---|
| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 |
| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) |
| avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) |
| mpegts, mpegps | yes | - | MPEG-1, H.264 |
| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1, MPEG-2 |
| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw, Theora (+ H.264) |
| ogv (Ogg Theora) | yes | yes (Theora + Vorbis / Opus copied) | Theora |
| avi | yes | yes | MJPEG, MPEG-1, MPEG-2, raw (+ H.264) |
| mpegts, mpegps | yes | - | MPEG-1, MPEG-2, H.264 |
| y4m | yes | yes | raw |
| h264 (Annex B) | yes | yes (copy) | H.264 |
| gif, png (APNG), webp | as video | as video via the image writers | frames |
See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`.
<!-- ws-video2-legacy: formats table addition -->
| fli / flc / flx | yes | - | FLIC (8-bit palettised, 15 / 16 / 24-bit) |
| smk | yes | - | Smacker video (SMK2 / SMK4) + Smacker audio / PCM |
AVI, MOV / MP4 and MKV (V_MS/VFW/FOURCC, V_QUICKTIME) also decode the legacy codecs: Cinepak, Microsoft Video 1,
QuickTime Animation (RLE) and QuickTime Graphics (SMC). See [Legacy video](#legacy-video).
<!-- ws-video2-legacy: section -->
## Legacy video
The 1990s formats and codecs decode to **rgba8** frames (they are palettised or RGB, not YUV), each frame painted
over the previous one, as the codecs define. Decoding is bit-exact with ffmpeg's.
| Codec id | Name | Containers | Depths |
|---|---|---|---|
| `flic` | Autodesk FLI / FLC | fli | 8-bit palettised, 15 / 16 / 24-bit |
| `smackvid` | Smacker video | smk | 8-bit palettised |
| `cinepak` | Cinepak (`cvid`) | avi, mov, mkv | 24-bit, grey, 8-bit palettised |
| `msvideo1` | Microsoft Video 1 (`CRAM`, `MSVC`, `WHAM`) | avi, mov, mkv | 16-bit (5-5-5), 8-bit palettised |
| `qtrle` | QuickTime Animation (`rle `) | mov, mkv | 1, 2, 4, 8 (palettised or grey), 16, 24, 32 (alpha) |
| `smc` | QuickTime Graphics (`smc `) | mov, mkv | 8-bit palettised |
Palettes come from the container: `track.palette` (256 entries, 4 bytes each: R, G, B, A) holds the AVI
BITMAPINFO palette or the QuickTime colour table (or the Macintosh default table it refers to); FLIC and Smacker
frames carry their own palette changes.
```luau
local v = assert(F.video.open(cinepakBytes)) -- Cinepak in a QuickTime movie
assert(v.format == "mov" and v.codec == "cinepak")
local frames = 0
while true do
local f = v:nextFrame()
if not f then break end
assert(f.image.format == "rgba8" and f.image.width == 64)
frames += 1
end
assert(frames == v.frames)
```
FLIC files (`.fli` at 70 Hz ticks, `.flc` / `.flx` in milliseconds) open as videos; the ring frame (an extra frame
leading back to the first, for looping) is not shown unless you ask for it.
```luau
local v = assert(F.video.open(flcBytes))
print(v.format, v.codec, v.width, v.height, v.frameRate) -- fli flic 64 48 10
assert(v.track.bitsPerPixel == 8 and v.frames == 10)
local f = assert(v:nextFrame())
local r, g, b, a = F.ops.image.getPixel(f.image, 0, 0) -- palette colours, opaque
assert(r and g and b and a == 255)
local all = assert(F.format("fli").open(F.Bytes.reader(flcBytes), { ringFrame = true }))
assert(all.codec == "flic")
```
Smacker files carry up to seven audio tracks. The format decodes Smacker's packed audio (and raw PCM tracks) itself:
`v.audio` is the first track, `F.format("smk").openAudio(demuxer, track)` opens any of them.
```luau
local v = assert(F.video.open(smkBytes))
assert(v.format == "smk" and v.codec == "smackvid")
local a = assert(v.audio, tostring(v.audioError)) -- packed 16-bit stereo, 22050 Hz
assert(a.sampleRate == 22050 and a.channels == 2)
local Smk = F.format("smk")
for _, t in v.demuxer.tracks do
if t.kind == "audio" then
local dec = assert(Smk.openAudio(v.demuxer, t)) -- smackaudio, pcm_u8 or pcm_s16le
local pcm, n = dec:read(1000)
assert(n == 1000 and buffer.len(pcm) == n * dec.channels * 4)
end
end
```
## Gotchas
- Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau`
+3
View File
@@ -28,6 +28,9 @@ F.convert(gif, "avi") -- animated images become videos (un
| `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio |
| `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap |
| `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
| `codecs/video/Mpeg2` (`Mpeg1` is the same module), `H264` | MPEG-1 / MPEG-2 and H.264 video decoders |
| `codecs/video/Dsp` | 8x8 IDCT (bit-exact with `ffmpeg -idct int`) and half-pel motion compensation for the MPEG-style codecs |
| `codecs/video/Legacy` | FLIC, Smacker, Cinepak, Microsoft Video 1, QuickTime RLE / SMC: rgba8, palettes from `track.palette` |
| `video/<fmt>` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source |
Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires
+2
View File
@@ -37,7 +37,9 @@
| `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
| `src/Formats/codecs/video/Dsp.luau` (the 8x8 IDCT: jrevdct.c translated to Luau, branch tree and constants unchanged) | IJG jrevdct.c as shipped in ffmpeg (libavcodec/jrevdct.c; IJG-licensed, not LGPL: ffmpeg's LICENSE.md) | IJG: [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. |
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
| `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+28
View File
@@ -0,0 +1,28 @@
Copyright (C) 2002-2009 Xiph.org Foundation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+42 -6
View File
@@ -285,11 +285,23 @@ local list: { Entry } = {
extensions = { "avi" },
mime = { "video/x-msvideo", "video/avi" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true },
load = function()
return require("@formats/video/avi")
end,
},
{
name = "fli",
category = "video",
path = "video/fli",
extensions = { "fli", "flc", "flx" },
mime = { "video/x-fli", "video/fli", "video/x-flc" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } },
load = function()
return require("@formats/video/fli")
end,
},
{
name = "h264",
category = "video",
@@ -308,8 +320,8 @@ local list: { Entry } = {
path = "video/mkv",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true },
load = function()
return require("@formats/video/mkv")
end,
@@ -321,7 +333,7 @@ local list: { Entry } = {
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true },
load = function()
return require("@formats/video/mp4")
end,
@@ -333,7 +345,7 @@ local list: { Entry } = {
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
mime = { "video/mpeg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true },
load = function()
return require("@formats/video/mpegps")
end,
@@ -345,11 +357,35 @@ local list: { Entry } = {
extensions = { "ts", "m2ts", "mts", "tsv" },
mime = { "video/mp2t" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true },
load = function()
return require("@formats/video/mpegts")
end,
},
{
name = "ogv",
category = "video",
path = "video/ogv",
extensions = { "ogv", "ogg" },
mime = { "video/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true },
load = function()
return require("@formats/video/ogv")
end,
},
{
name = "smk",
category = "video",
path = "video/smk",
extensions = { "smk" },
mime = { "video/vnd.radgamettools.smacker" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" },
caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } },
load = function()
return require("@formats/video/smk")
end,
},
{
name = "y4m",
category = "video",
+714
View File
@@ -0,0 +1,714 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
-- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added
-- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never
-- throws (the caller keeps offsets in range).
--
-- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg
-- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then
-- columns, with every sparse-input special case of the original kept, because several of them use merged constants
-- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that
-- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order
-- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for
-- coefficients in the MPEG range), and the put / add clamping fused into the last pass.
--
-- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it
-- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3)
-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block
-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE)
local Dsp = {}
local readu8 = buffer.readu8
local writeu8 = buffer.writeu8
local readu32 = buffer.readu32
local writeu32 = buffer.writeu32
local readi32 = buffer.readi32
local writei32 = buffer.writei32
local band = bit32.band
local bor = bit32.bor
local bxor = bit32.bxor
local rshift = bit32.rshift
-- clamp to 0..255 by lookup: CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the IDCT output of MPEG-range
-- coefficients is bounded by 64 * 2048 / 8 * sqrt(2)^2 < COFF, plus a prediction of up to 255
local COFF = 40000
local CLAMP = buffer.create(2 * COFF + 256)
for i = 0, 2 * COFF + 255 do
buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255))
end
Dsp.CLAMP = CLAMP
Dsp.COFF = COFF
-- ------------------------------------------------------------------------------------------------ IDCT
function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean)
local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0
local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0
local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0
-- pass 1: rows, scaled up by 2^PASS1_BITS
for r = 0, 224, 32 do
local d0 = readi32(blk, r)
local d1 = readi32(blk, r + 4)
local d2 = readi32(blk, r + 8)
local d3 = readi32(blk, r + 12)
local d4 = readi32(blk, r + 16)
local d5 = readi32(blk, r + 20)
local d6 = readi32(blk, r + 24)
local d7 = readi32(blk, r + 28)
if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then
if d0 ~= 0 then
local v = d0 * 4
writei32(blk, r, v)
writei32(blk, r + 4, v)
writei32(blk, r + 8, v)
writei32(blk, r + 12, v)
writei32(blk, r + 16, v)
writei32(blk, r + 20, v)
writei32(blk, r + 24, v)
writei32(blk, r + 28, v)
end
else
if d6 ~= 0 then
if d2 ~= 0 then
z1 = (d2 + d6) * 4433
tmp2 = z1 + (-d6) * 15137
tmp3 = z1 + (d2) * 6270
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp2 = (-d6) * 10703
tmp3 = (d6) * 4433
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
end
else
if d2 ~= 0 then
tmp2 = (d2) * 4433
tmp3 = (d2) * 10703
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp13 = (d0 + d4) * 8192
tmp10 = tmp13
tmp12 = (d0 - d4) * 8192
tmp11 = tmp12
end
end
if d7 ~= 0 then
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z2 = d5 + d3
z3 = d7 + d3
z4 = d5 + d1
z5 = (z3 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z3 = d7 + d3
z5 = (z3 + d5) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
z1 = (-d7) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-d5) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 = z1 + z4
end
else
if d1 ~= 0 then
z1 = d7 + d1
z4 = d5 + d1
z5 = (d7 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d5) * 20995
z3 = (-d7) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 = z2 + z3
tmp3 += z1 + z4
else
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
z3 = (-d7) * 16069
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (-d5) * 3196
z5 = (d5 + d7) * 9633
z3 += z5
z4 += z5
tmp0 += z3
tmp1 += z4
tmp2 = z2 + z3
tmp3 = z1 + z4
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z3 = d7 + d3
z5 = (z3 + d1) * 9633
tmp0 = (d7) * 2446
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d3) * 20995
z3 = (-z3) * 16069
z4 = (-d1) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 = z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z3 = d7 + d3
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
tmp2 = (d3) * 4176
z2 = (-d3) * 20995
z5 = (z3) * 9633
z3 = (-z3) * 6436
tmp0 += z3
tmp1 = z2 + z5
tmp2 += z3
tmp3 = z1 + z5
end
else
if d1 ~= 0 then
z1 = d7 + d1
z5 = (z1) * 9633
z1 = (z1) * 2260
z3 = (-d7) * 16069
tmp0 = (-d7) * 13623
z4 = (-d1) * 3196
tmp3 = (d1) * 9102
tmp0 += z1
tmp1 = z4 + z5
tmp2 = z3 + z5
tmp3 += z1
else
tmp0 = (-d7) * 11363
tmp1 = (d7) * 9633
tmp2 = (-d7) * 6436
tmp3 = (d7) * 2260
end
end
end
else
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z2 = d5 + d3
z4 = d5 + d1
z5 = (d3 + z4) * 9633
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-d1) * 7373
z2 = (-z2) * 20995
z3 = (-d3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 = z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z5 = (z2) * 9633
tmp1 = (d5) * 13623
z4 = (-d5) * 3196
z2 = (-z2) * 11363
tmp2 = (d3) * 9102
z3 = (-d3) * 16069
tmp0 = z3 + z5
tmp1 += z2
tmp2 += z2
tmp3 = z4 + z5
end
else
if d1 ~= 0 then
z4 = d5 + d1
z5 = (z4) * 9633
z1 = (-d1) * 7373
tmp3 = (d1) * 4926
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (z4) * 6436
tmp0 = z1 + z5
tmp1 += z4
tmp2 = z2 + z5
tmp3 += z4
else
tmp0 = (d5) * 9633
tmp1 = (d5) * 2260
tmp2 = (-d5) * 11363
tmp3 = (d5) * 6436
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z5 = d1 + d3
tmp3 = (d1) * 1730
tmp2 = (-d3) * 11893
z1 = (d1) * 8697
z2 = (-d3) * 17799
z4 = (z5) * 6436
z5 = (z5) * 9633
tmp0 = z1 - z4
tmp1 = z2 + z4
tmp2 += z5
tmp3 += z5
else
tmp0 = (-d3) * 6436
tmp1 = (-d3) * 11363
tmp2 = (-d3) * 2260
tmp3 = (d3) * 9633
end
else
if d1 ~= 0 then
tmp0 = (d1) * 2260
tmp1 = (d1) * 6436
tmp2 = (d1) * 9633
tmp3 = (d1) * 11363
else
tmp3 = 0
tmp0 = tmp3
tmp1 = tmp3
tmp2 = tmp3
end
end
end
end
writei32(blk, r, (tmp10 + tmp3 + 1024) // 2048)
writei32(blk, r + 28, (tmp10 - tmp3 + 1024) // 2048)
writei32(blk, r + 4, (tmp11 + tmp2 + 1024) // 2048)
writei32(blk, r + 24, (tmp11 - tmp2 + 1024) // 2048)
writei32(blk, r + 8, (tmp12 + tmp1 + 1024) // 2048)
writei32(blk, r + 20, (tmp12 - tmp1 + 1024) // 2048)
writei32(blk, r + 12, (tmp13 + tmp0 + 1024) // 2048)
writei32(blk, r + 16, (tmp13 - tmp0 + 1024) // 2048)
end
end
-- pass 2: columns, descaled by 2^(CONST_BITS + PASS1_BITS + 3)
for c = 0, 28, 4 do
local d0 = readi32(blk, c)
local d1 = readi32(blk, c + 32)
local d2 = readi32(blk, c + 64)
local d3 = readi32(blk, c + 96)
local d4 = readi32(blk, c + 128)
local d5 = readi32(blk, c + 160)
local d6 = readi32(blk, c + 192)
local d7 = readi32(blk, c + 224)
if d6 ~= 0 then
if d2 ~= 0 then
z1 = (d2 + d6) * 4433
tmp2 = z1 + (-d6) * 15137
tmp3 = z1 + (d2) * 6270
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp2 = (-d6) * 10703
tmp3 = (d6) * 4433
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
end
else
if d2 ~= 0 then
tmp2 = (d2) * 4433
tmp3 = (d2) * 10703
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp13 = (d0 + d4) * 8192
tmp10 = tmp13
tmp12 = (d0 - d4) * 8192
tmp11 = tmp12
end
end
if d7 ~= 0 then
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z2 = d5 + d3
z3 = d7 + d3
z4 = d5 + d1
z5 = (z3 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z3 = d7 + d3
z5 = (z3 + d5) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
z1 = (-d7) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-d5) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 = z1 + z4
end
else
if d1 ~= 0 then
z1 = d7 + d1
z3 = d7
z4 = d5 + d1
z5 = (z3 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d5) * 20995
z3 = (-d7) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 = z2 + z3
tmp3 += z1 + z4
else
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
z3 = (-d7) * 16069
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (-d5) * 3196
z5 = (d5 + d7) * 9633
z3 += z5
z4 += z5
tmp0 += z3
tmp1 += z4
tmp2 = z2 + z3
tmp3 = z1 + z4
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z3 = d7 + d3
z5 = (z3 + d1) * 9633
tmp0 = (d7) * 2446
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d3) * 20995
z3 = (-z3) * 16069
z4 = (-d1) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 = z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z3 = d7 + d3
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
tmp2 = (d3) * 4176
z2 = (-d3) * 20995
z5 = (z3) * 9633
z3 = (-z3) * 6436
tmp0 += z3
tmp1 = z2 + z5
tmp2 += z3
tmp3 = z1 + z5
end
else
if d1 ~= 0 then
z1 = d7 + d1
z5 = (z1) * 9633
z1 = (z1) * 2260
z3 = (-d7) * 16069
tmp0 = (-d7) * 13623
z4 = (-d1) * 3196
tmp3 = (d1) * 9102
tmp0 += z1
tmp1 = z4 + z5
tmp2 = z3 + z5
tmp3 += z1
else
tmp0 = (-d7) * 11363
tmp1 = (d7) * 9633
tmp2 = (-d7) * 6436
tmp3 = (d7) * 2260
end
end
end
else
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z2 = d5 + d3
z4 = d5 + d1
z5 = (d3 + z4) * 9633
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-d1) * 7373
z2 = (-z2) * 20995
z3 = (-d3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 = z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z5 = (z2) * 9633
tmp1 = (d5) * 13623
z4 = (-d5) * 3196
z2 = (-z2) * 11363
tmp2 = (d3) * 9102
z3 = (-d3) * 16069
tmp0 = z3 + z5
tmp1 += z2
tmp2 += z2
tmp3 = z4 + z5
end
else
if d1 ~= 0 then
z4 = d5 + d1
z5 = (z4) * 9633
z1 = (-d1) * 7373
tmp3 = (d1) * 4926
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (z4) * 6436
tmp0 = z1 + z5
tmp1 += z4
tmp2 = z2 + z5
tmp3 += z4
else
tmp0 = (d5) * 9633
tmp1 = (d5) * 2260
tmp2 = (-d5) * 11363
tmp3 = (d5) * 6436
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z5 = d1 + d3
tmp3 = (d1) * 1730
tmp2 = (-d3) * 11893
z1 = (d1) * 8697
z2 = (-d3) * 17799
z4 = (z5) * 6436
z5 = (z5) * 9633
tmp0 = z1 - z4
tmp1 = z2 + z4
tmp2 += z5
tmp3 += z5
else
tmp0 = (-d3) * 6436
tmp1 = (-d3) * 11363
tmp2 = (-d3) * 2260
tmp3 = (d3) * 9633
end
else
if d1 ~= 0 then
tmp0 = (d1) * 2260
tmp1 = (d1) * 6436
tmp2 = (d1) * 9633
tmp3 = (d1) * 11363
else
tmp3 = 0
tmp0 = tmp3
tmp1 = tmp3
tmp2 = tmp3
end
end
end
end
writei32(blk, c, (tmp10 + tmp3 + 131072) // 262144)
writei32(blk, c + 224, (tmp10 - tmp3 + 131072) // 262144)
writei32(blk, c + 32, (tmp11 + tmp2 + 131072) // 262144)
writei32(blk, c + 192, (tmp11 - tmp2 + 131072) // 262144)
writei32(blk, c + 64, (tmp12 + tmp1 + 131072) // 262144)
writei32(blk, c + 160, (tmp12 - tmp1 + 131072) // 262144)
writei32(blk, c + 96, (tmp13 + tmp0 + 131072) // 262144)
writei32(blk, c + 128, (tmp13 - tmp0 + 131072) // 262144)
end
-- put / add, clamped
for r = 0, 224, 32 do
local p0 = readi32(blk, r) + COFF
local p1 = readi32(blk, r + 4) + COFF
local p2 = readi32(blk, r + 8) + COFF
local p3 = readi32(blk, r + 12) + COFF
local p4 = readi32(blk, r + 16) + COFF
local p5 = readi32(blk, r + 20) + COFF
local p6 = readi32(blk, r + 24) + COFF
local p7 = readi32(blk, r + 28) + COFF
if add then
p0 += readu8(dst, off)
p1 += readu8(dst, off + 1)
p2 += readu8(dst, off + 2)
p3 += readu8(dst, off + 3)
p4 += readu8(dst, off + 4)
p5 += readu8(dst, off + 5)
p6 += readu8(dst, off + 6)
p7 += readu8(dst, off + 7)
end
writeu32(dst, off, readu8(CLAMP, p0) + readu8(CLAMP, p1) * 256 + readu8(CLAMP, p2) * 65536 + readu8(CLAMP, p3) * 16777216)
writeu32(dst, off + 4, readu8(CLAMP, p4) + readu8(CLAMP, p5) * 256 + readu8(CLAMP, p6) * 65536 + readu8(CLAMP, p7) * 16777216)
off += stride
end
end
-- ------------------------------------------------------------------------------------------------ blocks
-- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT
-- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere)
function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean)
if not add then
local c = readu8(CLAMP, v + COFF) * 0x01010101
for _ = 1, 8 do
writeu32(dst, off, c)
writeu32(dst, off + 4, c)
off += stride
end
else
for _ = 1, 8 do
for i = off, off + 7 do
writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF))
end
off += stride
end
end
end
-- ------------------------------------------------------------------------------------------------ motion
-- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst
-- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what
-- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for
-- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits
-- each byte into its low 2 bits and high 6 bits so no lane overflows.
function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean)
for _ = 1, h do
for i = 0, w - 4, 4 do
local p
if hx == 0 then
if hy == 0 then
p = readu32(src, sOff + i)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + sStride)
p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
end
elseif hy == 0 then
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1)
local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202
local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2)
p = hi + band(rshift(l, 2), 0x0F0F0F0F)
end
if avg then
local q = readu32(dst, dOff + i)
p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1)
end
writeu32(dst, dOff + i, p)
end
sOff += sStride
dOff += dStride
end
end
-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to
-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture
-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes).
Dsp.EDGE_STRIDE = 32
Dsp.EDGE_SIZE = 32 * 34 + 4
function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer)
for j = 0, h do
local sy = y + j
sy = if sy < 0 then 0 elseif sy >= ph then ph - 1 else sy
local row = base + sy * stride
local o = j * 32
for i = 0, w do
local sx = x + i
sx = if sx < 0 then 0 elseif sx >= pw then pw - 1 else sx
writeu8(out, o + i, readu8(src, row + sx))
end
end
end
return Dsp
@@ -0,0 +1,303 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4
-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description
-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4
-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame
-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are
-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra
-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak
-- decoder. Never throws: every read is range-checked against its chunk.
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
local band = bit32.band
local Cinepak = {}
local MAX_STRIPS = 32
-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index)
local ENTRY = 16
local BOOK = 256 * ENTRY
export type State = {
books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip)
filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet)
}
function Cinepak.state(): State
return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 }
end
local function be16(d: buffer, o: number): number
return readu8(d, o) * 256 + readu8(d, o + 1)
end
local function be24(d: buffer, o: number): number
return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2)
end
local function be32(d: buffer, o: number): number
return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3)
end
local function clip(v: number): number
return if v < 0 then 0 elseif v > 255 then 255 else v
end
-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set
local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number)
local six = band(id, 4) == 0
local partial = band(id, 1) ~= 0
local size = if six then 6 else 4
local flag, mask = 0, 0
for i = 0, 255 do
if partial then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
end
if not partial or band(flag, mask) ~= 0 then
if p + size > stop then
return
end
local e = book + i * ENTRY
local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3)
if six then
local u, v = readu8(d, p + 4), readu8(d, p + 5)
if u >= 128 then
u -= 256
end
if v >= 128 then
v -= 256
end
local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero)
local dr, dg, db = 2 * v, -uh - v, 2 * u
writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000)
writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000)
writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000)
writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000)
else
writeu32(books, e, y0 * 0x10101 + 0xFF000000)
writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000)
writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000)
writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000)
end
p += size
end
end
end
-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data
local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number,
stop: number, x1: number, y1: number, x2: number, y2: number): boolean
local stride = pic.stride
local pal = pic.idx
local px = (pal or pic.rgba) :: buffer
local flag, mask = 0, 0
local inter = band(id, 1) ~= 0
local v1only = band(id, 2) ~= 0
for y = y1, y2 - 1, 4 do
for x = x1, x2 - 1, 4 do
local paint = true
if inter then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return false
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
paint = band(flag, mask) ~= 0
end
if paint then
local useV1 = v1only
if not v1only then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return false
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
useV1 = band(flag, mask) == 0
end
local o = y * stride + x
if useV1 then
if p >= stop then
return false
end
local e = v1 + readu8(d, p) * ENTRY
p += 1
-- each of the 4 entries fills a 2x2 square
local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12)
if pal then
a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256
writeu32(px, o, a * 0x0101 + b * 0x01010000)
writeu32(px, o + stride, a * 0x0101 + b * 0x01010000)
writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000)
writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000)
else
for r = 0, 3 do
local q = (o + r * stride) * 4
local l, rr = if r < 2 then a else c, if r < 2 then b else e4
writeu32(px, q, l)
writeu32(px, q + 4, l)
writeu32(px, q + 8, rr)
writeu32(px, q + 12, rr)
end
end
else
if p + 4 > stop then
return false
end
local e0 = v4 + readu8(d, p) * ENTRY
local e1 = v4 + readu8(d, p + 1) * ENTRY
local e2 = v4 + readu8(d, p + 2) * ENTRY
local e3 = v4 + readu8(d, p + 3) * ENTRY
p += 4
-- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right)
if pal then
for r = 0, 3 do
local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3
local off = (r % 2) * 8
local q = o + r * stride
writeu8(px, q, readu8(books, l + off))
writeu8(px, q + 1, readu8(books, l + off + 4))
writeu8(px, q + 2, readu8(books, rr + off))
writeu8(px, q + 3, readu8(books, rr + off + 4))
end
else
for r = 0, 3 do
local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3
local off = (r % 2) * 8
local q = (o + r * stride) * 4
writeu32(px, q, readu32(books, l + off))
writeu32(px, q + 4, readu32(books, l + off + 4))
writeu32(px, q + 8, readu32(books, rr + off))
writeu32(px, q + 12, readu32(books, rr + off + 4))
end
end
end
end
end
end
return true
end
-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this
-- packet (an empty frame); false + message = an error
function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?)
local n = buffer.len(d)
if n < 10 then
return false, "frame too short"
end
local strips = be16(d, 8)
if strips == 0 and not (pic.idx and newPalette) then
return false, nil
end
local size = be24(d, 1)
if n < size * 5 // 100 then
return false, "frame shorter than its header says"
end
if st.filmSkip < 0 then
if size == 0 then
return false, "unsupported: a zero frame size"
end
if size ~= n and n % size ~= 0 then
if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6
and readu8(d, 14) == 0 and readu8(d, 15) == 0 then
st.filmSkip = 6
else
st.filmSkip = 2
end
else
st.filmSkip = 0
end
end
local skip = st.filmSkip
if n < 10 + skip + strips * 12 then
return false, "truncated strip headers"
end
if strips > 0 then
local ss = be24(d, 10 + skip + 1)
if ss < 12 or ss > size then
return false, "bad strip size"
end
end
local flags = readu8(d, 0)
local p = 10 + skip
strips = math.min(strips, MAX_STRIPS)
local books = st.books
-- the coded area: the size rounded up to whole blocks (the picture's plane)
local cw, ch = pic.stride, pic.rows
local y0 = 0
for i = 0, strips - 1 do
if p + 12 > n then
return true, nil
end
local sy1 = be16(d, p + 4)
local sx1 = be16(d, p + 6)
local sy2, sx2 = be16(d, p + 8), be16(d, p + 10)
if sy1 == 0 then
sy1 = y0
sy2 = y0 + sy2
end
local ssize = be24(d, p + 1) - 12
if ssize < 0 then
return true, nil
end
p += 12
local stop = math.min(n, p + ssize)
local v4 = i * 2 * BOOK
local v1 = v4 + BOOK
if i > 0 and band(flags, 1) == 0 then
buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK)
end
-- the strip's chunks: codebooks, then one vector chunk
-- (strips start on block boundaries in every known stream: the plane holds whole blocks only)
if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then
return true, nil
end
local q = p
local done = false
while q + 4 <= stop do
local id = readu8(d, q)
local csize = be24(d, q + 1) - 4
if csize < 0 then
return true, nil
end
q += 4
local cstop = math.min(stop, q + csize)
if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then
codebook(books, v4, id, d, q, cstop)
elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then
codebook(books, v1, id, d, q, cstop)
elseif id == 0x30 or id == 0x31 or id == 0x32 then
if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then
return true, nil
end
done = true
break
end
q = cstop
end
if not done then
return true, nil
end
p = stop
y0 = sy2
end
return true, nil
end
return Cinepak
+372
View File
@@ -0,0 +1,372 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is
-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's
-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit
-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK
-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX
-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26);
-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet
-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames.
-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture).
local Types = require("@formats/Types")
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bfill = buffer.fill
local Flic = {}
-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette
export type State = {
pic: Picture.Picture,
depth: number, -- 8, 15, 16, 24
bpp: number, -- bytes per pixel
}
-- state(w, h, depth) -> State | nil, message
function Flic.state(w: number, h: number, depth: number): (State?, string?)
local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0
if bpp == 0 then
return nil, "unsupported: " .. depth .. "-bit FLIC"
end
local pic = Picture.new(w * bpp, h, true)
pic.w = w
return { pic = pic, depth = depth, bpp = bpp }, nil
end
local function s8(v: number): number
return if v >= 128 then v - 256 else v
end
-- decode(st, data) -> true | false, message
function Flic.decode(st: State, d: buffer): (boolean, string?)
local pic = st.pic
local px = pic.idx :: buffer
local pal = pic.pal
local w, h = pic.w, pic.h
local bpp = st.bpp
local deep = bpp > 1
local stride = pic.stride
local limit = stride * h
local n = buffer.len(d)
if n < 16 then
return false, "frame too short"
end
local p = 0
local function u8(): number
local v = if p < n then readu8(d, p) else 0
p += 1
return v
end
local function u16(): number
local a = u8()
return a + u8() * 256
end
local frameSize = math.min(readu32(d, 0), n)
local chunks = readu8(d, 6) + readu8(d, 7) * 256
if frameSize < 16 then
return false, "bad frame size"
end
frameSize -= 16
p = 16
while frameSize >= 6 and chunks > 0 and n - p >= 4 do
local size = readu32(d, p)
if size > frameSize then
size = frameSize
end
local after = p + size
p += 4
local typ = u16()
if typ == 4 or typ == 11 then
if not deep then
-- palette packets: skip count, change count (0 = 256), r g b
local shift = typ == 11
local packets = u16()
local at = 0
for _ = 1, packets do
at += u8()
local count = u8()
if count == 0 then
count = 256
end
if p + count * 3 > after then
break
end
for _ = 1, count do
if at >= 256 then
at = 0
end
local r, g, b = u8(), u8(), u8()
if shift then
-- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below
r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256
r, g, b = r + r // 64, g + g // 64, b + b // 64
end
writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000)
at += 1
end
end
end
elseif typ == 7 or (deep and typ == 27) then
-- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode)
local y = 0
local lines = u16()
while lines > 0 do
if p + 2 > after then
break
end
if y > limit then
return false, "delta past the picture"
end
local lp = u16()
if lp >= 0x8000 then
lp -= 0x10000
end
if deep then
if lp < 0 then
if -lp > h then
return false, "bad line skip"
end
y += -lp * stride
continue
end
elseif lp < 0 and lp >= -0x4000 then
-- 0xC000 .. 0xFFFF: skip lines
if -lp > h then
return false, "bad line skip"
end
y += -lp * stride
continue
elseif lp < 0 then
-- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its
-- padded row instead: the same pixel when rows are not padded)
local q = y + w - 1
if q < 0 or q >= limit then
return false, "delta past the picture"
end
writeu8(px, q, lp % 256)
continue
elseif lp >= 0x4000 then
continue -- undefined opcode
end
lines -= 1
local q = y
for _ = 1, lp do
if p + 2 > after then
break
end
q += u8() * bpp
local run = s8(u8())
if deep then
local cnt = if run < 0 then -run else run
if q + cnt * bpp > limit then
return false, "delta past the picture"
end
if run < 0 then
local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0
for _ = 1, cnt do
writeu8(px, q, a)
writeu8(px, q + 1, b)
if bpp == 3 then
writeu8(px, q + 2, c)
end
q += bpp
end
else
if p + cnt * bpp > after then
break
end
buffer.copy(px, q, d, p, cnt * bpp)
p += cnt * bpp
q += cnt * bpp
end
elseif run < 0 then
local cnt = -run
local a, b = u8(), u8()
if q + cnt * 2 > limit then
return false, "delta past the picture"
end
for _ = 1, cnt do
writeu8(px, q, a)
writeu8(px, q + 1, b)
q += 2
end
else
if q + run * 2 > limit then
return false, "delta past the picture"
end
if p + run * 2 > after then
break
end
buffer.copy(px, q, d, p, run * 2)
p += run * 2
q += run * 2
end
end
y += stride
end
elseif typ == 12 and not deep then
-- byte-oriented delta (LC): first line, line count, per line packets of (skip, run)
local first = u16()
if first >= h then
return false, "bad first line"
end
local y = first * stride
local lines = u16()
while lines > 0 do
local q = y
if q > limit then
return false, "delta past the picture"
end
if p + 1 > after then
break
end
local packets = u8()
for _ = 1, packets do
if p + 1 > after then
break
end
q += u8()
local run = s8(u8())
if run > 0 then
if q + run > limit then
return false, "delta past the picture"
end
if p + run > after then
break
end
buffer.copy(px, q, d, p, run)
p += run
q += run
elseif run < 0 then
local v = u8()
if q - run > limit then
return false, "delta past the picture"
end
bfill(px, q, v, -run)
q -= run
end
end
y += stride
lines -= 1
end
elseif typ == 13 then
bfill(px, 0, 0, limit)
elseif typ == 15 or (deep and typ == 25) then
-- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals
local unit = if typ == 25 then bpp else 1
local y = 0
for _ = 1, h do
local q = y
p += 1 -- the packet count (unused)
local left = if typ == 25 then w else w * bpp
while left > 0 do
if p + 1 > after then
break
end
local run = s8(u8())
if run == 0 and not deep then
return false, "zero byte run"
end
if run > 0 then
if q + run * unit > limit then
return false, "run past the picture"
end
if unit == 1 then
bfill(px, q, u8(), run)
q += run
else
local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0
for _ = 1, run do
writeu8(px, q, a)
writeu8(px, q + 1, b)
if bpp == 3 then
writeu8(px, q + 2, c)
end
q += bpp
end
end
left -= run
else
local cnt = -run
if q + cnt * unit > limit then
return false, "run past the picture"
end
if p + cnt * unit > after then
break
end
buffer.copy(px, q, d, p, cnt * unit)
p += cnt * unit
q += cnt * unit
left -= cnt
end
end
y += stride
end
elseif typ == 16 or (deep and typ == 26) then
-- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more)
local row = w * bpp
local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4
local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h
if ok then
if deep and n - p < row * h then
return false, "truncated copy chunk"
end
for y = 0, h - 1 do
local s = p + y * padded
local cnt = math.max(0, math.min(row, n - s))
if cnt > 0 then
buffer.copy(px, y * stride, d, s, cnt)
end
end
p += padded * h
end
end
-- typ 18 (PSTAMP) and unknown chunks are skipped
if after - p >= 0 then
p = after
else
break
end
frameSize -= size
chunks -= 1
end
return true, nil
end
-- image(st) -> a fresh rgba8 Image
function Flic.image(st: State): Types.Image
local pic = st.pic
if st.bpp == 1 then
return Picture.image(pic)
end
local w, h = pic.w, pic.h
local img = Types.Image.new(w, h, "rgba8")
local out = img.pixels
local px = pic.idx :: buffer
local stride = pic.stride
if st.bpp == 3 then
for y = 0, h - 1 do
local s, o = y * stride, y * w * 4
for x = 0, w - 1 do
local q = s + x * 3
writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000)
end
end
else
local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565()
local mask = if st.depth == 15 then 32768 else 65536
for y = 0, h - 1 do
local s, o = y * stride, y * w * 4
for x = 0, w - 1 do
local q = s + x * 2
writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4))
end
end
end
return img
end
return Flic
@@ -0,0 +1,121 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit
-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows
-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour
-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour
-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture.
-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there).
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local band = bit32.band
local Msvideo1 = {}
-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1
-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)]
local function quadrant(x: number, y: number): number
return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0)
end
-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit)
function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?)
local n = buffer.len(d)
local bw, bh = pic.w // 4, pic.h // 4
if n < bw * bh // 512 then
return false, "frame too small"
end
local stride = pic.stride
local total = bw * bh
local skip = 0
local p = 0
local wide = bits ~= 8
local px = (if wide then pic.rgba else pic.idx) :: buffer
local lut = if wide then Picture.rgb555() else nil
local c = table.create(8, 0)
for by = bh - 1, 0, -1 do
for bx = 0, bw - 1 do
if skip ~= 0 then
skip -= 1
total -= 1
continue
end
if p + 2 > n then
return true, nil
end
local a, b = readu8(d, p), readu8(d, p + 1)
p += 2
if a == 0 and b == 0 and total == 0 then
return true, nil
end
-- the block's bottom-left pixel; its rows go up
local o = (by * 4 + 3) * stride + bx * 4
if band(b, 0xFC) == 0x84 then
skip = (b - 0x84) * 256 + a - 1
elseif b < 0x80 or (not wide and b >= 0x90) then
local flags = b * 256 + a
local eight
if wide then
if p + 4 > n then
return true, nil
end
c[1], c[2] = readu16(d, p), readu16(d, p + 2)
p += 4
eight = c[1] >= 0x8000
if eight then
if p + 12 > n then
return true, nil
end
for k = 3, 8 do
c[k] = readu16(d, p)
p += 2
end
end
else
eight = b >= 0x90
local cnt = if eight then 8 else 2
if p + cnt > n then
return true, nil
end
for k = 1, cnt do
c[k] = readu8(d, p)
p += 1
end
end
for y = 0, 3 do
local row = o - y * stride
for x = 0, 3 do
local k = (if band(flags, 1) == 1 then 1 else 2)
if eight then
k += quadrant(x, y)
end
flags = flags // 2
if lut then
writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4))
else
writeu8(px, row + x, c[k])
end
end
end
else
local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a
for y = 0, 3 do
local row = o - y * stride
if lut then
for x = 0, 3 do
writeu32(px, (row + x) * 4, v)
end
else
writeu32(px, row, v * 0x01010101)
end
end
end
total -= 1
end
end
return true, nil
end
return Msvideo1
@@ -0,0 +1,115 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame
-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette,
-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past
-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication
-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in formats-luau.
local Types = require("@formats/Types")
local Pixels = require("@formats/codecs/image/Pixels")
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local Picture = {}
export type Picture = {
w: number,
h: number,
stride: number, -- index plane: bytes per row; rgba plane: pixels per row
rows: number,
idx: buffer?, -- u8 index plane, stride * rows bytes (palettised)
rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour)
pal: buffer, -- 256 u32 entries, bytes R, G, B, A
}
-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...)
function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture
local pw, ph = padW or 1, padH or 1
local stride = ((w + pw - 1) // pw) * pw
local rows = ((h + ph - 1) // ph) * ph
local pal = buffer.create(1024)
if palette and buffer.len(palette) >= 1024 then
buffer.copy(pal, 0, palette, 0, 1024)
end
local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal }
if palettised then
p.idx = buffer.create(stride * rows)
else
p.rgba = buffer.create(stride * rows * 4)
end
return p
end
-- image(p) -> a fresh rgba8 Image of the visible w x h
function Picture.image(p: Picture): Types.Image
local w, h = p.w, p.h
local img = Types.Image.new(w, h, "rgba8")
local idx, rgba = p.idx, p.rgba
if idx then
Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal)
elseif rgba then
if p.stride == w then
buffer.copy(img.pixels, 0, rgba, 0, w * h * 4)
else
for y = 0, h - 1 do
buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4)
end
end
end
return img
end
-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track
function Picture.setPalette(p: Picture, src: buffer)
if buffer.len(src) >= 1024 then
buffer.copy(p.pal, 0, src, 0, 1024)
end
end
local lut555: buffer? = nil
local lut565: buffer? = nil
-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries
function Picture.rgb555(): buffer
local t = lut555
if t then
return t
end
local b = buffer.create(32768 * 4)
for v = 0, 32767 do
local r, g, bl = v // 1024, (v // 32) % 32, v % 32
r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4
writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000)
end
lut555 = b
return b
end
-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries
function Picture.rgb565(): buffer
local t = lut565
if t then
return t
end
local b = buffer.create(65536 * 4)
for v = 0, 65535 do
local r, g, bl = v // 2048, (v // 32) % 64, v % 32
r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4
writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000)
end
lut565 = b
return b
end
-- copy of a picture's plane (for decoders that read the previous picture while writing the next)
function Picture.clonePlane(p: Picture): buffer
local src = (p.idx or p.rgba) :: buffer
local c = buffer.create(buffer.len(src))
buffer.copy(c, 0, src, 0)
return c
end
local _ = readu32
return Picture
+276
View File
@@ -0,0 +1,276 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and
-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File
-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per
-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups).
-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its
-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames
-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read
-- and write is range-checked (a damaged frame stops where the damage is).
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local QtRle = {}
local function s8(v: number): number
return if v >= 128 then v - 256 else v
end
-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line)
local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number)
row -= stride
local q = row
lines += 1
while lines > 0 do
if p + 2 > n then
return
end
local skip = readu8(d, p)
local code = s8(readu8(d, p + 1))
p += 2
if code == 0 then
return
end
if skip >= 128 then
lines -= 1
row += stride
q = row + 16 * (skip - 128)
else
q += 16 * skip
end
if q < 0 or q > limit then
return
end
if code ~= -1 then
if code < 0 then
local cnt = -code
if p + 2 > n or q + cnt * 16 > limit then
return
end
local a, b = readu8(d, p), readu8(d, p + 1)
p += 2
for _ = 1, cnt do
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(a, k), 1))
q += 1
end
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(b, k), 1))
q += 1
end
end
else
local cnt = code * 2
if p + cnt > n or q + cnt * 8 > limit then
return
end
for _ = 1, cnt do
local a = readu8(d, p)
p += 1
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(a, k), 1))
q += 1
end
end
end
end
end
end
-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups
local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number)
local group = 32 // bpp -- pixels per 4 bytes
local per = 8 // bpp -- pixels per byte
local mask = 2 ^ bpp - 1
for _ = 1, lines do
if p >= n then
return
end
local q = row + group * (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
while true do
if p >= n then
return
end
local code = s8(readu8(d, p))
p += 1
if code == -1 then
break
end
if p >= n then
return
end
if code == 0 then
q += group * (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
elseif code < 0 then
local cnt = -code
if p + 4 > n or q + cnt * group > limit then
return
end
if bpp == 8 then
local v = readu32(d, p)
for _ = 1, cnt do
writeu32(px, q, v)
q += 4
end
else
local v0 = q
for b = 0, 3 do
local byte = readu8(d, p + b)
for k = per - 1, 0, -1 do
writeu8(px, q, band(rshift(byte, k * bpp), mask))
q += 1
end
end
for _ = 2, cnt do
buffer.copy(px, q, px, v0, group)
q += group
end
end
p += 4
else
local bytes = code * 4
if p + bytes > n or q + bytes * per > limit then
return
end
if bpp == 8 then
buffer.copy(px, q, d, p, bytes)
q += bytes
else
for b = 0, bytes - 1 do
local byte = readu8(d, p + b)
for k = per - 1, 0, -1 do
writeu8(px, q, band(rshift(byte, k * bpp), mask))
q += 1
end
end
end
p += bytes
end
end
row += stride
end
end
-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels)
local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number)
local bpp = depth // 8
local lut = if depth == 16 then Picture.rgb555() else nil
for _ = 1, lines do
if p >= n then
return
end
local q = row + (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
while true do
if p >= n then
return
end
local code = s8(readu8(d, p))
p += 1
if code == -1 then
break
end
if p >= n then
return
end
if code == 0 then
q += readu8(d, p) - 1
p += 1
if q < 0 or q > limit then
return
end
else
local cnt = if code < 0 then -code else code
local need = if code < 0 then bpp else bpp * cnt
if p + need > n or q + cnt > limit then
return
end
for _ = 1, cnt do
local v
if lut then
v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4)
elseif bpp == 3 then
v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000
else
v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216
end
writeu32(px, q * 4, v)
q += 1
if code > 0 then
p += bpp
end
end
if code < 0 then
p += bpp
end
end
end
row += stride
end
end
-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message
function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?)
local n = buffer.len(d)
if n < 8 then
return true, nil -- no change
end
local p = 4
local header = readu8(d, p) * 256 + readu8(d, p + 1)
p += 2
local h = pic.h
local start, lines = 0, h
if band(header, 8) ~= 0 then
if n < 14 then
return true, nil
end
start = readu8(d, p) * 256 + readu8(d, p + 1)
lines = readu8(d, p + 4) * 256 + readu8(d, p + 5)
p += 8
if lines > h - start then
return true, nil
end
end
local stride = pic.stride
local bits = if depth > 32 then depth - 32 else depth
local idx, rgba = pic.idx, pic.rgba
if idx and bits <= 8 then
local limit = stride * h
if bits == 1 then
decode1(idx, stride, limit, d, p, n, start * stride, lines)
else
decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits)
end
elseif rgba and (bits == 16 or bits == 24 or bits == 32) then
decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits)
else
return false, "unsupported: depth " .. depth
end
return true, nil
end
-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs
function QtRle.palettised(depth: number): boolean
return depth <= 8 or depth > 32
end
function QtRle.pad(depth: number): number
local bits = if depth > 32 then depth - 32 else depth
return if bits <= 8 then 32 // math.max(1, bits) else 1
end
return QtRle
@@ -0,0 +1,405 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and
-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are
-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value);
-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte
-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a
-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header;
-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a
-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour).
-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads
-- 10 bits at a time through a lookup table into them.
-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give
-- zero bits, a frame whose codes run out of bits gives no picture.
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local Smacker = {}
local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder)
local MAX_DEPTH16 = 500
-- block runs (TYPE code bits 2..7)
local RUNS = table.create(64, 0)
for i = 1, 59 do
RUNS[i] = i
end
RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048
-- a bit position over buf[0, nbits / 8)
export type Bits = { buf: buffer, pos: number, nbits: number }
function Smacker.bits(buf: buffer, offset: number, length: number): Bits
return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 }
end
local function bit(br: Bits): number
local p = br.pos
br.pos = p + 1
if p >= br.nbits then
return 0
end
return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1)
end
Smacker.bit = bit
-- read(br, n) -> n bits (LSB first; zeros past the end)
function Smacker.read(br: Bits, n: number): number
local v, m = 0, 1
for _ = 1, n do
v += bit(br) * m
m *= 2
end
return v
end
local readBits = Smacker.read
-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups)
local function walk(tree: { number }, br: Bits): number
local i = 1
local e = tree[1]
while e < 0 do
if bit(br) == 1 then
i += -e - 1
end
i += 1
e = tree[i]
end
return e
end
Smacker.walk = walk
-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based)
local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?)
local vals: { number } = {}
local n = 0
local stack: { number } = {}
local state: { number } = {}
local sp = 0
while true do
if sp > maxDepth then
return nil, "tree too deep"
end
if n >= maxEntries then
return nil, "tree too big"
end
if bigChecks and br.pos >= br.nbits then
return nil, "truncated tree"
end
if bit(br) == 1 then
n += 1
vals[n] = -1
sp += 1
stack[sp], state[sp] = n, 0
else
local v, msg = leaf(n)
if not v then
return nil, msg
end
n += 1
vals[n] = v
local more = false
while sp > 0 do
if state[sp] == 0 then
local at = stack[sp]
vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries
state[sp] = 1
more = true
break
end
sp -= 1
end
if not more then
return vals, nil
end
end
end
end
-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message
function Smacker.tree8(br: Bits): ({ number }?, string?)
local leaves = 0
return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?)
if leaves >= 256 then
return nil, "tree too big"
end
leaves += 1
if br.nbits - br.pos < 8 then
return nil, "truncated tree"
end
return readBits(br, 8), nil
end, false)
end
local tree8 = Smacker.tree8
export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based)
-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries)
local function bigTree(br: Bits, size: number): (BigTree?, string?)
if bit(br) == 0 then
return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0
end
local lohi: { { number } } = {}
for k = 1, 2 do
if bit(br) == 0 then
lohi[k] = { 0 }
else
local t, msg = tree8(br)
if not t then
return nil, msg
end
bit(br)
lohi[k] = t
end
end
local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) }
local last = { -1, -1, -1 }
local lo, hi = lohi[1], lohi[2]
local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?)
local v = walk(lo, br) + walk(hi, br) * 256
for k = 1, 3 do
if v == esc[k] then
last[k] = index + 1
return 0, nil
end
end
return v, nil
end, true)
if not vals then
return nil, msg
end
bit(br)
for k = 1, 3 do
if last[k] == -1 then
table.insert(vals, 0)
last[k] = #vals
end
end
return { vals = vals, last = last }, nil
end
export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree }
-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits
function Smacker.trees(config: buffer): (Trees?, string?)
local n = buffer.len(config)
if n <= 16 then
return nil, "no trees"
end
local br = Smacker.bits(config, 16, n - 16)
local out: { BigTree } = {}
local present = 0
for k = 1, 4 do
local size = buffer.readu32(config, (k - 1) * 4)
if size >= 2 ^ 28 then
return nil, "tree size too large"
end
local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1
local t, msg = bigTree(br, size)
if not t then
return nil, msg
end
if here then
present += 1
end
out[k] = t
end
if present == 0 or br.pos > br.nbits then
return nil, "bad trees"
end
return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil
end
local LUT_BITS = 10
-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits
local function lut(vals: { number }): buffer
local size = 2 ^ LUT_BITS
local t = buffer.create(size * 4)
for pat = 0, size - 1 do
local i, len = 1, 0
local e = vals[1]
while e < 0 and len < LUT_BITS do
if band(rshift(pat, len), 1) == 1 then
i += -e - 1
end
i += 1
len += 1
e = vals[i]
end
writeu32(t, pat * 4, i * 32 + len)
end
return t
end
local function reset(t: BigTree)
local vals, last = t.vals, t.last
vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0
end
-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4
function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?)
local px = pic.idx :: buffer
local stride = pic.stride
local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type
for _, t in { mmap, mclr, full, typ } do
reset(t)
if not t.lut then
t.lut = lut(t.vals)
end
end
local n = buffer.len(d)
local nbits = n * 8
local pos = 0
-- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree
local function code(t: BigTree): number
local vals = t.vals
local i, p
local byte = rshift(pos, 3)
if byte + 3 <= n then
local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023)
local ent = readu32(t.lut :: buffer, v * 4)
i = rshift(ent, 5)
p = pos + band(ent, 31)
else
i, p = 1, pos
end
local e = vals[i]
while e < 0 do
if p >= nbits then
return -1
end
if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then
i += -e - 1
end
p += 1
i += 1
e = vals[i]
end
pos = p
local last = t.last
local l0 = last[1]
if e ~= vals[l0] then
local l1 = last[2]
vals[last[3]] = vals[l1]
vals[l1] = vals[l0]
vals[l0] = e
end
return e
end
local function bit(): number
local p = pos
pos = p + 1
if p >= nbits then
return 0
end
return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1)
end
local bw, bh = pic.w // 4, pic.h // 4
local blocks = bw * bh
local blk = 0
while blk < blocks do
local ty = code(typ)
if ty < 0 then
return false, "truncated frame"
end
local run = RUNS[band(rshift(ty, 2), 63) + 1]
local kind = band(ty, 3)
if kind == 2 then
blk = math.min(blocks, blk + run)
elseif kind == 3 then
local v = rshift(ty, 8) * 0x01010101
for _ = 1, run do
if blk >= blocks then
break
end
local o = (blk // bw) * stride * 4 + (blk % bw) * 4
writeu32(px, o, v)
writeu32(px, o + stride, v)
writeu32(px, o + 2 * stride, v)
writeu32(px, o + 3 * stride, v)
blk += 1
end
elseif kind == 0 then
for _ = 1, run do
if blk >= blocks then
break
end
local clr = code(mclr)
local map = code(mmap)
if clr < 0 or map < 0 then
return false, "truncated frame"
end
local hi, lo = rshift(clr, 8), band(clr, 255)
local o = (blk // bw) * stride * 4 + (blk % bw) * 4
for r = 0, 3 do
local q = o + r * stride
writeu8(px, q, if band(map, 1) ~= 0 then hi else lo)
writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo)
writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo)
writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo)
map = rshift(map, 4)
end
blk += 1
end
else
local mode = 0
if v4 then
if pos >= nbits then
return false, "truncated frame"
end
if bit() == 1 then
mode = 1
elseif bit() == 1 then
mode = 2
end
end
for _ = 1, run do
if blk >= blocks then
break
end
local o = (blk // bw) * stride * 4 + (blk % bw) * 4
if mode == 0 then
for r = 0, 3 do
local a = code(full)
local b = code(full)
if a < 0 or b < 0 then
return false, "truncated frame"
end
-- the first code is the right pixel pair, the second the left one
writeu32(px, o + r * stride, b + a * 65536)
end
elseif mode == 1 then
for half = 0, 1 do
local a = code(full)
if a < 0 then
return false, "truncated frame"
end
local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000
writeu32(px, o + half * 2 * stride, v)
writeu32(px, o + (half * 2 + 1) * stride, v)
end
else
for half = 0, 1 do
local p2 = code(full)
local p1 = code(full)
if p1 < 0 or p2 < 0 then
return false, "truncated frame"
end
local v = p1 + p2 * 65536
writeu32(px, o + half * 2 * stride, v)
writeu32(px, o + (half * 2 + 1) * stride, v)
end
end
blk += 1
end
end
end
return true, nil
end
return Smacker
+183
View File
@@ -0,0 +1,183 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description
-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble
-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour
-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index:
-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc
-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row
-- above). Never throws: reads past the data give zeros, the block count bounds every write.
local Picture = require("@formats/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local Smc = {}
-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames)
function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?)
local px = pic.idx :: buffer
local n = buffer.len(d)
local stride = pic.stride -- a multiple of 4: the plane holds whole blocks
local bh = pic.rows // 4
local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4)
if total // 1024 > n then
return false, "frame too small"
end
local blocksWide = (pic.w + 3) // 4
local p = 4 -- flags byte + 24-bit chunk size
-- block position: bx, by (blocks)
local bx, by = 0, 0
local pairI, quadI, octI = 0, 0, 0
-- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8)
local function u8(): number
if p < n then
local v = readu8(d, p)
p += 1
return v
end
return 0
end
local function advance()
bx += 1
if bx >= blocksWide then
bx = 0
by += 1
end
total -= 1
end
while total > 0 do
if p >= n then
return false, "truncated"
end
local op = readu8(d, p)
p += 1
local kind = rshift(op, 4)
local count: number
if kind < 8 then
count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15)
else
count = band(op, 15) + 1
end
if kind <= 1 then
for _ = 1, count do
if total <= 0 then
break
end
advance()
end
elseif kind <= 5 then
-- repeat the last block (2, 3) or the last pair of blocks (4, 5)
local pair = kind >= 4
local back = if pair then 2 else 1
local pos = by * blocksWide + bx
if pos < back then
return false, "repeat before any block"
end
local reps = if pair then count * 2 else count
local srcA = pos - back
local srcB = pos - 1
for k = 0, reps - 1 do
if total <= 0 or by >= bh then
break
end
local s = if pair and k % 2 == 1 then srcB else srcA
local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4
local o, so = by * 4 * stride + bx * 4, sy * stride + sx
for r = 0, 3 do
writeu32(px, o + r * stride, readu32(px, so + r * stride))
end
advance()
end
elseif kind <= 7 then
local c = u8()
local v = c * 0x01010101
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
for r = 0, 3 do
writeu32(px, o + r * stride, v)
end
advance()
end
elseif kind <= 13 then
-- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds)
local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8
local base = if size == 2 then 0 elseif size == 4 then 512 else 1536
local entry: number
if kind % 2 == 0 then
local i = if size == 2 then pairI elseif size == 4 then quadI else octI
for k = 0, size - 1 do
writeu8(tables, base + i * size + k, u8())
end
entry = i
i = (i + 1) % 256
if size == 2 then
pairI = i
elseif size == 4 then
quadI = i
else
octI = i
end
else
entry = u8()
end
local t = base + entry * size
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
if size == 2 then
local f = u8() * 256 + u8()
for k = 0, 15 do
local bit = band(rshift(f, 15 - k), 1)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit))
end
elseif size == 4 then
local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8()
for k = 0, 15 do
local i = band(rshift(f, 30 - 2 * k), 3)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i))
end
else
-- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel)
local v1 = u8() * 256 + u8()
local v2 = u8() * 256 + u8()
local v3 = u8() * 256 + u8()
local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4)
local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15)
for k = 0, 15 do
local f = if k < 8 then fa else fb
local i = band(rshift(f, 21 - 3 * (k % 8)), 7)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i))
end
end
advance()
end
else
-- 16-colour blocks
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
for k = 0, 15 do
writeu8(px, o + (k // 4) * stride + k % 4, u8())
end
advance()
end
end
end
return true, nil
end
-- tables() -> the colour group scratch (pairs, quads, octets)
function Smc.tables(): buffer
return buffer.create(512 + 1024 + 2048)
end
return Smc
+214
View File
@@ -0,0 +1,214 @@
--!strict
-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk
-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak",
-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation
-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker
-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4).
-- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's
-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns
-- a fresh copy.
--
-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the
-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that
-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth).
--
-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder
-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
--
-- Never throws: bad tracks return nil, Err; bad packets return Err from decode().
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Picture = require("@formats/codecs/video/Legacy/Picture")
local Flic = require("@formats/codecs/video/Legacy/Flic")
local Cinepak = require("@formats/codecs/video/Legacy/Cinepak")
local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1")
local QtRle = require("@formats/codecs/video/Legacy/QtRle")
local Smc = require("@formats/codecs/video/Legacy/Smc")
local Smacker = require("@formats/codecs/video/Legacy/Smacker")
local Legacy = {}
Legacy.Picture = Picture
Legacy.Flic = Flic
Legacy.Cinepak = Cinepak
Legacy.Msvideo1 = Msvideo1
Legacy.QtRle = QtRle
Legacy.Smc = Smc
Legacy.Smacker = Smacker
Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
export type Options = {
maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26)
[string]: any,
}
-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err?
type Codec = {
make: (track: Types.Track) -> (any, string?),
step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?),
}
local function fail(msg: string?): Err.Err
return Err.from(msg or "corrupt frame")
end
local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean
local pal = (packet :: any).palette
if type(pal) == "buffer" then
Picture.setPalette(pic, pal)
return true
end
return false
end
local CODECS: { [string]: Codec } = {
qtrle = {
make = function(t)
local depth = t.bitsPerPixel or 24
local bits = if depth > 32 then depth - 32 else depth
if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then
return nil, "unsupported: depth " .. depth
end
return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
local ok, msg = QtRle.decode(st.pic, data, st.depth)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
smc = {
make = function(t)
return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
local ok, msg = Smc.decode(st.pic, data, st.tables)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
msvideo1 = {
make = function(t)
if (t.width :: number) < 4 or (t.height :: number) < 4 then
return nil, "smaller than one block"
end
local bits = if t.bitsPerPixel == 8 then 8 else 16
return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil
end,
step = function(st, data, packet)
if st.bits == 8 then
packetPalette(st.pic, packet)
end
local ok, msg = Msvideo1.decode(st.pic, data, st.bits)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
cinepak = {
make = function(t)
local pal = t.bitsPerPixel == 8
return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil
end,
step = function(st, data, packet)
local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet)
local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal)
if not ok then
return nil, if msg then fail(msg) else nil
end
return Picture.image(st.pic), nil
end,
},
smackvid = {
make = function(t)
local cfg = t.config
if type(cfg) ~= "buffer" then
return nil, "no Smacker trees"
end
local trees, msg = Smacker.trees(cfg)
if not trees then
return nil, msg
end
return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
if buffer.len(data) == 0 then
return nil, fail("empty frame")
end
local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
flic = {
make = function(t)
return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8)
end,
step = function(st, data, _packet)
local ok, msg = Flic.decode(st, data)
if not ok then
return nil, fail(msg)
end
return Flic.image(st), nil
end,
},
}
-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err
function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?)
local codec = CODECS[id]
if not codec then
return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id))
end
local w, h = track.width or 0, track.height or 0
if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then
return nil, Err.new(Err.CORRUPT, "video track without a valid size")
end
local max = (opts and opts.maxPixels) or 2 ^ 26
if w * h > max or w > 32768 or h > 32768 then
return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit")
end
local st, msg = codec.make(track)
if not st then
return nil, fail(msg)
end
-- Video.simpleDecoder, without requiring the registry (which requires this module)
local queue: { any } = {}
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, img, err = pcall(codec.step, st, packet.data, packet)
if not ok then
return Err.new(Err.CORRUPT, "decoder failed: " .. 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, nil, nil
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(queue)
st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe)
end
return self :: any, nil
end
return Legacy
File diff suppressed because it is too large. Load diff
+8 -259
View File
@@ -1,262 +1,11 @@
--!strict
-- codecs/video/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/video/Mpeg1/Decoder")
-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder
-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame /
-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2.
local Mpeg2 = require("@formats/codecs/video/Mpeg2")
local Mpeg1 = {}
export type Frame = Mpeg2.Frame
export type Options = Mpeg2.Options
export type Decoder = Mpeg2.Decoder
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
return Mpeg2
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,8 @@
--!strict
-- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those 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.
-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the
-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7.
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,
@@ -74,16 +75,6 @@ T.MOTION = { [0] = 3,
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,
@@ -114,4 +105,34 @@ T.DCT_COEFF = { [0] = 3,
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,
}
-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size
T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } }
T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } }
-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows)
T.DCT_COEFF_B15 = {
2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8,
124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16,
30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24,
22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32,
23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40,
2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264,
30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272,
17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769,
38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282,
18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050,
120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074,
36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098,
31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145,
28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937,
}
-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code
T.NON_LINEAR_QSCALE = { [0] = 0,
1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112,
}
-- the alternate scan (Figure 7-3): scan index -> natural position
T.ALTERNATE_SCAN = { [0] = 0,
8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58,
35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46,
54, 62, 39, 47, 55, 63,
}
return T
@@ -1,14 +1,15 @@
--!strict
-- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (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/video/Mpeg1/Tables")
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA /
-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees);
-- the MPEG-2 tables are built from code lists.
local T = require("@formats/codecs/video/Mpeg2/Tables")
local V = {}
@@ -32,8 +33,7 @@ local function leaves(tree: { [number]: number }): { Leaf }
return out
end
local function flat(tree: { [number]: number }): (buffer, number)
local ls = leaves(tree)
local function flatLeaves(ls: { Leaf }): (buffer, number)
local k = 0
for _, l in ls do
k = math.max(k, l.len)
@@ -49,6 +49,19 @@ local function flat(tree: { [number]: number }): (buffer, number)
return lut, k
end
local function flat(tree: { [number]: number }): (buffer, number)
return flatLeaves(leaves(tree))
end
-- { { code, length } } indexed from 1 -> leaves with value = index - 1
local function codeLeaves(codes: { { number } }): { Leaf }
local out: { Leaf } = {}
for i, c in codes do
table.insert(out, { code = c[1], len = c[2], value = i - 1 })
end
return out
end
V.SUB = 0x1000000
V.ESC = 0xFFFF
V.EOB = 0xFFFE
@@ -93,10 +106,16 @@ V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35
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)
do
-- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma
-- pattern bits)
local ls = leaves(T.CODE_BLOCK_PATTERN)
table.insert(ls, { code = 1, len = 9, value = 0 })
V.CBP, V.CBP_BITS = flatLeaves(ls)
end
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)
V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA))
V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA))
do
local ls = leaves(T.DCT_COEFF)
@@ -113,4 +132,13 @@ do
V.DCT_NEXT = twoLevel(nextLs)
end
do
local ls: { Leaf } = { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } }
local b = T.DCT_COEFF_B15
for i = 1, #b, 3 do
table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] })
end
V.DCT_B15 = twoLevel(ls)
end
return V
+364
View File
@@ -0,0 +1,364 @@
--!strict
-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I /
-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes
-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from
-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this
-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines);
-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded.
-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
--
-- local dec = Mpeg2.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg2.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, chroma, ... }
-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2)
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local D = require("@formats/codecs/video/Mpeg2/Decoder")
local Mpeg2 = {}
Mpeg2.PICTURE_I = 1
Mpeg2.PICTURE_P = 2
Mpeg2.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 planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride
-- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2)
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
chroma: number, -- 1 = 4:2:0, 2 = 4:2:2
mpeg2: boolean,
progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true)
fields: boolean, -- coded as two field pictures
topFieldFirst: boolean,
repeatFirstField: boolean,
clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated)
concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed)
}
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 Mpeg2.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,
chroma = s.chroma,
mpeg2 = s.mpeg2,
progressive = s.progressive,
fields = s.fields,
topFieldFirst = s.tff,
repeatFirstField = s.rff,
clamped = s.clamped,
concealed = s.concealed,
}
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"; 4:2:2 chroma
-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for
-- a value that is not a Frame.
function Mpeg2.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 c422 = frame.chroma == 2
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
local crows = if c422 then h else oh
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
if c422 then
D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
end
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
if not c422 then
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
else
-- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field
-- (4k + j and 4k + j + 2), so the fields do not mix
local inter = not frame.progressive
for y = 0, oh - 1 do
local a, b
if inter then
local base = (y // 2) * 4 + y % 2
a, b = base, base + 2
else
a, b = 2 * y, 2 * y + 1
end
if b >= h then
b = a
end
for x = 0, ow - 1 do
buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2)
buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2)
end
end
end
end
img.meta.source = {
format = if frame.mpeg2 then "mpeg2" else "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
chroma = if c422 then "422" else "420",
interlaced = not frame.progressive,
topFieldFirst = frame.topFieldFirst,
range = if rgba then nil else "limited",
}
return img
end
-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder
-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in
-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of
-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream).
function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
local function push(f: Frame)
local img = Mpeg2.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 tag = { packet.pts }
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag)
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
while f do -- more pictures in the packet
push(f)
f = dec:decode(packet.data, 0, 0, tag)
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, nil, nil
end
function self.flush(_: any)
for _ = 1, 8 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
return Mpeg2
File diff suppressed because it is too large. Load diff
+370
View File
@@ -0,0 +1,370 @@
--!strict
-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame /
-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis
-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the
-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman
-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause:
-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking;
-- the table layout here is simpler). Never throws: bad headers return nil, message.
local Bits = require("@formats/core/Bits")
local H = {}
export type Info = {
versionMajor: number,
versionMinor: number,
versionSub: number,
frameWidth: number, -- coded frame size (multiples of 16)
frameHeight: number,
picWidth: number, -- the picture region (the displayed part)
picHeight: number,
picX: number, -- from the left
picY: number, -- from the bottom, as stored
fpsNum: number,
fpsDen: number,
aspectNum: number,
aspectDen: number,
colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG
bitrate: number,
quality: number,
granuleShift: number,
pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved)
}
export type Setup = {
lflim: { number }, -- [qi + 1]: loop filter limit
dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora
huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable)
roots: { number }, -- [table + 1]: the root node offset in huff
}
-- the zig-zag scan: natural index of the coefficient at scan position zzi
H.ZIGZAG = {
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,
}
local function ilog(v: number): number
local n = 0
while v > 0 do
n += 1
v = v // 2
end
return n
end
-- ------------------------------------------------------------------------------------------------ identification
-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora"
function H.info(b: buffer, off: number, len: number): (Info?, string?)
if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora identification header"
end
local br = Bits.msbReader(b, off + 7, len - 7)
local info: Info = {
versionMajor = br:read(8),
versionMinor = br:read(8),
versionSub = br:read(8),
frameWidth = br:read(16) * 16,
frameHeight = br:read(16) * 16,
picWidth = br:read(24),
picHeight = br:read(24),
picX = br:read(8),
picY = br:read(8),
fpsNum = br:read(32),
fpsDen = br:read(32),
aspectNum = br:read(24),
aspectDen = br:read(24),
colorspace = br:read(8),
bitrate = br:read(24),
quality = br:read(6),
granuleShift = br:read(5),
pixelFormat = br:read(2),
}
local reserved = br:read(3)
if br.err then
return nil, "truncated identification header"
end
if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then
return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor
end
if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then
return nil, "bad frame / picture size"
end
if info.fpsNum == 0 or info.fpsDen == 0 then
return nil, "bad frame rate"
end
if info.pixelFormat == 1 or reserved ~= 0 then
return nil, "reserved pixel format"
end
return info, nil
end
-- ------------------------------------------------------------------------------------------------ comment
-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora"
function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, nil, "not a Theora comment header"
end
local p, e = off + 7, off + len
local function str(): string?
if p + 4 > e then
return nil
end
local n = buffer.readu32(b, p)
p += 4
if n > e - p then
return nil
end
local s = buffer.readstring(b, p, n)
p += n
return s
end
local vendor = str()
if not vendor or p + 4 > e then
return nil, nil, "truncated comment header"
end
local count = buffer.readu32(b, p)
p += 4
if count * 4 > e - p then
return nil, nil, "bad comment count"
end
local list: { string } = {}
for _ = 1, count do
local s = str()
if not s then
return nil, nil, "truncated comment header"
end
table.insert(list, s)
end
return vendor, list, nil
end
-- ------------------------------------------------------------------------------------------------ Huffman trees
-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in
-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf
-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits).
local MAXBITS = 8
local function readTree(br: any): ({ number }?, { number }?, { number }?)
-- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root)
local kid0, kid1, tok = { 0 }, { 0 }, { -1 }
-- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length
local code, len, nleaves = 0, 0, 0
while true do
local bit = br:read(1)
if br.err then
return nil, nil, nil
end
if bit == 0 then
len += 1
if len > 32 then
return nil, nil, nil
end
else
nleaves += 1
if nleaves > 32 then
return nil, nil, nil
end
local t = br:read(5)
-- insert the leaf
local n = 1
for d = 1, len do
local k = (code // 2 ^ (32 - d)) % 2
local kids = if k == 0 then kid0 else kid1
local nx = kids[n]
if nx == 0 then
nx = #tok + 1
kid0[nx], kid1[nx], tok[nx] = 0, 0, -1
kids[n] = nx
end
n = nx
end
tok[n] = t
if len <= 0 then
break
end
-- the next codeword: clear the trailing 1 bits, then set the last 0 bit
local cb = 2 ^ (32 - len)
while len > 0 and (code // cb) % 2 == 1 do
code -= cb
cb *= 2
len -= 1
end
if len <= 0 then
break
end
code += cb
end
end
return kid0, kid1, tok
end
local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number
local heights: { [number]: number } = {}
local function height(n: number): number
local h = heights[n]
if h then
return h
end
h = 0
if tok[n] < 0 then
local a = if kid0[n] ~= 0 then height(kid0[n]) else 0
local c = if kid1[n] ~= 0 then height(kid1[n]) else 0
h = 1 + math.max(a, c)
end
heights[n] = h
return h
end
local function node(n: number): number
local nb = math.clamp(height(n), 1, MAXBITS)
local off = #out + 1
out[off] = nb
local size = 2 ^ nb
for i = 1, size do
out[off + i] = 0
end
for i = 0, size - 1 do
local cur, d = n, 0
while d < nb and tok[cur] < 0 do
local bit = bit32.extract(i, nb - 1 - d, 1)
local nx = if bit == 0 then kid0[cur] else kid1[cur]
d += 1
cur = nx
if nx == 0 then
break
end
end
if cur == 0 then
out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0
elseif tok[cur] >= 0 then
out[off + 1 + i] = d * 64 + tok[cur]
else
out[off + 1 + i] = -node(cur)
end
end
return off
end
return node(1)
end
-- ------------------------------------------------------------------------------------------------ setup
local DC_MIN = { 16, 32 }
local AC_MIN = { 8, 16 }
-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora"
function H.setup(b: buffer, off: number, len: number): (Setup?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora setup header"
end
local br = Bits.msbReader(b, off + 7, len - 7)
-- loop filter limits, AC / DC scales
local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0)
local nb = br:read(3)
for qi = 1, 64 do
lflim[qi] = br:read(nb)
end
nb = br:read(4) + 1
for qi = 1, 64 do
acScale[qi] = br:read(nb)
end
nb = br:read(4) + 1
for qi = 1, 64 do
dcScale[qi] = br:read(nb)
end
local nbms = br:read(9) + 1
local bms: { { number } } = {}
for m = 1, nbms do
local mat = table.create(64, 0)
for ci = 1, 64 do
mat[ci] = br:read(8)
end
bms[m] = mat
end
if br.err then
return nil, "truncated setup header"
end
-- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based)
local ranges: { { sizes: { number }, idx: { number } } } = {}
local mb = ilog(nbms - 1)
for i = 0, 5 do
local qti, pli = i // 3, i % 3
local copy = false
if i > 0 and br:read(1) == 0 then
copy = true
local from = i - 1
if qti > 0 and br:read(1) == 1 then
from = pli -- the same plane of the intra set
end
ranges[i + 1] = ranges[from + 1]
end
if not copy then
local sizes, idx = {}, { br:read(mb) }
local qi = 0
while qi < 63 do
local s = br:read(ilog(62 - qi)) + 1
table.insert(sizes, s)
qi += s
table.insert(idx, br:read(mb))
end
if qi > 63 then
return nil, "bad quant ranges"
end
for _, m in idx do
if m >= nbms then
return nil, "bad base matrix index"
end
end
ranges[i + 1] = { sizes = sizes, idx = idx }
end
end
if br.err then
return nil, "truncated setup header"
end
-- the dequantisation tables (oc_dequant_tables_init)
local dequant = buffer.create(64 * 6 * 64 * 2)
local base = table.create(64, 0)
for qti = 0, 1 do
for pli = 0, 2 do
local r = ranges[qti * 3 + pli + 1]
local qi = 0
for qri = 0, #r.sizes do
local m0 = bms[r.idx[qri + 1] + 1]
table.move(m0, 1, 64, 1, base)
local qiStart = qi
local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1]
while true do
local o = ((qi * 3 + pli) * 2 + qti) * 64
local q = (dcScale[qi + 1] * base[1] // 100) * 4
buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096))
for zzi = 1, 63 do
q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4
buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096))
end
qi += 1
if qi >= qiEnd then
break
end
-- interpolate the next base matrix
local m1 = bms[r.idx[qri + 2] + 1]
local sz = r.sizes[qri + 1]
for ci = 1, 64 do
base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz)
end
end
end
end
end
-- the 80 Huffman trees
local huff: { number } = {}
local roots: { number } = {}
for t = 1, 80 do
local k0, k1, tk = readTree(br)
if not k0 or not k1 or not tk then
return nil, "bad Huffman tree " .. (t - 1)
end
roots[t] = buildTable(huff, k0, k1, tk)
end
return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil
end
return H
+289
View File
@@ -0,0 +1,289 @@
--!strict
-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau
-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames).
-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV
-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes,
-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau);
-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout).
-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too).
--
-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate
-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err
-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region
-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down
-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position
--
-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture).
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Header = require("@formats/codecs/video/Theora/Header")
local Decoder = require("@formats/codecs/video/Theora/Decoder")
local Theora = {}
export type Info = Header.Info
export type Options = {
maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304)
}
local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" }
-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil
function Theora.isHeader(b: buffer, off: number?, len: number?): number?
local o = off or 0
local n = len or (buffer.len(b) - o)
if n < 7 then
return nil
end
local t = buffer.readu8(b, o)
if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then
return t - 0x7F
end
return nil
end
-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil)
function Theora.splitConfig(c: buffer): { buffer }?
local n = buffer.len(c)
if n < 3 or buffer.readu8(c, 0) ~= 2 then
return nil
end
local p, lens = 1, {}
for k = 1, 2 do
local size = 0
repeat
if p >= n then
return nil
end
local b = buffer.readu8(c, p)
size += b
p += 1
until b < 255
lens[k] = size
end
lens[3] = n - p - lens[1] - lens[2]
if lens[3] < 0 then
return nil
end
local out = {}
for k = 1, 3 do
out[k] = buffer.create(lens[k])
buffer.copy(out[k], 0, c, p, lens[k])
p += lens[k]
end
return out
end
-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err
function Theora.info(h: buffer): (Header.Info?, Err.Err?)
local ok, info, err = pcall(Header.info, h, 0, buffer.len(h))
if not ok or not info then
return nil, Err.from(if ok then err else tostring(info))
end
return info, nil
end
-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err
function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?)
local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h))
if not ok or not vendor or not list then
return nil, nil, nil, Err.from(if ok then err else tostring(vendor))
end
return vendor, list, (VorbisComment.tags(list)), nil
end
-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none)
function Theora.granuleFrame(info: Header.Info, g: number): number
if g < 0 then
return -1
end
local shift = 2 ^ info.granuleShift
local key = g // shift
local f = key + g % shift
-- since bitstream 3.2.1 the first frame is granule 1
local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub
if v >= 0x030201 then
f -= 1
end
return f
end
-- ------------------------------------------------------------------------------------------------ decoder
local Dec = {}
Dec.__index = Dec
export type TheoraDecoder = typeof(setmetatable(
{} :: {
info: Header.Info,
vendor: string,
comments: { string },
tags: { [string]: string },
width: number, -- the picture region
height: number,
frameRate: number,
pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p"
aspect: number, -- pixel aspect ratio (1 when unknown)
frames: number, -- packets decoded (dupes included)
_st: Decoder.State,
_any: boolean, -- a frame was decoded
},
Dec
))
-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config
function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?)
local list: { buffer }? = nil
if type(headers) == "buffer" then
list = Theora.splitConfig(headers)
elseif type(headers) == "table" then
list = headers
end
if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then
return nil, Err.new(Err.CORRUPT, "missing Theora headers")
end
local info, ierr = Theora.info(list[1])
if not info then
return nil, ierr
end
local maxPixels = opts and opts.maxPixels or 4096 * 2304
if info.frameWidth * info.frameHeight > maxPixels then
return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels")
end
local vendor, comments, tags, cerr = Theora.comment(list[2])
if not vendor or not comments or not tags then
return nil, cerr
end
local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3]))
if not ok3 or not setup then
return nil, Err.from(if ok3 then serr else tostring(setup))
end
local st = Decoder.new(info, setup)
return setmetatable({
info = info,
vendor = vendor,
comments = comments,
tags = tags,
width = info.picWidth,
height = info.picHeight,
frameRate = info.fpsNum / info.fpsDen,
pixelFormat = PIXEL_FORMATS[info.pixelFormat],
aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1,
frames = 0,
_st = st,
_any = false,
}, Dec), nil
end
-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil).
function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?)
local o = off or 0
local n = len or (buffer.len(data) - o)
if o < 0 or n < 0 or o + n > buffer.len(data) then
return nil, Err.new(Err.ARG, "decode: range outside the buffer")
end
if n > 0 and buffer.readu8(data, o) >= 0x80 then
return nil, nil
end
local kind, msg = Decoder.decode(self._st, data, o, n)
if not kind then
return nil, Err.from(msg)
end
self.frames += 1
if kind ~= "dup" then
self._any = true
end
return kind, nil
end
-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data)
function Dec.reset(self: TheoraDecoder)
local st = self._st
st.shown = st.prev
end
local function window(self: TheoraDecoder): (number, number, number, number)
local info = self.info
-- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom)
return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight
end
-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width,
-- chroma height
function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number)
local st = self._st
local x0, y0, w, h = window(self)
local hd, vd = st.hdec, st.vdec
local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd
local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd
cw = math.min(cw, st.pw[2] - cx0)
ch = math.min(ch, st.ph[2] - cy0)
return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch
end
-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down)
function Dec.image(self: TheoraDecoder): Types.Image
local y, u, v, cw, ch = self:planes()
local w, h = self.width, self.height
local img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
local ow, oh = (w + 1) // 2, (h + 1) // 2
buffer.copy(px, 0, y, 0, w * h)
local st = self._st
if st.hdec == 1 and st.vdec == 1 then
for r = 0, oh - 1 do
local sr = math.min(r, ch - 1)
buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw))
buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw))
end
else
Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh)
Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh)
end
img.meta.yuv = { range = "limited", matrix = "bt601" }
img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace }
return img
end
-- ------------------------------------------------------------------------------------------------ registry
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config
-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat
function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
if not track.config then
return nil, Err.new(Err.CORRUPT, "Theora track without its headers")
end
local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels })
if not dec then
return nil, err
end
local d = dec :: TheoraDecoder
local pending: { any } = {}
local self: any = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local kind, e = d:decode(packet.data)
if not kind then
return e
end
if d._any then
table.insert(pending, { d:image(), packet.pts, kind == "key" })
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local p = table.remove(pending, 1)
if not p then
return nil, nil, nil
end
return p[1], p[2], p[3]
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(pending)
d:reset()
end
return self, nil
end
return Theora
+28 -48
View File
@@ -240,51 +240,10 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
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/video/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, nil, 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
-- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display
local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Mpeg2 = require("@formats/codecs/video/Mpeg2")
return Mpeg2.newVideoDecoder(track, opts)
end
-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264);
@@ -294,21 +253,42 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec
return H264.newVideoDecoder(track, opts)
end
-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv
-- builds the same); one picture per packet, empty packets repeat the previous one
local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Theora = require("@formats/codecs/video/Theora")
return Theora.newVideoDecoder(track, opts)
end
-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy)
local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?)
return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
return require("@formats/codecs/video/Legacy").newDecoder(id, track, opts)
end
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 = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg2Decoder },
{ 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 = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder },
{ 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 = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
-- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette)
{ id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") },
{ id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") },
{ id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") },
{ id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") },
{ id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") },
{ id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") },
}
local byId: { [string]: Entry } = {}
+47
View File
@@ -9,6 +9,7 @@
-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf
-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute
-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish()
-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW)
--
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
local Err = require("@formats/core/Err")
@@ -520,4 +521,50 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ BITMAPINFO
export type BitmapInfo = {
width: number,
height: number, -- signed: > 0 = bottom-up rows
bits: number, -- biBitCount
compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB)
palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0
extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none
}
-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) |
-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries;
-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it.
function Avi.bitmapInfo(f: buffer): BitmapInfo?
local n = buffer.len(f)
if n < 40 then
return nil
end
local bits = readu16(f, 14)
local info: BitmapInfo = {
width = buffer.readi32(f, 4),
height = buffer.readi32(f, 8),
bits = bits,
compression = readstring(f, 16, 4),
}
if n > 40 then
local e = buffer.create(n - 40)
buffer.copy(e, 0, f, 40)
info.extra = e
if bits >= 1 and bits <= 8 then
local count = math.min(2 ^ bits, (n - 40) // 4)
local at = n - count * 4
if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then
at -= 9
end
local pal = buffer.create(1024)
for i = 0, count - 1 do
local o = at + i * 4
buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000)
end
info.palette = pal
end
end
return info
end
return Avi
+14
View File
@@ -8,9 +8,14 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local QtPalette = require("@formats/containers/IsoBmff/QtPalette")
local readstring = buffer.readstring
local function readu16be(b: buffer, o: number): number
return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
end
local Demux = {}
export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty)
@@ -33,6 +38,8 @@ export type Track = {
channels: number?,
bitsPerSample: number?,
config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...)
bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...)
palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF)
objectType: number?, -- esds objectTypeIndication
pcm: { bits: number, float: boolean, little: boolean }?,
entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...)
@@ -194,6 +201,13 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
t.height = r:u16be()
r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2)
childStart = r.pos
-- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...)
local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ)
t.bitsPerPixel = depth
t.palette = pal
if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then
childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8)
end
else
childStart = r.pos
end
@@ -0,0 +1,120 @@
--!strict
-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime
-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0).
-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1,
-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey
-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the
-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps).
--
-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec)
-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil
--
-- Never throws.
local readu8, writeu32 = buffer.readu8, buffer.writeu32
local function readu16(b: buffer, o: number): number -- big-endian
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function readu32(b: buffer, o: number): number
return readu16(b, o) * 65536 + readu16(b, o + 2)
end
local QtPalette = {}
local function rgb(r: number, g: number, b: number): number
return r + g * 256 + b * 65536 + 0xFF000000
end
-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette)
local SMALL: { [number]: { number } } = {
[1] = { 0xFFFFFF, 0x000000 },
[2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 },
[4] = {
0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA,
0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000,
},
}
local function defaultTable(bits: number): buffer
local pal = buffer.create(1024)
local small = SMALL[bits]
if small then
for i, c in small do
writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256))
end
return pal
end
local i = 0
for r = 5, 0, -1 do
for g = 5, 0, -1 do
for b = 5, 0, -1 do
if i < 215 then
writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51))
end
i += 1
end
end
end
-- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black
local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 }
i = 215
for ch = 0, 3 do
for _, v in RAMP do
local r = if ch == 0 or ch == 3 then v else 0
local g = if ch == 1 or ch == 3 then v else 0
local b = if ch == 2 or ch == 3 then v else 0
writeu32(pal, i * 4, rgb(r, g, b))
i += 1
end
end
writeu32(pal, 255 * 4, rgb(0, 0, 0))
return pal
end
-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size
-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it.
function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?)
if start + 86 > stop or stop > buffer.len(b) then
return nil, nil
end
local raw = readu16(b, start + 82)
local id = readu16(b, start + 84)
local bits = raw % 32
local grey = raw >= 32 and (raw // 32) % 2 == 1
if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then
return raw, nil
end
if grey and codec == "cinepak" then
return raw, nil
end
if grey and bits > 1 and id ~= 0 then
local pal = buffer.create(1024)
local count = 2 ^ bits
local step = 256 // (count - 1)
local v = 255
for i = 0, count - 1 do
writeu32(pal, i * 4, rgb(v, v, v))
v = math.max(0, v - step)
end
return bits, pal
elseif id ~= 0 then
return bits, defaultTable(bits)
end
local pal = buffer.create(1024)
if start + 94 <= stop then
local first = readu32(b, start + 86)
local last = readu16(b, start + 92)
if first <= 255 and last <= 255 then
for i = first, last do
local o = start + 94 + (i - first) * 8
if o + 8 > stop then
break
end
writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6)))
end
end
end
return bits, pal
end
return QtPalette
+31 -3
View File
@@ -35,6 +35,8 @@ export type Picture = {
temporal: number, -- temporal_reference
gop: boolean, -- a GOP header precedes the picture
sequence: boolean, -- a sequence header precedes the picture
structure: number, -- MPEG-2 picture_structure: 1 top field, 2 bottom field, 3 frame (MPEG-1: 3)
fields: number?, -- 2: a frame coded as two field pictures (both in this unit)
}
export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean }
@@ -77,8 +79,30 @@ function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, num
return 0, 0
end
-- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture
-- coding extension (3 = frame when there is none: MPEG-1)
function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number
local q = MpegEs.findStart(b, p + 4, limit)
local count = 0
while q and count < 8 do
count += 1
local code = if q + 6 < limit then readu8(b, q + 3) else -1
if code == 0xB5 then
if readu8(b, q + 4) // 16 == 8 then
local st = readu8(b, q + 6) % 4
return if st == 0 then 3 else st
end
elseif code ~= 0xB2 then
break
end
q = MpegEs.findStart(b, q + 4, limit)
end
return 3
end
-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its
-- sequence / GOP header when one precedes it and runs to the next unit's start
-- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures
-- is one unit (fields = 2)
function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
local out: { Picture } = {}
local unitStart: number? = nil
@@ -87,7 +111,11 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
local p = MpegEs.findStart(b, off, limit)
while p do
local code = if p + 3 < limit then readu8(b, p + 3) else -1
if code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then
local st = if code == 0x00 then MpegEs.pictureStructure(b, p, limit) else 3
if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then
-- the second field of the current frame: same unit
cur.fields = 2
elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then
-- a sequence / GOP header or a picture after a picture closes it
if cur and (code ~= 0xB7) then
cur.size = p - cur.offset
@@ -106,7 +134,7 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
local x = readu8(b, p + 4) * 256 + readu8(b, p + 5)
t, tr = (x // 8) % 8, x // 64
end
cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq }
cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture
unitStart, seq, gop = nil, false, false
elseif code == 0xB7 and cur then
cur.size = p + 4 - cur.offset
+349
View File
@@ -2,7 +2,12 @@
-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the
-- standard types to engine objects:
-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first)
-- host.meshPages(prim, opts?) -> { MeshPage } a triangle Primitive split into pages that fit one EditableMesh
-- host.pageData(prim, page, opts?) -> PageData a page's vertices as flat arrays (scaled, centred, sRGB colours)
-- host.toEditableMesh(prim, page?, opts?) -> EditableMesh, centre one page as an EditableMesh
-- meshPages / pageData are pure (no engine calls: tests/host/roblox.luau runs them on every runtime).
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Host = {}
Host.name = "roblox"
@@ -37,4 +42,348 @@ function Host.toEditableImage(img: any): (any, Err.Err?)
return ei
end
-- ---------------------------------------------------------------------------------------------------------- meshes
-- A triangle Primitive (F.ops.mesh.merge gives one in world space) becomes EditableMeshes page by page. One
-- EditableMesh holds at most ~20k triangles and 60k vertices (measured in Studio: surfacenet-luau MeshOut), and a client
-- has only 8 growable ones at a time: build a page, turn it into what you keep (a MeshPart, a FixedSize copy through
-- AssetService:CreateEditableMeshAsync), destroy it, then build the next.
--
-- local prims = F.ops.mesh.merge(scene, { byMaterial = true })
-- for _, prim in prims do
-- for _, page in assert(F.host.meshPages(prim)) do
-- local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs
-- local part = AssetService:CreateMeshPartAsync(Content.fromObject(em))
-- part.Position = Vector3.new(centre[1], centre[2], centre[3])
-- end
-- end
--
-- Axes: Roblox is right-handed, y up, like glTF: z-up sources (STL, VOX, CAD) go through F.ops.mesh.setUp(scene, "y")
-- before merging. Winding: counter-clockwise front faces, as glTF. UVs keep the glTF top-left origin (opts.flipV
-- turns them over). Colours: COLOR_0 is linear (glTF); EditableMesh colours are sRGB, so they are converted.
export type MeshPage = {
first: number, -- the first triangle (0-based) of the primitive in this page
count: number, -- triangles
vertices: { number }, -- local vertex i (1-based) = source vertex vertices[i] (0-based)
corners: buffer, -- u32 local vertex (0-based) per corner, 3 per triangle
min: { number }, -- bounds of the page's positions (source units)
max: { number },
}
export type PageData = {
vertexCount: number,
triangleCount: number,
positions: { number }, -- x, y, z per vertex: (source - origin) * scale
normals: { number }?, -- x, y, z per vertex (unit; NORMAL scaled by the inverse scale)
uvs: { number }?, -- u, v per vertex (TEXCOORD_<opts.texCoord or 0>)
colors: { number }?, -- r, g, b, a per vertex, sRGB 0..1 (from linear COLOR_0)
corners: buffer, -- as MeshPage.corners
centre: { number }, -- origin * scale: where the page's local (0, 0, 0) sits
}
export type MeshOptions = {
maxTriangles: number?, -- per page, default 20000
maxVertices: number?, -- per page, default 60000
doubleSided: boolean?, -- toEditableMesh adds a back face per triangle (meshPages counts them), default false
scale: (number | { number })?, -- uniform or per axis, default 1
origin: { number }?, -- subtracted before scaling, default the page's bounds centre
texCoord: number?, -- the TEXCOORD_n set for uvs, default 0
flipV: boolean?, -- v = 1 - v, default false
normals: boolean?, -- NORMAL when present, default true
uvs: boolean?, -- default true
colors: boolean?, -- COLOR_0 when present, default true
editableMesh: any?, -- toEditableMesh appends to this mesh instead of creating one
yield: (() -> ())?, -- toEditableMesh calls it every yieldEvery triangles (e.g. a frame budget check)
yieldEvery: number?, -- default 2000
}
-- the index of each corner (0-based vertex numbers) or nil, Err
local function cornerReader(prim: any): ((number) -> number)?
local idx = prim.indices
if not idx then
return function(i: number): number
return i
end
end
local get = Types.Scene.reader(idx)
if not get then
return nil
end
return function(i: number): number
return (get :: any)(i, 0)
end
end
local function checkPrim(prim: any): (number, Err.Err?)
if type(prim) ~= "table" or type(prim.attributes) ~= "table" or type(prim.attributes.POSITION) ~= "table" then
return 0, Err.new(Err.ARG, "expected a Primitive with POSITION")
end
if (prim.mode or "triangles") ~= "triangles" then
return 0, Err.new(Err.ARG, "needs a triangle primitive (F.ops.mesh.merge or triangulate first), got " .. tostring(prim.mode))
end
local n = if prim.indices then prim.indices.count else prim.attributes.POSITION.count
return n // 3, nil
end
-- meshPages(prim, opts?) -> { MeshPage } | nil, Err: consecutive triangle runs, each within maxTriangles (back faces
-- counted when doubleSided) and maxVertices.
function Host.meshPages(prim: any, opts: MeshOptions?): ({ MeshPage }?, Err.Err?)
local tris, err = checkPrim(prim)
if err then
return nil, err
end
local o: MeshOptions = opts or {}
local per = if o.doubleSided then 2 else 1
local maxT = math.max(1, (o.maxTriangles or 20000) // per)
local maxV = math.max(3, o.maxVertices or 60000)
local pos = prim.attributes.POSITION
local getP = Types.Scene.reader(pos)
local corner = cornerReader(prim)
if not getP or not corner then
return nil, Err.new(Err.ARG, "unsupported accessor type")
end
local nv = pos.count
local pages: { MeshPage } = {}
local t = 0
while t < tris do
local map: { [number]: number } = {}
local verts: { number } = {}
local first = t
local lo = { math.huge, math.huge, math.huge }
local hi = { -math.huge, -math.huge, -math.huge }
local cs: { number } = {}
while t < tris and t - first < maxT do
local a, b, c = corner(t * 3), corner(t * 3 + 1), corner(t * 3 + 2)
if a >= nv or b >= nv or c >= nv or a < 0 or b < 0 or c < 0 then
return nil, Err.new(Err.ARG, string.format("triangle %d: vertex index out of range", t))
end
local fresh = (if map[a] then 0 else 1) + (if map[b] or b == a then 0 else 1) + (if map[c] or c == a or c == b then 0 else 1)
if #verts + fresh > maxV and t > first then
break
end
for _, v in { a, b, c } do
local l = map[v]
if not l then
l = #verts
verts[l + 1] = v
map[v] = l
for k = 1, 3 do
local x = (getP :: any)(v, k - 1)
if x < lo[k] then
lo[k] = x
end
if x > hi[k] then
hi[k] = x
end
end
end
cs[#cs + 1] = l
end
t += 1
end
local corners = buffer.create(#cs * 4)
for i, l in cs do
buffer.writeu32(corners, (i - 1) * 4, l)
end
pages[#pages + 1] = { first = first, count = t - first, vertices = verts, corners = corners, min = lo, max = hi }
end
return pages, nil
end
local function toSrgb(c: number): number
c = math.clamp(c, 0, 1)
return if c <= 0.0031308 then c * 12.92 else 1.055 * c ^ (1 / 2.4) - 0.055
end
-- pageData(prim, page, opts?) -> PageData | nil, Err: the page's vertex attributes as flat number arrays, ready for
-- engine calls (positions relative to the origin and scaled, unit normals, uvs, sRGB colours).
function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData?, Err.Err?)
local _, err = checkPrim(prim)
if err then
return nil, err
end
if type(page) ~= "table" or type(page.vertices) ~= "table" or type(page.corners) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected a MeshPage from meshPages")
end
local o: MeshOptions = opts or {}
local sc = o.scale or 1
local sx, sy, sz
if type(sc) == "table" then
sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1
else
sx, sy, sz = sc, sc, sc
end
local origin = o.origin
or { (page.min[1] + page.max[1]) / 2, (page.min[2] + page.max[2]) / 2, (page.min[3] + page.max[3]) / 2 }
local attrs = prim.attributes
local getP = Types.Scene.reader(attrs.POSITION)
local getN = if o.normals ~= false and attrs.NORMAL then Types.Scene.reader(attrs.NORMAL) else nil
local uvAcc = if o.uvs ~= false then attrs["TEXCOORD_" .. tostring(o.texCoord or 0)] else nil
local getT = if uvAcc then Types.Scene.reader(uvAcc) else nil
local colAcc = if o.colors ~= false then attrs.COLOR_0 else nil
local getC = if colAcc then Types.Scene.reader(colAcc) else nil
if not getP then
return nil, Err.new(Err.ARG, "unsupported POSITION accessor type")
end
local n = #page.vertices
local positions = table.create(n * 3, 0)
local normals = if getN then table.create(n * 3, 0) else nil
local uvs = if getT then table.create(n * 2, 0) else nil
local colors = if getC then table.create(n * 4, 1) else nil
local ox, oy, oz = origin[1], origin[2], origin[3]
local flip = o.flipV == true
local alpha = colAcc and colAcc.components >= 4
for i, v in page.vertices do
local j = (i - 1) * 3
positions[j + 1] = ((getP :: any)(v, 0) - ox) * sx
positions[j + 2] = ((getP :: any)(v, 1) - oy) * sy
positions[j + 3] = ((getP :: any)(v, 2) - oz) * sz
if normals then
-- normals of a scaled mesh scale by the inverse
local x, y, z = (getN :: any)(v, 0) / sx, (getN :: any)(v, 1) / sy, (getN :: any)(v, 2) / sz
local len = math.sqrt(x * x + y * y + z * z)
if len > 0 then
x, y, z = x / len, y / len, z / len
else
x, y, z = 0, 1, 0
end
normals[j + 1], normals[j + 2], normals[j + 3] = x, y, z
end
if uvs then
local u, w = (getT :: any)(v, 0), (getT :: any)(v, 1)
uvs[(i - 1) * 2 + 1] = u
uvs[(i - 1) * 2 + 2] = if flip then 1 - w else w
end
if colors then
local k = (i - 1) * 4
colors[k + 1] = toSrgb((getC :: any)(v, 0))
colors[k + 2] = toSrgb((getC :: any)(v, 1))
colors[k + 3] = toSrgb((getC :: any)(v, 2))
colors[k + 4] = if alpha then math.clamp((getC :: any)(v, 3), 0, 1) else 1
end
end
return {
vertexCount = n,
triangleCount = page.count,
positions = positions,
normals = normals,
uvs = uvs,
colors = colors,
corners = page.corners,
centre = { ox * sx, oy * sy, oz * sz },
}, nil
end
-- toEditableMesh(prim, page?, opts?) -> EditableMesh, centre { x, y, z } | nil, Err. Without a page the whole
-- primitive must fit one (else Err.LIMIT: use meshPages). Positions are relative to the centre (place the MeshPart
-- there). Engine errors (no free EditableMesh, limits) come back as Err.IO; a mesh this call created is destroyed then.
function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (any, any)
local o: MeshOptions = opts or {}
local pg = page
if not pg then
local pages, err = Host.meshPages(prim, o)
if not pages then
return nil, err
end
if #pages ~= 1 then
return nil, Err.new(Err.LIMIT, string.format("toEditableMesh: %d pages: split with meshPages", #pages))
end
pg = pages[1]
end
local data, err = Host.pageData(prim, pg :: MeshPage, o)
if not data then
return nil, err
end
local d = data :: PageData
local em = o.editableMesh
local own = em == nil
if own then
local AssetService = (game :: any):GetService("AssetService")
local ok, made = pcall(function()
return AssetService:CreateEditableMesh()
end)
if not ok or not made then
return nil, Err.new(Err.IO, "CreateEditableMesh failed (a client has 8 growable EditableMeshes): " .. tostring(made))
end
em = made
end
local ok, perr = pcall(function()
local P, N, U, C = d.positions, d.normals, d.uvs, d.colors
local vids = table.create(d.vertexCount, 0)
local nids = if N then table.create(d.vertexCount, 0) else nil
local bids = if N and o.doubleSided then table.create(d.vertexCount, 0) else nil
local uids = if U then table.create(d.vertexCount, 0) else nil
local cids = if C then table.create(d.vertexCount, 0) else nil
local palette: { [string]: number } = {}
for i = 1, d.vertexCount do
local j = (i - 1) * 3
vids[i] = em:AddVertex(Vector3.new(P[j + 1], P[j + 2], P[j + 3]))
if N and nids then
local n = Vector3.new(N[j + 1], N[j + 2], N[j + 3])
nids[i] = em:AddNormal(n)
if bids then
bids[i] = em:AddNormal(-n)
end
end
if U and uids then
uids[i] = em:AddUV(Vector2.new(U[(i - 1) * 2 + 1], U[(i - 1) * 2 + 2]))
end
if C and cids then
local k = (i - 1) * 4
local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4]
-- equal colours share one id (voxel palettes, flat-coloured models)
local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5))
local id = palette[key]
if not id then
id = em:AddColor(Color3.new(r, g, b), a)
palette[key] = id
end
cids[i] = id
end
end
local corners = d.corners
local every = o.yieldEvery or 2000
local yield = o.yield
for t = 0, d.triangleCount - 1 do
local a = buffer.readu32(corners, t * 12) + 1
local b = buffer.readu32(corners, t * 12 + 4) + 1
local c = buffer.readu32(corners, t * 12 + 8) + 1
local f = em:AddTriangle(vids[a], vids[b], vids[c])
if nids then
em:SetFaceNormals(f, { nids[a], nids[b], nids[c] })
end
if uids then
em:SetFaceUVs(f, { uids[a], uids[b], uids[c] })
end
if cids then
em:SetFaceColors(f, { cids[a], cids[b], cids[c] })
end
if o.doubleSided then
local g = em:AddTriangle(vids[a], vids[c], vids[b])
if bids then
em:SetFaceNormals(g, { bids[a], bids[c], bids[b] })
end
if uids then
em:SetFaceUVs(g, { uids[a], uids[c], uids[b] })
end
if cids then
em:SetFaceColors(g, { cids[a], cids[c], cids[b] })
end
end
if yield and (t + 1) % every == 0 then
yield()
end
end
end)
if not ok then
if own then
pcall(function()
em:Destroy()
end)
end
return nil, Err.new(Err.IO, "EditableMesh: " .. tostring(perr))
end
return em, d.centre
end
return Host
+5 -1
View File
@@ -25,7 +25,7 @@ local AviFormat = {
extensions = { "avi" },
mime = { "video/x-msvideo", "video/avi" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -110,6 +110,10 @@ local function videoTrack(s: Avi.Stream, id: number): Types.Track
t.pixelFormat = "yuv420p"
end
end
local bi = Avi.bitmapInfo(f)
if bi and bi.palette then
t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...)
end
local size = buffer.readu32(f, 0)
if size > 40 and buffer.len(f) > 40 then
local c = buffer.create(buffer.len(f) - 40)
+157
View File
@@ -0,0 +1,157 @@
--!strict
-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in formats-luau, written from the FLIC
-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC").
-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24:
-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped,
-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8
-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the
-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer.
-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
-- ------------------------------------------------------------------------------------------------ contract
local Fli = {
name = "fli",
category = "video",
extensions = { "fli", "flc", "flx" },
mime = { "video/x-fli", "video/fli", "video/x-flc" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- (frames are rgba8 already)
maxPixels: number?, -- default 2^26
ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does)
}
-- ------------------------------------------------------------------------------------------------ constants
local HEADER = 128
local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44
local FRAME, FRAME2 = 0xF1FA, 0xF5FA
-- ------------------------------------------------------------------------------------------------ sniff
function Fli.sniff(r: Bytes.Reader): number
local s = r:peek(18)
if #s < 18 then
return 0
end
local magic = string.byte(s, 5) + string.byte(s, 6) * 256
if magic ~= FLI and magic ~= FLC and magic ~= DTA then
return 0
end
local w = string.byte(s, 9) + string.byte(s, 10) * 256
local h = string.byte(s, 11) + string.byte(s, 12) * 256
if w > 4096 or h > 4096 then
return 0
end
return 0.9
end
-- ------------------------------------------------------------------------------------------------ decode
-- demux(r, opts?) -> the Demuxer | nil, Err
function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
local n = limit - base
if n < HEADER then
return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header")
end
local hr = Bytes.reader(b, base, HEADER)
hr:skip(4)
local magic = hr:u16le()
local frames = hr:u16le()
local w, h = hr:u16le(), hr:u16le()
local depth = hr:u16le()
hr:skip(2)
local speed = hr:u32le()
if hr.err then
return nil, hr.err
end
if magic ~= FLI and magic ~= FLC and magic ~= DTA then
return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4)
end
if magic == FLI then
speed = speed % 65536
end
if w == 0 or h == 0 then
return nil, Err.new(Err.CORRUPT, "no picture size")
end
local max = (opts and opts.maxPixels) or 2 ^ 26
if w * h > max then
return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels")
end
if magic == FLI or depth == 0 then
depth = 8
elseif magic == FLC and depth == 16 then
depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels
end
if speed == 0 then
speed = 5
end
local scale = if magic == FLI then 70 else 1000
local track: Types.Track = {
id = 1,
kind = "video",
codec = "flic",
codecTag = string.format("0x%04X", magic),
timescale = scale,
width = w,
height = h,
frameRate = scale / speed,
default = true,
bitsPerPixel = depth,
}
-- the frame chunks
local offs, sizes = {}, {}
local p = base + HEADER
while p + 6 <= limit do
local size = buffer.readu32(b, p)
local cm = buffer.readu16(b, p + 4)
if size < 6 then
break
end
if (cm == FRAME or cm == FRAME2) and size > 6 then
if p + size > limit then
break -- a truncated last frame
end
table.insert(offs, p)
table.insert(sizes, size)
end
p += size
end
local count = #offs
if frames > 0 and count > frames and not (opts and opts.ringFrame) then
count = frames -- the ring frame is not a frame of the animation
end
local dmx = Demux.new("fli", { track }, b, {
type = magic,
frames = frames,
depth = depth,
speed = speed,
ringFrame = #offs > frames and frames > 0,
})
for i = 1, count do
dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i])
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Fli.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts :: Video.OpenOptions?)
end
return Fli
+39
View File
@@ -9,6 +9,8 @@ local Types = require("@formats/Types")
local Ebml = require("@formats/containers/Ebml")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
local Avi = require("@formats/containers/Avi")
local QtPalette = require("@formats/containers/IsoBmff/QtPalette")
local Deflate = require("@formats/codecs/compress/Deflate")
local Parse = {}
@@ -152,6 +154,39 @@ local function codecFor(id: string, kind: string, bits: number?): string
end
Parse.codecFor = codecFor
-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample
-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata
local function vfwOrQuickTime(t: any, codecId: string, priv: buffer)
local n = buffer.len(priv)
if codecId == "V_MS/VFW/FOURCC" then
local bi = Avi.bitmapInfo(priv)
if bi then
t.codec = Video.fromFourcc(bi.compression) or t.codec
t.codecTag = bi.compression
t.bitsPerPixel = bi.bits
t.palette = bi.palette
t.config = bi.extra
end
elseif codecId == "V_QUICKTIME" and n >= 21 then
local desc = priv
if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then
desc = buffer.create(n + 4)
local size = n + 4
buffer.writeu8(desc, 0, size // 16777216 % 256)
buffer.writeu8(desc, 1, size // 65536 % 256)
buffer.writeu8(desc, 2, size // 256 % 256)
buffer.writeu8(desc, 3, size % 256)
buffer.copy(desc, 4, priv, 0, n)
end
local fcc = buffer.readstring(desc, 4, 4)
t.codec = Video.fromFourcc(fcc) or t.codec
t.codecTag = fcc
local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec)
t.bitsPerPixel = depth
t.palette = pal
end
end
type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? }
local function parseVideo(buf: buffer, off: number, len: number, t: any)
@@ -278,6 +313,10 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe
t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data"
t.codecTag = codecId
t.codec = codecFor(codecId, t.kind, t.bitsPerSample)
local cfg: buffer? = t.config
if t.kind == "video" and cfg then
vfwOrQuickTime(t, codecId, cfg)
end
if t.kind == "audio" then
t.sampleRate = t.sampleRate or 8000
t.channels = t.channels or 1
+2 -2
View File
@@ -27,8 +27,8 @@ local Mkv = {
category = "video",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true },
}
-- ------------------------------------------------------------------------------------------------ types
+3 -1
View File
@@ -30,7 +30,7 @@ local Mp4 = {
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -133,6 +133,8 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
bitsPerSample = it.bitsPerSample,
config = it.config,
default = true,
bitsPerPixel = it.bitsPerPixel,
palette = it.palette,
}
if it.kind == "video" then
if not Video.entry(t.codec) then
+6 -5
View File
@@ -1,10 +1,11 @@
--!strict
-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg /
-- .vob / VCD .dat). New in formats-luau, on containers/MpegPs. Video PES payloads are joined into the elementary
-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a
-- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references.
-- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1
-- video through the codecs/video/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook.
-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both
-- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get
-- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM).
-- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its
-- sequence extension), audio through the api's opts.openAudio hook.
-- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets.
-- ------------------------------------------------------------------------------------------------ requires
@@ -23,7 +24,7 @@ local Ps = {
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
mime = { "video/mpeg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true },
}
-- ------------------------------------------------------------------------------------------------ types
+4 -3
View File
@@ -2,8 +2,9 @@
-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs,
-- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS
-- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as
-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/video/Video
-- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 /
-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the
-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id,
-- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 /
-- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units.
-- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams,
-- PES without PTS for video before the first one (dropped).
@@ -24,7 +25,7 @@ local Ts = {
extensions = { "ts", "m2ts", "mts", "tsv" },
mime = { "video/mp2t" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true },
}
-- ------------------------------------------------------------------------------------------------ types
+407
View File
@@ -0,0 +1,407 @@
--!strict
-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification,
-- RFC 3533 / 5334). New in formats-luau, on containers/Ogg and containers/Demux.
-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from
-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config,
-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis /
-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's
-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone.
-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied
-- (the audio pages come from containers/AudioWrap and are interleaved by time).
-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped),
-- encoding Theora (there is no encoder: other sources cannot be written).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Demux = require("@formats/containers/Demux")
local AudioWrap = require("@formats/containers/AudioWrap")
local Theora = require("@formats/codecs/video/Theora")
local Video = require("@formats/codecs/video/Video")
local Source = require("@formats/codecs/video/Video/Source")
-- ------------------------------------------------------------------------------------------------ contract
local Ogv = {
name = "ogv",
category = "video",
extensions = { "ogv", "ogg" },
mime = { "video/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
track: number?, -- the video track id to decode (default: the first video track)
audio: boolean?, -- false: do not open the audio track
maxPixels: number?,
verify: boolean?, -- false: skip the page CRC checks (default true)
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
}
export type EncodeOptions = {
audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped)
}
-- ------------------------------------------------------------------------------------------------ constants
local AUDIO = { vorbis = true, opus = true, flac = true }
-- ------------------------------------------------------------------------------------------------ sniff
-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain
-- Ogg Vorbis / Opus / FLAC files are left to the audio formats)
function Ogv.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "OggS" then
return 0
end
local b, p, lim = r.buf, r.pos, r.limit
for _ = 1, 8 do
if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then
return 0
end
local nseg = buffer.readu8(b, p + 26)
local d = p + 27 + nseg
if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then
return 1
end
if d > lim then
return 0
end
local size = 0
for i = 0, nseg - 1 do
size += buffer.readu8(b, p + 27 + i)
end
p = d + size
end
return 0
end
-- ------------------------------------------------------------------------------------------------ encode
-- the pages of an Ogg buffer: { offset, size, serial, granule, bos }
local function pages(b: buffer): { { number } }
local out = {}
local pos = 0
while true do
local p = Ogg.Page.find(b, pos, nil, false)
if not p then
break
end
table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 })
pos = p.offset + p.size
end
return out
end
-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv)
function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = opts or {}
local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } })
if not streams then
return nil, err
end
local vs: Source.Stream? = nil
local as: Source.Stream? = nil
for _, s in streams do
if s.kind == "video" and s.codec == "theora" and not vs then
vs = s
elseif s.kind == "audio" and s.copied and not as then
as = s
end
end
if not vs or not vs.config then
return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)")
end
local v = vs :: Source.Stream
local headers = Theora.splitConfig(v.config :: buffer)
local info = headers and Theora.info(headers[1])
if not headers or not info then
return nil, Err.new(Err.CORRUPT, "Theora track without its three headers")
end
local fps = info.fpsNum / info.fpsDen
local scale = 2 ^ info.granuleShift
local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0
-- video pages (serial 0x7468656F), granules from the frame numbers
local mux = Ogg.muxer({ pageSize = 4096 })
local s = mux:stream(0x7468656F)
s:packet(headers[1], 0, { flush = true })
s:packet(headers[2], 0)
s:packet(headers[3], 0, { flush = true })
local key = 0
local start = if #v.packets > 0 then v.packets[1].pts else 0
for i, p in v.packets do
local frame = math.floor((p.pts - start) * fps + 0.5)
if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then
key = frame + bias
end
s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets })
end
local video = mux:finish()
-- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time
local audio: buffer? = nil
local arate, askip = 1, 0
if as and o.audio ~= false then
local a = as :: Source.Stream
local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels }
local shim = {
count = function(_: any, _t: number): number
return #a.packets
end,
get = function(_: any, _t: number, k: number): any
local p = a.packets[k]
return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data }
end,
}
local buf, _, aerr = AudioWrap.wrap(shim, track)
if not buf and o.audio == true then
return nil, aerr
end
audio = buf
if a.codec == "opus" then
arate = 48000
local c = a.config
askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0
else
arate = a.sampleRate or 44100
end
elseif o.audio == true and not as then
return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus")
end
local vp = pages(video)
local ap = if audio then pages(audio) else {}
local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0))
local function put(b: buffer, pg: { number })
out:bytes(b, pg[1], pg[2])
end
-- bos pages first (video, then audio), then the other header pages, then data by time
put(video, vp[1])
if audio and ap[1] then
put(audio :: buffer, ap[1])
end
local vi, ai = 2, 2
local function headerPage(list: { { number } }, i: number): boolean
local pg = list[i]
return pg ~= nil and pg[3] == 0
end
while headerPage(vp, vi) do
put(video, vp[vi])
vi += 1
end
while audio and headerPage(ap, ai) do
put(audio :: buffer, ap[ai])
ai += 1
end
local vt, at = 0, 0
while vi <= #vp or ai <= #ap do
local nv, na = vp[vi], ap[ai]
if nv and nv[3] >= 0 then
vt = Theora.granuleFrame(info, nv[3]) / fps
end
if na and na[3] >= 0 then
at = (na[3] - askip) / arate
end
if nv and (not na or vt <= at) then
put(video, nv)
vi += 1
else
put(audio :: buffer, na)
ai += 1
end
end
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets
local function xiphLace(list: { buffer }): buffer
local w = Bytes.writer(64)
w:u8(#list - 1)
for i = 1, #list - 1 do
local n = buffer.len(list[i])
while n >= 255 do
w:u8(255)
n -= 255
end
w:u8(n)
end
for _, h in list do
w:bytes(h)
end
return w:finish()
end
type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean }
-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err
function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) })
if not ogg then
return nil, err
end
local src: buffer = ogg.buf
local tracks: { Types.Track } = {}
local all: { Pending } = {}
local meta: { [string]: any } = {}
local function add(track: number, pts: number, key: boolean, p: any)
table.insert(all, {
track = track,
pts = pts,
key = key,
page = p.pageOffset,
data = p.data,
off = p.offset,
len = p.size,
own = p.data ~= src,
})
end
for _, st in ogg:streams() do
local codec = st.codec
if codec ~= "theora" and not AUDIO[codec] then
continue
end
local rd = ogg:reader(st.serial)
local headers: { buffer } = {}
local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1
while #headers < nh do
local p = rd:nextPacket()
if not p then
break
end
table.insert(headers, Ogg.copy(p))
if codec == "flac" and #headers == 1 and p.size >= 9 then
nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256
if nh > 64 then
nh = 1
end
end
end
if #headers < nh then
continue
end
local id = #tracks + 1
local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial }
if codec == "theora" then
local info = Theora.info(headers[1])
if not info then
continue
end
track.kind = "video"
track.width, track.height = info.picWidth, info.picHeight
track.timescale = info.fpsNum
track.frameRate = info.fpsNum / info.fpsDen
track.config = xiphLace(headers)
local _, _, tags = Theora.comment(headers[2])
meta.tags = tags
-- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1
local packets = {}
local base: number? = nil
while true do
local p = rd:nextPacket()
if not p then
break
end
if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then
continue -- a stray header
end
table.insert(packets, p)
if base == nil and p.granule >= 0 then
base = Theora.granuleFrame(info, p.granule) - (#packets - 1)
end
end
local b0 = base or 0
for k, p in packets do
local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0
add(id, (b0 + k - 1) * info.fpsDen, key, p)
end
track.duration = (b0 + #packets) / track.frameRate
else
local h = headers[1]
local rate, channels, skip = 0, 0, 0
if codec == "vorbis" and buffer.len(h) >= 16 then
channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12)
track.config = xiphLace(headers)
elseif codec == "opus" and buffer.len(h) >= 19 then
channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10)
track.config = h
track.codecDelay = skip / 48000
elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then
local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field
rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16
channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1
local parts = { buffer.create(buffer.len(h) - 9) }
buffer.copy(parts[1], 0, h, 9)
for i = 2, #headers do
table.insert(parts, headers[i])
end
local total = 0
for _, x in parts do
total += buffer.len(x)
end
local cfg = buffer.create(total)
local o2 = 0
for _, x in parts do
buffer.copy(cfg, o2, x)
o2 += buffer.len(x)
end
track.config = cfg
end
if rate <= 0 or channels <= 0 then
continue
end
track.sampleRate, track.channels, track.timescale = rate, channels, rate
local last = 0
while true do
local p = rd:nextPacket()
if not p then
break
end
add(id, math.max(0, last - skip), true, p)
if p.granule >= 0 then
last = p.granule
end
end
track.duration = math.max(0, last - skip) / rate
end
table.insert(tracks, track)
end
if #tracks == 0 then
return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream")
end
-- the index in file order (by the page each packet ends on)
local order = table.create(#all, 0)
for i = 1, #all do
order[i] = i
end
table.sort(order, function(a: number, c: number): boolean
local pa, pc = all[a].page, all[c].page
if pa ~= pc then
return pa < pc
end
return a < c
end)
local dmx = Demux.new("ogv", tracks, src, meta)
for _, i in order do
local e = all[i]
if e.own then
dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data)
else
dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len)
end
end
dmx:finish()
return dmx, nil
end
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local ok, dmx, err = pcall(Ogv.demux, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
end
if not dmx then
return nil, err
end
return Video.open(dmx, opts :: Video.OpenOptions?)
end
return Ogv
+123
View File
@@ -0,0 +1,123 @@
--!strict
--!native
--!optimize 2
-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker
-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32),
-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/
-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per
-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 /
-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives
-- them. Never throws: trees are bounded and every read past the packet gives zero bits.
local Smacker = require("@formats/codecs/video/Legacy/Smacker")
local readu8, readi16 = buffer.readu8, buffer.readi16
local Audio = {}
-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message
function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string)
local n = buffer.len(d)
if not packed then
local bps = bits // 8
local frames = n // (bps * channels)
local count = frames * channels
local out = table.create(count, 0)
if bps == 1 then
for i = 0, count - 1 do
out[i + 1] = (readu8(d, i) - 128) / 128
end
else
for i = 0, count - 1 do
out[i + 1] = readi16(d, i * 2) / 32768
end
end
return frames, out
end
if n <= 4 then
return nil, "packet too small"
end
local size = buffer.readu32(d, 0)
if size > 2 ^ 24 then
return nil, "packet too big"
end
local br = Smacker.bits(d, 4, n - 4)
local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk
if bit(br) == 0 then
return 0, {} -- no data
end
local stereo = bit(br)
local wide = bit(br)
if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then
return nil, "packet does not match the track's format"
end
local bytes = wide + 1
local ch = stereo + 1
if size % (ch * bytes) ~= 0 then
return nil, "unpacked size is not a whole number of samples"
end
local trees: { { number } } = {}
for k = 1, 2 ^ (wide + stereo) do
bit(br)
local t, msg = Smacker.tree8(br)
if not t then
return nil, msg or "bad tree"
end
bit(br)
trees[k] = t
end
if br.nbits - br.pos < ch * bytes * 8 then
return nil, "truncated packet"
end
-- whether any tree needs bits (else every delta is a constant and no end check applies)
local coded = false
for _, t in trees do
if #t > 1 then
coded = true
end
end
local frames = size // (ch * bytes)
local total = frames * ch
local out = table.create(total, 0)
if wide == 1 then
local pred = { 0, 0 }
for c = ch, 1, -1 do
local v = read(br, 16)
pred[c] = (v // 256) + (v % 256) * 256
end
for c = 1, math.min(ch, total) do
local v = pred[c]
out[c] = (if v >= 32768 then v - 65536 else v) / 32768
end
for i = ch, total - 1 do
local c = if ch == 2 then i % 2 else 0
if coded and br.pos > br.nbits then
return nil, "truncated packet"
end
local lo = walk(trees[2 * c + 1], br)
local hi = walk(trees[2 * c + 2], br)
local v = (pred[c + 1] + lo + hi * 256) % 65536
pred[c + 1] = v
out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768
end
else
local pred = { 0, 0 }
for c = ch, 1, -1 do
pred[c] = read(br, 8)
end
for c = 1, math.min(ch, total) do
out[c] = (pred[c] - 128) / 128
end
for i = ch, total - 1 do
local c = if ch == 2 then i % 2 else 0
if br.pos > br.nbits then
return nil, "truncated packet"
end
local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256
pred[c + 1] = v
out[i + 1] = (v - 128) / 128
end
end
return frames, out
end
return Audio
+320
View File
@@ -0,0 +1,320 @@
--!strict
-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in formats-luau, written from the format description
-- (MultimediaWiki "Smacker").
-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio
-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette
-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open()
-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the
-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio
-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it
-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that
-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx,
-- track) the Decoder of any of its audio tracks.
-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
local Stream = require("@formats/codecs/audio/Stream")
local Audio = require("@formats/video/smk/Audio")
-- ------------------------------------------------------------------------------------------------ contract
local Smk = {
name = "smk",
category = "video",
extensions = { "smk" },
mime = { "video/vnd.radgamettools.smacker" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" },
caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- (frames are rgba8 already)
maxPixels: number?, -- default 2^26
audio: boolean?, -- false: do not open the audio track
ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does)
openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio)
}
-- ------------------------------------------------------------------------------------------------ constants
local HEADER = 104
local RING = 1
-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4)
local PAL6 = table.create(64, 0)
for i = 0, 63 do
PAL6[i + 1] = i * 4 + i // 16
end
-- ------------------------------------------------------------------------------------------------ sniff
function Smk.sniff(r: Bytes.Reader): number
local s = r:peek(4)
if s ~= "SMK2" and s ~= "SMK4" then
return 0
end
return 1
end
-- ------------------------------------------------------------------------------------------------ decode
-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed
local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?)
local pal = buffer.create(1024)
buffer.copy(pal, 0, old, 0, 1024)
local function u8(): number
local v = if p < stop then buffer.readu8(b, p) else 0
p += 1
return v
end
local sz = 0
while sz < 256 do
local t = u8()
if t >= 0x80 then
sz += t - 0x80 + 1
elseif t >= 0x40 then
local off = u8()
local j = t - 0x40 + 1
if off + j > 256 then
return nil
end
while j > 0 and sz < 256 do
buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4))
sz += 1
off += 1
j -= 1
end
else
local r = PAL6[t + 1]
local g = PAL6[u8() % 64 + 1]
local bl = PAL6[u8() % 64 + 1]
buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000)
sz += 1
end
end
return pal
end
-- demux(r, opts?) -> the Demuxer | nil, Err
function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < HEADER then
return nil, Err.new(Err.TRUNCATED, "file shorter than the header")
end
local hr = Bytes.reader(b, base, HEADER)
local magic = hr:string(4)
local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le()
local ptsInc = hr:i32le()
local flags = hr:u32le()
hr:skip(28)
local treeSize = hr:u32le()
local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() }
local rates, aflags = {}, {}
for k = 1, 7 do
rates[k] = hr:u24le()
aflags[k] = hr:u8()
end
if hr.err then
return nil, hr.err
end
if magic ~= "SMK2" and magic ~= "SMK4" then
return nil, Err.new(Err.CORRUPT, "not a Smacker file")
end
if w == 0 or h == 0 or w > 32768 or h > 32768 then
return nil, Err.new(Err.CORRUPT, "bad picture size")
end
local max = (opts and opts.maxPixels) or 2 ^ 26
if w * h > max then
return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels")
end
local shown = frames
if bit32.band(flags, RING) ~= 0 then
frames += 1
end
local p = base + HEADER
if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then
return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file")
end
-- the trees (with the four sizes in front, as the video codec takes them)
local config = buffer.create(16 + treeSize)
for k = 1, 4 do
buffer.writeu32(config, (k - 1) * 4, sizes[k])
end
buffer.copy(config, 16, b, p + frames * 5, treeSize)
-- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s)
local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000
local tracks: { Types.Track } = {
{
id = 1,
kind = "video",
codec = "smackvid",
codecTag = magic,
timescale = 100000,
width = w,
height = h,
frameRate = 100000 / tick,
default = true,
config = config,
flags = flags,
} :: Types.Track,
}
local audio: { [number]: Types.Track } = {}
for k = 1, 7 do
if rates[k] > 0 then
local f = aflags[k]
local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8
local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio"
elseif bit32.band(f, 0x80) ~= 0 then "smackaudio"
elseif bits == 16 then "pcm_s16le"
else "pcm_u8"
local t: Types.Track = {
id = k + 1,
kind = "audio",
codec = codec,
codecTag = string.format("0x%02X", f),
timescale = rates[k],
sampleRate = rates[k],
channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1,
bitsPerSample = bits,
default = #tracks == 1,
}
audio[k] = t
table.insert(tracks, t)
end
end
local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown })
local count = if opts and opts.ringFrame then frames else shown
local pal = buffer.create(1024)
local apts = { 0, 0, 0, 0, 0, 0, 0 }
local at = p + frames * 5 + treeSize
for i = 0, frames - 1 do
local fsize = buffer.readu32(b, p + i * 4)
local fflags = buffer.readu8(b, p + frames * 4 + i)
local size = fsize - fsize % 4
local q, stop = at, math.min(limit, at + size)
at += size
local ok = true
if fflags % 2 == 1 and q < stop then
local psize = buffer.readu8(b, q) * 4
if psize > size then
ok = false
else
local np = palette(b, q + 1, math.min(stop, q + psize), pal)
if np then
pal = np
else
ok = false
end
q += psize
end
end
for k = 1, 7 do
if not ok then
break
end
if bit32.band(fflags, 2 ^ k) ~= 0 then
if q + 4 > stop then
ok = false
break
end
local asize = buffer.readu32(b, q)
local t = audio[k]
local min = if t and t.codec ~= "pcm_s16le" then 8 else 4
if asize < min or q + asize > stop then
ok = false
break
end
if t then
local len = asize - 4
local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8
local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes
elseif t.codec == "binkaudio" then 0
else len // frameBytes
dmx:add(t.id, apts[k], nil, n, true, q + 4, len)
apts[k] += n
end
q += asize
end
end
if ok and i < count then
dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q))
dmx:setExtra("palette", pal)
end
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err
function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?)
local codec = track.codec
if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec)
end
local id = track.id
local count = dmx:count(id)
local starts: { number } = {}
local total = 0
for k = 1, count do
local pts, _, dur = dmx:info(id, k)
starts[k] = pts or total
total = (pts or total) + (dur or 0)
end
starts[count + 1] = total
local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number
local packed = codec == "smackaudio"
local floats: { number } = {}
local dec: any = {
sampleRate = rate,
channels = ch,
frames = total,
duration = total / rate,
bitrate = rate * ch * bits,
tags = {},
}
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return starts[math.clamp(i, 1, count + 1)]
end,
decode = function(i: number): (number?, Err.Err?)
local pkt = dmx:get(id, i)
if not pkt then
return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i)
end
local n, out = Audio.decode(pkt.data, ch, bits, packed)
if not n then
return nil, Err.from(out :: string)
end
floats = out :: { number }
return n, nil
end,
pcm = function(): { number }
return floats
end,
reset = function() end,
cumulative = true,
})
end
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Smk.demux(r, opts)
if not dmx then
return nil, err
end
local o: any = table.clone(opts or {})
type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?)
local hook = o.openAudio :: Hook?
o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?)
if track.codec == "binkaudio" and hook then
return hook(d, track)
end
return Smk.openAudio(d, track)
end
return Video.open(dmx, o)
end
return Smk
+113
View File
@@ -0,0 +1,113 @@
-- codecs/video/Legacy tests: Cinepak (24-bit, grey, 8-bit palettised, several strips, a 92x68 size), Microsoft Video 1
-- (16-bit, 8-bit with an AVI palette), QuickTime RLE (depths 1 / 2 / 4 / 8 with colour tables, default Macintosh
-- tables and grey ramps; 16 / 24 / 32-bit and grey from ffmpeg) and QuickTime SMC, in AVI, MOV and MKV: every frame
-- equals ffmpeg's decode (CRC-32 of rgba); seeking; the registry entries; the fuzz pass on each codec's packet decoder.
-- Fixtures: tools/fixtures/legacy.py.
local T = require("@tests/T")
local F = require("@formats")
local Crc32 = require("@formats/core/Crc32")
local Video = require("@formats/codecs/video/Video")
local Legacy = require("@formats/codecs/video/Legacy")
local Fx = require("@tests/gen/legacy_cases")
local t = T.suite("legacy")
-- the registry
t:eq(Video.fromFourcc("cvid"), "cinepak", "cvid")
t:eq(Video.fromFourcc("CRAM"), "msvideo1", "CRAM")
t:eq(Video.fromFourcc("msvc"), "msvideo1", "msvc")
t:eq(Video.fromFourcc("rle "), "qtrle", "rle ")
t:eq(Video.fromFourcc("smc "), "smc", "smc ")
for _, id in Legacy.CODECS do
t:check(Video.canDecode(id), id .. ": decodable")
end
local samples: { [string]: { any } } = {}
for _, c in Fx do
local label = c.name
local v, err = F.video.open(c.data)
t:check(v ~= nil, label .. ": open: " .. tostring(err))
if v then
t:eq(v.codec, c.codec, label .. ": codec")
t:eq(v.width, c.width, label .. ": width")
local n, bad, first = 0, 0, nil
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": decode error " .. tostring(ferr))
break
end
n += 1
local img = f.image
if img.format ~= "rgba8" or img.width ~= c.width or Crc32.of(img.pixels) ~= c.frames[n] then
bad += 1
first = first or n
end
end
t:check(n == #c.frames and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ, first %s)", label, n - bad, #c.frames, bad, tostring(first)))
-- seeking: back to the start, the first frame again
v:seek(0)
local f = v:nextFrame()
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[1], label .. ": seek(0)")
-- packets for the fuzz pass
local dmx = v.demuxer
local tr = dmx:track("video")
if not samples[c.codec] then
local list = {}
for k = 1, math.min(3, dmx:count(tr.id)) do
table.insert(list, dmx:get(tr.id, k).data)
end
samples[c.codec] = { track = tr, packets = list }
end
end
end
-- the fuzz pass on the native packet decoders (no pcall in between)
local P = Legacy.Picture
local raw: { [string]: (tr: any) -> (buffer) -> any } = {
cinepak = function(tr)
return function(b)
local pic = P.new(tr.width, tr.height, tr.bitsPerPixel == 8, 4, 4, tr.palette)
return Legacy.Cinepak.decode(pic, b, Legacy.Cinepak.state(), false)
end
end,
msvideo1 = function(tr)
return function(b)
local bits = if tr.bitsPerPixel == 8 then 8 else 16
return Legacy.Msvideo1.decode(P.new(tr.width, tr.height, bits == 8, 4, 4), b, bits)
end
end,
qtrle = function(tr)
return function(b)
local d = tr.bitsPerPixel or 24
for _, depth in { d, 1, 2, 4, 8, 16, 32 } do
Legacy.QtRle.decode(P.new(tr.width, tr.height, Legacy.QtRle.palettised(depth), Legacy.QtRle.pad(depth), 1), b, depth)
end
return true
end
end,
smc = function(tr)
return function(b)
return Legacy.Smc.decode(P.new(tr.width, tr.height, true, 4, 4), b, Legacy.Smc.tables())
end
end,
}
for id, s in samples do
local fn = raw[id]
if fn then
t:fuzz(id .. " packets", fn(s.track), s.packets, { mutations = 24, garbage = 60 })
end
end
t:fuzz("open", function(b: buffer)
local v = F.video.open(b)
if v then
for _ = 1, 3 do
if not v:nextFrame() then
break
end
end
end
return v
end, { Fx[1].data, Fx[#Fx].data }, { mutations = 8, garbage = 20 })
t:done()
+25 -2
View File
@@ -1,4 +1,5 @@
-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg
-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Every frame bit-exact with
-- `ffmpeg -idct int` (the IDCT codecs/video/Dsp reproduces; frames with concealed macroblocks excepted). Against ffmpeg
-- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode,
-- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per
-- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p;
@@ -11,6 +12,7 @@ local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local Base64 = require("@formats/core/Base64")
local Deflate = require("@formats/codecs/compress/Deflate")
local Types = require("@formats/Types")
local Crc32 = require("@formats/core/Crc32")
local STREAMS = {
require("@tests/gen/mpeg1_qcif_200k"),
@@ -81,6 +83,7 @@ local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): nu
end
local MAE_LIMIT = 2
local totalExact, totalConcealed = 0, 0
local MEAN_LIMIT = 1.5
-- 1. every stream against ffmpeg
@@ -101,6 +104,7 @@ for _, fx in STREAMS do
local hasB = string.find(name, "bframes") ~= nil
local dec = Mpeg1.new({ reorder = hasB })
local frames = 0
local exact, concealed = 0, 0
local maxMae, maxMeanErr = 0, 0
local sums = {}
local function onFrame(f: any)
@@ -136,6 +140,21 @@ for _, fx in STREAMS do
end
t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255")
sums[frames] = buffer.tostring(px)
-- bit-exact against ffmpeg -idct int (outside macroblocks the decoder had to conceal)
local ex = fx.exact[frames]
if ex then
local img = Mpeg1.frameImage(f) :: Types.Image
local yc = Crc32.of(img.pixels, 0, n)
local uc = Crc32.of(img.pixels, n, cw * ch)
local vc = Crc32.of(img.pixels, n + cw * ch, cw * ch)
if yc == ex[1] and uc == ex[2] and vc == ex[3] then
exact += 1
elseif next(f.concealed) ~= nil then
concealed += 1
else
t:check(false, string.format("%s frame %d (type %d): differs from ffmpeg -idct int", name, frames, f.pictureType))
end
end
end
local t0 = os.clock()
for _, u in fx.units do
@@ -155,7 +174,10 @@ for _, fx in STREAMS do
t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)")
t:eq(dec.stats.errors, 0, name .. ": no bitstream errors")
worst = math.max(worst, maxMae)
t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt)
t:note("%-13s %4dx%-4d %3d frames %3d bit-exact worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, exact, maxMae, maxMeanErr, frames / dt)
t:eq(exact + concealed, frames, name .. ": frames equal to ffmpeg -idct int (or with concealed macroblocks)")
totalExact += exact
totalConcealed += concealed
-- streamed: random pieces through write / decodeFrame, then flush
local d2 = Mpeg1.new({ reorder = hasB })
@@ -187,6 +209,7 @@ for _, fx in STREAMS do
t:eq(got, frames, name .. ": streamed frame count")
end
t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC)
t:note("%d frames bit-exact with ffmpeg -idct int, %d with concealed macroblocks (ffmpeg error concealment)", totalExact, totalConcealed)
-- 2. a size change mid-stream
do
+304
View File
@@ -0,0 +1,304 @@
-- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and
-- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan,
-- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd
-- size, B-frames, dual prime, field pictures, concealment vectors) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display
-- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive,
-- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted
-- streams never throw; the fuzz no-throw pass.
local T = require("@tests/T")
local Mpeg2 = require("@formats/codecs/video/Mpeg2")
local Video = require("@formats/codecs/video/Video")
local Base64 = require("@formats/core/Base64")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/compress/Deflate")
local STREAMS = {
require("@tests/gen/mpeg2_prog"),
require("@tests/gen/mpeg2_tff"),
require("@tests/gen/mpeg2_bff_alt"),
require("@tests/gen/mpeg2_tools"),
require("@tests/gen/mpeg2_dc9_matrix"),
require("@tests/gen/mpeg2_dc11_q1"),
require("@tests/gen/mpeg2_motion"),
require("@tests/gen/mpeg2_odd_ilace"),
require("@tests/gen/mpeg2_c422"),
require("@tests/gen/mpeg2_c422_ilace"),
require("@tests/gen/mpeg2_dualprime"),
require("@tests/gen/mpeg2_fields"),
require("@tests/gen/mpeg2_fields_conceal"),
}
local t = T.suite("codecs/mpeg2")
local rand = T.rng(11)
local function b64(s: string): buffer
return Base64.decode(s) :: buffer
end
-- CRC-32 of a plane cropped to w x h from a buffer with stride
local function planeCrc(b: buffer, stride: number, w: number, h: number): number
local row = buffer.create(w * h)
for y = 0, h - 1 do
buffer.copy(row, y * w, b, y * stride, w)
end
return Crc32.of(row)
end
-- the cropped planes of a frame, as ffmpeg writes them (w x h luma, ceil(w / 2) x (h or ceil(h / 2)) chroma)
local function crcs(f: any): (number, number, number)
local w, h = f.width, f.height
local cw = (w + 1) // 2
local ch = if f.chroma == 2 then h else (h + 1) // 2
local chw = f.codedWidth // 2
return planeCrc(f.y, f.codedWidth, w, h), planeCrc(f.cb, chw, cw, ch), planeCrc(f.cr, chw, cw, ch)
end
-- differing samples between a frame's luma and a reference yuv frame (debug detail on a mismatch)
local function lumaDiff(f: any, ref: buffer): (number, number)
local n, first = 0, -1
for y = 0, f.height - 1 do
for x = 0, f.width - 1 do
if buffer.readu8(f.y, y * f.codedWidth + x) ~= buffer.readu8(ref, y * f.width + x) then
n += 1
if first < 0 then
first = y * 65536 + x
end
end
end
end
return n, first
end
local function decodeUnits(fx: any, file: buffer): { any }
local dec = Mpeg2.new({ reorder = true, rgba = false })
local out = {}
local function take(f: any)
local y, u, v = crcs(f)
-- the 16-line luma bands now: the planes belong to the decoder
local bands = {}
for b = 0, (f.height + 15) // 16 - 1 do
local rows = math.min(16, f.height - b * 16)
local buf = buffer.create(f.width * rows)
for r = 0, rows - 1 do
buffer.copy(buf, r * f.width, f.y, (b * 16 + r) * f.codedWidth, f.width)
end
bands[b] = Crc32.of(buf)
end
table.insert(out, { y, u, v, f, bands })
end
for i, u in fx.units do
local f = dec:decode(file, u[1], u[2], i)
while f do
take(f)
f = dec:decode(file, 0, 0, i)
end
end
while true do
local f = dec:flush()
if not f then
break
end
take(f)
end
return out
end
-- 1. every stream against ffmpeg, bit-exact. ffmpeg's encoder sometimes ends a B-picture slice before the row's last
-- macroblock (invalid MPEG-2); both decoders conceal the gap, ffmpeg with its error-resilience guesses and deblocking.
-- Frames with concealed macroblocks compare every 16-line luma band but those and their neighbours.
local total, concealedFrames = 0, 0
for _, fx in STREAMS do
local name = fx.name
local file = b64(fx.file)
local t0 = os.clock()
local got = decodeUnits(fx, file)
local dt = os.clock() - t0
t:eq(#got, fx.frames, name .. ": frame count")
local bad, msg = 0, ""
for k, ref in fx.crcs do
local g = got[k]
if g and (g[1] ~= ref[1] or g[2] ~= ref[2] or g[3] ~= ref[3]) then
local f = g[4]
local ok = next(f.concealed) ~= nil
if ok then
concealedFrames += 1
for band, crc in fx.bands[k] do
local b = band - 1
if not (f.concealed[b] or f.concealed[b - 1] or f.concealed[b + 1]) then
ok = ok and g[5][b] == crc
end
end
end
if not ok then
bad += 1
if bad == 1 then
local detail = ""
if k == 1 and #got == 1 then
local n, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer)
detail = string.format(" (%d luma samples differ, first at %d,%d)", n, first % 65536, first // 65536)
end
msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType,
tostring(g[1] == ref[1]), tostring(g[2] == ref[2]), tostring(g[3] == ref[3]), detail)
end
end
end
end
t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg)
local f1 = got[1] and got[1][4]
if f1 then
t:check(f1.mpeg2 == true, name .. ": mpeg2 flag")
t:eq(f1.chroma, fx.chroma, name .. ": chroma format")
end
total += #got
t:note(" %-12s %4dx%-4d %s %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height,
if fx.chroma == 2 then "4:2:2" else "4:2:0", #got, #got / dt)
end
-- 2. interlace flags
do
local got = decodeUnits(STREAMS[2], b64(STREAMS[2].file))
t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == true, "tff: interlaced, top field first")
got = decodeUnits(STREAMS[3], b64(STREAMS[3].file))
t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == false, "bff_alt: bottom field first")
got = decodeUnits(STREAMS[1], b64(STREAMS[1].file))
t:check(got[1][4].progressive == true, "prog: progressive")
end
-- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit
for _, idx in { 2, 9, 12 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local want = decodeUnits(fx, file)
local dec = Mpeg2.new({ reorder = true, rgba = false })
local p, k, ok = 0, 0, true
local n = buffer.len(file)
local function check(f: any)
k += 1
local y, u, v = crcs(f)
local ref = want[k]
ok = ok and ref ~= nil and y == ref[1] and u == ref[2] and v == ref[3]
end
while p < n do
local len = math.min(n - p, 1 + rand(5000))
dec:write(file, p, len)
p += len
while true do
local f = dec:decodeFrame()
if not f then
break
end
check(f)
end
end
while true do
local f = dec:flush()
if not f then
break
end
check(f)
end
t:check(ok and k == fx.frames, string.format("%s: random pieces give the same %d frames (%d)", fx.name, fx.frames, k))
end
-- 4. frameImage: yuv420p (4:2:2 converted), rgba8
do
local fx = STREAMS[9]
local dec = Mpeg2.new({ reorder = false, rgba = true })
local file = b64(fx.file)
local f = dec:decode(file, fx.units[1][1], fx.units[1][2])
t:check(f ~= nil and f.pixels ~= nil, "c422: rgba frame")
if f then
local img = Mpeg2.frameImage(f)
t:check(img ~= nil and img.format == "yuv420p" and img.width == fx.width, "c422: frameImage yuv420p")
if img then
local cw, ch = (fx.width + 1) // 2, (fx.height + 1) // 2
t:eq(buffer.len(img.pixels), fx.width * fx.height + 2 * cw * ch, "c422: yuv420p size")
t:eq(img.meta.source.format, "mpeg2", "c422: meta.source.format")
t:eq(img.meta.source.chroma, "422", "c422: meta.source.chroma")
end
local rgba = Mpeg2.frameImage(f, true)
t:check(rgba ~= nil and rgba.format == "rgba8", "c422: frameImage rgba8")
end
t:check(Mpeg2.frameImage({} :: any) == nil, "frameImage of a non-frame is nil")
end
-- 5. the registry's decoder (packets = access units), display order with pts
do
t:check(Video.fromFourcc("mpg2") == "mpeg2" and Video.fromMatroska("V_MPEG2") == "mpeg2", "registry names")
t:check(Video.canDecode("mpeg2") and Video.canDecode("mpeg1"), "registry decoders")
local fx = STREAMS[1]
local file = b64(fx.file)
local want = decodeUnits(fx, file)
local dec = assert(Video.decoder({ id = 1, kind = "video", codec = "mpeg2", timescale = 25 } :: any))
local frames, order = 0, true
local last = -1
for i, u in fx.units do
local d = buffer.create(u[2])
buffer.copy(d, 0, file, u[1], u[2])
dec:decode({ track = 1, pts = i, keyframe = false, data = d } :: any)
while true do
local img, pts = dec:receive()
if not img then
break
end
frames += 1
local ref = want[frames]
local w, h = fx.width, fx.height
order = order and ref ~= nil and Crc32.of(img.pixels, 0, w * h) == ref[1] and img.meta.yuv ~= nil
last = pts or last
end
end
dec:flush()
while dec:receive() do
frames += 1
end
t:eq(frames, fx.frames, "registry decoder: frame count")
t:check(order, "registry decoder: frames in display order, equal to the codec's")
end
-- 6. robustness: truncated units, bit flips, garbage (never throws), and the fuzz pass
do
local samples = {}
for _, idx in { 1, 2, 9, 11 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local n = math.min(buffer.len(file), 60000)
local b = buffer.create(n)
buffer.copy(b, 0, file, 0, n)
table.insert(samples, b)
end
local threw = 0
for round = 1, 12 do
local src = samples[1 + round % #samples]
local b = buffer.create(buffer.len(src))
buffer.copy(b, 0, src)
for _ = 1, 20 do
local i = rand(buffer.len(b))
buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8))))
end
local ok = pcall(function()
local dec = Mpeg2.new({ reorder = true })
dec:write(b)
while dec:decodeFrame() do
end
while dec:flush() do
end
end)
if not ok then
threw += 1
end
end
t:eq(threw, 0, "corrupted streams never throw")
t:fuzz("decode", function(b: buffer)
local dec = Mpeg2.new({ reorder = true })
dec:write(b)
local f = dec:decodeFrame()
while f do
f = dec:decodeFrame()
end
return dec:flush()
end, samples, { mutations = 60, garbage = 10 })
end
t:note(" %d frames bit-exact with ffmpeg -idct int (%d with concealed macroblocks: compared outside them)", total, concealedFrames)
t:done()
+285
View File
@@ -0,0 +1,285 @@
-- codecs/video/Theora tests. Against ffmpeg (tools/fixtures/theora.py, its vp3 decoder = libtheora's output): every
-- frame of every stream, bit-exact (Adler-32 of the native planes of the picture region, as ffmpeg's framecrc): 4:2:0 /
-- 4:2:2 / 4:4:4, qualities 0..10, a 300 kbit/s high-motion stream (4MV, golden frames, multiple qi), picture regions
-- smaller than the coded frame (even sizes from the encoder, odd sizes at offsets patched into the header), frames
-- the encoder dropped (empty packets: ffmpeg outputs nothing, we repeat the previous picture) and one spliced in;
-- image() as yuv420p (4:2:2 / 4:4:4 chroma averaged); Theora in Matroska through the codecs/video/Video registry.
-- Errors: missing / bad headers, maxPixels, header packets in the data, garbage packets; the fuzz no-throw passes
-- (headers, key and inter frames).
local T = require("@tests/T")
local Theora = require("@formats/codecs/video/Theora")
local Video = require("@formats/codecs/video/Video")
local Ogg = require("@formats/containers/Ogg")
local Mkv = require("@formats/video/mkv")
local Bytes = require("@formats/core/Bytes")
local Base64 = require("@formats/core/Base64")
local Adler32 = require("@formats/core/Adler32")
local Err = require("@formats/core/Err")
local t = T.suite("theora")
local CASES = { "q6", "q0", "q10", "motion", "odd", "static", "yuv422", "yuv444", "odd444", "crop", "crop422" }
local FIXTURES: { [string]: any } = {
q6 = require("@tests/gen/theora_q6"),
q0 = require("@tests/gen/theora_q0"),
q10 = require("@tests/gen/theora_q10"),
motion = require("@tests/gen/theora_motion"),
odd = require("@tests/gen/theora_odd"),
static = require("@tests/gen/theora_static"),
yuv422 = require("@tests/gen/theora_yuv422"),
yuv444 = require("@tests/gen/theora_yuv444"),
odd444 = require("@tests/gen/theora_odd444"),
crop = require("@tests/gen/theora_crop"),
crop422 = require("@tests/gen/theora_crop422"),
}
-- the Theora packets of an Ogg file: headers, data packets
local function packets(file: buffer): ({ buffer }, { buffer })
local d = Ogg.open(file)
local serial = d:find("theora")
local hdrs, data = {}, {}
for p in d:packets(serial) do
if #hdrs < 3 then
table.insert(hdrs, Ogg.copy(p))
else
table.insert(data, Ogg.copy(p))
end
end
return hdrs, data
end
-- ffmpeg's framecrc: Adler-32 started at 0 over the packed planes
local function crc(y: buffer, u: buffer, v: buffer): number
local a = Adler32.of(y, nil, nil, 0)
a = Adler32.of(u, nil, nil, a)
return Adler32.of(v, nil, nil, a)
end
local samples: { buffer } = {}
local headerSets: { { buffer } } = {}
-- 1. every fixture, every frame
for _, name in CASES do
local fx = FIXTURES[name]
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
table.insert(headerSets, hdrs)
local dec, err = Theora.new(hdrs)
t:check(dec ~= nil, name .. ": headers: " .. tostring(err))
if dec then
t:eq(dec.width, fx.width, name .. ": width")
t:eq(dec.height, fx.height, name .. ": height")
t:eq(dec.pixelFormat, fx.pixfmt, name .. ": pixel format")
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
local bad, dupes, prev = 0, 0, nil :: number?
for k, p in data do
local kind, e = dec:decode(p)
if not kind then
bad += 1
t:check(false, name .. ": frame " .. (k - 1) .. ": " .. tostring(e))
continue
end
local y, u, v = dec:planes()
local c = crc(y, u, v)
local w = want[k - 1]
if kind == "dup" then
dupes += 1
t:check(w == nil, name .. ": ffmpeg shows no frame for empty packet " .. (k - 1))
if c ~= prev then
bad += 1
end
elseif w ~= c then
bad += 1
end
prev = c
end
t:eq(bad, 0, name .. ": frames different from ffmpeg's (of " .. #data .. ", " .. dupes .. " repeated)")
t:eq(#data - dupes, #fx.frames, name .. ": as many shown frames as ffmpeg")
table.insert(samples, data[1])
if data[2] then
table.insert(samples, data[2])
end
end
end
-- 2. an empty packet spliced in after the 5th frame repeats it; the rest follows
do
local fx = require("@tests/gen/theora_dupe") :: any
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
local bad, prev = 0, nil :: number?
for k, p in data do
local kind = dec:decode(p)
local y, u, v = dec:planes()
local c = crc(y, u, v)
if k == 6 then
t:eq(kind, "dup", "dupe: the empty packet")
t:eq(buffer.len(p), 0, "dupe: it is empty")
t:eq(c, prev, "dupe: repeats the previous picture")
elseif c ~= fx.frames[if k > 6 then k - 1 else k][2] then
bad += 1
end
prev = c
end
t:eq(bad, 0, "dupe: the other frames")
end
-- 3. image(): yuv420p, the planes as they are (4:2:0) or averaged (4:2:2 / 4:4:4)
for _, name in { "q6", "crop", "yuv422", "crop422", "odd444" } do
local fx = FIXTURES[name]
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
dec:decode(data[1])
dec:decode(data[2])
local img = dec:image()
local y, u, v, cw, ch = dec:planes()
local w, h = dec.width, dec.height
local ow, oh = (w + 1) // 2, (h + 1) // 2
t:eq(img.format, "yuv420p", name .. ": image format")
t:eq(img.width * 1000 + img.height, w * 1000 + h, name .. ": image size")
t:eq(buffer.len(img.pixels), w * h + 2 * ow * oh, name .. ": image bytes")
t:eq(Adler32.of(img.pixels, 0, w * h), Adler32.of(y), name .. ": luma")
local bad = 0
for r = 0, oh - 1 do
for c = 0, ow - 1 do
local want
if fx.pixfmt == "yuv420p" then
want = buffer.readu8(u, math.min(r, ch - 1) * cw + c)
elseif fx.pixfmt == "yuv422p" then
want = (buffer.readu8(u, math.min(2 * r, ch - 1) * cw + c) + buffer.readu8(u, math.min(2 * r + 1, ch - 1) * cw + c) + 1) // 2
else
local r0, r1 = math.min(2 * r, ch - 1), math.min(2 * r + 1, ch - 1)
local c0, c1 = math.min(2 * c, cw - 1), math.min(2 * c + 1, cw - 1)
want = (buffer.readu8(u, r0 * cw + c0) + buffer.readu8(u, r0 * cw + c1) + buffer.readu8(u, r1 * cw + c0) + buffer.readu8(u, r1 * cw + c1) + 2) // 4
end
if buffer.readu8(img.pixels, w * h + r * ow + c) ~= want then
bad += 1
end
end
end
t:eq(bad, 0, name .. ": U downsampled")
local _ = v
t:eq(img.meta.yuv and img.meta.yuv.matrix, "bt601", name .. ": colour matrix")
end
-- 4. Theora in Matroska: the registry entry (V_THEORA, Xiph-laced CodecPrivate) through video/mkv
do
t:eq(Video.fromMatroska("V_THEORA"), "theora", "registry: V_THEORA")
t:check(Video.canDecode("theora"), "registry: theora decodes")
local fx = require("@tests/gen/theora_mkv") :: any
local v, err = Mkv.open(Bytes.reader(Base64.decode(fx.file) :: buffer))
t:check(v ~= nil, "mkv: open: " .. tostring(err))
if v then
t:eq(v.codec, "theora", "mkv: codec")
local n, bad, shown = 0, 0, 0
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
while true do
local f, e = v:nextFrame()
if not f then
t:check(e == nil, "mkv: frames: " .. tostring(e))
break
end
local img = f.image
local w = want[math.floor(f.pts * 25 + 0.5)]
if w then
shown += 1
if Adler32.of(img.pixels, nil, nil, 0) ~= w then
bad += 1
end
end
n += 1
end
t:eq(bad, 0, "mkv: frames as ffmpeg's")
t:eq(shown, #fx.frames, "mkv: every frame ffmpeg shows")
end
end
-- 5. API details and errors
do
local fx = FIXTURES.q6
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
t:eq(dec.frameRate, 25, "frame rate")
t:check(dec.vendor ~= "" and dec.tags.encoder ~= nil, "comment header: vendor and ENCODER tag")
t:eq(Theora.isHeader(hdrs[1]), 1, "isHeader: identification")
t:eq(Theora.isHeader(hdrs[3]), 3, "isHeader: setup")
t:eq(Theora.isHeader(data[1]), nil, "isHeader: data")
local kind, e = dec:decode(hdrs[2])
t:check(kind == nil and e == nil, "a header packet in the data is skipped")
t:eq(Theora.granuleFrame(dec.info, 0), -1, "granule 0 (3.2.1 numbering)")
t:eq(Theora.granuleFrame(dec.info, 2 ^ dec.info.granuleShift * 12 + 3), 14, "granule: keyframe 12 + 3")
-- the Xiph-laced config Matroska uses
local lens = { buffer.len(hdrs[1]), buffer.len(hdrs[2]) }
local w = Bytes.writer(64)
w:u8(2)
for _, l in lens do
local x = l
while x >= 255 do
w:u8(255)
x -= 255
end
w:u8(x)
end
for _, h in hdrs do
w:bytes(h)
end
local cfg = w:finish()
local parts = Theora.splitConfig(cfg)
t:check(parts ~= nil and #parts == 3 and buffer.len(parts[3]) == buffer.len(hdrs[3]), "splitConfig")
t:check(Theora.new(cfg) ~= nil, "new(config)")
local d2, e2 = Theora.new({ hdrs[1], hdrs[2] })
t:check(d2 == nil and e2 ~= nil and e2.code == Err.CORRUPT, "missing setup header: CORRUPT")
local _, e3 = Theora.new({ hdrs[2], hdrs[1], hdrs[3] })
t:check(e3 ~= nil and e3.code == Err.CORRUPT, "headers out of order: CORRUPT")
local cut = buffer.create(100)
buffer.copy(cut, 0, hdrs[3], 0, 100)
local _, e4 = Theora.new({ hdrs[1], hdrs[2], cut })
t:check(e4 ~= nil, "truncated setup header: " .. tostring(e4))
local _, e5 = Theora.new(hdrs, { maxPixels = 1000 })
t:check(e5 ~= nil and e5.code == Err.LIMIT, "maxPixels: LIMIT")
local _, e6 = dec:decode(data[1], 5, buffer.len(data[1]))
t:check(e6 ~= nil and e6.code == Err.ARG, "decode: range outside the buffer")
-- an inter frame before any keyframe decodes over grey
local fresh = Theora.new(hdrs) :: Theora.TheoraDecoder
t:check(fresh:decode(data[2]) == "inter", "an inter frame first")
local track: any = { id = 1, kind = "video", codec = "theora", timescale = 25, config = cfg }
local vd = Theora.newVideoDecoder(track)
t:check(vd ~= nil, "newVideoDecoder")
if vd then
vd:decode({ track = 1, pts = 0, keyframe = true, data = data[1] })
local img, pts, key = vd:receive()
t:check(img ~= nil and pts == 0 and key == true, "newVideoDecoder: a keyframe picture")
vd:reset()
t:check(vd:receive() == nil, "newVideoDecoder: reset drops pending pictures")
end
local nv, nerr = Theora.newVideoDecoder({ id = 1, kind = "video", codec = "theora", timescale = 25 } :: any)
t:check(nv == nil and nerr ~= nil, "newVideoDecoder without config")
end
-- 6. fuzz: headers, keyframes and inter frames (a decoder primed with a keyframe, fed mutated packets)
do
local hdrs = headerSets[1]
t:fuzz("headers", function(b: buffer)
return Theora.new({ hdrs[1], hdrs[2], b })
end, { hdrs[3] }, { mutations = 24, garbage = 50 })
t:fuzz("identification", function(b: buffer)
return Theora.new({ b, hdrs[2], hdrs[3] })
end, { hdrs[1] }, { mutations = 24, garbage = 20 })
for i, h in headerSets do
local dec = Theora.new(h) :: Theora.TheoraDecoder
local s = { samples[2 * i - 1], samples[2 * i] }
dec:decode(s[1])
t:fuzz("frames " .. CASES[i], function(b: buffer)
local kind = dec:decode(b)
dec:planes()
return kind
end, s, { mutations = 12, garbage = 20, seed = i })
end
end
t:done()
+138
View File
@@ -0,0 +1,138 @@
-- host/Roblox tests: the pure half of the EditableMesh adapter (meshPages: triangle runs within the triangle / vertex
-- limits, corners mapping back to the source indices, double-sided counting, errors; pageData: centring, per-axis
-- scale, inverse-scaled unit normals, uvs + flipV, linear -> sRGB colours). toEditableMesh itself needs Roblox.
local T = require("@tests/T")
local Host = require("@formats/host/Roblox")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local t = T.suite("host_roblox")
local S = Types.Scene
local function f32(list: { number }, comps: number): Types.Accessor
local a = S.accessor(nil, "f32", comps, #list // comps)
for i, v in list do
buffer.writef32(a.data, (i - 1) * 4, v)
end
return a
end
local function near(a: number, b: number, eps: number?): boolean
return math.abs(a - b) <= (eps or 1e-5)
end
-- an n x n grid of quads in the xz plane (two triangles each), u16 indices, normals up, uvs, colours
local function grid(n: number): Types.Primitive
local pos, nrm, uv, col = {}, {}, {}, {}
for z = 0, n do
for x = 0, n do
table.insert(pos, x)
table.insert(pos, 0)
table.insert(pos, z)
for _, v in { 0, 1, 0 } do
table.insert(nrm, v)
end
table.insert(uv, x / n)
table.insert(uv, z / n)
for _, v in { 0.5, 0, 1, 0.25 } do
table.insert(col, v)
end
end
end
local idx = {}
for z = 0, n - 1 do
for x = 0, n - 1 do
local a = z * (n + 1) + x
local b, c, d = a + 1, a + n + 1, a + n + 2
for _, v in { a, c, b, b, c, d } do
table.insert(idx, v)
end
end
end
local ia = S.accessor(nil, "u16", 1, #idx)
for i, v in idx do
buffer.writeu16(ia.data, (i - 1) * 2, v)
end
return {
attributes = { POSITION = f32(pos, 3), NORMAL = f32(nrm, 3), TEXCOORD_0 = f32(uv, 2), COLOR_0 = f32(col, 4) },
indices = ia,
mode = "triangles",
}
end
-- 1. pages within the limits, covering every triangle once, corners = the source indices
local prim = grid(10) -- 121 vertices, 200 triangles
local pages = assert(Host.meshPages(prim, { maxTriangles = 64 }))
t:eq(#pages, 4, "200 triangles / 64 per page")
local covered = 0
for pi, pg in pages do
t:eq(pg.first, covered, "page " .. pi .. " starts after the previous one")
t:check(pg.count <= 64, "page " .. pi .. " within maxTriangles")
t:eq(buffer.len(pg.corners), pg.count * 12, "page " .. pi .. " corners")
for k = 0, pg.count * 3 - 1 do
local src = buffer.readu16((prim.indices :: any).data, (pg.first * 3 + k) * 2)
local l = buffer.readu32(pg.corners, k * 4)
if pg.vertices[l + 1] ~= src then
t:check(false, string.format("page %d corner %d maps back to %d", pi, k, src))
end
end
covered += pg.count
end
t:eq(covered, 200, "every triangle in a page")
t:eq(pages[1].min[1], 0, "page bounds min")
t:check(pages[1].max[3] > 0, "page bounds max")
local one = assert(Host.meshPages(prim))
t:eq(#one, 1, "default limits: one page")
t:eq(#one[1].vertices, 121, "every vertex once")
local two = assert(Host.meshPages(prim, { maxTriangles = 64, doubleSided = true }))
t:eq(#two, 7, "double-sided: 32 front triangles per page")
local tight = assert(Host.meshPages(prim, { maxVertices = 30 }))
for _, pg in tight do
t:check(#pg.vertices <= 30, "maxVertices")
end
t:check(#tight > 1, "maxVertices splits")
-- no indices: vertices in order
local soup = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0, 2, 0, 0, 3, 0, 0, 2, 1, 0 }, 3) }, mode = "triangles" }
local sp = assert(Host.meshPages(soup :: any))
t:eq(sp[1].count, 2, "unindexed triangles")
t:eq(#sp[1].vertices, 6, "unindexed vertices")
-- 2. errors
local _, e1 = Host.meshPages({ attributes = { POSITION = f32({ 0, 0, 0 }, 3) }, mode = "lines" } :: any)
t:check(e1 and e1.code == Err.ARG, "lines are not triangles")
local _, e2 = Host.meshPages({} :: any)
t:check(e2 and e2.code == Err.ARG, "no POSITION")
local bad = grid(1)
buffer.writeu16((bad.indices :: any).data, 2, 999)
local _, e3 = Host.meshPages(bad)
t:check(e3 and e3.code == Err.ARG, "index out of range")
local _, e4 = Host.pageData(prim, {} :: any)
t:check(e4 and e4.code == Err.ARG, "pageData needs a page")
-- 3. pageData: centred, scaled, normals, uvs, colours
local pg = one[1]
local d = assert(Host.pageData(prim, pg, { scale = { 2, 1, 4 } }))
t:eq(d.vertexCount, 121, "vertex count")
t:eq(d.triangleCount, 200, "triangle count")
t:eq(d.centre[1], 10, "centre x (5 * 2)")
t:eq(d.centre[3], 20, "centre z (5 * 4)")
local v0 = pg.vertices[1] -- source vertex of local 1
local sx0 = v0 % 11
t:eq(d.positions[1], (sx0 - 5) * 2, "position x relative to the centre, scaled")
t:check(d.normals and near(d.normals[2], 1), "unit normal")
t:check(d.uvs and near(d.uvs[1], sx0 / 10), "uv")
t:check(d.colors and near(d.colors[1], 0.7353569, 1e-4), "linear 0.5 -> sRGB")
t:check(d.colors and near(d.colors[3], 1) and near(d.colors[4], 0.25), "sRGB 1 and alpha kept")
local slanted = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3), NORMAL = f32({ 1, 1, 0, 1, 1, 0, 1, 1, 0 }, 3) }, mode = "triangles" }
local sd = assert(Host.pageData(slanted :: any, assert(Host.meshPages(slanted :: any))[1], { scale = { 2, 1, 1 }, origin = { 0, 0, 0 } }))
t:check(near(sd.normals[1], 0.5 / math.sqrt(1.25)) and near(sd.normals[2], 1 / math.sqrt(1.25)), "normals scale by the inverse")
t:eq(sd.positions[4], 2, "origin option")
local fl = assert(Host.pageData(prim, pg, { flipV = true, normals = false, colors = false }))
t:check(fl.normals == nil and fl.colors == nil, "attributes switched off")
t:check(fl.uvs and near(fl.uvs[2], 1 - (v0 // 11) / 10), "flipV")
t:done()
+105
View File
@@ -0,0 +1,105 @@
-- video/fli tests: FLI (COLOR_64, BRUN, LC, BLACK, COPY, PSTAMP, a ring frame), FLC (prefix chunk, COLOR_256, SS2 with
-- line skips and the last-byte opcode, an empty frame), an odd-size FLC, and 15 / 16 / 24-bit FLCs (BRUN, DTA_BRUN,
-- DELTA, DTA_LC, COPY, DTA_COPY, BLACK), all encoded by the fixture script: every frame equals ffmpeg's decode
-- (CRC-32 of rgba), frame rates, the ring frame option, seeking, errors, the fuzz pass. Fixtures: tools/fixtures/fli.py.
local T = require("@tests/T")
local F = require("@formats")
local Fli = require("@formats/video/fli")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/fli_cases")
local t = T.suite("fli")
t:eq(Fli.name, "fli", "name")
t:eq(Fli.category, "video", "category")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
for _, c in Fx do
local label = c.name
t:check(Fli.sniff(reader(c.data)) > 0, label .. ": sniff")
t:eq(F.detect(buffer.fromstring(c.data)), "fli", label .. ": detect")
local v, err = F.video.open(buffer.fromstring(c.data))
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
t:eq(v.codec, "flic", label .. ": codec")
t:check(v.width == c.width and v.height == c.height, label .. ": size")
t:check(math.abs(v.frameRate - c.rate) < 1e-9, label .. ": frame rate " .. v.frameRate)
t:eq(v.track.bitsPerPixel, c.depth, label .. ": depth")
local ring = v.demuxer.meta.ringFrame
local want = if ring then #c.frames - 1 else #c.frames
local n, bad = 0, 0
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": " .. tostring(ferr))
break
end
n += 1
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad))
v:seek(0.25)
local f = v:nextFrame()
local k = math.floor(0.25 * c.rate + 1 - 1e-9) + 1
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k)
if ring then
local v2 = Fli.open(reader(c.data), { ringFrame = true })
local m = 0
while v2 and v2:nextFrame() do
m += 1
end
t:eq(m, #c.frames, label .. ": with the ring frame")
end
end
end
-- errors
do
local _, e = Fli.open(reader(string.sub(Fx[1].data, 1, 100)))
t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED")
local bad = Fx[1].data
bad = string.sub(bad, 1, 4) .. "\0\0" .. string.sub(bad, 7)
t:eq(Fli.sniff(reader(bad)), 0, "bad magic: no sniff")
local _, e2 = Fli.open(reader(bad))
t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT")
local big = string.sub(Fx[1].data, 1, 8) .. "\255\15\255\15" .. string.sub(Fx[1].data, 13)
local _, e3 = Fli.open(reader(big), { maxPixels = 2 ^ 20 })
t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT")
end
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("open", function(b: buffer)
local v = Fli.open(Bytes.reader(b))
if v then
while v:nextFrame() do
end
end
return v
end, samples, { mutations = 12, garbage = 40, keepHeader = 16 })
-- the frame decoder itself (codecs/video/Legacy/Flic, native: no pcall in between)
local Flic = require("@formats/codecs/video/Legacy").Flic
for _, c in { Fx[1], Fx[2], Fx[4], Fx[6] } do
local d = Fli.demux(reader(c.data))
local packets = {}
for k = 1, math.min(4, d:count(1)) do
table.insert(packets, d:get(1, k).data)
end
t:fuzz(c.name .. " frames", function(b: buffer)
local st = Flic.state(c.width, c.height, c.depth)
if st then
Flic.decode(st, b)
return Flic.image(st)
end
return nil
end, packets, { mutations = 20, garbage = 30 })
end
t:done()
+80
View File
@@ -0,0 +1,80 @@
-- MPEG-2 video in the containers (tools/fixtures/mpeg2.py, "mpeg2_containers"): the same elementary stream copied by
-- ffmpeg into MPEG-TS (stream type 0x02, and the PMT patched to 0x80, private / DigiCipher II video), MPEG-PS (VOB),
-- Matroska (V_MPEG2) and AVI: each opens through F.video.open with codec "mpeg2", its frames equal ffmpeg's
-- `-idct int` decode (luma CRC per frame, display order), seeking lands on a frame; the raw .m2v opens too.
local T = require("@tests/T")
local F = require("@formats")
local Base64 = require("@formats/core/Base64")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/mpeg2_containers")
local Prog = require("@tests/gen/mpeg2_prog")
local t = T.suite("video/mpeg2")
local function lumaCrc(img: any): number
return Crc32.of(img.pixels, 0, img.width * img.height)
end
local CASES = {
{ "ts", "mpegts" },
{ "ts80", "mpegts" },
{ "mpg", "mpegps" },
{ "mkv", "mkv" },
{ "avi", "avi" },
}
for _, c in CASES do
local key, format = c[1], c[2]
local data = Base64.decode(Fx[key]) :: buffer
local v, err = F.video.open(data)
t:check(v ~= nil, key .. ": opens: " .. tostring(err))
if v then
t:eq(v.format, format, key .. ": format")
t:eq(v.codec, "mpeg2", key .. ": codec")
t:check(v.width == Prog.width and v.height == Prog.height, key .. ": size")
local frames, exact = 0, 0
while true do
local f, ferr = v:nextFrame()
t:check(ferr == nil, key .. ": frame error " .. tostring(ferr))
if not f then
break
end
frames += 1
local ref = Fx.crcs[frames]
if ref and lumaCrc(f.image) == ref[1] then
exact += 1
end
end
t:eq(frames, #Fx.crcs, key .. ": frame count")
-- the frames ffmpeg's encoder left with an uncoded macroblock are concealed differently (tests/codecs/mpeg2)
t:check(exact >= frames - 2, string.format("%s: %d of %d frames equal ffmpeg's", key, exact, frames))
v:seek(0.4)
local f = v:nextFrame()
t:check(f ~= nil and math.abs(f.pts - 0.4) < 0.05, key .. ": seek")
t:note(" %-5s %-7s %d frames, %d bit-exact", key, format, frames, exact)
end
end
-- the elementary stream itself
do
local v, err = F.video.open(Base64.decode(Prog.file) :: buffer)
t:check(v ~= nil and v.codec == "mpeg2", "m2v: opens as mpeg2: " .. tostring(err))
if v then
local n = 0
while v:nextFrame() do
n += 1
end
t:eq(n, Prog.frames, "m2v: frame count")
end
end
t:fuzz("open", function(b: buffer)
local v = F.video.open(b)
if v then
for _ = 1, 3 do
v:nextFrame()
end
end
return v
end, { Base64.decode(Fx.ts) :: buffer, Base64.decode(Fx.mpg) :: buffer }, { mutations = 30, garbage = 5 })
t:done()
+211
View File
@@ -0,0 +1,211 @@
-- video/ogv tests: Ogg Theora files from ffmpeg (libtheora + libvorbis; tools/fixtures/theora.py): sniffing (Theora
-- BOS pages, plain Ogg Vorbis left to the audio formats), tracks, granule times, every frame through F.video.open
-- bit-exact with ffmpeg's (Adler-32 of yuv420p, its framecrc), an empty packet (a repeated frame), the Vorbis track
-- through the api's audio hook against ffmpeg's decode, tags, seeking, remuxing (ogv -> ogv, mkv -> ogv, ogv -> mkv)
-- read back, errors and the fuzz no-throw pass.
local T = require("@tests/T")
local C = require("@tests/video/_common")
local F = require("@formats")
local Ogv = require("@formats/video/ogv")
local Theora = require("@formats/codecs/video/Theora")
local AudioWrap = require("@formats/containers/AudioWrap")
local Bytes = require("@formats/core/Bytes")
local Base64 = require("@formats/core/Base64")
local Adler32 = require("@formats/core/Adler32")
local Err = require("@formats/core/Err")
local t = T.suite("ogv")
local AV = require("@tests/gen/theora_av") :: any
local Q0 = require("@tests/gen/theora_q0") :: any
local DUPE = require("@tests/gen/theora_dupe") :: any
local MKV = require("@tests/gen/theora_mkv") :: any
local OPUS = require("@tests/gen/theora_opus") :: any
local FLAC = require("@tests/gen/theora_flac") :: any
local function file(fx: any): buffer
return Base64.decode(fx.file) :: buffer
end
-- every frame of a VideoDecoder against ffmpeg's framecrc (yuv420p, keyed by frame number); frames ffmpeg does not
-- show (empty packets) must repeat the previous one
local function frames(v: any, fx: any, label: string, fps: number)
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
local n, bad, shown, prev = 0, 0, 0, nil :: number?
while true do
local f, err = v:nextFrame()
if not f then
t:check(err == nil, label .. ": decode error " .. tostring(err))
break
end
n += 1
local c = Adler32.of(f.image.pixels, nil, nil, 0)
local w = want[math.floor(f.pts * fps + 0.5)]
if w then
shown += 1
if c ~= w then
bad += 1
end
elseif c ~= prev then
bad += 1
end
prev = c
end
t:eq(bad, 0, label .. ": frames equal to ffmpeg's (" .. n .. " frames)")
t:eq(shown, #fx.frames, label .. ": every frame ffmpeg shows")
return n
end
-- 1. contract and sniffing
t:eq(Ogv.name, "ogv", "name")
t:eq(Ogv.category, "video", "category")
t:check(table.find(Ogv.extensions, "ogv") ~= nil, "ogv extension")
t:eq(Ogv.sniff(Bytes.reader(file(AV))), 1, "sniff: Theora + Vorbis")
t:eq(Ogv.sniff(Bytes.reader(file(Q0))), 1, "sniff: Theora")
t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("OggS\0\2" .. string.rep("\0", 40)))), 0, "sniff: an Ogg page without Theora")
t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff: not Ogg")
-- 2. Theora + Vorbis through the api
local v, err = F.video.open(file(AV))
t:check(v ~= nil, "open: " .. tostring(err))
if v then
t:eq(v.format, "ogv", "format")
t:eq(v.codec, "theora", "codec")
t:eq(v.width * 1000 + v.height, 160120, "size")
t:eq(v.frameRate, 25, "frame rate")
local dmx = v.demuxer :: any
t:eq(#dmx.tracks, 2, "two tracks")
local vt, at = dmx:track("video"), dmx:track("audio")
t:check(vt and vt.codec == "theora" and vt.timescale == 25, "video track")
t:check(at and at.codec == "vorbis" and at.sampleRate == 44100 and at.channels == 2, "audio track")
t:check(vt and vt.config and #(Theora.splitConfig(vt.config) or {}) == 3, "video config: three Xiph-laced headers")
t:check(math.abs(v.duration - 1) < 0.05, "duration " .. v.duration)
t:check(v.meta.tags and v.meta.tags.encoder ~= nil, "tags from the comment header")
local first = dmx:get(vt.id, 1)
t:check(first and first.keyframe and first.pts == 0, "first packet: a keyframe at 0")
t:check(not dmx:get(vt.id, 2).keyframe, "second packet: an inter frame")
frames(v, AV, "av", 25)
local pcm = Base64.decode(AV.pcm) :: buffer
C.audio(t, v, { pcm = buffer.tostring(pcm) }, "av", false, 20)
-- seeking
v:seek(0.5)
local f = v:nextFrame()
t:check(f ~= nil and f.pts >= 0.5 - 1e-6 and f.pts < 0.6, "seek 0.5 -> " .. tostring(f and f.pts))
if f then
local want = nil
for _, w in AV.frames do
if w[1] == math.floor(f.pts * 25 + 0.5) then
want = w[2]
end
end
t:eq(Adler32.of(f.image.pixels, nil, nil, 0), want, "the frame after seeking equals ffmpeg's")
end
-- remux ogv -> ogv
v:reset()
local out, rerr = F.save(v, nil, { format = "ogv" })
t:check(out ~= nil, "remux: " .. tostring(rerr))
if out then
t:eq(Ogv.sniff(Bytes.reader(out)), 1, "remux: sniff")
local v2 = F.video.open(out) :: any
t:check(v2 ~= nil and #v2.demuxer.tracks == 2, "remux: two tracks")
if v2 then
frames(v2, AV, "remux", 25)
C.audio(t, v2, { pcm = buffer.tostring(pcm) }, "remux", false, 20)
end
end
-- remux ogv -> mkv (V_THEORA)
v:reset()
local mk, merr = F.save(v, nil, { format = "mkv" })
t:check(mk ~= nil, "to mkv: " .. tostring(merr))
if mk then
local v3 = F.video.open(mk) :: any
t:check(v3 ~= nil and v3.codec == "theora", "to mkv: Theora track")
if v3 then
frames(v3, AV, "to mkv", 25)
end
end
end
-- 3. Opus and FLAC audio tracks (FLAC: exact)
for _, c in { { OPUS, "opus", 48000 }, { FLAC, "flac", 22050 } } do
local fx, codec, rate = c[1], c[2], c[3]
local vd, e = F.video.open(file(fx))
t:check(vd ~= nil, codec .. ": open: " .. tostring(e))
if vd then
local at = (vd.demuxer :: any):track("audio")
t:check(at and at.codec == codec and at.sampleRate == rate and at.channels == 1, codec .. ": audio track")
frames(vd, fx, codec, 25)
C.audio(t, vd, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, codec, codec == "flac", 20)
if codec == "opus" then
vd:reset()
local out = F.save(vd, nil, { format = "ogv" })
local v2 = out and F.video.open(out) :: any
t:check(v2 ~= nil and v2.audio ~= nil, "opus: remux keeps the audio")
if v2 then
C.audio(t, v2, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, "opus remux", false, 20)
end
end
end
end
-- 4. an empty packet: a repeated frame with its own time
do
local vd = Ogv.open(Bytes.reader(file(DUPE))) :: any
local n = 0
local prev, dupAt = nil, nil
while true do
local f = vd:nextFrame()
if not f then
break
end
n += 1
local c = Adler32.of(f.image.pixels, nil, nil, 0)
if n == 6 then
dupAt = f.pts
t:eq(c, prev, "dupe: frame 6 repeats frame 5")
end
prev = c
end
t:eq(n, #DUPE.frames + 1, "dupe: one frame per packet")
t:check(dupAt ~= nil and math.abs((dupAt :: number) - 0.2) < 1e-6, "dupe: its time slot (0.2 s)")
t:check(vd.audio == nil and vd.audioError == nil, "no audio track, no audio error")
end
-- 5. Theora in Matroska -> ogv
do
local mv = F.video.open(file(MKV)) :: any
local out, e = F.save(mv, nil, { format = "ogv" })
t:check(out ~= nil, "mkv -> ogv: " .. tostring(e))
if out then
local v2 = Ogv.open(Bytes.reader(out)) :: any
frames(v2, MKV, "mkv -> ogv", 25)
end
end
-- 6. not Theora: plain Ogg Vorbis goes to the audio format, writing other codecs fails
do
local vd = Ogv.open(Bytes.reader(file(AV))) :: any
local at = vd.demuxer:track("audio")
local ogg = AudioWrap.wrap(vd.demuxer, at) :: buffer
t:eq(Ogv.sniff(Bytes.reader(ogg)), 0, "sniff: Ogg Vorbis is not ogv")
local a = F.load(ogg, { name = "x.ogg" })
t:check(a ~= nil and a.kind == "audio", "F.load of Ogg Vorbis named .ogg: audio")
local v4, e4 = Ogv.open(Bytes.reader(ogg))
t:check(v4 ~= nil and v4.decodeError ~= nil, "an Ogg without video: opens, frames UNSUPPORTED (" .. tostring(e4) .. ")")
local _, ee = Ogv.encode(Ogv.open(Bytes.reader(ogg)) :: any)
t:check(ee ~= nil and ee.code == Err.UNSUPPORTED, "encode without Theora: UNSUPPORTED")
local _, eg = Ogv.open(Bytes.reader(buffer.fromstring("OggS garbage")))
t:check(eg ~= nil, "garbage: an error")
local cut = buffer.create(5000)
buffer.copy(cut, 0, file(Q0), 0, 5000)
local vc = Ogv.open(Bytes.reader(cut))
t:check(vc ~= nil, "a truncated file opens")
end
-- 7. fuzz
t:fuzz("open", C.fuzzOpen(Ogv), { buffer.tostring(file(Q0)) }, { mutations = 16, garbage = 50 })
t:done()
+180
View File
@@ -0,0 +1,180 @@
-- video/smk tests: Smacker files encoded by the fixture script (SMK2 and SMK4, every block type and run, the trees'
-- escape cache, palette updates, a ring frame, ms and 10 us frame times; packed 16-bit stereo / 8-bit mono / 16-bit
-- mono / 8-bit stereo audio and raw s16le / u8 tracks): every video frame and every audio track equal ffmpeg's
-- decode (CRC-32 of rgba / f32le), audio seeking, errors, and the fuzz pass on the container, the video codec and the
-- audio codec. Fixtures: tools/fixtures/smk.py.
local T = require("@tests/T")
local F = require("@formats")
local Smk = require("@formats/video/smk")
local SmkAudio = require("@formats/video/smk/Audio")
local Legacy = require("@formats/codecs/video/Legacy")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/smk_cases")
local t = T.suite("smk")
t:eq(Smk.name, "smk", "name")
t:eq(Smk.category, "video", "category")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
-- every frame of an audio Decoder -> f32 buffer, frames
local function drain(dec: any): (buffer, number)
local chunks, total = {}, 0
while true do
local b, n = dec:read(1000)
if n == 0 then
break
end
table.insert(chunks, { b, n })
total += n
end
local out = buffer.create(total * dec.channels * 4)
local at = 0
for _, c in chunks do
buffer.copy(out, at, c[1], 0, c[2] * dec.channels * 4)
at += c[2] * dec.channels * 4
end
return out, total
end
for _, c in Fx do
local label = c.name
t:check(Smk.sniff(reader(c.data)) == 1, label .. ": sniff")
t:eq(F.detect(buffer.fromstring(c.data)), "smk", label .. ": detect")
local v, err = F.video.open(buffer.fromstring(c.data))
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
t:eq(v.codec, "smackvid", label .. ": codec")
t:check(v.width == c.width and v.height == c.height, label .. ": size")
t:check(math.abs(v.frameRate - c.rate) < 1e-6, label .. ": frame rate " .. v.frameRate)
local want = if c.ring then #c.frames - 1 else #c.frames
local n, bad = 0, 0
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": " .. tostring(ferr))
break
end
n += 1
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad))
v:seek(0.2)
local f = v:nextFrame()
local k = math.floor(0.2 * c.rate - 1e-9) + 2
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k)
-- audio: the first track through the VideoDecoder, every track through Smk.openAudio
if #c.audio > 0 then
t:check(v.audio ~= nil, label .. ": audio " .. tostring(v.audioError))
end
local tracks = {}
for _, tr in v.demuxer.tracks do
if tr.kind == "audio" then
table.insert(tracks, tr)
end
end
t:eq(#tracks, #c.audio, label .. ": audio tracks")
for i, a in c.audio do
local tr = tracks[i]
t:eq(tr.codec, a.codec, label .. ": audio " .. i .. " codec")
local dec, aerr = Smk.openAudio(v.demuxer, tr)
t:check(dec ~= nil, label .. ": audio " .. i .. ": " .. tostring(aerr))
if dec then
t:check(dec.sampleRate == a.rate and dec.channels == a.channels, label .. ": audio " .. i .. " format")
local pcm, frames = drain(dec)
t:eq(frames, a.frames, label .. ": audio " .. i .. " frames")
t:eq(Crc32.of(pcm), a.crc, label .. ": audio " .. i .. " equals ffmpeg's")
dec:seek(0)
local again = drain(dec)
t:eq(Crc32.of(again), a.crc, label .. ": audio " .. i .. " after seek(0)")
dec:seek(0.3)
local tail, rest = drain(dec)
local skip = a.frames - rest
t:check(math.abs(skip - 0.3 * a.rate) <= 1, label .. ": audio " .. i .. " seek(0.3) at frame " .. skip)
local same = buffer.len(tail) > 0
for q = 0, math.min(buffer.len(tail), 4000) - 4, 4 do
if buffer.readu32(tail, q) ~= buffer.readu32(pcm, skip * a.channels * 4 + q) then
same = false
break
end
end
t:check(same, label .. ": audio " .. i .. " seek(0.3) samples")
end
end
if c.ring then
local v2 = Smk.open(reader(c.data), { ringFrame = true })
local m = 0
while v2 and v2:nextFrame() do
m += 1
end
t:eq(m, #c.frames, label .. ": with the ring frame")
end
end
end
-- errors
do
local _, e = Smk.open(reader(string.sub(Fx[1].data, 1, 60)))
t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED")
local _, e2 = Smk.open(reader("SMK3" .. string.sub(Fx[1].data, 5)))
t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT")
t:eq(Smk.sniff(reader("SMK3" .. string.sub(Fx[1].data, 5))), 0, "bad magic: no sniff")
local _, e3 = Smk.open(reader(Fx[1].data), { maxPixels = 100 })
t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT")
local _, e4 = Smk.open(reader(string.sub(Fx[1].data, 1, 200)))
t:check(e4 ~= nil and e4.code == Err.TRUNCATED, "trees past the end: TRUNCATED")
end
-- fuzz: the container, the video codec (native, no pcall in between) and the audio codec
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("open", function(b: buffer)
local v = Smk.open(Bytes.reader(b))
if v then
for _ = 1, 4 do
if not v:nextFrame() then
break
end
end
if v.audio then
v.audio:read(500)
end
end
return v
end, samples, { mutations = 16, garbage = 40, keepHeader = 4 })
local S, P = Legacy.Smacker, Legacy.Picture
for _, c in { Fx[1], Fx[2] } do
local d = Smk.demux(reader(c.data))
local tr = d.tracks[1]
local packets = {}
for k = 1, math.min(3, d:count(1)) do
table.insert(packets, d:get(1, k).data)
end
t:fuzz(c.name .. " trees", function(b: buffer)
return S.trees(b)
end, { tr.config }, { mutations = 30, garbage = 30, keepHeader = 16 })
local trees = assert(S.trees(tr.config))
t:fuzz(c.name .. " frames", function(b: buffer)
return S.decode(P.new(c.width, c.height, true, 4, 4), b, trees, tr.codecTag == "SMK4")
end, packets, { mutations = 30, garbage = 30 })
for _, at in d.tracks do
if at.kind == "audio" then
local ap = {}
for k = 1, math.min(2, d:count(at.id)) do
table.insert(ap, d:get(at.id, k).data)
end
t:fuzz(c.name .. " audio " .. at.codec, function(b: buffer)
return SmkAudio.decode(b, at.channels, at.bitsPerSample, at.codec == "smackaudio")
end, ap, { mutations = 20, garbage = 20 })
end
end
end
t:done()
+156
View File
@@ -1203,3 +1203,159 @@ do
Qb.decode(Bytes.reader(qb))
end)
end
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
do
local Jpeg = require("@formats/codecs/image/Jpeg")
local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local Base64 = require("@formats/core/Base64")
local Types = require("@formats/Types")
local MB = require("@tests/gen/mjpeg_bench")
local M1 = require("@tests/gen/mpeg1_bench")
-- best of n runs of f (which handles `frames` frames): ms per frame and frames per second
local function fps(label: string, n: number, frames: number, f: () -> ())
f()
local dt = math.huge
for _ = 1, n do
local t0 = os.clock()
f()
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt))
end
for _, c in MB.frames do
local b = Base64.decode(c.data) :: buffer
local img = assert(Jpeg.decode(b, 0, nil, { yuv = true }))
assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG")
fps("mjpeg decode yuv " .. c.name, 10, 1, function()
Jpeg.decode(b, 0, nil, { yuv = true })
end)
fps("mjpeg decode rgba " .. c.name, 10, 1, function()
Jpeg.decode(b)
end)
end
for _, s in MB.sources do
local img = Types.Image.new(s.width, s.height, "yuv420p")
img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer))
fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function()
Jpeg.encode(img, { quality = 85 })
end)
end
-- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1)
local function mpeg1(tag: string)
for _, s in M1 do
local file = Base64.decode(s.file) :: buffer
for _, rgba in { false, true } do
fps(string.format("mpeg1 decode %s %dx%d%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
end
-- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2)
local M2 = require("@tests/gen/mpeg2_bench")
local function mpeg2(tag: string)
for _, s in M2 do
local file = Base64.decode(s.file) :: buffer
fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = false })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
jitTune(false)
mpeg1("")
mpeg2("")
if runtime == "luajit" then
jitTune(true)
mpeg1(" (jit tuned)")
mpeg2(" (jit tuned)")
jitTune(false)
end
end
do
-- ------------------------------------------------------------------------------------- ws-video2-theora: fps
-- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static:
-- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode +
-- image() (the yuv420p copy every VideoDecoder frame makes)
local Theora = require("@formats/codecs/video/Theora")
local Ogg = require("@formats/containers/Ogg")
local Base64 = require("@formats/core/Base64")
local TB = require("@tests/gen/theora_bench")
local function run(tag: string)
for _, c in TB do
local d = Ogg.open(Base64.decode(c.file) :: buffer)
local hdrs, data = {}, {}
for p in d:packets(d:find("theora")) do
table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p))
end
for _, image in { false, true } do
local n = c.width * c.height * 3 // 2 * #data
local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function()
local dec = Theora.new(hdrs) :: any
for _, p in data do
dec:decode(p)
if image then
dec:image()
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps
do
-- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240
-- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks);
-- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second)
local F = require("@formats")
local LB = require("@tests/gen/legacy_bench")
local cases = table.clone(LB)
table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 })
table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 })
for _, c in cases do
local data = buffer.fromstring(c.data)
local frames = 0
local dt = math.huge
for _ = 1, 3 do
local t0 = os.clock()
local v = assert(F.video.open(data, { audio = false }))
frames = 0
while v:nextFrame() do
frames += 1
end
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt))
end
local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data)))
local a = assert(v.audio)
local t0 = os.clock()
local n = 0
while true do
local _, got = a:read(4096)
if got == 0 then
break
end
n += got
end
local dt = os.clock() - t0
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
end
+375
View File
@@ -0,0 +1,375 @@
# Shared helpers for the legacy video fixture generators (legacy.py), loaded by path: tiny AVI and QuickTime MOV
# writers (one video track, constant frame rate) for streams encoded here, and small encoders for what ffmpeg cannot
# encode: QuickTime RLE at depths 1 / 2 / 4 / 8, Microsoft Video 1 at 8 bits, Cinepak at 8 bits (palettised).
import struct
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def be16(v):
return struct.pack(">H", v & 0xFFFF)
def be32(v):
return struct.pack(">I", v & 0xFFFFFFFF)
# ---------------------------------------------------------------------------------------------------- AVI
def _ck(cid, body):
return cid + le32(len(body)) + body + (b"\0" if len(body) & 1 else b"")
def _lst(kind, body):
return b"LIST" + le32(len(body) + 4) + kind + body
def bitmapinfo(w, h, bits, fourcc, palette=None):
"""BITMAPINFOHEADER (+ palette: a list of (r, g, b) stored as B, G, R, 0)"""
n = len(palette) if palette else 0
out = le32(40) + le32(w) + le32(h) + le16(1) + le16(bits) + fourcc + le32(w * h * max(1, bits // 8)) + \
le32(0) + le32(0) + le32(n) + le32(0)
for r, g, b in palette or []:
out += bytes([b, g, r, 0])
return out
def avi(w, h, fourcc, strf, frames, keys, fps=10):
"""an AVI file: one video stream, frames = [bytes], keys = [bool]"""
n = len(frames)
avih = le32(1000000 // fps) + le32(0) + le32(0) + le32(0x10) + le32(n) + le32(0) + le32(1) + \
le32(max(len(f) for f in frames)) + le32(w) + le32(h) + bytes(16)
strh = b"vids" + fourcc + le32(0) + le16(0) + le16(0) + le32(0) + le32(1) + le32(fps) + le32(0) + le32(n) + \
le32(max(len(f) for f in frames)) + struct.pack("<i", -1) + le32(0) + struct.pack("<hhhh", 0, 0, w, h)
hdrl = _lst(b"hdrl", _ck(b"avih", avih) + _lst(b"strl", _ck(b"strh", strh) + _ck(b"strf", strf)))
movi = b""
idx = b""
for f, k in zip(frames, keys):
idx += b"00dc" + le32(0x10 if k else 0) + le32(4 + len(movi)) + le32(len(f))
movi += _ck(b"00dc", f)
body = b"AVI " + hdrl + _lst(b"movi", movi) + _ck(b"idx1", idx)
return b"RIFF" + le32(len(body)) + body
# ---------------------------------------------------------------------------------------------------- MOV
def _box(t, body):
return be32(8 + len(body)) + t + body
def qt_entry(fourcc, w, h, depth, ctab_id=0xFFFF, colors=None):
"""a QuickTime video sample description; colors = [(r, g, b)] makes a colour table (ctab_id 0)"""
body = bytes(6) + be16(1) + be16(0) + be16(0) + b"appl" + be32(0) + be32(512) + be16(w) + be16(h) + \
be32(72 << 16) + be32(72 << 16) + be32(0) + be16(1) + bytes([4]) + b"test" + bytes(27) + be16(depth)
if colors is not None:
body += be16(0) + be32(0) + be16(0x8000) + be16(len(colors) - 1)
for i, (r, g, b) in enumerate(colors):
body += be16(i) + bytes([r, r, g, g, b, b])
else:
body += be16(ctab_id)
return _box(fourcc, body)
def mov(w, h, entry, frames, keys, fps=10):
"""a QuickTime file: one video track with the sample description `entry`"""
scale, delta = fps * 100, 100
n = len(frames)
ftyp = _box(b"ftyp", b"qt " + be32(0x200) + b"qt ")
mdat_off = len(ftyp) + 8
offs, pos = [], mdat_off
for f in frames:
offs.append(pos)
pos += len(f)
mdat = _box(b"mdat", b"".join(frames))
matrix = be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x40000000)
dur = n * delta
mvhd = _box(b"mvhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be32(0x10000) + be16(0x100) +
bytes(10) + matrix + bytes(24) + be32(2))
tkhd = _box(b"tkhd", be32(3) + be32(0) + be32(0) + be32(1) + be32(0) + be32(dur) + bytes(8) + be16(0) + be16(0) +
be16(0) + be16(0) + matrix + be32(w << 16) + be32(h << 16))
mdhd = _box(b"mdhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be16(0) + be16(0))
hdlr = _box(b"hdlr", be32(0) + b"mhlr" + b"vide" + bytes(12) + b"\x05Video")
vmhd = _box(b"vmhd", be32(1) + bytes(8))
dinf = _box(b"dinf", _box(b"dref", be32(0) + be32(1) + _box(b"alis", be32(1))))
stsd = _box(b"stsd", be32(0) + be32(1) + entry)
stts = _box(b"stts", be32(0) + be32(1) + be32(n) + be32(delta))
sync = [i + 1 for i, k in enumerate(keys) if k]
stss = _box(b"stss", be32(0) + be32(len(sync)) + b"".join(be32(i) for i in sync))
stsc = _box(b"stsc", be32(0) + be32(1) + be32(1) + be32(1) + be32(1))
stsz = _box(b"stsz", be32(0) + be32(0) + be32(n) + b"".join(be32(len(f)) for f in frames))
stco = _box(b"stco", be32(0) + be32(n) + b"".join(be32(o) for o in offs))
stbl = _box(b"stbl", stsd + stts + stss + stsc + stsz + stco)
minf = _box(b"minf", vmhd + dinf + stbl)
mdia = _box(b"mdia", mdhd + hdlr + minf)
trak = _box(b"trak", tkhd + mdia)
moov = _box(b"moov", mvhd + trak)
return ftyp + mdat + moov
# ---------------------------------------------------------------------------------------------------- pictures
def index_frames(w, h, n, colors, seed=1):
"""n palettised pictures (rows of indexes < colors): bands, a moving square, a noisy patch; most of each frame
stays the same as the previous one (inter-frame codecs get skips)"""
import random
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[((x // 7 + y // 5) % colors) for x in range(w)] for y in range(h)]
sx, sy = (t * 5) % max(1, w - 12), (t * 3) % max(1, h - 10)
for y in range(sy, min(h, sy + 10)):
for x in range(sx, min(w, sx + 12)):
img[y][x] = (t + 1) % colors
for y in range(h // 2, min(h, h // 2 + 6)):
for x in range(w // 3, min(w, w // 3 + 9)):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def palette(n, seed=7):
import random
rnd = random.Random(seed)
return [(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- QuickTime RLE
def _groups(row, per):
return [tuple(row[i:i + per]) for i in range(0, len(row), per)]
def _pack(group, bits):
out = bytearray()
per = 8 // bits
for i in range(0, len(group), per):
v = 0
for k in range(per):
v = (v << bits) | group[i + k]
out.append(v)
return bytes(out)
def qtrle_frame(img, prev, bits):
"""one 'rle ' frame at 1 / 2 / 4 / 8 bits (prev = the previous picture or None: changed line range only, with
skip codes inside lines)"""
h, w = len(img), len(img[0])
per = 16 if bits == 1 else 32 // bits # pixels per group
pw = (w + per - 1) // per * per
rows = [r + [0] * (pw - w) for r in img]
prow = [r + [0] * (pw - w) for r in prev] if prev else None
changed = [y for y in range(h) if not prow or rows[y] != prow[y]]
if not changed:
return be32(6) + be16(0)
y0, y1 = changed[0], changed[-1] + 1
body = bytearray()
for y in range(y0, y1):
g = _groups(rows[y], per)
pg = _groups(prow[y], per) if prow else None
if bits == 1:
# (skip, code) pairs: the first of a line has bit 7 set
first = True
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 127:
skip += 1
i += 1
if i >= len(g):
if first:
body += bytes([0x80 | skip, 0xFF])
first = False
break
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
sb = (0x80 if first else 0) | skip
first = False
if j > i:
body += bytes([sb, 256 - (j - i + 1)]) + _pack(g[i], 1)
i = j + 1
else:
k = i
while k < len(g) and k - i < 63 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
body += bytes([sb, k - i]) + b"".join(_pack(x, 1) for x in g[i:k])
i = k
if first:
body += bytes([0x80, 0xFF])
continue
line = bytearray([1])
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 250:
skip += 1
i += 1
if i >= len(g):
break
if skip:
line += bytes([0, skip + 1])
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
if j > i:
line += bytes([256 - (j - i + 1)]) + _pack(g[i], bits)
i = j + 1
else:
k = i
while k < len(g) and k - i < 127 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
line += bytes([k - i]) + b"".join(_pack(x, bits) for x in g[i:k])
i = k
line += b"\xff"
body += line
if bits == 1:
body += b"\x00\x00"
else:
body += b"\x00"
head = be16(8) + be16(y0) + be16(0) + be16(y1 - y0) + be16(0)
return be32(4 + len(head) + len(body)) + head + bytes(body)
# ---------------------------------------------------------------------------------------------------- MS Video 1
def _block(img, bx, by):
"""the 16 pixels of a block, MS Video 1 order: bottom row first, left to right"""
return [img[by * 4 + 3 - y][bx * 4 + x] for y in range(4) for x in range(4)]
def msvc8_frame(img, prev):
"""one 8-bit CRAM frame: skips for unchanged blocks, 1-colour, 2-colour or 8-colour blocks"""
h, w = len(img), len(img[0])
bw, bh = w // 4, h // 4
out = bytearray()
skip = 0
def flush():
nonlocal skip
while skip:
k = min(skip, 1023)
out.extend([k & 0xFF, 0x84 + (k >> 8)])
skip -= k
for by in range(bh - 1, -1, -1):
for bx in range(bw):
px = _block(img, bx, by)
if prev and px == _block(prev, bx, by):
skip += 1
continue
flush()
cols = sorted(set(px), key=lambda c: (-px.count(c), c))
if len(cols) == 1:
out.extend([px[0], 0x80])
elif len(cols) == 2:
c0 = px[15] # pixel 15's flag bit is 0: it takes colours[1]
c1 = cols[0] if cols[0] != c0 else cols[1]
flags = sum(1 << i for i in range(16) if px[i] == c1)
out.extend([flags & 0xFF, flags >> 8, c1, c0])
else:
# 8-colour: a pair per quadrant; pixel 12 and 15 take the first colour of their quadrant (flags >= 0x9000)
colours = [0] * 8
flags = 0
for q, (qx, qy) in enumerate([(0, 0), (2, 0), (0, 2), (2, 2)]):
ids = [(qy + y) * 4 + qx + x for y in range(2) for x in range(2)]
vals = [px[i] for i in ids]
key = {2: 12, 3: 15}.get(q)
a = px[key] if key is not None else sorted(set(vals), key=lambda c: (-vals.count(c), c))[0]
rest = [v for v in vals if v != a]
b = rest[0] if rest else a
base = ((qy & 2) << 1) + (qx & 2)
colours[base], colours[base + 1] = a, b
for i in ids:
if px[i] == a:
flags |= 1 << i
else:
px[i] = b
out.extend([flags & 0xFF, flags >> 8] + colours)
flush()
return bytes(out)
# ---------------------------------------------------------------------------------------------------- Cinepak (8-bit)
def cvid8_frame(img, prev, first):
"""one palettised Cinepak frame: one strip, a V1 codebook of 4-index entries (each a 2x2 square of one colour per
entry quarter) and a V4 codebook; blocks are V1 when their four 2x2 squares are uniform, else V4 (from the
codebook of 2x2 squares); inter frames skip unchanged blocks"""
h, w = len(img), len(img[0])
blocks = [(x, y) for y in range(0, h, 4) for x in range(0, w, 4)]
v1, v4 = {}, {}
def sq(x, y):
return (img[y][x], img[y][x + 1], img[y + 1][x], img[y + 1][x + 1])
plan = []
for (x, y) in blocks:
if prev is not None and all(img[y + j][x + i] == prev[y + j][x + i] for j in range(4) for i in range(4)):
plan.append(None)
continue
q = [sq(x, y), sq(x + 2, y), sq(x, y + 2), sq(x + 2, y + 2)]
if all(len(set(s)) == 1 for s in q) and len(v1) < 256:
e = (q[0][0], q[1][0], q[2][0], q[3][0])
v1.setdefault(e, len(v1))
plan.append(("v1", v1[e]))
else:
ids = []
for s in q:
if s not in v4 and len(v4) < 256:
v4[s] = len(v4)
ids.append(v4.get(s, 0))
plan.append(("v4", ids))
def book(cid, entries):
data = b"".join(bytes(e) for e, _ in sorted(entries.items(), key=lambda kv: kv[1]))
return bytes([cid]) + (4 + len(data)).to_bytes(3, "big") + data
chunks = b""
if v4:
chunks += book(0x24, v4)
if v1:
chunks += book(0x26, v1)
bits, data = [], bytearray()
inter = prev is not None
# flags (MSB first, 32 per word) are interleaved with the indexes in decode order
words = bytearray()
flagbuf = []
def flag(b):
flagbuf.append(b)
if len(flagbuf) == 1:
words.extend(b"FLAG") # placeholder, patched below
pos_stack.append(len(words) - 4)
if len(flagbuf) == 32:
patch()
pos_stack = []
def patch():
v = 0
for i, b in enumerate(flagbuf):
v |= b << (31 - i)
p = pos_stack.pop()
words[p:p + 4] = v.to_bytes(4, "big")
flagbuf.clear()
for item in plan:
if inter:
flag(0 if item is None else 1)
if item is None:
continue
flag(1 if item[0] == "v4" else 0)
if item[0] == "v1":
words.append(item[1])
else:
words.extend(item[1])
if flagbuf:
patch()
vid = (0x31 if inter else 0x30)
chunks += bytes([vid]) + (4 + len(words)).to_bytes(3, "big") + bytes(words)
strip = bytes([0x10 if first else 0x11]) + (12 + len(chunks)).to_bytes(3, "big") + be16(0) + be16(0) + be16(h) + \
be16(w) + chunks
size = 10 + len(strip)
return bytes([0]) + size.to_bytes(3, "big") + be16(w) + be16(h) + be16(1) + strip
+7 -3
View File
@@ -1,8 +1,8 @@
# Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them):
# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG +
# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of
# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT /
# ASS subtitles.
# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a
# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py
# (song_basic), and SRT / WebVTT / ASS subtitles.
# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } }
import importlib.util, os, struct, tempfile
@@ -91,6 +91,9 @@ def generate(ctx):
"-c:a", "aac", "-b:a", "64k"]),
("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]),
("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]),
("clip.ts", ["-c:v", "mpeg2video", "-b:v", "300k", "-g", "5", "-bf", "2", "-vf", "setfield=tff",
"-flags", "+ilme+ildct",
"-c:a", "mp2", "-b:a", "64k"]),
):
out = os.path.join(d, name)
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out])
@@ -107,6 +110,7 @@ def generate(ctx):
"mp4Bytes": "clip.mp4",
"aviBytes": "clip.avi",
"webmBytes": "clip.webm",
"tsBytes": "clip.ts",
"midiBytes": "tune.mid",
"sf2Bytes": "bank.sf2",
"modBytes": "song.mod",
+33
View File
@@ -0,0 +1,33 @@
# Docs inputs for the legacy video sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them):
# a 64x48 FLC (tools/fixtures/fli.py's encoder), a 64x48 SMK4 with a packed stereo and a raw mono audio track
# (tools/fixtures/smk.py's encoder) and a 64x48 Cinepak MOV from ffmpeg.
# tests/gen/docs_legacy.luau { files = { [name] = bytes }, vars = { flcBytes = "anim.flc", ... } }
import importlib.util, os, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/fli.py", "tools/fixtures/smk.py", "tools/fixtures/_video.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_legacy_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check")
fli = load(ctx, "fixtures/fli")
smk = load(ctx, "fixtures/smk")
v = load(ctx, "fixtures/_video")
files = {}
w, h, n = 64, 48, 10
imgs = fli.idx_frames(w, h, n, 256, 5)
frames = [fli.frame([fli.color([(0, fli.pal(256, 5, False))], False), fli.brun([[bytes([x]) for x in r] for r in imgs[0]], 1, True)])]
frames += [fli.frame([fli.ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
files["anim.flc"] = fli.file(0xAF12, w, h, 8, 100, frames)
files["intro.smk"] = smk.smk_file(4, 64, 48, 10, 100, [("packed", 22050, 2, 16), ("raw", 11025, 1, 8)], False, 7)
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "cinepak.mov")
v.ffmpeg(["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "cinepak", out])
files["cinepak.mov"] = open(out, "rb").read()
dc.emit_inputs(ctx, files, {"flcBytes": "anim.flc", "smkBytes": "intro.smk", "cinepakBytes": "cinepak.mov"})
+20
View File
@@ -0,0 +1,20 @@
# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a
# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video.
# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "clip.ogv")
subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora",
"-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True)
files = {"clip.ogv": open(out, "rb").read()}
dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"})
+401
View File
@@ -0,0 +1,401 @@
# FLI / FLC fixtures (tools/fixtures.py): ffmpeg cannot write FLICs, so this encodes them (every chunk type: COLOR_64,
# COLOR_256, BRUN, LC / DELTA_FLI, SS2 / DELTA_FLC with line skips and the last-byte opcode, BLACK, COPY, PSTAMP; a
# prefix chunk and a ring frame; 15-bit FLC, 16-bit DTA and 24-bit FLC with BRUN / DTA_BRUN / DELTA / DTA_LC / COPY /
# DTA_COPY) and uses ffmpeg's decode as the reference (CRC-32 of each frame as rgba).
# tests/gen/fli_cases.luau { { name, data, width, height, depth, rate, frames = { crc } } }
import importlib.util, os, random, struct, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py"]
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def s8(v):
return v & 0xFF
def chunk(typ, body):
if len(body) & 1:
body += b"\0"
return le32(6 + len(body)) + le16(typ) + body
def frame(chunks, magic=0xF1FA):
body = b"".join(chunks)
return le32(16 + len(body)) + le16(magic) + le16(len(chunks)) + bytes(8) + body
# ---------------------------------------------------------------------------------------------------- chunks
def color(entries, six):
"""COLOR_64 / COLOR_256: entries = [(skip, [(r, g, b), ...])]"""
out = le16(len(entries))
for skip, cols in entries:
out += bytes([skip, len(cols) & 0xFF])
for c in cols:
out += bytes(c)
return chunk(11 if six else 4, out)
def runs(seq, maxrun=127):
"""split a sequence into ('rep', value, n) and ('lit', [values]) pieces"""
out, i = [], 0
while i < len(seq):
j = i
while j + 1 < len(seq) and seq[j + 1] == seq[i] and j - i + 1 < maxrun:
j += 1
if j - i >= 2:
out.append(("rep", seq[i], j - i + 1))
i = j + 1
else:
k = i
while k < len(seq) and k - i < maxrun and not (k + 2 < len(seq) and seq[k] == seq[k + 1] == seq[k + 2]):
k += 1
k = max(k, i + 1)
out.append(("lit", seq[i:k]))
i = k
return out
def brun_line(units, unit_bytes):
"""BRUN line body: > 0 repeat, < 0 literal (units are byte strings of unit_bytes each)"""
out = bytes([0])
for p in runs(units):
if p[0] == "rep":
out += bytes([p[2]]) + p[1]
else:
out += bytes([s8(-len(p[1]))]) + b"".join(p[1])
return out
def brun(img, bpp, pixel_runs, typ=15):
lines = b""
for row in img:
if pixel_runs:
units = [row[x] for x in range(len(row))]
else:
flat = b"".join(row)
units = [flat[i:i + 1] for i in range(len(flat))]
lines += brun_line(units, bpp)
return chunk(typ, lines)
def lc(img, prev):
"""DELTA_FLI (LC): first changed line, line count, per line (skip, run) packets on bytes"""
h, w = len(img), len(img[0])
ch = [y for y in range(h) if img[y] != prev[y]]
if not ch:
return chunk(12, le16(0) + le16(0))
y0, y1 = ch[0], ch[-1] + 1
out = le16(y0) + le16(y1 - y0)
for y in range(y0, y1):
row, prow = img[y], prev[y]
packets = []
x = 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
seg = [bytes([v]) for v in row[x:e]]
pieces = runs(seg)
first = True
for p in pieces:
sk = skip if first else 0
first = False
if p[0] == "rep":
packets.append(bytes([sk, s8(-p[2])]) + p[1])
else:
packets.append(bytes([sk, len(p[1])]) + b"".join(p[1]))
x = e
out += bytes([len(packets)]) + b"".join(packets)
return chunk(12, out)
def ss2(img, prev, last_byte=False):
"""DELTA_FLC (SS2) on 8-bit pixels: word packets, line-skip words, the last-byte opcode on odd lines"""
h, w = len(img), len(img[0])
out = b""
count = 0
skip_lines = 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body = b""
packets = 0
lastop = last_byte and y % 2 == 1 and row[w - 1] != prow[w - 1]
ww = w - (1 if lastop else 0)
words = [bytes(row[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
pwords = [bytes(prow[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
i = 0
while i < len(words):
skip = 0
while i < len(words) and words[i] == pwords[i] and skip < 127:
skip += 1
i += 1
if i >= len(words):
break
e = i
while e < len(words) and words[e] != pwords[e] and e - i < 127:
e += 1
first = True
for p in runs(words[i:e]):
sk = skip * 2 if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
i = e
if lastop:
out += le16(0x8000 | row[w - 1])
out += le16(packets) + body
count += 1
return chunk(7, le16(count) + out)
def delta_deep(img, prev, bpp, typ=7):
"""DELTA / DTA_LC on 15/16/24-bit pixels: negative words skip lines, packets (skip pixels, run)"""
h, w = len(img), len(img[0])
out, count, skip_lines = b"", 0, 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body, packets, x = b"", 0, 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
first = True
for p in runs(row[x:e]):
sk = skip if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
x = e
out += le16(packets) + body
count += 1
return chunk(typ, le16(count) + out)
def copy8(img):
w = len(img[0])
pad = (w + 3) // 4 * 4 - w
return le32(6 + len(img) * (w + pad)) + le16(16) + b"".join(bytes(r) + bytes(pad) for r in img)
def copy_deep(img, bpp, typ=16):
w = len(img[0])
body = b"".join(b"".join(r) + (bytes(bpp) if w % 2 else b"") for r in img)
return le32(6 + len(body)) + le16(typ) + body
# ---------------------------------------------------------------------------------------------------- pictures
def idx_frames(w, h, n, colors, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[(x // 6 + y // 4 + (t // 4)) % colors for x in range(w)] for y in range(h)]
sx, sy = (t * 7) % (w - 16), (t * 3) % (h - 12)
for y in range(sy, sy + 12):
for x in range(sx, sx + 16):
img[y][x] = (200 + t) % colors
for y in range(h // 2, h // 2 + 4):
for x in range(w // 2, w // 2 + 10):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def deep_frames(w, h, n, bpp, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = []
for y in range(h):
row = []
for x in range(w):
v = ((x * 37 + y * 11 + t * 3) // 8) & 0x7FFF if bpp == 2 else ((x * 4) & 255, (y * 5) & 255, (t * 20) & 255)
if 10 + t <= x < 26 + t and 8 <= y < 20:
v = 0x7C00 if bpp == 2 else (250, 10, 10)
if bpp == 2 and h // 2 <= y < h // 2 + 3 and w // 2 <= x < w // 2 + 7:
v = rnd.randrange(65536)
row.append(struct.pack("<H", v) if bpp == 2 else bytes([v[2], v[1], v[0]]))
img.append(row)
out.append(img)
return out
def header(typ, frames, w, h, depth, speed, oframes=(0, 0)):
hd = bytearray(128)
hd[4:6] = le16(typ)
hd[6:8] = le16(frames)
hd[8:10] = le16(w)
hd[10:12] = le16(h)
hd[12:14] = le16(depth)
hd[14:16] = le16(3)
if typ == 0xAF11:
hd[16:18] = le16(speed)
else:
hd[16:20] = le32(speed)
hd[80:84] = le32(oframes[0])
hd[84:88] = le32(oframes[1])
return hd
def file(typ, w, h, depth, speed, frames, prefix=b"", nframes=None):
hd = header(typ, nframes if nframes is not None else len(frames), w, h, depth, speed)
body = prefix + b"".join(frames)
hd[0:4] = le32(128 + len(body))
if typ != 0xAF11 and frames:
hd[80:84] = le32(128 + len(prefix))
hd[84:88] = le32(128 + len(prefix) + len(frames[0]))
return bytes(hd) + body
def pal(n, seed, six):
rnd = random.Random(seed)
m = 64 if six else 256
return [(rnd.randrange(m), rnd.randrange(m), rnd.randrange(m)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- files
def fli_8():
"""FLI (AF11), 70 Hz jiffies: COLOR_64 + BRUN, LC deltas, a BLACK frame, a COPY frame, a palette change, PSTAMP"""
w, h, n = 80, 50, 10
imgs = idx_frames(w, h, n, 256, 1)
frames = [frame([color([(0, pal(256, 1, True))], True), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 4:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy8(imgs[t]), chunk(18, le16(10) + le16(6) + bytes(20))]))
elif t == 7:
frames.append(frame([color([(10, pal(20, 9, True)), (30, pal(5, 10, True))], True), lc(imgs[t], imgs[t - 1])]))
else:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
frames.append(frame([lc(imgs[0], imgs[-1])])) # the ring frame
return file(0xAF11, w, h, 8, 5, frames, nframes=n)
def flc_8():
"""FLC (AF12), ms: a prefix chunk, COLOR_256 + BRUN, SS2 deltas (line skips, last-byte opcode), COPY, BLACK, an
empty frame, COLOR_256 updates"""
w, h, n = 128, 64, 12
imgs = idx_frames(w, h, n, 256, 2)
frames = [frame([color([(0, pal(256, 2, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 3:
imgs[t] = imgs[t - 1]
frames.append(frame([]))
elif t == 6:
frames.append(frame([copy8(imgs[t])]))
elif t == 8:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b""), color([(0, pal(16, 3, False)), (100, pal(50, 4, False))], False)]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1], last_byte=True)]))
prefix = le32(16) + le16(0xF100) + le16(0) + bytes(8)
return file(0xAF12, w, h, 8, 66, frames, prefix=prefix)
def flc_8_odd():
"""FLC 8-bit at an odd size: BRUN, LC, SS2 without the last-byte opcode, COPY with padded rows"""
w, h, n = 61, 37, 6
imgs = idx_frames(w, h, n, 256, 3)
frames = [frame([color([(0, pal(256, 5, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 2:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
elif t == 4:
frames.append(frame([copy8(imgs[t])]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1])]))
return file(0xAF12, w, h, 8, 100, frames)
def flc_deep(typ, depth, bpp, w, h):
"""15 / 16 / 24-bit: BRUN (bytes) or DTA_BRUN (pixels), DELTA / DTA_LC, BLACK, COPY / DTA_COPY"""
n = 7
imgs = deep_frames(w, h, n, bpp, depth)
frames = [frame([brun(imgs[0], bpp, False)])]
for t in range(1, n):
if t == 2:
frames.append(frame([copy_deep(imgs[t], bpp, 16)]))
elif t == 3:
frames.append(frame([brun(imgs[t], bpp, True, 25)]))
elif t == 4:
imgs[t] = [[bytes(bpp)] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy_deep(imgs[t], bpp, 26)]))
else:
frames.append(frame([delta_deep(imgs[t], imgs[t - 1], bpp, 7 if t % 2 else 27)]))
return file(typ, w, h, depth, 50, frames)
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="flifx_")
files = [
("anim.fli", fli_8(), 80, 50, 8, 70 / 5),
("anim.flc", flc_8(), 128, 64, 8, 1000 / 66),
("odd.flc", flc_8_odd(), 61, 37, 8, 10),
("rgb15.flc", flc_deep(0xAF12, 16, 2, 63, 40), 63, 40, 15, 20),
("rgb565.flc", flc_deep(0xAF44, 16, 2, 48, 30), 48, 30, 16, 20),
("bgr24.flc", flc_deep(0xAF12, 24, 3, 41, 30), 41, 30, 24, 20),
]
cases = []
for name, data, w, h, depth, rate in files:
path = os.path.join(tmp, name)
open(path, "wb").write(data)
crcs = rgba_crcs(path, w, h)
assert crcs, name
cases.append({"name": name, "data": data, "width": w, "height": h, "depth": depth, "rate": rate, "frames": crcs})
ctx.emit("fli_cases", cases)
# tools/bench.luau: a 320x200 FLC, 10 frames (BRUN then SS2 deltas)
w, h, n = 320, 200, 10
imgs = idx_frames(w, h, n, 256, 9)
frames = [frame([color([(0, pal(256, 9, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
frames += [frame([ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
ctx.emit("fli_bench", {"data": file(0xAF12, w, h, 8, 66, frames), "width": w, "height": h, "frames": n})
+108
View File
@@ -0,0 +1,108 @@
# Legacy video codec fixtures (tools/fixtures.py): Cinepak, Microsoft Video 1, QuickTime RLE and QuickTime SMC
# streams in AVI, MOV and MKV. ffmpeg encodes what it can (cinepak rgb24 / gray, msvideo1 rgb555, qtrle rgb24 /
# rgb555 / argb / gray, smc pal8); tools/fixtures/_legacy_mux.py encodes the rest (QuickTime RLE at 1 / 2 / 4 / 8 bits
# with colour tables and the default Macintosh palettes, 8-bit Microsoft Video 1 and Cinepak with AVI palettes). The
# reference is ffmpeg's decode of every file: the CRC-32 of each frame as rgba.
# tests/gen/legacy_cases.luau { { name, data, codec, width, height, frames = { crc } } }
import importlib.util, os, tempfile, zlib
_here = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_here, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
V = _load("_video")
M = _load("_legacy_mux")
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_legacy_mux.py"]
W, H = 128, 96
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H), "-t", "1"]
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def case(tmp, name, codec, w=W, h=H):
path = os.path.join(tmp, name)
return {"name": name, "data": open(path, "rb").read(), "codec": codec, "width": w, "height": h,
"frames": rgba_crcs(path, w, h)}
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="legacyfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
cases = []
# ffmpeg's encoders
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "cinepak", "cinepak." + ext)
cases.append(case(tmp, "cinepak." + ext, "cinepak"))
ff(*SRC, "-c:v", "cinepak", "-pix_fmt", "gray", "cinepak_gray.avi")
cases.append(case(tmp, "cinepak_gray.avi", "cinepak"))
ff("-f", "lavfi", "-i", "testsrc2=size=92x68:rate=10", "-t", "0.5", "-c:v", "cinepak", "cinepak_odd.mov")
cases.append(case(tmp, "cinepak_odd.mov", "cinepak", 92, 68))
ff(*SRC, "-c:v", "cinepak", "-min_strips", "3", "-max_strips", "3", "-skip_empty_cb", "1", "cinepak_strips.avi")
cases.append(case(tmp, "cinepak_strips.avi", "cinepak"))
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "msvideo1", "msvideo1." + ext)
cases.append(case(tmp, "msvideo1." + ext, "msvideo1"))
for pf in ("rgb24", "rgb555be", "argb", "gray"):
ff(*SRC, "-c:v", "qtrle", "-pix_fmt", pf, "qtrle_%s.mov" % pf)
cases.append(case(tmp, "qtrle_%s.mov" % pf, "qtrle"))
ff("-f", "lavfi", "-i", "testsrc2=size=100x60:rate=10", "-t", "0.5", "-c:v", "qtrle", "-pix_fmt", "argb", "qtrle_odd.mov")
cases.append(case(tmp, "qtrle_odd.mov", "qtrle", 100, 60))
for ext in ("mov", "mkv"): # (ffmpeg's AVI muxer has no tag for smc: it writes raw pal8)
ff(*SRC, "-c:v", "smc", "smc." + ext)
cases.append(case(tmp, "smc." + ext, "smc"))
# streams encoded here
w, h, n = 64, 48, 8
for bits in (1, 2, 4, 8):
imgs = M.index_frames(w, h, n, 1 << bits, seed=bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
keys = [i == 0 for i in range(n)]
# a colour table in the sample description, and the Macintosh default table
pal = M.palette(1 << bits, seed=bits)
name = "qtrle_%d_ctab.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits, colors=pal), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
name = "qtrle_%d_default.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
# grey depths (0x20 + bits) with the default table id: grey ramps
for bits in (2, 4):
imgs = M.index_frames(w, h, 4, 1 << bits, seed=10 + bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
name = "qtrle_%d_grey.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, 32 + bits), frames, [True] + [False] * 3))
cases.append(case(tmp, name, "qtrle", w, h))
# 8-bit Microsoft Video 1 and Cinepak with an AVI palette
pal = M.palette(256, seed=3)
imgs = M.index_frames(w, h, n, 256, seed=5)
frames = [M.msvc8_frame(img, imgs[i - 1] if i else None) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "msvideo1_8.avi"), "wb").write(
M.avi(w, h, b"CRAM", M.bitmapinfo(w, h, 8, b"CRAM", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "msvideo1_8.avi", "msvideo1", w, h))
imgs = M.index_frames(w, h, n, 200, seed=6)
frames = [M.cvid8_frame(img, imgs[i - 1] if i else None, i == 0) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "cinepak_8.avi"), "wb").write(
M.avi(w, h, b"cvid", M.bitmapinfo(w, h, 8, b"cvid", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "cinepak_8.avi", "cinepak", w, h))
for c in cases:
assert c["frames"], c["name"] + ": ffmpeg decoded no frame"
ctx.emit("legacy_cases", cases)
# tools/bench.luau: 320x240, 10 frames of each codec
bench = []
big = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=10", "-t", "1"]
for name, args in [("cinepak.avi", ["-c:v", "cinepak"]), ("msvideo1.avi", ["-c:v", "msvideo1"]),
("qtrle.mov", ["-c:v", "qtrle", "-pix_fmt", "rgb24"]), ("smc.mov", ["-c:v", "smc"])]:
ff(*big, *args, "bench_" + name)
bench.append({"name": name, "data": open(os.path.join(tmp, "bench_" + name), "rb").read(), "width": 320, "height": 240})
ctx.emit("legacy_bench", bench)
+11 -4
View File
@@ -4,7 +4,9 @@
# tests/gen/mpeg1_<name>.luau { name, width, height, frames, file (base64), units = { { offset, length } },
# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA),
# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib),
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) }
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib),
# exact = { { y, u, v } } (CRC-32 of every frame's planes from `ffmpeg -idct int`, the IDCT
# codecs/video/Dsp reproduces: the decode must equal it) }
# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } }
# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with
# B-frames) for tools/bench.luau
@@ -122,9 +124,9 @@ def generate(ctx):
es = open(path, "rb").read()
return (patch_size(es, *size) if size else es), path
def reference(path, fmt):
out = path + "." + fmt
ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
def reference(path, fmt, idct=None):
out = path + "." + fmt + (idct or "")
ff((["-idct", idct] if idct else []) + ["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2])
@@ -134,10 +136,13 @@ def generate(ctx):
es, path = encode(name, args, size)
rgba, w, h = reference(path, "rgba")
yuv, _, _ = reference(path, "yuv420p")
exact, _, _ = reference(path, "yuv420p", "int")
if size:
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
exact = crop_yuv(exact, w, h, size[0], size[1])
w, h = size
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
c = ((w + 1) // 2) * ((h + 1) // 2)
n = len(rgba) // fs
means = []
for k in range(n):
@@ -151,6 +156,8 @@ def generate(ctx):
"means": means,
"rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks],
"yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks],
"exact": [[zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + c]), zlib.crc32(f[w * h + c:ys])]
for f in (exact[k * ys:(k + 1) * ys] for k in range(n))],
})
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
+424
View File
@@ -0,0 +1,424 @@
# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder
# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the
# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and
# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime
# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second
# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors),
# each with `ffmpeg -idct int` decoding as the reference: the IJG integer IDCT that codecs/video/Dsp reproduces, so
# the planes must match exactly.
# tests/gen/mpeg2_<name>.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64),
# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of
# every frame's cropped planes, display order), bands = { { crc } } (per frame, of
# each 16-line luma band), first / last = the yuv frame (base64 zlib) }
# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS,
# Matroska and AVI, base64, with the stream's crcs
# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau
import base64, os, shutil, subprocess, tempfile, zlib
def b64(b):
return base64.b64encode(b).decode()
def z64(b):
return base64.b64encode(zlib.compress(b, 9)).decode()
FF = ["-hide_banner", "-loglevel", "error", "-y"]
ENC = ["-c:v", "mpeg2video", "-f", "mpeg2video"]
ILACE = ["-flags", "+ilme+ildct"]
CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64))
INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64))
INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64))
def src(kind, w, h, t, rate=25, vf=None):
s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate)
if vf:
s += "," + vf
return ["-f", "lavfi", "-i", s, "-t", str(t)]
# name: (ffmpeg input + encoder args, chroma)
CASES = {
"prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1",
"-b:v", "1500k", "-bf", "1", "-g", "9"], 1),
"tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k",
"-bf", "2", "-g", "8"], 1),
"dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER,
"-b:v", "800k", "-bf", "1", "-g", "6"], 1),
"dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1),
"motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1),
"odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1),
"c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6",
"-chroma_intra_matrix", CHROMA_INTRA], 2),
"c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE +
["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2),
}
def access_units(es):
# one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start
starts = []
i = 0
pending = None
while True:
i = es.find(b"\x00\x00\x01", i)
if i < 0 or i + 3 >= len(es):
break
code = es[i + 3]
if code in (0xB3, 0xB8) and pending is None:
pending = i
elif code == 0x00:
starts.append(pending if pending is not None else i)
pending = None
i += 3
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe")
def ff(args):
subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True)
def size(path):
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2])
def reference(path, chroma):
out = path + ".yuv"
ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo",
"-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out])
return open(out, "rb").read()
def emit(name, es, path, chroma):
w, h = size(path)
yuv = reference(path, chroma)
cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2)
fs = w * h + 2 * cw * ch
n = len(yuv) // fs
crcs, bands = [], []
for k in range(n):
f = yuv[k * fs:(k + 1) * fs]
crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])])
bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)])
ctx.emit("mpeg2_" + name, {
"name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es),
"units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]),
})
return crcs
with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp:
crcs = {}
for name, (args, chroma) in CASES.items():
path = os.path.join(tmp, name + ".m2v")
ff(args + ENC + [path])
crcs[name] = emit(name, open(path, "rb").read(), path, chroma)
# mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires)
y4m = os.path.join(tmp, "src.y4m")
ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m])
dp = os.path.join(tmp, "dualprime.m2v")
ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'"
% (dp, y4m)])
emit("dualprime", open(dp, "rb").read(), dp, 1)
# field pictures and concealment vectors (field_stream below: no encoder at hand writes them)
seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")]
for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)):
path = os.path.join(tmp, name + ".m2v")
es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal)
open(path, "wb").write(es)
emit(name, es, path, 1)
# the prog stream in the containers (stream copy)
prog = os.path.join(tmp, "prog.m2v")
cont = {"crcs": crcs["prog"]}
for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")):
out = os.path.join(tmp, "prog." + ext)
ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out])
cont[ext] = b64(open(out, "rb").read())
# stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone
ts = bytearray(base64.b64decode(cont["ts"]))
patched = False
for p in range(0, len(ts), 188):
pkt = ts[p:p + 188]
if pkt[0] != 0x47 or not (pkt[1] & 0x40):
continue
pid = ((pkt[1] & 0x1F) << 8) | pkt[2]
if pid == 0 or pid == 0x11 or pkt[3] & 0x20:
continue
o = p + 5 + pkt[4]
if ts[o] != 0x02: # table_id of a PMT
continue
slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2]
pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11]
e = o + 12 + pinfo
while e < o + 3 + slen - 4:
if ts[e] == 0x02:
ts[e] = 0x80
patched = True
e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4])
crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4]))
ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big")
assert patched, "mpeg2: no PMT entry patched"
cont["ts80"] = b64(bytes(ts))
ctx.emit("mpeg2_containers", cont)
bench = []
path = os.path.join(tmp, "bench.m2v")
ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path])
es = open(path, "rb").read()
bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)})
ctx.emit("mpeg2_bench", bench)
def zlib_crc32_mpeg(data):
# CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor
crc = 0xFFFFFFFF
for b in data:
crc ^= b << 24
for _ in range(8):
crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF
return crc
# ---------------------------------------------------------------------------------------------------------------------
# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field
# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in
# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse
# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is
# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here).
MBAI = {1: "1", 2: "011", 3: "010"}
DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"]
DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"]
# |motion_code| 0..16 (Table B-10), then the sign bit
MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001",
"0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"]
CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"}
MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"}
MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011",
"intra": "00011"}
class Bits:
def __init__(self):
self.s = []
def put(self, v, n):
self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "")
def code(self, c):
self.s.append(c)
def start(self, code):
# next_start_code: zero stuffing to a byte boundary, then 00 00 01 code
n = len("".join(self.s))
if n % 8:
self.s.append("0" * (8 - n % 8))
self.put(0x000001, 24)
self.put(code, 8)
def bytes(self):
s = "".join(self.s)
s += "0" * (-len(s) % 8)
return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8))
def field_stream(rng, w, h, frames, conceal=False):
"""frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]"""
b = Bits()
mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32)
fh = mbh * 8 # field height in lines (coded)
b.start(0xB3)
b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1)
b.put(0, 1), b.put(0, 1)
b.start(0xB5)
b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1)
b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5)
b.start(0xB8)
b.put(0, 25), b.put(1, 1), b.put(0, 1)
# temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded
# just before it)
tr, d, last_ref = {}, 0, None
for k, f in enumerate(frames):
if f[0] != "B":
if last_ref is not None:
tr[last_ref] = d
d += 1
last_ref = k
else:
tr[k] = d
d += 1
tr[last_ref] = d
for k, (t0, t1) in enumerate(frames):
for fi, ptype in enumerate((t0, t1)):
parity = fi # top field first
pt = {"I": 1, "P": 2, "B": 3}[ptype]
b.start(0x00)
b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16)
if pt >= 2:
b.put(0, 1), b.put(7, 3)
if pt == 3:
b.put(0, 1), b.put(7, 3)
b.put(0, 1)
b.start(0xB5)
fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15)
if pt == 1 and conceal:
fc = (1, 1, 15, 15)
b.put(8, 4)
for f in fc:
b.put(f, 4)
b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1)
b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1)
# the second field of the first frame has one reference: the first field (no skips, zero-vector or
# dual-prime prediction from its own parity)
only_first = k == 0 and fi == 1
for row in range(mbh // 2):
b.start(row + 1)
b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1)
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c]
dc = [128, 128, 128]
col = 0
prev_dirs = None
while col < mbw:
# B skips repeat the previous vectors: only after zero ones (they stay inside the picture)
skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and
prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1])))
if skip:
b.code(MBAI[2])
col += 1 # the skipped one
dc = [128, 128, 128]
if pt == 2:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
else:
b.code(MBAI[1])
if pt == 1 or rng.random() < 0.08:
b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"])
if conceal:
# field_select, a concealment vector (the predictor again: motion codes 0), marker
b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1)
pmv[0][2:] = pmv[0][:2]
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
for blk in range(6):
comp = 0 if blk < 4 else blk - 3
target = rng.randrange(40, 216)
diff = target - dc[comp]
dc[comp] = target
size = abs(diff).bit_length()
b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size])
if size:
b.put(diff if diff > 0 else diff + (1 << size) - 1, size)
ac_block(b, rng, 1, 0.5)
prev_dirs = None
col += 1
continue
dc = [128, 128, 128]
if pt == 2:
kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else
("mc", "mc_coded", "mc_coded", "nomc_coded", "mc"))
dirs = (0,) if kind != "nomc_coded" else ()
b.code(MBTYPE_P[kind])
coded = kind != "mc"
else:
kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded"))
dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,)
b.code(MBTYPE_B[kind])
coded = kind.endswith("coded")
if dirs:
choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else [])
mt = rng.choice(choices)
b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2)
for d in dirs:
motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None)
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
if coded:
cbp = rng.choice(list(CBP))
b.code(CBP[cbp])
for blk in range(6):
if cbp & (32 >> blk):
ac_block(b, rng, 0, 0.6)
prev_dirs = dirs
col += 1
b.start(0xB7)
return b.bytes()
def ac_block(b, rng, first, more):
# escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one
n = first
count = 0
while n < 64 and (count == 0 and first == 0 or rng.random() < more):
run = rng.randrange(0, 6)
if n + run > 63:
break
level = rng.choice((-1, 1)) * rng.randrange(1, 24)
b.code("000001"), b.put(run, 6), b.put(level, 12)
n += run + 1
count += 1
b.code("10")
def put_motion(b, delta):
b.code(MOTION[abs(delta)])
if delta:
b.put(1 if delta < 0 else 0, 1)
def wrap(v):
return (v + 16) % 32 - 16
def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel):
"""one direction's vectors for a field-picture macroblock, kept inside the reference field"""
def ok(mx, my, rows, y0):
sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1)
return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh
def pick(px, py, rows, y0, extra=None):
for _ in range(50):
mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11)
dx, dy = wrap(mx - px), wrap(my - py)
if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)):
return dx, dy, mx, my
return None
if mt == "field":
sel = rng.randrange(2) if force_sel is None else force_sel
r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
elif mt == "16x8":
for half in range(2):
sel = rng.randrange(2) if force_sel is None else force_sel
px, py = pmv[half * 2], pmv[half * 2 + 1]
r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1])
else:
# dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector
def dmv_ok(dmx, dmy):
def f(mx, my):
ox = ((mx + (mx > 0)) >> 1) + dmx
oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1)
return ok(ox, oy, 16, row * 16)
return f
for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7):
r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy))
if r:
break
assert r, "dual prime: no vector fits"
put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx])
put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
+499
View File
@@ -0,0 +1,499 @@
# Smacker fixtures (tools/fixtures.py): ffmpeg cannot write Smacker, so this encodes SMK2 / SMK4 files: the four
# header trees (8-bit low / high byte trees, escape leaves used through the recent-value cache, absent trees), every
# block type (MONO, FULL with the SMK4 doubled modes, SKIP, FILL) with block runs, palette updates (new entries, skips,
# copies from the old palette), a ring frame, both frame-time units, and audio tracks: packed DPCM 16-bit stereo and
# 8-bit mono, raw s16le and u8. The reference is ffmpeg's decode: the CRC-32 of each video frame as rgba and of each
# audio track as f32le.
# tests/gen/smk_cases.luau { { name, data, width, height, rate, frames = { crc }, audio = { { rate, channels,
# bits, codec, frames, crc } } } }
import heapq, importlib.util, math, os, random, struct, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py"]
RUNS = list(range(1, 60)) + [128, 256, 512, 1024, 2048]
# ---------------------------------------------------------------------------------------------------- bits / trees
class Bits:
def __init__(self):
self.bits = []
def put(self, v, n):
for i in range(n):
self.bits.append((v >> i) & 1)
def code(self, c):
self.bits.extend(c)
def bytes(self):
out = bytearray((len(self.bits) + 7) // 8)
for i, b in enumerate(self.bits):
out[i >> 3] |= b << (i & 7)
return bytes(out)
def huffman(freqs, maxdepth):
"""a Huffman tree over freqs {value: count}: nested (left, right) tuples / ('leaf', value)"""
f = dict(freqs)
while True:
heap = [(c, i, ("leaf", v)) for i, (v, c) in enumerate(sorted(f.items()))]
heapq.heapify(heap)
k = len(heap)
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
heapq.heappush(heap, (a[0] + b[0], k, (a[2], b[2])))
k += 1
tree = heap[0][2]
if depth(tree) <= maxdepth:
return tree
f = {v: c // 2 + 1 for v, c in f.items()}
def depth(t):
return 0 if t[0] == "leaf" else 1 + max(depth(t[0]), depth(t[1]))
def codes(t, prefix=(), out=None):
out = {} if out is None else out
if t[0] == "leaf":
out[t[1]] = list(prefix)
else:
codes(t[0], prefix + (0,), out)
codes(t[1], prefix + (1,), out)
return out
def write_tree8(bw, t):
if t[0] == "leaf":
bw.put(0, 1)
bw.put(t[1], 8)
else:
bw.put(1, 1)
write_tree8(bw, t[0])
write_tree8(bw, t[1])
class BigTree:
"""a header tree: values (16-bit) with three escape leaves for the recent-value cache"""
def __init__(self, freqs, rnd, absent_ok=True):
self.absent = not freqs
if self.absent:
return
lo = {}
hi = {}
for v, c in freqs.items():
lo[v & 255] = lo.get(v & 255, 0) + c
hi[v >> 8] = hi.get(v >> 8, 0) + c
# three escape values made of bytes the byte trees have, not used as values (a high-byte tree of only 0 is
# left out: absent byte trees decode as 0)
esc = []
for l in sorted(lo):
for h in sorted(hi):
v = l | h << 8
if v not in freqs and len(esc) < 3:
esc.append(v)
while len(esc) < 3: # every combination used: widen the low byte tree
nl = next(x for x in range(256) if x not in lo)
lo[nl] = 1
esc.append(nl | sorted(hi)[0] << 8)
self.esc = esc
self.lo = huffman(lo, 27)
self.hi = huffman(hi, 27)
allv = dict(freqs)
for i, e in enumerate(esc):
allv[e] = max(1, sum(freqs.values()) // (8 + i))
self.tree = huffman(allv, 200)
self.lcodes, self.hcodes, self.vcodes = codes(self.lo), codes(self.hi), codes(self.tree)
self.entries = count_entries(self.tree)
self.hi_absent = len(hi) == 1 and 0 in hi
self.rnd = rnd
def write(self, bw):
if self.absent:
bw.put(0, 1)
return
bw.put(1, 1)
bw.put(1, 1)
write_tree8(bw, self.lo)
bw.put(0, 1)
if self.hi_absent:
bw.put(0, 1)
else:
bw.put(1, 1)
write_tree8(bw, self.hi)
bw.put(0, 1)
for e in self.esc:
bw.put(e, 16)
self._write_big(bw, self.tree)
bw.put(0, 1)
def _write_big(self, bw, t):
if t[0] == "leaf":
bw.put(0, 1)
v = t[1]
bw.code(self.lcodes[v & 255])
if not self.hi_absent:
bw.code(self.hcodes[v >> 8])
else:
bw.put(1, 1)
self._write_big(bw, t[0])
self._write_big(bw, t[1])
def size(self):
return 0 if self.absent else (self.entries + 3) * 4
def reset(self):
self.cache = [0, 0, 0]
def emit(self, bw, v):
if self.absent:
assert v == 0
return
hit = [k for k in range(3) if self.cache[k] == v]
if hit and self.rnd.random() < 0.7:
bw.code(self.vcodes[self.esc[hit[0]]])
else:
bw.code(self.vcodes[v])
if v != self.cache[0]:
self.cache[2] = self.cache[1]
self.cache[1] = self.cache[0]
self.cache[0] = v
def count_entries(t):
return 1 if t[0] == "leaf" else 1 + count_entries(t[0]) + count_entries(t[1])
# ---------------------------------------------------------------------------------------------------- video
def blocks_of(img, w, h):
return [[[img[by * 4 + r][bx * 4 + x] for x in range(4)] for r in range(4)] for by in range(h // 4) for bx in range(w // 4)]
def classify(b, prev, v4):
if prev is not None and b == prev:
return ("skip",)
flat = [p for r in b for p in r]
cols = sorted(set(flat))
if len(cols) == 1:
return ("fill", cols[0])
if len(cols) == 2:
lo, hi = cols
m = 0
for i, p in enumerate(flat):
if p == hi:
m |= 1 << i
return ("mono", hi << 8 | lo, m)
if v4 and b[0] == b[1] and b[2] == b[3] and b[0][0] == b[0][1] and b[0][2] == b[0][3] and b[2][0] == b[2][1] and b[2][2] == b[2][3]:
return ("full", 1)
if v4 and b[0] == b[1] and b[2] == b[3]:
return ("full", 2)
return ("full", 0)
def full_codes(b, mode):
if mode == 0:
out = []
for r in b:
out += [r[2] | r[3] << 8, r[0] | r[1] << 8]
return out
if mode == 1:
return [b[0][0] | b[0][2] << 8, b[2][0] | b[2][2] << 8]
return [b[0][2] | b[0][3] << 8, b[0][0] | b[0][1] << 8, b[2][2] | b[2][3] << 8, b[2][0] | b[2][1] << 8]
def plan(frames, w, h, v4):
"""per frame the list of runs: (kind, extra, [blocks])"""
out = []
prev = None
for img in frames:
bl = blocks_of(img, w, h)
cls = [classify(b, prev[i] if prev else None, v4) for i, b in enumerate(bl)]
runs = []
i = 0
while i < len(bl):
c = cls[i]
key = c[:2] if c[0] in ("fill", "full") else c[:1]
j = i
while j + 1 < len(bl) and (cls[j + 1][:2] if cls[j + 1][0] in ("fill", "full") else cls[j + 1][:1]) == key:
j += 1
n = j - i + 1
# the largest run length of the table that fits
k = max(r for r in RUNS if r <= n)
runs.append((c, [bl[x] for x in range(i, i + k)], [cls[x] for x in range(i, i + k)], RUNS.index(k)))
i += k
out.append(runs)
prev = bl
return out
def type_value(c, ri):
kind = {"mono": 0, "full": 1, "skip": 2, "fill": 3}[c[0]]
v = kind | ri << 2
if c[0] == "fill":
v |= c[1] << 8
return v
def stats(plans, v4):
f = {"type": {}, "mclr": {}, "mmap": {}, "full": {}}
def add(t, v):
f[t][v] = f[t].get(v, 0) + 1
for runs in plans:
for c, bl, cl, ri in runs:
add("type", type_value(c, ri))
if c[0] == "mono":
for x in cl:
add("mclr", x[1])
add("mmap", x[2])
elif c[0] == "full":
for b in bl:
for v in full_codes(b, c[1]):
add("full", v)
return f
def encode_video(frames, w, h, v4, rnd):
plans = plan(frames, w, h, v4)
f = stats(plans, v4)
trees = {k: BigTree(f[k], rnd) for k in ("mmap", "mclr", "full", "type")}
tb = Bits()
for k in ("mmap", "mclr", "full", "type"):
trees[k].write(tb)
treebytes = tb.bytes()
out = []
for runs in plans:
for t in trees.values():
t.reset()
bw = Bits()
for c, bl, cl, ri in runs:
trees["type"].emit(bw, type_value(c, ri))
if c[0] == "mono":
for x in cl:
trees["mclr"].emit(bw, x[1])
trees["mmap"].emit(bw, x[2])
elif c[0] == "full":
if v4:
bw.code([1] if c[1] == 1 else [0, 1] if c[1] == 2 else [0, 0])
for b in bl:
for v in full_codes(b, c[1]):
trees["full"].emit(bw, v)
out.append(bw.bytes() or b"\0")
return treebytes, [trees[k].size() for k in ("mmap", "mclr", "full", "type")], out
# ---------------------------------------------------------------------------------------------------- palettes
def pal_chunk(new, old, first):
"""a palette update: new / old are lists of 256 6-bit (r, g, b)"""
body = bytearray()
i = 0
while i < 256:
if not first and new[i] == old[i]:
j = i
while j < 256 and j - i < 128 and new[j] == old[j]:
j += 1
body.append(0x80 | (j - i - 1))
i = j
continue
# a copy from the old palette when the next entries appear there in a row
if not first:
for off in range(256):
n = 0
while i + n < 256 and off + n < 256 and n < 64 and new[i + n] == old[off + n]:
n += 1
if n >= 2:
body += bytes([0x40 | (n - 1), off])
i += n
break
else:
off = None
if off is not None:
continue
body += bytes(new[i])
i += 1
size = 1 + len(body)
size = (size + 3) // 4 * 4
return bytes([size // 4]) + bytes(body) + bytes(size - 1 - len(body))
# ---------------------------------------------------------------------------------------------------- audio
def pack_audio(samples, ch, bits):
"""one packed (SMKA) chunk body: samples interleaved (s16 or u8)"""
nb = bits // 8
bw = Bits()
bw.put(1, 1)
bw.put(1 if ch == 2 else 0, 1)
bw.put(1 if bits == 16 else 0, 1)
mod = 65536 if bits == 16 else 256
pred = list(samples[:ch])
deltas = []
for i in range(ch, len(samples)):
c = i % ch
d = (samples[i] - pred[c]) % mod
pred[c] = samples[i]
deltas.append((c, d))
ntrees = (2 if bits == 16 else 1) * ch
freqs = [dict() for _ in range(ntrees)]
for c, d in deltas:
if bits == 16:
freqs[2 * c][d & 255] = freqs[2 * c].get(d & 255, 0) + 1
freqs[2 * c + 1][d >> 8] = freqs[2 * c + 1].get(d >> 8, 0) + 1
else:
freqs[c][d] = freqs[c].get(d, 0) + 1
trees = [huffman(f or {0: 1}, 27) for f in freqs]
cds = [codes(t) for t in trees]
for t in trees:
bw.put(1, 1)
write_tree8(bw, t)
bw.put(0, 1)
for c in range(ch - 1, -1, -1):
v = samples[c] % mod
if bits == 16:
v = ((v & 255) << 8) | (v >> 8) # stored byte-swapped
bw.put(v, bits)
for c, d in deltas:
if bits == 16:
bw.code(cds[2 * c][d & 255])
bw.code(cds[2 * c + 1][d >> 8])
else:
bw.code(cds[c][d])
return struct.pack("<I", len(samples) * nb) + bw.bytes()
def tone(n, ch, bits, rate, seed, f0):
rnd = random.Random(seed)
out = []
for i in range(n):
for c in range(ch):
v = 0.5 * math.sin(2 * math.pi * f0 * (c + 1) * i / rate) + 0.05 * (rnd.random() - 0.5)
if bits == 16:
out.append(int(v * 30000))
else:
out.append(int(128 + v * 120))
return out
# ---------------------------------------------------------------------------------------------------- files
def idx_frames(w, h, n, seed, busy=False):
rnd = random.Random(seed)
out = []
for t in range(n):
if busy: # textured, moving: mostly FULL blocks (the bench)
img = [[(x * 3 + y * 5 + ((x + t * 4) * (y + t)) // 7) % 251 for x in range(w)] for y in range(h)]
else:
img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)]
for y in range(8, 24):
for x in range(8 + t * 4, 24 + t * 4):
img[y][x] = 100 + (x + y) % 2 # two colours: MONO blocks
for y in range(h - 16, h - 8):
for x in range(0, w):
img[y][x] = 50 + ((x // 2) % 5) if (t % 2 == 0) else 60 # doubled pixels: SMK4 modes
for y in range(28, 36):
for x in range(w // 2, w // 2 + 12):
img[y][x] = rnd.randrange(256)
out.append(img)
return out
def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed, busy=False):
"""version 2 / 4; tracks = [(kind, rate, ch, bits)] kind "packed" / "raw"; returns bytes, track info"""
rnd = random.Random(seed)
frames = idx_frames(w, h, nframes, seed, busy)
if ring:
frames = frames + [frames[0]]
treebytes, sizes, video = encode_video(frames, w, h, version == 4, rnd)
total = len(frames)
# palettes (6-bit), changing on some frames
pals = []
cur = [(rnd.randrange(64), rnd.randrange(64), rnd.randrange(64)) for _ in range(256)]
for t in range(total):
if t in (3, 5):
cur = list(cur)
for k in range(20 + t, 40 + t):
cur[k] = (rnd.randrange(64), rnd.randrange(64), rnd.randrange(64))
cur[200:210] = pals[0][10:20] # a copy from the old palette
pals.append(list(cur))
# audio per frame
seconds = (pts_inc / 1000.0 if pts_inc > 0 else -pts_inc / 100000.0)
achunks = []
for ti, (kind, rate, ch, bits) in enumerate(tracks):
per = []
done = 0
for t in range(total):
n = int(round((t + 1) * seconds * rate)) - done
done += n
s = tone(n, ch, bits, rate, seed * 10 + ti * 100 + t, 440 + 110 * ti)
if kind == "packed":
per.append(pack_audio(s, ch, bits))
else:
per.append(b"".join(struct.pack("<h", v) if bits == 16 else bytes([v]) for v in s))
achunks.append(per)
data = []
flags = []
for t in range(total):
body = b""
fl = 0
if t == 0 or pals[t] != pals[t - 1]:
body += pal_chunk(pals[t], pals[t - 1] if t else None, t == 0)
fl |= 1
for ti in range(len(tracks)):
a = achunks[ti][t]
body += struct.pack("<I", 4 + len(a)) + a
fl |= 2 << ti
body += video[t]
body += bytes((-len(body)) % 4)
data.append(body)
flags.append(fl)
hd = b"SMK%d" % version + struct.pack("<IIIiI", w, h, nframes, pts_inc, 1 if ring else 0)
hd += struct.pack("<7I", *[max(len(a) for a in achunks[i]) if i < len(tracks) else 0 for i in range(7)])
hd += struct.pack("<I", len(treebytes)) + struct.pack("<4I", *sizes)
for i in range(7):
if i < len(tracks):
kind, rate, ch, bits = tracks[i]
f = 0x40 | (0x80 if kind == "packed" else 0) | (0x20 if bits == 16 else 0) | (0x10 if ch == 2 else 0)
hd += struct.pack("<I", rate | f << 24)
else:
hd += struct.pack("<I", 0)
hd += struct.pack("<I", 0)
hd += b"".join(struct.pack("<I", len(d) | (1 if t == 0 else 0)) for t, d in enumerate(data))
hd += bytes(flags)
return hd + treebytes + b"".join(data)
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="smkfx_")
specs = [
("smk2_audio.smk", 2, 64, 48, 8, 100, [("packed", 22050, 2, 16), ("packed", 11025, 1, 8)], False, 1),
("smk4_ring.smk", 4, 96, 64, 9, -6667, [("raw", 16000, 1, 16), ("raw", 8000, 2, 8)], True, 2),
("smk4_mono.smk", 4, 64, 48, 6, 80, [("packed", 22050, 1, 16), ("packed", 11025, 2, 8)], False, 3),
("smk2_silent.smk", 2, 128, 64, 5, 66, [], False, 4),
]
cases = []
for name, ver, w, h, n, pts, tracks, ring, seed in specs:
data = smk_file(ver, w, h, n, pts, tracks, ring, seed)
path = os.path.join(tmp, name)
open(path, "wb").write(data)
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
sz = w * h * 4
crcs = [zlib.crc32(raw[i:i + sz]) & 0xffffffff for i in range(0, len(raw) - sz + 1, sz)]
assert len(crcs) == n + (1 if ring else 0), (name, len(crcs))
audio = []
for i, (kind, rate, ch, bits) in enumerate(tracks):
pcm = V.ffmpeg(["-i", path, "-map", "0:a:%d" % i, "-f", "f32le", "-"])
audio.append({"rate": rate, "channels": ch, "bits": bits,
"codec": "smackaudio" if kind == "packed" else ("pcm_s16le" if bits == 16 else "pcm_u8"),
"frames": len(pcm) // (4 * ch), "crc": zlib.crc32(pcm) & 0xffffffff})
rate = 1000 / pts if pts > 0 else 100000 / -pts
cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio,
"ring": ring})
ctx.emit("smk_cases", cases)
# tools/bench.luau: a 320x200 SMK4 with 22.05 kHz packed stereo audio, 10 frames
ctx.emit("smk_bench", {"data": smk_file(4, 320, 200, 10, 100, [("packed", 22050, 2, 16)], False, 9, True), "width": 320,
"height": 200, "frames": 10})
+208
View File
@@ -0,0 +1,208 @@
# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's
# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions
# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a
# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode
# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per
# frame over the packed planes of the picture region, with the frame's pts.
# tests/gen/theora_<name>.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } }
# tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original)
# tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64),
# rate, channels }
# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio
# tests/gen/theora_mkv.luau { file (base64 .mkv), frames }
# tests/gen/theora_bench.luau { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau
import base64, os, shutil, struct, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def b64(b):
return base64.b64encode(b).decode()
def src(kind, w, h, rate, t):
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
# name: (input args, encoder args, pixel format)
CASES = {
"q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"),
"q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"),
"q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"),
"motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"),
"odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"),
"static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"),
"yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"),
"yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"),
"odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"),
}
# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd
# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched
# file (-flags unaligned: the exact crop)
PATCH = {
"crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)),
"crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)),
}
def crc32(b):
return zlib.crc32(b) & 0xFFFFFFFF
def ogg_pages(data):
"""yield (header fields, segment table, body) of each Ogg page"""
i = 0
while i + 27 <= len(data):
assert data[i:i + 4] == b"OggS"
flags, granule, serial, seq = data[i + 5], struct.unpack_from("<q", data, i + 6)[0], \
struct.unpack_from("<I", data, i + 14)[0], struct.unpack_from("<I", data, i + 18)[0]
n = data[i + 26]
segs = list(data[i + 27:i + 27 + n])
body = data[i + 27 + n:i + 27 + n + sum(segs)]
yield flags, granule, serial, seq, segs, body
i += 27 + n + sum(segs)
OGG_CRC = []
for _i in range(256):
r = _i << 24
for _ in range(8):
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
OGG_CRC.append(r & 0xFFFFFFFF)
def ogg_crc(b):
c = 0
for x in b:
c = ((c << 8) ^ OGG_CRC[((c >> 24) ^ x) & 0xFF]) & 0xFFFFFFFF
return c
def page(flags, granule, serial, seq, packets_segs, body):
head = b"OggS" + bytes([0, flags]) + struct.pack("<qII", granule, serial, seq) + b"\0\0\0\0" + \
bytes([len(packets_segs)]) + bytes(packets_segs)
p = bytearray(head + body)
struct.pack_into("<I", p, 22, ogg_crc(p))
return bytes(p)
def splice_empty(data, after):
"""rewrite a single-stream Ogg Theora file with one page per packet and an empty packet after data packet
`after` (1-based); granules are recomputed as frame counts since the last keyframe (bitstream 3.2.1 numbering)"""
packets, cur = [], b""
shift = None
for flags, granule, serial, seq, segs, body in ogg_pages(data):
o = 0
for s in segs:
cur += body[o:o + s]
o += s
if s < 255:
packets.append(cur)
cur = b""
sid = serial
shift = (packets[0][40] & 0x03) << 3 | packets[0][41] >> 5
out = []
seq = 0
frames = []
data_packets = packets[3:]
data_packets = data_packets[:after] + [b""] + data_packets[after:]
key = 0
for k, p in enumerate(packets[:3]):
segs = [255] * (len(p) // 255) + [len(p) % 255]
out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p))
seq += 1
for k, p in enumerate(data_packets):
n = k + 1
if len(p) > 0 and not (p[0] & 0x40):
key = n
segs = [255] * (len(p) // 255) + [len(p) % 255]
g = (key << shift) | (n - key)
out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p))
seq += 1
return b"".join(out)
def patch_picture(data, w, h, x, y):
"""rewrite the first page (the identification header) with another picture region"""
out = bytearray(data)
n = out[26]
o = 27 + n # the packet starts here
assert out[o:o + 7] == b"\x80theora"
out[o + 14:o + 17] = w.to_bytes(3, "big")
out[o + 17:o + 20] = h.to_bytes(3, "big")
out[o + 20] = x
out[o + 21] = y
plen = 27 + n + sum(out[27:27 + n])
out[22:26] = b"\0\0\0\0"
struct.pack_into("<I", out, 22, ogg_crc(bytes(out[:plen])))
return bytes(out)
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
def ff(args):
return subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True).stdout
def framecrc(path, pixfmt, extra=None):
out = ff(["-flags", "unaligned", "-i", path] + (extra or []) + ["-map", "0:v", "-fps_mode", "passthrough", "-pix_fmt", pixfmt,
"-f", "framecrc", "-"]).decode()
frames = []
for line in out.splitlines():
if line.startswith("#"):
continue
parts = [x.strip() for x in line.split(",")]
frames.append([int(parts[1]), int(parts[5], 16)])
return frames
with tempfile.TemporaryDirectory(prefix="formats-theora-") as tmp:
for name, (inp, enc, pixfmt) in CASES.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = open(path, "rb").read()
w, h = [int(x) for x in inp[3].split("=")[2].split(":")[0].split("x")]
ctx.emit("theora_" + name, {"name": name, "width": w, "height": h, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
if name == "q6":
# an empty packet (a dropped / repeated frame) after the 5th frame
dupe = splice_empty(data, 5)
dpath = os.path.join(tmp, "dupe.ogv")
open(dpath, "wb").write(dupe)
ctx.emit("theora_dupe", {"name": "dupe", "width": w, "height": h, "pixfmt": pixfmt, "file": b64(dupe),
"frames": framecrc(path, pixfmt)})
for name, (inp, enc, pixfmt, (pw, ph, px, py)) in PATCH.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = patch_picture(open(path, "rb").read(), pw, ph, px, py)
open(path, "wb").write(data)
ctx.emit("theora_" + name, {"name": name, "width": pw, "height": ph, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
# Theora + Vorbis (stereo 44.1 kHz)
av = os.path.join(tmp, "av.ogv")
ff(src("testsrc2", 160, 120, 25, 1) + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1",
"-ac", "2", "-c:v", "libtheora", "-q:v", "5", "-c:a", "libvorbis",
"-q:a", "3", "-shortest", av])
pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"),
"width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2})
# Theora + Opus, Theora + FLAC (mono, 0.5 s)
for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)):
path = os.path.join(tmp, "a_" + name + ".ogv")
ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate,
"-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc +
["-shortest", path])
pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"),
"width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1})
# Theora in Matroska (CodecPrivate: the three headers, Xiph-laced)
mkv = os.path.join(tmp, "t.mkv")
ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv])
ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"),
"width": 174, "height": 98})
# the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves)
bench = []
for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")):
path = os.path.join(tmp, "bench_" + kind + ".ogv")
ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path])
bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240})
ctx.emit("theora_bench", bench)