ws-video-codecs: codecs/Mpeg1 absorbed from mpeg1-luau e2e2898 (jsmpeg port, MIT: licenses/jsmpeg-MIT.txt + NOTICE); requires and headers, frameImage (yuv420p / rgba8 copies); IDCT kept (bit-identical to codecs/Dct islow in put mode, but MPEG adds residuals before clamping); tests/codecs/mpeg1.luau + tools/fixtures/mpeg1.py (base64 / zlib fixtures, 5.6 MB)

This commit is contained in:
4DBug committed 2026-10-31 09:41:27 -05:00
1 parent 33a5a5b409
commit 2493b9db36
10 files changed
+2225 -1

No files matched your search

+1
View File
@@ -72,6 +72,7 @@ Codecs (layer 1, shared by formats; not loadable on their own):
- 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/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/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
- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
+1
View File
@@ -19,6 +19,7 @@
| `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/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) |
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
| `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) |
| `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) |
+8
View File
@@ -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.
+1 -1
View File
@@ -296,7 +296,7 @@ function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOption
local truncated = img.meta.truncated or b.meta.truncated
img = weave(img, b)
img.meta.truncated = truncated
img.meta.source.fields = 2
(img.meta.source :: any).fields = 2
end
end
end
File diff suppressed because it is too large. Load diff
+117
View File
@@ -0,0 +1,117 @@
--!strict
-- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from
-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays.
local T = {}
T.PICTURE_RATE = { [0] = 0.0,
23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
}
T.ZIG_ZAG = { [0] = 0,
1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58,
59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
}
T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8,
16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22,
22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26,
27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83,
}
T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
}
T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3,
6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0,
0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0,
0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99,
102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135,
138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1,
144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1,
186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0,
0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0,
0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0,
0, 24, 0, 0, 23, 0, 0, 22,
}
T.MACROBLOCK_TYPE_INTRA = { [0] = 3,
6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17,
}
T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3,
6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33,
36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17,
}
T.MACROBLOCK_TYPE_B = { [0] = 3,
6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36,
33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0,
0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26,
}
T.CODE_BLOCK_PATTERN = { [0] = 6,
3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54,
48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132,
144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129,
102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0,
0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171,
174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0,
0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0,
0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264,
246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0,
0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270,
276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336,
333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0,
0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0,
0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0,
0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0,
0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31,
}
T.MOTION = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36,
33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51,
57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108,
105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0,
0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156,
141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0,
0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0,
0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0,
0, -15, 0, 0, -11, 0, 0, -13,
}
T.DCT_DC_SIZE_LUMINANCE = { [0] = 6,
3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36,
33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6,
3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0,
0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_COEFF = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0,
0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81,
75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0,
0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120,
123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0,
0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0,
0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201,
210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273,
240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0,
0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333,
342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339,
309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417,
420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411,
399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0,
0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0,
0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510,
483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549,
546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0,
0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0,
0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0,
0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0,
0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0,
0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654,
633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657,
624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0,
0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0,
0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0,
0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842,
}
return T
+116
View File
@@ -0,0 +1,116 @@
--!strict
-- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
--
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level
-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF,
-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the
-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but
-- for this header and the require.
local T = require("@formats/codecs/Mpeg1/Tables")
local V = {}
type Leaf = { code: number, len: number, value: number }
local function leaves(tree: { [number]: number }): { Leaf }
local out: { Leaf } = {}
local function walk(state: number, code: number, len: number)
if tree[state] == 0 and len > 0 then
table.insert(out, { code = code, len = len, value = tree[state + 2] })
return
end
for bit = 0, 1 do
local nxt = tree[state + bit]
if nxt ~= nil and nxt > 0 then
walk(nxt, code * 2 + bit, len + 1)
end
end
end
walk(0, 0, 0)
return out
end
local function flat(tree: { [number]: number }): (buffer, number)
local ls = leaves(tree)
local k = 0
for _, l in ls do
k = math.max(k, l.len)
end
local lut = buffer.create(4 * 2 ^ k)
for _, l in ls do
local shift = k - l.len
local first = l.code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768)
end
end
return lut, k
end
V.SUB = 0x1000000
V.ESC = 0xFFFF
V.EOB = 0xFFFE
-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits
local function twoLevel(ls: { Leaf }): buffer
local subs: { [number]: number } = {}
local nsub = 0
for _, l in ls do
if l.len > 8 then
local prefix = l.code // 2 ^ (l.len - 8)
if subs[prefix] == nil then
nsub += 1
subs[prefix] = nsub
end
end
end
local lut = buffer.create(4 * 256 * (1 + nsub))
for _, l in ls do
if l.len <= 8 then
local shift = 8 - l.len
local first = l.code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value)
end
else
local prefix = l.code // 2 ^ (l.len - 8)
local s = subs[prefix]
buffer.writeu32(lut, prefix * 4, V.SUB + s)
local rest = l.code % 2 ^ (l.len - 8)
local shift = 16 - l.len
local first = rest * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value)
end
end
end
return lut
end
V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape
V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA)
V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE)
V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B)
V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN)
V.MOTION, V.MOTION_BITS = flat(T.MOTION)
V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE)
V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE)
do
local ls = leaves(T.DCT_COEFF)
V.DCT_FIRST = twoLevel(ls)
local nextLs: { Leaf } = {}
for _, l in ls do
if l.len == 1 and l.code == 1 then
table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10"
table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11"
else
table.insert(nextLs, l)
end
end
V.DCT_NEXT = twoLevel(nextLs)
end
return V
+262
View File
@@ -0,0 +1,262 @@
--!strict
-- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures,
-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage.
-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom
-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display
-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau).
-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding.
--
-- local dec = Mpeg1.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... }
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@formats/Types")
local D = require("@formats/codecs/Mpeg1/Decoder")
local Mpeg1 = {}
Mpeg1.PICTURE_I = 1
Mpeg1.PICTURE_P = 2
Mpeg1.PICTURE_B = 3
export type Frame = {
width: number,
height: number,
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based)
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
-- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth,
-- chroma stride codedWidth / 2
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
}
export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
-- display order for streams without B-frames.
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
_core: D.Core,
_reorder: boolean,
_rgba: boolean,
_held: D.Store?,
_pixels: buffer?,
_count: number,
width: number,
height: number,
frameRate: number,
bitRate: number,
stats: { pictures: number, errors: number, skipped: number },
},
Decoder
))
function Mpeg1.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local core = D.new(o.maxPixels)
return setmetatable({
_core = core,
_reorder = o.reorder == true,
_rgba = o.rgba ~= false,
_held = nil,
_pixels = nil,
_count = 0,
width = 0,
height = 0,
frameRate = 0,
bitRate = 0,
stats = { pictures = 0, errors = 0, skipped = 0 },
}, Decoder)
end
local function emit(self: Decoder, s: D.Store): Frame
local core = self._core
local pixels: buffer? = nil
if self._rgba then
local need = s.w * s.h * 4
local px = self._pixels
if px == nil or buffer.len(px) ~= need then
px = buffer.create(need)
self._pixels = px
end
core.toRgba(s, px :: buffer)
pixels = px
end
self._count += 1
return {
width = s.w,
height = s.h,
pixels = pixels,
pictureType = s.ptype,
temporalReference = s.tref,
index = self._count,
tag = s.tag,
y = s.y,
cb = s.cb,
cr = s.cr,
codedWidth = s.cw,
}
end
local function sync(self: Decoder)
local st = self._core.state
self.width = st.width
self.height = st.height
self.frameRate = st.frameRate
self.bitRate = st.bitRate
self.stats.pictures = st.pictures
self.stats.errors = st.errors
self.stats.skipped = st.skipped
end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s)
end
local prev = self._held
self._held = s
if prev then
return emit(self, prev)
end
return nil
end
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
local core = self._core
while true do
local s, needData = core.nextPicture(atEnd, tag)
sync(self)
if s then
local f = handle(self, s)
if f then
return f
end
elseif needData then
return nil
end
end
end
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
src = buffer.fromstring(data)
elseif type(data) == "buffer" then
src = data
else
return false
end
local total = buffer.len(src)
local off = math.floor(tonumber(offset) or 0)
if off < 0 or off > total then
return false
end
local n = math.floor(tonumber(len) or (total - off))
if n < 0 or off + n > total then
return false
end
self._core.write(src, off, n)
return true
end
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then
return nil
end
return run(self, true, tag)
end
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
-- for reordering. Call until it returns nil.
function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil)
if f then
return f
end
local held = self._held
if held then
self._held = nil
return emit(self, held)
end
return nil
end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8
-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame.
function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil
end
local w, h, cw = frame.width, frame.height, frame.codedWidth
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
return nil
end
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
for y = 0, h - 1 do
buffer.copy(px, y * w, frame.y, y * cw, w)
end
local o = w * h
for y = 0, oh - 1 do
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
end
end
img.meta.source = {
format = "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
range = if rgba then nil else "limited",
}
return img
end
return Mpeg1
+413
View File
@@ -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()
+170
View File
@@ -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)