merge ws/video: containers mkv/avi/mp4/ts/ps/y4m (+writers), codecs Jpeg/Mpeg1/Vp8 inter/Video registry, AudioWrap, F.video.open
This commit is contained in:
commit
3cc44af0b2
96 files changed
+13398
-517
No files matched your search
@@ -27,6 +27,12 @@ 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 | 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 | 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` |
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
@@ -87,11 +93,13 @@ Codecs (layer 1, shared by formats; not loadable on their own):
|
||||
- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
|
||||
- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
|
||||
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
|
||||
- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
||||
- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
|
||||
- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
|
||||
- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
|
||||
- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
|
||||
- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
|
||||
- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
|
||||
- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
|
||||
- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
|
||||
- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
|
||||
@@ -100,7 +108,9 @@ Codecs (layer 1, shared by formats; not loadable on their own):
|
||||
- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
|
||||
- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
|
||||
- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
|
||||
- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
|
||||
- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
|
||||
- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
|
||||
- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
|
||||
@@ -0,0 +1,62 @@
|
||||
# Video
|
||||
|
||||
```luau
|
||||
local v = F.video.open(src) -- MKV / WebM, AVI, MP4 / MOV, MPEG-TS / PS, Y4M, and animated GIF / APNG / WebP
|
||||
while true do
|
||||
local f, err = v:nextFrame() -- f.image: yuv420p (codec output) or rgba8; f.pts / f.duration in seconds
|
||||
if not f then break end
|
||||
local rgba = v:toRGBA(f)
|
||||
end
|
||||
v:seek(12.5) -- the next frame is the first at or after 12.5 s
|
||||
local pcm = v.audio and v.audio:read(4096) -- the first audio track, as an audio Decoder (nil + v.audioError otherwise)
|
||||
for p in v.demuxer:packets(v.track.id) do end -- raw packets (pts / dts / duration in track ticks)
|
||||
F.save(v, "out.webm") -- remux (VP8 / Opus / Vorbis copied), or "out.avi" / ".mkv" / ".mp4" (MJPEG)
|
||||
F.convert(gif, "avi") -- animated images become videos (uneven delays: repeated frames)
|
||||
```
|
||||
|
||||
`F.load` of a video returns the same VideoDecoder (`kind = "video"`, decoded lazily).
|
||||
|
||||
## Layers
|
||||
|
||||
| Module | Role |
|
||||
|---|---|
|
||||
| `Types` (Video section) | `Track`, `Packet`, `Demuxer`, `VideoFrame`, `VideoDecoder`, `VideoCodecDecoder` |
|
||||
| `containers/Demux` | the indexed Demuxer every container builds: per-track cursors, keyframe seek, `count` / `get` / `info` |
|
||||
| `containers/Ebml`, `Avi`, `IsoBmff`, `MpegTs`, `MpegPs`, `MpegEs` | container structures |
|
||||
| `containers/AudioWrap` | an audio track as a stream an audio format reads (PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, ...) |
|
||||
| `codecs/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) |
|
||||
| `codecs/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio |
|
||||
| `codecs/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap |
|
||||
| `codecs/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
|
||||
| `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
|
||||
another format): `F.video.open` / `F.load` set it; calling a video format's `open` directly gives `v.audio = nil` and
|
||||
`v.audioError` unless you pass your own.
|
||||
|
||||
## Adding a codec (H.264, ...)
|
||||
|
||||
The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/Video/init.luau`
|
||||
with a `new` constructor that requires the codec lazily, or call `Video.register(entry)` at run time
|
||||
(`F.video.codecs.register`).
|
||||
|
||||
```luau
|
||||
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", ... }, matroska = { "V_MPEG4/ISO/AVC" },
|
||||
new = function(track, opts) return require("@formats/codecs/H264").newVideoDecoder(track, opts) end }
|
||||
```
|
||||
|
||||
`new(track, opts)` returns a `Types.VideoCodecDecoder`:
|
||||
|
||||
- `decode(self, packet) -> Err?`: one packet in decode order. `track.config` holds the codec configuration (avcC from
|
||||
MP4 / Matroska; nil for Annex B streams from MPEG-TS / AVI, whose packets carry the parameter sets).
|
||||
- `receive(self) -> image?, pts?, keyframe?`: the next picture in display order and the pts (track ticks) of the packet
|
||||
it came from. Return a fresh `yuv420p` Image (set `image.meta.yuv = { range = "limited", matrix = "bt601" }`).
|
||||
- `flush(self)`: end of stream (release pictures held for reordering). `reset(self)`: after a seek.
|
||||
|
||||
`Video.simpleDecoder(decodeOne, reset)` wraps a codec with one picture per packet and no reordering. Encoders are an
|
||||
entry's `encode(image, opts) -> buffer` (MJPEG), used by the writers when they cannot copy the source's packets.
|
||||
|
||||
## Speed (one Zen 5 core, `taskset -c 2`)
|
||||
|
||||
Whole pipeline (`F.video.open` + `nextFrame`, yuv / rgba output): see `tools/bench.luau` (ws-video block) and the
|
||||
codec lines (ws-video-codecs, VP8).
|
||||
+6
-2
@@ -19,8 +19,10 @@
|
||||
| `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code |
|
||||
| `src/Formats/audio/mp3/EncTables.luau` (ws-audio encoders) | PDMP3 by Krister Lagerström et al. (https://github.com/technosaurus/PDMP3): the ISO/IEC 11172-3 synthesis window and layer III Huffman trees | public domain (unlicense): [PDMP3-UNLICENSE.txt](PDMP3-UNLICENSE.txt) |
|
||||
| `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code |
|
||||
| `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. |
|
||||
| `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above |
|
||||
| `src/Formats/codecs/Jpeg/` (Decode, Scan, Color, Yuv; moved from image/jpeg), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. |
|
||||
| `src/Formats/codecs/Jpeg/Arith.luau`, `src/Formats/codecs/Jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above |
|
||||
| `src/Formats/codecs/Mpeg1/` (init, Decoder, Vlc, Tables) | mpeg1-luau e2e2898 (same author), a port of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, src/mpeg1.js; the tables are generated from it) by Dominic Szablewski | MIT: [jsmpeg-MIT.txt](jsmpeg-MIT.txt) |
|
||||
| `src/Formats/containers/MpegTs/` | mpegts-luau 6e16197 (same author), written from ISO/IEC 13818-1 | no licence chosen yet; no third-party code |
|
||||
| `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data |
|
||||
| `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code |
|
||||
| `src/Formats/audio/opus/CeltEncoder.luau`, `src/Formats/audio/opus/RangeEncoder.luau` | the encoder side of libopus 1.6 (celt_encoder.c, entenc.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c), ported to mirror the absorbed decoder; analysis simplified (ws-m4a) | libopus BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) |
|
||||
@@ -32,6 +34,8 @@
|
||||
| `src/Formats/codecs/Tracker/`, `src/Formats/music/{mod,s3m,xm,it}/` | written for this library from the format documents: ProTracker 2.3 effect docs, the XM specification (Mr.H / Triton) and FT2 behaviour notes, ST3 TECH.DOC (Sami Tammilehto / Future Crew), ITTECH.TXT (Jeffrey Lim); OpenMPT (libopenmpt, BSD) was used only as the reference player in the tests, and its documented playback quirks (mix levels, MOD panning, FT2 E6x / tremor / instrument behaviour) are matched | no third-party code |
|
||||
| `tools/fixtures/{mod,s3m,xm,it}.py` test modules | generated by the fixture scripts (synthesized samples) | no third-party data |
|
||||
| `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-LICENSE.txt) |
|
||||
| `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) |
|
||||
|
||||
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").
|
||||
@@ -0,0 +1,8 @@
|
||||
The MIT License (MIT)
|
||||
Copyright (c) 2017 Dominic Szablewski
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,56 @@
|
||||
Copyright (c) 2010, The WebM Project authors. All rights reserved.
|
||||
|
||||
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 Google, nor the WebM Project, 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 COPYRIGHT
|
||||
HOLDER 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.
|
||||
|
||||
|
||||
----- PATENTS -----
|
||||
Additional IP Rights Grant (Patents)
|
||||
------------------------------------
|
||||
|
||||
"These implementations" means the copyrightable works that implement the WebM
|
||||
codecs distributed by Google as part of the WebM Project.
|
||||
|
||||
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
|
||||
royalty-free, irrevocable (except as stated in this section) patent license to
|
||||
make, have made, use, offer to sell, sell, import, transfer, and otherwise
|
||||
run, modify and propagate the contents of these implementations of WebM, where
|
||||
such license applies only to those patent claims, both currently owned by
|
||||
Google and acquired in the future, licensable by Google that are necessarily
|
||||
infringed by these implementations of WebM. This grant does not include claims
|
||||
that would be infringed only as a consequence of further modification of these
|
||||
implementations. If you or your agent or exclusive licensee institute or order
|
||||
or agree to the institution of patent litigation or any other patent
|
||||
enforcement activity against any entity (including a cross-claim or
|
||||
counterclaim in a lawsuit) alleging that any of these implementations of WebM
|
||||
or any code incorporated within any of these implementations of WebM
|
||||
constitute direct or contributory patent infringement, or inducement of
|
||||
patent infringement, then any patent rights granted to you under this License
|
||||
for these implementations of WebM shall terminate as of the date such
|
||||
litigation is filed.
|
||||
@@ -68,7 +68,7 @@ local list: { Entry } = {
|
||||
path = "image/jpeg",
|
||||
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
||||
mime = { "image/jpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
|
||||
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
|
||||
load = function()
|
||||
return require("@formats/image/jpeg")
|
||||
@@ -278,6 +278,78 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/wav")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "avi",
|
||||
category = "video",
|
||||
path = "video/avi",
|
||||
extensions = { "avi" },
|
||||
mime = { "video/x-msvideo", "video/avi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
|
||||
load = function()
|
||||
return require("@formats/video/avi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mkv",
|
||||
category = "video",
|
||||
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/Deflate", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
|
||||
load = function()
|
||||
return require("@formats/video/mkv")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mp4",
|
||||
category = "video",
|
||||
path = "video/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", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
|
||||
load = function()
|
||||
return require("@formats/video/mp4")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mpegps",
|
||||
category = "video",
|
||||
path = "video/mpegps",
|
||||
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
|
||||
mime = { "video/mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
|
||||
load = function()
|
||||
return require("@formats/video/mpegps")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mpegts",
|
||||
category = "video",
|
||||
path = "video/mpegts",
|
||||
extensions = { "ts", "m2ts", "mts", "tsv" },
|
||||
mime = { "video/mp2t" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
|
||||
load = function()
|
||||
return require("@formats/video/mpegts")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "y4m",
|
||||
category = "video",
|
||||
path = "video/y4m",
|
||||
extensions = { "y4m" },
|
||||
mime = { "video/x-yuv4mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } },
|
||||
load = function()
|
||||
return require("@formats/video/y4m")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "3mf",
|
||||
category = "model",
|
||||
|
||||
+67
-15
@@ -163,38 +163,90 @@ end
|
||||
Types.Midi = Midi
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Video
|
||||
-- A video file opens (F.video.open / a video format's open) as a VideoDecoder; F.load returns the same object (kind =
|
||||
-- "video", decoded lazily). Underneath sits a Demuxer: the container's tracks and their packets. Video tracks decode
|
||||
-- through the codec registry (codecs/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through
|
||||
-- the audio formats (the api hook opts.openAudio, since a format never requires another format).
|
||||
--
|
||||
-- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts
|
||||
-- / duration and every `duration` / `seek` argument are seconds.
|
||||
export type Track = {
|
||||
id: number,
|
||||
id: number, -- the container's track number (Matroska TrackNumber, AVI stream index + 1, TS PID, ...)
|
||||
kind: "video" | "audio" | "subtitle" | "data",
|
||||
codec: string, -- "h264", "vp8", "mpeg1", "mjpeg", "aac", "mp3", "opus", ...
|
||||
timescale: number, -- ticks per second for pts / duration
|
||||
codec: string, -- our codec id: "vp8", "mjpeg", "mpeg1", "h264", "rawvideo"; "pcm_s16le", "mp3", "opus", "vorbis", ...
|
||||
codecTag: string?, -- the container's own id ("V_VP8", "MJPG", stream_type "0x01", "avc1", ...)
|
||||
timescale: number, -- ticks per second for pts / dts / duration
|
||||
duration: number?, -- seconds
|
||||
default: boolean?,
|
||||
language: string?,
|
||||
name: string?,
|
||||
-- video
|
||||
width: number?,
|
||||
height: number?,
|
||||
frameRate: number?, -- frames per second (nominal; 0 / nil when unknown)
|
||||
pixelFormat: string?, -- raw video: "yuv420p", "rgb24", "bgr24", ...
|
||||
-- audio
|
||||
sampleRate: number?,
|
||||
channels: number?,
|
||||
config: buffer?, -- codec configuration (avcC, CodecPrivate, ...)
|
||||
bitsPerSample: number?,
|
||||
config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...)
|
||||
[string]: any,
|
||||
}
|
||||
export type Packet = { track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer }
|
||||
export type Packet = {
|
||||
track: number, -- Track.id
|
||||
pts: number, -- presentation time, ticks
|
||||
dts: number?, -- decode time, ticks (nil = pts)
|
||||
duration: number?, -- ticks
|
||||
keyframe: boolean,
|
||||
data: buffer, -- the packet's bytes (its own buffer)
|
||||
}
|
||||
export type Demuxer = {
|
||||
kind: "demuxer",
|
||||
format: string, -- the container format name
|
||||
tracks: { Track },
|
||||
duration: number,
|
||||
-- packets(trackId?) -> iterator of Packets in file order (one track, or all)
|
||||
duration: number, -- seconds (0 = unknown)
|
||||
startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it)
|
||||
meta: { [string]: any }, -- title, tags, ...
|
||||
-- packets(trackId?) -> iterator of Packets in file order (one track, or all), from the current position
|
||||
packets: (self: any, track: number?) -> () -> Packet?,
|
||||
seek: ((self: any, seconds: number) -> ())?,
|
||||
-- read(trackId?) -> the next Packet (one track, or any) | nil at the end
|
||||
read: (self: any, track: number?) -> Packet?,
|
||||
-- seek(seconds): every track to its last keyframe at or before the time
|
||||
seek: (self: any, seconds: number) -> (),
|
||||
track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind
|
||||
}
|
||||
export type VideoFrame = {
|
||||
image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed)
|
||||
pts: number, -- seconds from the start of the stream (the demuxer's startTime)
|
||||
duration: number, -- seconds
|
||||
keyframe: boolean?,
|
||||
index: number, -- 1-based, in output order
|
||||
}
|
||||
export type VideoFrame = { image: Image, pts: number, duration: number }
|
||||
export type VideoDecoder = {
|
||||
kind: "video",
|
||||
format: string, -- the container format name ("mkv", "avi", "gif", ...)
|
||||
codec: string, -- the video codec id ("vp8", "mjpeg", "frames" for animated images)
|
||||
width: number,
|
||||
height: number,
|
||||
frameRate: number,
|
||||
duration: number,
|
||||
frameRate: number, -- frames per second (nominal)
|
||||
frames: number, -- frame count when known (0 = unknown)
|
||||
duration: number, -- seconds
|
||||
track: Track?, -- the video track decoded
|
||||
nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end
|
||||
toRGBA: (self: any, frame: VideoFrame) -> Image,
|
||||
seek: ((self: any, seconds: number) -> ())?,
|
||||
audio: Decoder?, -- the first audio track, decoded
|
||||
demuxer: Demuxer?,
|
||||
toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8)
|
||||
seek: (self: any, seconds: number) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it)
|
||||
reset: (self: any) -> (), -- back to the start
|
||||
audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError)
|
||||
audioError: Err?,
|
||||
demuxer: Demuxer?, -- nil for frames-backed videos (animated images)
|
||||
meta: { [string]: any },
|
||||
}
|
||||
-- a codec's decoder instance (codecs/Video registry entries create them): packets in, pictures out
|
||||
export type VideoCodecDecoder = {
|
||||
decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order)
|
||||
receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil
|
||||
flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive()
|
||||
reset: (self: any) -> (), -- after a seek: drop references / held pictures
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
|
||||
-- codecs/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
|
||||
-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
|
||||
-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
|
||||
--
|
||||
@@ -1,7 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
|
||||
-- codecs/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
|
||||
-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
|
||||
-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
|
||||
--
|
||||
@@ -1,12 +1,15 @@
|
||||
--!strict
|
||||
-- image/jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
|
||||
-- Arith / Dct / Color loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
|
||||
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a reader range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
|
||||
-- / JFIF density collected for meta. The IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c.
|
||||
local Scan = require("@formats/image/jpeg/Scan")
|
||||
local Arith = require("@formats/image/jpeg/Arith")
|
||||
local Color = require("@formats/image/jpeg/Color")
|
||||
local Tables = require("@formats/image/jpeg/Tables")
|
||||
-- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
|
||||
-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
|
||||
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
|
||||
-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a
|
||||
-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows
|
||||
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats.
|
||||
local Scan = require("@formats/codecs/Jpeg/Scan")
|
||||
local Arith = require("@formats/codecs/Jpeg/Arith")
|
||||
local Color = require("@formats/codecs/Jpeg/Color")
|
||||
local Tables = require("@formats/codecs/Jpeg/Tables")
|
||||
local Yuv = require("@formats/codecs/Jpeg/Yuv")
|
||||
local Dct = require("@formats/codecs/Dct")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
@@ -226,6 +229,8 @@ export type State = {
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
scale: number,
|
||||
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
|
||||
endPos: number, -- the byte after the EOI marker (or the end of the data)
|
||||
}
|
||||
|
||||
-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with
|
||||
@@ -255,6 +260,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
comments = {},
|
||||
truncated = false,
|
||||
scale = scale,
|
||||
avi1 = nil,
|
||||
endPos = n,
|
||||
}
|
||||
local iccChunks: { buffer } = {}
|
||||
local ri = 0
|
||||
@@ -277,6 +284,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
local m = readu8(b, pos)
|
||||
pos += 1
|
||||
if m == 0xD9 then
|
||||
st.endPos = pos
|
||||
break -- EOI
|
||||
elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then
|
||||
continue -- standalone markers (or stray stuffing)
|
||||
@@ -303,6 +311,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
|
||||
st.jfif = true
|
||||
st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
|
||||
elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then
|
||||
st.avi1 = readu8(b, p + 4)
|
||||
end
|
||||
elseif m == 0xE1 then
|
||||
local t, o = exif(b, p, e)
|
||||
@@ -663,4 +673,90 @@ function Decode.output(st: State): (number?, any, any, string?)
|
||||
return outW, outH, pixels, space
|
||||
end
|
||||
|
||||
-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the
|
||||
-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion
|
||||
-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half
|
||||
-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma
|
||||
-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray":
|
||||
-- chroma 128). Full scale only (opts.scale = 1).
|
||||
-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes
|
||||
-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame
|
||||
local scratch: buffer? = nil
|
||||
local function scratchPlane(n: number): buffer
|
||||
local sc = scratch
|
||||
if sc and buffer.len(sc) >= n then
|
||||
return sc
|
||||
end
|
||||
local b = buffer.create(n)
|
||||
if n <= 4 * 1024 * 1024 then
|
||||
scratch = b
|
||||
end
|
||||
return b
|
||||
end
|
||||
|
||||
function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
|
||||
local f: Frame = st.frame
|
||||
if st.scale ~= 1 or f.precision ~= 8 then
|
||||
return nil
|
||||
end
|
||||
local comps = f.comps
|
||||
local space = colorSpaceOf(f, st.adobe, st.jfif)
|
||||
local mode = nil
|
||||
if space == "gray" then
|
||||
mode = "gray"
|
||||
elseif space == "ycbcr" then
|
||||
-- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere)
|
||||
local l, cb, cr = comps[1], comps[2], comps[3]
|
||||
if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then
|
||||
local rh, rv = f.hmax // cb.h, f.vmax // cb.v
|
||||
if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then
|
||||
mode = nil
|
||||
elseif rh == 2 and rv == 2 then
|
||||
mode = "420"
|
||||
elseif rh == 2 and rv == 1 then
|
||||
mode = "422"
|
||||
elseif rh == 1 and rv == 1 then
|
||||
mode = "444"
|
||||
end
|
||||
end
|
||||
end
|
||||
if not mode then
|
||||
return nil
|
||||
end
|
||||
for _, c in comps do
|
||||
if c.coef and not c.quant then
|
||||
return nil -- output() reports the missing table
|
||||
end
|
||||
end
|
||||
local w, h = f.width, f.height
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local out = buffer.create(w * h + 2 * cw * ch)
|
||||
local zeroQ: buffer? = nil
|
||||
for i, c in comps do
|
||||
local stride, rows = c.bpl * 8, c.bpc * 8
|
||||
local plane = scratchPlane(stride * rows * 2)
|
||||
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
|
||||
local q = c.quant
|
||||
if not q then
|
||||
zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey
|
||||
q = zeroQ
|
||||
end
|
||||
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255)
|
||||
if i == 1 then
|
||||
Yuv.crop(plane, stride, w, h, out, 0)
|
||||
elseif mode == "420" then
|
||||
Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch)
|
||||
elseif mode == "422" then
|
||||
Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch)
|
||||
else
|
||||
Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch)
|
||||
end
|
||||
c.coef = nil
|
||||
end
|
||||
if mode == "gray" then
|
||||
buffer.fill(out, w * h, 128, 2 * cw * ch)
|
||||
end
|
||||
return w, h, out, mode
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -1,15 +1,16 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
|
||||
-- codecs/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
|
||||
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
|
||||
-- 4:4:4 / 4:2:2 / 4:2:0; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is
|
||||
-- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling
|
||||
-- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c
|
||||
-- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
|
||||
-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG
|
||||
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. It follows libjpeg-turbo's
|
||||
-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c
|
||||
-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication),
|
||||
-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
|
||||
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
|
||||
local Dct = require("@formats/codecs/Dct")
|
||||
local Tables = require("@formats/image/jpeg/Tables")
|
||||
local Tables = require("@formats/codecs/Jpeg/Tables")
|
||||
|
||||
local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
|
||||
local band, countlz = bit32.band, bit32.countlz
|
||||
@@ -574,8 +575,9 @@ export type Options = {
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
}
|
||||
|
||||
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8); the caller
|
||||
-- validated sizes (1..65535) and options.
|
||||
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0:
|
||||
-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The
|
||||
-- caller validated sizes (1..65535), the buffer length and options.
|
||||
function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
|
||||
OUT = buffer.create(math.max(1024, w * h // 2))
|
||||
CAP = buffer.len(OUT)
|
||||
@@ -584,7 +586,19 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
GATHER = false
|
||||
EOBRUN, BE = 0, 0
|
||||
|
||||
local Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
|
||||
local yuv = bpp == 0
|
||||
local Y, Cb, Cr
|
||||
if yuv then
|
||||
local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2)
|
||||
Y = px
|
||||
if not o.gray then
|
||||
Cb, Cr = buffer.create(cn), buffer.create(cn)
|
||||
buffer.copy(Cb :: buffer, 0, px, n, cn)
|
||||
buffer.copy(Cr :: buffer, 0, px, n + cn, cn)
|
||||
end
|
||||
else
|
||||
Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
|
||||
end
|
||||
local hs, vs = 1, 1
|
||||
if not o.gray then
|
||||
if o.sampling == "420" then
|
||||
@@ -615,7 +629,9 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
|
||||
local bpl, bpc = mcusX * ch, mcusY * cv
|
||||
local plane, pw, ph = src, w, h
|
||||
if ch < hs or cv < vs then
|
||||
if yuv and i > 1 then
|
||||
pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does
|
||||
elseif ch < hs or cv < vs then
|
||||
pw, ph = bw * 8, chh
|
||||
plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
|
||||
end
|
||||
@@ -1,7 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
|
||||
-- codecs/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
|
||||
-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
|
||||
--
|
||||
-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
|
||||
@@ -1,5 +1,5 @@
|
||||
--!strict
|
||||
-- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
|
||||
-- codecs/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
|
||||
-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
|
||||
-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
|
||||
local Tables = {}
|
||||
@@ -0,0 +1,76 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
|
||||
-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4
|
||||
-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG).
|
||||
-- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes.
|
||||
local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Yuv = {}
|
||||
|
||||
-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8
|
||||
-- samples at dst[doff], w per row
|
||||
function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local quads = w // 4
|
||||
local rest = w - quads * 4
|
||||
for y = 0, h - 1 do
|
||||
local s = y * stride * 2
|
||||
local d = doff + y * w
|
||||
-- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write
|
||||
for _ = 1, quads do
|
||||
local a, b = readu32(src, s), readu32(src, s + 4)
|
||||
writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216)
|
||||
s += 8
|
||||
d += 4
|
||||
end
|
||||
for k = 0, rest - 1 do
|
||||
writeu8(dst, d + k, readu16(src, s + k * 2))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output
|
||||
-- row the rounded mean of two source rows (the last row alone when h is odd)
|
||||
function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local oh = (h + 1) // 2
|
||||
for y = 0, oh - 1 do
|
||||
local a = 2 * y * stride * 2
|
||||
local b = if 2 * y + 1 < h then a + stride * 2 else a
|
||||
local d = doff + y * w
|
||||
for x = 0, w - 1 do
|
||||
writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2),
|
||||
-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column)
|
||||
function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local ow, oh = (w + 1) // 2, (h + 1) // 2
|
||||
for y = 0, oh - 1 do
|
||||
local a = 2 * y * stride * 2
|
||||
local b = if 2 * y + 1 < h then a + stride * 2 else a
|
||||
local d = doff + y * ow
|
||||
for x = 0, ow - 1 do
|
||||
local x0 = 2 * x * 2
|
||||
local x1 = if 2 * x + 1 < w then x0 + 2 else x0
|
||||
writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field
|
||||
-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2)
|
||||
function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number)
|
||||
for y = 0, rows - 1 do
|
||||
local k = y // 2
|
||||
if y % 2 == 0 then
|
||||
buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes)
|
||||
else
|
||||
buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Yuv
|
||||
@@ -0,0 +1,387 @@
|
||||
--!strict
|
||||
-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
||||
-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and
|
||||
-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
|
||||
-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's
|
||||
-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
|
||||
--
|
||||
-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image
|
||||
-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes
|
||||
-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer
|
||||
-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header
|
||||
--
|
||||
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
|
||||
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
|
||||
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation
|
||||
-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go
|
||||
-- (meta.truncated = true).
|
||||
-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field
|
||||
-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame
|
||||
-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even
|
||||
-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field
|
||||
-- leaves the first field alone (meta.source.fields = 1).
|
||||
-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour
|
||||
-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera
|
||||
-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other
|
||||
-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format).
|
||||
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
|
||||
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments
|
||||
-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion).
|
||||
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding.
|
||||
-- Never throws: bad data or arguments return nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/codecs/Jpeg/Decode")
|
||||
local Encode = require("@formats/codecs/Jpeg/Encode")
|
||||
local Yuv = require("@formats/codecs/Jpeg/Yuv")
|
||||
|
||||
local Jpeg = {}
|
||||
|
||||
export type DecodeOptions = {
|
||||
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
|
||||
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8)
|
||||
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
|
||||
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
|
||||
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
|
||||
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0)
|
||||
progressive: boolean?, -- default false
|
||||
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
|
||||
gray: boolean?, -- a one-component file (default: true for gray8 images)
|
||||
restart: number?, -- restart interval in MCUs (default 0 = none)
|
||||
jfif: boolean?, -- write the JFIF APP0 header (default true)
|
||||
density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1)
|
||||
segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header
|
||||
}
|
||||
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
components: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
precision: number,
|
||||
colorSpace: string,
|
||||
sampling: { { number } }, -- { h, v } per component
|
||||
orientation: number,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header
|
||||
}
|
||||
|
||||
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
|
||||
|
||||
local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(math.floor(tonumber(off) or 0), 0, n)
|
||||
return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o)
|
||||
end
|
||||
|
||||
-- the marker parser over [o, o + l): State | nil, Err
|
||||
local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
|
||||
local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
|
||||
end
|
||||
if not st then
|
||||
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o)
|
||||
end
|
||||
return st, nil
|
||||
end
|
||||
|
||||
local function samplingOf(f: any): { { number } }
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
return sampling
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header)
|
||||
function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected a buffer")
|
||||
end
|
||||
local o, l = range(buf, off, len)
|
||||
local st, err = parse(buf, o, l, nil, true)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local f = st.frame
|
||||
return {
|
||||
width = f.width,
|
||||
height = f.height,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
precision = f.precision,
|
||||
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
|
||||
sampling = samplingOf(f),
|
||||
orientation = st.orientation,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
avi1 = st.avi1,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
|
||||
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
|
||||
if o <= 1 or o > 8 then
|
||||
return px, w, h
|
||||
end
|
||||
local swap = o >= 5
|
||||
local ow, oh = if swap then h else w, if swap then w else h
|
||||
local out = buffer.create(ow * oh * 4)
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
for y = 0, oh - 1 do
|
||||
for x = 0, ow - 1 do
|
||||
local col, row
|
||||
if o == 2 then
|
||||
col, row = w - 1 - x, y
|
||||
elseif o == 3 then
|
||||
col, row = w - 1 - x, h - 1 - y
|
||||
elseif o == 4 then
|
||||
col, row = x, h - 1 - y
|
||||
elseif o == 5 then
|
||||
col, row = y, x
|
||||
elseif o == 6 then
|
||||
col, row = y, h - 1 - x
|
||||
elseif o == 7 then
|
||||
col, row = w - 1 - y, h - 1 - x
|
||||
else
|
||||
col, row = w - 1 - y, x
|
||||
end
|
||||
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
|
||||
end
|
||||
end
|
||||
return out, ow, oh
|
||||
end
|
||||
|
||||
-- one JPEG at [o, o + l): Image, State | nil, Err
|
||||
local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any)
|
||||
local st, err = parse(buf, o, l, opts, false)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local s = st :: Decode.State
|
||||
local img = Types.Image.new(0, 0)
|
||||
local space, mode = nil, nil
|
||||
if opts and opts.yuv then
|
||||
local ok, w, h, px, m = pcall(Decode.outputYuv, s)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if w then
|
||||
img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p"
|
||||
mode = m
|
||||
space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif)
|
||||
end
|
||||
end
|
||||
if not mode then
|
||||
local ok, w, h, px, sp = pcall(Decode.output, s)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if not w then
|
||||
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o)
|
||||
end
|
||||
space = sp
|
||||
if opts and opts.orient then
|
||||
px, w, h = orient(px, w, h, s.orientation)
|
||||
end
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
if opts and opts.native and space == "gray" then
|
||||
local g = buffer.create(w * h)
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
|
||||
end
|
||||
img.pixels, img.format = g, "gray8"
|
||||
end
|
||||
end
|
||||
local f = s.frame
|
||||
local meta = img.meta
|
||||
meta.orientation = s.orientation
|
||||
meta.oriented = (opts and opts.orient and not mode) or false
|
||||
meta.exif = s.exif
|
||||
meta.icc = s.icc
|
||||
if #s.comments > 0 then
|
||||
meta.text = { comment = table.concat(s.comments, "\n") }
|
||||
end
|
||||
if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then
|
||||
local k = if s.density.unit == 2 then 2.54 else 1
|
||||
meta.dpi = { x = s.density.x * k, y = s.density.y * k }
|
||||
end
|
||||
meta.truncated = s.truncated
|
||||
meta.source = {
|
||||
format = "jpeg",
|
||||
bitDepth = f.precision,
|
||||
colorType = space,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
sampling = samplingOf(f),
|
||||
scale = s.scale,
|
||||
adobe = s.adobe,
|
||||
jfif = s.jfif,
|
||||
avi1 = s.avi1,
|
||||
yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv)
|
||||
range = if mode then "full" else nil,
|
||||
fields = 1,
|
||||
}
|
||||
return img, s
|
||||
end
|
||||
|
||||
-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none
|
||||
local function nextSoi(buf: buffer, p: number, e: number): number
|
||||
local readu8 = buffer.readu8
|
||||
while p + 3 <= e do
|
||||
if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then
|
||||
return p
|
||||
end
|
||||
p += 1
|
||||
end
|
||||
return -1
|
||||
end
|
||||
|
||||
-- two fields (same size and format) -> one frame of twice the height, field a on the even rows
|
||||
local function weave(a: Types.Image, b: Types.Image): Types.Image
|
||||
local w, hf = a.width, a.height
|
||||
local h = hf * 2
|
||||
local out = Types.Image.new(w, h, a.format)
|
||||
local dst = out.pixels
|
||||
if a.format == "yuv420p" then
|
||||
local cw, chf = (w + 1) // 2, (hf + 1) // 2
|
||||
local ch = (h + 1) // 2 -- = hf
|
||||
Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0)
|
||||
for k = 0, 1 do
|
||||
Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch)
|
||||
end
|
||||
else
|
||||
local bpp = Types.Image.bpp(a.format) or 4
|
||||
Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0)
|
||||
end
|
||||
out.meta = a.meta
|
||||
return out
|
||||
end
|
||||
|
||||
-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len)
|
||||
function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected a buffer")
|
||||
end
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local o, l = range(buf, off, len)
|
||||
local img, st = decodeOne(buf, o, l, opts)
|
||||
if not img then
|
||||
return nil, st
|
||||
end
|
||||
local s = st :: Decode.State
|
||||
local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2)
|
||||
if wantFields and not (opts and opts.orient) then
|
||||
local e = o + l
|
||||
local p = nextSoi(buf, s.endPos, e)
|
||||
if p >= 0 then
|
||||
local o2 = table.clone(opts or {}) :: any
|
||||
if o2.maxPixels then
|
||||
o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height)
|
||||
end
|
||||
local b = decodeOne(buf, p, e - p, o2)
|
||||
if b and b.width == img.width and b.height == img.height and b.format == img.format then
|
||||
local truncated = img.meta.truncated or b.meta.truncated
|
||||
img = weave(img, b)
|
||||
img.meta.truncated = truncated
|
||||
local source: any = img.meta.source
|
||||
source.fields = 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 }
|
||||
|
||||
-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local bpp = BPP[img.format]
|
||||
if not bpp then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
||||
end
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local quality = o.quality or 90
|
||||
if type(quality) ~= "number" or quality < 1 or quality > 100 then
|
||||
return nil, Err.new(Err.ARG, "quality must be 1..100")
|
||||
end
|
||||
local sub = o.subsampling or "420"
|
||||
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
|
||||
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
|
||||
end
|
||||
if bpp == 0 then
|
||||
sub = "420"
|
||||
end
|
||||
local restart = o.restart or 0
|
||||
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
|
||||
end
|
||||
local gray = o.gray
|
||||
if gray == nil then
|
||||
gray = img.format == "gray8"
|
||||
end
|
||||
local segments = {}
|
||||
if o.segments ~= nil then
|
||||
if type(o.segments) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }")
|
||||
end
|
||||
for _, sg in o.segments do
|
||||
if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)")
|
||||
end
|
||||
if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then
|
||||
return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)")
|
||||
end
|
||||
table.insert(segments, sg)
|
||||
end
|
||||
end
|
||||
local density = o.density
|
||||
if density ~= nil then
|
||||
if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "bad density")
|
||||
end
|
||||
density = {
|
||||
unit = math.clamp(math.floor(density.unit), 0, 2),
|
||||
x = math.clamp(math.floor(density.x), 1, 65535),
|
||||
y = math.clamp(math.floor(density.y), 1, 65535),
|
||||
}
|
||||
end
|
||||
local out = Encode.run(img.pixels, w, h, bpp, {
|
||||
quality = quality,
|
||||
sampling = sub,
|
||||
progressive = o.progressive == true,
|
||||
optimize = o.optimize == true,
|
||||
gray = gray,
|
||||
restart = restart,
|
||||
segments = segments,
|
||||
jfif = o.jfif ~= false,
|
||||
density = density,
|
||||
})
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Jpeg
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
--!strict
|
||||
-- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
|
||||
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from
|
||||
-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays.
|
||||
local T = {}
|
||||
T.PICTURE_RATE = { [0] = 0.0,
|
||||
23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
|
||||
}
|
||||
T.ZIG_ZAG = { [0] = 0,
|
||||
1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
|
||||
20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58,
|
||||
59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
|
||||
}
|
||||
T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8,
|
||||
16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22,
|
||||
22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26,
|
||||
27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83,
|
||||
}
|
||||
T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16,
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
}
|
||||
T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3,
|
||||
6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0,
|
||||
0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0,
|
||||
0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99,
|
||||
102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135,
|
||||
138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1,
|
||||
144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1,
|
||||
186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0,
|
||||
0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0,
|
||||
0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0,
|
||||
0, 24, 0, 0, 23, 0, 0, 22,
|
||||
}
|
||||
T.MACROBLOCK_TYPE_INTRA = { [0] = 3,
|
||||
6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17,
|
||||
}
|
||||
T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3,
|
||||
6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33,
|
||||
36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17,
|
||||
}
|
||||
T.MACROBLOCK_TYPE_B = { [0] = 3,
|
||||
6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36,
|
||||
33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0,
|
||||
0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26,
|
||||
}
|
||||
T.CODE_BLOCK_PATTERN = { [0] = 6,
|
||||
3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54,
|
||||
48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132,
|
||||
144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129,
|
||||
102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0,
|
||||
0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171,
|
||||
174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0,
|
||||
0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0,
|
||||
0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264,
|
||||
246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0,
|
||||
0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270,
|
||||
276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336,
|
||||
333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0,
|
||||
0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0,
|
||||
0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0,
|
||||
0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0,
|
||||
0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31,
|
||||
}
|
||||
T.MOTION = { [0] = 3,
|
||||
6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36,
|
||||
33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51,
|
||||
57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108,
|
||||
105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0,
|
||||
0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156,
|
||||
141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0,
|
||||
0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0,
|
||||
0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0,
|
||||
0, -15, 0, 0, -11, 0, 0, -13,
|
||||
}
|
||||
T.DCT_DC_SIZE_LUMINANCE = { [0] = 6,
|
||||
3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36,
|
||||
33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0,
|
||||
0, 7, 0, 0, 8,
|
||||
}
|
||||
T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6,
|
||||
3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0,
|
||||
0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0,
|
||||
0, 7, 0, 0, 8,
|
||||
}
|
||||
T.DCT_COEFF = { [0] = 3,
|
||||
6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0,
|
||||
0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81,
|
||||
75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0,
|
||||
0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120,
|
||||
123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0,
|
||||
0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0,
|
||||
0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201,
|
||||
210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273,
|
||||
240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0,
|
||||
0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333,
|
||||
342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339,
|
||||
309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417,
|
||||
420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411,
|
||||
399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0,
|
||||
0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0,
|
||||
0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510,
|
||||
483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549,
|
||||
546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0,
|
||||
0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0,
|
||||
0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0,
|
||||
0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0,
|
||||
0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0,
|
||||
0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654,
|
||||
633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657,
|
||||
624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0,
|
||||
0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0,
|
||||
0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0,
|
||||
0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842,
|
||||
}
|
||||
return T
|
||||
@@ -0,0 +1,116 @@
|
||||
--!strict
|
||||
-- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
|
||||
--
|
||||
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds
|
||||
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level
|
||||
-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF,
|
||||
-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the
|
||||
-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one
|
||||
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but
|
||||
-- for this header and the require.
|
||||
local T = require("@formats/codecs/Mpeg1/Tables")
|
||||
|
||||
local V = {}
|
||||
|
||||
type Leaf = { code: number, len: number, value: number }
|
||||
|
||||
local function leaves(tree: { [number]: number }): { Leaf }
|
||||
local out: { Leaf } = {}
|
||||
local function walk(state: number, code: number, len: number)
|
||||
if tree[state] == 0 and len > 0 then
|
||||
table.insert(out, { code = code, len = len, value = tree[state + 2] })
|
||||
return
|
||||
end
|
||||
for bit = 0, 1 do
|
||||
local nxt = tree[state + bit]
|
||||
if nxt ~= nil and nxt > 0 then
|
||||
walk(nxt, code * 2 + bit, len + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(0, 0, 0)
|
||||
return out
|
||||
end
|
||||
|
||||
local function flat(tree: { [number]: number }): (buffer, number)
|
||||
local ls = leaves(tree)
|
||||
local k = 0
|
||||
for _, l in ls do
|
||||
k = math.max(k, l.len)
|
||||
end
|
||||
local lut = buffer.create(4 * 2 ^ k)
|
||||
for _, l in ls do
|
||||
local shift = k - l.len
|
||||
local first = l.code * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768)
|
||||
end
|
||||
end
|
||||
return lut, k
|
||||
end
|
||||
|
||||
V.SUB = 0x1000000
|
||||
V.ESC = 0xFFFF
|
||||
V.EOB = 0xFFFE
|
||||
|
||||
-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits
|
||||
local function twoLevel(ls: { Leaf }): buffer
|
||||
local subs: { [number]: number } = {}
|
||||
local nsub = 0
|
||||
for _, l in ls do
|
||||
if l.len > 8 then
|
||||
local prefix = l.code // 2 ^ (l.len - 8)
|
||||
if subs[prefix] == nil then
|
||||
nsub += 1
|
||||
subs[prefix] = nsub
|
||||
end
|
||||
end
|
||||
end
|
||||
local lut = buffer.create(4 * 256 * (1 + nsub))
|
||||
for _, l in ls do
|
||||
if l.len <= 8 then
|
||||
local shift = 8 - l.len
|
||||
local first = l.code * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value)
|
||||
end
|
||||
else
|
||||
local prefix = l.code // 2 ^ (l.len - 8)
|
||||
local s = subs[prefix]
|
||||
buffer.writeu32(lut, prefix * 4, V.SUB + s)
|
||||
local rest = l.code % 2 ^ (l.len - 8)
|
||||
local shift = 16 - l.len
|
||||
local first = rest * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value)
|
||||
end
|
||||
end
|
||||
end
|
||||
return lut
|
||||
end
|
||||
|
||||
V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape
|
||||
V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA)
|
||||
V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE)
|
||||
V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B)
|
||||
V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN)
|
||||
V.MOTION, V.MOTION_BITS = flat(T.MOTION)
|
||||
V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE)
|
||||
V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE)
|
||||
|
||||
do
|
||||
local ls = leaves(T.DCT_COEFF)
|
||||
V.DCT_FIRST = twoLevel(ls)
|
||||
local nextLs: { Leaf } = {}
|
||||
for _, l in ls do
|
||||
if l.len == 1 and l.code == 1 then
|
||||
table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10"
|
||||
table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11"
|
||||
else
|
||||
table.insert(nextLs, l)
|
||||
end
|
||||
end
|
||||
V.DCT_NEXT = twoLevel(nextLs)
|
||||
end
|
||||
|
||||
return V
|
||||
@@ -0,0 +1,262 @@
|
||||
--!strict
|
||||
-- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
|
||||
-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder
|
||||
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures,
|
||||
-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage.
|
||||
-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom
|
||||
-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display
|
||||
-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau).
|
||||
-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding.
|
||||
--
|
||||
-- local dec = Mpeg1.new({ reorder = true, rgba = false })
|
||||
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
|
||||
-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
|
||||
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
|
||||
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
|
||||
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... }
|
||||
--
|
||||
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
|
||||
local Types = require("@formats/Types")
|
||||
local D = require("@formats/codecs/Mpeg1/Decoder")
|
||||
|
||||
local Mpeg1 = {}
|
||||
|
||||
Mpeg1.PICTURE_I = 1
|
||||
Mpeg1.PICTURE_P = 2
|
||||
Mpeg1.PICTURE_B = 3
|
||||
|
||||
export type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
|
||||
pictureType: number, -- 1 I, 2 P, 3 B
|
||||
temporalReference: number, -- the picture's 10-bit display index within its GOP
|
||||
index: number, -- frames returned so far (1-based)
|
||||
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
|
||||
-- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth,
|
||||
-- chroma stride codedWidth / 2
|
||||
y: buffer,
|
||||
cb: buffer,
|
||||
cr: buffer,
|
||||
codedWidth: number,
|
||||
}
|
||||
|
||||
export type Options = {
|
||||
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
|
||||
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
|
||||
-- display order for streams without B-frames.
|
||||
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
|
||||
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
|
||||
}
|
||||
|
||||
local Decoder = {}
|
||||
Decoder.__index = Decoder
|
||||
|
||||
export type Decoder = typeof(setmetatable(
|
||||
{} :: {
|
||||
_core: D.Core,
|
||||
_reorder: boolean,
|
||||
_rgba: boolean,
|
||||
_held: D.Store?,
|
||||
_pixels: buffer?,
|
||||
_count: number,
|
||||
width: number,
|
||||
height: number,
|
||||
frameRate: number,
|
||||
bitRate: number,
|
||||
stats: { pictures: number, errors: number, skipped: number },
|
||||
},
|
||||
Decoder
|
||||
))
|
||||
|
||||
function Mpeg1.new(opts: Options?): Decoder
|
||||
local o: Options = if type(opts) == "table" then opts else {}
|
||||
local core = D.new(o.maxPixels)
|
||||
return setmetatable({
|
||||
_core = core,
|
||||
_reorder = o.reorder == true,
|
||||
_rgba = o.rgba ~= false,
|
||||
_held = nil,
|
||||
_pixels = nil,
|
||||
_count = 0,
|
||||
width = 0,
|
||||
height = 0,
|
||||
frameRate = 0,
|
||||
bitRate = 0,
|
||||
stats = { pictures = 0, errors = 0, skipped = 0 },
|
||||
}, Decoder)
|
||||
end
|
||||
|
||||
local function emit(self: Decoder, s: D.Store): Frame
|
||||
local core = self._core
|
||||
local pixels: buffer? = nil
|
||||
if self._rgba then
|
||||
local need = s.w * s.h * 4
|
||||
local px = self._pixels
|
||||
if px == nil or buffer.len(px) ~= need then
|
||||
px = buffer.create(need)
|
||||
self._pixels = px
|
||||
end
|
||||
core.toRgba(s, px :: buffer)
|
||||
pixels = px
|
||||
end
|
||||
self._count += 1
|
||||
return {
|
||||
width = s.w,
|
||||
height = s.h,
|
||||
pixels = pixels,
|
||||
pictureType = s.ptype,
|
||||
temporalReference = s.tref,
|
||||
index = self._count,
|
||||
tag = s.tag,
|
||||
y = s.y,
|
||||
cb = s.cb,
|
||||
cr = s.cr,
|
||||
codedWidth = s.cw,
|
||||
}
|
||||
end
|
||||
|
||||
local function sync(self: Decoder)
|
||||
local st = self._core.state
|
||||
self.width = st.width
|
||||
self.height = st.height
|
||||
self.frameRate = st.frameRate
|
||||
self.bitRate = st.bitRate
|
||||
self.stats.pictures = st.pictures
|
||||
self.stats.errors = st.errors
|
||||
self.stats.skipped = st.skipped
|
||||
end
|
||||
|
||||
-- a decoded picture -> the frame to return now (nil while reordering holds it)
|
||||
local function handle(self: Decoder, s: D.Store): Frame?
|
||||
if not self._reorder or s.ptype == D.PICTURE_B then
|
||||
return emit(self, s)
|
||||
end
|
||||
local prev = self._held
|
||||
self._held = s
|
||||
if prev then
|
||||
return emit(self, prev)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
|
||||
local core = self._core
|
||||
while true do
|
||||
local s, needData = core.nextPicture(atEnd, tag)
|
||||
sync(self)
|
||||
if s then
|
||||
local f = handle(self, s)
|
||||
if f then
|
||||
return f
|
||||
end
|
||||
elseif needData then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
|
||||
local src: buffer
|
||||
if type(data) == "string" then
|
||||
src = buffer.fromstring(data)
|
||||
elseif type(data) == "buffer" then
|
||||
src = data
|
||||
else
|
||||
return false
|
||||
end
|
||||
local total = buffer.len(src)
|
||||
local off = math.floor(tonumber(offset) or 0)
|
||||
if off < 0 or off > total then
|
||||
return false
|
||||
end
|
||||
local n = math.floor(tonumber(len) or (total - off))
|
||||
if n < 0 or off + n > total then
|
||||
return false
|
||||
end
|
||||
self._core.write(src, off, n)
|
||||
return true
|
||||
end
|
||||
|
||||
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
|
||||
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
|
||||
return append(self, data, offset, len)
|
||||
end
|
||||
|
||||
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
|
||||
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
|
||||
function Decoder.decodeFrame(self: Decoder): Frame?
|
||||
return run(self, false, nil)
|
||||
end
|
||||
|
||||
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
|
||||
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
|
||||
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
|
||||
if not append(self, data, offset, len) then
|
||||
return nil
|
||||
end
|
||||
return run(self, true, tag)
|
||||
end
|
||||
|
||||
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
|
||||
-- for reordering. Call until it returns nil.
|
||||
function Decoder.flush(self: Decoder): Frame?
|
||||
local f = run(self, true, nil)
|
||||
if f then
|
||||
return f
|
||||
end
|
||||
local held = self._held
|
||||
if held then
|
||||
self._held = nil
|
||||
return emit(self, held)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
|
||||
function Decoder.reset(self: Decoder)
|
||||
self._core.reset()
|
||||
self._held = nil
|
||||
end
|
||||
|
||||
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
|
||||
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8
|
||||
-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame.
|
||||
function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image?
|
||||
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
|
||||
return nil
|
||||
end
|
||||
local w, h, cw = frame.width, frame.height, frame.codedWidth
|
||||
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
|
||||
return nil
|
||||
end
|
||||
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
|
||||
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then
|
||||
return nil
|
||||
end
|
||||
local img
|
||||
if rgba then
|
||||
img = Types.Image.new(w, h)
|
||||
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
|
||||
else
|
||||
img = Types.Image.new(w, h, "yuv420p")
|
||||
local px = img.pixels
|
||||
for y = 0, h - 1 do
|
||||
buffer.copy(px, y * w, frame.y, y * cw, w)
|
||||
end
|
||||
local o = w * h
|
||||
for y = 0, oh - 1 do
|
||||
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
|
||||
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
|
||||
end
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "mpeg1",
|
||||
pictureType = frame.pictureType,
|
||||
temporalReference = frame.temporalReference,
|
||||
range = if rgba then nil else "limited",
|
||||
}
|
||||
return img
|
||||
end
|
||||
|
||||
return Mpeg1
|
||||
@@ -0,0 +1,305 @@
|
||||
--!strict
|
||||
-- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given:
|
||||
-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either
|
||||
-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM,
|
||||
-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw
|
||||
-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau.
|
||||
--
|
||||
-- local streams, err = Source.streams(value, opts, {
|
||||
-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any)
|
||||
-- audio = { copy = { opus = true, vorbis = true }, pcm = true },
|
||||
-- })
|
||||
-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config,
|
||||
-- -- track, packets = { { pts, duration (seconds), keyframe, data } } }
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Yuv = require("@formats/codecs/Yuv")
|
||||
|
||||
local Source = {}
|
||||
|
||||
export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer }
|
||||
export type Stream = {
|
||||
kind: "video" | "audio",
|
||||
codec: string,
|
||||
copied: boolean,
|
||||
width: number?,
|
||||
height: number?,
|
||||
frameRate: number?,
|
||||
sampleRate: number?,
|
||||
channels: number?,
|
||||
bitsPerSample: number?,
|
||||
config: buffer?,
|
||||
track: Types.Track?,
|
||||
packets: { OutPacket },
|
||||
}
|
||||
export type Want = {
|
||||
video: { copy: { [string]: boolean }?, encode: string? }?,
|
||||
audio: { copy: { [string]: boolean }?, pcm: boolean? }?,
|
||||
}
|
||||
|
||||
local function allows(set: { [string]: boolean }?, codec: string): boolean
|
||||
return set ~= nil and (set[codec] == true or set["*"] == true)
|
||||
end
|
||||
|
||||
-- the packets of a source track, times in seconds
|
||||
local function copyPackets(dmx: any, track: Types.Track): { OutPacket }
|
||||
local out = {}
|
||||
local scale = if track.timescale and track.timescale > 0 then track.timescale else 1
|
||||
local n = dmx:count(track.id)
|
||||
for k = 1, n do
|
||||
local p = dmx:get(track.id, k)
|
||||
if p then
|
||||
table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data })
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function trackStream(track: Types.Track, packets: { OutPacket }): Stream
|
||||
return {
|
||||
kind = track.kind :: any,
|
||||
codec = track.codec,
|
||||
copied = true,
|
||||
width = track.width,
|
||||
height = track.height,
|
||||
frameRate = track.frameRate,
|
||||
sampleRate = track.sampleRate,
|
||||
channels = track.channels,
|
||||
bitsPerSample = track.bitsPerSample,
|
||||
config = track.config,
|
||||
track = track,
|
||||
packets = packets,
|
||||
}
|
||||
end
|
||||
|
||||
-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo":
|
||||
-- yuv420p planes)
|
||||
local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?)
|
||||
local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil
|
||||
if codec ~= "rawvideo" then
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local e = Video.entry(codec)
|
||||
encode = e and e.encode
|
||||
if not encode then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder")
|
||||
end
|
||||
end
|
||||
if type(v.reset) == "function" then
|
||||
v:reset()
|
||||
end
|
||||
local packets: { OutPacket } = {}
|
||||
local w, h = v.width, v.height
|
||||
local maxFrames = opts.maxFrames or math.huge
|
||||
while #packets < maxFrames do
|
||||
local f, err = v:nextFrame()
|
||||
if not f then
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
break
|
||||
end
|
||||
local img: Types.Image = f.image
|
||||
if (w == 0 or h == 0) and #packets == 0 then
|
||||
w, h = img.width, img.height
|
||||
end
|
||||
if img.width ~= w or img.height ~= h then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")")
|
||||
end
|
||||
local data: buffer?
|
||||
if codec == "rawvideo" then
|
||||
local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601")
|
||||
if not y then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format)
|
||||
end
|
||||
data = y.pixels
|
||||
else
|
||||
local e2
|
||||
data, e2 = (encode :: any)(img, opts)
|
||||
if not data then
|
||||
return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode")
|
||||
end
|
||||
end
|
||||
table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer })
|
||||
end
|
||||
if #packets == 0 then
|
||||
return nil, Err.new(Err.ARG, "no frames to write")
|
||||
end
|
||||
local fr = v.frameRate
|
||||
if not fr or fr <= 0 then
|
||||
local d = packets[1].duration
|
||||
fr = if d > 0 then 1 / d else 25
|
||||
end
|
||||
return {
|
||||
kind = "video",
|
||||
codec = codec,
|
||||
copied = false,
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = fr,
|
||||
packets = packets,
|
||||
} :: Stream, nil
|
||||
end
|
||||
|
||||
-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096)
|
||||
local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
|
||||
local ch, rate = dec.channels, dec.sampleRate
|
||||
if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then
|
||||
return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate")
|
||||
end
|
||||
pcall(dec.seek, dec, 0)
|
||||
local chunk = opts.audioChunk or 4096
|
||||
local packets: { OutPacket } = {}
|
||||
local pos = 0
|
||||
local tmp: buffer? = nil
|
||||
while true do
|
||||
local ok, out, n = pcall(dec.read, dec, chunk, tmp)
|
||||
if not ok or not out or not n or n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = out
|
||||
local data = buffer.create(n * ch * 2)
|
||||
for i = 0, n * ch - 1 do
|
||||
local s = buffer.readf32(out, i * 4)
|
||||
local v = math.floor(s * 32768 + 0.5)
|
||||
if v > 32767 then
|
||||
v = 32767
|
||||
elseif v < -32768 then
|
||||
v = -32768
|
||||
elseif v ~= v then
|
||||
v = 0
|
||||
end
|
||||
buffer.writei16(data, i * 2, v)
|
||||
end
|
||||
table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data })
|
||||
pos += n
|
||||
end
|
||||
return {
|
||||
kind = "audio",
|
||||
codec = "pcm_s16le",
|
||||
copied = false,
|
||||
sampleRate = rate,
|
||||
channels = ch,
|
||||
bitsPerSample = 16,
|
||||
packets = packets,
|
||||
} :: Stream, nil
|
||||
end
|
||||
|
||||
-- streams(value, opts, want) -> { Stream } | nil, Err
|
||||
function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?)
|
||||
local o = opts or {}
|
||||
if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then
|
||||
return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer")
|
||||
end
|
||||
local dmx = if value.kind == "demuxer" then value else value.demuxer
|
||||
local out: { Stream } = {}
|
||||
-- video
|
||||
local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video"))
|
||||
local wv = want.video
|
||||
if wv and o.video ~= false then
|
||||
if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then
|
||||
table.insert(out, trackStream(vt, copyPackets(dmx, vt)))
|
||||
elseif value.kind == "video" and wv.encode then
|
||||
local s, err = encodeFrames(value, wv.encode, o)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(out, s)
|
||||
elseif vt then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)"))
|
||||
end
|
||||
end
|
||||
-- audio
|
||||
local wa = want.audio
|
||||
if wa and o.audio ~= false then
|
||||
local at: Types.Track? = dmx and dmx:track("audio")
|
||||
if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then
|
||||
table.insert(out, trackStream(at, copyPackets(dmx, at)))
|
||||
elseif wa.pcm and value.kind == "video" and value.audio then
|
||||
local s, err = pcmFrom(value.audio, o)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
if #s.packets > 0 then
|
||||
table.insert(out, s)
|
||||
end
|
||||
elseif at and o.audio == true then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container")
|
||||
end
|
||||
end
|
||||
if #out == 0 then
|
||||
return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)")
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
|
||||
function Source.rational(fps: number): (number, number)
|
||||
if fps ~= fps or fps <= 0 then
|
||||
return 25, 1
|
||||
end
|
||||
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
|
||||
return math.floor(fps + 0.5), 1
|
||||
end
|
||||
local ntsc = fps * 1001 / 1000
|
||||
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
|
||||
return math.floor(ntsc + 0.5) * 1000, 1001
|
||||
end
|
||||
return math.floor(fps * 1000 + 0.5), 1000
|
||||
end
|
||||
|
||||
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
|
||||
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
|
||||
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
|
||||
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
|
||||
local fd = math.huge
|
||||
for _, p in s.packets do
|
||||
if p.duration and p.duration > 0 and p.duration < fd then
|
||||
fd = p.duration
|
||||
end
|
||||
end
|
||||
if fd == math.huge then
|
||||
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
|
||||
end
|
||||
fd = math.max(fd, 1 / (maxFps or 100))
|
||||
local num, den = Source.rational(1 / fd)
|
||||
local step = den / num
|
||||
local out: { OutPacket } = {}
|
||||
local slots = 0
|
||||
local t0 = if s.packets[1] then s.packets[1].pts else 0
|
||||
for _, p in s.packets do
|
||||
local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step)
|
||||
local n = math.max(1, math.floor(stop / step + 0.5) - slots)
|
||||
for _ = 1, n do
|
||||
table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data })
|
||||
slots += 1
|
||||
end
|
||||
end
|
||||
return num, den, out
|
||||
end
|
||||
|
||||
-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its
|
||||
-- own order
|
||||
function Source.interleave(streams: { Stream }): { { any } }
|
||||
local order = {}
|
||||
local pos = table.create(#streams, 1)
|
||||
while true do
|
||||
local best, bt = 0, math.huge
|
||||
for si, s in streams do
|
||||
local p = s.packets[pos[si]]
|
||||
if p then
|
||||
local t = p.dts or p.pts
|
||||
if best == 0 or t < bt then
|
||||
best, bt = si, t
|
||||
end
|
||||
end
|
||||
end
|
||||
if best == 0 then
|
||||
break
|
||||
end
|
||||
table.insert(order, { best, streams[best].packets[pos[best]] })
|
||||
pos[best] += 1
|
||||
end
|
||||
return order
|
||||
end
|
||||
|
||||
return Source
|
||||
@@ -0,0 +1,577 @@
|
||||
--!strict
|
||||
-- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
|
||||
--
|
||||
-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them
|
||||
-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a
|
||||
-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc /
|
||||
-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs
|
||||
-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry).
|
||||
--
|
||||
-- local Video = require("@formats/codecs/Video")
|
||||
-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8"
|
||||
-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder)
|
||||
-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open())
|
||||
-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP)
|
||||
--
|
||||
-- Never throws: bad data / missing codecs come back as nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Yuv = require("@formats/codecs/Yuv")
|
||||
|
||||
local Video = {}
|
||||
|
||||
export type Entry = {
|
||||
id: string, -- our codec id
|
||||
name: string, -- a human name
|
||||
fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs
|
||||
matroska: { string }?, -- Matroska / WebM CodecIDs
|
||||
-- new(track, opts) -> a decoder instance (nil = decode not supported)
|
||||
new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?,
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ simple decoders
|
||||
-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no
|
||||
-- picture to show, such as a hidden VP8 altref frame)
|
||||
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
|
||||
local queue: { any } = {}
|
||||
local self = {}
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
local ok, img, err = pcall(decodeOne, packet.data, packet)
|
||||
if not ok then
|
||||
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img))
|
||||
end
|
||||
if img then
|
||||
table.insert(queue, { img, packet.pts, packet.keyframe })
|
||||
end
|
||||
return err
|
||||
end
|
||||
function self.receive(_: any): (Types.Image?, number?, boolean?)
|
||||
local q = table.remove(queue, 1)
|
||||
if q then
|
||||
return q[1], q[2], q[3]
|
||||
end
|
||||
return nil
|
||||
end
|
||||
function self.flush(_: any) end
|
||||
function self.reset(_: any)
|
||||
table.clear(queue)
|
||||
if resetFn then
|
||||
resetFn()
|
||||
end
|
||||
end
|
||||
return self :: any
|
||||
end
|
||||
|
||||
-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged
|
||||
-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 /
|
||||
-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows)
|
||||
local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
local px = img.pixels
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local bps = if bits > 8 then 2 else 1
|
||||
local shift = 2 ^ (bits - 8)
|
||||
local function sample(o: number): number
|
||||
if bps == 1 then
|
||||
return buffer.readu8(data, o)
|
||||
end
|
||||
return math.min(255, buffer.readu16(data, o) // shift)
|
||||
end
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(px, i, sample(i * bps))
|
||||
end
|
||||
local scw, sch = w, h -- source chroma plane size
|
||||
if pf == "yuv420p" then
|
||||
scw, sch = cw, ch
|
||||
elseif pf == "yuv422p" then
|
||||
scw, sch = cw, h
|
||||
end
|
||||
local uo, vo = w * h * bps, (w * h + scw * sch) * bps
|
||||
for cy = 0, ch - 1 do
|
||||
for cx = 0, cw - 1 do
|
||||
local i = cy * cw + cx
|
||||
local u, v
|
||||
if pf == "gray" then
|
||||
u, v = 128, 128
|
||||
elseif pf == "yuv420p" then
|
||||
u, v = sample(uo + i * bps), sample(vo + i * bps)
|
||||
elseif pf == "yuv422p" then
|
||||
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
|
||||
u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2
|
||||
v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2
|
||||
else
|
||||
local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1)
|
||||
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
|
||||
local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps
|
||||
u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4
|
||||
v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4
|
||||
end
|
||||
buffer.writeu8(px, w * h + i, u)
|
||||
buffer.writeu8(px, w * h + cw * ch + i, v)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = {
|
||||
yuv420p = function(w, h, cw, ch)
|
||||
return w * h + 2 * cw * ch
|
||||
end,
|
||||
yv12 = function(w, h, cw, ch)
|
||||
return w * h + 2 * cw * ch
|
||||
end,
|
||||
yuv422p = function(w, h, cw, _ch)
|
||||
return w * h + 2 * cw * h
|
||||
end,
|
||||
yuv444p = function(w, h)
|
||||
return w * h * 3
|
||||
end,
|
||||
yuva444p = function(w, h)
|
||||
return w * h * 4
|
||||
end,
|
||||
gray = function(w, h)
|
||||
return w * h
|
||||
end,
|
||||
}
|
||||
|
||||
local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local w, h = track.width or 0, track.height or 0
|
||||
if w <= 0 or h <= 0 or w * h > 2 ^ 26 then
|
||||
return nil, Err.new(Err.CORRUPT, "raw video without a valid size")
|
||||
end
|
||||
local pf = track.pixelFormat or "yuv420p"
|
||||
local bits = track.bitDepth or 8
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local flip = track.flip == true
|
||||
local planar = PLANAR_SIZE[pf]
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local n = buffer.len(data)
|
||||
if planar then
|
||||
local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1)
|
||||
if n < need then
|
||||
return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes")
|
||||
end
|
||||
if pf == "yuv420p" and bits == 8 then
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
buffer.copy(img.pixels, 0, data, 0, need)
|
||||
return img
|
||||
elseif pf == "yv12" then
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
buffer.copy(img.pixels, 0, data, 0, w * h)
|
||||
buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch)
|
||||
buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch)
|
||||
return img
|
||||
end
|
||||
return rawPlanar(data, pf, bits, w, h)
|
||||
end
|
||||
local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3
|
||||
local stride = if track.stride then track.stride else w * bpp
|
||||
if n < stride * (h - 1) + w * bpp then
|
||||
return nil, Err.new(Err.TRUNCATED, "raw frame too short")
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local bgr = pf == "bgr24" or pf == "bgra"
|
||||
for y = 0, h - 1 do
|
||||
local s = (if flip then h - 1 - y else y) * stride
|
||||
local o = y * w * 4
|
||||
for x = 0, w - 1 do
|
||||
local p = s + x * bpp
|
||||
local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2)
|
||||
if bgr then
|
||||
a, c = c, a
|
||||
end
|
||||
buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end)
|
||||
end
|
||||
|
||||
local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Vp8 = require("@formats/codecs/Vp8")
|
||||
local dec = Vp8.newDecoder()
|
||||
local o = { maxPixels = opts and opts.maxPixels }
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local img, err = dec:decodeFrame(data, 0, buffer.len(data), o)
|
||||
if not img then
|
||||
return nil, err
|
||||
end
|
||||
local src = img.meta.source
|
||||
if type(src) == "table" and src.show == false then
|
||||
return nil, nil
|
||||
end
|
||||
img.meta.yuv = { range = "limited", matrix = "bt601" }
|
||||
return img, nil
|
||||
end, function()
|
||||
if dec.reset then
|
||||
dec:reset()
|
||||
else
|
||||
dec = Vp8.newDecoder()
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout
|
||||
-- allows, else rgba8
|
||||
local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local o = { yuv = true, maxPixels = opts and opts.maxPixels }
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local img, err = Jpeg.decode(data, 0, buffer.len(data), o)
|
||||
if img and img.format == "yuv420p" then
|
||||
img.meta.yuv = { range = "full", matrix = "bt601" }
|
||||
end
|
||||
return img, err
|
||||
end)
|
||||
end
|
||||
|
||||
-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first
|
||||
local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local src = img
|
||||
if img.format == "yuv420p" then
|
||||
local range = Yuv.info(img)
|
||||
if range ~= "full" then
|
||||
src = Yuv.toFullRange(img)
|
||||
end
|
||||
end
|
||||
return Jpeg.encode(src, { quality = opts and opts.quality or 90 })
|
||||
end
|
||||
|
||||
-- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture)
|
||||
local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Mpeg1 = require("@formats/codecs/Mpeg1")
|
||||
local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
|
||||
local queue: { any } = {}
|
||||
local function push(f: any)
|
||||
local img = Mpeg1.frameImage(f)
|
||||
if img then
|
||||
img.meta.yuv = { range = "limited", matrix = "bt601" }
|
||||
local tag = f.tag
|
||||
table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 })
|
||||
end
|
||||
end
|
||||
local self = {}
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts })
|
||||
if not ok then
|
||||
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
|
||||
end
|
||||
if f then
|
||||
push(f)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
function self.receive(_: any): (Types.Image?, number?, boolean?)
|
||||
local q = table.remove(queue, 1)
|
||||
if q then
|
||||
return q[1], q[2], q[3]
|
||||
end
|
||||
return nil
|
||||
end
|
||||
function self.flush(_: any)
|
||||
for _ = 1, 4 do
|
||||
local f = dec:flush()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
push(f)
|
||||
end
|
||||
end
|
||||
function self.reset(_: any)
|
||||
dec:reset()
|
||||
table.clear(queue)
|
||||
end
|
||||
return self :: any, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ registry
|
||||
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
|
||||
local BUILTIN: { Entry } = {
|
||||
{ id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder },
|
||||
{ id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode },
|
||||
{ id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder },
|
||||
{ id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder },
|
||||
{ id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } },
|
||||
{ id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } },
|
||||
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264" }, matroska = { "V_MPEG4/ISO/AVC" } },
|
||||
{ id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } },
|
||||
{ id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } },
|
||||
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
|
||||
{ id = "theora", name = "Theora", matroska = { "V_THEORA" } },
|
||||
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
|
||||
}
|
||||
|
||||
local byId: { [string]: Entry } = {}
|
||||
local byFourcc: { [string]: string } = {}
|
||||
local byMatroska: { [string]: string } = {}
|
||||
|
||||
-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it
|
||||
function Video.register(entry: Entry): (boolean, Err.Err?)
|
||||
if type(entry) ~= "table" or type(entry.id) ~= "string" then
|
||||
return false, Err.new(Err.ARG, "register: needs an entry with an id")
|
||||
end
|
||||
local old = byId[entry.id]
|
||||
if old and entry.new == nil then
|
||||
entry.new = old.new
|
||||
end
|
||||
byId[entry.id] = entry
|
||||
for _, f in entry.fourcc or {} do
|
||||
byFourcc[f] = entry.id
|
||||
end
|
||||
for _, m in entry.matroska or {} do
|
||||
byMatroska[m] = entry.id
|
||||
end
|
||||
return true
|
||||
end
|
||||
for _, e in BUILTIN do
|
||||
Video.register(e)
|
||||
end
|
||||
|
||||
-- the registry (read only by convention): id -> Entry
|
||||
Video.codecs = byId
|
||||
|
||||
-- fromFourcc(fourcc) -> codec id | nil
|
||||
function Video.fromFourcc(fcc: string): string?
|
||||
return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)]
|
||||
end
|
||||
|
||||
-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...)
|
||||
function Video.fromMatroska(id: string): string?
|
||||
return byMatroska[id]
|
||||
end
|
||||
|
||||
-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil
|
||||
function Video.entry(id: string): Entry?
|
||||
return byId[id]
|
||||
end
|
||||
|
||||
-- canDecode(codecId) -> boolean
|
||||
function Video.canDecode(id: string): boolean
|
||||
local e = byId[id]
|
||||
return e ~= nil and e.new ~= nil
|
||||
end
|
||||
|
||||
-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered)
|
||||
function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local e = byId[track.codec]
|
||||
if not e or not e.new then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec))
|
||||
end
|
||||
local ok, dec, err = pcall(e.new :: any, track, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec))
|
||||
end
|
||||
return dec, err
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ VideoDecoder
|
||||
local function toRGBA(_self: any, f: any): Types.Image
|
||||
local img = if type(f) == "table" and f.image then f.image else f
|
||||
local out = Yuv.imageToRgba(img)
|
||||
return out or img
|
||||
end
|
||||
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p)
|
||||
track: number?, -- the video track id (default: the first video track)
|
||||
maxPixels: number?,
|
||||
openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through
|
||||
-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and
|
||||
-- the demuxer (remuxing) and audio work.
|
||||
function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local o: OpenOptions = opts or {}
|
||||
local track: Types.Track? = nil
|
||||
if o.track then
|
||||
for _, t in demuxer.tracks do
|
||||
if t.id == o.track then
|
||||
track = t
|
||||
end
|
||||
end
|
||||
if not track then
|
||||
return nil, Err.new(Err.ARG, "no track " .. tostring(o.track))
|
||||
end
|
||||
else
|
||||
track = demuxer:track("video")
|
||||
end
|
||||
local codec: Types.VideoCodecDecoder? = nil
|
||||
local codecErr: Err.Err? = nil
|
||||
if track then
|
||||
codec, codecErr = Video.decoder(track, o)
|
||||
else
|
||||
codecErr = Err.new(Err.UNSUPPORTED, "no video track")
|
||||
end
|
||||
local v: any = {
|
||||
kind = "video",
|
||||
format = demuxer.format,
|
||||
codec = if track then track.codec else "none",
|
||||
width = if track then track.width or 0 else 0,
|
||||
height = if track then track.height or 0 else 0,
|
||||
frameRate = if track then track.frameRate or 0 else 0,
|
||||
frames = if track then track.frames or 0 else 0,
|
||||
duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration,
|
||||
track = track,
|
||||
demuxer = demuxer,
|
||||
meta = demuxer.meta or {},
|
||||
decodeError = codecErr,
|
||||
toRGBA = toRGBA,
|
||||
}
|
||||
if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then
|
||||
v.frames = math.floor(v.duration * v.frameRate + 0.5)
|
||||
end
|
||||
-- audio
|
||||
if o.audio ~= false then
|
||||
local at = demuxer:track("audio")
|
||||
if at then
|
||||
if o.openAudio then
|
||||
local ok, dec, err = pcall(o.openAudio, demuxer, at)
|
||||
if ok and dec then
|
||||
v.audio = dec
|
||||
else
|
||||
v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec))
|
||||
end
|
||||
else
|
||||
v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)")
|
||||
end
|
||||
end
|
||||
end
|
||||
local index, flushed, skipUntil = 0, false, -math.huge
|
||||
local tid = if track then track.id else -1
|
||||
local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000
|
||||
local start = demuxer.startTime or 0
|
||||
v.startTime = start
|
||||
local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0
|
||||
local lastPts = nil :: number?
|
||||
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
|
||||
if not codec then
|
||||
return nil, codecErr
|
||||
end
|
||||
local dec = codec :: Types.VideoCodecDecoder
|
||||
while true do
|
||||
local img, pts, key = dec:receive()
|
||||
if img then
|
||||
local t = (pts or 0) / scale - start
|
||||
if t + 1e-9 >= skipUntil then
|
||||
index += 1
|
||||
local d = defaultDur
|
||||
if lastPts and t > lastPts and defaultDur == 0 then
|
||||
d = t - lastPts
|
||||
end
|
||||
lastPts = t
|
||||
if o.rgba then
|
||||
img = Yuv.imageToRgba(img) or img
|
||||
end
|
||||
return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil
|
||||
end
|
||||
else
|
||||
local p = demuxer:read(tid)
|
||||
if p == nil then
|
||||
if flushed then
|
||||
return nil, nil
|
||||
end
|
||||
flushed = true
|
||||
dec:flush()
|
||||
else
|
||||
local err = dec:decode(p)
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
function v.seek(self: any, seconds: number)
|
||||
demuxer:seek(seconds + start)
|
||||
if codec then
|
||||
codec:reset()
|
||||
end
|
||||
flushed = false
|
||||
skipUntil = seconds
|
||||
lastPts = nil
|
||||
if self.audio then
|
||||
pcall(self.audio.seek, self.audio, seconds)
|
||||
end
|
||||
end
|
||||
function v.reset(self: any)
|
||||
self:seek(0)
|
||||
skipUntil = -math.huge
|
||||
index = 0
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frames-backed
|
||||
-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after
|
||||
-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded.
|
||||
function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?)
|
||||
if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images")
|
||||
end
|
||||
local w, h = images[1].width, images[1].height
|
||||
local pts: { number } = {}
|
||||
local durs: { number } = {}
|
||||
local t = 0
|
||||
for i, img in images do
|
||||
if type(img) ~= "table" or img.width ~= w or img.height ~= h then
|
||||
return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image")
|
||||
end
|
||||
local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1)
|
||||
if type(d) ~= "number" or d ~= d or d < 0 then
|
||||
d = 0.1
|
||||
end
|
||||
pts[i] = t
|
||||
durs[i] = d
|
||||
t += d
|
||||
end
|
||||
local n = #images
|
||||
local o = opts or {}
|
||||
local v: any = {
|
||||
kind = "video",
|
||||
format = o.format or "frames",
|
||||
codec = "frames",
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = if t > 0 then n / t else 10,
|
||||
frames = n,
|
||||
duration = t,
|
||||
loops = o.loops,
|
||||
meta = o.meta or {},
|
||||
toRGBA = toRGBA,
|
||||
images = images,
|
||||
}
|
||||
local i = 0
|
||||
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
|
||||
i += 1
|
||||
if i > n then
|
||||
i = n
|
||||
return nil, nil
|
||||
end
|
||||
local img = images[i]
|
||||
if o.rgba then
|
||||
img = Yuv.imageToRgba(img) or img
|
||||
end
|
||||
return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil
|
||||
end
|
||||
function v.seek(self: any, seconds: number)
|
||||
local k = 0
|
||||
for j = 1, n do
|
||||
if pts[j] <= seconds + 1e-9 then
|
||||
k = j - 1
|
||||
end
|
||||
end
|
||||
i = k
|
||||
end
|
||||
function v.reset(self: any)
|
||||
i = 0
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
return Video
|
||||
+880
-246
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,274 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
|
||||
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
|
||||
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
|
||||
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
|
||||
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
|
||||
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
|
||||
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
|
||||
local Tables = require("@formats/codecs/Vp8/Tables")
|
||||
|
||||
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
local rshift, band = bit32.rshift, bit32.band
|
||||
local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR
|
||||
|
||||
local Predict = {}
|
||||
|
||||
local BORDER = 32
|
||||
Predict.BORDER = BORDER
|
||||
|
||||
-- the work buffer stride (codecs/Vp8/Decode: BPS)
|
||||
local BPS = 32
|
||||
|
||||
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
|
||||
local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter
|
||||
|
||||
-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads
|
||||
-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator).
|
||||
local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local k = f * 6
|
||||
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
|
||||
for _ = 1, h do
|
||||
for i = so - 2, so + w - 3 do
|
||||
local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3
|
||||
+ readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64
|
||||
writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
-- the six-tap filter along columns
|
||||
local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local k = f * 6
|
||||
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
|
||||
local s1, s2, s3 = ss, 2 * ss, 3 * ss
|
||||
for _ = 1, h do
|
||||
local p = so - s2
|
||||
for i = 0, w - 1 do
|
||||
local q = p + i
|
||||
local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3
|
||||
+ readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64
|
||||
writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7
|
||||
local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 1 do
|
||||
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 1 do
|
||||
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel
|
||||
-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax,
|
||||
-- hmax: the last pixel column / row of the (macroblock aligned) plane.
|
||||
local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean)
|
||||
local fx, fy = band(mvx, 7), band(mvy, 7)
|
||||
local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8
|
||||
local sb, so, ss = src, 0, stride
|
||||
if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then
|
||||
so = base + py * stride + px
|
||||
else
|
||||
for r = 0, h + 4 do
|
||||
local sy = py - 2 + r
|
||||
if sy < 0 then
|
||||
sy = 0
|
||||
elseif sy > hmax then
|
||||
sy = hmax
|
||||
end
|
||||
local row = base + sy * stride
|
||||
local o = r * 32
|
||||
for c = 0, w + 4 do
|
||||
local sx = px - 2 + c
|
||||
if sx < 0 then
|
||||
sx = 0
|
||||
elseif sx > wmax then
|
||||
sx = wmax
|
||||
end
|
||||
writeu8(emu, o + c, readu8(src, row + sx))
|
||||
end
|
||||
end
|
||||
sb, so, ss = emu, 66, 32
|
||||
end
|
||||
if fx == 0 then
|
||||
if fy == 0 then
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 4, 4 do
|
||||
writeu32(dst, d + i, readu32(sb, so + i))
|
||||
end
|
||||
so += ss
|
||||
d += BPS
|
||||
end
|
||||
elseif bil then
|
||||
bilV(sb, so, ss, dst, d, BPS, w, h, fy)
|
||||
else
|
||||
sixV(sb, so, ss, dst, d, BPS, w, h, fy)
|
||||
end
|
||||
elseif fy == 0 then
|
||||
if bil then
|
||||
bilH(sb, so, ss, dst, d, BPS, w, h, fx)
|
||||
else
|
||||
sixH(sb, so, ss, dst, d, BPS, w, h, fx)
|
||||
end
|
||||
elseif bil then
|
||||
bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx)
|
||||
bilV(tmp, 0, 32, dst, d, BPS, w, h, fy)
|
||||
else
|
||||
sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx)
|
||||
sixV(tmp, 64, 32, dst, d, BPS, w, h, fy)
|
||||
end
|
||||
end
|
||||
|
||||
local function chroma16(v: number): number
|
||||
-- the chroma vector of a whole macroblock: half the luma one, rounded away from zero
|
||||
if v < 0 then
|
||||
return -((1 - v) // 2)
|
||||
end
|
||||
return (v + 1) // 2
|
||||
end
|
||||
|
||||
local function chroma4(s: number): number
|
||||
-- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero
|
||||
if s < 0 then
|
||||
return -((4 - s) // 8)
|
||||
end
|
||||
return (s + 4) // 8
|
||||
end
|
||||
|
||||
export type Planes = {
|
||||
Y: buffer,
|
||||
U: buffer,
|
||||
V: buffer,
|
||||
ys: number, -- luma stride
|
||||
uvs: number, -- chroma stride
|
||||
yb: number, -- offset of luma pixel (0, 0)
|
||||
uvb: number,
|
||||
mbw: number,
|
||||
mbh: number,
|
||||
}
|
||||
|
||||
-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter
|
||||
-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels;
|
||||
-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them).
|
||||
function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
|
||||
local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb
|
||||
local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1
|
||||
local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1
|
||||
local x, y = mbx * 16, mby * 16
|
||||
local cx, cy = mbx * 8, mby * 8
|
||||
if part < 0 then
|
||||
block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil)
|
||||
local cr, cc = chroma16(mvr), chroma16(mvc)
|
||||
if full then
|
||||
cr -= band(cr, 7)
|
||||
cc -= band(cc, 7)
|
||||
end
|
||||
block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil)
|
||||
return
|
||||
end
|
||||
if part < 3 then
|
||||
for q = 0, 3 do
|
||||
local bx, by = (q % 2) * 8, (q // 2) * 8
|
||||
local k = sb + by + bx // 4 + 1
|
||||
block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil)
|
||||
end
|
||||
else
|
||||
for b = 0, 15, 2 do
|
||||
local k = sb + b + 1
|
||||
local bx, by = (b % 4) * 4, (b // 4) * 4
|
||||
local r0, c0 = subR[k], subC[k]
|
||||
if r0 == subR[k + 1] and c0 == subC[k + 1] then
|
||||
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil)
|
||||
else
|
||||
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil)
|
||||
block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil)
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 0, 1 do
|
||||
local rr, rc = 0, 0
|
||||
for j = 0, 1 do
|
||||
local k = sb + i * 8 + j * 2 + 1
|
||||
local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5])
|
||||
local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5])
|
||||
if full then
|
||||
cr -= band(cr, 7)
|
||||
cc -= band(cc, 7)
|
||||
end
|
||||
if j == 0 then
|
||||
rr, rc = cr, cc
|
||||
elseif cr == rr and cc == rc then
|
||||
-- both 4x4 chroma blocks of the row share one vector: one 8x4 block
|
||||
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil)
|
||||
else
|
||||
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil)
|
||||
block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the
|
||||
-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo;
|
||||
-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder).
|
||||
function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
|
||||
for mbx = 0, mbw - 1 do
|
||||
local rf = ref[mbx + 1]
|
||||
if rf > 0 then
|
||||
local mi = mi0 + mbx + 1
|
||||
local o = mbx * chunk
|
||||
Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels
|
||||
local function extend(P: buffer, stride: number, base: number, w: number, h: number)
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * stride
|
||||
bfill(P, o - BORDER, readu8(P, o), BORDER)
|
||||
bfill(P, o + w, readu8(P, o + w - 1), BORDER)
|
||||
end
|
||||
local top = base - BORDER
|
||||
local bottom = base + (h - 1) * stride - BORDER
|
||||
for r = 1, BORDER do
|
||||
bcopy(P, top - r * stride, P, top, stride)
|
||||
bcopy(P, bottom + r * stride, P, bottom, stride)
|
||||
end
|
||||
end
|
||||
|
||||
function Predict.extend(ref: Planes)
|
||||
extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16)
|
||||
extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
|
||||
extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
|
||||
end
|
||||
|
||||
return Predict
|
||||
@@ -1,6 +1,9 @@
|
||||
--!strict
|
||||
-- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
|
||||
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays.
|
||||
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables
|
||||
-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from
|
||||
-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c;
|
||||
-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays.
|
||||
local Tables = {}
|
||||
|
||||
-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1
|
||||
@@ -177,4 +180,70 @@ Tables.CAT4 = { 176, 155, 140, 135 }
|
||||
Tables.CAT5 = { 180, 157, 141, 134, 130 }
|
||||
Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }
|
||||
|
||||
-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones
|
||||
Tables.YMODE_PROB = { 112, 86, 140, 37 }
|
||||
Tables.UVMODE_PROB = { 162, 101, 204 }
|
||||
Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 }
|
||||
|
||||
-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10)
|
||||
Tables.MV_DEFAULT = {
|
||||
162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254,
|
||||
164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254,
|
||||
}
|
||||
Tables.MV_UPDATE = {
|
||||
237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254,
|
||||
231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254,
|
||||
}
|
||||
|
||||
-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1
|
||||
Tables.MODE_CONTEXTS = {
|
||||
7, 1, 1, 143,
|
||||
14, 18, 14, 107,
|
||||
135, 64, 57, 68,
|
||||
60, 56, 128, 65,
|
||||
159, 134, 128, 34,
|
||||
234, 188, 128, 28,
|
||||
}
|
||||
|
||||
-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3]
|
||||
Tables.SUB_MV_REF_PROB = {
|
||||
147, 136, 18,
|
||||
223, 1, 34,
|
||||
106, 145, 1,
|
||||
208, 1, 1,
|
||||
179, 121, 1,
|
||||
223, 1, 34,
|
||||
179, 121, 1,
|
||||
208, 1, 1,
|
||||
}
|
||||
|
||||
-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each
|
||||
-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition
|
||||
Tables.SPLIT_OFFSET = {
|
||||
0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
}
|
||||
Tables.SPLIT_FILL = {
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
|
||||
0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
}
|
||||
Tables.SPLIT_COUNT = { 8, 8, 4, 1 }
|
||||
|
||||
-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3)
|
||||
Tables.SIXTAP = {
|
||||
0, 0, 128, 0, 0, 0,
|
||||
0, -6, 123, 12, -1, 0,
|
||||
2, -11, 108, 36, -8, 1,
|
||||
0, -9, 93, 50, -6, 0,
|
||||
3, -16, 77, 77, -16, 3,
|
||||
0, -6, 50, 93, -9, 0,
|
||||
1, -8, 36, 108, -11, 2,
|
||||
0, -1, 12, 123, -6, 0,
|
||||
}
|
||||
Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 }
|
||||
|
||||
return Tables
|
||||
@@ -1,16 +1,23 @@
|
||||
--!strict
|
||||
-- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
-- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause,
|
||||
-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause,
|
||||
-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
|
||||
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`.
|
||||
-- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions,
|
||||
-- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object
|
||||
-- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does).
|
||||
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause,
|
||||
-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams.
|
||||
-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear;
|
||||
-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with
|
||||
-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save /
|
||||
-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error
|
||||
-- concealment (a damaged frame returns an Err).
|
||||
-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace
|
||||
-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps).
|
||||
--
|
||||
-- local Vp8 = require("@formats/codecs/Vp8")
|
||||
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header)
|
||||
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image
|
||||
-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
|
||||
-- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM)
|
||||
-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames
|
||||
-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame
|
||||
-- dec:reset() -- after a seek: the next frame must be a key frame
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -67,7 +74,9 @@ function Vp8.newDecoder(): Decoder
|
||||
return setmetatable({ state = Decode.new() }, DecoderMeta)
|
||||
end
|
||||
|
||||
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err
|
||||
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames;
|
||||
-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed),
|
||||
-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT.
|
||||
function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer")
|
||||
@@ -79,14 +88,18 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
|
||||
end
|
||||
local img = Types.Image.new(f.width, f.height, "yuv420p")
|
||||
local ny = f.width * f.height
|
||||
local nc = buffer.len(f.u)
|
||||
buffer.copy(img.pixels, 0, f.y, 0, ny)
|
||||
buffer.copy(img.pixels, ny, f.u, 0, nc)
|
||||
buffer.copy(img.pixels, ny + nc, f.v, 0, nc)
|
||||
img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile }
|
||||
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
|
||||
Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc)
|
||||
local h = f.header
|
||||
img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame
|
||||
function DecoderMeta.reset(self: Decoder)
|
||||
Decode.reset(self.state)
|
||||
end
|
||||
|
||||
-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame)
|
||||
function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
|
||||
return Vp8.newDecoder():decodeFrame(buf, off, len, opts)
|
||||
@@ -102,7 +115,10 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options
|
||||
if not f then
|
||||
return nil, fail(err, o)
|
||||
end
|
||||
return f.y, f.u, f.v, f.width, f.height
|
||||
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
|
||||
local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc)
|
||||
Decode.cropTo(f, y, 0, u, 0, v, 0)
|
||||
return y, u, v, f.width, f.height
|
||||
end
|
||||
|
||||
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range.
|
||||
-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the
|
||||
-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma
|
||||
-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this).
|
||||
--
|
||||
-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255)
|
||||
-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2))
|
||||
-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
|
||||
local bcreate = buffer.create
|
||||
local floor = math.floor
|
||||
|
||||
local Yuv = {}
|
||||
|
||||
-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u
|
||||
-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224
|
||||
local MATRIX = {
|
||||
bt601 = { kr = 0.299, kb = 0.114 },
|
||||
bt709 = { kr = 0.2126, kb = 0.0722 },
|
||||
}
|
||||
|
||||
type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number }
|
||||
|
||||
local cache: { [string]: Coeffs } = {}
|
||||
local function coeffs(range: string?, matrix: string?): Coeffs
|
||||
local key = (range or "limited") .. (matrix or "bt601")
|
||||
local c = cache[key]
|
||||
if c then
|
||||
return c
|
||||
end
|
||||
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
|
||||
local kr, kb = m.kr, m.kb
|
||||
local kg = 1 - kr - kb
|
||||
local full = range == "full"
|
||||
local ys = if full then 1 else 255 / 219
|
||||
local cs = if full then 1 else 255 / 224
|
||||
c = {
|
||||
ys = floor(ys * 65536 + 0.5),
|
||||
yo = if full then 0 else 16,
|
||||
crv = floor(2 * (1 - kr) * cs * 65536 + 0.5),
|
||||
cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5),
|
||||
cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5),
|
||||
cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5),
|
||||
cs = cs,
|
||||
}
|
||||
cache[key] = c
|
||||
return c
|
||||
end
|
||||
|
||||
-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279
|
||||
local CLIP = bcreate(2304)
|
||||
for i = 0, 2303 do
|
||||
writeu8(CLIP, i, math.clamp(i - 1024, 0, 255))
|
||||
end
|
||||
|
||||
-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with
|
||||
-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2))
|
||||
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer
|
||||
local dst = out or bcreate(w * h * 4)
|
||||
local c = coeffs(range, matrix)
|
||||
local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu
|
||||
local ch = (h + 1) // 2
|
||||
if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then
|
||||
return dst
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local yrow = y * w
|
||||
local crow = (y // 2) * cw
|
||||
local o = yrow * 4
|
||||
for x = 0, w - 1, 2 do
|
||||
local ci = crow + (x // 2)
|
||||
local u = readu8(src, uo + ci) - 128
|
||||
local v = readu8(src, vo + ci) - 128
|
||||
local rv = (crv * v + 32768) // 65536
|
||||
local gv = (cgu * u + cgv * v + 32768) // 65536
|
||||
local bu = (cbu * u + 32768) // 65536
|
||||
local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024
|
||||
writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
|
||||
if x + 1 < w then
|
||||
yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024
|
||||
writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
|
||||
end
|
||||
o += 8
|
||||
end
|
||||
end
|
||||
return dst
|
||||
end
|
||||
|
||||
-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p
|
||||
function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local uo, vo = w * h, w * h + cw * ch
|
||||
local dst = out or bcreate(w * h + 2 * cw * ch)
|
||||
if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then
|
||||
return dst
|
||||
end
|
||||
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
|
||||
local kr, kb = m.kr, m.kb
|
||||
local kg = 1 - kr - kb
|
||||
local full = range == "full"
|
||||
local ysc = if full then 1 else 219 / 255
|
||||
local csc = if full then 1 else 224 / 255
|
||||
local yof = if full then 0.5 else 16.5
|
||||
-- fixed point x 65536
|
||||
local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5)
|
||||
local yoff = floor(yof * 65536)
|
||||
local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5)
|
||||
local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5)
|
||||
local ub = floor(0.5 * csc * 65536 + 0.5)
|
||||
local vr = ub
|
||||
local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5)
|
||||
local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5)
|
||||
local coff4 = floor(128.5 * 65536) * 4
|
||||
for i = 0, w * h - 1 do
|
||||
local o = i * 4
|
||||
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
|
||||
writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024))
|
||||
end
|
||||
for cy = 0, ch - 1 do
|
||||
local y0 = cy * 2
|
||||
local y1 = if y0 + 1 < h then y0 + 1 else y0
|
||||
for cx = 0, cw - 1 do
|
||||
local x0 = cx * 2
|
||||
local x1 = if x0 + 1 < w then x0 + 1 else x0
|
||||
local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4
|
||||
local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d)
|
||||
local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1)
|
||||
local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2)
|
||||
local i = cy * cw + cx
|
||||
writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024))
|
||||
writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024))
|
||||
end
|
||||
end
|
||||
return dst
|
||||
end
|
||||
|
||||
-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent
|
||||
local function info(img: Types.Image): (string, string)
|
||||
local m = img.meta
|
||||
local y = m and m.yuv
|
||||
if type(y) == "table" then
|
||||
return y.range or "limited", y.matrix or "bt601"
|
||||
end
|
||||
local src = m and m.source
|
||||
if type(src) == "table" and src.range == "full" then
|
||||
return "full", "bt601"
|
||||
end
|
||||
return "limited", "bt601"
|
||||
end
|
||||
Yuv.info = info
|
||||
|
||||
-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer
|
||||
function Yuv.planes(w: number, h: number): (number, number, number, number)
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
return w * h, w * h + cw * ch, cw, ch
|
||||
end
|
||||
|
||||
-- FULL_Y / FULL_C: limited -> full range sample maps
|
||||
local FULL_Y = bcreate(256)
|
||||
local FULL_C = bcreate(256)
|
||||
for v = 0, 255 do
|
||||
writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255))
|
||||
writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255))
|
||||
end
|
||||
|
||||
-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned)
|
||||
function Yuv.toFullRange(img: Types.Image): Types.Image
|
||||
if img.format ~= "yuv420p" or info(img) == "full" then
|
||||
return img
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local out = Types.Image.new(w, h, "yuv420p")
|
||||
local src, dst = img.pixels, out.pixels
|
||||
local ny = w * h
|
||||
local n = math.min(buffer.len(src), buffer.len(dst))
|
||||
for i = 0, math.min(ny, n) - 1 do
|
||||
writeu8(dst, i, readu8(FULL_Y, readu8(src, i)))
|
||||
end
|
||||
for i = ny, n - 1 do
|
||||
writeu8(dst, i, readu8(FULL_C, readu8(src, i)))
|
||||
end
|
||||
out.meta.yuv = { range = "full", matrix = select(2, info(img)) }
|
||||
out.meta.source = img.meta.source
|
||||
return out
|
||||
end
|
||||
|
||||
-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats)
|
||||
function Yuv.imageToRgba(img: Types.Image): Types.Image?
|
||||
if img.format == "rgba8" then
|
||||
return img
|
||||
end
|
||||
if img.format ~= "yuv420p" then
|
||||
return nil
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local uo, vo, cw = Yuv.planes(w, h)
|
||||
local range, matrix = info(img)
|
||||
local out = Types.Image.new(w, h, "rgba8")
|
||||
Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels)
|
||||
out.meta.source = img.meta.source
|
||||
return out
|
||||
end
|
||||
|
||||
-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix)
|
||||
function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image?
|
||||
if img.format == "yuv420p" then
|
||||
return img
|
||||
end
|
||||
if img.format ~= "rgba8" then
|
||||
return nil
|
||||
end
|
||||
local out = Types.Image.new(img.width, img.height, "yuv420p")
|
||||
Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels)
|
||||
out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" }
|
||||
out.meta.source = img.meta.source
|
||||
return out
|
||||
end
|
||||
|
||||
return Yuv
|
||||
@@ -0,0 +1,463 @@
|
||||
--!strict
|
||||
-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone
|
||||
-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another
|
||||
-- format). New in formats-luau.
|
||||
-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped);
|
||||
-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk;
|
||||
-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3");
|
||||
-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames;
|
||||
-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations);
|
||||
-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout);
|
||||
-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac.
|
||||
--
|
||||
-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format })
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Mux = require("@formats/containers/Ogg/Mux")
|
||||
|
||||
local AudioWrap = {}
|
||||
|
||||
local function allPackets(dmx: any, track: Types.Track): { Types.Packet }
|
||||
local out = {}
|
||||
local n = if dmx.count then dmx:count(track.id) else 0
|
||||
if n > 0 and dmx.get then
|
||||
for k = 1, n do
|
||||
local p = dmx:get(track.id, k)
|
||||
if p then
|
||||
table.insert(out, p)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function concat(packets: { Types.Packet }, prefix: buffer?): buffer
|
||||
local total = if prefix then buffer.len(prefix) else 0
|
||||
for _, p in packets do
|
||||
total += buffer.len(p.data)
|
||||
end
|
||||
local out = buffer.create(total)
|
||||
local o = 0
|
||||
if prefix then
|
||||
buffer.copy(out, 0, prefix)
|
||||
o = buffer.len(prefix)
|
||||
end
|
||||
for _, p in packets do
|
||||
buffer.copy(out, o, p.data)
|
||||
o += buffer.len(p.data)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ WAV
|
||||
local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source)
|
||||
pcm_u8 = { 1, 8, 0 },
|
||||
pcm_s8 = { 1, 8, 0 },
|
||||
pcm_s16le = { 1, 16, 0 },
|
||||
pcm_s24le = { 1, 24, 0 },
|
||||
pcm_s32le = { 1, 32, 0 },
|
||||
pcm_s16be = { 1, 16, 1 },
|
||||
pcm_s24be = { 1, 24, 1 },
|
||||
pcm_s32be = { 1, 32, 1 },
|
||||
pcm_f32le = { 3, 32, 0 },
|
||||
pcm_f64le = { 3, 64, 0 },
|
||||
pcm_f32be = { 3, 32, 1 },
|
||||
pcm_f64be = { 3, 64, 1 },
|
||||
pcm_alaw = { 6, 8, 0 },
|
||||
pcm_mulaw = { 7, 8, 0 },
|
||||
}
|
||||
|
||||
local function wav(fmt: buffer, data: buffer): buffer
|
||||
local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64)
|
||||
local fl = buffer.len(fmt)
|
||||
local dl = buffer.len(data)
|
||||
w:string("RIFF")
|
||||
w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2))
|
||||
w:string("WAVE")
|
||||
w:string("fmt ")
|
||||
w:u32le(fl)
|
||||
w:bytes(fmt)
|
||||
if fl % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
w:string("data")
|
||||
w:u32le(dl)
|
||||
w:bytes(data)
|
||||
if dl % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
||||
local spec = PCM[track.codec]
|
||||
local ch = track.channels or 1
|
||||
local rate = math.floor((track.sampleRate or 0) + 0.5)
|
||||
if ch < 1 or rate <= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate")
|
||||
end
|
||||
local bits = spec[2]
|
||||
local data = concat(packets)
|
||||
if spec[3] == 1 then
|
||||
local bps = bits // 8
|
||||
for i = 0, buffer.len(data) - bps, bps do
|
||||
for k = 0, bps // 2 - 1 do
|
||||
local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k)
|
||||
buffer.writeu8(data, i + k, b)
|
||||
buffer.writeu8(data, i + bps - 1 - k, a)
|
||||
end
|
||||
end
|
||||
end
|
||||
if track.codec == "pcm_s8" then
|
||||
for i = 0, buffer.len(data) - 1 do
|
||||
buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256)
|
||||
end
|
||||
end
|
||||
local f = Bytes.writer(16)
|
||||
local align = ch * bits // 8
|
||||
f:u16le(spec[1])
|
||||
f:u16le(ch)
|
||||
f:u32le(rate)
|
||||
f:u32le(rate * align)
|
||||
f:u16le(align)
|
||||
f:u16le(bits)
|
||||
return wav(f:finish(), data), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Ogg
|
||||
-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1)
|
||||
local function opusSamples(b: buffer): number
|
||||
local n = buffer.len(b)
|
||||
if n < 1 then
|
||||
return 0
|
||||
end
|
||||
local toc = buffer.readu8(b, 0)
|
||||
local config = toc // 8
|
||||
local fs: number
|
||||
if config < 12 then
|
||||
fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1]
|
||||
elseif config < 16 then
|
||||
fs = if config % 2 == 0 then 480 else 960
|
||||
else
|
||||
fs = ({ 120, 240, 480, 960 })[config % 4 + 1]
|
||||
end
|
||||
local c = toc % 4
|
||||
local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2
|
||||
return fs * frames
|
||||
end
|
||||
|
||||
local function opusHead(track: Types.Track): buffer
|
||||
local c = track.config
|
||||
if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then
|
||||
return c
|
||||
end
|
||||
local w = Bytes.writer(19)
|
||||
w:string("OpusHead")
|
||||
w:u8(1)
|
||||
w:u8(math.clamp(track.channels or 2, 1, 2))
|
||||
w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5))
|
||||
w:u32le(math.floor(track.sampleRate or 48000))
|
||||
w:u16le(0)
|
||||
w:u8(0)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function opusTags(): buffer
|
||||
local w = Bytes.writer(32)
|
||||
w:string("OpusTags")
|
||||
local vendor = "formats-luau"
|
||||
w:u32le(#vendor)
|
||||
w:string(vendor)
|
||||
w:u32le(0)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer
|
||||
local mux = Mux.new({ pageSize = 4096 })
|
||||
local s = mux:stream(1)
|
||||
for i, h in headers do
|
||||
s:packet(h, 0, { flush = i == 1 or i == #headers })
|
||||
end
|
||||
for i, p in packets do
|
||||
s:packet(p.data, granuleOf(p, i), { eos = i == #packets })
|
||||
end
|
||||
return mux:finish()
|
||||
end
|
||||
|
||||
-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data)
|
||||
local function xiphHeaders(c: buffer): { buffer }?
|
||||
local n = buffer.len(c)
|
||||
if n < 3 then
|
||||
return nil
|
||||
end
|
||||
local count = buffer.readu8(c, 0) + 1
|
||||
local p = 1
|
||||
local sizes = {}
|
||||
local total = 0
|
||||
for k = 1, count - 1 do
|
||||
local s = 0
|
||||
while true do
|
||||
if p >= n then
|
||||
return nil
|
||||
end
|
||||
local b = buffer.readu8(c, p)
|
||||
p += 1
|
||||
s += b
|
||||
if b ~= 255 then
|
||||
break
|
||||
end
|
||||
end
|
||||
sizes[k] = s
|
||||
total += s
|
||||
end
|
||||
sizes[count] = n - p - total
|
||||
if sizes[count] < 0 then
|
||||
return nil
|
||||
end
|
||||
local out = {}
|
||||
for k = 1, count do
|
||||
local b = buffer.create(sizes[k])
|
||||
buffer.copy(b, 0, c, p, sizes[k])
|
||||
p += sizes[k]
|
||||
out[k] = b
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the
|
||||
-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0,
|
||||
-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4
|
||||
-- samples (the first one as if its previous block had its own size, as ffmpeg times it).
|
||||
local function bit(b: buffer, k: number): number
|
||||
return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1)
|
||||
end
|
||||
local function bits(b: buffer, k: number, n: number): number
|
||||
local v = 0
|
||||
for i = n - 1, 0, -1 do
|
||||
v = v * 2 + bit(b, k + i)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?)
|
||||
if buffer.len(id) < 30 or buffer.len(setup) < 8 then
|
||||
return nil
|
||||
end
|
||||
local bs = buffer.readu8(id, 28)
|
||||
local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) }
|
||||
-- the framing bit: the highest set bit of the last non-zero byte
|
||||
local last = buffer.len(setup) - 1
|
||||
while last > 0 and buffer.readu8(setup, last) == 0 do
|
||||
last -= 1
|
||||
end
|
||||
local v = buffer.readu8(setup, last)
|
||||
local hb = 7
|
||||
while hb > 0 and bit32.extract(v, hb, 1) == 0 do
|
||||
hb -= 1
|
||||
end
|
||||
local f = last * 8 + hb
|
||||
local flags: { boolean } = {}
|
||||
local pos = f
|
||||
while #flags < 64 and pos - 41 >= 7 * 8 do
|
||||
local s0 = pos - 41
|
||||
if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then
|
||||
break
|
||||
end
|
||||
table.insert(flags, 1, bit(setup, s0) == 1)
|
||||
pos = s0
|
||||
end
|
||||
-- the largest count whose 6-bit field matches
|
||||
for n = #flags, 1, -1 do
|
||||
local start = f - 41 * n
|
||||
if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then
|
||||
local out = {}
|
||||
for i = #flags - n + 1, #flags do
|
||||
table.insert(out, flags[i])
|
||||
end
|
||||
return sizes, out
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ ADTS
|
||||
local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
||||
local c = track.config
|
||||
local profile, rateIndex, chanConfig
|
||||
if c and buffer.len(c) >= 2 then
|
||||
local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1)
|
||||
profile = b0 // 8 -- audio object type
|
||||
rateIndex = (b0 % 8) * 2 + b1 // 128
|
||||
chanConfig = (b1 // 8) % 16
|
||||
else
|
||||
local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
profile = 2
|
||||
rateIndex = 4
|
||||
for i, r in rates do
|
||||
if r == math.floor((track.sampleRate or 44100) + 0.5) then
|
||||
rateIndex = i - 1
|
||||
end
|
||||
end
|
||||
chanConfig = track.channels or 2
|
||||
end
|
||||
if profile < 1 or profile > 4 or rateIndex > 12 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS")
|
||||
end
|
||||
local w = Bytes.writer(64)
|
||||
for _, p in packets do
|
||||
local len = buffer.len(p.data) + 7
|
||||
w:u8(0xFF)
|
||||
w:u8(0xF1)
|
||||
w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4)
|
||||
w:u8((chanConfig % 4) * 64 + (len // 2048) % 4)
|
||||
w:u8((len // 8) % 256)
|
||||
w:u8((len % 8) * 32 + 0x1F)
|
||||
w:u8(0xFC)
|
||||
w:bytes(p.data)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ trim
|
||||
-- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay:
|
||||
-- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself)
|
||||
function AudioWrap.trim(dec: any, skip: number): any
|
||||
if skip <= 0 then
|
||||
return dec
|
||||
end
|
||||
local rate = dec.sampleRate
|
||||
local w: any = setmetatable({}, { __index = dec })
|
||||
w.frames = math.max(0, (dec.frames or 0) - skip)
|
||||
w.duration = math.max(0, (dec.duration or 0) - skip / rate)
|
||||
local function drop()
|
||||
local left = skip
|
||||
while left > 0 do
|
||||
local _, n = dec:read(math.min(left, 4096))
|
||||
if not n or n <= 0 then
|
||||
break
|
||||
end
|
||||
left -= n
|
||||
end
|
||||
end
|
||||
local started = false
|
||||
function w.read(_: any, n: number, out: buffer?): (buffer, number)
|
||||
if not started then
|
||||
started = true
|
||||
drop()
|
||||
end
|
||||
return dec:read(n, out)
|
||||
end
|
||||
function w.seek(_: any, seconds: number)
|
||||
started = true
|
||||
if seconds <= 0 then
|
||||
dec:seek(0)
|
||||
drop()
|
||||
else
|
||||
dec:seek(seconds + skip / rate)
|
||||
end
|
||||
end
|
||||
function w.position(_: any): number
|
||||
return math.max(0, dec:position() - skip / rate)
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ wrap
|
||||
-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err
|
||||
function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?)
|
||||
if type(track) ~= "table" or track.kind ~= "audio" then
|
||||
return nil, nil, Err.new(Err.ARG, "not an audio track")
|
||||
end
|
||||
if track.unsupported then
|
||||
return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported)
|
||||
end
|
||||
local codec = track.codec
|
||||
local packets = allPackets(dmx, track)
|
||||
if #packets == 0 then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "audio track without packets")
|
||||
end
|
||||
if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then
|
||||
return wav(track.waveFormat, concat(packets)), "wav", nil
|
||||
end
|
||||
if PCM[codec] then
|
||||
local b, err = pcmWav(track, packets)
|
||||
return b, if b then "wav" else nil, err
|
||||
end
|
||||
if codec == "mp3" or codec == "mp2" or codec == "mp1" then
|
||||
return concat(packets), "mp3", nil
|
||||
end
|
||||
if codec == "flac" then
|
||||
local c = track.config
|
||||
local prefix: buffer? = nil
|
||||
if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then
|
||||
prefix = c
|
||||
elseif c and buffer.len(c) >= 34 then
|
||||
-- metadata blocks without the marker (MP4 dfLa payload after version / flags)
|
||||
local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0
|
||||
local b = buffer.create(4 + buffer.len(c) - start)
|
||||
buffer.writestring(b, 0, "fLaC")
|
||||
buffer.copy(b, 4, c, start)
|
||||
prefix = b
|
||||
else
|
||||
return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO")
|
||||
end
|
||||
return concat(packets, prefix), "flac", nil
|
||||
end
|
||||
if codec == "opus" then
|
||||
local head = opusHead(track)
|
||||
local pre = buffer.readu16(head, 10)
|
||||
local g = pre
|
||||
local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number
|
||||
g += opusSamples(p.data)
|
||||
local d = (p :: any).discardPadding
|
||||
if type(d) == "number" and d > 0 then
|
||||
return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding)
|
||||
end
|
||||
return g
|
||||
end)
|
||||
return out, "opus", nil
|
||||
end
|
||||
if codec == "vorbis" then
|
||||
local c = track.config
|
||||
local headers = c and xiphHeaders(c)
|
||||
if not headers or #headers ~= 3 then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers")
|
||||
end
|
||||
local sizes, modes = vorbisModes(headers[1], headers[3])
|
||||
local granule, prev = 0, nil :: number?
|
||||
local rate = track.sampleRate or 44100
|
||||
local scale = track.timescale
|
||||
local out = ogg(headers, packets, function(p: Types.Packet): number
|
||||
if not sizes or not modes then
|
||||
return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times
|
||||
end
|
||||
local d = p.data
|
||||
if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then
|
||||
return granule
|
||||
end
|
||||
local mb = 0
|
||||
while 2 ^ mb < #modes do
|
||||
mb += 1
|
||||
end
|
||||
local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0
|
||||
local cur = sizes[if modes[m + 1] then 2 else 1]
|
||||
if prev then
|
||||
granule += (prev + cur) // 4
|
||||
end
|
||||
prev = cur
|
||||
return granule
|
||||
end)
|
||||
return out, "vorbis", nil
|
||||
end
|
||||
if codec == "aac" then
|
||||
if track.adts then
|
||||
return concat(packets), "aac", nil -- already ADTS (MPEG-TS)
|
||||
end
|
||||
local b, err = adts(track, packets)
|
||||
return b, if b then "aac" else nil, err
|
||||
end
|
||||
return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec))
|
||||
end
|
||||
|
||||
return AudioWrap
|
||||
@@ -0,0 +1,523 @@
|
||||
--!strict
|
||||
-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in formats-luau.
|
||||
-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk
|
||||
-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets
|
||||
-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included).
|
||||
-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given.
|
||||
--
|
||||
-- local avi, err = Avi.read(buf, base, limit)
|
||||
-- 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()
|
||||
--
|
||||
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
|
||||
|
||||
local Avi = {}
|
||||
|
||||
export type Chunk = { offset: number, size: number, key: boolean }
|
||||
export type Stream = {
|
||||
index: number, -- 0-based stream number (the "##" of the chunk ids)
|
||||
type: string, -- strh fccType: "vids", "auds", "txts", "mids"
|
||||
handler: string,
|
||||
flags: number,
|
||||
scale: number,
|
||||
rate: number,
|
||||
start: number,
|
||||
length: number,
|
||||
suggestedBufferSize: number,
|
||||
sampleSize: number,
|
||||
frame: { number }, -- rcFrame left, top, right, bottom
|
||||
strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...)
|
||||
name: string?,
|
||||
chunks: { Chunk },
|
||||
}
|
||||
export type File = {
|
||||
avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number },
|
||||
streams: { Stream },
|
||||
odml: { totalFrames: number }?,
|
||||
info: { [string]: string },
|
||||
index: string, -- "odml" | "idx1" | "scan"
|
||||
}
|
||||
|
||||
local function u32(b: buffer, o: number): number
|
||||
return readu32(b, o)
|
||||
end
|
||||
|
||||
-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not
|
||||
-- entered); returns where it stopped
|
||||
local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number
|
||||
while p + 8 <= limit do
|
||||
local id = readstring(b, p, 4)
|
||||
local size = u32(b, p + 4)
|
||||
local data = p + 8
|
||||
local ltype: string? = nil
|
||||
if (id == "LIST" or id == "RIFF") and data + 4 <= limit then
|
||||
ltype = readstring(b, data, 4)
|
||||
end
|
||||
if data + size > limit then
|
||||
size = limit - data
|
||||
end
|
||||
if fn(id, data, size, ltype) == false then
|
||||
return p
|
||||
end
|
||||
p = data + size + (size % 2)
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
local function streamNumber(id: string): number?
|
||||
local a, b = string.byte(id, 1, 2)
|
||||
if not a or not b then
|
||||
return nil
|
||||
end
|
||||
local function hex(c: number): number?
|
||||
if c >= 48 and c <= 57 then
|
||||
return c - 48
|
||||
elseif c >= 65 and c <= 70 then
|
||||
return c - 55
|
||||
elseif c >= 97 and c <= 102 then
|
||||
return c - 87
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local h, l = hex(a), hex(b)
|
||||
if h and l then
|
||||
return h * 16 + l
|
||||
end
|
||||
return nil
|
||||
end
|
||||
Avi.streamNumber = streamNumber
|
||||
|
||||
local function parseStrl(b: buffer, data: number, size: number, index: number): Stream
|
||||
local s: Stream = {
|
||||
index = index,
|
||||
type = "",
|
||||
handler = "",
|
||||
flags = 0,
|
||||
scale = 1,
|
||||
rate = 1,
|
||||
start = 0,
|
||||
length = 0,
|
||||
suggestedBufferSize = 0,
|
||||
sampleSize = 0,
|
||||
frame = { 0, 0, 0, 0 },
|
||||
strf = buffer.create(0),
|
||||
chunks = {},
|
||||
}
|
||||
local indx: { number }? = nil
|
||||
walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean?
|
||||
if id == "strh" and n >= 48 then
|
||||
s.type = readstring(b, d, 4)
|
||||
s.handler = readstring(b, d + 4, 4)
|
||||
s.flags = u32(b, d + 8)
|
||||
s.scale = u32(b, d + 20)
|
||||
s.rate = u32(b, d + 24)
|
||||
s.start = u32(b, d + 28)
|
||||
s.length = u32(b, d + 32)
|
||||
s.suggestedBufferSize = u32(b, d + 36)
|
||||
s.sampleSize = u32(b, d + 44)
|
||||
if n >= 56 then
|
||||
s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) }
|
||||
end
|
||||
elseif id == "strf" then
|
||||
local f = buffer.create(n)
|
||||
buffer.copy(f, 0, b, d, n)
|
||||
s.strf = f
|
||||
elseif id == "strn" then
|
||||
local str = readstring(b, d, n)
|
||||
s.name = string.match(str, "^[^%z]*")
|
||||
elseif id == "indx" and n >= 24 then
|
||||
indx = { d, n }
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
;(s :: any)._indx = indx
|
||||
return s
|
||||
end
|
||||
|
||||
-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s
|
||||
local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean
|
||||
if n < 24 or depth > 2 then
|
||||
return false
|
||||
end
|
||||
local longsPerEntry = readu16(b, d)
|
||||
local subType = readu8(b, d + 2)
|
||||
local indexType = readu8(b, d + 3)
|
||||
local entries = u32(b, d + 4)
|
||||
if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration }
|
||||
if longsPerEntry ~= 4 then
|
||||
return false
|
||||
end
|
||||
local p = d + 24
|
||||
for _ = 1, entries do
|
||||
if p + 16 > d + n then
|
||||
break
|
||||
end
|
||||
local off = u32(b, p) + u32(b, p + 4) * 4294967296
|
||||
local size = u32(b, p + 8)
|
||||
p += 16
|
||||
if off > 0 and off + 8 <= limit then
|
||||
local sz = math.min(u32(b, off + 4), limit - off - 8)
|
||||
readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1)
|
||||
end
|
||||
end
|
||||
return #s.chunks > 0
|
||||
elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs)
|
||||
if n < 24 then
|
||||
return false
|
||||
end
|
||||
local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296
|
||||
local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD
|
||||
local p = d + 24
|
||||
for _ = 1, entries do
|
||||
if p + per > d + n then
|
||||
break
|
||||
end
|
||||
local off = u32(b, p)
|
||||
local size = u32(b, p + 4)
|
||||
p += per
|
||||
local key = size < 0x80000000
|
||||
size %= 0x80000000
|
||||
local at = base + off
|
||||
if at >= 0 and at + size <= limit then
|
||||
table.insert(s.chunks, { offset = at, size = size, key = key })
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- read(buf, base, limit) -> File | nil, Err
|
||||
function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
|
||||
if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then
|
||||
return nil, Err.new(Err.CORRUPT, "not an AVI file", base)
|
||||
end
|
||||
local file: File = {
|
||||
avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 },
|
||||
streams = {},
|
||||
odml = nil,
|
||||
info = {},
|
||||
index = "scan",
|
||||
}
|
||||
local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end }
|
||||
local idx1: { number }? = nil
|
||||
local hdrl = false
|
||||
-- every RIFF piece (AVI, then AVIX for OpenDML files)
|
||||
walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean?
|
||||
if id ~= "RIFF" then
|
||||
return nil
|
||||
end
|
||||
walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean?
|
||||
if cid == "LIST" and cltype == "hdrl" and not hdrl then
|
||||
hdrl = true
|
||||
local si = 0
|
||||
walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean?
|
||||
if hid == "avih" and hn >= 40 then
|
||||
file.avih = {
|
||||
microSecPerFrame = u32(b, hd),
|
||||
flags = u32(b, hd + 12),
|
||||
totalFrames = u32(b, hd + 16),
|
||||
streams = u32(b, hd + 24),
|
||||
width = u32(b, hd + 32),
|
||||
height = u32(b, hd + 36),
|
||||
}
|
||||
elseif hid == "LIST" and hltype == "strl" then
|
||||
table.insert(file.streams, parseStrl(b, hd, hn, si))
|
||||
si += 1
|
||||
elseif hid == "LIST" and hltype == "odml" then
|
||||
walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean?
|
||||
if oid == "dmlh" and on >= 4 then
|
||||
file.odml = { totalFrames = u32(b, od) }
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
elseif cid == "LIST" and cltype == "movi" then
|
||||
table.insert(movis, { cd, cd + cn })
|
||||
elseif cid == "LIST" and cltype == "INFO" then
|
||||
walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean?
|
||||
file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or ""
|
||||
return nil
|
||||
end)
|
||||
elseif cid == "idx1" and not idx1 then
|
||||
idx1 = { cd, cn }
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
return nil
|
||||
end)
|
||||
if not hdrl then
|
||||
return nil, Err.new(Err.CORRUPT, "no hdrl list")
|
||||
end
|
||||
if #file.streams == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no streams")
|
||||
end
|
||||
-- 1. OpenDML indexes
|
||||
local odml = true
|
||||
for _, s in file.streams do
|
||||
local ix = (s :: any)._indx
|
||||
if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then
|
||||
odml = false
|
||||
end
|
||||
end
|
||||
if odml then
|
||||
file.index = "odml"
|
||||
else
|
||||
for _, s in file.streams do
|
||||
table.clear(s.chunks)
|
||||
end
|
||||
-- 2. idx1
|
||||
local ok = false
|
||||
if idx1 and movis[1] then
|
||||
local d, n = idx1[1], idx1[2]
|
||||
local count = n // 16
|
||||
local moviBase = movis[1][1] -- the 'movi' fourcc
|
||||
-- relative or absolute offsets: check the first entry that points at a chunk id
|
||||
local rel = true
|
||||
if count > 0 then
|
||||
local off = u32(b, d + 8)
|
||||
local ckid = readstring(b, d, 4)
|
||||
local relAt, absAt = moviBase + off, base + off
|
||||
if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then
|
||||
rel = true
|
||||
elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then
|
||||
rel = false
|
||||
end
|
||||
end
|
||||
for k = 0, count - 1 do
|
||||
local e = d + k * 16
|
||||
local ckid = readstring(b, e, 4)
|
||||
local flags = u32(b, e + 4)
|
||||
local off = u32(b, e + 8)
|
||||
local size = u32(b, e + 12)
|
||||
local sn = streamNumber(ckid)
|
||||
local s = sn and file.streams[sn + 1]
|
||||
if s and string.sub(ckid, 3, 4) ~= "pc" then
|
||||
local at = (if rel then moviBase else base) + off + 8
|
||||
if at + size <= limit then
|
||||
table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 })
|
||||
ok = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
file.index = "idx1"
|
||||
else
|
||||
for _, s in file.streams do
|
||||
table.clear(s.chunks)
|
||||
end
|
||||
-- 3. scan the movi lists
|
||||
local function scan(d0: number, e0: number)
|
||||
walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean?
|
||||
if id == "LIST" and ltype == "rec " then
|
||||
scan(d + 4, d + n)
|
||||
return nil
|
||||
end
|
||||
local sn = streamNumber(id)
|
||||
local s = sn and file.streams[sn + 1]
|
||||
if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then
|
||||
table.insert(s.chunks, { offset = d, size = n, key = true })
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
end
|
||||
for _, m in movis do
|
||||
scan(m[1] + 4, m[2])
|
||||
end
|
||||
file.index = "scan"
|
||||
end
|
||||
end
|
||||
for _, s in file.streams do
|
||||
(s :: any)._indx = nil
|
||||
end
|
||||
return file, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writing
|
||||
export type WStream = {
|
||||
type: string, -- "vids" | "auds"
|
||||
handler: string, -- fccHandler (4 chars)
|
||||
scale: number,
|
||||
rate: number,
|
||||
sampleSize: number, -- 0 = every chunk one sample (video, VBR audio)
|
||||
strf: buffer,
|
||||
name: string?,
|
||||
width: number?,
|
||||
height: number?,
|
||||
quality: number?,
|
||||
ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio)
|
||||
}
|
||||
export type WOptions = {
|
||||
streams: { WStream },
|
||||
microSecPerFrame: number,
|
||||
width: number,
|
||||
height: number,
|
||||
software: string?,
|
||||
}
|
||||
|
||||
-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order
|
||||
function Avi.write(opts: WOptions, chunks: { { any } }): buffer
|
||||
local ns = #opts.streams
|
||||
local lengths = table.create(ns, 0)
|
||||
local maxChunk = table.create(ns, 0)
|
||||
local bytes = table.create(ns, 0)
|
||||
local total = 0
|
||||
for _, c in chunks do
|
||||
local si, data = c[1], c[2]
|
||||
local n = buffer.len(data)
|
||||
local s = opts.streams[si]
|
||||
if s.sampleSize > 0 then
|
||||
lengths[si] += n // s.sampleSize
|
||||
else
|
||||
lengths[si] += 1
|
||||
end
|
||||
bytes[si] += n
|
||||
if n > maxChunk[si] then
|
||||
maxChunk[si] = n
|
||||
end
|
||||
total += n + 8 + (n % 2)
|
||||
end
|
||||
local frames = 0
|
||||
for si, s in opts.streams do
|
||||
if s.type == "vids" and frames == 0 then
|
||||
frames = lengths[si]
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(total + 4096 + #chunks * 16)
|
||||
w:string("RIFF")
|
||||
local riffSize = w:tell()
|
||||
w:u32le(0)
|
||||
w:string("AVI ")
|
||||
-- hdrl
|
||||
w:string("LIST")
|
||||
local hdrlSize = w:tell()
|
||||
w:u32le(0)
|
||||
w:string("hdrl")
|
||||
w:string("avih")
|
||||
w:u32le(56)
|
||||
local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1
|
||||
local maxBytes = 0
|
||||
for si = 1, ns do
|
||||
maxBytes += bytes[si]
|
||||
end
|
||||
w:u32le(math.floor(opts.microSecPerFrame + 0.5))
|
||||
w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0)
|
||||
w:u32le(0) -- padding granularity
|
||||
w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED
|
||||
w:u32le(frames)
|
||||
w:u32le(0) -- initial frames
|
||||
w:u32le(ns)
|
||||
local suggested = 0
|
||||
for si = 1, ns do
|
||||
suggested = math.max(suggested, maxChunk[si] + 8)
|
||||
end
|
||||
w:u32le(suggested)
|
||||
w:u32le(opts.width)
|
||||
w:u32le(opts.height)
|
||||
for _ = 1, 4 do
|
||||
w:u32le(0)
|
||||
end
|
||||
for si, s in opts.streams do
|
||||
w:string("LIST")
|
||||
local strlSize = w:tell()
|
||||
w:u32le(0)
|
||||
w:string("strl")
|
||||
w:string("strh")
|
||||
w:u32le(56)
|
||||
w:string(s.type)
|
||||
w:string(s.handler)
|
||||
w:u32le(0) -- flags
|
||||
w:u16le(0) -- priority
|
||||
w:u16le(0) -- language
|
||||
w:u32le(0) -- initial frames
|
||||
w:u32le(s.scale)
|
||||
w:u32le(s.rate)
|
||||
w:u32le(0) -- start
|
||||
w:u32le(lengths[si])
|
||||
w:u32le(maxChunk[si])
|
||||
w:u32le(if s.quality then s.quality else 0xFFFFFFFF)
|
||||
w:u32le(s.sampleSize)
|
||||
w:u16le(0)
|
||||
w:u16le(0)
|
||||
w:u16le(s.width or 0)
|
||||
w:u16le(s.height or 0)
|
||||
w:string("strf")
|
||||
w:u32le(buffer.len(s.strf))
|
||||
w:bytes(s.strf)
|
||||
if buffer.len(s.strf) % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
if s.name then
|
||||
local nm = s.name .. "\0"
|
||||
w:string("strn")
|
||||
w:u32le(#nm)
|
||||
w:string(nm)
|
||||
if #nm % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
end
|
||||
w:setU32le(strlSize, w:tell() - strlSize - 4)
|
||||
end
|
||||
-- OpenDML extended header (total frames)
|
||||
w:string("LIST")
|
||||
w:u32le(16)
|
||||
w:string("odml")
|
||||
w:string("dmlh")
|
||||
w:u32le(4)
|
||||
w:u32le(frames)
|
||||
w:setU32le(hdrlSize, w:tell() - hdrlSize - 4)
|
||||
-- INFO
|
||||
local sw = (opts.software or "formats-luau") .. "\0"
|
||||
if #sw % 2 == 1 then
|
||||
sw ..= "\0"
|
||||
end
|
||||
w:string("LIST")
|
||||
w:u32le(4 + 8 + #sw)
|
||||
w:string("INFO")
|
||||
w:string("ISFT")
|
||||
w:u32le(#sw)
|
||||
w:string(sw)
|
||||
-- movi
|
||||
w:string("LIST")
|
||||
local moviSize = w:tell()
|
||||
w:u32le(0)
|
||||
local moviBase = w:tell()
|
||||
w:string("movi")
|
||||
local index = table.create(#chunks)
|
||||
for _, c in chunks do
|
||||
local si, data, key = c[1], c[2], c[3]
|
||||
local s = opts.streams[si]
|
||||
local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb"))
|
||||
local at = w:tell()
|
||||
local n = buffer.len(data)
|
||||
w:string(id)
|
||||
w:u32le(n)
|
||||
w:bytes(data)
|
||||
if n % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n })
|
||||
end
|
||||
w:setU32le(moviSize, w:tell() - moviSize - 4)
|
||||
-- idx1
|
||||
w:string("idx1")
|
||||
w:u32le(#index * 16)
|
||||
for _, e in index do
|
||||
w:string(e[1])
|
||||
w:u32le(e[2])
|
||||
w:u32le(e[3])
|
||||
w:u32le(e[4])
|
||||
end
|
||||
w:setU32le(riffSize, w:tell() - 8)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
return Avi
|
||||
@@ -0,0 +1,296 @@
|
||||
--!strict
|
||||
-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4).
|
||||
-- New in formats-luau. A container parses its file once into an index of packets (track, pts, dts, duration,
|
||||
-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives
|
||||
-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file
|
||||
-- independently), a file-order cursor, keyframe seeking, packet copies on demand.
|
||||
--
|
||||
-- local d = Demux.new("mkv", tracks, src, meta)
|
||||
-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order
|
||||
-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src
|
||||
-- d:finish() -- durations, per-track indexes
|
||||
-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i)
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Demux = {}
|
||||
local D = {}
|
||||
D.__index = D
|
||||
|
||||
export type Demux = typeof(setmetatable(
|
||||
{} :: {
|
||||
kind: "demuxer",
|
||||
format: string,
|
||||
tracks: { Types.Track },
|
||||
duration: number,
|
||||
startTime: number,
|
||||
meta: { [string]: any },
|
||||
src: buffer,
|
||||
n: number,
|
||||
tr: { number },
|
||||
pts: { number },
|
||||
dts: { number },
|
||||
dur: { number },
|
||||
key: { boolean },
|
||||
off: { number },
|
||||
len: { number },
|
||||
data: { [number]: buffer },
|
||||
extra: { [number]: { [string]: any } },
|
||||
byTrack: { [number]: { number } },
|
||||
cur: { [number]: number },
|
||||
gcur: number,
|
||||
},
|
||||
D
|
||||
))
|
||||
|
||||
-- new(format, tracks, src, meta?) -> an empty index
|
||||
function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux
|
||||
return setmetatable({
|
||||
kind = "demuxer" :: "demuxer",
|
||||
format = format,
|
||||
tracks = tracks,
|
||||
duration = 0,
|
||||
startTime = 0,
|
||||
meta = meta or {},
|
||||
src = src,
|
||||
n = 0,
|
||||
tr = {},
|
||||
pts = {},
|
||||
dts = {},
|
||||
dur = {},
|
||||
key = {},
|
||||
off = {},
|
||||
len = {},
|
||||
data = {},
|
||||
extra = {},
|
||||
byTrack = {},
|
||||
cur = {},
|
||||
gcur = 1,
|
||||
}, D)
|
||||
end
|
||||
|
||||
-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length)
|
||||
function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number)
|
||||
local i = self.n + 1
|
||||
self.n = i
|
||||
self.tr[i] = track
|
||||
self.pts[i] = pts
|
||||
self.dts[i] = dts or pts
|
||||
self.dur[i] = duration or 0
|
||||
self.key[i] = keyframe
|
||||
self.off[i] = offset
|
||||
self.len[i] = length
|
||||
end
|
||||
|
||||
-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes
|
||||
function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer)
|
||||
self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data))
|
||||
self.data[self.n] = data
|
||||
end
|
||||
|
||||
-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...)
|
||||
function D.setExtra(self: Demux, key: string, value: any)
|
||||
local e = self.extra[self.n]
|
||||
if not e then
|
||||
e = {}
|
||||
self.extra[self.n] = e
|
||||
end
|
||||
e[key] = value
|
||||
end
|
||||
|
||||
-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's
|
||||
-- frame rate), and the track / file durations (seconds) where the container gave none
|
||||
function D.finish(self: Demux)
|
||||
local byTrack: { [number]: { number } } = {}
|
||||
for _, t in self.tracks do
|
||||
byTrack[t.id] = {}
|
||||
end
|
||||
for i = 1, self.n do
|
||||
local list = byTrack[self.tr[i]]
|
||||
if list then
|
||||
table.insert(list, i)
|
||||
end
|
||||
end
|
||||
self.byTrack = byTrack
|
||||
local total = self.duration
|
||||
local start = math.huge
|
||||
for _, t in self.tracks do
|
||||
local list = byTrack[t.id]
|
||||
local scale = if t.timescale and t.timescale > 0 then t.timescale else 1
|
||||
t.timescale = scale
|
||||
local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0
|
||||
-- durations from the next packet in presentation order
|
||||
if #list > 0 then
|
||||
local order = table.clone(list)
|
||||
table.sort(order, function(a: number, b: number): boolean
|
||||
return self.pts[a] < self.pts[b]
|
||||
end)
|
||||
for k = 1, #order do
|
||||
local i = order[k]
|
||||
if self.dur[i] <= 0 then
|
||||
local nx = order[k + 1]
|
||||
if nx and self.pts[nx] > self.pts[i] then
|
||||
self.dur[i] = self.pts[nx] - self.pts[i]
|
||||
elseif frameTicks > 0 then
|
||||
self.dur[i] = frameTicks
|
||||
elseif k > 1 then
|
||||
self.dur[i] = self.dur[order[k - 1]]
|
||||
end
|
||||
end
|
||||
end
|
||||
local first, last = order[1], order[#order]
|
||||
if t.kind == "video" or t.kind == "audio" then
|
||||
start = math.min(start, self.pts[first] / scale)
|
||||
end
|
||||
local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale
|
||||
if not t.duration or t.duration <= 0 then
|
||||
t.duration = d
|
||||
end
|
||||
t.frames = t.frames or #list
|
||||
end
|
||||
if t.duration and t.duration > total then
|
||||
total = t.duration
|
||||
end
|
||||
self.cur[t.id] = 1
|
||||
end
|
||||
self.duration = total
|
||||
-- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count
|
||||
-- frame times from it
|
||||
self.startTime = if start ~= math.huge and start > 0 then start else 0
|
||||
end
|
||||
|
||||
-- the Packet for index entry i (a copy of its bytes)
|
||||
function D._packet(self: Demux, i: number): Types.Packet
|
||||
local data = self.data[i]
|
||||
if not data then
|
||||
local o, l = self.off[i], self.len[i]
|
||||
local src = self.src
|
||||
local n = buffer.len(src)
|
||||
if o < 0 or o > n then
|
||||
o, l = n, 0
|
||||
elseif o + l > n then
|
||||
l = n - o
|
||||
end
|
||||
data = buffer.create(l)
|
||||
buffer.copy(data, 0, src, o, l)
|
||||
end
|
||||
local p: any = {
|
||||
track = self.tr[i],
|
||||
pts = self.pts[i],
|
||||
dts = self.dts[i],
|
||||
duration = self.dur[i],
|
||||
keyframe = self.key[i],
|
||||
data = data :: buffer,
|
||||
}
|
||||
local e = self.extra[i]
|
||||
if e then
|
||||
for k, v in e do
|
||||
p[k] = v
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end
|
||||
function D.read(self: Demux, track: number?): Types.Packet?
|
||||
if track == nil then
|
||||
local i = self.gcur
|
||||
if i > self.n then
|
||||
return nil
|
||||
end
|
||||
self.gcur = i + 1
|
||||
return self:_packet(i)
|
||||
end
|
||||
local list = self.byTrack[track]
|
||||
if not list then
|
||||
return nil
|
||||
end
|
||||
local c = self.cur[track] or 1
|
||||
local i = list[c]
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
self.cur[track] = c + 1
|
||||
return self:_packet(i)
|
||||
end
|
||||
|
||||
-- packets(track?) -> an iterator of Packets from the current position (advancing it)
|
||||
function D.packets(self: Demux, track: number?): () -> Types.Packet?
|
||||
return function(): Types.Packet?
|
||||
return self:read(track)
|
||||
end
|
||||
end
|
||||
|
||||
-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors
|
||||
function D.count(self: Demux, track: number): number
|
||||
local list = self.byTrack[track]
|
||||
return if list then #list else 0
|
||||
end
|
||||
function D.get(self: Demux, track: number, k: number): Types.Packet?
|
||||
local list = self.byTrack[track]
|
||||
local i = list and list[k]
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
return self:_packet(i)
|
||||
end
|
||||
|
||||
-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy)
|
||||
function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?)
|
||||
local list = self.byTrack[track]
|
||||
local i = list and list[k]
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i]
|
||||
end
|
||||
|
||||
-- rewind(track?): a track's cursor (or every cursor) back to the start
|
||||
function D.rewind(self: Demux, track: number?)
|
||||
if track then
|
||||
self.cur[track] = 1
|
||||
return
|
||||
end
|
||||
for id in self.cur do
|
||||
self.cur[id] = 1
|
||||
end
|
||||
self.gcur = 1
|
||||
end
|
||||
|
||||
-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest)
|
||||
function D.seek(self: Demux, seconds: number)
|
||||
local g = self.n + 1
|
||||
for _, t in self.tracks do
|
||||
local list = self.byTrack[t.id]
|
||||
if list and #list > 0 then
|
||||
local target = seconds * t.timescale
|
||||
local best = 1
|
||||
for k = 1, #list do
|
||||
local i = list[k]
|
||||
if self.key[i] and self.pts[i] <= target + 1e-6 then
|
||||
best = k
|
||||
end
|
||||
end
|
||||
self.cur[t.id] = best
|
||||
if list[best] < g then
|
||||
g = list[best]
|
||||
end
|
||||
end
|
||||
end
|
||||
self.gcur = if g > self.n then 1 else g
|
||||
end
|
||||
|
||||
-- track(kind) -> the first default track of the kind, else the first of the kind
|
||||
function D.track(self: Demux, kind: string): Types.Track?
|
||||
local first = nil
|
||||
for _, t in self.tracks do
|
||||
if t.kind == kind then
|
||||
if t.default then
|
||||
return t
|
||||
end
|
||||
first = first or t
|
||||
end
|
||||
end
|
||||
return first
|
||||
end
|
||||
|
||||
return Demux
|
||||
@@ -0,0 +1,335 @@
|
||||
--!strict
|
||||
-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in formats-luau.
|
||||
-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it;
|
||||
-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats,
|
||||
-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and
|
||||
-- minimal-length value elements.
|
||||
--
|
||||
-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated
|
||||
-- for id, off, size in Ebml.children(buf, off, limit) do ... end
|
||||
-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish()
|
||||
--
|
||||
-- Never throws: malformed input gives nil (readers) or stops iteration.
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local Ebml = {}
|
||||
|
||||
Ebml.UNKNOWN = -1
|
||||
|
||||
-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1.
|
||||
function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?)
|
||||
if pos >= limit then
|
||||
return nil
|
||||
end
|
||||
local b = readu8(buf, pos)
|
||||
if b == 0 then
|
||||
return nil
|
||||
end
|
||||
local len = 1
|
||||
local mask = 0x80
|
||||
while bit32.band(b, mask) == 0 do
|
||||
len += 1
|
||||
mask = mask // 2
|
||||
end
|
||||
if pos + len > limit then
|
||||
return nil
|
||||
end
|
||||
local v = bit32.band(b, mask - 1)
|
||||
local allOnes = v == mask - 1
|
||||
for i = 1, len - 1 do
|
||||
local c = readu8(buf, pos + i)
|
||||
v = v * 256 + c
|
||||
if c ~= 255 then
|
||||
allOnes = false
|
||||
end
|
||||
end
|
||||
if allOnes then
|
||||
return -1, len
|
||||
end
|
||||
return v, len
|
||||
end
|
||||
|
||||
-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil
|
||||
function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?)
|
||||
local v, len = Ebml.vint(buf, pos, limit)
|
||||
if v == nil or len == nil then
|
||||
return nil
|
||||
end
|
||||
if v == -1 then
|
||||
return nil
|
||||
end
|
||||
return v - (2 ^ (7 * len - 1) - 1), len
|
||||
end
|
||||
|
||||
-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes)
|
||||
function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?)
|
||||
if pos >= limit then
|
||||
return nil
|
||||
end
|
||||
local b = readu8(buf, pos)
|
||||
local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0
|
||||
if len == 0 or pos + len > limit then
|
||||
return nil
|
||||
end
|
||||
local v = b
|
||||
for i = 1, len - 1 do
|
||||
v = v * 256 + readu8(buf, pos + i)
|
||||
end
|
||||
return v, len
|
||||
end
|
||||
|
||||
-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil
|
||||
function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?)
|
||||
local id, il = Ebml.id(buf, pos, limit)
|
||||
if not id or not il then
|
||||
return nil
|
||||
end
|
||||
local size, sl = Ebml.vint(buf, pos + il, limit)
|
||||
if not size or not sl then
|
||||
return nil
|
||||
end
|
||||
return id, size, pos + il + sl
|
||||
end
|
||||
|
||||
-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the
|
||||
-- limit is clipped; a malformed header ends the iteration)
|
||||
function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number)
|
||||
local pos = off
|
||||
return function(): (number?, number, number)
|
||||
if pos >= limit then
|
||||
return nil, 0, 0
|
||||
end
|
||||
local id, size, data = Ebml.header(buf, pos, limit)
|
||||
if not id or not size or not data then
|
||||
pos = limit
|
||||
return nil, 0, 0
|
||||
end
|
||||
if size < 0 or data + size > limit then
|
||||
size = limit - data
|
||||
end
|
||||
pos = data + size
|
||||
return id, data, size
|
||||
end
|
||||
end
|
||||
|
||||
-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements)
|
||||
function Ebml.uint(buf: buffer, off: number, len: number): number
|
||||
local v = 0
|
||||
for i = 0, math.min(len, 8) - 1 do
|
||||
v = v * 256 + readu8(buf, off + i)
|
||||
end
|
||||
return v
|
||||
end
|
||||
function Ebml.int(buf: buffer, off: number, len: number): number
|
||||
if len <= 0 then
|
||||
return 0
|
||||
end
|
||||
local v = Ebml.uint(buf, off, len)
|
||||
local n = math.min(len, 8)
|
||||
if readu8(buf, off) >= 0x80 then
|
||||
v -= 2 ^ (8 * n)
|
||||
end
|
||||
return v
|
||||
end
|
||||
function Ebml.float(buf: buffer, off: number, len: number): number
|
||||
local r = Bytes.reader(buf, off, len)
|
||||
if len == 4 then
|
||||
return r:f32be()
|
||||
elseif len == 8 then
|
||||
return r:f64be()
|
||||
end
|
||||
return 0
|
||||
end
|
||||
function Ebml.string(buf: buffer, off: number, len: number): string
|
||||
local s = buffer.readstring(buf, off, len)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
if z then
|
||||
s = string.sub(s, 1, z - 1)
|
||||
end
|
||||
return s
|
||||
end
|
||||
function Ebml.binary(buf: buffer, off: number, len: number): buffer
|
||||
local b = buffer.create(len)
|
||||
buffer.copy(b, 0, buf, off, len)
|
||||
return b
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writing
|
||||
local W = {}
|
||||
W.__index = W
|
||||
|
||||
export type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W))
|
||||
|
||||
-- writer(capacity?) -> an EBML byte builder
|
||||
function Ebml.writer(capacity: number?): Writer
|
||||
return setmetatable({ w = Bytes.writer(capacity or 65536) }, W)
|
||||
end
|
||||
|
||||
-- idBytes(id) -> the ID's bytes as written
|
||||
local function writeId(w: Bytes.Writer, id: number)
|
||||
if id >= 0x1000000 then
|
||||
w:u32be(id)
|
||||
elseif id >= 0x10000 then
|
||||
w:u24be(id)
|
||||
elseif id >= 0x100 then
|
||||
w:u16be(id)
|
||||
else
|
||||
w:u8(id)
|
||||
end
|
||||
end
|
||||
|
||||
-- size as a minimal vint (n bytes: force a length)
|
||||
local function writeSize(w: Bytes.Writer, size: number, n: number?)
|
||||
local len = n or 1
|
||||
if not n then
|
||||
while size >= 2 ^ (7 * len) - 1 do
|
||||
len += 1
|
||||
end
|
||||
end
|
||||
local v = size + 2 ^ (7 * len) -- the marker bit
|
||||
local bytes = table.create(len, 0)
|
||||
for i = len, 1, -1 do
|
||||
bytes[i] = v % 256
|
||||
v = v // 256
|
||||
end
|
||||
for i = 1, len do
|
||||
w:u8(bytes[i])
|
||||
end
|
||||
end
|
||||
Ebml.writeSize = writeSize
|
||||
|
||||
-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers)
|
||||
function Ebml.vintString(v: number, n: number?): string
|
||||
local w = Bytes.writer(8)
|
||||
writeSize(w, v, n)
|
||||
return buffer.readstring(w:finish(), 0, w:tell())
|
||||
end
|
||||
|
||||
function W.tell(self: Writer): number
|
||||
return self.w:tell()
|
||||
end
|
||||
|
||||
-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder
|
||||
function W.open(self: Writer, id: number): number
|
||||
writeId(self.w, id)
|
||||
local at = self.w:tell()
|
||||
for _ = 1, 8 do
|
||||
self.w:u8(0)
|
||||
end
|
||||
return at
|
||||
end
|
||||
|
||||
-- close(handle): patches the size of the element opened at handle
|
||||
function W.close(self: Writer, at: number)
|
||||
local w = self.w
|
||||
local v = w:tell() - at - 8
|
||||
w:setU8(at, 0x01)
|
||||
for i = 7, 1, -1 do
|
||||
w:setU8(at + i, v % 256)
|
||||
v = v // 256
|
||||
end
|
||||
end
|
||||
|
||||
-- unknownSize(id): a master element with an unknown size (live streams)
|
||||
function W.openUnknown(self: Writer, id: number)
|
||||
writeId(self.w, id)
|
||||
self.w:u8(0x01)
|
||||
for _ = 1, 7 do
|
||||
self.w:u8(0xFF)
|
||||
end
|
||||
end
|
||||
|
||||
function W.uint(self: Writer, id: number, v: number)
|
||||
local n = 1
|
||||
while v >= 2 ^ (8 * n) and n < 8 do
|
||||
n += 1
|
||||
end
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, n)
|
||||
local bytes = table.create(n, 0)
|
||||
local x = v
|
||||
for i = n, 1, -1 do
|
||||
bytes[i] = x % 256
|
||||
x = x // 256
|
||||
end
|
||||
for i = 1, n do
|
||||
self.w:u8(bytes[i])
|
||||
end
|
||||
end
|
||||
|
||||
function W.int(self: Writer, id: number, v: number)
|
||||
local n = 1
|
||||
while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do
|
||||
n += 1
|
||||
end
|
||||
local u = if v < 0 then v + 2 ^ (8 * n) else v
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, n)
|
||||
local bytes = table.create(n, 0)
|
||||
for i = n, 1, -1 do
|
||||
bytes[i] = u % 256
|
||||
u = u // 256
|
||||
end
|
||||
for i = 1, n do
|
||||
self.w:u8(bytes[i])
|
||||
end
|
||||
end
|
||||
|
||||
function W.float(self: Writer, id: number, v: number)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, 8)
|
||||
self.w:f64be(v)
|
||||
end
|
||||
|
||||
function W.string(self: Writer, id: number, s: string)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, #s)
|
||||
self.w:string(s)
|
||||
end
|
||||
|
||||
-- binary(id, buf, off?, len?)
|
||||
function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?)
|
||||
local o = off or 0
|
||||
local n = len or (buffer.len(b) - o)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, n)
|
||||
self.w:bytes(b, o, n)
|
||||
end
|
||||
|
||||
-- raw bytes (a pre-built element, block headers)
|
||||
function W.raw(self: Writer, s: string)
|
||||
self.w:string(s)
|
||||
end
|
||||
function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?)
|
||||
local o = off or 0
|
||||
self.w:bytes(b, o, len or (buffer.len(b) - o))
|
||||
end
|
||||
-- element header for a binary element whose payload follows in pieces: id + size
|
||||
function W.header(self: Writer, id: number, size: number)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, size)
|
||||
end
|
||||
|
||||
-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space
|
||||
function W.void(self: Writer, n: number)
|
||||
self.w:u8(0xEC)
|
||||
if n - 2 < 127 then
|
||||
writeSize(self.w, n - 2, 1)
|
||||
for _ = 1, n - 2 do
|
||||
self.w:u8(0)
|
||||
end
|
||||
else
|
||||
writeSize(self.w, n - 9, 8)
|
||||
for _ = 1, n - 9 do
|
||||
self.w:u8(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function W.finish(self: Writer): buffer
|
||||
return self.w:finish()
|
||||
end
|
||||
|
||||
return Ebml
|
||||
@@ -92,7 +92,7 @@ local function esds(w: Bytes.Writer, t: MuxTrack)
|
||||
c:u24be(0)
|
||||
c:u32be(t.bitrate or 0)
|
||||
c:u32be(t.bitrate or 0)
|
||||
if t.config then
|
||||
if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info)
|
||||
descriptor(c, 5, function(s)
|
||||
s:bytes(t.config :: buffer)
|
||||
end)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
--!strict
|
||||
-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in formats-luau.
|
||||
-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it,
|
||||
-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence
|
||||
-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws.
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local MpegEs = {}
|
||||
|
||||
-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil
|
||||
function MpegEs.findStart(b: buffer, p: number, limit: number): number?
|
||||
local i = p
|
||||
while i + 3 <= limit do
|
||||
local c = readu8(b, i + 2)
|
||||
if c > 1 then
|
||||
i += 3
|
||||
elseif c == 1 then
|
||||
if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then
|
||||
return i
|
||||
end
|
||||
i += 3
|
||||
else -- c == 0: the start code may begin at i + 1 or i + 2
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 }
|
||||
|
||||
export type Picture = {
|
||||
offset: number, -- start of the access unit (its first header's start code)
|
||||
size: number,
|
||||
type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown)
|
||||
temporal: number, -- temporal_reference
|
||||
gop: boolean, -- a GOP header precedes the picture
|
||||
sequence: boolean, -- a sequence header precedes the picture
|
||||
}
|
||||
export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean }
|
||||
|
||||
-- info(b, off, limit) -> the first sequence header's facts | nil
|
||||
function MpegEs.info(b: buffer, off: number, limit: number): Info?
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
local info: Info? = nil
|
||||
local count = 0
|
||||
while p and count < 64 do
|
||||
count += 1
|
||||
local code = if p + 3 < limit then readu8(b, p + 3) else -1
|
||||
if code == 0xB3 and p + 11 < limit and not info then
|
||||
local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16
|
||||
local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6)
|
||||
local fr = readu8(b, p + 7) % 16
|
||||
info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false }
|
||||
elseif code == 0xB5 and info then
|
||||
info.mpeg2 = true
|
||||
return info
|
||||
elseif code == 0x00 and info then
|
||||
return info
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 4, limit)
|
||||
end
|
||||
return info
|
||||
end
|
||||
|
||||
-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0
|
||||
function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number)
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
local count = 0
|
||||
while p and count < 32 do
|
||||
count += 1
|
||||
if p + 5 < limit and readu8(b, p + 3) == 0x00 then
|
||||
local x = readu8(b, p + 4) * 256 + readu8(b, p + 5)
|
||||
return (x // 8) % 8, x // 64
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 4, limit)
|
||||
end
|
||||
return 0, 0
|
||||
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
|
||||
function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
|
||||
local out: { Picture } = {}
|
||||
local unitStart: number? = nil
|
||||
local seq, gop = false, false
|
||||
local cur: Picture? = nil
|
||||
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
|
||||
-- a sequence / GOP header or a picture after a picture closes it
|
||||
if cur and (code ~= 0xB7) then
|
||||
cur.size = p - cur.offset
|
||||
table.insert(out, cur)
|
||||
cur = nil
|
||||
end
|
||||
if code == 0xB3 then
|
||||
unitStart = unitStart or p
|
||||
seq = true
|
||||
elseif code == 0xB8 then
|
||||
unitStart = unitStart or p
|
||||
gop = true
|
||||
elseif code == 0x00 then
|
||||
local t, tr = 0, 0
|
||||
if p + 5 < limit then
|
||||
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 }
|
||||
unitStart, seq, gop = nil, false, false
|
||||
elseif code == 0xB7 and cur then
|
||||
cur.size = p + 4 - cur.offset
|
||||
table.insert(out, cur)
|
||||
cur = nil
|
||||
end
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 4, limit)
|
||||
end
|
||||
if cur then
|
||||
cur.size = limit - cur.offset
|
||||
table.insert(out, cur)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5)
|
||||
function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
local count = 0
|
||||
while p and count < 64 do
|
||||
count += 1
|
||||
if p + 3 < limit then
|
||||
local t = readu8(b, p + 3) % 32
|
||||
if t == 5 then
|
||||
return true
|
||||
elseif t == 1 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 3, limit)
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
return MpegEs
|
||||
@@ -0,0 +1,224 @@
|
||||
--!strict
|
||||
-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams:
|
||||
-- .mpg / .mpeg / .vob). New in formats-luau. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program
|
||||
-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private
|
||||
-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts,
|
||||
-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync).
|
||||
--
|
||||
-- local ps, err = MpegPs.read(buf, base, limit)
|
||||
-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or
|
||||
-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance
|
||||
--
|
||||
-- Never throws: malformed packets are skipped and counted in ps.errors.
|
||||
local Err = require("@formats/core/Err")
|
||||
local MpegEs = require("@formats/containers/MpegEs")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local MpegPs = {}
|
||||
|
||||
export type Pes = { pts: number?, dts: number?, offset: number, size: number }
|
||||
export type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } }
|
||||
export type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number }
|
||||
|
||||
local WRAP = 8589934592 -- 2^33
|
||||
|
||||
-- PSM stream_type -> kind, codec
|
||||
local TYPES: { [number]: { string } } = {
|
||||
[0x01] = { "video", "mpeg1" },
|
||||
[0x02] = { "video", "mpeg2" },
|
||||
[0x03] = { "audio", "mp2" },
|
||||
[0x04] = { "audio", "mp2" },
|
||||
[0x0F] = { "audio", "aac" },
|
||||
[0x10] = { "video", "mpeg4" },
|
||||
[0x1B] = { "video", "h264" },
|
||||
[0x24] = { "video", "hevc" },
|
||||
[0x81] = { "audio", "ac3" },
|
||||
}
|
||||
|
||||
local function ts(b: buffer, p: number): number
|
||||
local a = readu8(b, p)
|
||||
local v = (a // 2) % 8
|
||||
v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2
|
||||
v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2
|
||||
return v
|
||||
end
|
||||
|
||||
-- read(buf, base, limit) -> File | nil, Err
|
||||
function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
|
||||
local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 }
|
||||
local types: { [number]: number } = {}
|
||||
local last: { [number]: number } = {}
|
||||
local wrap: { [number]: number } = {}
|
||||
local packs = 0
|
||||
local p = MpegEs.findStart(b, base, limit)
|
||||
local function unwrap(id: number, v: number): number
|
||||
local off = wrap[id] or 0
|
||||
local prev = last[id]
|
||||
local t = v + off
|
||||
if prev and t < prev - WRAP / 2 then
|
||||
off += WRAP
|
||||
wrap[id] = off
|
||||
t = v + off
|
||||
end
|
||||
last[id] = t
|
||||
return t
|
||||
end
|
||||
while p do
|
||||
if p + 4 > limit then
|
||||
break
|
||||
end
|
||||
local code = readu8(b, p + 3)
|
||||
local nextP = p + 4
|
||||
if code == 0xBA then
|
||||
packs += 1
|
||||
if p + 5 > limit then
|
||||
break
|
||||
end
|
||||
local m = readu8(b, p + 4)
|
||||
if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing
|
||||
file.mpeg2 = true
|
||||
if p + 14 > limit then
|
||||
break
|
||||
end
|
||||
nextP = p + 14 + readu8(b, p + 13) % 8
|
||||
else
|
||||
nextP = p + 12
|
||||
end
|
||||
elseif code == 0xB9 then
|
||||
nextP = p + 4
|
||||
elseif code >= 0xBB then
|
||||
if p + 6 > limit then
|
||||
break
|
||||
end
|
||||
local len = readu8(b, p + 4) * 256 + readu8(b, p + 5)
|
||||
local stop = p + 6 + len
|
||||
if stop > limit then
|
||||
stop = limit
|
||||
end
|
||||
nextP = stop
|
||||
if code == 0xBC and len >= 10 then -- program stream map
|
||||
local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9)
|
||||
local q = p + 10 + infoLen
|
||||
if q + 2 <= stop then
|
||||
local mapLen = readu8(b, q) * 256 + readu8(b, q + 1)
|
||||
q += 2
|
||||
local e = math.min(stop, q + mapLen)
|
||||
while q + 4 <= e do
|
||||
local st, sid = readu8(b, q), readu8(b, q + 1)
|
||||
local il = readu8(b, q + 2) * 256 + readu8(b, q + 3)
|
||||
types[sid] = st
|
||||
q += 4 + il
|
||||
end
|
||||
end
|
||||
elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then
|
||||
-- a PES packet
|
||||
local q = p + 6
|
||||
local pts, dts: number? = nil, nil
|
||||
local ok = true
|
||||
if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header
|
||||
if q + 3 > stop then
|
||||
ok = false
|
||||
else
|
||||
local flags = readu8(b, q + 1)
|
||||
local hlen = readu8(b, q + 2)
|
||||
local h = q + 3
|
||||
if flags >= 0x80 and h + 5 <= stop then
|
||||
pts = ts(b, h)
|
||||
if flags // 64 == 3 and h + 10 <= stop then
|
||||
dts = ts(b, h + 5)
|
||||
end
|
||||
end
|
||||
q = h + hlen
|
||||
end
|
||||
else -- MPEG-1 packet header
|
||||
local n = 0
|
||||
while q < stop and readu8(b, q) == 0xFF and n < 16 do
|
||||
q += 1
|
||||
n += 1
|
||||
end
|
||||
if q < stop and readu8(b, q) // 64 == 1 then
|
||||
q += 2
|
||||
end
|
||||
if q < stop then
|
||||
local c = readu8(b, q) // 16
|
||||
if c == 2 and q + 5 <= stop then
|
||||
pts = ts(b, q)
|
||||
q += 5
|
||||
elseif c == 3 and q + 10 <= stop then
|
||||
pts = ts(b, q)
|
||||
dts = ts(b, q + 5)
|
||||
q += 10
|
||||
elseif readu8(b, q) == 0x0F then
|
||||
q += 1
|
||||
else
|
||||
ok = false
|
||||
end
|
||||
end
|
||||
end
|
||||
if ok and q <= stop then
|
||||
local id = code
|
||||
local kind, codec = "other", "unknown"
|
||||
if code == 0xBD then
|
||||
if q >= stop then
|
||||
ok = false
|
||||
else
|
||||
local sub = readu8(b, q)
|
||||
id = 0xBD00 + sub
|
||||
if sub >= 0x80 and sub <= 0x87 then
|
||||
kind, codec = "audio", "ac3"
|
||||
q += 4
|
||||
elseif sub >= 0x88 and sub <= 0x8F then
|
||||
kind, codec = "audio", "dts"
|
||||
q += 4
|
||||
elseif sub >= 0xA0 and sub <= 0xA7 then
|
||||
kind, codec = "audio", "pcm_dvd"
|
||||
q += 7
|
||||
elseif sub >= 0x20 and sub <= 0x3F then
|
||||
kind, codec = "subtitle", "dvdsub"
|
||||
q += 1
|
||||
else
|
||||
q += 1
|
||||
end
|
||||
end
|
||||
elseif code >= 0xE0 then
|
||||
kind, codec = "video", "mpeg1"
|
||||
else
|
||||
kind, codec = "audio", "mp2"
|
||||
end
|
||||
local st = types[code]
|
||||
if st and TYPES[st] then
|
||||
kind, codec = TYPES[st][1], TYPES[st][2]
|
||||
end
|
||||
if ok and q <= stop then
|
||||
local s = file.streams[id]
|
||||
if not s then
|
||||
s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} }
|
||||
file.streams[id] = s
|
||||
table.insert(file.order, id)
|
||||
end
|
||||
table.insert(s.pes, {
|
||||
pts = if pts then unwrap(id, pts) else nil,
|
||||
dts = if dts then unwrap(id + 0x10000, dts) else nil,
|
||||
offset = q,
|
||||
size = stop - q,
|
||||
})
|
||||
end
|
||||
end
|
||||
if not ok then
|
||||
file.errors += 1
|
||||
end
|
||||
end
|
||||
else
|
||||
-- a start code that is not a system one (stray ES data between packets): resync
|
||||
file.errors += 1
|
||||
end
|
||||
p = MpegEs.findStart(b, nextP, limit)
|
||||
end
|
||||
if packs == 0 and #file.order == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base)
|
||||
end
|
||||
return file, nil
|
||||
end
|
||||
|
||||
return MpegPs
|
||||
@@ -0,0 +1,831 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same
|
||||
-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a
|
||||
-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections
|
||||
-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity
|
||||
-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS.
|
||||
--
|
||||
-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... }
|
||||
-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed
|
||||
--
|
||||
-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is
|
||||
-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised.
|
||||
|
||||
local MpegTs = {}
|
||||
|
||||
export type Stream = {
|
||||
pid: number,
|
||||
streamType: number, -- PMT stream_type (0 when the stream was found without a PMT)
|
||||
kind: string, -- "video" | "audio" | "other"
|
||||
codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ...
|
||||
program: number, -- program_number (0 without a PMT)
|
||||
language: string?, -- ISO 639 language descriptor, when present
|
||||
}
|
||||
|
||||
export type Unit = {
|
||||
pid: number,
|
||||
kind: string,
|
||||
codec: string,
|
||||
streamType: number,
|
||||
streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio)
|
||||
pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID)
|
||||
dts: number?, -- seconds; equals pts when the PES carries no DTS
|
||||
pts90: number?, -- the same in 90 kHz ticks
|
||||
dts90: number?,
|
||||
data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio)
|
||||
ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit
|
||||
randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set
|
||||
discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set
|
||||
}
|
||||
|
||||
export type Stats = {
|
||||
packets: number,
|
||||
syncLosses: number, -- resyncs (bytes skipped to find 0x47 again)
|
||||
skippedBytes: number,
|
||||
teiErrors: number, -- transport_error_indicator packets (dropped)
|
||||
ccErrors: number, -- continuity counter gaps
|
||||
duplicates: number, -- duplicate packets (same CC), dropped
|
||||
crcErrors: number, -- PSI sections with a bad CRC (ignored)
|
||||
pesErrors: number, -- PES units without a valid header (dropped)
|
||||
scrambled: number, -- scrambled packets (dropped)
|
||||
pcr: number?, -- last PCR seen, seconds
|
||||
}
|
||||
|
||||
export type Demuxed = {
|
||||
video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order
|
||||
audio: { Unit }, -- units of the selected audio PID
|
||||
streams: { Stream }, -- every elementary stream, PMT order
|
||||
units: { Unit }, -- every unit of every PID, in completion order
|
||||
videoPid: number?,
|
||||
audioPid: number?,
|
||||
stats: Stats,
|
||||
}
|
||||
|
||||
type PesState = {
|
||||
buf: buffer,
|
||||
len: number,
|
||||
active: boolean,
|
||||
expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start)
|
||||
hdrChecked: boolean,
|
||||
ccError: boolean,
|
||||
randomAccess: boolean,
|
||||
discontinuity: boolean,
|
||||
lastPts: number, -- for 33-bit wrap unwrapping
|
||||
wrapOffset: number,
|
||||
}
|
||||
|
||||
type SectionState = { buf: buffer, len: number, active: boolean }
|
||||
|
||||
local TS_SIZE = 188
|
||||
local SYNC = 0x47
|
||||
local MAX_SECTION = 4096 + 188
|
||||
local WRAP = 8589934592 -- 2^33
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local band = bit32.band
|
||||
local bor = bit32.bor
|
||||
local lshift = bit32.lshift
|
||||
local rshift = bit32.rshift
|
||||
|
||||
local CODECS: { [number]: { string } } = {
|
||||
[0x01] = { "video", "mpeg1video" },
|
||||
[0x02] = { "video", "mpeg2video" },
|
||||
[0x03] = { "audio", "mpegaudio" },
|
||||
[0x04] = { "audio", "mpegaudio" },
|
||||
[0x0F] = { "audio", "aac" },
|
||||
[0x10] = { "video", "mpeg4" },
|
||||
[0x11] = { "audio", "aac_latm" },
|
||||
[0x1B] = { "video", "h264" },
|
||||
[0x24] = { "video", "hevc" },
|
||||
[0x81] = { "audio", "ac3" },
|
||||
[0x87] = { "audio", "eac3" },
|
||||
}
|
||||
|
||||
-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0
|
||||
local CRC = buffer.create(256 * 4)
|
||||
for i = 0, 255 do
|
||||
local c = lshift(i, 24)
|
||||
for _ = 1, 8 do
|
||||
if band(c, 0x80000000) ~= 0 then
|
||||
c = bit32.bxor(lshift(c, 1), 0x04C11DB7)
|
||||
else
|
||||
c = lshift(c, 1)
|
||||
end
|
||||
end
|
||||
buffer.writeu32(CRC, i * 4, c)
|
||||
end
|
||||
|
||||
local function crc32(b: buffer, off: number, n: number): number
|
||||
local c = 0xFFFFFFFF
|
||||
for i = off, off + n - 1 do
|
||||
c = bit32.bxor(lshift(c, 8), buffer.readu32(CRC, band(bit32.bxor(rshift(c, 24), readu8(b, i)), 255) * 4))
|
||||
end
|
||||
return c
|
||||
end
|
||||
MpegTs.crc32 = crc32
|
||||
|
||||
local function u16(b: buffer, p: number): number
|
||||
return readu8(b, p) * 256 + readu8(b, p + 1)
|
||||
end
|
||||
|
||||
-- 33-bit timestamp from the 5-byte PES encoding at p
|
||||
local function readTs(b: buffer, p: number): number
|
||||
local b0 = readu8(b, p)
|
||||
local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30
|
||||
local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15
|
||||
local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0
|
||||
return hi + mid * 32768 + lo
|
||||
end
|
||||
|
||||
local Demuxer = {}
|
||||
Demuxer.__index = Demuxer
|
||||
|
||||
export type Demuxer = typeof(setmetatable(
|
||||
{} :: {
|
||||
_pend: buffer,
|
||||
_pendLen: number,
|
||||
_pmtPids: { [number]: number },
|
||||
_streams: { [number]: Stream },
|
||||
_pes: { [number]: PesState },
|
||||
_sections: { [number]: SectionState },
|
||||
_cc: { [number]: number },
|
||||
_queue: { Unit },
|
||||
_qhead: number,
|
||||
_qtail: number,
|
||||
streams: { Stream },
|
||||
stats: Stats,
|
||||
},
|
||||
Demuxer
|
||||
))
|
||||
|
||||
function MpegTs.new(): Demuxer
|
||||
local self = setmetatable({
|
||||
_pend = buffer.create(64 * 1024),
|
||||
_pendLen = 0,
|
||||
_pmtPids = {},
|
||||
_streams = {},
|
||||
_pes = {},
|
||||
_sections = {},
|
||||
_cc = {},
|
||||
_queue = {},
|
||||
_qhead = 1,
|
||||
_qtail = 0,
|
||||
streams = {},
|
||||
stats = {
|
||||
packets = 0,
|
||||
syncLosses = 0,
|
||||
skippedBytes = 0,
|
||||
teiErrors = 0,
|
||||
ccErrors = 0,
|
||||
duplicates = 0,
|
||||
crcErrors = 0,
|
||||
pesErrors = 0,
|
||||
scrambled = 0,
|
||||
pcr = nil,
|
||||
} :: Stats,
|
||||
}, Demuxer)
|
||||
return self
|
||||
end
|
||||
|
||||
-- PSI ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?)
|
||||
local info = CODECS[streamType]
|
||||
local s = self._streams[pid]
|
||||
if s == nil then
|
||||
s = {
|
||||
pid = pid,
|
||||
streamType = streamType,
|
||||
kind = if info then info[1] else "other",
|
||||
codec = if info then info[2] else "unknown",
|
||||
program = program,
|
||||
language = language,
|
||||
}
|
||||
self._streams[pid] = s
|
||||
table.insert(self.streams, s)
|
||||
else
|
||||
s.streamType = streamType
|
||||
s.kind = if info then info[1] else "other"
|
||||
s.codec = if info then info[2] else "unknown"
|
||||
s.program = program
|
||||
s.language = language
|
||||
end
|
||||
end
|
||||
|
||||
local function parseSection(self: Demuxer, pid: number, b: buffer, n: number)
|
||||
-- n >= 3 bytes: table_id, section_length (n = 3 + section_length)
|
||||
if n < 12 then
|
||||
return
|
||||
end
|
||||
if band(readu8(b, 1), 0x80) == 0 then
|
||||
return -- no section_syntax_indicator: not a PAT / PMT
|
||||
end
|
||||
if crc32(b, 0, n) ~= 0 then
|
||||
self.stats.crcErrors += 1
|
||||
return
|
||||
end
|
||||
if band(readu8(b, 5), 1) == 0 then
|
||||
return -- current_next_indicator = 0: a future table
|
||||
end
|
||||
local tid = readu8(b, 0)
|
||||
local stop = n - 4
|
||||
if tid == 0x00 and pid == 0 then
|
||||
local p = 8
|
||||
while p + 4 <= stop do
|
||||
local prog = u16(b, p)
|
||||
local pmt = band(u16(b, p + 2), 0x1FFF)
|
||||
if prog ~= 0 then
|
||||
self._pmtPids[pmt] = prog
|
||||
end
|
||||
p += 4
|
||||
end
|
||||
elseif tid == 0x02 and self._pmtPids[pid] ~= nil then
|
||||
local program = u16(b, 3)
|
||||
local p = 12 + band(u16(b, 10), 0x0FFF)
|
||||
while p + 5 <= stop do
|
||||
local st = readu8(b, p)
|
||||
local epid = band(u16(b, p + 1), 0x1FFF)
|
||||
local esl = band(u16(b, p + 3), 0x0FFF)
|
||||
local d = p + 5
|
||||
local dend = math.min(d + esl, stop)
|
||||
local language: string? = nil
|
||||
while d + 2 <= dend do
|
||||
local tag, len = readu8(b, d), readu8(b, d + 1)
|
||||
if tag == 0x0A and len >= 3 and d + 5 <= dend then
|
||||
language = buffer.readstring(b, d + 2, 3)
|
||||
end
|
||||
d += 2 + len
|
||||
end
|
||||
addStream(self, epid, st, program, language)
|
||||
p += 5 + esl
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number)
|
||||
local n = to - from
|
||||
if n <= 0 then
|
||||
return
|
||||
end
|
||||
if s.len + n > MAX_SECTION then
|
||||
s.active = false
|
||||
s.len = 0
|
||||
return
|
||||
end
|
||||
buffer.copy(s.buf, s.len, src, from, n)
|
||||
s.len += n
|
||||
-- every complete section in the buffer
|
||||
while s.active and s.len >= 3 do
|
||||
if readu8(s.buf, 0) == 0xFF then
|
||||
s.active = false -- stuffing: no more sections until the next unit start
|
||||
s.len = 0
|
||||
return
|
||||
end
|
||||
local need = 3 + band(u16(s.buf, 1), 0x0FFF)
|
||||
if s.len < need then
|
||||
return
|
||||
end
|
||||
parseSection(self, pid, s.buf, need)
|
||||
local rest = s.len - need
|
||||
if rest > 0 then
|
||||
buffer.copy(s.buf, 0, s.buf, need, rest)
|
||||
end
|
||||
s.len = rest
|
||||
end
|
||||
end
|
||||
|
||||
local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number)
|
||||
local s = self._sections[pid]
|
||||
if s == nil then
|
||||
s = { buf = buffer.create(MAX_SECTION), len = 0, active = false }
|
||||
self._sections[pid] = s
|
||||
end
|
||||
if pusi then
|
||||
if pos >= stop then
|
||||
return
|
||||
end
|
||||
local ptr = readu8(b, pos)
|
||||
pos += 1
|
||||
local tail = math.min(pos + ptr, stop)
|
||||
if s.active then
|
||||
sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section
|
||||
end
|
||||
s.active = true
|
||||
s.len = 0
|
||||
pos = tail
|
||||
elseif not s.active then
|
||||
return
|
||||
end
|
||||
sectionBytes(self, pid, s, b, pos, stop)
|
||||
end
|
||||
|
||||
-- PES ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
local function completePes(self: Demuxer, pid: number, st: PesState)
|
||||
st.active = false
|
||||
local b, len = st.buf, st.len
|
||||
if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
local sid = readu8(b, 3)
|
||||
local stop = if st.expected > 0 then math.min(st.expected, len) else len
|
||||
local start = 6
|
||||
local pts: number?, dts: number? = nil, nil
|
||||
if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then
|
||||
if stop < 9 then
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
if band(readu8(b, 6), 0xC0) == 0x80 then
|
||||
-- MPEG-2 PES header
|
||||
local flags = readu8(b, 7)
|
||||
local hl = readu8(b, 8)
|
||||
start = 9 + hl
|
||||
if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then
|
||||
pts = readTs(b, 9)
|
||||
if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then
|
||||
dts = readTs(b, 14)
|
||||
end
|
||||
end
|
||||
else
|
||||
-- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS
|
||||
local p = 6
|
||||
local k = 0
|
||||
while p < stop and readu8(b, p) == 0xFF and k < 16 do
|
||||
p += 1
|
||||
k += 1
|
||||
end
|
||||
if p < stop and band(readu8(b, p), 0xC0) == 0x40 then
|
||||
p += 2
|
||||
end
|
||||
if p < stop then
|
||||
local c = band(readu8(b, p), 0xF0)
|
||||
if c == 0x20 and p + 5 <= stop then
|
||||
pts = readTs(b, p)
|
||||
p += 5
|
||||
elseif c == 0x30 and p + 10 <= stop then
|
||||
pts = readTs(b, p)
|
||||
dts = readTs(b, p + 5)
|
||||
p += 10
|
||||
else
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
start = p
|
||||
end
|
||||
end
|
||||
if start > stop then
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
-- unwrap the 33-bit clock (per PID)
|
||||
if pts ~= nil then
|
||||
pts += st.wrapOffset
|
||||
if st.lastPts >= 0 then
|
||||
if pts < st.lastPts - WRAP / 2 then
|
||||
st.wrapOffset += WRAP
|
||||
pts += WRAP
|
||||
elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then
|
||||
st.wrapOffset -= WRAP
|
||||
pts -= WRAP
|
||||
end
|
||||
end
|
||||
st.lastPts = pts
|
||||
if dts ~= nil then
|
||||
dts += st.wrapOffset
|
||||
if dts > pts + WRAP / 2 then
|
||||
dts -= WRAP
|
||||
elseif dts < pts - WRAP / 2 then
|
||||
dts += WRAP
|
||||
end
|
||||
else
|
||||
dts = pts
|
||||
end
|
||||
end
|
||||
local n = stop - start
|
||||
local data = buffer.create(n)
|
||||
if n > 0 then
|
||||
buffer.copy(data, 0, b, start, n)
|
||||
end
|
||||
local s = self._streams[pid]
|
||||
local kind, codec, streamType
|
||||
if s then
|
||||
kind, codec, streamType = s.kind, s.codec, s.streamType
|
||||
elseif sid >= 0xE0 and sid <= 0xEF then
|
||||
kind, codec, streamType = "video", "unknown", 0
|
||||
elseif sid >= 0xC0 and sid <= 0xDF then
|
||||
kind, codec, streamType = "audio", "mpegaudio", 0
|
||||
else
|
||||
kind, codec, streamType = "other", "unknown", 0
|
||||
end
|
||||
local unit: Unit = {
|
||||
pid = pid,
|
||||
kind = kind,
|
||||
codec = codec,
|
||||
streamType = streamType,
|
||||
streamId = sid,
|
||||
pts = if pts then pts / 90000 else nil,
|
||||
dts = if dts then dts / 90000 else nil,
|
||||
pts90 = pts,
|
||||
dts90 = dts,
|
||||
data = data,
|
||||
ccError = st.ccError,
|
||||
randomAccess = st.randomAccess,
|
||||
discontinuity = st.discontinuity,
|
||||
}
|
||||
local tail = self._qtail + 1
|
||||
self._qtail = tail
|
||||
self._queue[tail] = unit
|
||||
end
|
||||
|
||||
local function pesPayload(
|
||||
self: Demuxer,
|
||||
pid: number,
|
||||
pusi: boolean,
|
||||
b: buffer,
|
||||
pos: number,
|
||||
stop: number,
|
||||
ccError: boolean,
|
||||
randomAccess: boolean,
|
||||
discontinuity: boolean
|
||||
)
|
||||
local st = self._pes[pid]
|
||||
-- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored
|
||||
local startCode = pusi
|
||||
and stop - pos >= 3
|
||||
and readu8(b, pos) == 0
|
||||
and readu8(b, pos + 1) == 0
|
||||
and readu8(b, pos + 2) == 1
|
||||
if st == nil then
|
||||
if not startCode then
|
||||
return
|
||||
end
|
||||
st = {
|
||||
buf = buffer.create(16 * 1024),
|
||||
len = 0,
|
||||
active = false,
|
||||
expected = 0,
|
||||
hdrChecked = false,
|
||||
ccError = false,
|
||||
randomAccess = false,
|
||||
discontinuity = false,
|
||||
lastPts = -1,
|
||||
wrapOffset = 0,
|
||||
}
|
||||
self._pes[pid] = st
|
||||
end
|
||||
if ccError and st.active then
|
||||
st.ccError = true -- packets of the unit in progress were lost
|
||||
end
|
||||
if pusi then
|
||||
if st.active then
|
||||
completePes(self, pid, st)
|
||||
end
|
||||
if not startCode then
|
||||
if self._streams[pid] ~= nil then
|
||||
self.stats.pesErrors += 1
|
||||
end
|
||||
return
|
||||
end
|
||||
st.active = true
|
||||
st.len = 0
|
||||
st.expected = 0
|
||||
st.hdrChecked = false
|
||||
st.ccError = false
|
||||
st.randomAccess = randomAccess
|
||||
st.discontinuity = discontinuity
|
||||
elseif not st.active then
|
||||
return
|
||||
end
|
||||
local n = stop - pos
|
||||
if n <= 0 then
|
||||
return
|
||||
end
|
||||
if st.len + n > buffer.len(st.buf) then
|
||||
local cap = buffer.len(st.buf) * 2
|
||||
while cap < st.len + n do
|
||||
cap *= 2
|
||||
end
|
||||
if cap > 64 * 1024 * 1024 then
|
||||
st.active = false -- runaway unit (no unit start for 64 MB): drop it
|
||||
st.len = 0
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
local nb = buffer.create(cap)
|
||||
buffer.copy(nb, 0, st.buf, 0, st.len)
|
||||
st.buf = nb
|
||||
end
|
||||
buffer.copy(st.buf, st.len, b, pos, n)
|
||||
st.len += n
|
||||
if not st.hdrChecked and st.len >= 6 then
|
||||
st.hdrChecked = true
|
||||
local plen = u16(st.buf, 4)
|
||||
if plen > 0 then
|
||||
st.expected = 6 + plen
|
||||
end
|
||||
end
|
||||
if st.expected > 0 and st.len >= st.expected then
|
||||
completePes(self, pid, st)
|
||||
end
|
||||
end
|
||||
|
||||
-- packets -----------------------------------------------------------------------------------------------------
|
||||
|
||||
local function packet(self: Demuxer, b: buffer, pk: number)
|
||||
local stats = self.stats
|
||||
stats.packets += 1
|
||||
local b1 = readu8(b, pk + 1)
|
||||
if band(b1, 0x80) ~= 0 then
|
||||
stats.teiErrors += 1
|
||||
return
|
||||
end
|
||||
local pusi = band(b1, 0x40) ~= 0
|
||||
local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2)
|
||||
if pid == 0x1FFF then
|
||||
return
|
||||
end
|
||||
local b3 = readu8(b, pk + 3)
|
||||
if band(b3, 0xC0) ~= 0 then
|
||||
stats.scrambled += 1
|
||||
return
|
||||
end
|
||||
local afc = band(rshift(b3, 4), 3)
|
||||
local cc = band(b3, 15)
|
||||
if afc == 0 then
|
||||
return
|
||||
end
|
||||
local pos = pk + 4
|
||||
local stop = pk + TS_SIZE
|
||||
local discontinuity, randomAccess = false, false
|
||||
if afc >= 2 then
|
||||
local afl = readu8(b, pos)
|
||||
pos += 1
|
||||
if afl > 183 then
|
||||
return
|
||||
end
|
||||
if afl > 0 then
|
||||
local flags = readu8(b, pos)
|
||||
discontinuity = band(flags, 0x80) ~= 0
|
||||
randomAccess = band(flags, 0x40) ~= 0
|
||||
if band(flags, 0x10) ~= 0 and afl >= 7 then
|
||||
local base = readu8(b, pos + 1) * 33554432
|
||||
+ readu8(b, pos + 2) * 131072
|
||||
+ readu8(b, pos + 3) * 512
|
||||
+ readu8(b, pos + 4) * 2
|
||||
+ rshift(readu8(b, pos + 5), 7)
|
||||
local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6)
|
||||
stats.pcr = base / 90000 + ext / 27000000
|
||||
end
|
||||
end
|
||||
pos += afl
|
||||
if afc == 2 then
|
||||
if discontinuity then
|
||||
self._cc[pid] = nil
|
||||
end
|
||||
return -- adaptation field only: the counter does not advance
|
||||
end
|
||||
end
|
||||
-- continuity counter
|
||||
local ccError = false
|
||||
local last = self._cc[pid]
|
||||
if last ~= nil and not discontinuity then
|
||||
if cc == last then
|
||||
stats.duplicates += 1
|
||||
return
|
||||
elseif cc ~= band(last + 1, 15) then
|
||||
ccError = true
|
||||
stats.ccErrors += 1
|
||||
end
|
||||
end
|
||||
self._cc[pid] = cc
|
||||
if pid == 0 or self._pmtPids[pid] ~= nil then
|
||||
sectionPayload(self, pid, pusi, b, pos, stop)
|
||||
elseif pid >= 0x10 then
|
||||
pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity)
|
||||
end
|
||||
end
|
||||
|
||||
-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for
|
||||
-- pull(). Returns false for a bad argument.
|
||||
function Demuxer.push(self: Demuxer, data: buffer | string, 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 off = math.max(0, math.floor(offset or 0))
|
||||
local total = buffer.len(src)
|
||||
if off > total then
|
||||
return false
|
||||
end
|
||||
local n = math.min(math.floor(len or (total - off)), total - off)
|
||||
if n < 0 then
|
||||
return false
|
||||
end
|
||||
-- append to the pending bytes
|
||||
local need = self._pendLen + n
|
||||
if need > buffer.len(self._pend) then
|
||||
local cap = buffer.len(self._pend)
|
||||
while cap < need do
|
||||
cap *= 2
|
||||
end
|
||||
local nb = buffer.create(cap)
|
||||
buffer.copy(nb, 0, self._pend, 0, self._pendLen)
|
||||
self._pend = nb
|
||||
end
|
||||
if n > 0 then
|
||||
buffer.copy(self._pend, self._pendLen, src, off, n)
|
||||
end
|
||||
self._pendLen = need
|
||||
local b, avail = self._pend, self._pendLen
|
||||
local p = 0
|
||||
while p + TS_SIZE <= avail do
|
||||
if readu8(b, p) ~= SYNC then
|
||||
-- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data)
|
||||
self.stats.syncLosses += 1
|
||||
local q = p + 1
|
||||
local found = -1
|
||||
local waitAt = -1
|
||||
while q < avail do
|
||||
if readu8(b, q) == SYNC then
|
||||
if q + TS_SIZE < avail then
|
||||
if readu8(b, q + TS_SIZE) == SYNC then
|
||||
found = q
|
||||
break
|
||||
end
|
||||
elseif q + TS_SIZE == avail then
|
||||
found = q
|
||||
break
|
||||
else
|
||||
waitAt = q -- not enough bytes to confirm: wait for more
|
||||
break
|
||||
end
|
||||
end
|
||||
q += 1
|
||||
end
|
||||
if found >= 0 then
|
||||
self.stats.skippedBytes += found - p
|
||||
p = found
|
||||
elseif waitAt >= 0 then
|
||||
self.stats.skippedBytes += waitAt - p
|
||||
p = waitAt
|
||||
break
|
||||
else
|
||||
self.stats.skippedBytes += avail - p
|
||||
p = avail
|
||||
break
|
||||
end
|
||||
else
|
||||
packet(self, b, p)
|
||||
p += TS_SIZE
|
||||
end
|
||||
end
|
||||
local rest = avail - p
|
||||
if rest > 0 and p > 0 then
|
||||
buffer.copy(b, 0, b, p, rest)
|
||||
end
|
||||
self._pendLen = rest
|
||||
return true
|
||||
end
|
||||
|
||||
-- The next completed unit (any PID), or nil.
|
||||
function Demuxer.pull(self: Demuxer): Unit?
|
||||
local q = self._queue
|
||||
local h = self._qhead
|
||||
local u = q[h]
|
||||
if u == nil then
|
||||
return nil
|
||||
end
|
||||
q[h] = nil :: any
|
||||
h += 1
|
||||
if h > self._qtail then
|
||||
table.clear(q)
|
||||
h = 1
|
||||
self._qtail = 0
|
||||
end
|
||||
self._qhead = h
|
||||
return u
|
||||
end
|
||||
|
||||
-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next
|
||||
-- unit start). Units still queue up for pull().
|
||||
function Demuxer.flush(self: Demuxer)
|
||||
local pids = {}
|
||||
for pid, st in self._pes do
|
||||
if st.active then
|
||||
table.insert(pids, pid)
|
||||
end
|
||||
end
|
||||
table.sort(pids)
|
||||
for _, pid in pids do
|
||||
completePes(self, pid, self._pes[pid])
|
||||
end
|
||||
self._pendLen = 0
|
||||
end
|
||||
|
||||
-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek).
|
||||
function Demuxer.reset(self: Demuxer)
|
||||
self._pendLen = 0
|
||||
for _, st in self._pes do
|
||||
st.active = false
|
||||
st.len = 0
|
||||
st.lastPts = -1
|
||||
st.wrapOffset = 0
|
||||
end
|
||||
for _, s in self._sections do
|
||||
s.active = false
|
||||
s.len = 0
|
||||
end
|
||||
table.clear(self._cc)
|
||||
table.clear(self._queue)
|
||||
self._qhead = 1
|
||||
self._qtail = 0
|
||||
end
|
||||
|
||||
-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT).
|
||||
function Demuxer.streamFor(self: Demuxer, kind: string): Stream?
|
||||
for _, s in self.streams do
|
||||
if s.kind == kind then
|
||||
return s
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
export type DemuxOptions = { videoPid: number?, audioPid: number? }
|
||||
|
||||
-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid /
|
||||
-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video /
|
||||
-- audio (PES stream_id). Never throws; a bad argument gives empty lists.
|
||||
function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
|
||||
local d = MpegTs.new()
|
||||
d:push(data)
|
||||
d:flush()
|
||||
local units = {}
|
||||
while true do
|
||||
local u = d:pull()
|
||||
if u == nil then
|
||||
break
|
||||
end
|
||||
table.insert(units, u)
|
||||
end
|
||||
local videoPid = opts and opts.videoPid
|
||||
local audioPid = opts and opts.audioPid
|
||||
if videoPid == nil then
|
||||
local s = d:streamFor("video")
|
||||
videoPid = if s then s.pid else nil
|
||||
end
|
||||
if audioPid == nil then
|
||||
local s = d:streamFor("audio")
|
||||
audioPid = if s then s.pid else nil
|
||||
end
|
||||
for _, u in units do
|
||||
if videoPid == nil and u.kind == "video" then
|
||||
videoPid = u.pid
|
||||
end
|
||||
if audioPid == nil and u.kind == "audio" then
|
||||
audioPid = u.pid
|
||||
end
|
||||
end
|
||||
local video, audio = {}, {}
|
||||
for _, u in units do
|
||||
if u.pid == videoPid then
|
||||
table.insert(video, u)
|
||||
elseif u.pid == audioPid then
|
||||
table.insert(audio, u)
|
||||
end
|
||||
end
|
||||
return {
|
||||
video = video,
|
||||
audio = audio,
|
||||
streams = d.streams,
|
||||
units = units,
|
||||
videoPid = videoPid,
|
||||
audioPid = audioPid,
|
||||
stats = d.stats,
|
||||
}
|
||||
end
|
||||
|
||||
-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open).
|
||||
function MpegTs.concat(units: { Unit }): buffer
|
||||
local n = 0
|
||||
for _, u in units do
|
||||
n += buffer.len(u.data)
|
||||
end
|
||||
local out = buffer.create(n)
|
||||
local p = 0
|
||||
for _, u in units do
|
||||
local l = buffer.len(u.data)
|
||||
buffer.copy(out, p, u.data, 0, l)
|
||||
p += l
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return MpegTs
|
||||
@@ -1,7 +1,10 @@
|
||||
--!strict
|
||||
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs,
|
||||
-- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta
|
||||
-- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
|
||||
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG
|
||||
-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical
|
||||
-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the
|
||||
-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi
|
||||
-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images
|
||||
-- (coded 4:2:0 from the planes as they are).
|
||||
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
|
||||
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
|
||||
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
|
||||
@@ -17,8 +20,7 @@
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/image/jpeg/Decode")
|
||||
local Encode = require("@formats/image/jpeg/Encode")
|
||||
local Codec = require("@formats/codecs/Jpeg")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Jpeg = {
|
||||
@@ -26,7 +28,7 @@ local Jpeg = {
|
||||
category = "image",
|
||||
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
||||
mime = { "image/jpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
|
||||
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
|
||||
}
|
||||
|
||||
@@ -48,22 +50,7 @@ export type EncodeOptions = {
|
||||
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
|
||||
}
|
||||
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
components: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
precision: number,
|
||||
colorSpace: string,
|
||||
sampling: { { number } }, -- { h, v } per component
|
||||
orientation: number,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
|
||||
export type Info = Codec.Info
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Jpeg.sniff(r: Bytes.Reader): number
|
||||
@@ -72,214 +59,91 @@ function Jpeg.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
|
||||
local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, opts, headerOnly)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
|
||||
end
|
||||
if not st then
|
||||
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed")
|
||||
end
|
||||
return st, nil
|
||||
end
|
||||
|
||||
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
|
||||
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local st, err = parse(r, nil, true)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local f = st.frame
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
return {
|
||||
width = f.width,
|
||||
height = f.height,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
precision = f.precision,
|
||||
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
|
||||
sampling = sampling,
|
||||
orientation = st.orientation,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
|
||||
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
|
||||
if o <= 1 or o > 8 then
|
||||
return px, w, h
|
||||
end
|
||||
local swap = o >= 5
|
||||
local ow, oh = if swap then h else w, if swap then w else h
|
||||
local out = buffer.create(ow * oh * 4)
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
for y = 0, oh - 1 do
|
||||
for x = 0, ow - 1 do
|
||||
local col, row
|
||||
if o == 2 then
|
||||
col, row = w - 1 - x, y
|
||||
elseif o == 3 then
|
||||
col, row = w - 1 - x, h - 1 - y
|
||||
elseif o == 4 then
|
||||
col, row = x, h - 1 - y
|
||||
elseif o == 5 then
|
||||
col, row = y, x
|
||||
elseif o == 6 then
|
||||
col, row = y, h - 1 - x
|
||||
elseif o == 7 then
|
||||
col, row = w - 1 - y, h - 1 - x
|
||||
else
|
||||
col, row = w - 1 - y, x
|
||||
end
|
||||
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
|
||||
end
|
||||
end
|
||||
return out, ow, oh
|
||||
return Codec.info(r.buf, r.base, r.limit - r.base)
|
||||
end
|
||||
|
||||
function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local st, err = parse(r, opts, false)
|
||||
if not st then
|
||||
return nil, err
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if not w then
|
||||
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px))
|
||||
end
|
||||
local orientation = st.orientation
|
||||
if opts and opts.orient then
|
||||
px, w, h = orient(px, w, h, orientation)
|
||||
end
|
||||
local img = Types.Image.new(1, 1)
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
if opts and opts.native and space == "gray" then
|
||||
local g = buffer.create(w * h)
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
|
||||
end
|
||||
img.pixels, img.format = g, "gray8"
|
||||
end
|
||||
local f = st.frame
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
img.meta.orientation = orientation
|
||||
img.meta.oriented = (opts and opts.orient) or false
|
||||
img.meta.exif = st.exif
|
||||
img.meta.icc = st.icc
|
||||
if #st.comments > 0 then
|
||||
img.meta.text = { comment = table.concat(st.comments, "\n") }
|
||||
end
|
||||
if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then
|
||||
local k = if st.density.unit == 2 then 2.54 else 1
|
||||
img.meta.dpi = { x = st.density.x * k, y = st.density.y * k }
|
||||
end
|
||||
img.meta.truncated = st.truncated
|
||||
img.meta.source = {
|
||||
format = "jpeg",
|
||||
bitDepth = f.precision,
|
||||
colorType = space,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
sampling = sampling,
|
||||
scale = st.scale,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
}
|
||||
return img, nil
|
||||
local o = opts or {} :: DecodeOptions
|
||||
-- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF)
|
||||
return Codec.decode(r.buf, r.base, r.limit - r.base, {
|
||||
scale = o.scale,
|
||||
orient = o.orient,
|
||||
native = o.native,
|
||||
maxPixels = o.maxPixels,
|
||||
fields = false,
|
||||
})
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 }
|
||||
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local bpp = BPP[img.format]
|
||||
if not bpp then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image (got " .. tostring(img.format) .. ")")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local quality = o.quality or 90
|
||||
if type(quality) ~= "number" or quality < 1 or quality > 100 then
|
||||
return nil, Err.new(Err.ARG, "quality must be 1..100")
|
||||
end
|
||||
local sub = o.subsampling or "420"
|
||||
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
|
||||
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
|
||||
end
|
||||
local restart = o.restart or 0
|
||||
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
|
||||
end
|
||||
local gray = o.gray
|
||||
if gray == nil then
|
||||
gray = img.format == "gray8"
|
||||
end
|
||||
-- the APP1 / APP2 / COM segments and the JFIF density from img.meta
|
||||
local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?)
|
||||
local segments = {}
|
||||
local meta = img.meta or {}
|
||||
if o.meta ~= false then
|
||||
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
|
||||
local d = buffer.create(buffer.len(meta.exif) + 6)
|
||||
buffer.writestring(d, 0, "Exif\0\0")
|
||||
buffer.copy(d, 6, meta.exif)
|
||||
table.insert(segments, { marker = 0xE1, data = d })
|
||||
end
|
||||
if type(meta.icc) == "buffer" then
|
||||
local icc = meta.icc :: buffer
|
||||
local n = buffer.len(icc)
|
||||
local chunk = 65519
|
||||
local count = math.max(1, math.ceil(n / chunk))
|
||||
if count <= 255 then
|
||||
for i = 1, count do
|
||||
local a = (i - 1) * chunk
|
||||
local l = math.min(chunk, n - a)
|
||||
local d = buffer.create(l + 14)
|
||||
buffer.writestring(d, 0, "ICC_PROFILE\0")
|
||||
buffer.writeu8(d, 12, i)
|
||||
buffer.writeu8(d, 13, count)
|
||||
buffer.copy(d, 14, icc, a, l)
|
||||
table.insert(segments, { marker = 0xE2, data = d })
|
||||
end
|
||||
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
|
||||
local d = buffer.create(buffer.len(meta.exif) + 6)
|
||||
buffer.writestring(d, 0, "Exif\0\0")
|
||||
buffer.copy(d, 6, meta.exif)
|
||||
table.insert(segments, { marker = 0xE1, data = d })
|
||||
end
|
||||
if type(meta.icc) == "buffer" then
|
||||
local icc = meta.icc :: buffer
|
||||
local n = buffer.len(icc)
|
||||
local chunk = 65519
|
||||
local count = math.max(1, math.ceil(n / chunk))
|
||||
if count <= 255 then
|
||||
for i = 1, count do
|
||||
local a = (i - 1) * chunk
|
||||
local l = math.min(chunk, n - a)
|
||||
local d = buffer.create(l + 14)
|
||||
buffer.writestring(d, 0, "ICC_PROFILE\0")
|
||||
buffer.writeu8(d, 12, i)
|
||||
buffer.writeu8(d, 13, count)
|
||||
buffer.copy(d, 14, icc, a, l)
|
||||
table.insert(segments, { marker = 0xE2, data = d })
|
||||
end
|
||||
end
|
||||
local text = meta.text
|
||||
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
|
||||
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
|
||||
end
|
||||
end
|
||||
local text = meta.text
|
||||
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
|
||||
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
|
||||
end
|
||||
local density = nil
|
||||
if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
|
||||
density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) }
|
||||
end
|
||||
local out = Encode.run(img.pixels, w, h, bpp, {
|
||||
quality = quality,
|
||||
sampling = sub,
|
||||
progressive = o.progressive == true,
|
||||
optimize = o.optimize == true,
|
||||
gray = gray,
|
||||
restart = restart,
|
||||
segments = segments,
|
||||
jfif = o.jfif ~= false,
|
||||
return segments, density
|
||||
end
|
||||
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local segments, density = {}, nil
|
||||
if o.meta ~= false then
|
||||
segments, density = metaSegments(img.meta or {})
|
||||
elseif type(img.meta) == "table" then
|
||||
local _
|
||||
_, density = metaSegments({ dpi = img.meta.dpi })
|
||||
end
|
||||
return Codec.encode(img, {
|
||||
quality = o.quality,
|
||||
subsampling = o.subsampling,
|
||||
progressive = o.progressive,
|
||||
optimize = o.optimize,
|
||||
gray = o.gray,
|
||||
restart = o.restart,
|
||||
jfif = o.jfif,
|
||||
density = density,
|
||||
segments = segments,
|
||||
})
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Jpeg
|
||||
+95
-3
@@ -19,6 +19,9 @@ local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Types = require("@formats/Types")
|
||||
local Registry = require("@formats/Registry")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local AudioWrap = require("@formats/containers/AudioWrap")
|
||||
local ImageOps = require("@formats/ops/ImageOps")
|
||||
local host = require("@formats/host")
|
||||
|
||||
local F = {}
|
||||
@@ -35,6 +38,7 @@ F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.b
|
||||
local KIND_CATEGORY: { [string]: string } = {
|
||||
image = "image",
|
||||
audio = "audio",
|
||||
video = "video",
|
||||
scene = "model",
|
||||
cad = "cad",
|
||||
font = "font",
|
||||
@@ -255,6 +259,7 @@ end
|
||||
-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
|
||||
-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
|
||||
-- the embedded parts) when called directly.
|
||||
<<<<<<< HEAD
|
||||
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
|
||||
local function withHooks(o: Options): Options
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then
|
||||
@@ -263,6 +268,33 @@ local function withHooks(o: Options): Options
|
||||
local c = table.clone(o)
|
||||
if c.plugins == nil then
|
||||
c.plugins = F.plugins
|
||||
=======
|
||||
--
|
||||
-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets
|
||||
-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 /
|
||||
-- FLAC as they are), opened through F.open with that format.
|
||||
local function openAudio(demuxer: any, track: any): (any, Err.Err?)
|
||||
local buf, fmt, err = AudioWrap.wrap(demuxer, track)
|
||||
if not buf then
|
||||
return nil, err
|
||||
end
|
||||
local dec, oerr = F.open(buf, { format = fmt, category = "audio" })
|
||||
-- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is
|
||||
-- already the decoder's own (its first packet returns nothing)
|
||||
if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
|
||||
dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5))
|
||||
end
|
||||
return dec, oerr
|
||||
end
|
||||
|
||||
local function withHooks(o: Options): Options
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.openAudio ~= nil then
|
||||
return o
|
||||
end
|
||||
local c = table.clone(o)
|
||||
if c.openAudio == nil then
|
||||
c.openAudio = openAudio
|
||||
>>>>>>> ws/video
|
||||
end
|
||||
if c.decodeImage == nil then
|
||||
c.decodeImage = function(b: buffer): (any, Err.Err?)
|
||||
@@ -309,12 +341,12 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
|
||||
end
|
||||
value, err = v, e
|
||||
elseif m.open then
|
||||
local ok, dec, e = pcall(m.open, Bytes.reader(buf), o)
|
||||
local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o))
|
||||
if not ok then
|
||||
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
|
||||
end
|
||||
if dec then
|
||||
value = drain(dec)
|
||||
value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec)
|
||||
end
|
||||
err = e
|
||||
else
|
||||
@@ -337,6 +369,9 @@ function F.open(src: any, opts: Options?): (any, Err.Err?)
|
||||
return nil, ierr
|
||||
end
|
||||
local entry, derr = detect(buf, name, o.category, o.format)
|
||||
if not entry and o.category == "video" and o.format == nil then
|
||||
entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos
|
||||
end
|
||||
if not entry then
|
||||
return nil, derr
|
||||
end
|
||||
@@ -344,10 +379,20 @@ function F.open(src: any, opts: Options?): (any, Err.Err?)
|
||||
if not m then
|
||||
return nil, merr
|
||||
end
|
||||
if not m.open and entry.category == "image" and o.category == "video" then
|
||||
local io = table.clone(o)
|
||||
io.category = "image"
|
||||
io.format = entry.name
|
||||
local img, lerr = F.load(buf, io)
|
||||
if not img then
|
||||
return nil, lerr
|
||||
end
|
||||
return F.video.fromImage(img, o)
|
||||
end
|
||||
if not m.open then
|
||||
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name)
|
||||
end
|
||||
local ok, dec, e = pcall(m.open, Bytes.reader(buf), o)
|
||||
local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o))
|
||||
if not ok then
|
||||
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
|
||||
end
|
||||
@@ -373,6 +418,9 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr
|
||||
return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)")
|
||||
end
|
||||
local entry = find(key, category)
|
||||
if not entry and category == "image" and type(value) == "table" and value.kind == "image" then
|
||||
entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi")
|
||||
end
|
||||
if not entry then
|
||||
return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else ""))
|
||||
end
|
||||
@@ -427,6 +475,13 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
o.files = {}
|
||||
end
|
||||
end
|
||||
if entry.category == "video" and type(value) == "table" and value.kind == "image" then
|
||||
local v, verr = F.video.fromImage(value)
|
||||
if not v then
|
||||
return nil, verr
|
||||
end
|
||||
value = v
|
||||
end
|
||||
if type(value) == "table" and value.kind == "scene" then
|
||||
local terr = encodeTextures(value)
|
||||
if terr then
|
||||
@@ -543,6 +598,7 @@ for category in Types.CATEGORIES do
|
||||
end
|
||||
F.data.null = Types.null
|
||||
|
||||
<<<<<<< HEAD
|
||||
-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err;
|
||||
-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel
|
||||
-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED.
|
||||
@@ -567,6 +623,42 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do
|
||||
return a, b
|
||||
end
|
||||
end
|
||||
=======
|
||||
-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited
|
||||
-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8).
|
||||
F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?)
|
||||
if type(img) ~= "table" or img.kind ~= "image" then
|
||||
return nil, Err.new(Err.ARG, "fromImage: expected an Image")
|
||||
end
|
||||
local frames, delays = { img }, { 0.1 }
|
||||
if type(img.frames) == "table" and #img.frames > 0 then
|
||||
local list, cerr = ImageOps.coalesce(img)
|
||||
if not list then
|
||||
return nil, cerr
|
||||
end
|
||||
frames = list
|
||||
delays = {}
|
||||
for i, f in img.frames do
|
||||
delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1
|
||||
end
|
||||
elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then
|
||||
local c, cerr = ImageOps.convert(img, "rgba8")
|
||||
if not c then
|
||||
return nil, cerr
|
||||
end
|
||||
frames = { c }
|
||||
end
|
||||
local src = type(img.meta) == "table" and img.meta.source
|
||||
return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta })
|
||||
end
|
||||
-- F.video.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence:
|
||||
-- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1)
|
||||
F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?)
|
||||
return Video.fromFrames(images, delays, opts)
|
||||
end
|
||||
-- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder)
|
||||
F.video.codecs = Video
|
||||
>>>>>>> ws/video
|
||||
|
||||
-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or
|
||||
-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
--!strict
|
||||
-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in formats-luau, on containers/Avi.
|
||||
-- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces
|
||||
-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/Video registry by FourCC (MJPEG, MPEG-1,
|
||||
-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is
|
||||
-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX,
|
||||
-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer.
|
||||
-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's
|
||||
-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header.
|
||||
-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Avi = require("@formats/containers/Avi")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local AviFormat = {
|
||||
name = "avi",
|
||||
category = "video",
|
||||
extensions = { "avi" },
|
||||
mime = { "video/x-msvideo", "video/avi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8)
|
||||
track: number?, -- the video track (stream index + 1) to decode
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
quality: number?, -- MJPEG quality 1..100 (default 90)
|
||||
reencode: boolean?, -- encode the frames even when the source is MJPEG
|
||||
audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one)
|
||||
video: boolean?,
|
||||
maxFps: number?, -- the highest frame rate variable delays may need (default 100)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- WAVEFORMATEX wFormatTag -> codec id
|
||||
local AUDIO_TAGS: { [number]: string } = {
|
||||
[0x0001] = "pcm",
|
||||
[0x0002] = "adpcm_ms",
|
||||
[0x0003] = "pcm_f",
|
||||
[0x0006] = "pcm_alaw",
|
||||
[0x0007] = "pcm_mulaw",
|
||||
[0x0011] = "adpcm_ima_wav",
|
||||
[0x0050] = "mp2",
|
||||
[0x0055] = "mp3",
|
||||
[0x00FF] = "aac",
|
||||
[0x1610] = "aac",
|
||||
[0x706D] = "aac",
|
||||
[0x2000] = "ac3",
|
||||
[0x2001] = "dts",
|
||||
[0xF1AC] = "flac",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function AviFormat.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function videoTrack(s: Avi.Stream, id: number): Types.Track
|
||||
local f = s.strf
|
||||
local t: any = {
|
||||
id = id,
|
||||
kind = "video",
|
||||
codec = "",
|
||||
codecTag = s.handler,
|
||||
timescale = if s.scale > 0 then s.rate / s.scale else 25,
|
||||
frameRate = if s.scale > 0 then s.rate / s.scale else 0,
|
||||
default = true,
|
||||
name = s.name,
|
||||
frames = s.length,
|
||||
}
|
||||
if buffer.len(f) >= 40 then
|
||||
local w = buffer.readi32(f, 4)
|
||||
local h = buffer.readi32(f, 8)
|
||||
local bits = buffer.readu16(f, 14)
|
||||
local comp = buffer.readstring(f, 16, 4)
|
||||
t.width = math.abs(w)
|
||||
t.height = math.abs(h)
|
||||
t.codecTag = comp
|
||||
t.bitsPerPixel = bits
|
||||
if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then
|
||||
t.codec = "rawvideo"
|
||||
t.pixelFormat = if bits == 32 then "bgra" else "bgr24"
|
||||
t.flip = h > 0
|
||||
t.stride = ((math.abs(w) * bits + 31) // 32) * 4
|
||||
if bits ~= 24 and bits ~= 32 then
|
||||
t.codec = "rawvideo_" .. bits
|
||||
end
|
||||
else
|
||||
t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", "")))
|
||||
if comp == "YV12" then
|
||||
t.pixelFormat = "yv12"
|
||||
elseif t.codec == "rawvideo" then
|
||||
t.pixelFormat = "yuv420p"
|
||||
end
|
||||
end
|
||||
local size = buffer.readu32(f, 0)
|
||||
if size > 40 and buffer.len(f) > 40 then
|
||||
local c = buffer.create(buffer.len(f) - 40)
|
||||
buffer.copy(c, 0, f, 40)
|
||||
t.config = c
|
||||
end
|
||||
else
|
||||
t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler)
|
||||
local fr = s.frame
|
||||
t.width, t.height = fr[3] - fr[1], fr[4] - fr[2]
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local function audioTrack(s: Avi.Stream, id: number): Types.Track
|
||||
local f = s.strf
|
||||
local t: any = {
|
||||
id = id,
|
||||
kind = "audio",
|
||||
codec = "unknown",
|
||||
codecTag = s.handler,
|
||||
timescale = if s.scale > 0 then s.rate / s.scale else 1,
|
||||
default = true,
|
||||
name = s.name,
|
||||
waveFormat = f,
|
||||
}
|
||||
if buffer.len(f) >= 16 then
|
||||
local tag = buffer.readu16(f, 0)
|
||||
t.channels = buffer.readu16(f, 2)
|
||||
t.sampleRate = buffer.readu32(f, 4)
|
||||
t.blockAlign = buffer.readu16(f, 12)
|
||||
local bits = buffer.readu16(f, 14)
|
||||
t.bitsPerSample = bits
|
||||
if tag == 0xFFFE and buffer.len(f) >= 26 then
|
||||
tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag
|
||||
end
|
||||
t.formatTag = tag
|
||||
local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag)
|
||||
if c == "pcm" then
|
||||
c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le"
|
||||
elseif c == "pcm_f" then
|
||||
c = "pcm_f" .. bits .. "le"
|
||||
end
|
||||
t.codec = c
|
||||
if buffer.len(f) >= 18 then
|
||||
local cb = buffer.readu16(f, 16)
|
||||
if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then
|
||||
local cfg = buffer.create(cb)
|
||||
buffer.copy(cfg, 0, f, 18, cb)
|
||||
t.config = cfg
|
||||
end
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
|
||||
local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file))
|
||||
end
|
||||
if not file then
|
||||
return nil, err
|
||||
end
|
||||
local tracks: { Types.Track } = {}
|
||||
local streams: { { any } } = {}
|
||||
for i, s in file.streams do
|
||||
local t: Types.Track? = nil
|
||||
if s.type == "vids" then
|
||||
t = videoTrack(s, i)
|
||||
elseif s.type == "auds" then
|
||||
t = audioTrack(s, i)
|
||||
elseif s.type == "txts" then
|
||||
t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 }
|
||||
end
|
||||
if t then
|
||||
table.insert(tracks, t)
|
||||
table.insert(streams, { s, t })
|
||||
end
|
||||
end
|
||||
local meta = { info = file.info, index = file.index, odml = file.odml ~= nil }
|
||||
local dmx = Demux.new("avi", tracks, r.buf, meta)
|
||||
-- packets in file order across streams: merge by offset
|
||||
local items: { { number } } = {}
|
||||
for k, st in streams do
|
||||
local s: Avi.Stream, t: any = st[1], st[2]
|
||||
local tick = s.start
|
||||
for _, c in s.chunks do
|
||||
local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1
|
||||
if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then
|
||||
dur = c.size / t.blockAlign
|
||||
end
|
||||
if c.size > 0 then
|
||||
table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size })
|
||||
tick += dur
|
||||
elseif t.kind == "video" then
|
||||
tick += 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(items, function(a: { number }, b: { number }): boolean
|
||||
return a[1] < b[1]
|
||||
end)
|
||||
for _, it in items do
|
||||
local t: any = streams[it[2]][2]
|
||||
dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6])
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err
|
||||
function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = table.clone(opts or {})
|
||||
o.quality = o.quality or 90
|
||||
local streams, err = Source.streams(value, o, {
|
||||
video = { copy = { mjpeg = true }, encode = "mjpeg" },
|
||||
audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true },
|
||||
})
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local wstreams: { Avi.WStream } = {}
|
||||
local width, height, usPerFrame = 0, 0, 0
|
||||
local frameDur = 0
|
||||
for _, s in streams do
|
||||
if s.kind == "video" then
|
||||
-- a constant frame rate: the shortest frame duration (variable delays repeat frames)
|
||||
local num, den, packets = Source.constantRate(s, o.maxFps)
|
||||
s.packets = packets
|
||||
frameDur = den / num
|
||||
width, height = s.width or 0, s.height or 0
|
||||
usPerFrame = 1e6 * frameDur
|
||||
local bih = Bytes.writer(40)
|
||||
bih:u32le(40)
|
||||
bih:u32le(width)
|
||||
bih:u32le(height)
|
||||
bih:u16le(1)
|
||||
bih:u16le(24)
|
||||
bih:string("MJPG")
|
||||
bih:u32le(width * height * 3)
|
||||
bih:u32le(0)
|
||||
bih:u32le(0)
|
||||
bih:u32le(0)
|
||||
bih:u32le(0)
|
||||
table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" })
|
||||
else
|
||||
local ch = s.channels or 1
|
||||
local bits = if s.codec == "pcm_u8" then 8 else 16
|
||||
local align = ch * bits // 8
|
||||
local rate = math.floor((s.sampleRate or 44100) + 0.5)
|
||||
local wf = Bytes.writer(18)
|
||||
wf:u16le(1)
|
||||
wf:u16le(ch)
|
||||
wf:u32le(rate)
|
||||
wf:u32le(rate * align)
|
||||
wf:u16le(align)
|
||||
wf:u16le(bits)
|
||||
wf:u16le(0)
|
||||
table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" })
|
||||
end
|
||||
end
|
||||
-- chunks in time order (the video packets already repeated to the constant rate)
|
||||
local chunks: { { any } } = {}
|
||||
for _, item in Source.interleave(streams) do
|
||||
table.insert(chunks, { item[1], item[2].data, true })
|
||||
end
|
||||
local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
|
||||
end
|
||||
return buf, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = AviFormat.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return AviFormat
|
||||
@@ -0,0 +1,285 @@
|
||||
--!strict
|
||||
-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration),
|
||||
-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of
|
||||
-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative
|
||||
-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come
|
||||
-- from codecs/Video/Source (copied packets or encoded frames). Interpreted; never throws.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Ebml = require("@formats/containers/Ebml")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
local Parse = require("@formats/video/mkv/Parse")
|
||||
|
||||
local ID = Parse.ID
|
||||
local Mux = {}
|
||||
|
||||
local AUDIO_IDS: { [string]: string } = {
|
||||
vorbis = "A_VORBIS",
|
||||
opus = "A_OPUS",
|
||||
flac = "A_FLAC",
|
||||
mp3 = "A_MPEG/L3",
|
||||
mp2 = "A_MPEG/L2",
|
||||
mp1 = "A_MPEG/L1",
|
||||
aac = "A_AAC",
|
||||
ac3 = "A_AC3",
|
||||
eac3 = "A_EAC3",
|
||||
alac = "A_ALAC",
|
||||
pcm_u8 = "A_PCM/INT/LIT",
|
||||
pcm_s16le = "A_PCM/INT/LIT",
|
||||
pcm_s24le = "A_PCM/INT/LIT",
|
||||
pcm_s32le = "A_PCM/INT/LIT",
|
||||
pcm_s16be = "A_PCM/INT/BIG",
|
||||
pcm_s24be = "A_PCM/INT/BIG",
|
||||
pcm_s32be = "A_PCM/INT/BIG",
|
||||
pcm_f32le = "A_PCM/FLOAT/IEEE",
|
||||
pcm_f64le = "A_PCM/FLOAT/IEEE",
|
||||
}
|
||||
Mux.AUDIO_IDS = AUDIO_IDS
|
||||
|
||||
-- codecId(stream) -> the Matroska CodecID | nil
|
||||
function Mux.codecId(kind: string, codec: string): string?
|
||||
if kind == "video" then
|
||||
local e = Video.entry(codec)
|
||||
local m = e and e.matroska
|
||||
return m and m[1]
|
||||
end
|
||||
return AUDIO_IDS[codec]
|
||||
end
|
||||
|
||||
local function pcmBits(codec: string): number?
|
||||
local b = string.match(codec, "^pcm_[suf](%d+)")
|
||||
if b then
|
||||
return tonumber(b)
|
||||
end
|
||||
if codec == "pcm_u8" then
|
||||
return 8
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
export type Options = {
|
||||
webm: boolean?,
|
||||
title: string?,
|
||||
app: string?,
|
||||
clusterSeconds: number?, -- default 2
|
||||
}
|
||||
|
||||
-- mux(streams, opts) -> buffer | nil, Err
|
||||
function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?)
|
||||
local webm = opts.webm == true
|
||||
local app = opts.app or "formats-luau"
|
||||
local clusterSpan = opts.clusterSeconds or 2
|
||||
-- tracks
|
||||
local ids: { string } = {}
|
||||
local videoIndex = 0
|
||||
for i, s in streams do
|
||||
local cid = Mux.codecId(s.kind, s.codec)
|
||||
if not cid then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec)
|
||||
end
|
||||
ids[i] = cid
|
||||
if s.kind == "video" and videoIndex == 0 then
|
||||
videoIndex = i
|
||||
end
|
||||
end
|
||||
local order = Source.interleave(streams)
|
||||
local duration = 0
|
||||
for _, s in streams do
|
||||
for _, p in s.packets do
|
||||
local e = p.pts + (p.duration or 0)
|
||||
if e > duration then
|
||||
duration = e
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known)
|
||||
local body = Ebml.writer(65536)
|
||||
local infoAt = body:tell()
|
||||
local info = body:open(ID.Info)
|
||||
body:uint(ID.TimecodeScale, 1000000)
|
||||
body:string(ID.MuxingApp, app)
|
||||
body:string(ID.WritingApp, app)
|
||||
if opts.title then
|
||||
body:string(ID.Title, opts.title)
|
||||
end
|
||||
body:float(ID.Duration, duration * 1000)
|
||||
body:close(info)
|
||||
|
||||
local tracksAt = body:tell()
|
||||
local tracks = body:open(ID.Tracks)
|
||||
for i, s in streams do
|
||||
local te = body:open(ID.TrackEntry)
|
||||
body:uint(ID.TrackNumber, i)
|
||||
body:uint(ID.TrackUID, i)
|
||||
body:uint(ID.TrackType, if s.kind == "video" then 1 else 2)
|
||||
body:uint(ID.FlagLacing, 0)
|
||||
body:string(ID.Language, "und")
|
||||
body:string(ID.CodecID, ids[i])
|
||||
if s.config and buffer.len(s.config) > 0 then
|
||||
body:binary(ID.CodecPrivate, s.config)
|
||||
end
|
||||
if s.kind == "video" then
|
||||
if s.frameRate and s.frameRate > 0 then
|
||||
body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5))
|
||||
end
|
||||
local v = body:open(ID.Video)
|
||||
body:uint(ID.PixelWidth, s.width or 0)
|
||||
body:uint(ID.PixelHeight, s.height or 0)
|
||||
body:close(v)
|
||||
else
|
||||
if s.codec == "opus" then
|
||||
local pre = 0
|
||||
local c = s.config
|
||||
if c and buffer.len(c) >= 12 then
|
||||
pre = buffer.readu16(c, 10)
|
||||
end
|
||||
body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5))
|
||||
body:uint(ID.SeekPreRoll, 80000000)
|
||||
end
|
||||
local a = body:open(ID.Audio)
|
||||
body:float(ID.SamplingFrequency, s.sampleRate or 48000)
|
||||
body:uint(ID.Channels, s.channels or 1)
|
||||
local bits = pcmBits(s.codec) or s.bitsPerSample
|
||||
if bits and string.sub(s.codec, 1, 4) == "pcm_" then
|
||||
body:uint(ID.BitDepth, bits)
|
||||
end
|
||||
body:close(a)
|
||||
end
|
||||
body:close(te)
|
||||
end
|
||||
body:close(tracks)
|
||||
|
||||
-- clusters
|
||||
local cues: { { number } } = {} -- { time ms, track, cluster offset in body }
|
||||
local cl: number? = nil
|
||||
local clTime = 0
|
||||
local clStart = 0
|
||||
for _, item in order do
|
||||
local si: number, p = item[1], item[2]
|
||||
local ms = math.floor(p.pts * 1000 + 0.5)
|
||||
local isVideoKey = si == videoIndex and p.keyframe
|
||||
local need = cl == nil
|
||||
or ms - clTime > 30000
|
||||
or ms < clTime
|
||||
or (isVideoKey and ms - clStart >= clusterSpan * 1000)
|
||||
or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000)
|
||||
if need then
|
||||
if cl then
|
||||
body:close(cl)
|
||||
end
|
||||
local at = body:tell()
|
||||
cl = body:open(ID.Cluster)
|
||||
clTime = ms
|
||||
clStart = ms
|
||||
body:uint(ID.Timecode, ms)
|
||||
if videoIndex == 0 or isVideoKey then
|
||||
table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at })
|
||||
end
|
||||
end
|
||||
local data: buffer = p.data
|
||||
local hdr = Ebml.vintString(si, 1)
|
||||
local rel = ms - clTime
|
||||
local size = #hdr + 3 + buffer.len(data)
|
||||
body:header(ID.SimpleBlock, size)
|
||||
body:raw(hdr)
|
||||
body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0))
|
||||
body:rawBuffer(data)
|
||||
end
|
||||
if cl then
|
||||
body:close(cl)
|
||||
end
|
||||
local cuesAt = body:tell()
|
||||
if #cues > 0 then
|
||||
local c = body:open(ID.Cues)
|
||||
for _, q in cues do
|
||||
local cp = body:open(ID.CuePoint)
|
||||
body:uint(ID.CueTime, q[1])
|
||||
local tp = body:open(ID.CueTrackPositions)
|
||||
body:uint(ID.CueTrack, q[2])
|
||||
body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length
|
||||
body:close(tp)
|
||||
body:close(cp)
|
||||
end
|
||||
body:close(c)
|
||||
end
|
||||
local bodyBuf = body:finish()
|
||||
|
||||
-- the SeekHead: its own length shifts every position, so build it until its size is stable
|
||||
local function seekHead(shift: number): buffer
|
||||
local w = Ebml.writer(256)
|
||||
local sh = w:open(ID.SeekHead)
|
||||
local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } }
|
||||
if #cues > 0 then
|
||||
table.insert(entries, { ID.Cues, cuesAt })
|
||||
end
|
||||
for _, e in entries do
|
||||
local sk = w:open(0x4DBB)
|
||||
local idv = e[1]
|
||||
local bytes = {}
|
||||
while idv > 0 do
|
||||
table.insert(bytes, 1, idv % 256)
|
||||
idv = idv // 256
|
||||
end
|
||||
w:header(0x53AB, #bytes)
|
||||
for _, b in bytes do
|
||||
w:raw(string.char(b))
|
||||
end
|
||||
w:uint(0x53AC, e[2] + shift)
|
||||
w:close(sk)
|
||||
end
|
||||
w:close(sh)
|
||||
return w:finish()
|
||||
end
|
||||
local shift = 0
|
||||
local head = seekHead(0)
|
||||
for _ = 1, 4 do
|
||||
local n = buffer.len(head)
|
||||
if n == shift then
|
||||
break
|
||||
end
|
||||
shift = n
|
||||
head = seekHead(shift)
|
||||
end
|
||||
shift = buffer.len(head)
|
||||
-- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element
|
||||
-- (its uint widths may grow, but Cues are last, so nothing after them moves)
|
||||
if #cues > 0 then
|
||||
local w = Ebml.writer(4096)
|
||||
local c = w:open(ID.Cues)
|
||||
for _, q in cues do
|
||||
local cp = w:open(ID.CuePoint)
|
||||
w:uint(ID.CueTime, q[1])
|
||||
local tp = w:open(ID.CueTrackPositions)
|
||||
w:uint(ID.CueTrack, q[2])
|
||||
w:uint(ID.CueClusterPosition, q[3] + shift)
|
||||
w:close(tp)
|
||||
w:close(cp)
|
||||
end
|
||||
w:close(c)
|
||||
local cuesBuf = w:finish()
|
||||
local nb = buffer.create(cuesAt + buffer.len(cuesBuf))
|
||||
buffer.copy(nb, 0, bodyBuf, 0, cuesAt)
|
||||
buffer.copy(nb, cuesAt, cuesBuf)
|
||||
bodyBuf = nb
|
||||
end
|
||||
|
||||
-- the file
|
||||
local out = Ebml.writer(buffer.len(bodyBuf) + 256)
|
||||
local eb = out:open(ID.EBML)
|
||||
out:uint(0x4286, 1)
|
||||
out:uint(0x42F7, 1)
|
||||
out:uint(0x42F2, 4)
|
||||
out:uint(0x42F3, 8)
|
||||
out:string(ID.DocType, if webm then "webm" else "matroska")
|
||||
out:uint(0x4287, 4)
|
||||
out:uint(0x4285, 2)
|
||||
out:close(eb)
|
||||
local seg = out:open(ID.Segment)
|
||||
out:rawBuffer(head)
|
||||
out:rawBuffer(bodyBuf)
|
||||
out:close(seg)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Mux
|
||||
@@ -0,0 +1,681 @@
|
||||
--!strict
|
||||
-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles
|
||||
-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration,
|
||||
-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression,
|
||||
-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by
|
||||
-- default). Interpreted (it only walks headers); never throws.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Ebml = require("@formats/containers/Ebml")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
|
||||
local Parse = {}
|
||||
|
||||
-- element IDs
|
||||
local ID = {
|
||||
EBML = 0x1A45DFA3,
|
||||
DocType = 0x4282,
|
||||
Segment = 0x18538067,
|
||||
SeekHead = 0x114D9B74,
|
||||
Info = 0x1549A966,
|
||||
TimecodeScale = 0x2AD7B1,
|
||||
Duration = 0x4489,
|
||||
Title = 0x7BA9,
|
||||
MuxingApp = 0x4D80,
|
||||
WritingApp = 0x5741,
|
||||
DateUTC = 0x4461,
|
||||
Tracks = 0x1654AE6B,
|
||||
TrackEntry = 0xAE,
|
||||
TrackNumber = 0xD7,
|
||||
TrackUID = 0x73C5,
|
||||
TrackType = 0x83,
|
||||
FlagEnabled = 0xB9,
|
||||
FlagDefault = 0x88,
|
||||
FlagForced = 0x55AA,
|
||||
FlagLacing = 0x9C,
|
||||
DefaultDuration = 0x23E383,
|
||||
Name = 0x536E,
|
||||
Language = 0x22B59C,
|
||||
LanguageBCP47 = 0x22B59D,
|
||||
CodecID = 0x86,
|
||||
CodecPrivate = 0x63A2,
|
||||
CodecDelay = 0x56AA,
|
||||
SeekPreRoll = 0x56BB,
|
||||
Video = 0xE0,
|
||||
PixelWidth = 0xB0,
|
||||
PixelHeight = 0xBA,
|
||||
DisplayWidth = 0x54B0,
|
||||
DisplayHeight = 0x54BA,
|
||||
ColourSpace = 0x2EB524,
|
||||
Audio = 0xE1,
|
||||
SamplingFrequency = 0xB5,
|
||||
OutputSamplingFrequency = 0x78B5,
|
||||
Channels = 0x9F,
|
||||
BitDepth = 0x6264,
|
||||
ContentEncodings = 0x6D80,
|
||||
ContentEncoding = 0x6240,
|
||||
ContentEncodingType = 0x5033,
|
||||
ContentEncodingScope = 0x5032,
|
||||
ContentCompression = 0x5034,
|
||||
ContentCompAlgo = 0x4254,
|
||||
ContentCompSettings = 0x4255,
|
||||
ContentEncryption = 0x5035,
|
||||
Cluster = 0x1F43B675,
|
||||
Timecode = 0xE7,
|
||||
SimpleBlock = 0xA3,
|
||||
BlockGroup = 0xA0,
|
||||
Block = 0xA1,
|
||||
BlockDuration = 0x9B,
|
||||
ReferenceBlock = 0xFB,
|
||||
DiscardPadding = 0x75A2,
|
||||
Cues = 0x1C53BB6B,
|
||||
CuePoint = 0xBB,
|
||||
CueTime = 0xB3,
|
||||
CueTrackPositions = 0xB7,
|
||||
CueTrack = 0xF7,
|
||||
CueClusterPosition = 0xF1,
|
||||
CueRelativePosition = 0xF0,
|
||||
Tags = 0x1254C367,
|
||||
Tag = 0x7373,
|
||||
SimpleTag = 0x67C8,
|
||||
TagName = 0x45A3,
|
||||
TagString = 0x4487,
|
||||
Targets = 0x63C0,
|
||||
Chapters = 0x1043A770,
|
||||
Attachments = 0x1941A469,
|
||||
Void = 0xEC,
|
||||
Crc32 = 0xBF,
|
||||
}
|
||||
Parse.ID = ID
|
||||
|
||||
-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts)
|
||||
local TOP: { [number]: boolean } = {
|
||||
[ID.SeekHead] = true,
|
||||
[ID.Info] = true,
|
||||
[ID.Tracks] = true,
|
||||
[ID.Cluster] = true,
|
||||
[ID.Cues] = true,
|
||||
[ID.Tags] = true,
|
||||
[ID.Chapters] = true,
|
||||
[ID.Attachments] = true,
|
||||
[ID.Segment] = true,
|
||||
[ID.EBML] = true,
|
||||
}
|
||||
|
||||
-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/Video registry)
|
||||
local AUDIO: { [string]: string } = {
|
||||
A_VORBIS = "vorbis",
|
||||
A_OPUS = "opus",
|
||||
A_FLAC = "flac",
|
||||
["A_MPEG/L3"] = "mp3",
|
||||
["A_MPEG/L2"] = "mp2",
|
||||
["A_MPEG/L1"] = "mp1",
|
||||
A_AAC = "aac",
|
||||
["A_AAC/MPEG4/LC"] = "aac",
|
||||
["A_AAC/MPEG4/LC/SBR"] = "aac",
|
||||
["A_AAC/MPEG2/LC"] = "aac",
|
||||
A_AC3 = "ac3",
|
||||
A_EAC3 = "eac3",
|
||||
A_DTS = "dts",
|
||||
A_ALAC = "alac",
|
||||
A_TTA1 = "tta",
|
||||
A_WAVPACK4 = "wavpack",
|
||||
["A_MS/ACM"] = "acm",
|
||||
}
|
||||
local SUBS: { [string]: string } = {
|
||||
["S_TEXT/UTF8"] = "text",
|
||||
["S_TEXT/ASCII"] = "text",
|
||||
["S_TEXT/WEBVTT"] = "webvtt",
|
||||
["S_TEXT/ASS"] = "ass",
|
||||
["S_TEXT/SSA"] = "ssa",
|
||||
["S_ASS"] = "ass",
|
||||
["S_SSA"] = "ssa",
|
||||
["S_VOBSUB"] = "dvdsub",
|
||||
["S_HDMV/PGS"] = "pgs",
|
||||
}
|
||||
|
||||
-- codecFor(CodecID, bitDepth) -> our codec id
|
||||
local function codecFor(id: string, kind: string, bits: number?): string
|
||||
if kind == "video" then
|
||||
return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", "")))
|
||||
end
|
||||
if id == "A_PCM/INT/LIT" then
|
||||
return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le"
|
||||
elseif id == "A_PCM/INT/BIG" then
|
||||
return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be"
|
||||
elseif id == "A_PCM/FLOAT/IEEE" then
|
||||
return "pcm_f" .. (bits or 32) .. "le"
|
||||
end
|
||||
return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", "")))
|
||||
end
|
||||
Parse.codecFor = codecFor
|
||||
|
||||
type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? }
|
||||
|
||||
local function parseVideo(buf: buffer, off: number, len: number, t: any)
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.PixelWidth then
|
||||
t.width = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.PixelHeight then
|
||||
t.height = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.DisplayWidth then
|
||||
t.displayWidth = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.DisplayHeight then
|
||||
t.displayHeight = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.ColourSpace then
|
||||
t.colourSpace = buffer.readstring(buf, o, math.min(n, 4))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function parseAudio(buf: buffer, off: number, len: number, t: any)
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.SamplingFrequency then
|
||||
t.sampleRate = Ebml.float(buf, o, n)
|
||||
elseif id == ID.OutputSamplingFrequency then
|
||||
t.outputSampleRate = Ebml.float(buf, o, n)
|
||||
elseif id == ID.Channels then
|
||||
t.channels = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.BitDepth then
|
||||
t.bitsPerSample = Ebml.uint(buf, o, n)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption
|
||||
-- are not
|
||||
local function parseEncodings(buf: buffer, off: number, len: number, t: any): string?
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.ContentEncoding then
|
||||
local etype = 0
|
||||
local scope = 1
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.ContentEncodingScope then
|
||||
scope = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.ContentEncodingType then
|
||||
etype = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.ContentCompression then
|
||||
local algo, settings = 0, nil
|
||||
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
|
||||
if id3 == ID.ContentCompAlgo then
|
||||
algo = Ebml.uint(buf, o3, n3)
|
||||
elseif id3 == ID.ContentCompSettings then
|
||||
settings = Ebml.binary(buf, o3, n3)
|
||||
end
|
||||
end
|
||||
if algo == 3 then
|
||||
t.strip = settings
|
||||
elseif algo == 0 then
|
||||
t.zlib = scope -- 1: frames, 2: CodecPrivate
|
||||
else
|
||||
return "content compression algorithm " .. algo
|
||||
end
|
||||
elseif id2 == ID.ContentEncryption then
|
||||
return "encrypted track"
|
||||
end
|
||||
end
|
||||
if etype ~= 0 then
|
||||
return "encrypted track"
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string })
|
||||
local tracks: { TrackInfo } = {}
|
||||
local problems: { [number]: string } = {}
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.TrackEntry then
|
||||
local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" }
|
||||
local ttype, codecId = 0, ""
|
||||
local problem: string? = nil
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.TrackNumber then
|
||||
t.id = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.TrackUID then
|
||||
t.uid = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.TrackType then
|
||||
ttype = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.FlagDefault then
|
||||
t.default = Ebml.uint(buf, o2, n2) ~= 0
|
||||
elseif id2 == ID.FlagEnabled then
|
||||
t.enabled = Ebml.uint(buf, o2, n2) ~= 0
|
||||
elseif id2 == ID.FlagLacing then
|
||||
t.lacing = Ebml.uint(buf, o2, n2) ~= 0
|
||||
elseif id2 == ID.DefaultDuration then
|
||||
t.defaultDurationNs = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.Name then
|
||||
t.name = Ebml.string(buf, o2, n2)
|
||||
elseif id2 == ID.Language then
|
||||
t.language = Ebml.string(buf, o2, n2)
|
||||
elseif id2 == ID.CodecID then
|
||||
codecId = Ebml.string(buf, o2, n2)
|
||||
elseif id2 == ID.CodecPrivate then
|
||||
t.config = Ebml.binary(buf, o2, n2)
|
||||
elseif id2 == ID.CodecDelay then
|
||||
t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9
|
||||
elseif id2 == ID.SeekPreRoll then
|
||||
t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9
|
||||
elseif id2 == ID.Video then
|
||||
parseVideo(buf, o2, n2, t)
|
||||
elseif id2 == ID.Audio then
|
||||
parseAudio(buf, o2, n2, t)
|
||||
elseif id2 == ID.ContentEncodings then
|
||||
problem = parseEncodings(buf, o2, n2, t)
|
||||
end
|
||||
end
|
||||
if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then
|
||||
local c = Deflate.zlib(t.config)
|
||||
if c then
|
||||
t.config = c
|
||||
else
|
||||
problem = "bad zlib-compressed CodecPrivate"
|
||||
end
|
||||
end
|
||||
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)
|
||||
if t.kind == "audio" then
|
||||
t.sampleRate = t.sampleRate or 8000
|
||||
t.channels = t.channels or 1
|
||||
end
|
||||
if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then
|
||||
t.frameRate = 1e9 / t.defaultDurationNs
|
||||
end
|
||||
if t.id > 0 then
|
||||
table.insert(tracks, t)
|
||||
if problem then
|
||||
problems[t.id] = problem
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return tracks, problems
|
||||
end
|
||||
|
||||
local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?)
|
||||
local scale, duration = 1000000, nil
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.TimecodeScale then
|
||||
scale = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.Duration then
|
||||
duration = Ebml.float(buf, o, n)
|
||||
elseif id == ID.Title then
|
||||
meta.title = Ebml.string(buf, o, n)
|
||||
elseif id == ID.MuxingApp then
|
||||
meta.muxingApp = Ebml.string(buf, o, n)
|
||||
elseif id == ID.WritingApp then
|
||||
meta.writingApp = Ebml.string(buf, o, n)
|
||||
end
|
||||
end
|
||||
if scale <= 0 then
|
||||
scale = 1000000
|
||||
end
|
||||
return scale, duration
|
||||
end
|
||||
|
||||
local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } }
|
||||
local cues = {}
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.CuePoint then
|
||||
local time = 0
|
||||
local positions = {}
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.CueTime then
|
||||
time = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.CueTrackPositions then
|
||||
local tr, pos = 0, 0
|
||||
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
|
||||
if id3 == ID.CueTrack then
|
||||
tr = Ebml.uint(buf, o3, n3)
|
||||
elseif id3 == ID.CueClusterPosition then
|
||||
pos = Ebml.uint(buf, o3, n3)
|
||||
end
|
||||
end
|
||||
table.insert(positions, { tr, pos })
|
||||
end
|
||||
end
|
||||
for _, p in positions do
|
||||
table.insert(cues, { time = time, track = p[1], position = segData + p[2] })
|
||||
end
|
||||
end
|
||||
end
|
||||
return cues
|
||||
end
|
||||
|
||||
local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any })
|
||||
local tags = meta.tags or {}
|
||||
meta.tags = tags
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.Tag then
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.SimpleTag then
|
||||
local name, value = nil, nil
|
||||
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
|
||||
if id3 == ID.TagName then
|
||||
name = Ebml.string(buf, o3, n3)
|
||||
elseif id3 == ID.TagString then
|
||||
value = Ebml.string(buf, o3, n3)
|
||||
end
|
||||
end
|
||||
if name and value and tags[string.lower(name)] == nil then
|
||||
tags[string.lower(name)] = value
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
type Ctx = {
|
||||
buf: buffer,
|
||||
dmx: any,
|
||||
byNum: { [number]: TrackInfo },
|
||||
scaleNs: number,
|
||||
err: string?,
|
||||
maxPackets: number,
|
||||
}
|
||||
|
||||
-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing
|
||||
local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?)
|
||||
local buf = ctx.buf
|
||||
local limit = off + len
|
||||
local tn, tl = Ebml.vint(buf, off, limit)
|
||||
if not tn or not tl or tn < 0 or off + tl + 3 > limit then
|
||||
return
|
||||
end
|
||||
local p = off + tl
|
||||
local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1)
|
||||
if rel >= 32768 then
|
||||
rel -= 65536
|
||||
end
|
||||
local flags = buffer.readu8(buf, p + 2)
|
||||
p += 3
|
||||
local t = ctx.byNum[tn]
|
||||
if not t then
|
||||
return
|
||||
end
|
||||
local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false)
|
||||
if t.kind == "audio" or t.kind == "subtitle" then
|
||||
key = true
|
||||
end
|
||||
local pts = clusterTime + rel
|
||||
local lacing = bit32.band(bit32.rshift(flags, 1), 3)
|
||||
local sizes: { number } = {}
|
||||
if lacing == 0 then
|
||||
sizes[1] = limit - p
|
||||
else
|
||||
if p >= limit then
|
||||
return
|
||||
end
|
||||
local count = buffer.readu8(buf, p) + 1
|
||||
p += 1
|
||||
if lacing == 1 then -- Xiph
|
||||
local total = 0
|
||||
for k = 1, count - 1 do
|
||||
local s = 0
|
||||
while true do
|
||||
if p >= limit then
|
||||
return
|
||||
end
|
||||
local b = buffer.readu8(buf, p)
|
||||
p += 1
|
||||
s += b
|
||||
if b ~= 255 then
|
||||
break
|
||||
end
|
||||
end
|
||||
sizes[k] = s
|
||||
total += s
|
||||
end
|
||||
sizes[count] = limit - p - total
|
||||
elseif lacing == 3 then -- EBML
|
||||
local s, l = Ebml.vint(buf, p, limit)
|
||||
if not s or not l or s < 0 then
|
||||
return
|
||||
end
|
||||
p += l
|
||||
sizes[1] = s
|
||||
local total = s
|
||||
for k = 2, count - 1 do
|
||||
local d, dl = Ebml.svint(buf, p, limit)
|
||||
if not d or not dl then
|
||||
return
|
||||
end
|
||||
p += dl
|
||||
s += d
|
||||
if s < 0 then
|
||||
return
|
||||
end
|
||||
sizes[k] = s
|
||||
total += s
|
||||
end
|
||||
sizes[count] = limit - p - total
|
||||
else -- fixed
|
||||
local each = (limit - p) // count
|
||||
for k = 1, count do
|
||||
sizes[k] = each
|
||||
end
|
||||
end
|
||||
if sizes[count] < 0 then
|
||||
return
|
||||
end
|
||||
end
|
||||
-- frames after the first of a lace: the track's default duration
|
||||
local stepTicks = 0
|
||||
if t.defaultDurationNs and t.defaultDurationNs > 0 then
|
||||
stepTicks = t.defaultDurationNs / ctx.scaleNs
|
||||
elseif durTicks and #sizes > 0 then
|
||||
stepTicks = durTicks / #sizes
|
||||
end
|
||||
local dmx = ctx.dmx
|
||||
for k, s in sizes do
|
||||
if p + s > limit then
|
||||
return
|
||||
end
|
||||
if dmx.n >= ctx.maxPackets then
|
||||
ctx.err = "too many packets"
|
||||
return
|
||||
end
|
||||
local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil)
|
||||
local kf = key and (k == 1 or t.kind ~= "video")
|
||||
local strip = t.strip
|
||||
local z = (t :: any).zlib
|
||||
if z and bit32.band(z, 1) ~= 0 then
|
||||
local out = Deflate.zlib(buf, p, s)
|
||||
if out then
|
||||
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out)
|
||||
end
|
||||
elseif strip then
|
||||
local nb = buffer.create(buffer.len(strip) + s)
|
||||
buffer.copy(nb, 0, strip)
|
||||
buffer.copy(nb, buffer.len(strip), buf, p, s)
|
||||
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb)
|
||||
else
|
||||
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s)
|
||||
end
|
||||
if discardNs and k == #sizes then
|
||||
dmx:setExtra("discardPadding", discardNs / 1e9)
|
||||
end
|
||||
p += s
|
||||
end
|
||||
end
|
||||
|
||||
-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended
|
||||
local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number
|
||||
local buf = ctx.buf
|
||||
local pos = off
|
||||
local time = 0
|
||||
while pos < limit and not ctx.err do
|
||||
local id, size, data = Ebml.header(buf, pos, limit)
|
||||
if not id or not size or not data then
|
||||
return limit
|
||||
end
|
||||
if unknown and TOP[id] then
|
||||
return pos
|
||||
end
|
||||
if size < 0 then
|
||||
size = limit - data -- an unknown-size child: to the end
|
||||
end
|
||||
if data + size > limit then
|
||||
size = limit - data
|
||||
end
|
||||
if id == ID.Timecode then
|
||||
time = Ebml.uint(buf, data, size)
|
||||
elseif id == ID.SimpleBlock then
|
||||
block(ctx, data, size, time, true)
|
||||
elseif id == ID.BlockGroup then
|
||||
local bo, bl = -1, 0
|
||||
local ref, dur, discard = false, nil, nil
|
||||
for id2, o2, n2 in Ebml.children(buf, data, data + size) do
|
||||
if id2 == ID.Block then
|
||||
bo, bl = o2, n2
|
||||
elseif id2 == ID.ReferenceBlock then
|
||||
ref = true
|
||||
elseif id2 == ID.BlockDuration then
|
||||
dur = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.DiscardPadding then
|
||||
discard = Ebml.int(buf, o2, n2)
|
||||
end
|
||||
end
|
||||
if bo >= 0 then
|
||||
block(ctx, bo, bl, time, false, not ref, dur, discard)
|
||||
end
|
||||
end
|
||||
pos = data + size
|
||||
end
|
||||
return pos
|
||||
end
|
||||
|
||||
export type Options = { maxPackets: number? }
|
||||
|
||||
-- parse(buf, base, limit, opts) -> a Demux | nil, Err
|
||||
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
|
||||
local id, size, data = Ebml.header(buf, base, limit)
|
||||
if id ~= ID.EBML or not size or not data then
|
||||
return nil, Err.new(Err.CORRUPT, "not an EBML file", base)
|
||||
end
|
||||
if size < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base)
|
||||
end
|
||||
local docType = "matroska"
|
||||
for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do
|
||||
if cid == ID.DocType then
|
||||
docType = Ebml.string(buf, o, n)
|
||||
end
|
||||
end
|
||||
if docType ~= "matroska" and docType ~= "webm" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType)
|
||||
end
|
||||
local pos = data + size
|
||||
-- the Segment (skip anything else at the top level)
|
||||
local segData, segEnd = -1, limit
|
||||
while pos < limit do
|
||||
local sid, ssize, sdata = Ebml.header(buf, pos, limit)
|
||||
if not sid or not ssize or not sdata then
|
||||
break
|
||||
end
|
||||
if sid == ID.Segment then
|
||||
segData = sdata
|
||||
segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize
|
||||
break
|
||||
end
|
||||
if ssize < 0 then
|
||||
break
|
||||
end
|
||||
pos = sdata + ssize
|
||||
end
|
||||
if segData < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no Segment")
|
||||
end
|
||||
local meta: { [string]: any } = { docType = docType }
|
||||
local scaleNs, duration = 1000000, nil :: number?
|
||||
local tracks: { TrackInfo } = {}
|
||||
local problems: { [number]: string } = {}
|
||||
local cuesAt: { number } = {}
|
||||
local clusters: { { number } } = {}
|
||||
-- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead)
|
||||
pos = segData
|
||||
while pos < segEnd do
|
||||
local cid, csize, cdata = Ebml.header(buf, pos, segEnd)
|
||||
if not cid or not csize or not cdata then
|
||||
break
|
||||
end
|
||||
local unknown = csize < 0
|
||||
local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize
|
||||
if cid == ID.Info then
|
||||
local d
|
||||
scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta)
|
||||
duration = d
|
||||
elseif cid == ID.Tracks then
|
||||
tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs)
|
||||
elseif cid == ID.Cluster then
|
||||
if unknown then
|
||||
-- find its end: walk children until a top-level ID
|
||||
local p = cdata
|
||||
while p < segEnd do
|
||||
local xid, xsize, xdata = Ebml.header(buf, p, segEnd)
|
||||
if not xid or not xsize or not xdata or TOP[xid] then
|
||||
break
|
||||
end
|
||||
if xsize < 0 then
|
||||
p = segEnd
|
||||
break
|
||||
end
|
||||
p = math.min(segEnd, xdata + xsize)
|
||||
end
|
||||
cend = p
|
||||
end
|
||||
table.insert(clusters, { cdata, cend })
|
||||
elseif cid == ID.Cues then
|
||||
table.insert(cuesAt, cdata)
|
||||
table.insert(cuesAt, cend - cdata)
|
||||
elseif cid == ID.Tags then
|
||||
parseTags(buf, cdata, cend - cdata, meta)
|
||||
end
|
||||
if cend <= pos then
|
||||
break
|
||||
end
|
||||
pos = cend
|
||||
end
|
||||
if #tracks == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no tracks")
|
||||
end
|
||||
-- track timescales follow the final TimecodeScale (Info may follow Tracks)
|
||||
local byNum: { [number]: TrackInfo } = {}
|
||||
for _, t in tracks do
|
||||
t.timescale = 1e9 / scaleNs
|
||||
byNum[t.id] = t
|
||||
end
|
||||
local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta)
|
||||
local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 }
|
||||
for _, c in clusters do
|
||||
cluster(ctx, c[1], c[2], false)
|
||||
if ctx.err then
|
||||
return nil, Err.new(Err.LIMIT, ctx.err)
|
||||
end
|
||||
end
|
||||
if duration then
|
||||
dmx.duration = duration * scaleNs / 1e9
|
||||
end
|
||||
local cues = {}
|
||||
for k = 1, #cuesAt, 2 do
|
||||
for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do
|
||||
c.time = c.time * scaleNs / 1e9
|
||||
table.insert(cues, c)
|
||||
end
|
||||
end
|
||||
meta.cues = cues
|
||||
meta.timecodeScale = scaleNs
|
||||
for tid, msg in problems do
|
||||
local t = byNum[tid]
|
||||
t.unsupported = msg
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,160 @@
|
||||
--!strict
|
||||
-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in
|
||||
-- formats-luau, on containers/Ebml.
|
||||
-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing,
|
||||
-- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video
|
||||
-- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio
|
||||
-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text
|
||||
-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone.
|
||||
-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied
|
||||
-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from
|
||||
-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration.
|
||||
-- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored,
|
||||
-- track.unsupported says why), chapters / attachments (skipped), writing subtitles.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
local Parse = require("@formats/video/mkv/Parse")
|
||||
local Mux = require("@formats/video/mkv/Mux")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mkv = {
|
||||
name = "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/Deflate", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
|
||||
track: number?, -- the video track number to decode (default: the first video track)
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
maxPackets: number?, -- refuse files with more packets (default 2^24)
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska
|
||||
webm: boolean?, -- the same as format = "webm"
|
||||
quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90)
|
||||
reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG)
|
||||
video: boolean?, -- false: no video stream
|
||||
audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped)
|
||||
title: string?,
|
||||
clusterSeconds: number?, -- target cluster length (default 2)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true }
|
||||
local WEBM_AUDIO = { opus = true, vorbis = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mkv.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) ~= "\26\69\223\163" then
|
||||
return 0
|
||||
end
|
||||
local head = r:peek(math.min(64, r:remaining()))
|
||||
if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then
|
||||
return 1
|
||||
end
|
||||
return 0.5
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image)
|
||||
-- or a Demuxer
|
||||
function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm")
|
||||
local want: Source.Want
|
||||
if webm then
|
||||
want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } }
|
||||
else
|
||||
local copy: { [string]: boolean } = {}
|
||||
for id, e in Video.codecs do
|
||||
if e.matroska then
|
||||
copy[id] = true
|
||||
end
|
||||
end
|
||||
want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } }
|
||||
end
|
||||
local so = table.clone(o)
|
||||
so.quality = so.quality or 90
|
||||
local streams, err = Source.streams(value, so, want)
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
if not webm then
|
||||
-- audio codecs Matroska cannot name: PCM instead
|
||||
for i, s in streams do
|
||||
if s.kind == "audio" and not Mux.codecId("audio", s.codec) then
|
||||
local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } })
|
||||
if alt and alt[1] then
|
||||
streams[i] = alt[1]
|
||||
else
|
||||
return nil, aerr
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds })
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
|
||||
end
|
||||
return buf, merr
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err
|
||||
function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
|
||||
end
|
||||
return dmx, err
|
||||
end
|
||||
|
||||
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
|
||||
function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Mkv.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil
|
||||
function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles?
|
||||
local track = nil
|
||||
for _, t in dmx.tracks do
|
||||
if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then
|
||||
track = t
|
||||
break
|
||||
end
|
||||
end
|
||||
if not track then
|
||||
return nil
|
||||
end
|
||||
local subs = Types.Subtitles.new()
|
||||
subs.meta.codec = track.codec
|
||||
subs.meta.language = track.language
|
||||
for k = 1, dmx:count(track.id) do
|
||||
local p = dmx:get(track.id, k)
|
||||
if p then
|
||||
local start = p.pts / track.timescale
|
||||
local stop = start + (p.duration or 0) / track.timescale
|
||||
table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) })
|
||||
end
|
||||
end
|
||||
return subs
|
||||
end
|
||||
|
||||
return Mkv
|
||||
@@ -0,0 +1,324 @@
|
||||
--!strict
|
||||
-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on
|
||||
-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in formats-luau.
|
||||
-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first
|
||||
-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as
|
||||
-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/Video registry (MJPEG
|
||||
-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through
|
||||
-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' /
|
||||
-- 'lpcm' / 'ipcm').
|
||||
-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied
|
||||
-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v
|
||||
-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV
|
||||
-- only; MP4 drops other audio unless opts.audio = true, which fails).
|
||||
-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented
|
||||
-- writing, timed text tracks, encrypted tracks.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mp4 = {
|
||||
name = "mp4",
|
||||
category = "video",
|
||||
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", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?,
|
||||
track: number?, -- the video track id (default: the first video track)
|
||||
audio: boolean?,
|
||||
maxPixels: number?,
|
||||
maxSamples: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom')
|
||||
quality: number?, -- MJPEG quality when frames are encoded (default 90)
|
||||
reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied
|
||||
video: boolean?,
|
||||
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true }
|
||||
local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true }
|
||||
-- copied video codecs -> sample entry (MP4 / MOV)
|
||||
local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" }
|
||||
local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mp4.sniff(r: Bytes.Reader): number
|
||||
local brand = IsoBmff.sniff(r)
|
||||
if brand == nil or IMAGE_BRANDS[brand] then
|
||||
return 0
|
||||
end
|
||||
if AUDIO_BRANDS[brand] then
|
||||
return 0.2
|
||||
end
|
||||
if brand == "M4V " then
|
||||
return 0.9
|
||||
end
|
||||
return if brand == "" then 0.6 else 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian)
|
||||
local function opusHead(d: buffer): buffer?
|
||||
if buffer.len(d) < 11 then
|
||||
return nil
|
||||
end
|
||||
local w = Bytes.writer(19 + buffer.len(d))
|
||||
w:string("OpusHead")
|
||||
w:u8(1)
|
||||
local ch = buffer.readu8(d, 1)
|
||||
w:u8(ch)
|
||||
w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3))
|
||||
w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7))
|
||||
w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9))
|
||||
local family = buffer.readu8(d, 10)
|
||||
w:u8(family)
|
||||
if family ~= 0 and buffer.len(d) >= 13 + ch then
|
||||
w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function pcmCodec(t: any): string
|
||||
local p = t.pcm
|
||||
local bits = if p then p.bits else (t.bitsPerSample or 16)
|
||||
if p and p.float then
|
||||
return "pcm_f" .. bits .. (if p.little then "le" else "be")
|
||||
end
|
||||
if bits == 8 then
|
||||
return if t.entry == "raw " then "pcm_u8" else "pcm_s8"
|
||||
end
|
||||
return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be")
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie))
|
||||
end
|
||||
if not movie then
|
||||
return nil, err
|
||||
end
|
||||
local tracks: { Types.Track } = {}
|
||||
local src = {}
|
||||
for _, it in movie.tracks do
|
||||
local t: any = {
|
||||
id = it.id,
|
||||
kind = it.kind,
|
||||
codec = it.codec,
|
||||
codecTag = it.entry,
|
||||
timescale = it.timescale,
|
||||
duration = it.duration,
|
||||
language = it.language,
|
||||
width = it.width,
|
||||
height = it.height,
|
||||
sampleRate = it.sampleRate,
|
||||
channels = it.channels,
|
||||
bitsPerSample = it.bitsPerSample,
|
||||
config = it.config,
|
||||
default = true,
|
||||
}
|
||||
if it.kind == "video" then
|
||||
if not Video.entry(t.codec) then
|
||||
t.codec = Video.fromFourcc(it.entry) or t.codec
|
||||
end
|
||||
if it.sampleCount > 0 and it.duration > 0 then
|
||||
t.frameRate = it.sampleCount / it.duration
|
||||
end
|
||||
elseif it.kind == "audio" then
|
||||
if it.codec == "pcm" then
|
||||
t.codec = pcmCodec(it)
|
||||
elseif it.codec == "ulaw" then
|
||||
t.codec = "pcm_mulaw"
|
||||
elseif it.codec == "alaw" then
|
||||
t.codec = "pcm_alaw"
|
||||
elseif it.codec == "opus" and it.config then
|
||||
t.config = opusHead(it.config)
|
||||
end
|
||||
if it.skip and it.skip > 0 then
|
||||
t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg
|
||||
end
|
||||
end
|
||||
table.insert(tracks, t)
|
||||
table.insert(src, it)
|
||||
end
|
||||
local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand })
|
||||
-- samples in file order across tracks
|
||||
local items: { { number } } = {}
|
||||
for k, it in src do
|
||||
-- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio
|
||||
-- keeps it as its codec delay), plus an initial empty edit (converted to media ticks)
|
||||
local shift = 0
|
||||
if it.kind == "video" then
|
||||
shift = -(it.skip or 0)
|
||||
end
|
||||
if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then
|
||||
shift += it.delay / movie.timescale * it.timescale
|
||||
end
|
||||
for i = 1, it.sampleCount do
|
||||
table.insert(items, { it.offsets[i], k, i, shift })
|
||||
end
|
||||
end
|
||||
table.sort(items, function(a: { number }, b: { number }): boolean
|
||||
return a[1] < b[1]
|
||||
end)
|
||||
for _, e in items do
|
||||
local it = src[e[2]]
|
||||
local i = e[3]
|
||||
local dts = it.dts[i]
|
||||
local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4]
|
||||
dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i])
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- OpusHead -> dOps payload
|
||||
local function dOps(head: buffer?): buffer?
|
||||
if not head or buffer.len(head) < 19 then
|
||||
return nil
|
||||
end
|
||||
local w = Bytes.writer(16)
|
||||
w:u8(0)
|
||||
local ch = buffer.readu8(head, 9)
|
||||
w:u8(ch)
|
||||
w:u16be(buffer.readu16(head, 10))
|
||||
w:u32be(buffer.readu32(head, 12))
|
||||
w:u16be(buffer.readu16(head, 16))
|
||||
local family = buffer.readu8(head, 18)
|
||||
w:u8(family)
|
||||
if family ~= 0 and buffer.len(head) >= 21 + ch then
|
||||
w:bytes(head, 19, 2 + ch)
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
-- encode(video, opts?) -> buffer | nil, Err
|
||||
function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = table.clone(opts or {})
|
||||
o.quality = o.quality or 90
|
||||
local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt")
|
||||
local vcopy: { [string]: boolean } = { mjpeg = true }
|
||||
for id in VIDEO_ENTRY do
|
||||
vcopy[id] = true
|
||||
end
|
||||
local acopy: { [string]: boolean } = {}
|
||||
for id in AUDIO_ENTRY do
|
||||
acopy[id] = true
|
||||
end
|
||||
acopy.pcm_s16le = mov
|
||||
local streams, err = Source.streams(value, o, {
|
||||
video = { copy = vcopy, encode = "mjpeg" },
|
||||
audio = { copy = acopy, pcm = mov },
|
||||
})
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local mtracks = {}
|
||||
for _, s in streams do
|
||||
local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000
|
||||
if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then
|
||||
scale = s.track.timescale
|
||||
end
|
||||
local samples, durations, cts, sync = {}, {}, {}, {}
|
||||
local anyCts = false
|
||||
local firstDts = nil :: number?
|
||||
for i, p in s.packets do
|
||||
samples[i] = p.data
|
||||
local dts = p.dts or p.pts
|
||||
firstDts = firstDts or dts
|
||||
local nextP = s.packets[i + 1]
|
||||
local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration
|
||||
durations[i] = math.max(0, math.floor(d * scale + 0.5))
|
||||
local c = math.floor((p.pts - dts) * scale + 0.5)
|
||||
cts[i] = c
|
||||
if c ~= 0 then
|
||||
anyCts = true
|
||||
end
|
||||
if p.keyframe then
|
||||
sync[i] = true
|
||||
end
|
||||
end
|
||||
-- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay
|
||||
local skip = 0
|
||||
if firstDts and firstDts < 0 then
|
||||
skip = math.floor(-firstDts * scale + 0.5)
|
||||
end
|
||||
if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then
|
||||
skip = math.floor(s.track.codecDelay * scale + 0.5)
|
||||
end
|
||||
local t: any = {
|
||||
kind = s.kind,
|
||||
timescale = scale,
|
||||
skip = if skip > 0 then skip else nil,
|
||||
samples = samples,
|
||||
durations = durations,
|
||||
cts = if anyCts then cts else nil,
|
||||
sync = sync,
|
||||
width = s.width,
|
||||
height = s.height,
|
||||
sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5),
|
||||
channels = s.channels,
|
||||
}
|
||||
if s.kind == "video" then
|
||||
if s.codec == "mjpeg" then
|
||||
t.entry = if mov then "jpeg" else "mp4v"
|
||||
if not mov then
|
||||
t.objectType = 0x6C
|
||||
t.configBox = "esds"
|
||||
t.config = buffer.create(0)
|
||||
end
|
||||
else
|
||||
t.entry = VIDEO_ENTRY[s.codec]
|
||||
t.config = s.config
|
||||
end
|
||||
else
|
||||
if s.codec == "pcm_s16le" then
|
||||
t.entry = "sowt"
|
||||
t.bitsPerSample = 16
|
||||
else
|
||||
t.entry = AUDIO_ENTRY[s.codec]
|
||||
t.config = if s.codec == "opus" then dOps(s.config) else s.config
|
||||
if s.codec == "mp3" then
|
||||
t.objectType = 0x6B
|
||||
t.configBox = "esds"
|
||||
t.config = buffer.create(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
if not t.entry then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec)
|
||||
end
|
||||
table.insert(mtracks, t)
|
||||
end
|
||||
return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Mp4.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Mp4
|
||||
@@ -0,0 +1,192 @@
|
||||
--!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 registry (MPEG-2 detected and reported), 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
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local MpegPs = require("@formats/containers/MpegPs")
|
||||
local MpegEs = require("@formats/containers/MpegEs")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ps = {
|
||||
name = "mpegps",
|
||||
category = "video",
|
||||
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
|
||||
mime = { "video/mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?,
|
||||
track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream)
|
||||
audio: boolean?,
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ps.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "\0\0\1\186" then
|
||||
return 0.9
|
||||
end
|
||||
if r:peek(4) == "\0\0\1\179" then
|
||||
return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header)
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps
|
||||
local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any)
|
||||
local total = 0
|
||||
for _, p in s.pes do
|
||||
total += p.size
|
||||
end
|
||||
local es = buffer.create(total)
|
||||
local starts: { number } = {}
|
||||
local o = 0
|
||||
for i, p in s.pes do
|
||||
starts[i] = o
|
||||
buffer.copy(es, o, buf, p.offset, p.size)
|
||||
o += p.size
|
||||
end
|
||||
local info = MpegEs.info(es, 0, total)
|
||||
if info then
|
||||
t.width, t.height, t.frameRate = info.width, info.height, info.frameRate
|
||||
if info.mpeg2 then
|
||||
t.codec = "mpeg2"
|
||||
end
|
||||
end
|
||||
local pics = MpegEs.pictures(es, 0, total)
|
||||
local fd = if t.frameRate and t.frameRate > 0 then 90000 / t.frameRate else 3600
|
||||
-- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it)
|
||||
local k = 1
|
||||
local used: { [number]: boolean } = {}
|
||||
local ptsOf: { [number]: number } = {}
|
||||
for i, pic in pics do
|
||||
while k < #s.pes and starts[k + 1] <= pic.offset do
|
||||
k += 1
|
||||
end
|
||||
-- a PES whose payload starts inside this picture's headers also labels it
|
||||
local pes = s.pes[k]
|
||||
if pes and pes.pts and not used[k] then
|
||||
used[k] = true
|
||||
ptsOf[i] = pes.pts
|
||||
end
|
||||
end
|
||||
-- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0)
|
||||
local anchorPts, anchorTr = nil :: number?, 0
|
||||
local lastPts = nil :: number?
|
||||
local timed = next(ptsOf) ~= nil
|
||||
local count = 0
|
||||
for i, pic in pics do
|
||||
if pic.gop then
|
||||
anchorPts = nil
|
||||
if not timed then
|
||||
anchorPts, anchorTr = count * fd, 0
|
||||
end
|
||||
end
|
||||
if not timed and anchorPts == nil then
|
||||
anchorPts, anchorTr = count * fd, pic.temporal
|
||||
end
|
||||
count += 1
|
||||
local pts = ptsOf[i]
|
||||
if pts then
|
||||
anchorPts, anchorTr = pts, pic.temporal
|
||||
elseif anchorPts then
|
||||
pts = anchorPts + (pic.temporal - anchorTr) * fd
|
||||
elseif lastPts then
|
||||
pts = lastPts + fd
|
||||
end
|
||||
if pts then
|
||||
lastPts = pts
|
||||
local d = buffer.create(pic.size)
|
||||
buffer.copy(d, 0, es, pic.offset, pic.size)
|
||||
dmx:addData(t.id, pts, nil, fd, pic.type == 1, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
|
||||
if r:peek(4) == "\0\0\1\179" then
|
||||
-- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps
|
||||
local t: any = { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 }
|
||||
local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true })
|
||||
videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t)
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file))
|
||||
end
|
||||
if not file then
|
||||
return nil, err
|
||||
end
|
||||
local tracks: { Types.Track } = {}
|
||||
for _, id in file.order do
|
||||
local s = file.streams[id]
|
||||
table.insert(tracks, {
|
||||
id = id,
|
||||
kind = s.kind :: any,
|
||||
codec = s.codec,
|
||||
codecTag = string.format("0x%02x", id % 256),
|
||||
timescale = 90000,
|
||||
streamId = id,
|
||||
})
|
||||
end
|
||||
local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors })
|
||||
for i, id in file.order do
|
||||
local s = file.streams[id]
|
||||
local t: any = tracks[i]
|
||||
if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then
|
||||
videoPackets(dmx, r.buf, s, t)
|
||||
else
|
||||
local last = nil :: number?
|
||||
for _, p in s.pes do
|
||||
local pts = p.pts or last
|
||||
if pts and p.size > 0 then
|
||||
last = pts
|
||||
dmx:add(id, pts, p.dts, nil, true, p.offset, p.size)
|
||||
end
|
||||
end
|
||||
if t.codec == "mp2" and #s.pes > 0 then
|
||||
local p = s.pes[1]
|
||||
local b = r.buf
|
||||
for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do
|
||||
if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then
|
||||
local layer = (buffer.readu8(b, i2 + 1) // 2) % 4
|
||||
t.codec = if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2"
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
dmx:finish() -- (read() without a track gives the video packets first, then the audio ones)
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Ps.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Ps
|
||||
@@ -0,0 +1,245 @@
|
||||
--!strict
|
||||
-- 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
|
||||
-- registry (stream type 0x02 checked for 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).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local MpegTs = require("@formats/containers/MpegTs")
|
||||
local MpegEs = require("@formats/containers/MpegEs")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ts = {
|
||||
name = "mpegts",
|
||||
category = "video",
|
||||
extensions = { "ts", "m2ts", "mts", "tsv" },
|
||||
mime = { "video/mp2t" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?,
|
||||
track: number?, -- the video PID to decode (default: the first video stream of the PMT)
|
||||
audio: boolean?,
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODEC: { [string]: string } = {
|
||||
mpeg1video = "mpeg1",
|
||||
mpeg2video = "mpeg2",
|
||||
mpegaudio = "mp2",
|
||||
aac = "aac",
|
||||
aac_latm = "aac_latm",
|
||||
h264 = "h264",
|
||||
hevc = "hevc",
|
||||
mpeg4 = "mpeg4",
|
||||
ac3 = "ac3",
|
||||
eac3 = "eac3",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart
|
||||
-- (fewer in a short file) within the first 2 KB
|
||||
local function packetSize(r: Bytes.Reader): (number, number)
|
||||
local n = r:remaining()
|
||||
for start = 0, math.min(n, 2048) - 1 do
|
||||
if r:peekU8(start) == 0x47 then
|
||||
for _, size in { 188, 192 } do
|
||||
local hits, need = 0, math.min(3, (n - start - 1) // size + 1)
|
||||
for k = 0, 2 do
|
||||
local at = start + k * size
|
||||
if at < n and r:peekU8(at) == 0x47 then
|
||||
hits += 1
|
||||
end
|
||||
end
|
||||
if hits >= need and (need >= 2 or start == 0) then
|
||||
if size == 192 and start >= 4 then
|
||||
return 192, start - 4
|
||||
elseif size == 188 then
|
||||
return 188, start
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return 0, 0
|
||||
end
|
||||
|
||||
function Ts.sniff(r: Bytes.Reader): number
|
||||
local s, off = packetSize(r)
|
||||
if s == 0 then
|
||||
return 0
|
||||
end
|
||||
if off > 0 then
|
||||
return 0.6
|
||||
end
|
||||
return if r:remaining() >= 3 * s then 0.9 else 0.5
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps)
|
||||
local function strip192(b: buffer, base: number, limit: number): buffer
|
||||
local n = (limit - base) // 192
|
||||
local out = buffer.create(n * 188)
|
||||
for i = 0, n - 1 do
|
||||
buffer.copy(out, i * 188, b, base + i * 192 + 4, 188)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function mpegAudioCodec(u: any): string
|
||||
local d: buffer = u.data
|
||||
for i = 0, math.min(buffer.len(d), 4096) - 2 do
|
||||
if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then
|
||||
local layer = (buffer.readu8(d, i + 1) // 2) % 4
|
||||
return if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2"
|
||||
end
|
||||
end
|
||||
return "mp2"
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
|
||||
local size, off = packetSize(r)
|
||||
if size == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base)
|
||||
end
|
||||
local d = MpegTs.new()
|
||||
if size == 192 then
|
||||
local b = strip192(r.buf, r.base + off, r.limit)
|
||||
d:push(b, 0, buffer.len(b))
|
||||
else
|
||||
d:push(r.buf, r.base + off, r.limit - r.base - off)
|
||||
end
|
||||
d:flush()
|
||||
local units = {}
|
||||
while true do
|
||||
local u = d:pull()
|
||||
if u == nil then
|
||||
break
|
||||
end
|
||||
table.insert(units, u)
|
||||
end
|
||||
if #units == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no PES units")
|
||||
end
|
||||
-- tracks: the PMT's streams, then PIDs found without one
|
||||
local tracks: { Types.Track } = {}
|
||||
local byPid: { [number]: any } = {}
|
||||
local function track(pid: number, kind: string, codec: string, st: number, lang: string?): any
|
||||
local t = byPid[pid]
|
||||
if t then
|
||||
return t
|
||||
end
|
||||
t = {
|
||||
id = pid,
|
||||
kind = if kind == "other" then "data" else kind,
|
||||
codec = CODEC[codec] or codec,
|
||||
codecTag = string.format("0x%02x", st),
|
||||
timescale = 90000,
|
||||
language = lang,
|
||||
streamType = st,
|
||||
}
|
||||
byPid[pid] = t
|
||||
table.insert(tracks, t)
|
||||
return t
|
||||
end
|
||||
for _, s in d.streams do
|
||||
track(s.pid, s.kind, s.codec, s.streamType, s.language)
|
||||
end
|
||||
for _, u in units do
|
||||
track(u.pid, u.kind, u.codec, u.streamType, nil)
|
||||
end
|
||||
-- codec details from the first unit
|
||||
local seen: { [number]: boolean } = {}
|
||||
for _, u in units do
|
||||
local t = byPid[u.pid]
|
||||
if not seen[u.pid] then
|
||||
seen[u.pid] = true
|
||||
if t.codec == "unknown" or t.kind == "data" then
|
||||
-- a private / unknown stream type: go by the PES stream id and the payload
|
||||
local sid = u.streamId or 0
|
||||
if sid >= 0xE0 and sid <= 0xEF then
|
||||
t.kind = "video"
|
||||
local info = MpegEs.info(u.data, 0, buffer.len(u.data))
|
||||
t.codec = if info then (if info.mpeg2 then "mpeg2" else "mpeg1") elseif MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) then "h264" else "unknown"
|
||||
elseif sid >= 0xC0 and sid <= 0xDF then
|
||||
t.kind, t.codec = "audio", "mp2"
|
||||
end
|
||||
end
|
||||
if t.codec == "mpeg1" or t.codec == "mpeg2" then
|
||||
local info = MpegEs.info(u.data, 0, buffer.len(u.data))
|
||||
if info then
|
||||
t.codec = if info.mpeg2 then "mpeg2" else "mpeg1"
|
||||
t.width, t.height, t.frameRate = info.width, info.height, info.frameRate
|
||||
end
|
||||
elseif t.codec == "mp2" then
|
||||
t.codec = mpegAudioCodec(u)
|
||||
elseif t.codec == "aac" then
|
||||
t.adts = true
|
||||
local b: buffer = u.data
|
||||
if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then
|
||||
local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
t.sampleRate = rates[(buffer.readu8(b, 2) // 4) % 16 + 1]
|
||||
t.channels = (buffer.readu8(b, 2) % 2) * 4 + buffer.readu8(b, 3) // 64
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats })
|
||||
local lastPts: { [number]: number } = {}
|
||||
for _, u in units do
|
||||
local t = byPid[u.pid]
|
||||
local pts = u.pts90 or u.dts90
|
||||
if pts == nil then
|
||||
local prev = lastPts[u.pid]
|
||||
if prev and t.frameRate and t.frameRate > 0 then
|
||||
pts = prev + 90000 / t.frameRate
|
||||
else
|
||||
pts = prev
|
||||
end
|
||||
end
|
||||
if pts ~= nil then
|
||||
lastPts[u.pid] = pts
|
||||
local key = true
|
||||
local data: buffer = u.data
|
||||
if t.kind == "video" then
|
||||
if t.codec == "mpeg1" or t.codec == "mpeg2" then
|
||||
key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1
|
||||
elseif t.codec == "h264" then
|
||||
key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data))
|
||||
else
|
||||
key = u.randomAccess
|
||||
end
|
||||
end
|
||||
dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data)
|
||||
end
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Ts.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Ts
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in formats-luau.
|
||||
-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder
|
||||
-- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono
|
||||
-- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer.
|
||||
-- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8
|
||||
-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta),
|
||||
-- alpha (C444alpha drops it).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Y4m = {
|
||||
name = "y4m",
|
||||
category = "video",
|
||||
extensions = { "y4m" },
|
||||
mime = { "video/x-yuv4mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p)
|
||||
maxPixels: number?, -- default 2^26
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the
|
||||
-- shortest frame, longer frames repeated)
|
||||
maxFps: number?, -- the highest rate uneven frame times may need (default 100)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "YUV4MPEG2 "
|
||||
-- C tag -> pixel format, bits
|
||||
local COLOR: { [string]: { any } } = {
|
||||
["420jpeg"] = { "yuv420p", 8 },
|
||||
["420paldv"] = { "yuv420p", 8 },
|
||||
["420mpeg2"] = { "yuv420p", 8 },
|
||||
["420"] = { "yuv420p", 8 },
|
||||
["422"] = { "yuv422p", 8 },
|
||||
["444"] = { "yuv444p", 8 },
|
||||
["444alpha"] = { "yuva444p", 8 },
|
||||
mono = { "gray", 8 },
|
||||
}
|
||||
for _, b in { 9, 10, 12, 14, 16 } do
|
||||
COLOR["420p" .. b] = { "yuv420p", b }
|
||||
COLOR["422p" .. b] = { "yuv422p", b }
|
||||
COLOR["444p" .. b] = { "yuv444p", b }
|
||||
COLOR["mono" .. b] = { "gray", b }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Y4m.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(10) == MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function frameSize(pf: string, bits: number, w: number, h: number): number
|
||||
local bps = if bits > 8 then 2 else 1
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
if pf == "yuv420p" then
|
||||
return (w * h + 2 * cw * ch) * bps
|
||||
elseif pf == "yuv422p" then
|
||||
return (w * h + 2 * cw * h) * bps
|
||||
elseif pf == "yuv444p" then
|
||||
return w * h * 3 * bps
|
||||
elseif pf == "yuva444p" then
|
||||
return w * h * 4 * bps
|
||||
end
|
||||
return w * h * bps
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the raw-video Demuxer | nil, Err
|
||||
function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local buf, base, limit = r.buf, r.base, r.limit
|
||||
local nl = -1
|
||||
for i = base, math.min(limit, base + 4096) - 1 do
|
||||
if buffer.readu8(buf, i) == 10 then
|
||||
nl = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base)
|
||||
end
|
||||
if nl < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base)
|
||||
end
|
||||
local header = buffer.readstring(buf, base + 10, nl - base - 10)
|
||||
local w, h, fn, fd = 0, 0, 25, 1
|
||||
local ctag, itag, atag = "420jpeg", "p", "0:0"
|
||||
local extra = {}
|
||||
for tok in string.gmatch(header, "%S+") do
|
||||
local k, v = string.sub(tok, 1, 1), string.sub(tok, 2)
|
||||
if k == "W" then
|
||||
w = tonumber(v) or 0
|
||||
elseif k == "H" then
|
||||
h = tonumber(v) or 0
|
||||
elseif k == "F" then
|
||||
local a, b = string.match(v, "^(%d+):(%d+)$")
|
||||
if a and b and tonumber(a) > 0 and tonumber(b) > 0 then
|
||||
fn, fd = tonumber(a) :: number, tonumber(b) :: number
|
||||
end
|
||||
elseif k == "C" then
|
||||
ctag = v
|
||||
elseif k == "I" then
|
||||
itag = v
|
||||
elseif k == "A" then
|
||||
atag = v
|
||||
elseif k == "X" then
|
||||
table.insert(extra, v)
|
||||
end
|
||||
end
|
||||
local color = COLOR[ctag]
|
||||
if not color then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag)
|
||||
end
|
||||
if w <= 0 or h <= 0 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels")
|
||||
end
|
||||
local pf, bits = color[1], color[2]
|
||||
local size = frameSize(pf, bits, w, h)
|
||||
local track: Types.Track = {
|
||||
id = 1,
|
||||
kind = "video",
|
||||
codec = "rawvideo",
|
||||
codecTag = "C" .. ctag,
|
||||
timescale = fn / fd,
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = fn / fd,
|
||||
pixelFormat = pf,
|
||||
bitDepth = bits,
|
||||
default = true,
|
||||
}
|
||||
local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag }
|
||||
local dmx = Demux.new("y4m", { track }, buf, meta)
|
||||
local pos = nl + 1
|
||||
local k = 0
|
||||
while pos + 5 <= limit do
|
||||
if buffer.readstring(buf, pos, 5) ~= "FRAME" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected FRAME", pos)
|
||||
end
|
||||
local e = -1
|
||||
for i = pos + 5, math.min(limit, pos + 4096) - 1 do
|
||||
if buffer.readu8(buf, i) == 10 then
|
||||
e = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if e < 0 then
|
||||
break
|
||||
end
|
||||
local data = e + 1
|
||||
if data + size > limit then
|
||||
break -- a truncated last frame is dropped
|
||||
end
|
||||
dmx:add(1, k, k, 1, true, data, size)
|
||||
k += 1
|
||||
pos = data + size
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err
|
||||
function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } })
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local s = streams[1]
|
||||
local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps)
|
||||
if opts and type(opts.frameRate) == "table" then
|
||||
fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets
|
||||
end
|
||||
s.packets = packets
|
||||
local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6))
|
||||
w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd))
|
||||
for _, p in s.packets do
|
||||
w:string("FRAME\n")
|
||||
w:bytes(p.data)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Y4m.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Y4m
|
||||
@@ -0,0 +1,273 @@
|
||||
-- codecs/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through
|
||||
-- image/jpeg): ffmpeg mjpeg frames (4:2:0, 4:2:2, 4:4:4, odd sizes, stripped DHT, AVI1 + junk after EOI) decoded
|
||||
-- to yuv420p bit-exact with libjpeg-turbo's IDCT planes (TurboJPEG) and to rgba8 bit-exact with djpeg, and within
|
||||
-- PSNR thresholds of ffmpeg's own decode; an interlaced AVI1 frame (two fields) woven; the yuv420p encoder
|
||||
-- byte-identical to TurboJPEG's tj3CompressFromYUV8, read back by djpeg (exact) and ffmpeg (PSNR); the API's
|
||||
-- arguments; the fuzz no-throw pass. Fixtures: tools/fixtures/mjpeg.py.
|
||||
local T = require("@tests/T")
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Fx = require("@tests/gen/mjpeg_cases")
|
||||
local Enc = require("@tests/gen/mjpeg_enc")
|
||||
|
||||
local t = T.suite("codecs/jpeg")
|
||||
|
||||
-- the fixtures' binary fields: base64, and base64 of zlib data for raw planes / pixels
|
||||
local function b64(s: string): string
|
||||
return buffer.tostring(Base64.decode(s) :: buffer)
|
||||
end
|
||||
local function z64(s: string): buffer
|
||||
return Deflate.zlib(Base64.decode(s) :: buffer) :: buffer
|
||||
end
|
||||
for _, s in Fx.streams do
|
||||
for _, f in s.frames do
|
||||
f.data = b64(f.data)
|
||||
end
|
||||
s.ff.yuv = z64(s.ff.yuv)
|
||||
if s.ff.rgba then
|
||||
s.ff.rgba = z64(s.ff.rgba)
|
||||
end
|
||||
end
|
||||
Fx.fields.data = b64(Fx.fields.data)
|
||||
for _, c in Enc do
|
||||
c.want = b64(c.want)
|
||||
end
|
||||
|
||||
-- PSNR of n bytes of a at ao against b at bo
|
||||
local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return 99
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * n / se)
|
||||
end
|
||||
|
||||
-- PSNR of the RGB channels of two rgba8 buffers of n pixels
|
||||
local function psnrRgb(a: buffer, b: buffer, n: number): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
for k = 0, 2 do
|
||||
local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * 4 + k)
|
||||
se += d * d
|
||||
end
|
||||
end
|
||||
if se == 0 then
|
||||
return 99
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * n * 3 / se)
|
||||
end
|
||||
|
||||
local function hasDht(s: string): boolean
|
||||
local at = string.find(s, "\255\196", 1, true)
|
||||
local sos = string.find(s, "\255\218", 1, true)
|
||||
return at ~= nil and sos ~= nil and at < sos
|
||||
end
|
||||
|
||||
-- 1. ffmpeg's frames: yuv420p (TurboJPEG planes) and rgba8 (djpeg) bit-exact, PSNR against ffmpeg's decode
|
||||
do
|
||||
local frames, worstY, worstC, worstRgb = 0, 99, 99, 99
|
||||
for _, s in Fx.streams do
|
||||
local w, h = s.width, s.height
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
for i, f in s.frames do
|
||||
local label = string.format("%s frame %d", s.name, i)
|
||||
local b = buffer.fromstring(f.data)
|
||||
local img, err = Jpeg.decode(b, 0, buffer.len(b), { yuv = true })
|
||||
t:check(img, label .. ": " .. tostring(err))
|
||||
t:check(img.format == "yuv420p" and img.width == w and img.height == h, label .. ": a yuv420p " .. w .. "x" .. h .. " Image")
|
||||
t:eq(buffer.len(img.pixels), w * h + 2 * cw * ch, label .. ": plane sizes")
|
||||
t:check(img.meta.source.yuv == s.sampling and img.meta.source.range == "full", label .. ": meta.source.yuv " .. tostring(img.meta.source.yuv))
|
||||
t:check(not img.meta.truncated, label .. ": not truncated")
|
||||
t:eq(Crc32.of(img.pixels), f.yuv, label .. ": yuv420p planes = TurboJPEG's")
|
||||
local rgba = Jpeg.decode(b) :: Types.Image
|
||||
t:check(rgba and rgba.format == "rgba8", label .. ": rgba8")
|
||||
t:eq(Crc32.of(rgba.pixels), f.rgba, label .. ": rgba8 = djpeg")
|
||||
if i == 1 then
|
||||
local ref = s.ff.yuv
|
||||
local py = psnr(img.pixels, 0, ref, 0, w * h)
|
||||
local pc = math.min(psnr(img.pixels, w * h, ref, w * h, cw * ch), psnr(img.pixels, w * h + cw * ch, ref, w * h + cw * ch, cw * ch))
|
||||
-- ffmpeg's IDCT differs from libjpeg's islow by rounding only; its 4:2:2 / 4:4:4 -> 4:2:0 is a filter
|
||||
t:check(py > 55, string.format("%s: luma PSNR %.1f dB against ffmpeg", s.name, py))
|
||||
t:check(pc > (if s.sampling == "420" then 55 else 20), string.format("%s: chroma PSNR %.1f dB against ffmpeg", s.name, pc))
|
||||
worstY, worstC = math.min(worstY, py), math.min(worstC, pc)
|
||||
if s.ff.rgba then
|
||||
local pr = psnrRgb(rgba.pixels, s.ff.rgba, w * h)
|
||||
-- swscale upsamples chroma differently from libjpeg (fancy): testsrc2's sharp colour edges cost ~10 dB
|
||||
t:check(pr > 25, string.format("%s: rgba PSNR %.1f dB against ffmpeg", s.name, pr))
|
||||
worstRgb = math.min(worstRgb, pr)
|
||||
end
|
||||
end
|
||||
if string.find(s.name, "nodht") then
|
||||
t:check(not hasDht(f.data), label .. ": no DHT segment")
|
||||
end
|
||||
if s.name == "avi1_junk" then
|
||||
t:eq(img.meta.source.avi1, 0, label .. ": AVI1 polarity")
|
||||
t:eq(Jpeg.info(b).avi1, 0, label .. ": info.avi1")
|
||||
end
|
||||
frames += 1
|
||||
end
|
||||
end
|
||||
t:note("%d ffmpeg mjpeg frames bit-exact (yuv420p: TurboJPEG, rgba8: djpeg); worst PSNR against ffmpeg: luma %.1f, chroma %.1f, rgba %.1f dB", frames, worstY, worstC, worstRgb)
|
||||
end
|
||||
|
||||
-- 2. an interlaced frame: two fields (AVI1 polarity 1) woven, field 1 on the even rows
|
||||
do
|
||||
local F = Fx.fields
|
||||
local b = buffer.fromstring(F.data)
|
||||
local img = Jpeg.decode(b, 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(img and img.width == F.width and img.height == F.height and img.format == "yuv420p", "fields: one 320x240 yuv420p frame")
|
||||
t:eq(img.meta.source.fields, 2, "fields: meta.source.fields")
|
||||
t:eq(Crc32.of(img.pixels), F.yuv, "fields: woven yuv420p planes = TurboJPEG's fields woven")
|
||||
local src = z64(F.src)
|
||||
local p = psnr(img.pixels, 0, src, 0, F.width * F.height)
|
||||
t:check(p > 35, string.format("fields: luma PSNR %.1f dB against the source frame", p))
|
||||
local rgba = Jpeg.decode(b) :: Types.Image
|
||||
t:check(rgba.height == F.height and Crc32.of(rgba.pixels) == F.rgba, "fields: woven rgba8 = djpeg's fields woven")
|
||||
local one = Jpeg.decode(b, 0, nil, { yuv = true, fields = false }) :: Types.Image
|
||||
t:check(one.height == F.height // 2 and one.meta.source.fields == 1, "fields = false: the first field only")
|
||||
-- the first field alone (no second JPEG): a half-height frame, not an error
|
||||
local first = string.find(F.data, "\255\217", 1, true) :: number
|
||||
local half = Jpeg.decode(buffer.fromstring(string.sub(F.data, 1, first + 1)), 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(half and half.height == F.height // 2 and half.meta.source.fields == 1, "a missing second field leaves the first")
|
||||
t:check(Jpeg.info(b).avi1 == 1, "fields: info.avi1")
|
||||
end
|
||||
|
||||
-- 3. the yuv420p encoder: byte-identical with TurboJPEG, read back by djpeg (exact) and ffmpeg (PSNR)
|
||||
do
|
||||
local exact = 0
|
||||
for _, c in Enc do
|
||||
local img = Types.Image.new(c.width, c.height, "yuv420p")
|
||||
img.pixels = z64(c.yuv)
|
||||
local out, err = Jpeg.encode(img, { quality = c.quality })
|
||||
t:check(out, c.name .. ": " .. tostring(err))
|
||||
local s = buffer.tostring(out :: buffer)
|
||||
if s ~= c.want then
|
||||
local at = 0
|
||||
for i = 1, math.min(#s, #c.want) do
|
||||
if string.byte(s, i) ~= string.byte(c.want, i) then
|
||||
at = i
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(false, string.format("%s: differs from tj3CompressFromYUV8 at byte %d (ours %d bytes, TurboJPEG %d)", c.name, at, #s, #c.want))
|
||||
end
|
||||
exact += 1
|
||||
local back = Jpeg.decode(out :: buffer) :: Types.Image
|
||||
t:eq(Crc32.of(back.pixels), c.rgba, c.name .. ": our decode of it = djpeg's")
|
||||
local floor = if c.quality >= 75 then 30 else 26
|
||||
if c.width * c.height >= 1000 then
|
||||
t:check(c.ffpsnr > floor, string.format("%s: ffmpeg reads it at %.1f dB luma PSNR", c.name, c.ffpsnr))
|
||||
local y = Jpeg.decode(out :: buffer, 0, nil, { yuv = true }) :: Types.Image
|
||||
local p = psnr(y.pixels, 0, img.pixels, 0, c.width * c.height)
|
||||
t:check(p > floor, string.format("%s: yuv round trip %.1f dB", c.name, p))
|
||||
end
|
||||
end
|
||||
t:note("%d yuv420p encodes byte-identical with tj3CompressFromYUV8", exact)
|
||||
-- grey from yuv420p: the luma plane only
|
||||
local c = Enc[1]
|
||||
local img = Types.Image.new(c.width, c.height, "yuv420p")
|
||||
img.pixels = z64(c.yuv)
|
||||
local g = Jpeg.encode(img, { quality = 80, gray = true }) :: buffer
|
||||
local gi = Jpeg.info(g)
|
||||
t:check(gi and gi.components == 1, "yuv420p with gray = true: one component")
|
||||
local gy = Jpeg.decode(g, 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(gy.format == "yuv420p" and gy.meta.source.yuv == "gray" and buffer.readu8(gy.pixels, c.width * c.height) == 128, "grey decodes to yuv420p with chroma 128")
|
||||
local p = Jpeg.encode(img, { quality = 80, progressive = true, restart = 2 }) :: buffer
|
||||
local pi = Jpeg.info(p)
|
||||
t:check(pi and pi.progressive and pi.sampling[1][1] == 2 and pi.sampling[1][2] == 2, "yuv420p progressive")
|
||||
local pd = Jpeg.decode(p, 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(psnr(pd.pixels, 0, img.pixels, 0, c.width * c.height) > 30, "yuv420p progressive round trip")
|
||||
local s4 = Jpeg.encode(img, { subsampling = "444" }) :: buffer
|
||||
t:eq(Jpeg.info(s4).sampling[1][1], 2, "yuv420p input is always 4:2:0")
|
||||
-- extra segments and density
|
||||
local seg = Jpeg.encode(img, { segments = { { marker = 0xFE, data = buffer.fromstring("hello") } }, density = { unit = 1, x = 72, y = 72 } }) :: buffer
|
||||
local sd = Jpeg.decode(seg) :: Types.Image
|
||||
t:check(sd.meta.text and sd.meta.text.comment == "hello" and sd.meta.dpi and sd.meta.dpi.x == 72, "segments and density")
|
||||
end
|
||||
|
||||
-- 4. the API: ranges, options, fallbacks, errors
|
||||
do
|
||||
local s = Fx.streams[1]
|
||||
local data = s.frames[1].data
|
||||
local big = buffer.create(#data + 30)
|
||||
buffer.writestring(big, 17, data)
|
||||
local a = Jpeg.decode(big, 17, #data, { yuv = true }) :: Types.Image
|
||||
t:eq(Crc32.of(a.pixels), s.frames[1].yuv, "decode from a sub-range")
|
||||
local i = Jpeg.info(big, 17, #data)
|
||||
t:check(i and i.width == s.width and i.colorSpace == "ycbcr" and i.sampling[1][2] == 2, "info from a sub-range")
|
||||
local sc = Jpeg.decode(buffer.fromstring(data), 0, nil, { yuv = true, scale = 2 }) :: Types.Image
|
||||
t:check(sc.format == "rgba8" and sc.width == s.width // 2, "yuv with scale 2 falls back to rgba8")
|
||||
local _, e1 = Jpeg.decode("nope" :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "decode(string)")
|
||||
local _, e2 = Jpeg.decode(buffer.fromstring("nope"))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "junk")
|
||||
local _, e3 = Jpeg.decode(buffer.fromstring(data), 0, nil, { maxPixels = 100, yuv = true })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "maxPixels")
|
||||
local _, e4 = Jpeg.decode(buffer.fromstring(data), 0, nil, 5 :: any)
|
||||
t:check(e4 and e4.code == Err.ARG, "non-table options")
|
||||
local _, e5 = Jpeg.encode(Types.Image.new(4, 4, "rgba16"))
|
||||
t:check(e5 and e5.code == Err.ARG, "rgba16 is refused")
|
||||
local short = Types.Image.new(8, 8, "yuv420p")
|
||||
short.pixels = buffer.create(70)
|
||||
local _, e6 = Jpeg.encode(short)
|
||||
t:check(e6 and e6.code == Err.ARG, "a short yuv420p buffer")
|
||||
local _, e7 = Jpeg.encode(Types.Image.new(8, 8), { segments = { { marker = 0xC4, data = buffer.create(1) } } })
|
||||
t:check(e7 and e7.code == Err.ARG, "a bad segment marker")
|
||||
local _, e8 = Jpeg.info(buffer.create(0))
|
||||
t:check(e8 and Err.is(e8), "info of nothing")
|
||||
-- truncated frames decode as far as they go or fail with an Err
|
||||
local cuts, partial = 0, 0
|
||||
for cut = 0, #data - 1, #data // 37 do
|
||||
local img, err = Jpeg.decode(buffer.fromstring(string.sub(data, 1, cut)), 0, nil, { yuv = true })
|
||||
t:check(img or Err.is(err), "cut at " .. cut .. ": no image and no Err")
|
||||
if img then
|
||||
partial += 1
|
||||
t:check(img.meta.truncated, "cut at " .. cut .. ": flagged truncated")
|
||||
end
|
||||
cuts += 1
|
||||
end
|
||||
t:note("%d truncated frames, %d decoded partially", cuts, partial)
|
||||
end
|
||||
|
||||
-- 5. speed (a note; tools/bench.luau has the real numbers)
|
||||
do
|
||||
local s = Fx.streams[1]
|
||||
local frames = {}
|
||||
for _, f in s.frames do
|
||||
table.insert(frames, buffer.fromstring(f.data))
|
||||
end
|
||||
local t0, n = os.clock(), 0
|
||||
while os.clock() - t0 < 0.3 do
|
||||
for _, b in frames do
|
||||
Jpeg.decode(b, 0, nil, { yuv = true })
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
t:note("%dx%d yuv420p decode: %.0f fps", s.width, s.height, n / (os.clock() - t0))
|
||||
end
|
||||
|
||||
-- 6. fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for k, s in Fx.streams do
|
||||
if k % 2 == 1 then
|
||||
table.insert(samples, s.frames[1].data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode yuv", function(b: buffer)
|
||||
return Jpeg.decode(b, 0, nil, { yuv = true })
|
||||
end, samples, { mutations = 4, keepHeader = 2 })
|
||||
t:fuzz("decode fields", function(b: buffer)
|
||||
return Jpeg.decode(b, 0, nil, { fields = true })
|
||||
end, { Fx.fields.data }, { mutations = 3, garbage = 10 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,413 @@
|
||||
-- codecs/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. 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;
|
||||
-- the same stream written in random pieces through write() / decodeFrame() gives identical frames; a size change.
|
||||
-- Robustness / API: bad arguments, pictures before the first sequence header, reset(), rgba = false, tags through
|
||||
-- B-frame reordering, string input, truncated units, bit flips and garbage (never throws, recovers at an
|
||||
-- I-picture), an oversized sequence header; frameImage; the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local Mpeg1 = require("@formats/codecs/Mpeg1")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local STREAMS = {
|
||||
require("@tests/gen/mpeg1_qcif_200k"),
|
||||
require("@tests/gen/mpeg1_main_450k"),
|
||||
require("@tests/gen/mpeg1_zoom_150k"),
|
||||
require("@tests/gen/mpeg1_zoom_1500k"),
|
||||
require("@tests/gen/mpeg1_big_1000k"),
|
||||
require("@tests/gen/mpeg1_odd_173x95"),
|
||||
require("@tests/gen/mpeg1_matrix"),
|
||||
require("@tests/gen/mpeg1_q1"),
|
||||
require("@tests/gen/mpeg1_q31"),
|
||||
require("@tests/gen/mpeg1_zeromv"),
|
||||
require("@tests/gen/mpeg1_bframes"),
|
||||
require("@tests/gen/mpeg1_bframes_zoom"),
|
||||
}
|
||||
local SizeChange = require("@tests/gen/mpeg1_sizechange")
|
||||
|
||||
local t = T.suite("codecs/mpeg1")
|
||||
local rand = T.rng(7)
|
||||
local function between(a: number, b: number): number
|
||||
return a + rand(b - a + 1)
|
||||
end
|
||||
|
||||
local function b64(s: string): buffer
|
||||
return Base64.decode(s) :: buffer
|
||||
end
|
||||
local function z64(s: string): buffer
|
||||
return Deflate.zlib(b64(s)) :: buffer
|
||||
end
|
||||
|
||||
-- mean absolute error per channel (r, g, b) between two RGBA8 buffers of n pixels, and the largest difference
|
||||
local function mae(a: buffer, b: buffer, n: number): (number, number, number, number)
|
||||
local sr, sg, sb, mx = 0, 0, 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
local dr = math.abs(buffer.readu8(a, o) - buffer.readu8(b, o))
|
||||
local dg = math.abs(buffer.readu8(a, o + 1) - buffer.readu8(b, o + 1))
|
||||
local db = math.abs(buffer.readu8(a, o + 2) - buffer.readu8(b, o + 2))
|
||||
sr += dr
|
||||
sg += dg
|
||||
sb += db
|
||||
mx = math.max(mx, dr, dg, db)
|
||||
end
|
||||
return sr / n, sg / n, sb / n, mx
|
||||
end
|
||||
|
||||
local function means(a: buffer, n: number): (number, number, number)
|
||||
local r, g, b = 0, 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
r += buffer.readu8(a, o)
|
||||
g += buffer.readu8(a, o + 1)
|
||||
b += buffer.readu8(a, o + 2)
|
||||
end
|
||||
return r / n, g / n, b / n
|
||||
end
|
||||
|
||||
local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return 99
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * n / se)
|
||||
end
|
||||
|
||||
local MAE_LIMIT = 2
|
||||
local MEAN_LIMIT = 1.5
|
||||
|
||||
-- 1. every stream against ffmpeg
|
||||
local worst, worstY, worstC = 0, 99, 99
|
||||
for _, fx in STREAMS do
|
||||
local name = fx.name
|
||||
local file = b64(fx.file)
|
||||
local w, h = fx.width, fx.height
|
||||
local n = w * h
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local rgbaRef, yuvRef = {}, {}
|
||||
for _, s in fx.rgba do
|
||||
rgbaRef[s.index] = z64(s.pixels)
|
||||
end
|
||||
for _, s in fx.yuv do
|
||||
yuvRef[s.index] = z64(s.planes)
|
||||
end
|
||||
local hasB = string.find(name, "bframes") ~= nil
|
||||
local dec = Mpeg1.new({ reorder = hasB })
|
||||
local frames = 0
|
||||
local maxMae, maxMeanErr = 0, 0
|
||||
local sums = {}
|
||||
local function onFrame(f: any)
|
||||
frames += 1
|
||||
t:check(f.width == w and f.height == h, string.format("%s: size %dx%d", name, f.width, f.height))
|
||||
t:eq(f.index, frames, name .. ": frame index")
|
||||
local px = f.pixels :: buffer
|
||||
t:eq(buffer.len(px), n * 4, name .. ": pixels size")
|
||||
local ref = fx.means[frames]
|
||||
t:check(ref ~= nil, string.format("%s: more frames than ffmpeg (%d)", name, frames))
|
||||
local r, g, b = means(px, n)
|
||||
local me = math.max(math.abs(r - ref[1]), math.abs(g - ref[2]), math.abs(b - ref[3]))
|
||||
maxMeanErr = math.max(maxMeanErr, me)
|
||||
t:check(me <= MEAN_LIMIT, string.format("%s frame %d: channel means off by %.2f", name, frames, me))
|
||||
local s = rgbaRef[frames]
|
||||
if s then
|
||||
local mr, mg, mb = mae(px, s, n)
|
||||
local m = math.max(mr, mg, mb)
|
||||
maxMae = math.max(maxMae, m)
|
||||
t:check(m <= MAE_LIMIT, string.format("%s frame %d: MAE %.3f %.3f %.3f", name, frames, mr, mg, mb))
|
||||
local again = Mpeg1.frameImage(f, true) :: Types.Image
|
||||
t:check(again.format == "rgba8" and buffer.tostring(again.pixels) == buffer.tostring(px), name .. ": frameImage(f, true) = frame.pixels")
|
||||
end
|
||||
local y = yuvRef[frames]
|
||||
if y then
|
||||
local img = Mpeg1.frameImage(f) :: Types.Image
|
||||
t:check(img.format == "yuv420p" and img.width == w and img.height == h and buffer.len(img.pixels) == n + 2 * cw * ch, name .. ": frameImage yuv420p")
|
||||
t:check(img.meta.source.range == "limited" and img.meta.source.pictureType == f.pictureType, name .. ": frameImage meta")
|
||||
local py = psnr(img.pixels, 0, y, 0, n)
|
||||
local pc = psnr(img.pixels, n, y, n, 2 * cw * ch)
|
||||
worstY, worstC = math.min(worstY, py), math.min(worstC, pc)
|
||||
t:check(py > 50 and pc > 50, string.format("%s frame %d: yuv420p PSNR %.1f / %.1f dB against ffmpeg", name, frames, py, pc))
|
||||
end
|
||||
t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255")
|
||||
sums[frames] = buffer.tostring(px)
|
||||
end
|
||||
local t0 = os.clock()
|
||||
for _, u in fx.units do
|
||||
local f = dec:decode(file, u[1], u[2])
|
||||
if f then
|
||||
onFrame(f)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local f = dec:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
onFrame(f)
|
||||
end
|
||||
local dt = os.clock() - t0
|
||||
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)
|
||||
|
||||
-- streamed: random pieces through write / decodeFrame, then flush
|
||||
local d2 = Mpeg1.new({ reorder = hasB })
|
||||
local got = 0
|
||||
local p, total = 0, buffer.len(file)
|
||||
local function take(f: any)
|
||||
got += 1
|
||||
t:check(sums[got] == buffer.tostring(f.pixels :: buffer), string.format("%s streamed frame %d identical", name, got))
|
||||
end
|
||||
while p < total do
|
||||
local k = math.min(total - p, between(1, 6000))
|
||||
t:check(d2:write(file, p, k), "write")
|
||||
p += k
|
||||
while true do
|
||||
local f = d2:decodeFrame()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
take(f)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local f = d2:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
take(f)
|
||||
end
|
||||
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)
|
||||
|
||||
-- 2. a size change mid-stream
|
||||
do
|
||||
local file = b64(SizeChange.file)
|
||||
local dec = Mpeg1.new()
|
||||
dec:write(file)
|
||||
local list = {}
|
||||
while true do
|
||||
local f = dec:decodeFrame() or dec:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
table.insert(list, { w = f.width, h = f.height, px = buffer.tostring(f.pixels :: buffer) })
|
||||
end
|
||||
local a, b = SizeChange.parts[1], SizeChange.parts[2]
|
||||
t:eq(#list, a.frames + b.frames, "sizechange: frame count")
|
||||
t:check(list[1].w == a.width and list[1].h == a.height, "sizechange: first size")
|
||||
t:check(list[a.frames].w == a.width and list[a.frames + 1].w == b.width and list[#list].h == b.height, "sizechange: second size")
|
||||
for k, part in { a, b } do
|
||||
local last = list[if k == 1 then a.frames else #list]
|
||||
local mr, mg, mb = mae(buffer.fromstring(last.px), z64(part.last), part.width * part.height)
|
||||
t:check(math.max(mr, mg, mb) <= MAE_LIMIT, string.format("sizechange part %d MAE %.3f %.3f %.3f", k, mr, mg, mb))
|
||||
end
|
||||
end
|
||||
|
||||
-- 3. robustness and the API
|
||||
local function slice(b: buffer, from: number, n: number): buffer
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, from, n)
|
||||
return out
|
||||
end
|
||||
local main = STREAMS[2]
|
||||
local mainFile = b64(main.file)
|
||||
local W, H = main.width, main.height
|
||||
local ref = {}
|
||||
do
|
||||
local dec = Mpeg1.new()
|
||||
for _, u in main.units do
|
||||
local f = dec:decode(mainFile, u[1], u[2])
|
||||
table.insert(ref, buffer.tostring((f :: any).pixels))
|
||||
end
|
||||
t:eq(#ref, #main.units, "reference decode")
|
||||
end
|
||||
|
||||
do -- bad arguments
|
||||
local dec = Mpeg1.new()
|
||||
t:check(dec:decode((nil :: any)) == nil, "decode(nil)")
|
||||
t:check(dec:decode((42 :: any)) == nil, "decode(number)")
|
||||
t:check(dec:write(buffer.create(4), 10) == false, "write offset past the end")
|
||||
t:check(dec:write(buffer.create(4), 0, 9) == false, "write length past the end")
|
||||
t:check(dec:write(buffer.create(4), -1) == false, "write negative offset")
|
||||
t:check(dec:decodeFrame() == nil, "decodeFrame with no data")
|
||||
t:check(dec:flush() == nil, "flush with no data")
|
||||
t:check(Mpeg1.new((5 :: any)) ~= nil, "new(non-table)")
|
||||
t:check(dec:decode(buffer.create(0)) == nil, "empty unit")
|
||||
t:check(Mpeg1.frameImage(nil :: any) == nil and Mpeg1.frameImage({} :: any) == nil, "frameImage of a non-frame")
|
||||
end
|
||||
|
||||
do -- string input; pictures before the first sequence header are skipped
|
||||
local dec = Mpeg1.new()
|
||||
local u2 = main.units[2]
|
||||
t:check(dec:decode(buffer.tostring(slice(mainFile, u2[1], u2[2]))) == nil, "P picture before any sequence header")
|
||||
local u1 = main.units[1]
|
||||
local f = dec:decode(buffer.tostring(slice(mainFile, u1[1], u1[2])))
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "string unit decodes")
|
||||
t:check(dec.width == W and dec.height == H and math.abs(dec.frameRate - 24) < 0.01, "sequence fields")
|
||||
t:check(f.pictureType == Mpeg1.PICTURE_I and f.codedWidth == 320 and buffer.len(f.y) == 320 * 192, "frame fields")
|
||||
t:eq(dec.stats.skipped, 1, "stats.skipped")
|
||||
end
|
||||
|
||||
do -- rgba = false: planes only, frameImage still gives both
|
||||
local dec = Mpeg1.new({ rgba = false })
|
||||
local u1 = main.units[1]
|
||||
local f = dec:decode(mainFile, u1[1], u1[2]) :: any
|
||||
t:check(f ~= nil and f.pixels == nil and buffer.len(f.y) > 0 and buffer.len(f.cb) == buffer.len(f.y) // 4, "rgba = false")
|
||||
local img = Mpeg1.frameImage(f, true) :: Types.Image
|
||||
t:check(img and buffer.tostring(img.pixels) == ref[1], "frameImage(f, true) after rgba = false")
|
||||
local y = Mpeg1.frameImage(f) :: Types.Image
|
||||
t:check(y.format == "yuv420p" and buffer.readu8(y.pixels, W) == buffer.readu8(f.y, f.codedWidth), "frameImage crops the coded width")
|
||||
end
|
||||
|
||||
do -- reset (seek): the next picture must be an I-picture again
|
||||
local dec = Mpeg1.new()
|
||||
for i = 1, 5 do
|
||||
local u = main.units[i]
|
||||
dec:decode(mainFile, u[1], u[2])
|
||||
end
|
||||
dec:reset()
|
||||
local u = main.units[10]
|
||||
t:check(dec:decode(mainFile, u[1], u[2]) == nil, "P after reset has no reference")
|
||||
u = main.units[1]
|
||||
local f = dec:decode(mainFile, u[1], u[2])
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "I after reset")
|
||||
end
|
||||
|
||||
do -- tags (pts) follow pictures through reordering
|
||||
local fx = STREAMS[11]
|
||||
local b = b64(fx.file)
|
||||
local dec = Mpeg1.new({ reorder = true, rgba = false })
|
||||
local order = {}
|
||||
for i, u in fx.units do
|
||||
local f = dec:decode(b, u[1], u[2], i)
|
||||
if f then
|
||||
table.insert(order, f)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local f = dec:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
table.insert(order, f)
|
||||
end
|
||||
t:eq(#order, #fx.units, "bframes: every picture out")
|
||||
local sawB = false
|
||||
for i = 2, #order do
|
||||
local a, c = order[i - 1], order[i]
|
||||
if c.temporalReference ~= 0 then
|
||||
t:check(c.temporalReference == a.temporalReference + 1, "display order at " .. i)
|
||||
end
|
||||
if c.pictureType == Mpeg1.PICTURE_B then
|
||||
sawB = true
|
||||
t:check(c.tag == a.tag + 1 or a.pictureType ~= Mpeg1.PICTURE_B, "B tag order")
|
||||
end
|
||||
end
|
||||
t:check(sawB, "the stream has B-frames")
|
||||
local d2 = Mpeg1.new()
|
||||
for i, u in fx.units do
|
||||
local f = d2:decode(b, u[1], u[2], i)
|
||||
t:check(f ~= nil and f.tag == i, "decode order tag " .. i)
|
||||
end
|
||||
end
|
||||
|
||||
do -- truncated units: every prefix length of a picture, then recovery
|
||||
local dec = Mpeg1.new()
|
||||
local u1 = main.units[1]
|
||||
for k = 0, u1[2], 97 do
|
||||
Mpeg1.new():decode(mainFile, u1[1], k)
|
||||
end
|
||||
for i = 1, 6 do
|
||||
local u = main.units[i]
|
||||
dec:decode(mainFile, u[1], u[2] // 2)
|
||||
end
|
||||
local f = dec:decode(mainFile, main.units[1][1], main.units[1][2])
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "recovers at an I-picture after truncation")
|
||||
end
|
||||
|
||||
-- bit flips and byte garbage in every unit: no throw, sane frames
|
||||
local rounds = 0
|
||||
for _, k in { 2, 11, 8, 6 } do
|
||||
local fx = STREAMS[k]
|
||||
local b = b64(fx.file)
|
||||
for round = 1, 6 do
|
||||
local dec = Mpeg1.new({ reorder = round % 2 == 0 })
|
||||
for _, u in fx.units do
|
||||
local unit = slice(b, u[1], u[2])
|
||||
local nflip = if round <= 3 then round * 3 else 40
|
||||
for _ = 1, nflip do
|
||||
local at = between(0, u[2] - 1)
|
||||
if round == 6 then
|
||||
buffer.writeu8(unit, at, between(0, 255))
|
||||
else
|
||||
buffer.writeu8(unit, at, bit32.bxor(buffer.readu8(unit, at), bit32.lshift(1, between(0, 7))))
|
||||
end
|
||||
end
|
||||
local ok, f = pcall(dec.decode, dec, unit)
|
||||
t:check(ok, fx.name .. ": corrupt unit threw " .. tostring(f))
|
||||
if f then
|
||||
t:check(buffer.len((f :: any).pixels) == f.width * f.height * 4, "frame size")
|
||||
end
|
||||
end
|
||||
while dec:flush() do
|
||||
end
|
||||
rounds += 1
|
||||
end
|
||||
end
|
||||
t:note("%d corrupted-stream rounds", rounds)
|
||||
|
||||
do -- streamed garbage and random units
|
||||
local dec = Mpeg1.new()
|
||||
for _ = 1, 300 do
|
||||
local n = between(0, 3000)
|
||||
local g = buffer.create(n)
|
||||
for i = 0, n - 1 do
|
||||
local r = between(0, 9)
|
||||
buffer.writeu8(g, i, if r < 3 then 0 elseif r == 3 then 1 elseif r == 4 then 0xB3 else between(0, 255))
|
||||
end
|
||||
dec:write(g)
|
||||
while dec:decodeFrame() do
|
||||
end
|
||||
dec:decode(g)
|
||||
end
|
||||
dec:reset()
|
||||
local f = dec:decode(mainFile, main.units[1][1], main.units[1][2])
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "clean after garbage")
|
||||
end
|
||||
|
||||
do -- a hostile sequence header: a huge size is rejected
|
||||
local b = buffer.create(16)
|
||||
buffer.writestring(b, 0, "\0\0\1\xB3\xFF\xFF\xFF\x13\xFF\xFF\xE0\x18\0\0\1\xB8")
|
||||
local dec = Mpeg1.new({ maxPixels = 1000 * 1000 })
|
||||
dec:decode(b)
|
||||
t:eq(dec.width, 0, "oversized sequence header rejected")
|
||||
end
|
||||
|
||||
-- 4. the fuzz pass: whole elementary streams (cut, mutated, garbage) through one decoder each
|
||||
do
|
||||
local samples = {}
|
||||
for _, k in { 1, 9 } do
|
||||
local fx = STREAMS[k]
|
||||
local b = b64(fx.file)
|
||||
local u = fx.units
|
||||
table.insert(samples, buffer.tostring(slice(b, 0, u[4][1] + u[4][2])))
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local dec = Mpeg1.new({ reorder = true })
|
||||
local out = { dec:decode(b) }
|
||||
while dec:flush() do
|
||||
end
|
||||
return table.unpack(out)
|
||||
end, samples, { mutations = 12, keepHeader = 4 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -56,7 +56,7 @@ do
|
||||
local inter = buffer.fromstring(frames[1])
|
||||
buffer.writeu8(inter, 0, bit32.bor(buffer.readu8(inter, 0), 1))
|
||||
local _, e1 = Vp8.decodeFrame(inter)
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "inter frame: " .. tostring(e1))
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "inter frame without a key frame: " .. tostring(e1))
|
||||
local bad = buffer.fromstring(frames[1])
|
||||
buffer.writeu8(bad, 3, 0)
|
||||
local _, e2 = Vp8.decodeFrame(bad)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
-- codecs/Vp8 video tests: whole IVF streams through one decoder object, every shown frame bit-exact against ffmpeg's
|
||||
-- native vp8 decoder (yuv420p CRC32): the official VP8 test vectors (vp80-00-comprehensive-001..018 and others) and
|
||||
-- libvpx clips at many settings (alt-ref / hidden frames, golden, token partitions, error resilience, profiles 1-3,
|
||||
-- sharpness, segmentation, q extremes, short key frame intervals, motion off the frame, odd sizes). Also hidden
|
||||
-- frames, reset() and inter frames without a key frame, and the fuzz no-throw pass over damaged streams.
|
||||
-- Fixtures: tools/fixtures/vp8video.py.
|
||||
local T = require("@tests/T")
|
||||
local Vp8 = require("@formats/codecs/Vp8")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/vp8video_cases")
|
||||
|
||||
local t = T.suite("vp8video")
|
||||
|
||||
-- the frames of an IVF file: { offset, length }
|
||||
local function ivfFrames(b: buffer): { { number } }
|
||||
local out = {}
|
||||
local p = buffer.readu16(b, 6) -- header length (32)
|
||||
while p + 12 <= buffer.len(b) do
|
||||
local n = buffer.readu32(b, p)
|
||||
if p + 12 + n > buffer.len(b) then
|
||||
break
|
||||
end
|
||||
table.insert(out, { p + 12, n })
|
||||
p += 12 + n
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local total, hidden, vectors = 0, 0, 0
|
||||
local samples: { buffer } = {}
|
||||
for _, c in Cases do
|
||||
local b = buffer.fromstring(c.ivf)
|
||||
local fr = ivfFrames(b)
|
||||
local dec = Vp8.newDecoder()
|
||||
local shown, bad, firstBad = 0, 0, ""
|
||||
local ok = true
|
||||
for i, f in fr do
|
||||
local img, err = dec:decodeFrame(b, f[1], f[2])
|
||||
if not img then
|
||||
ok = false
|
||||
firstBad = "frame " .. i .. ": " .. tostring(err)
|
||||
break
|
||||
end
|
||||
local src = img.meta.source
|
||||
if src.show then
|
||||
shown += 1
|
||||
if buffer.len(img.pixels) ~= c.sizes[shown] or Crc32.of(img.pixels) ~= c.crcs[shown] then
|
||||
bad += 1
|
||||
if bad == 1 then
|
||||
firstBad = string.format("frame %d (shown %d, %s)", i, shown, if src.keyFrame then "key" else "inter")
|
||||
end
|
||||
end
|
||||
else
|
||||
hidden += 1
|
||||
end
|
||||
end
|
||||
t:check(ok and bad == 0 and shown == #c.crcs, string.format("%s: %d / %d frames bit-exact, %d shown of %d; first bad: %s", c.name, shown - bad, #c.crcs, shown, #fr, firstBad))
|
||||
total += shown
|
||||
if string.sub(c.name, 1, 5) == "vp80-" then
|
||||
vectors += 1
|
||||
end
|
||||
if #samples < 6 and #c.ivf < 20000 then
|
||||
table.insert(samples, b)
|
||||
end
|
||||
end
|
||||
t:note("%d streams (%d official test vectors), %d shown frames bit-exact with ffmpeg, %d hidden frames", #Cases, vectors, total, hidden)
|
||||
|
||||
-- hidden frames, reset(), inter frames without a key frame
|
||||
do
|
||||
local c
|
||||
for _, x in Cases do
|
||||
if x.name == "altref_352x288" then
|
||||
c = x
|
||||
end
|
||||
end
|
||||
local b = buffer.fromstring(c.ivf)
|
||||
local fr = ivfFrames(b)
|
||||
local dec = Vp8.newDecoder()
|
||||
local _, e0 = dec:decodeFrame(b, fr[2][1], fr[2][2])
|
||||
t:check(e0 and e0.code == Err.CORRUPT, "inter frame first: " .. tostring(e0))
|
||||
local key = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any
|
||||
t:check(key and key.meta.source.keyFrame and key.meta.source.show and key.meta.source.format == "vp8", "key frame meta")
|
||||
local sawHidden = false
|
||||
for i = 2, #fr do
|
||||
local img = dec:decodeFrame(b, fr[i][1], fr[i][2]) :: any
|
||||
if img and not img.meta.source.show then
|
||||
sawHidden = true
|
||||
t:check(not img.meta.source.keyFrame and img.width == c.width, "hidden frame is an Image")
|
||||
end
|
||||
end
|
||||
t:check(sawHidden, "the alt-ref stream has a hidden frame")
|
||||
-- the returned planes are a copy: decoding more frames leaves an earlier image alone
|
||||
local d2 = Vp8.newDecoder()
|
||||
local first = d2:decodeFrame(b, fr[1][1], fr[1][2]) :: any
|
||||
local crc = Crc32.of(first.pixels)
|
||||
d2:decodeFrame(b, fr[2][1], fr[2][2])
|
||||
d2:decodeFrame(b, fr[3][1], fr[3][2])
|
||||
t:eq(Crc32.of(first.pixels), crc, "images are fresh buffers")
|
||||
dec:reset()
|
||||
local _, e1 = dec:decodeFrame(b, fr[3][1], fr[3][2])
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "inter frame after reset: " .. tostring(e1))
|
||||
local again = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any
|
||||
t:eq(again and Crc32.of(again.pixels), c.crcs[1], "key frame after reset")
|
||||
local nxt = dec:decodeFrame(b, fr[2][1], fr[2][2]) :: any
|
||||
t:check(nxt ~= nil, "inter frame after the key frame")
|
||||
local _, e2 = Vp8.decodeFrame(b, fr[2][1], fr[2][2])
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "one-shot decodeFrame of an inter frame")
|
||||
local _, e3 = dec:decodeFrame(b, fr[2][1], 2)
|
||||
t:check(e3 and e3.code == Err.TRUNCATED, "truncated frame tag: " .. tostring(e3))
|
||||
end
|
||||
|
||||
-- fuzz: whole damaged streams through one decoder (truncated / mutated frames after valid ones)
|
||||
local function feed(b: buffer)
|
||||
local dec = Vp8.newDecoder()
|
||||
local any = false
|
||||
local p, n = 32, buffer.len(b)
|
||||
while p + 12 <= n do
|
||||
local len = math.min(buffer.readu32(b, p), n - p - 12)
|
||||
local img = dec:decodeFrame(b, p + 12, len, { maxPixels = 2 ^ 20 })
|
||||
any = any or img ~= nil
|
||||
p += 12 + len
|
||||
end
|
||||
return any, nil
|
||||
end
|
||||
-- damage aimed at inter frames: one frame truncated, or bytes changed in its headers / modes (first 48 bytes)
|
||||
local damaged: { buffer } = {}
|
||||
local rand = T.rng(8)
|
||||
for _, b in samples do
|
||||
local fr = ivfFrames(b)
|
||||
for _ = 1, 12 do
|
||||
local k = 2 + rand(#fr - 1)
|
||||
local parts = {}
|
||||
for i, f in fr do
|
||||
local data = buffer.readstring(b, f[1], f[2])
|
||||
if i == k then
|
||||
if rand(2) == 0 then
|
||||
data = string.sub(data, 1, rand(#data))
|
||||
else
|
||||
for _ = 1, 1 + rand(3) do
|
||||
local at = 1 + rand(math.min(48, #data))
|
||||
data = string.sub(data, 1, at - 1) .. string.char(rand(256)) .. string.sub(data, at + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local hdr = buffer.create(12)
|
||||
buffer.writeu32(hdr, 0, #data)
|
||||
table.insert(parts, buffer.tostring(hdr) .. data)
|
||||
end
|
||||
table.insert(damaged, buffer.fromstring(buffer.readstring(b, 0, 32) .. table.concat(parts)))
|
||||
end
|
||||
end
|
||||
local throws = 0
|
||||
for _, b in damaged do
|
||||
if not pcall(feed, b) then
|
||||
throws += 1
|
||||
end
|
||||
end
|
||||
t:eq(throws, 0, #damaged .. " streams with one damaged inter frame: no throw")
|
||||
t:fuzz("stream", feed, samples, { mutations = 5, keepHeader = 32 })
|
||||
t:fuzz("stream (more damage)", feed, samples, { mutations = 15, keepHeader = 32, garbage = 20 })
|
||||
|
||||
t:done()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,221 @@
|
||||
-- tests/video/_common: shared checks for the video container tests (mkv, avi, y4m, mpegts, mpegps, mp4): a demuxer's
|
||||
-- tracks and packets against ffprobe's, decoded frames against ffmpeg's (CRC-32 for bit-exact codecs, PSNR for the
|
||||
-- others), audio through the api's hook against ffmpeg's f32 decode, seeking. Not a test by itself.
|
||||
local F = require("@formats")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
|
||||
local C = {}
|
||||
|
||||
-- the codecs whose decode must equal ffmpeg's bit for bit
|
||||
C.EXACT = { vp8 = true, rawvideo = true }
|
||||
|
||||
-- psnr(a, b, off?, n?) -> dB between two byte strings / buffers (math.huge when equal)
|
||||
function C.psnr(a: buffer, b: buffer, n: number?): number
|
||||
local len = n or math.min(buffer.len(a), buffer.len(b))
|
||||
local se = 0
|
||||
for i = 0, len - 1 do
|
||||
local d = buffer.readu8(a, i) - buffer.readu8(b, i)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return math.huge
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * len / se)
|
||||
end
|
||||
|
||||
-- snr(ours f32 buffer, reference f32 string, n samples) -> dB
|
||||
function C.snr(ours: buffer, ref: string, n: number): number
|
||||
local rb = buffer.fromstring(ref)
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
local d = buffer.readf32(ours, i * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
if err == 0 then
|
||||
return math.huge
|
||||
end
|
||||
return 10 * math.log10(sig / err)
|
||||
end
|
||||
|
||||
-- packets(t, dmx, c, label, opts?): every track's packets against ffprobe's (in order): size, CRC, time, keyframe.
|
||||
-- opts.skipStream(ffprobePacket, track) -> true skips a stream (ffmpeg's parsers re-split some, e.g. MPEG audio in TS)
|
||||
function C.packets(t: any, dmx: any, c: any, label: string, opts: any?)
|
||||
local o = opts or {}
|
||||
local trackOf = {} -- ffprobe stream index -> our track
|
||||
for i, s in c.streams do
|
||||
trackOf[s.index] = o.trackFor and o.trackFor(dmx, s) or dmx.tracks[i]
|
||||
end
|
||||
local k: { [number]: number } = {}
|
||||
local total, bad = 0, 0
|
||||
local first = nil
|
||||
for _, want in c.packets do
|
||||
local tr = trackOf[want.stream]
|
||||
if not (o.skipStream and o.skipStream(want, tr)) then
|
||||
total += 1
|
||||
local id = if tr then tr.id else -1
|
||||
k[id] = (k[id] or 0) + 1
|
||||
local p = if tr then dmx:get(id, k[id]) else nil
|
||||
local ok = p ~= nil and buffer.len(p.data) == want.size and Crc32.of(p.data) == want.crc
|
||||
local s = c.streams[want.stream + 1]
|
||||
if ok and p and want.pts and s and not o.noPts then
|
||||
local ours = p.pts / tr.timescale - (tr.codecDelay or 0) -- ffmpeg shifts by Matroska's CodecDelay
|
||||
local theirs = want.pts * s.tbn / s.tbd
|
||||
ok = math.abs(ours - theirs) < 0.0015
|
||||
end
|
||||
if ok and p and not o.noKey and tr and tr.kind == "video" then
|
||||
ok = p.keyframe == want.key
|
||||
end
|
||||
if not ok then
|
||||
bad += 1
|
||||
if not first then
|
||||
first = string.format("track %s packet %d: size %s/%d pts %s/%s key %s/%s crc %s", tostring(id), k[id], tostring(p and buffer.len(p.data)), want.size, tostring(p and p.pts), tostring(want.pts), tostring(p and p.keyframe), tostring(want.key), tostring(p and Crc32.of(p.data) == want.crc))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local extra = 0
|
||||
for id, n in k do
|
||||
extra += math.max(0, dmx:count(id) - n)
|
||||
end
|
||||
t:check(bad == 0, label .. ": " .. total .. " packets equal ffprobe's (" .. bad .. " differ" .. (if first then "; first: " .. first else "") .. ")")
|
||||
t:check(extra == 0, label .. ": no extra packets (" .. extra .. ")")
|
||||
end
|
||||
|
||||
-- frames(t, v, c, label): every decoded frame against ffmpeg's (CRC for EXACT codecs, else PSNR of the raw ones)
|
||||
function C.frames(t: any, v: any, c: any, label: string, minPsnr: number?)
|
||||
if not c.frames then
|
||||
return
|
||||
end
|
||||
if not Video.canDecode(v.codec) then
|
||||
t:note("%s: no %s decoder, frames not checked", label, v.codec)
|
||||
return
|
||||
end
|
||||
v:reset()
|
||||
local n, bad, worst = 0, 0, math.huge
|
||||
local firstBad = nil
|
||||
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 img = f.image
|
||||
if img.format ~= "yuv420p" then
|
||||
t:check(false, label .. ": frame " .. n .. " is " .. img.format)
|
||||
break
|
||||
end
|
||||
if C.EXACT[v.codec] then
|
||||
if Crc32.of(img.pixels) ~= c.frames[n] then
|
||||
bad += 1
|
||||
firstBad = firstBad or n
|
||||
end
|
||||
elseif c.yuv and c.yuv[n] then
|
||||
local p = C.psnr(img.pixels, buffer.fromstring(c.yuv[n]))
|
||||
worst = math.min(worst, p)
|
||||
end
|
||||
end
|
||||
t:eq(n, #c.frames, label .. ": frame count")
|
||||
if C.EXACT[v.codec] then
|
||||
t:check(bad == 0, label .. ": every frame bit-exact with ffmpeg (" .. bad .. " differ, first " .. tostring(firstBad) .. ")")
|
||||
elseif c.yuv then
|
||||
t:check(worst >= (minPsnr or 38), string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst))
|
||||
end
|
||||
end
|
||||
|
||||
-- audio(t, v, c, label, exact?): the audio decoder (through the api hook) against ffmpeg's f32
|
||||
function C.audio(t: any, v: any, c: any, label: string, exact: boolean?, minSnr: number?)
|
||||
if not c.pcm then
|
||||
return
|
||||
end
|
||||
if not v.audio then
|
||||
local code = v.audioError and v.audioError.code
|
||||
t:check(code == F.Err.UNKNOWN_FORMAT or code == F.Err.UNSUPPORTED, label .. ": audio missing only for a missing audio format (" .. tostring(v.audioError) .. ")")
|
||||
return
|
||||
end
|
||||
local a = v.audio
|
||||
a:seek(0)
|
||||
local want = #c.pcm // 4
|
||||
local out = buffer.create(want * 4)
|
||||
local got = 0
|
||||
while got * a.channels < want do
|
||||
local chunk, k = a:read(want // a.channels - got)
|
||||
if not chunk or k <= 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, got * a.channels * 4, chunk, 0, k * a.channels * 4)
|
||||
got += k
|
||||
end
|
||||
local n = got * a.channels
|
||||
t:check(n == want or n * 4 == c.pcmBytes, label .. ": " .. n .. " samples read of " .. want)
|
||||
n = math.min(n, want)
|
||||
if exact then
|
||||
local same = true
|
||||
local rb = buffer.fromstring(c.pcm)
|
||||
for i = 0, n - 1 do
|
||||
if math.abs(buffer.readf32(out, i * 4) - buffer.readf32(rb, i * 4)) > 1e-6 then
|
||||
same = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(same, label .. ": PCM equal to ffmpeg's")
|
||||
else
|
||||
local s = C.snr(out, c.pcm, n)
|
||||
t:check(s >= (minSnr or 30), string.format("%s: audio SNR vs ffmpeg %.1f dB", label, s))
|
||||
end
|
||||
end
|
||||
|
||||
-- seek(t, v, c, label, at): after seek(at) the next frame is the first at or after `at`
|
||||
function C.seek(t: any, v: any, c: any, label: string, at: number)
|
||||
if not (c.frames or c.rgba) or not Video.canDecode(v.codec) then
|
||||
return
|
||||
end
|
||||
if v.duration > 0 and at > v.duration * 0.6 then
|
||||
at = math.floor(v.duration * 50) / 100
|
||||
end
|
||||
v:seek(at)
|
||||
local f = v:nextFrame()
|
||||
t:check(f ~= nil and f.pts >= at - 1e-6 and f.pts < at + 0.2, label .. ": seek to " .. at .. " lands at " .. tostring(f and f.pts))
|
||||
if f and C.EXACT[v.codec] and c.frames then
|
||||
local idx = math.floor(f.pts * v.frameRate + 0.5) + 1
|
||||
t:eq(Crc32.of(f.image.pixels), c.frames[idx], label .. ": the frame after seeking equals ffmpeg's frame " .. idx)
|
||||
end
|
||||
v:reset()
|
||||
end
|
||||
|
||||
-- fuzzOpen(Fmt) -> a fuzz function: open, read every packet, decode up to 8 frames, read some audio
|
||||
function C.fuzzOpen(Fmt: any): (buffer) -> any
|
||||
return function(b: buffer): any
|
||||
local v = Fmt.open(Bytes.reader(b), { openAudio = function(d: any, tr: any): any
|
||||
local AudioWrap = require("@formats/containers/AudioWrap")
|
||||
AudioWrap.wrap(d, tr)
|
||||
return nil
|
||||
end })
|
||||
if not v then
|
||||
return nil
|
||||
end
|
||||
for _ = 1, 8 do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
end
|
||||
if v.demuxer then
|
||||
v.demuxer:rewind()
|
||||
while v.demuxer:read() do
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
end
|
||||
|
||||
-- open(data, opts?) -> VideoDecoder through the api (category video)
|
||||
function C.open(data: string, opts: any?): (any, any)
|
||||
return F.video.open(buffer.fromstring(data), opts)
|
||||
end
|
||||
|
||||
return C
|
||||
@@ -0,0 +1,97 @@
|
||||
-- video/avi tests: AVI files from ffmpeg (MJPEG + PCM s16 / u8 / IMA ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA /
|
||||
-- I420) read through the OpenDML indexes, idx1 alone, and a movi scan: tracks and every packet against ffprobe,
|
||||
-- frames against ffmpeg, audio through the api hook, seeking; our muxer (MJPEG + PCM) read back; a GIF converted to
|
||||
-- AVI. Fixtures: tools/fixtures/avi.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local AviFormat = require("@formats/video/avi")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Fx = require("@tests/gen/avi_cases")
|
||||
|
||||
local t = T.suite("avi")
|
||||
|
||||
t:eq(AviFormat.name, "avi", "name")
|
||||
t:eq(AviFormat.category, "video", "category")
|
||||
|
||||
local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, adpcm_ima_wav = true }
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(AviFormat.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff")
|
||||
local v, err = C.open(c.data)
|
||||
if c.truncated then
|
||||
t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly")
|
||||
else
|
||||
t:check(v ~= nil, label .. ": open: " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
C.packets(t, dmx, c, label)
|
||||
if c.rgba then
|
||||
v:reset()
|
||||
local n, bad = 0, 0
|
||||
while true do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.rgba[n] then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
t:check(n == #c.rgba and bad == 0, label .. ": " .. n .. " rgba frames equal ffmpeg's (" .. bad .. " differ)")
|
||||
else
|
||||
C.frames(t, v, c, label)
|
||||
end
|
||||
local at = dmx:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(C.open(byName["mjpeg_pcm.avi"].data).demuxer.meta.index, "idx1", "ffmpeg's AVI: idx1 used")
|
||||
t:eq(C.open(byName["odml.avi"].data).demuxer.meta.index, "odml", "OpenDML indexes used")
|
||||
t:eq(C.open(byName["idx1_only.avi"].data).demuxer.meta.index, "idx1", "idx1 used without OpenDML indexes")
|
||||
t:eq(C.open(byName["no_index.avi"].data).demuxer.meta.index, "scan", "movi scanned without indexes")
|
||||
|
||||
-- our muxer: MJPEG copied + PCM, read back packet for packet
|
||||
do
|
||||
local v = C.open(byName["mjpeg_pcm.avi"].data)
|
||||
local out, err = F.save(v, nil, { format = "avi" })
|
||||
t:check(out ~= nil, "mux avi: " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil, "mux avi: reads back")
|
||||
if v2 then
|
||||
local a, b = v.demuxer, v2.demuxer
|
||||
local same = a:count(1) == b:count(1)
|
||||
for k = 1, a:count(1) do
|
||||
local p, q = a:get(1, k), b:get(1, k)
|
||||
if not q or buffer.tostring(p.data) ~= buffer.tostring(q.data) then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
t:check(same, "mux avi: identical MJPEG packets")
|
||||
t:eq(v2.frameRate, 10, "mux avi: frame rate")
|
||||
C.audio(t, v2, byName["mjpeg_pcm.avi"], "mux avi", true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
local samples = {}
|
||||
for _, n in { "mjpeg_pcm.avi", "mjpeg_ima.avi", "idx1_only.avi", "i420.avi" } do
|
||||
local d = byName[n].data
|
||||
table.insert(samples, string.sub(d, 1, math.min(#d, 40000)))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(AviFormat), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,116 @@
|
||||
-- video writer tests: files our muxers wrote (tools/fixtures/_video_encode.luau: WebM remux, MJPEG Matroska / AVI
|
||||
-- copied and re-encoded from VP8 / MPEG-1, an animated GIF with uneven delays to AVI / Matroska / Y4M, WebM to Y4M)
|
||||
-- were probed by ffprobe and decoded by ffmpeg at fixture time; here our demuxers must see the same packets, our
|
||||
-- decoders the same frames (CRC for VP8 / raw, PSNR for MJPEG) and audio; the writers are rerun and must give the same
|
||||
-- bytes. Fixtures: tools/fixtures/videoenc.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Fx = require("@tests/gen/videoenc_cases")
|
||||
local Src = require("@tests/gen/videoenc_src")
|
||||
|
||||
local t = T.suite("video encode")
|
||||
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
if c.err then
|
||||
t:note("%s: not written at fixture time: %s", label, c.err)
|
||||
else
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": opens: " .. tostring(err))
|
||||
if v then
|
||||
t:eq(#v.demuxer.tracks, #c.streams, label .. ": track count (ffprobe)")
|
||||
-- (ffmpeg's AVI demuxer cuts PCM chunks into 1024-sample packets: AVI audio is compared decoded)
|
||||
local avi = string.sub(label, -4) == ".avi"
|
||||
C.packets(t, v.demuxer, c, label, { skipStream = function(_: any, tr: any): boolean
|
||||
return avi and tr ~= nil and tr.kind == "audio"
|
||||
end })
|
||||
C.frames(t, v, c, label, 40)
|
||||
local at = v.demuxer:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, string.sub(at.codec, 1, 4) == "pcm_", 30)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the GIF (100 / 50 / 200 / 100 ms) at a constant 20 fps: 2 + 1 + 4 + 2 frames
|
||||
do
|
||||
local c = byName["gif.avi"]
|
||||
if c and c.frames then
|
||||
t:eq(#c.frames, 9, "gif.avi: 9 frames at 20 fps (ffmpeg)")
|
||||
local v = C.open(c.data)
|
||||
t:eq(v.frameRate, 20, "gif.avi: 20 fps")
|
||||
end
|
||||
local y = byName["gif.y4m"]
|
||||
if y and y.frames then
|
||||
t:eq(#y.frames, 9, "gif.y4m: 9 frames (ffmpeg)")
|
||||
end
|
||||
-- F.video.open on the GIF itself: a frames-backed video
|
||||
local g = F.video.open(buffer.fromstring(Src.gif))
|
||||
t:check(g ~= nil and g.codec == "frames" and g.frames == 4, "F.video.open(gif): 4 frames")
|
||||
if g then
|
||||
local f1 = g:nextFrame()
|
||||
local f2 = g:nextFrame()
|
||||
t:check(f1 and f1.image.format == "rgba8" and f1.duration == 0.1 and f2 and f2.pts == 0.1 and f2.duration == 0.05, "gif frames: rgba8 with the GIF's times")
|
||||
g:seek(0.2)
|
||||
local f3 = g:nextFrame()
|
||||
t:check(f3 ~= nil and f3.index == 3, "gif seek: frame 3 at 0.15 s holds 0.2 s")
|
||||
end
|
||||
end
|
||||
|
||||
-- animated WebP through F.video.open: frames-backed, the canvases equal Pillow's (libwebp's WebPAnimDecoder)
|
||||
do
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Anims = require("@tests/gen/webp_anim")
|
||||
for _, a in Anims do
|
||||
local v = F.video.open(buffer.fromstring(a.data))
|
||||
t:check(v ~= nil and v.codec == "frames" and v.frames == #a.frames, a.name .. ": opens as a " .. #a.frames .. "-frame video")
|
||||
if v then
|
||||
local bad, n, t0 = 0, 0, 0
|
||||
while true do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
local px = f.image.pixels
|
||||
if a.rgba == false then
|
||||
px = buffer.create(buffer.len(f.image.pixels))
|
||||
buffer.copy(px, 0, f.image.pixels)
|
||||
for i = 3, buffer.len(px) - 1, 4 do
|
||||
buffer.writeu8(px, i, 255)
|
||||
end
|
||||
end
|
||||
if Crc32.of(px) ~= a.frames[n].crc or math.abs(f.pts - t0) > 1e-6 then
|
||||
bad += 1
|
||||
end
|
||||
t0 += a.frames[n].ms / 1000
|
||||
end
|
||||
t:check(n == #a.frames and bad == 0, a.name .. ": video frames equal Pillow's canvases and times (" .. bad .. " differ)")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the writers are deterministic: the same bytes again
|
||||
do
|
||||
local Mkv = require("@tests/gen/mkv_cases")
|
||||
local remux = byName["remux.webm"]
|
||||
for _, m in Mkv do
|
||||
if m.name == "vp8_opus.webm" and remux and remux.data then
|
||||
local out = F.convert(buffer.fromstring(m.data), "webm")
|
||||
t:check(out ~= nil and buffer.tostring(out) == remux.data, "remux.webm: written again byte for byte")
|
||||
end
|
||||
end
|
||||
local gifAvi = byName["gif.avi"]
|
||||
if gifAvi and gifAvi.data then
|
||||
local out = F.convert(buffer.fromstring(Src.gif), "avi", { quality = 95 })
|
||||
t:check(out ~= nil and buffer.tostring(out) == gifAvi.data, "gif.avi: F.convert(gif, 'avi') again byte for byte")
|
||||
end
|
||||
end
|
||||
t:done()
|
||||
@@ -0,0 +1,128 @@
|
||||
-- video/mkv tests: Matroska / WebM files from ffmpeg and mkvmerge (VP8 + Opus / Vorbis, MJPEG + PCM, MPEG-1 + MP2,
|
||||
-- VP8 + FLAC, srt subtitles, Xiph / EBML / fixed lacing, zlib compression, unknown-size clusters, a truncated file):
|
||||
-- tracks and every packet against ffprobe, frames against ffmpeg (bit-exact VP8, PSNR for MJPEG / MPEG-1), audio
|
||||
-- through the api hook against ffmpeg, seeking, subtitles; our muxer's output (remux and MJPEG) read back. Fixtures:
|
||||
-- tools/fixtures/mkv.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Mkv = require("@formats/video/mkv")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/mkv_cases")
|
||||
|
||||
local t = T.suite("mkv")
|
||||
|
||||
-- 1. contract
|
||||
t:eq(Mkv.name, "mkv", "name")
|
||||
t:eq(Mkv.category, "video", "category")
|
||||
t:check(table.find(Mkv.extensions, "webm") ~= nil, "webm extension")
|
||||
|
||||
local EXACT_AUDIO = { pcm_s16le = true, flac = true }
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
-- 2. every fixture
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Mkv.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff")
|
||||
if c.truncated then
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly")
|
||||
if v then
|
||||
local n = 0
|
||||
while v:nextFrame() do
|
||||
n += 1
|
||||
end
|
||||
t:note("%s: %d frames before the cut", label, n)
|
||||
end
|
||||
else
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": open: " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
for i, s in c.streams do
|
||||
local tr = dmx.tracks[i]
|
||||
if tr then
|
||||
t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind")
|
||||
if s.width then
|
||||
t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size")
|
||||
end
|
||||
if s.rate then
|
||||
t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": track " .. i .. " rate / channels")
|
||||
end
|
||||
end
|
||||
end
|
||||
-- Vorbis frames inside a lace carry no time of their own (ffmpeg derives them from the Vorbis block sizes)
|
||||
C.packets(t, dmx, c, label, { noPts = c.name == "laced_vorbis.mkv" or c.name == "zlib_vorbis.mka" })
|
||||
C.frames(t, v, c, label)
|
||||
local at = dmx:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], if at.codec == "vorbis" then 20 else 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.6)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 3. specific files
|
||||
do
|
||||
local v = C.open(byName["vp8_opus.webm"].data)
|
||||
t:eq(v.format, "webm", "webm: format")
|
||||
t:eq(v.codec, "vp8", "webm: codec")
|
||||
t:eq(v.width, 160, "webm: width")
|
||||
t:check(math.abs(v.duration - 1) < 0.1, "webm: duration " .. v.duration)
|
||||
t:check(#v.demuxer.meta.cues > 0, "webm: cues read")
|
||||
local subs = Mkv.subtitles(C.open(byName["subs.mkv"].data).demuxer)
|
||||
t:check(subs ~= nil and #subs.cues == 2, "subtitles: two cues")
|
||||
if subs then
|
||||
t:eq(subs.cues[1].text, "Hello", "subtitles: text")
|
||||
t:check(math.abs(subs.cues[1].start - 0.1) < 0.002 and math.abs(subs.cues[1].stop - 0.5) < 0.002, "subtitles: times")
|
||||
end
|
||||
local lv = C.open(byName["lacing.mka"].data)
|
||||
t:eq(lv.demuxer:count(1), 10, "lacing: 10 frames from three laced blocks")
|
||||
local _, _, _, _, len = lv.demuxer:info(1, 4)
|
||||
t:eq(len, 160, "lacing: EBML-laced frame size")
|
||||
end
|
||||
|
||||
-- 4. our muxer: remux WebM (VP8 + Opus copied) and read it back packet for packet
|
||||
do
|
||||
local src = byName["vp8_opus.webm"]
|
||||
local v = C.open(src.data)
|
||||
local out, err = F.save(v, nil, { format = "webm" })
|
||||
t:check(out ~= nil, "remux webm: " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil and v2.format == "webm", "remux webm: reads back as webm")
|
||||
if v2 then
|
||||
local a, b = v.demuxer, v2.demuxer
|
||||
t:eq(#b.tracks, 2, "remux webm: two tracks")
|
||||
local same = a:count(1) == b:count(1) and a:count(2) == b:count(2)
|
||||
for k = 1, a:count(1) do
|
||||
local p, q = a:get(1, k), b:get(1, k)
|
||||
if not q or p.pts ~= q.pts or buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
t:check(same, "remux webm: identical video packets")
|
||||
C.frames(t, v2, src, "remux webm")
|
||||
C.audio(t, v2, src, "remux webm", false, 30)
|
||||
end
|
||||
end
|
||||
local bad, berr = F.save(C.open(byName["mjpeg_pcm.mkv"].data), nil, { format = "webm" })
|
||||
t:check(bad == nil and berr ~= nil and berr.code == Err.UNSUPPORTED, "webm refuses MJPEG: " .. tostring(berr))
|
||||
end
|
||||
|
||||
-- 5. errors and the fuzz pass
|
||||
local e1 = select(2, Mkv.open(Bytes.reader(buffer.fromstring("\26\69\223\163\128"))))
|
||||
t:check(e1 ~= nil, "empty EBML header fails")
|
||||
local samples = {}
|
||||
for _, n in { "vp8_opus.webm", "mjpeg_pcm.mkv", "lacing.mka", "zlib_vorbis.mka", "subs.mkv" } do
|
||||
local d = byName[n].data
|
||||
table.insert(samples, string.sub(d, 1, math.min(#d, 60000)))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Mkv), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,74 @@
|
||||
-- video/mp4 tests: MP4 / MOV files from ffmpeg (MJPEG + AAC / PCM / FLAC / MP2, H.264 with B-frames and edit lists +
|
||||
-- AAC, fragmented MP4, MPEG-1 + Opus): tracks and every packet against ffprobe (pts moved by the edit lists, as ffmpeg),
|
||||
-- frames against ffmpeg (PSNR), audio through the api hook (AAC priming dropped), seeking, our MP4 / MOV writer read
|
||||
-- back, fuzz. Fixtures: tools/fixtures/mp4.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Mp4 = require("@formats/video/mp4")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Fx = require("@tests/gen/mp4_cases")
|
||||
|
||||
local t = T.suite("mp4")
|
||||
t:eq(Mp4.name, "mp4", "name")
|
||||
|
||||
local EXACT_AUDIO = { pcm_s16le = true, flac = true }
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Mp4.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.6, label .. ": sniff")
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
C.packets(t, dmx, c, label)
|
||||
C.frames(t, v, c, label, 38)
|
||||
local at = dmx:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
|
||||
-- our writer: MP4 (MJPEG + AAC copied) and MOV (MJPEG + PCM) read back packet for packet
|
||||
for _, job in { { "mjpeg_aac.mp4", "mp4" }, { "mjpeg_pcm.mov", "mov" }, { "h264_aac.mp4", "mp4" } } do
|
||||
local src = byName[job[1]]
|
||||
local v = C.open(src.data)
|
||||
local out, err = F.save(v, nil, { format = job[2] })
|
||||
t:check(out ~= nil, "write " .. job[2] .. " from " .. job[1] .. ": " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil, "write " .. job[1] .. ": reads back")
|
||||
if v2 then
|
||||
local a, b = v.demuxer, v2.demuxer
|
||||
local same = #a.tracks == #b.tracks
|
||||
for i, tr in a.tracks do
|
||||
local tr2 = b.tracks[i]
|
||||
if not tr2 or a:count(tr.id) ~= b:count(tr2.id) then
|
||||
same = false
|
||||
else
|
||||
for k = 1, a:count(tr.id) do
|
||||
local p, q = a:get(tr.id, k), b:get(tr2.id, k)
|
||||
if not q or buffer.tostring(p.data) ~= buffer.tostring(q.data) or math.abs(p.pts / tr.timescale - q.pts / tr2.timescale) > 0.002 then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(same, "write " .. job[1] .. ": same packets and times")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, n in { "mjpeg_aac.mp4", "fragmented.mp4", "h264_aac.mp4" } do
|
||||
table.insert(samples, string.sub(byName[n].data, 1, 30000))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Mp4), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,48 @@
|
||||
-- video/mpegps tests: program streams from ffmpeg (MPEG-1 system stream, B-frames, MPEG-2 PS / VOB packs, a raw .m1v
|
||||
-- elementary stream): tracks, picture packets (count and timestamps against ffmpeg's frames), frames against ffmpeg
|
||||
-- (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz. Fixtures:
|
||||
-- tools/fixtures/mpegts.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local Ps = require("@formats/video/mpegps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Fx = require("@tests/gen/mpegps_cases")
|
||||
|
||||
local t = T.suite("mpegps")
|
||||
t:eq(Ps.name, "mpegps", "name")
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Ps.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff")
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
local vt = dmx:track("video")
|
||||
t:check(vt ~= nil and vt.codec == "mpeg1", label .. ": an MPEG-1 video track")
|
||||
t:eq(dmx:count(vt.id), #c.frames, label .. ": one packet per picture")
|
||||
-- presentation times: one per frame slot
|
||||
local seen, ok = {}, true
|
||||
for k = 1, dmx:count(vt.id) do
|
||||
local pts = dmx:info(vt.id, k)
|
||||
local slot = math.floor((pts - dmx:info(vt.id, 1)) / 3600 + 0.5)
|
||||
if seen[slot] then
|
||||
ok = false
|
||||
end
|
||||
seen[slot] = true
|
||||
end
|
||||
t:check(ok, label .. ": distinct presentation times")
|
||||
C.frames(t, v, c, label, 36)
|
||||
if dmx:track("audio") then
|
||||
C.audio(t, v, c, label, false, 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, string.sub(c.data, 1, 30000))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Ps), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,64 @@
|
||||
-- video/mpegts tests: transport streams from ffmpeg (MPEG-1 + MP2, B-frames, H.264 + AAC, M2TS, garbage before the
|
||||
-- first packet, a truncated file): tracks and the video packets against ffprobe (time, size, CRC, keyframe), frames
|
||||
-- against ffmpeg (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz.
|
||||
-- Fixtures: tools/fixtures/mpegts.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local Ts = require("@formats/video/mpegts")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Fx = require("@tests/gen/mpegts_cases")
|
||||
|
||||
local t = T.suite("mpegts")
|
||||
t:eq(Ts.name, "mpegts", "name")
|
||||
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
local function audioStream(want: any, tr: any): boolean
|
||||
return tr == nil or tr.kind ~= "video" -- ffmpeg's parser re-splits PES audio into frames
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
local v, err = C.open(c.data)
|
||||
if c.truncated then
|
||||
t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly")
|
||||
else
|
||||
t:check(Ts.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0 or label == "garbage.ts", label .. ": sniff")
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
for i, s in c.streams do
|
||||
local tr = dmx.tracks[i]
|
||||
t:check(tr ~= nil and tr.kind == s.kind, label .. ": track " .. i .. " kind")
|
||||
if tr and s.width and tr.width then -- (H.264 sizes come from its SPS, read by the codec)
|
||||
t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size")
|
||||
end
|
||||
end
|
||||
if c.packets then
|
||||
C.packets(t, dmx, c, label, { skipStream = audioStream })
|
||||
end
|
||||
C.frames(t, v, c, label, 36)
|
||||
if dmx:track("audio") then
|
||||
C.audio(t, v, c, label, false, 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
end
|
||||
do
|
||||
local v = C.open(byName["mpeg1_mp2.ts"].data)
|
||||
t:eq(v.codec, "mpeg1", "stream type 0x02 without a sequence extension is MPEG-1")
|
||||
t:eq(v.demuxer.tracks[2].codec, "mp2", "MPEG audio layer II")
|
||||
t:eq(C.open(byName["h264_aac.ts"].data).codec, "h264", "H.264 track")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, n in { "mpeg1_mp2.ts", "bframes.ts", "h264_aac.ts" } do
|
||||
table.insert(samples, string.sub(byName[n].data, 1, 188 * 120))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Ts), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,103 @@
|
||||
-- video/y4m tests: YUV4MPEG2 streams from ffmpeg (C420jpeg at an odd size, C420mpeg2, C422, C444, Cmono, C420p10)
|
||||
-- against ffmpeg's yuv420p decode (bit-exact for 4:2:0 8-bit, PSNR for the converted layouts), the header fields,
|
||||
-- our writer round trip (and from an rgba frames-backed video), errors and the fuzz pass. Fixtures:
|
||||
-- tools/fixtures/y4m.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Y4m = require("@formats/video/y4m")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/y4m_cases")
|
||||
|
||||
local t = T.suite("y4m")
|
||||
t:eq(Y4m.name, "y4m", "name")
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Y4m.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, label .. ": sniff")
|
||||
local v, err = Y4m.open(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
t:check(v.width == c.width and v.height == c.height, label .. ": size")
|
||||
t:check(math.abs(v.frameRate - c.rate[1] / c.rate[2]) < 1e-9, label .. ": frame rate")
|
||||
local n, bad, worst = 0, 0, math.huge
|
||||
while true do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
if c.exact then
|
||||
if Crc32.of(f.image.pixels) ~= c.frames[n] then
|
||||
bad += 1
|
||||
end
|
||||
elseif c.yuv[n] then
|
||||
worst = math.min(worst, C.psnr(f.image.pixels, buffer.fromstring(c.yuv[n])))
|
||||
end
|
||||
end
|
||||
t:eq(n, #c.frames, label .. ": frame count")
|
||||
if c.exact then
|
||||
t:check(bad == 0, label .. ": frames bit-exact with ffmpeg")
|
||||
else
|
||||
t:check(worst > 30, string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- writer: a y4m stream back to y4m is byte-identical in its frames; header as ffmpeg writes it
|
||||
do
|
||||
local c = Fx[1]
|
||||
local v = F.video.open(buffer.fromstring(c.data))
|
||||
local out, err = F.save(v, nil, { format = "y4m" })
|
||||
t:check(out ~= nil, "write: " .. tostring(err))
|
||||
if out then
|
||||
local s = buffer.tostring(out)
|
||||
t:check(string.find(s, "YUV4MPEG2 W173 H95 F30000:1001 Ip A1:1 C420jpeg XYSCSS=420JPEG\n", 1, true) == 1, "write: header " .. string.sub(s, 1, 60))
|
||||
local v2 = Y4m.open(Bytes.reader(out))
|
||||
local n, same = 0, true
|
||||
while true do
|
||||
local f = v2:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
same = same and Crc32.of(f.image.pixels) == c.frames[n]
|
||||
end
|
||||
t:check(n == #c.frames and same, "write: frames round trip")
|
||||
end
|
||||
-- an rgba frames-backed video (a 2-frame animation) to y4m
|
||||
local a = Types.Image.new(4, 2)
|
||||
buffer.fill(a.pixels, 0, 255)
|
||||
local b = Types.Image.new(4, 2)
|
||||
a.frames = { { image = a, delay = 0.5, x = 0, y = 0, dispose = "none", blend = "source" }, { image = b, delay = 0.5, x = 0, y = 0, dispose = "none", blend = "source" } }
|
||||
local y, yerr = F.save(a, nil, { format = "y4m" })
|
||||
t:check(y ~= nil, "write from frames: " .. tostring(yerr))
|
||||
if y then
|
||||
local v3 = Y4m.open(Bytes.reader(y))
|
||||
local f1 = v3:nextFrame()
|
||||
local f2 = v3:nextFrame()
|
||||
t:check(f1 ~= nil and f2 ~= nil and v3:nextFrame() == nil, "write from frames: 2 frames")
|
||||
t:eq(v3.frameRate, 2, "write from frames: frame rate from the delays")
|
||||
t:eq(buffer.readu8(f1.image.pixels, 0), 235, "write from frames: white -> Y 235 (limited range)")
|
||||
t:eq(buffer.readu8(f2.image.pixels, 0), 16, "write from frames: black -> Y 16")
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
local function code(s: string): string?
|
||||
local _, e = Y4m.open(Bytes.reader(buffer.fromstring(s)))
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("YUV4MPEG2 W0 H0\n"), Err.CORRUPT, "zero size")
|
||||
t:eq(code("YUV4MPEG2 W16 H16 Cfoo\n"), Err.UNSUPPORTED, "unknown colour space")
|
||||
t:eq(code("YUV4MPEG2 W99999999 H99999 C420\n"), Err.CORRUPT, "huge size")
|
||||
t:eq(code("YUV4MPEG2 W16 H16"), Err.TRUNCATED, "no header end")
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, string.sub(c.data, 1, 30000))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Y4m), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -898,3 +898,135 @@ do
|
||||
Step.encode(cad)
|
||||
end)
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
|
||||
do
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local Mpeg1 = require("@formats/codecs/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
|
||||
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", if rgba then "rgba" else "yuv", s.width, s.height), 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
|
||||
-- ------------------------------------------------------------------------------------------- ws-video: containers
|
||||
do
|
||||
local F = require("@formats")
|
||||
local VB = require("@tests/gen/videobench")
|
||||
local function clock(n: number, f: () -> number): (number, number)
|
||||
local frames = f()
|
||||
local dt = math.huge
|
||||
for _ = 1, n do
|
||||
local t0 = os.clock()
|
||||
frames = f()
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
return dt, frames
|
||||
end
|
||||
for _, c in VB do
|
||||
local data = buffer.fromstring(c.data)
|
||||
local dtOpen = clock(3, function(): number
|
||||
F.video.open(data, { audio = false })
|
||||
return 1
|
||||
end)
|
||||
for _, rgba in { false, true } do
|
||||
local ok, dt, frames = pcall(clock, 2, function(): number
|
||||
local v = assert(F.video.open(data, { audio = false, rgba = rgba }))
|
||||
local n = 0
|
||||
while true do
|
||||
local f, err = v:nextFrame()
|
||||
if not f then
|
||||
assert(err == nil, tostring(err))
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
return n
|
||||
end)
|
||||
if ok then
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps (open %.1f ms)", runtime, string.format("video %s %s %s", c.size, c.name, if rgba then "rgba" else "yuv"), dt * 1000 / frames, frames / dt, dtOpen * 1000))
|
||||
else
|
||||
print(string.format("%-8s %-30s %s", runtime, "video " .. c.size .. " " .. c.name, tostring(dt)))
|
||||
end
|
||||
end
|
||||
if c.name == "raw.y4m" then
|
||||
local dt, frames = clock(2, function(): number
|
||||
assert(F.convert(data, "avi", { quality = 85 }))
|
||||
return 8
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, "video " .. c.size .. " y4m -> mjpeg avi", dt * 1000 / frames, frames / dt))
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------- ws-video-vp8: fps
|
||||
do
|
||||
-- VP8 video (codecs/Vp8, tools/fixtures/vp8video.py): whole IVF streams (libvpx, panning testsrc2) through one
|
||||
-- decoder object; frames per second. On LuaJIT the library's host module raises the trace limits (maxtrace=8000,
|
||||
-- see src/Formats/host/init.luau): the second pair of lines runs with them, as the api does.
|
||||
local Vp8 = require("@formats/codecs/Vp8")
|
||||
local VB = require("@tests/gen/vp8video_bench")
|
||||
local function run(tag: string)
|
||||
for _, c in VB do
|
||||
local b = buffer.fromstring(c.ivf)
|
||||
local frames = {}
|
||||
local p = 32
|
||||
while p + 12 <= buffer.len(b) do
|
||||
local n = buffer.readu32(b, p)
|
||||
table.insert(frames, { p + 12, n })
|
||||
p += 12 + n
|
||||
end
|
||||
local dt = bench(string.format("vp8 decode %dx%d%s", c.width, c.height, tag), 3, c.width * c.height * 1.5 * #frames, function()
|
||||
local dec = Vp8.newDecoder()
|
||||
for _, f in frames do
|
||||
dec:decodeFrame(b, f[1], f[2])
|
||||
end
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt))
|
||||
end
|
||||
end
|
||||
run("")
|
||||
if runtime == "luajit" then
|
||||
require("@formats/host")
|
||||
run(" (jit tuned)")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,122 @@
|
||||
# Shared helpers for the video fixture generators (mkv.py, avi.py, y4m.py, mpegts.py, videoapi.py), loaded by path.
|
||||
# ffmpeg / ffprobe come from PATH when present (a build with libvpx / libopus / libvorbis), else nix (ffmpeg-full).
|
||||
import json, os, shutil, subprocess, zlib
|
||||
|
||||
_FF = None
|
||||
|
||||
|
||||
def ff_prefix():
|
||||
global _FF
|
||||
if _FF is None:
|
||||
if shutil.which("ffmpeg") and shutil.which("ffprobe"):
|
||||
_FF = []
|
||||
else:
|
||||
_FF = ["nix", "shell", "nixpkgs#ffmpeg-full", "-c"]
|
||||
return _FF
|
||||
|
||||
|
||||
def ffmpeg(args, cwd=None, input=None):
|
||||
return subprocess.run(ff_prefix() + ["ffmpeg", "-v", "error", "-y"] + args, cwd=cwd, input=input,
|
||||
capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def ffprobe_json(path, extra):
|
||||
out = subprocess.run(ff_prefix() + ["ffprobe", "-v", "error", "-of", "json"] + extra + [path],
|
||||
capture_output=True, check=True).stdout
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def streams(path):
|
||||
"""ffprobe streams: [{index, kind, codec, width, height, rate, channels, time_base}]"""
|
||||
d = ffprobe_json(path, ["-show_streams"])
|
||||
out = []
|
||||
for s in d.get("streams", []):
|
||||
e = {"index": s["index"], "kind": s.get("codec_type", ""), "codec": s.get("codec_name", "")}
|
||||
if "width" in s:
|
||||
e["width"], e["height"] = s["width"], s["height"]
|
||||
if "sample_rate" in s:
|
||||
e["rate"] = int(s["sample_rate"])
|
||||
e["channels"] = s.get("channels", 0)
|
||||
tb = s.get("time_base", "1/1").split("/")
|
||||
e["tbn"], e["tbd"] = int(tb[0]), int(tb[1])
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def packets(path):
|
||||
"""ffprobe packets in file order: [{stream, pts, dur, key, size, crc}] (pts / dur in the stream time base)"""
|
||||
d = ffprobe_json(path, ["-show_packets", "-show_data_hash", "crc32"])
|
||||
out = []
|
||||
for p in d.get("packets", []):
|
||||
e = {"stream": p["stream_index"], "key": "K" in p.get("flags", ""), "size": int(p["size"]),
|
||||
"crc": int(p["data_hash"].split(":")[1], 16)}
|
||||
if p.get("pts") not in (None, "N/A"):
|
||||
e["pts"] = int(p["pts"])
|
||||
if p.get("duration") not in (None, "N/A"):
|
||||
e["dur"] = int(p["duration"])
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def yuv_frames(path, w, h, extra=None, codec=None):
|
||||
"""the first video stream decoded by ffmpeg to yuv420p (yuvj420p for MJPEG: full range, no conversion): a list of
|
||||
frame bytes"""
|
||||
pix = "yuvj420p" if codec == "mjpeg" else "yuv420p"
|
||||
raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix, "-"])
|
||||
n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
return [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)]
|
||||
|
||||
|
||||
def pcm_f32(path, extra=None):
|
||||
"""the first audio stream decoded by ffmpeg to interleaved f32le"""
|
||||
return ffmpeg(["-i", path] + (extra or []) + ["-map", "0:a:0", "-f", "f32le", "-"])
|
||||
|
||||
|
||||
def crc(b):
|
||||
return zlib.crc32(b) & 0xffffffff
|
||||
|
||||
|
||||
def ebml_vint(b, p):
|
||||
"""(value, length) of an EBML vint (marker removed; all ones -> -1)"""
|
||||
first = b[p]
|
||||
n = 1
|
||||
mask = 0x80
|
||||
while n <= 8 and not first & mask:
|
||||
n += 1
|
||||
mask >>= 1
|
||||
v = first & (mask - 1)
|
||||
ones = v == mask - 1
|
||||
for i in range(1, n):
|
||||
v = (v << 8) | b[p + i]
|
||||
ones = ones and b[p + i] == 255
|
||||
return (-1 if ones else v), n
|
||||
|
||||
|
||||
def ebml_id(b, p):
|
||||
first = b[p]
|
||||
n = 1 if first >= 0x80 else 2 if first >= 0x40 else 3 if first >= 0x20 else 4
|
||||
return int.from_bytes(b[p:p + n], "big"), n
|
||||
|
||||
|
||||
def mkv_unknown_clusters(data):
|
||||
"""the same Matroska file with every Cluster's size field rewritten to 'unknown' (same length)"""
|
||||
b = bytearray(data)
|
||||
p = 0
|
||||
# EBML header
|
||||
i, n = ebml_id(b, p)
|
||||
s, m = ebml_vint(b, p + n)
|
||||
p += n + m + s
|
||||
i, n = ebml_id(b, p) # Segment
|
||||
s, m = ebml_vint(b, p + n)
|
||||
p += n + m
|
||||
while p < len(b):
|
||||
i, n = ebml_id(b, p)
|
||||
s, m = ebml_vint(b, p + n)
|
||||
if i == 0x1F43B675:
|
||||
b[p + n] = (0xFF >> (m - 1)) if m < 8 else 0x01
|
||||
for k in range(1, m):
|
||||
b[p + n + k] = 0xFF
|
||||
if m == 1:
|
||||
b[p + n] = 0xFF
|
||||
p += n + m + s
|
||||
return bytes(b)
|
||||
@@ -0,0 +1,53 @@
|
||||
-- tools/fixtures/_video_encode: run by tools/fixtures/videoenc.py (luau, from the repo root) so ffprobe / ffmpeg can
|
||||
-- check our video writers: remuxes and re-encodes the container fixtures (tests/gen/mkv_cases, avi_cases, mp4_cases) and the
|
||||
-- animated GIF of tests/gen/videoenc_src, and prints "<name> <hex>" lines (or "<name> ERR <message>").
|
||||
local F = require("@formats")
|
||||
local Mkv = require("@tests/gen/mkv_cases")
|
||||
local Avi = require("@tests/gen/avi_cases")
|
||||
local Mp4 = require("@tests/gen/mp4_cases")
|
||||
local Src = require("@tests/gen/videoenc_src")
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local t = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(t)
|
||||
end
|
||||
|
||||
local function find(list: any, name: string): string
|
||||
for _, c in list do
|
||||
if c.name == name then
|
||||
return c.data
|
||||
end
|
||||
end
|
||||
error("no fixture " .. name)
|
||||
end
|
||||
|
||||
local JOBS = {
|
||||
{ "remux.webm", find(Mkv, "vp8_opus.webm"), "webm", {} },
|
||||
{ "copy.mkv", find(Mkv, "mjpeg_pcm.mkv"), "mkv", {} },
|
||||
{ "vp8_mjpeg.mkv", find(Mkv, "vp8_opus.webm"), "mkv", { reencode = true, quality = 92 } },
|
||||
{ "copy.avi", find(Avi, "mjpeg_pcm.avi"), "avi", {} },
|
||||
{ "vp8_mjpeg.avi", find(Mkv, "vp8_opus.webm"), "avi", { quality = 92 } },
|
||||
{ "mpeg1_mjpeg.avi", find(Mkv, "mpeg1_mp2.mkv"), "avi", { quality = 92 } },
|
||||
{ "gif.avi", Src.gif, "avi", { quality = 95 } },
|
||||
{ "gif.mkv", Src.gif, "mkv", { quality = 95 } },
|
||||
{ "gif.y4m", Src.gif, "y4m", {} },
|
||||
{ "webm.y4m", find(Mkv, "vp8_opus.webm"), "y4m", {} },
|
||||
{ "gif.mp4", Src.gif, "mp4", { quality = 95 } },
|
||||
{ "pcm.mov", find(Mkv, "mjpeg_pcm.mkv"), "mov", {} },
|
||||
{ "h264_aac.mov", find(Mp4, "h264_aac.mp4"), "mov", {} },
|
||||
{ "h264_aac.mkv", find(Mp4, "h264_aac.mp4"), "mkv", {} },
|
||||
{ "vp8_mjpeg.mp4", find(Mkv, "vp8_opus.webm"), "mp4", { quality = 92 } },
|
||||
{ "flac.mp4", find(Mp4, "mjpeg_flac.mp4"), "mp4", {} },
|
||||
}
|
||||
for _, j in JOBS do
|
||||
local name, data, fmt, opts = j[1], j[2], j[3], j[4]
|
||||
local out, err = F.convert(buffer.fromstring(data), fmt, opts)
|
||||
if out then
|
||||
print(name .. " " .. hex(out))
|
||||
else
|
||||
print(name .. " ERR " .. string.gsub(tostring(err), "%s", "_"))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,152 @@
|
||||
# AVI fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + PCM with idx1, the same with OpenDML indexes added
|
||||
# here, MJPEG + IMA
|
||||
# ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA / I420 video) and edits made here (the OpenDML indexes renamed to
|
||||
# JUNK so idx1 is used; idx1 renamed too so the movi list is scanned; a truncated file). For each file: ffprobe's
|
||||
# streams and packets, ffmpeg's frames (CRC-32 of yuv420p, or of rgba for uncompressed RGB; the first frames raw for
|
||||
# PSNR checks) and ffmpeg's decoded audio (f32).
|
||||
# tests/gen/avi_cases.luau { { name, data, streams, packets, frames, yuv, rgba, pcm, ... } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_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"]
|
||||
|
||||
W, H = 160, 120
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H)]
|
||||
|
||||
|
||||
def sine(rate, ch=1):
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, "-ac", str(ch)]
|
||||
|
||||
|
||||
def rename(data, old, new):
|
||||
"""every chunk id `old` renamed to `new` (same length), found by walking the RIFF lists"""
|
||||
b = bytearray(data)
|
||||
|
||||
def walk(p, end):
|
||||
while p + 8 <= end:
|
||||
cid = bytes(b[p:p + 4])
|
||||
size = int.from_bytes(b[p + 4:p + 8], "little")
|
||||
if cid in (b"RIFF", b"LIST"):
|
||||
walk(p + 12, min(end, p + 8 + size))
|
||||
elif cid == old:
|
||||
b[p:p + 4] = new
|
||||
p += 8 + size + (size & 1)
|
||||
walk(0, len(b))
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def chunks(b, p, end):
|
||||
out = []
|
||||
while p + 8 <= end:
|
||||
cid = b[p:p + 4]
|
||||
size = int.from_bytes(b[p + 4:p + 8], "little")
|
||||
out.append((cid, p, size))
|
||||
p += 8 + size + (size & 1)
|
||||
return out
|
||||
|
||||
|
||||
def ck(cid, body):
|
||||
return cid + len(body).to_bytes(4, "little") + body + (b"\0" if len(body) & 1 else b"")
|
||||
|
||||
|
||||
def add_odml(data):
|
||||
"""the same AVI with OpenDML indexes: an indx super index in every strl pointing at an ix## standard index
|
||||
appended to the movi list (built from idx1, which is kept)"""
|
||||
b = data
|
||||
top = chunks(b, 12, len(b))
|
||||
hdrl = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"hdrl")
|
||||
movi = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"movi")
|
||||
idx1 = next(c for c in top if c[0] == b"idx1")
|
||||
movi_base = movi[1] + 8 # the 'movi' fourcc
|
||||
streams = {}
|
||||
for k in range(idx1[2] // 16):
|
||||
e = idx1[1] + 8 + k * 16
|
||||
cid = b[e:e + 4]
|
||||
flags, off, size = (int.from_bytes(b[e + 4 + 4 * i:e + 8 + 4 * i], "little") for i in range(3))
|
||||
sn = int(cid[:2])
|
||||
streams.setdefault(sn, (cid, []))[1].append((movi_base + off + 8, size, bool(flags & 0x10)))
|
||||
n = len([c for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]) if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl"])
|
||||
INDX = 8 + 24 + 16 # one super index entry
|
||||
delta = n * INDX
|
||||
# the ix## chunks at the end of the movi list
|
||||
ixs = []
|
||||
pos = movi[1] + 8 + movi[2] + delta # where the first ix chunk starts (movi grows by them)
|
||||
for sn in range(n):
|
||||
cid, ents = streams.get(sn, (b"%02dwb" % sn, []))
|
||||
body = (2).to_bytes(2, "little") + bytes([0, 1]) + len(ents).to_bytes(4, "little") + cid + \
|
||||
(0).to_bytes(8, "little") + bytes(4)
|
||||
for off, size, key in ents:
|
||||
body += (off + delta).to_bytes(4, "little") + (size | (0 if key else 0x80000000)).to_bytes(4, "little")
|
||||
chunk = ck(b"ix%02d" % sn, body)
|
||||
ixs.append((pos, len(chunk), len(ents), cid, chunk))
|
||||
pos += len(chunk)
|
||||
# hdrl with an indx in every strl
|
||||
out_h = b""
|
||||
si = 0
|
||||
for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]):
|
||||
raw = b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)]
|
||||
if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl":
|
||||
p, ln, cnt, cid, _ = ixs[si]
|
||||
indx = (4).to_bytes(2, "little") + bytes([0, 0]) + (1).to_bytes(4, "little") + cid + bytes(12) + \
|
||||
p.to_bytes(8, "little") + ln.to_bytes(4, "little") + cnt.to_bytes(4, "little")
|
||||
raw = ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + ck(b"indx", indx))
|
||||
si += 1
|
||||
out_h += raw
|
||||
out = b""
|
||||
for c in top:
|
||||
if c is hdrl:
|
||||
out += ck(b"LIST", b"hdrl" + out_h)
|
||||
elif c is movi:
|
||||
out += ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + b"".join(x[4] for x in ixs))
|
||||
else:
|
||||
out += b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)]
|
||||
res = b"RIFF" + (len(out) + 4).to_bytes(4, "little") + b"AVI " + out
|
||||
assert res[ixs[0][0]:ixs[0][0] + 2] == b"ix", "odml layout"
|
||||
return res
|
||||
|
||||
|
||||
def case(tmp, name, rgba=False, raw_frames=2, pcm_frames=8192):
|
||||
path = os.path.join(tmp, name)
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
w, h = vs[0]["width"], vs[0]["height"]
|
||||
if rgba:
|
||||
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
|
||||
n = w * h * 4
|
||||
c["rgba"] = [V.crc(raw[i:i + n]) for i in range(0, len(raw) - n + 1, n)]
|
||||
else:
|
||||
frames = V.yuv_frames(path, w, h, codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:raw_frames]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:pcm_frames * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="avifx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.avi")
|
||||
ff(*SRC, *sine(22050), "-t", "1", "-c:v", "mjpeg", "-q:v", "5", "-c:a", "adpcm_ima_wav", "mjpeg_ima.avi")
|
||||
ff(*SRC, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "500k", "-c:a", "mp2", "mpeg1_mp2.avi")
|
||||
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgr24", "bgr24.avi")
|
||||
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgra", "bgra.avi")
|
||||
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "yuv420p", "i420.avi")
|
||||
ff(*SRC, *sine(8000), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_u8", "pcm_u8.avi")
|
||||
full = open(os.path.join(tmp, "mjpeg_pcm.avi"), "rb").read()
|
||||
idx1 = rename(full, b"indx", b"JUNK")
|
||||
open(os.path.join(tmp, "idx1_only.avi"), "wb").write(idx1)
|
||||
open(os.path.join(tmp, "no_index.avi"), "wb").write(rename(idx1, b"idx1", b"JUNK"))
|
||||
open(os.path.join(tmp, "odml.avi"), "wb").write(add_odml(full))
|
||||
cases = [case(tmp, "mjpeg_pcm.avi"), case(tmp, "mjpeg_ima.avi"), case(tmp, "mpeg1_mp2.avi"),
|
||||
case(tmp, "bgr24.avi", rgba=True), case(tmp, "bgra.avi", rgba=True), case(tmp, "i420.avi"),
|
||||
case(tmp, "pcm_u8.avi"), case(tmp, "idx1_only.avi"), case(tmp, "no_index.avi"),
|
||||
case(tmp, "odml.avi")]
|
||||
cases.append({"name": "truncated.avi", "data": full[: len(full) * 6 // 10], "truncated": True})
|
||||
ctx.emit("avi_cases", cases)
|
||||
@@ -0,0 +1,317 @@
|
||||
# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources,
|
||||
# yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame:
|
||||
# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes
|
||||
# (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged
|
||||
# ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact
|
||||
# rgba CRC-32 of djpeg -dct int (bit-exact)
|
||||
# ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's
|
||||
# IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240)
|
||||
# Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as
|
||||
# Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields,
|
||||
# each its own half-height JPEG with an AVI1 segment of polarity 1, back to back).
|
||||
# tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } },
|
||||
# ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } }
|
||||
# tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our
|
||||
# encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file
|
||||
# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources
|
||||
# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate):
|
||||
# Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33.
|
||||
import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
FF = ["-hide_banner", "-loglevel", "error", "-y"]
|
||||
|
||||
|
||||
def b64(b):
|
||||
return base64.b64encode(b).decode()
|
||||
|
||||
|
||||
def z64(b):
|
||||
return base64.b64encode(zlib.compress(b, 9)).decode()
|
||||
|
||||
|
||||
def tool(ctx, pkg, name):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip()
|
||||
|
||||
|
||||
def store(attr):
|
||||
return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True,
|
||||
capture_output=True, text=True).stdout.strip().split("\n")[0]
|
||||
|
||||
|
||||
class TurboJpeg:
|
||||
"""the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out"""
|
||||
|
||||
def __init__(self):
|
||||
lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so"))
|
||||
lib.tj3Init.restype = ctypes.c_void_p
|
||||
lib.tj3Init.argtypes = [ctypes.c_int]
|
||||
lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
|
||||
lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
||||
lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
|
||||
lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int]
|
||||
lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
|
||||
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)]
|
||||
lib.tj3Free.argtypes = [ctypes.c_void_p]
|
||||
self.lib = lib
|
||||
self.dec = lib.tj3Init(1)
|
||||
self.enc = lib.tj3Init(0)
|
||||
|
||||
def planes(self, jpeg):
|
||||
"""-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)"""
|
||||
L = self.lib
|
||||
assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0
|
||||
w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4)
|
||||
mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss]
|
||||
pw, ph = -(-w // mw) * mw, -(-h // mh) * mh
|
||||
cw, ch = pw // mw, ph // mh
|
||||
out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch)
|
||||
assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0
|
||||
raw = out.raw
|
||||
return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch)
|
||||
|
||||
def yuv420(self, jpeg):
|
||||
"""what codecs/Jpeg { yuv = true } must produce for this frame"""
|
||||
w, h, ss, (Y, pw), cb, cr = self.planes(jpeg)
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
out += Y[y * pw:y * pw + w]
|
||||
ow, oh = (w + 1) // 2, (h + 1) // 2
|
||||
for P, cw, ch in (cb, cr):
|
||||
for y in range(oh):
|
||||
if ss == 2:
|
||||
out += P[y * cw:y * cw + ow]
|
||||
elif ss == 1:
|
||||
a = P[2 * y * cw:2 * y * cw + ow]
|
||||
b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a
|
||||
out += bytes((p + q + 1) >> 1 for p, q in zip(a, b))
|
||||
else:
|
||||
r0 = P[2 * y * cw:2 * y * cw + cw]
|
||||
r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0
|
||||
row = bytearray()
|
||||
for x in range(ow):
|
||||
x1 = min(2 * x + 1, w - 1)
|
||||
row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2)
|
||||
out += row
|
||||
return bytes(out)
|
||||
|
||||
def compress420(self, yuv, w, h, quality):
|
||||
"""yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes"""
|
||||
pw, ph = w + (w & 1), h + (h & 1)
|
||||
Y = yuv[:w * h]
|
||||
buf = bytearray()
|
||||
for y in range(ph):
|
||||
r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w]
|
||||
buf += r + r[-1:] * (pw - w)
|
||||
buf += yuv[w * h:]
|
||||
L = self.lib
|
||||
L.tj3Set(self.enc, 3, quality)
|
||||
L.tj3Set(self.enc, 4, 2)
|
||||
p, n = ctypes.c_void_p(), ctypes.c_size_t(0)
|
||||
assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0
|
||||
data = ctypes.string_at(p, n.value)
|
||||
L.tj3Free(p)
|
||||
return data
|
||||
|
||||
|
||||
def split(stream):
|
||||
"""a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)"""
|
||||
frames, pos = [], 0
|
||||
while True:
|
||||
s = stream.find(b"\xff\xd8", pos)
|
||||
if s < 0:
|
||||
return frames
|
||||
p = s + 2
|
||||
while True:
|
||||
m = stream[p + 1]
|
||||
if m == 0xD9:
|
||||
p += 2
|
||||
break
|
||||
ln = (stream[p + 2] << 8) | stream[p + 3]
|
||||
p += 2 + ln
|
||||
if m == 0xDA:
|
||||
while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7):
|
||||
p += 1
|
||||
frames.append(stream[s:p])
|
||||
pos = p
|
||||
|
||||
|
||||
def strip_dht(jpeg):
|
||||
out, pos = bytearray(jpeg[:2]), 2
|
||||
while pos < len(jpeg):
|
||||
m = jpeg[pos + 1]
|
||||
if m == 0xDA:
|
||||
out += jpeg[pos:]
|
||||
break
|
||||
ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3]
|
||||
if m != 0xC4:
|
||||
out += jpeg[pos:pos + 2 + ln]
|
||||
pos += 2 + ln
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def avi1(jpeg, polarity):
|
||||
"""an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)"""
|
||||
n = len(jpeg) + 18
|
||||
body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big")
|
||||
return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
work = tempfile.mkdtemp(prefix="formats-mjpeg-")
|
||||
try:
|
||||
_generate(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, work):
|
||||
ffmpeg = tool(ctx, "ffmpeg", "ffmpeg")
|
||||
djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg")
|
||||
tj = TurboJpeg()
|
||||
W = lambda n: os.path.join(work, n)
|
||||
|
||||
def ff(*args):
|
||||
subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True)
|
||||
|
||||
def source(src, w, h, frames, extra=()):
|
||||
# a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes)
|
||||
sw, sh = w + (w & 1), h + (h & 1)
|
||||
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames),
|
||||
"-vf", "scale=%d:%d" % (w, h)] + list(extra)
|
||||
|
||||
def rgba_crc(jpeg):
|
||||
p = W("f.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout
|
||||
return zlib.crc32(rgba_of_pnm(r))
|
||||
|
||||
def rgba_of_pnm(d):
|
||||
# djpeg's "P6\n<w> <h>\n255\n" + RGB -> RGBA
|
||||
parts = d.split(maxsplit=3)
|
||||
w, h = int(parts[1]), int(parts[2])
|
||||
rgb = d[len(d) - w * h * 3:]
|
||||
out = bytearray(w * h * 4)
|
||||
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
|
||||
out[3::4] = b"\xff" * (w * h)
|
||||
return bytes(out)
|
||||
|
||||
def ffdecode(jpeg, fmt):
|
||||
p = W("ff.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
o = W("ff.raw")
|
||||
ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o)
|
||||
return open(o, "rb").read()
|
||||
|
||||
streams = []
|
||||
|
||||
def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None):
|
||||
out = W(name + ".mjpeg")
|
||||
ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out)
|
||||
frames = split(open(out, "rb").read())
|
||||
assert len(frames) == nframes, (name, len(frames))
|
||||
entries = []
|
||||
for fr in frames:
|
||||
ref = fr
|
||||
data = mutate(fr) if mutate else fr
|
||||
entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)})
|
||||
ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))}
|
||||
if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240
|
||||
ref["rgba"] = z64(ffdecode(frames[0], "rgba"))
|
||||
streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref})
|
||||
|
||||
stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3"))
|
||||
stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3"))
|
||||
stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4"))
|
||||
stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6"))
|
||||
stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2"))
|
||||
stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2"))
|
||||
stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31"))
|
||||
# Motion-JPEG as AVI stores it: the annex K tables left out
|
||||
stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
|
||||
stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
|
||||
# an AVI1 segment (progressive, polarity 0) and padding / junk after EOI
|
||||
stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"),
|
||||
lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8")
|
||||
|
||||
# an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back
|
||||
full = W("full.yuv")
|
||||
ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full)
|
||||
fy = open(full, "rb").read()
|
||||
fw, fh = 320, 240
|
||||
fields, fsrc = [], []
|
||||
for k in range(2):
|
||||
rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2))
|
||||
cw = fw // 2
|
||||
chroma = b""
|
||||
for pl in range(2):
|
||||
base = fw * fh + pl * cw * (fh // 2)
|
||||
chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2))
|
||||
p = W("field%d.yuv" % k)
|
||||
open(p, "wb").write(rows + chroma)
|
||||
o = W("field%d.jpg" % k)
|
||||
ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p",
|
||||
"-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
|
||||
fields.append(open(o, "rb").read())
|
||||
data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1)
|
||||
|
||||
def weave(a, b, w, hf, bpp):
|
||||
out = bytearray()
|
||||
for y in range(2 * hf):
|
||||
src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2)
|
||||
out += src[k * w * bpp:(k + 1) * w * bpp]
|
||||
return bytes(out)
|
||||
|
||||
ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1])
|
||||
hf, cw, chf = fh // 2, fw // 2, fh // 4
|
||||
wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1)
|
||||
for pl in range(2):
|
||||
o = fw * hf + pl * cw * chf
|
||||
wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1)
|
||||
|
||||
def rgba_raw(jpeg):
|
||||
p = W("f.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout)
|
||||
|
||||
wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4)
|
||||
ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh,
|
||||
"yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}})
|
||||
|
||||
# the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8
|
||||
enc = []
|
||||
for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)),
|
||||
("mandel_176x144", "mandelbrot", 176, 144, (30, 95)),
|
||||
("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)),
|
||||
("one_1x1", "testsrc2", 1, 1, (90,))):
|
||||
p = W(name + ".yuv")
|
||||
ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv"))
|
||||
raw = open(W("s.yuv"), "rb").read()
|
||||
if (w, h) == (1, 1):
|
||||
raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source
|
||||
open(p, "wb").write(raw)
|
||||
for q in qs:
|
||||
want = tj.compress420(raw, w, h, q)
|
||||
got = ffdecode(want, "yuvj420p") if w > 1 else None
|
||||
psnr = 99.0
|
||||
if got:
|
||||
se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h]))
|
||||
psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se)
|
||||
enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw),
|
||||
"want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)})
|
||||
ctx.emit("mjpeg_enc", enc)
|
||||
|
||||
bench = []
|
||||
for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"),
|
||||
("640x480 4:2:2", 640, 480, "yuvj422p")):
|
||||
o = W("bench.mjpeg")
|
||||
ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
|
||||
fr = split(open(o, "rb").read())[0]
|
||||
bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))})
|
||||
srcs = []
|
||||
for w, h in ((320, 240), (640, 480)):
|
||||
ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv"))
|
||||
srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())})
|
||||
ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs})
|
||||
@@ -0,0 +1,131 @@
|
||||
# Matroska / WebM fixtures (tools/fixtures.py): files made by ffmpeg (libvpx VP8 + Opus / Vorbis WebM, MJPEG + PCM,
|
||||
# MPEG-1 + MP3, srt subtitles) and mkvmerge (Xiph / EBML / fixed lacing, header-removal compression), plus edits made
|
||||
# here (every cluster rewritten to an unknown size, a truncated file). For each file: ffprobe's streams and packets
|
||||
# (pts, duration, keyframe flag, size, CRC-32 of the data), ffmpeg's yuv420p frames (CRC-32 each; the first frames
|
||||
# raw for PSNR checks) and ffmpeg's decoded audio (f32).
|
||||
# tests/gen/mkv_cases.luau { { name, data, streams, packets, frames = { crc }, yuv = { raw frame }, pcm, ... } }
|
||||
import importlib.util, os, subprocess, tempfile
|
||||
|
||||
_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"]
|
||||
|
||||
W, H = 160, 120
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=15" % (W, H)]
|
||||
MOVE = ["-f", "lavfi", "-i", "mandelbrot=size=%dx%d:rate=15" % (W, H)]
|
||||
|
||||
|
||||
def sine(rate, ch=1):
|
||||
if ch == 1:
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate]
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate, "-ac", str(ch)]
|
||||
|
||||
|
||||
def case(ctx, tmp, name, raw_frames=2, audio=True, video=True, pcm_frames=8192):
|
||||
path = os.path.join(tmp, name)
|
||||
data = open(path, "rb").read()
|
||||
c = {"name": name, "data": data, "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if video and vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:raw_frames]
|
||||
if audio and any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm if pcm_frames is None else pcm[:pcm_frames * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def el(i, payload):
|
||||
"""an EBML element: id (int), payload bytes"""
|
||||
n = len(payload)
|
||||
size = bytes([0x01]) + n.to_bytes(7, "big")
|
||||
return i.to_bytes((i.bit_length() + 7) // 8, "big") + size + payload
|
||||
|
||||
|
||||
def uint(v):
|
||||
return v.to_bytes(max(1, (v.bit_length() + 7) // 8), "big")
|
||||
|
||||
|
||||
def lacing_file(ctx):
|
||||
"""A_PCM/INT/LIT mono 8 kHz s16 in three SimpleBlocks, Xiph-, EBML- and fixed-laced (DefaultDuration 10 ms)"""
|
||||
rng = ctx.rng(7)
|
||||
frames = [bytes(rng.randrange(256) for _ in range(2 * n)) for n in (80, 40, 120, 80, 80, 80, 80, 80, 80, 80)]
|
||||
head = el(0x1A45DFA3, el(0x4282, b"matroska") + el(0x4287, uint(4)) + el(0x4285, uint(2)))
|
||||
info = el(0x1549A966, el(0x2AD7B1, uint(1000000)) + el(0x4D80, b"fixture") + el(0x5741, b"fixture"))
|
||||
track = el(0xAE, el(0xD7, uint(1)) + el(0x73C5, uint(1)) + el(0x83, uint(2)) + el(0x86, b"A_PCM/INT/LIT") +
|
||||
el(0x23E383, uint(10000000)) + el(0xE1, el(0xB5, __import__("struct").pack(">d", 8000.0)) +
|
||||
el(0x9F, uint(1)) + el(0x6264, uint(16))))
|
||||
tracks = el(0x1654AE6B, track)
|
||||
|
||||
def xiph(sizes):
|
||||
out = b""
|
||||
for s in sizes:
|
||||
out += b"\xff" * (s // 255) + bytes([s % 255])
|
||||
return out
|
||||
|
||||
def ebmlnum(v):
|
||||
n = 1
|
||||
while v >= (1 << (7 * n)) - 1:
|
||||
n += 1
|
||||
return ((1 << (7 * n)) | v).to_bytes(n, "big")
|
||||
|
||||
def sebml(v, n=2):
|
||||
return ((1 << (7 * n)) | (v + (1 << (7 * n - 1)) - 1)).to_bytes(n, "big")
|
||||
|
||||
def block(rel, flags, body):
|
||||
return el(0xA3, b"\x81" + rel.to_bytes(2, "big") + bytes([flags]) + body)
|
||||
|
||||
f = frames
|
||||
b1 = block(0, 0x80 | 0x02, bytes([2]) + xiph([len(f[0]), len(f[1])]) + f[0] + f[1] + f[2])
|
||||
sizes = [len(f[3]), len(f[4]), len(f[5])]
|
||||
b2 = block(40, 0x80 | 0x06, bytes([2]) + ebmlnum(sizes[0]) + sebml(sizes[1] - sizes[0]) + f[3] + f[4] + f[5])
|
||||
b3 = block(70, 0x80 | 0x04, bytes([3]) + f[6] + f[7] + f[8] + f[9])
|
||||
cluster = el(0x1F43B675, el(0xE7, uint(0)) + b1 + b2 + b3)
|
||||
return head + el(0x18538067, info + tracks + cluster)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="mkvfx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *sine(48000), "-t", "1", "-c:v", "libvpx", "-g", "8", "-auto-alt-ref", "1", "-lag-in-frames", "8",
|
||||
"-b:v", "300k", "-c:a", "libopus", "-b:a", "48k", "vp8_opus.webm")
|
||||
ff(*MOVE, *sine(44100, 2), "-t", "1", "-c:v", "libvpx", "-g", "30", "-b:v", "200k", "-c:a", "libvorbis",
|
||||
"vp8_vorbis.webm")
|
||||
ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.mkv")
|
||||
ff(*MOVE, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "400k", "-c:a", "mp2", "-b:a", "64k",
|
||||
"mpeg1_mp2.mkv")
|
||||
ff(*SRC, *sine(48000, 2), "-t", "1", "-c:v", "libvpx", "-g", "15", "-c:a", "flac", "vp8_flac.mkv")
|
||||
open(os.path.join(tmp, "subs.srt"), "w").write(
|
||||
"1\n00:00:00,100 --> 00:00:00,500\nHello\n\n2\n00:00:00,600 --> 00:00:00,900\nWorld <b>bold</b>\n\n")
|
||||
ff(*SRC, "-i", "subs.srt", "-t", "1", "-c:v", "mjpeg", "-c:s", "srt", "subs.mkv")
|
||||
# mkvmerge: Xiph lacing (Vorbis) and zlib content compression; a file crafted here with all three lacings
|
||||
mk = lambda *a: subprocess.run(["nix", "shell", "nixpkgs#mkvtoolnix-cli", "-c", "mkvmerge", "-q"] + list(a),
|
||||
cwd=tmp, check=False, capture_output=True)
|
||||
mk("-o", "laced_vorbis.mkv", "vp8_vorbis.webm")
|
||||
ff(*sine(44100), "-t", "1", "-c:a", "libvorbis", "v.ogg")
|
||||
mk("-o", "zlib_vorbis.mka", "--compression", "0:zlib", "v.ogg")
|
||||
open(os.path.join(tmp, "lacing.mka"), "wb").write(lacing_file(ctx))
|
||||
# unknown-size clusters, a truncated file
|
||||
open(os.path.join(tmp, "unknown_clusters.webm"), "wb").write(
|
||||
V.mkv_unknown_clusters(open(os.path.join(tmp, "vp8_opus.webm"), "rb").read()))
|
||||
full = open(os.path.join(tmp, "mjpeg_pcm.mkv"), "rb").read()
|
||||
|
||||
cases = [
|
||||
case(ctx, tmp, "vp8_opus.webm"),
|
||||
case(ctx, tmp, "vp8_vorbis.webm"),
|
||||
case(ctx, tmp, "mjpeg_pcm.mkv"),
|
||||
case(ctx, tmp, "mpeg1_mp2.mkv"),
|
||||
case(ctx, tmp, "vp8_flac.mkv"),
|
||||
case(ctx, tmp, "subs.mkv", audio=False),
|
||||
case(ctx, tmp, "unknown_clusters.webm"),
|
||||
]
|
||||
for name in ("laced_vorbis.mkv", "zlib_vorbis.mka", "lacing.mka"):
|
||||
if os.path.exists(os.path.join(tmp, name)):
|
||||
cases.append(case(ctx, tmp, name))
|
||||
cut = full[: len(full) * 7 // 10]
|
||||
cases.append({"name": "truncated.mkv", "data": cut, "truncated": True})
|
||||
ctx.emit("mkv_cases", cases)
|
||||
@@ -0,0 +1,50 @@
|
||||
# MP4 / MOV fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + AAC MP4, MJPEG + PCM MOV, H.264 with B-frames
|
||||
# + AAC (edit lists), fragmented MP4, MPEG-1 + Opus, MJPEG + FLAC, MJPEG + MP2 MOV) with ffprobe's streams and packets,
|
||||
# ffmpeg's frames (CRC-32; the first raw) and audio (f32). Our MP4 / MOV writer's files are checked in
|
||||
# tools/fixtures/videoenc.py.
|
||||
# tests/gen/mp4_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_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"]
|
||||
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"]
|
||||
|
||||
|
||||
def aud(rate, ch=1):
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=550:sample_rate=%d" % rate, "-ac", str(ch)]
|
||||
|
||||
|
||||
def case(tmp, name):
|
||||
path = os.path.join(tmp, name)
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:2]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:8192 * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="mp4fx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-q:v", "4", "-c:a", "aac", "-b:a", "96k", "mjpeg_aac.mp4")
|
||||
ff(*SRC, *aud(48000, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_s16le", "mjpeg_pcm.mov")
|
||||
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac",
|
||||
"h264_aac.mp4")
|
||||
ff(*SRC, *aud(48000), "-t", "1", "-c:v", "mjpeg", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov",
|
||||
"fragmented.mp4")
|
||||
ff(*SRC, *aud(48000), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-c:a", "libopus", "mpeg1_opus.mp4")
|
||||
ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "flac", "mjpeg_flac.mp4")
|
||||
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-c:a", "mp2", "mjpeg_mp2.mov")
|
||||
cases = [case(tmp, n) for n in ("mjpeg_aac.mp4", "mjpeg_pcm.mov", "h264_aac.mp4", "fragmented.mp4",
|
||||
"mpeg1_opus.mp4", "mjpeg_flac.mp4", "mjpeg_mp2.mov")]
|
||||
ctx.emit("mp4_cases", cases)
|
||||
@@ -0,0 +1,170 @@
|
||||
# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary
|
||||
# streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices,
|
||||
# B-frames, a size change), their access units, and ffmpeg's own decode of each as references:
|
||||
# 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) }
|
||||
# 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
|
||||
# Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with
|
||||
# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and
|
||||
# few whole frames the set stays near 10 MB.
|
||||
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", "mpeg1video", "-f", "mpeg1video"]
|
||||
# a non-default intra matrix (steeper) and inter matrix (rising), 64 values in natural order
|
||||
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, rate, t):
|
||||
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
|
||||
|
||||
|
||||
# name: (ffmpeg input + encoder args, size patched into the sequence headers or None, rgba sample picks, yuv picks)
|
||||
CASES = {
|
||||
"qcif_200k": (src("testsrc2", 176, 144, 25, 1.2) + ["-b:v", "200k", "-bf", "0", "-g", "50"], None),
|
||||
"main_450k": (src("testsrc2", 320, 180, 24, 1.5) + ["-b:v", "450k", "-bf", "0", "-g", "48"], None),
|
||||
"zoom_150k": (src("mandelbrot", 320, 180, 24, 1.5) + ["-b:v", "150k", "-bf", "0", "-g", "48"], None),
|
||||
"zoom_1500k": (src("mandelbrot", 320, 180, 24, 1) + ["-b:v", "1500k", "-bf", "0", "-g", "48"], None),
|
||||
"big_1000k": (src("testsrc2", 640, 360, 24, 0.5) + ["-b:v", "1000k", "-bf", "0", "-g", "36"], None),
|
||||
# odd sizes: ffmpeg's encoder only writes even ones, so the size in the sequence headers is patched; the
|
||||
# reference is ffmpeg's decode of the unpatched stream, cropped (swscale's odd-size RGBA path interpolates
|
||||
# chroma differently from its even-size one, which is what the decoder matches)
|
||||
"odd_173x95": (src("mandelbrot", 174, 96, 24, 1) + ["-b:v", "300k", "-bf", "0", "-g", "24"], (173, 95)),
|
||||
"bframes": (src("testsrc2", 320, 180, 24, 1) + ["-b:v", "600k", "-bf", "2", "-g", "24"], None),
|
||||
"bframes_zoom": (src("mandelbrot", 176, 144, 24, 1.5) + ["-b:v", "250k", "-bf", "3", "-g", "16"], None),
|
||||
"matrix": (src("testsrc2", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "12",
|
||||
"-intra_matrix", INTRA, "-inter_matrix", INTER], None),
|
||||
"q1": (src("mandelbrot", 176, 144, 25, 0.6) + ["-q:v", "1", "-bf", "0", "-g", "8"], None),
|
||||
"q31": (src("testsrc2", 176, 144, 25, 1) + ["-q:v", "31", "-bf", "0", "-g", "25"], None),
|
||||
"zeromv": (src("mandelbrot", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "25", "-me_method", "zero"], None),
|
||||
}
|
||||
|
||||
|
||||
def patch_size(es, w, h):
|
||||
# every sequence header (00 00 01 B3): 12-bit width, 12-bit height
|
||||
b = bytearray(es)
|
||||
i = 0
|
||||
while True:
|
||||
i = b.find(b"\x00\x00\x01\xb3", i)
|
||||
if i < 0:
|
||||
return bytes(b)
|
||||
b[i + 4] = w >> 4
|
||||
b[i + 5] = ((w & 15) << 4) | (h >> 8)
|
||||
b[i + 6] = h & 255
|
||||
i += 4
|
||||
|
||||
|
||||
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 crop(frames, w, h, cw, ch, bpp):
|
||||
fs = w * h * bpp
|
||||
out = bytearray()
|
||||
for k in range(len(frames) // fs):
|
||||
for y in range(ch):
|
||||
o = k * fs + y * w * bpp
|
||||
out += frames[o:o + cw * bpp]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def crop_yuv(frames, w, h, cw, ch):
|
||||
fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
out = bytearray()
|
||||
for k in range(len(frames) // fs):
|
||||
f = frames[k * fs:(k + 1) * fs]
|
||||
out += crop(f[:w * h], w, h, cw, ch, 1)
|
||||
c = ((w + 1) // 2) * ((h + 1) // 2)
|
||||
for pl in range(2):
|
||||
out += crop(f[w * h + pl * c:w * h + (pl + 1) * c], (w + 1) // 2, (h + 1) // 2, (cw + 1) // 2, (ch + 1) // 2, 1)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="formats-mpeg1-") as tmp:
|
||||
def encode(name, args, size):
|
||||
path = os.path.join(tmp, name + ".m1v")
|
||||
ff(args + ENC + [path])
|
||||
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])
|
||||
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])
|
||||
return open(out, "rb").read(), w, h
|
||||
|
||||
for name, (args, size) in CASES.items():
|
||||
es, path = encode(name, args, size)
|
||||
rgba, w, h = reference(path, "rgba")
|
||||
yuv, _, _ = reference(path, "yuv420p")
|
||||
if size:
|
||||
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
|
||||
w, h = size
|
||||
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
n = len(rgba) // fs
|
||||
means = []
|
||||
for k in range(n):
|
||||
fr = rgba[k * fs:(k + 1) * fs]
|
||||
means.append([round(sum(fr[c::4]) / (w * h), 4) for c in range(3)])
|
||||
# whole frames: the first P-picture and the last one (the most drift) as RGBA, three as yuv420p
|
||||
picks = sorted({1, n - 1}) if n > 2 else list(range(n))
|
||||
ypicks = sorted({0, n // 2, n - 1})
|
||||
ctx.emit("mpeg1_" + name, {
|
||||
"name": name, "width": w, "height": h, "frames": n, "file": b64(es), "units": access_units(es),
|
||||
"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],
|
||||
})
|
||||
|
||||
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
|
||||
a, pa = encode("sc_a", src("testsrc2", 176, 144, 24, 0.5) + ["-b:v", "200k", "-bf", "0", "-g", "6"], None)
|
||||
b, pb = encode("sc_b", src("mandelbrot", 320, 180, 24, 0.5) + ["-b:v", "400k", "-bf", "0", "-g", "6"], None)
|
||||
parts = []
|
||||
for path in (pa, pb):
|
||||
rg, w, h = reference(path, "rgba")
|
||||
n = len(rg) // (w * h * 4)
|
||||
parts.append({"width": w, "height": h, "frames": n, "last": z64(rg[(n - 1) * w * h * 4:])})
|
||||
ctx.emit("mpeg1_sizechange", {"file": b64(a + b), "parts": parts})
|
||||
|
||||
bench = []
|
||||
for w, h, rate in ((320, 240, "600k"), (640, 480, "1500k")):
|
||||
es, _ = encode("bench", src("testsrc2", w, h, 25, 2) + ["-b:v", rate, "-bf", "2", "-g", "25"], None)
|
||||
bench.append({"width": w, "height": h, "file": b64(es), "units": access_units(es)})
|
||||
ctx.emit("mpeg1_bench", bench)
|
||||
@@ -0,0 +1,59 @@
|
||||
# MPEG-TS / PS fixtures (tools/fixtures.py): transport streams (MPEG-1 + MP2 as bugtv plays them, with B-frames,
|
||||
# H.264 + AAC, M2TS 192-byte packets, garbage before the first packet) and program streams (MPEG-1 system stream,
|
||||
# MPEG-2 PS / VOB layout, B-frames, a raw .m1v elementary stream), made by ffmpeg. For each file: ffprobe's streams
|
||||
# and packets, ffmpeg's frames (CRC-32 of yuv420p; the first frames raw) and audio (f32).
|
||||
# tests/gen/mpegts_cases.luau, tests/gen/mpegps_cases.luau
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_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"]
|
||||
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"]
|
||||
AUD = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100"]
|
||||
|
||||
|
||||
def case(tmp, name, raw_frames=3, pcm_frames=8192, packets=True):
|
||||
path = os.path.join(tmp, name)
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path)}
|
||||
if packets:
|
||||
c["packets"] = V.packets(path)
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:raw_frames]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:pcm_frames * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="mpegfx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-b:a", "128k",
|
||||
"-f", "mpegts", "mpeg1_mp2.ts")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpegts",
|
||||
"bframes.ts")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-g", "10", "-c:a", "aac", "-b:a", "96k",
|
||||
"-f", "mpegts", "h264_aac.ts")
|
||||
ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-f", "mpegts", "-mpegts_m2ts_mode", "1", "m2ts.m2ts")
|
||||
open(os.path.join(tmp, "garbage.ts"), "wb").write(bytes(ctx.rng(3).randrange(256) for _ in range(333)).replace(b"G", b"g") +
|
||||
open(os.path.join(tmp, "mpeg1_mp2.ts"), "rb").read())
|
||||
ts = [case(tmp, "mpeg1_mp2.ts"), case(tmp, "bframes.ts"), case(tmp, "h264_aac.ts"), case(tmp, "m2ts.m2ts"),
|
||||
case(tmp, "garbage.ts", packets=False)]
|
||||
full = ts[0]["data"]
|
||||
ts.append({"name": "truncated.ts", "data": full[: len(full) // 2 + 77], "truncated": True})
|
||||
ctx.emit("mpegts_cases", ts)
|
||||
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-f", "mpeg", "system.mpg")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpeg",
|
||||
"bframes.mpg")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-c:a", "mp2", "-f", "vob", "mpeg2ps.vob")
|
||||
ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-f", "mpeg1video", "es.m1v")
|
||||
ps = [case(tmp, n, packets=False) for n in ("system.mpg", "bframes.mpg", "mpeg2ps.vob", "es.m1v")]
|
||||
ctx.emit("mpegps_cases", ps)
|
||||
@@ -0,0 +1,27 @@
|
||||
# Video bench inputs (tools/fixtures.py, for tools/bench.luau): 1 s of testsrc2 at 320x240 and 640x480, 25 fps, as
|
||||
# MJPEG AVI, MPEG-1 TS, VP8 WebM (libvpx) and 8 frames of 320x240 Y4M.
|
||||
# tests/gen/videobench.luau { { name, size, data } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_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 generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="videobench_")
|
||||
out = []
|
||||
for size in ("320x240", "640x480"):
|
||||
src = ["-f", "lavfi", "-i", "testsrc2=size=%s:rate=25" % size, "-t", "1"]
|
||||
for name, args in (("mjpeg.avi", ["-c:v", "mjpeg", "-q:v", "4"]),
|
||||
("mpeg1.ts", ["-c:v", "mpeg1video", "-b:v", "2M", "-bf", "2", "-f", "mpegts"]),
|
||||
("vp8.webm", ["-c:v", "libvpx", "-b:v", "1M", "-g", "50"]),
|
||||
("raw.y4m", ["-pix_fmt", "yuv420p", "-frames:v", "8"])):
|
||||
if name == "raw.y4m" and size == "640x480":
|
||||
continue
|
||||
path = os.path.join(tmp, size + "_" + name)
|
||||
V.ffmpeg(src + args + [path])
|
||||
out.append({"name": name, "size": size, "data": open(path, "rb").read()})
|
||||
ctx.emit("videobench", out)
|
||||
@@ -0,0 +1,63 @@
|
||||
# Our video writers checked by ffprobe / ffmpeg (tools/fixtures.py): tools/fixtures/_video_encode.luau remuxes /
|
||||
# re-encodes the container fixtures (WebM remux, MJPEG Matroska / AVI / MP4 from VP8 and MPEG-1, MJPEG copies, H.264 +
|
||||
# AAC MP4 to MOV / Matroska, PCM MOV, FLAC MP4, an animated GIF with uneven delays to AVI / Matroska / Y4M / MP4, WebM
|
||||
# to Y4M); each output must probe in ffprobe and decode in
|
||||
# ffmpeg. Emitted per file: our bytes, ffprobe's streams and packets, ffmpeg's frames (CRC-32; the first raw) and
|
||||
# audio, so the test can decode our file with our decoders and compare.
|
||||
# tests/gen/videoenc_src.luau { gif = <animated GIF made by Pillow: 4 frames, 100 / 50 / 200 / 100 ms> }
|
||||
# tests/gen/videoenc_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } | { name, err } }
|
||||
import importlib.util, os, shutil, subprocess, tempfile
|
||||
|
||||
_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", "tools/fixtures/_video_encode.luau", "tools/fixtures/mkv.py", "tools/fixtures/avi.py", "tools/fixtures/mp4.py",
|
||||
"src/Formats/video", "src/Formats/codecs/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", "src/Formats/containers/IsoBmff",
|
||||
"src/Formats/codecs/Jpeg", "src/Formats/codecs/Vp8"]
|
||||
|
||||
GIF = r"""
|
||||
import io, sys
|
||||
from PIL import Image, ImageDraw
|
||||
frames = []
|
||||
for i, c in enumerate([(255, 0, 0), (0, 160, 0), (0, 0, 255), (240, 200, 0)]):
|
||||
im = Image.new("RGB", (64, 48), (20, 20, 20))
|
||||
d = ImageDraw.Draw(im)
|
||||
d.rectangle([4 + i * 10, 8, 24 + i * 10, 40], fill=c)
|
||||
d.ellipse([40, 4 + i * 6, 60, 20 + i * 6], fill=(255, 255, 255))
|
||||
frames.append(im)
|
||||
b = io.BytesIO()
|
||||
frames[0].save(b, "GIF", save_all=True, append_images=frames[1:], duration=[100, 50, 200, 100], loop=0)
|
||||
sys.stdout.buffer.write(b.getvalue())
|
||||
"""
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="videoenc_")
|
||||
gif = ctx.python(["pillow"], GIF)
|
||||
ctx.emit("videoenc_src", {"gif": gif})
|
||||
luau = os.environ.get("LUAU") or shutil.which("luau")
|
||||
cmd = [luau, "tools/fixtures/_video_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_video_encode.luau"]
|
||||
out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
cases = []
|
||||
for line in out.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
name, rest = line.split(" ", 1)
|
||||
if rest.startswith("ERR "):
|
||||
cases.append({"name": name, "err": rest[4:]})
|
||||
continue
|
||||
path = os.path.join(tmp, name)
|
||||
open(path, "wb").write(bytes.fromhex(rest))
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:3]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:8192 * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
cases.append(c)
|
||||
ctx.emit("videoenc_cases", cases)
|
||||
@@ -0,0 +1,133 @@
|
||||
# VP8 video fixtures (tools/fixtures.py) for tests/codecs/vp8video.luau and tools/bench.luau. Clips are encoded by
|
||||
# ffmpeg's libvpx into IVF (many encoder settings: alt-ref / hidden frames, golden refreshes, token partitions, error
|
||||
# resilience, profiles 1-3, sharpness, segmentation, q extremes, short key frame intervals, motion off the frame edges),
|
||||
# plus the official VP8 test vectors (tests/fixtures/vp8video/vp80-*.ivf, from the libvpx test data, BSD:
|
||||
# licenses/libvpx-LICENSE.txt). The reference output is ffmpeg's native vp8 decoder (bit-exact with libvpx):
|
||||
# `ffmpeg -c:v vp8 -i x.ivf -noautoscale -fps_mode passthrough -f framehash -hash crc32 -`: the CRC32 of every
|
||||
# shown yuv420p frame (and its size: key frames may change it).
|
||||
# tests/gen/vp8video_cases.luau { name, ivf, width, height (of the first frame), crcs, sizes (bytes) }
|
||||
# tests/gen/vp8video_bench.luau { { name, ivf, width, height, frames, crcs, sizes } } for tools/bench.luau
|
||||
import os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["tests/fixtures/vp8video"]
|
||||
|
||||
VECTORS = "tests/fixtures/vp8video"
|
||||
|
||||
|
||||
def ffmpeg(ctx, args):
|
||||
"""runs ffmpeg (the one on PATH when it has libvpx, else nixpkgs#ffmpeg) and returns stdout"""
|
||||
exe = shutil.which("ffmpeg")
|
||||
if exe:
|
||||
enc = subprocess.run([exe, "-hide_banner", "-encoders"], capture_output=True).stdout
|
||||
if b"libvpx " in enc:
|
||||
return subprocess.run([exe, "-hide_banner", "-loglevel", "error"] + args, capture_output=True, check=True).stdout
|
||||
return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error"] + args)
|
||||
|
||||
|
||||
def ivf_size(data):
|
||||
return data[12] | data[13] << 8, data[14] | data[15] << 8
|
||||
|
||||
|
||||
def reference(ctx, path):
|
||||
"""ffmpeg's decode: (crc32, byte size) of each shown yuv420p frame (sizes may change at key frames)"""
|
||||
out = ffmpeg(ctx, ["-c:v", "vp8", "-i", path, "-noautoscale", "-fps_mode", "passthrough", "-f", "framehash",
|
||||
"-hash", "crc32", "-"])
|
||||
frames = []
|
||||
for line in out.decode().splitlines():
|
||||
if line and not line.startswith("#"):
|
||||
f = [x.strip() for x in line.split(",")]
|
||||
frames.append((int(f[5], 16), int(f[4])))
|
||||
return frames
|
||||
|
||||
|
||||
# (name, lavfi source, frames, encoder options)
|
||||
SRC_320 = "testsrc2=s=320x240:r=25"
|
||||
PAN = "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'"
|
||||
CLIPS = [
|
||||
("default_320x240", SRC_320, 20, ["-b:v", "400k"]),
|
||||
("odd_173x95", "mandelbrot=s=173x95:r=25", 16, ["-b:v", "200k"]),
|
||||
("pan_320x240", PAN, 24, ["-b:v", "300k", "-g", "100"]),
|
||||
("altref_352x288", "testsrc2=s=352x288:r=25", 30,
|
||||
["-b:v", "300k", "-auto-alt-ref", "1", "-lag-in-frames", "16", "-arnr-maxframes", "7", "-arnr-strength", "5",
|
||||
"-arnr-type", "3", "2pass"]),
|
||||
("altref_pan", PAN, 30, ["-b:v", "250k", "-auto-alt-ref", "1", "-lag-in-frames", "25", "-g", "200", "2pass"]),
|
||||
("tokenparts3", SRC_320, 12, ["-b:v", "500k", "-slices", "8"]),
|
||||
("tokenparts1_odd", "mandelbrot=s=201x77:r=25", 12, ["-b:v", "300k", "-slices", "2"]),
|
||||
("error_resilient", PAN, 16, ["-b:v", "300k", "-error-resilient", "1"]),
|
||||
("profile1", PAN, 16, ["-b:v", "300k", "-profile:v", "1"]),
|
||||
("profile2", PAN, 16, ["-b:v", "300k", "-profile:v", "2"]),
|
||||
("profile3", PAN, 16, ["-b:v", "300k", "-profile:v", "3"]),
|
||||
("sharpness7", PAN, 12, ["-b:v", "200k", "-sharpness", "7"]),
|
||||
("sharpness3", "mandelbrot=s=160x120:r=25", 12, ["-b:v", "150k", "-sharpness", "3"]),
|
||||
("realtime_cyclic", PAN, 24,
|
||||
["-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-static-thresh", "100", "-screen-content-mode", "1"]),
|
||||
("realtime_noise", "testsrc2=s=320x240:r=25,noise=alls=30:allf=t", 16,
|
||||
["-deadline", "realtime", "-cpu-used", "4", "-b:v", "400k"]),
|
||||
("best_split", "testsrc2=s=176x144:r=25,rotate=a='t*0.4':c=black", 16, ["-deadline", "best", "-b:v", "250k"]),
|
||||
("cellauto_split", "cellauto=s=176x144:rule=110:r=25,scale=176:144", 16, ["-b:v", "300k", "-cpu-used", "0"]),
|
||||
("q_high", PAN, 10, ["-qmin", "0", "-qmax", "2", "-b:v", "20M"]),
|
||||
("q_low", PAN, 16, ["-qmin", "60", "-qmax", "63", "-b:v", "20k"]),
|
||||
("keyint5", PAN, 16, ["-b:v", "300k", "-g", "5"]),
|
||||
("golden", "testsrc2=s=240x160:r=25", 40, ["-b:v", "150k", "-g", "300", "-auto-alt-ref", "0"]),
|
||||
("big_motion", "testsrc2=s=640x480:r=25,crop=w=192:h=144:x='224+200*sin(t*9)':y='168+150*cos(t*7)'", 16,
|
||||
["-b:v", "300k"]),
|
||||
("tiny_24x18", "testsrc2=s=24x18:r=25", 12, ["-b:v", "50k"]),
|
||||
("temporal_layers", PAN, 16,
|
||||
["-deadline", "realtime", "-b:v", "300k", "-ts-parameters",
|
||||
"ts_number_layers=2:ts_target_bitrate=150,300:ts_rate_decimator=2,1:ts_periodicity=2:ts_layer_id=0,1"]),
|
||||
]
|
||||
|
||||
BENCH = [
|
||||
("bench_320x240", "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'", 40,
|
||||
["-b:v", "500k"]),
|
||||
("bench_640x480", "testsrc2=s=960x720:r=25,crop=w=640:h=480:x='160+150*sin(t*3)':y='120+100*cos(t*2)'", 30,
|
||||
["-b:v", "1200k"]),
|
||||
]
|
||||
|
||||
|
||||
def encode(ctx, tmp, name, src, frames, opts):
|
||||
path = os.path.join(tmp, name + ".ivf")
|
||||
base = ["-f", "lavfi", "-i", src, "-frames:v", str(frames), "-pix_fmt", "yuv420p", "-c:v", "libvpx"]
|
||||
try:
|
||||
if "2pass" in opts: # alt-ref frames need the two-pass encoder
|
||||
opts = [o for o in opts if o != "2pass"]
|
||||
log = os.path.join(tmp, name + "-pass")
|
||||
ffmpeg(ctx, base + opts + ["-pass", "1", "-passlogfile", log, "-f", "null", "-"])
|
||||
opts = opts + ["-pass", "2", "-passlogfile", log]
|
||||
ffmpeg(ctx, base + opts + ["-f", "ivf", "-y", path])
|
||||
except subprocess.CalledProcessError as e:
|
||||
if name == "temporal_layers": # optional: depends on the libvpx wrapper's options
|
||||
return None
|
||||
raise RuntimeError("vp8video: %s: %s" % (name, e.stderr.decode(errors="replace")))
|
||||
return path
|
||||
|
||||
|
||||
def case(ctx, name, path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
w, h = ivf_size(data)
|
||||
ref = reference(ctx, path)
|
||||
return {"name": name, "ivf": data, "width": w, "height": h, "crcs": [r[0] for r in ref], "sizes": [r[1] for r in ref]}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="vp8video")
|
||||
try:
|
||||
cases = []
|
||||
vec = os.path.join(ctx.root, VECTORS)
|
||||
for f in sorted(os.listdir(vec)):
|
||||
if f.endswith(".ivf"):
|
||||
cases.append(case(ctx, f[:-4], os.path.join(vec, f)))
|
||||
for name, src, frames, opts in CLIPS:
|
||||
path = encode(ctx, tmp, name, src, frames, opts)
|
||||
if path:
|
||||
cases.append(case(ctx, name, path))
|
||||
ctx.emit("vp8video_cases", cases)
|
||||
bench = []
|
||||
for name, src, frames, opts in BENCH:
|
||||
c = case(ctx, name, encode(ctx, tmp, name, src, frames, opts))
|
||||
c["frames"] = len(c["crcs"])
|
||||
bench.append(c)
|
||||
ctx.emit("vp8video_bench", bench)
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
@@ -0,0 +1,34 @@
|
||||
# YUV4MPEG2 fixtures (tools/fixtures.py): streams written by ffmpeg in C420jpeg (odd size 173x95), C420mpeg2, C422,
|
||||
# C444, Cmono and C420p10 (10-bit) with ffmpeg's yuv420p decode of each (CRC-32 per frame; the first frames raw for
|
||||
# the converted layouts, which are compared by PSNR).
|
||||
# tests/gen/y4m_cases.luau { { name, data, width, height, rate = { num, den }, frames = { crc }, yuv = { raw } } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_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 generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="y4mfx_")
|
||||
cases = []
|
||||
for name, size, rate, pix, extra in [
|
||||
("c420jpeg.y4m", "173x95", "30000/1001", "yuv420p", []),
|
||||
("c420mpeg2.y4m", "160x120", "25", "yuv420p", ["-chroma_sample_location", "left"]),
|
||||
("c422.y4m", "160x120", "24", "yuv422p", []),
|
||||
("c444.y4m", "160x120", "10", "yuv444p", []),
|
||||
("cmono.y4m", "160x120", "10", "gray", []),
|
||||
("c420p10.y4m", "96x64", "10", "yuv420p10le", ["-strict", "-1"]),
|
||||
]:
|
||||
path = os.path.join(tmp, name)
|
||||
w, h = (int(x) for x in size.split("x"))
|
||||
V.ffmpeg(["-f", "lavfi", "-i", "testsrc2=size=%s:rate=%s" % (size, rate), "-frames:v", "6", "-vf",
|
||||
"pad=%d:%d" % (w + 1, h + 1) if w % 2 else "null", "-s", size, "-pix_fmt", pix] + extra + [path])
|
||||
frames = V.yuv_frames(path, w, h)
|
||||
num, den = (rate.split("/") + ["1"])[:2]
|
||||
cases.append({"name": name, "data": open(path, "rb").read(), "width": w, "height": h,
|
||||
"rate": [int(num), int(den)], "frames": [V.crc(f) for f in frames], "yuv": frames[:2],
|
||||
"exact": pix == "yuv420p"})
|
||||
ctx.emit("y4m_cases", cases)
|
||||
Reference in new issue
Block a user