diff --git a/docs/FORMATS.md b/docs/FORMATS.md index e0ef163..675899b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -5,7 +5,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| -| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | +| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | +| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | +| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | +| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | | font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` | @@ -16,6 +21,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | +| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | | archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` | | data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` | | data | csv | .csv .tsv | yes | yes | header: true | `tests/data/csv.luau` | @@ -26,6 +32,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | +| playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | +| playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | +| playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` | Codecs (layer 1, shared by formats; not loadable on their own): @@ -36,6 +45,8 @@ Codecs (layer 1, shared by formats; not loadable on their own): - 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/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 - 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/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index bef8c77..a36c9eb 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -7,6 +7,16 @@ | `src/Formats/codecs/Brotli/Static.luau` (static dictionary, context lookup table, word transforms; generated by `tools/brotli_static.py`), `src/Formats/codecs/Brotli/Decode.luau` (written from RFC 7932, structure after the reference decoder) | google/brotli | MIT: [brotli-LICENSE.txt](brotli-LICENSE.txt) | | `src/Formats/codecs/Lzma/`, `src/Formats/archive/xz/`, `src/Formats/archive/7z/` | written from the LZMA specification / LzmaSpec.cpp and 7zFormat.txt (LZMA SDK, Igor Pavlov), the xz file format specification and xz-embedded's BCJ filters (Lasse Collin) | all public domain: [lzma-xz-PUBLIC-DOMAIN.txt](lzma-xz-PUBLIC-DOMAIN.txt) | | `src/Formats/codecs/TrueType/`, `src/Formats/codecs/Cff/` | stb_truetype 1.26 (Sean Barrett), via imgui-luau's `imstb_truetype.lua`; fixed and extended | MIT or public domain: [stb_truetype-LICENSE.txt](stb_truetype-LICENSE.txt) | +| `src/Formats/containers/Ogg/` (init, Page) | ogg-luau be9f604 (same author), written from RFC 3533 | no licence chosen yet; no third-party code | +| `src/Formats/audio/wav/`, `src/Formats/containers/Riff/` (the chunk walker) | wav-luau fd9a909 (same author), written from the RIFF / WAVE / RF64 (EBU Tech 3306) specifications | no licence chosen yet; no third-party code | +| `src/Formats/audio/mp3/` | mp3-luau c755bbf (same author), a port of minimp3 by lieff (https://github.com/lieff/minimp3) | minimp3: CC0 1.0, [minimp3-CC0.txt](minimp3-CC0.txt) | +| `tests/fixtures/mp3/` | made by ffmpeg (libmp3lame / mp2) from a synthetic signal; `*.ref` are minimp3 decodes of them | test data, no third-party content | +| `src/Formats/audio/opus/` (Decoder, Celt, Silk, Mdct, RangeDecoder, Packet, CeltTables, SilkTables) | opus-luau dd2b4e5 (same author): a port of the libopus 1.6 decoder (git bafd40dcbd50; tables generated from its sources); the stereo downmix weights follow opusfile | libopus BSD 3-clause (Xiph.Org, Skype, Octasic, J.-M. Valin, T. B. Terriberry, CSIRO, G. Maxwell, M. Borgerding, E. de Castro Lopo, Mozilla, Amazon), opusfile BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | +| `src/Formats/audio/flac/` | flac-luau 7083d0d (same author), written from RFC 9639 | no licence chosen yet; no third-party code | +| `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | +| `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | +| `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/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 | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/licenses/bmpsuite-NOTICE.txt b/licenses/bmpsuite-NOTICE.txt new file mode 100644 index 0000000..a47b169 --- /dev/null +++ b/licenses/bmpsuite-NOTICE.txt @@ -0,0 +1,7 @@ +tests/fixtures/bmpsuite/ (g/, q/, b/ and the reference PNGs in ref/) come from the BMP Suite 2.8 by Jason Summers +(https://entropymine.com/jason/bmpsuite/). The suite's generator program is GPL-3.0, but, in its own words: + + Image files generated by this program are in the public domain. + +Only the generated image files are included here (ref.txt, mapping files to their reference PNG, was written for +formats-luau from the suite's bmpsuite.html). diff --git a/licenses/libopus-BSD.txt b/licenses/libopus-BSD.txt new file mode 100644 index 0000000..7571146 --- /dev/null +++ b/licenses/libopus-BSD.txt @@ -0,0 +1,44 @@ +Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic, + Jean-Marc Valin, Timothy B. Terriberry, + CSIRO, Gregory Maxwell, Mark Borgerding, + Erik de Castro Lopo, Mozilla, Amazon + +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 Internet Society, IETF or IETF Trust, nor the +names of specific 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 OWNER +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. + +Opus is subject to the royalty-free patent licenses which are +specified at: + +Xiph.Org Foundation: +https://datatracker.ietf.org/ipr/1524/ + +Microsoft Corporation: +https://datatracker.ietf.org/ipr/1914/ + +Broadcom Corporation: +https://datatracker.ietf.org/ipr/1526/ diff --git a/licenses/minimp3-CC0.txt b/licenses/minimp3-CC0.txt new file mode 100644 index 0000000..2c4afab --- /dev/null +++ b/licenses/minimp3-CC0.txt @@ -0,0 +1,117 @@ +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + + diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 94aece3..67f5a98 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -14,6 +14,18 @@ export type Entry = { } local list: { Entry } = { + { + name = "bmp", + category = "image", + path = "image/bmp", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true }, + load = function() + return require("@formats/image/bmp") + end, + }, { name = "png", category = "image", @@ -21,11 +33,59 @@ local list: { Entry } = { extensions = { "png", "apng" }, mime = { "image/png", "image/apng" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" }, - caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } }, + caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } }, load = function() return require("@formats/image/png") end, }, + { + name = "flac", + category = "audio", + path = "audio/flac", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, + caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + load = function() + return require("@formats/audio/flac") + end, + }, + { + name = "mp3", + category = "audio", + path = "audio/mp3", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + load = function() + return require("@formats/audio/mp3") + end, + }, + { + name = "opus", + category = "audio", + path = "audio/opus", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + load = function() + return require("@formats/audio/opus") + end, + }, + { + name = "wav", + category = "audio", + path = "audio/wav", + extensions = { "wav", "wave", "rf64", "bw64" }, + mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, + load = function() + return require("@formats/audio/wav") + end, + }, { name = "bmfont", category = "font", @@ -146,6 +206,18 @@ local list: { Entry } = { return require("@formats/archive/xz") end, }, + { + name = "zip", + category = "archive", + path = "archive/zip", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, + load = function() + return require("@formats/archive/zip") + end, + }, { name = "zst", category = "archive", @@ -266,6 +338,42 @@ local list: { Entry } = { return require("@formats/data/yaml") end, }, + { + name = "m3u", + category = "playlist", + path = "playlist/m3u", + extensions = { "m3u", "m3u8" }, + mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + caps = { decode = true, encode = true, hls = true }, + load = function() + return require("@formats/playlist/m3u") + end, + }, + { + name = "pls", + category = "playlist", + path = "playlist/pls", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + caps = { decode = true, encode = true }, + load = function() + return require("@formats/playlist/pls") + end, + }, + { + name = "xspf", + category = "playlist", + path = "playlist/xspf", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" }, + caps = { decode = true, encode = true }, + load = function() + return require("@formats/playlist/xspf") + end, + }, } return list diff --git a/src/Formats/archive/zip/init.luau b/src/Formats/archive/zip/init.luau new file mode 100644 index 0000000..081a7e0 --- /dev/null +++ b/src/Formats/archive/zip/init.luau @@ -0,0 +1,238 @@ +--!strict +-- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. +-- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new +-- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments, +-- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated +-- entries (codecs/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. +-- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2, +-- LZMA, zstd entries are listed but not readable), multi-disk archives. +-- +-- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) +-- for _, e in a:list() do print(e.name, e.size, e.method) end +-- local data = a:read("dir/file.txt") +-- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } +-- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) +-- local b = Zip.create() -- an empty archive + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Container = require("@formats/containers/Zip") + +-- ------------------------------------------------------------------------------------------------ contract +local Zip = { + name = "zip", + category = "archive", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + verify: boolean?, -- check every entry's CRC-32 on read (default true) +} +export type AddOptions = Container.AddOptions +export type WriteOptions = Container.FinishOptions + +-- ------------------------------------------------------------------------------------------------ constants +local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" } + +local Archive = {} +Archive.__index = Archive + +local function new(zip: any, verify: boolean): any + local a = setmetatable({ + kind = "archive", + format = "zip", + meta = { source = { format = "zip" }, comment = if zip then zip.comment else nil, zip64 = if zip then zip.zip64 else nil }, + _zip = zip, + _verify = verify, + _order = {} :: { string }, + _items = {} :: { [string]: any }, + }, Archive) + if zip then + for _, e in zip:list() do + if a._items[e.name] == nil then + table.insert(a._order, e.name) + end + a._items[e.name] = { raw = e } + end + end + return a +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Zip.sniff(r: Bytes.Reader): number + local s = r:peek(4) + -- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff + if s == "PK\3\4" or s == "PK\5\6" then + return 0.6 + end + if string.sub(s, 1, 2) == "MZ" then + return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip" + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Archive | nil, Err +function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local zip, err = Container.open(r) + if not zip then + return nil, err + end + return new(zip, not (opts and opts.verify == false)), nil +end + +-- create() -> an empty Archive +function Zip.create(): Types.Archive + return new(nil, true) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written +-- here), or a plain table { [name] = buffer | string }. +function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") + end + if getmetatable(value) == Archive then + return value:write(opts) + end + local a = new(nil, true) + if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then + for _, e in value:list() do + if e.dir then + a:add(e.name, nil, { mtime = e.mtime }) + else + local data, err = value:read(e.name) + if not data then + return nil, err + end + a:add(e.name, data, { mtime = e.mtime }) + end + end + else + local names = {} + for k, v in value do + if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then + return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data") + end + table.insert(names, k) + end + table.sort(names) + for _, k in names do + a:add(k, value[k]) + end + end + return a:write(opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the Archive methods (Types.Archive) + +-- list() -> { ArchiveEntry } in archive order (+ crc32, comment) +function Archive.list(self: any): { Types.ArchiveEntry } + local out = {} + for _, name in self._order do + local it = self._items[name] + if it.raw then + local e = it.raw + table.insert(out, { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = METHODS[e.method] or ("method " .. e.method), + mtime = e.mtime, + dir = e.isDir, + crc32 = e.crc32, + comment = e.comment, + }) + else + table.insert(out, { + name = name, + size = buffer.len(it.data), + compressedSize = nil, + method = it.opts.method or "deflate", + mtime = it.opts.mtime, + dir = string.sub(name, -1) == "/", + }) + end + end + return out +end + +-- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup +function Archive.read(self: any, name: string): (buffer?, Err.Err?) + if type(name) ~= "string" then + return nil, Err.new(Err.ARG, "read: name must be a string") + end + local it = self._items[name] + if it and not it.raw then + local copy = buffer.create(buffer.len(it.data)) + buffer.copy(copy, 0, it.data) + return copy, nil + end + if it then + return self._zip:read(it.raw, self._verify) + end + if self._zip then + local e = self._zip:find(name) + if e and self._items[e.name] and self._items[e.name].raw == e then + return self._zip:read(e, self._verify) + end + end + return nil, Err.new(Err.ARG, "no entry " .. name) +end + +-- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") +function Archive.add(self: any, name: string, data: any, opts: AddOptions?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + if self._items[name] == nil then + table.insert(self._order, name) + end + self._items[name] = { data = b, opts = opts or {} } +end + +-- remove(name) -> true when there was such an entry +function Archive.remove(self: any, name: string): boolean + if self._items[name] == nil then + return false + end + self._items[name] = nil + local i = table.find(self._order, name) + if i then + table.remove(self._order, i) + end + return true +end + +-- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are +function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) + local w = Container.writer() + for _, name in self._order do + local it = self._items[name] + local ok, err + if it.raw then + ok, err = w:addRaw(it.raw, self._zip) + else + ok, err = w:add(name, it.data, it.opts) + end + if not ok then + return nil, err + end + end + local o: WriteOptions = opts or {} + if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then + o = table.clone(o) + o.comment = self.meta.comment + end + return w:finish(o) +end + +Zip.Container = Container + +return Zip diff --git a/src/Formats/audio/flac/Frame.luau b/src/Formats/audio/flac/Frame.luau new file mode 100644 index 0000000..d31ed05 --- /dev/null +++ b/src/Formats/audio/flac/Frame.luau @@ -0,0 +1,605 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), +-- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check. +-- +-- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit +-- words without bounds checks and instead compares its position with the data end once per sample. Nothing here +-- throws: bad data gives nil, err. +-- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, + bit32.countlz, bit32.byteswap +local floor = math.floor + +local Frame = {} +Frame.PAD = 32 + +-- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0 +local CRC8 = table.create(256, 0) +local CRC16 = table.create(256, 0) +for i = 0, 255 do + local c = i + for _ = 1, 8 do + c = if band(c, 0x80) ~= 0 then band(bxor(lshift(c, 1), 0x07), 0xFF) else band(lshift(c, 1), 0xFF) + end + CRC8[i + 1] = c + local d = lshift(i, 8) + for _ = 1, 8 do + d = if band(d, 0x8000) ~= 0 then band(bxor(lshift(d, 1), 0x8005), 0xFFFF) else band(lshift(d, 1), 0xFFFF) + end + CRC16[i + 1] = d +end + +local function crc16(b: buffer, from: number, to: number): number + local c = 0 + for i = from, to - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end +Frame.crc16 = crc16 + +local POW2 = table.create(64, 0) +for i = 0, 63 do + POW2[i + 1] = 2 ^ i +end + +local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024, + [11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 } +local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000, + [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } +local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } + +export type Header = { + offset: number, -- byte offset of the sync code + size: number, -- header bytes, CRC-8 included + blockSize: number, + sampleRate: number, + channels: number, + assignment: number, -- 0..7 independent, 8 left/side, 9 side/right, 10 mid/side + bps: number, + variable: boolean, -- variable block size: number is a sample number, else a frame number + number: number, +} + +-- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults +-- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. +function Frame.header(b: buffer, pos: number, len: number, si: any): Header? + if pos < 0 or pos + 6 > len then + return nil + end + if readu8(b, pos) ~= 0xFF then + return nil + end + local b1 = readu8(b, pos + 1) + if band(b1, 0xFE) ~= 0xF8 then + return nil + end + local b2 = readu8(b, pos + 2) + local b3 = readu8(b, pos + 3) + local bsCode, rCode = rshift(b2, 4), band(b2, 15) + local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7) + if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then + return nil + end + -- UTF-8-like coded number + local p = pos + 4 + local x = readu8(b, p) + p += 1 + local num, more + if x < 0x80 then + num, more = x, 0 + elseif x >= 0xC0 and x < 0xE0 then + num, more = band(x, 0x1F), 1 + elseif x >= 0xE0 and x < 0xF0 then + num, more = band(x, 0x0F), 2 + elseif x >= 0xF0 and x < 0xF8 then + num, more = band(x, 0x07), 3 + elseif x >= 0xF8 and x < 0xFC then + num, more = band(x, 0x03), 4 + elseif x >= 0xFC and x < 0xFE then + num, more = band(x, 0x01), 5 + elseif x == 0xFE then + num, more = 0, 6 + else + return nil + end + for _ = 1, more do + local c = readu8(b, p) + p += 1 + if band(c, 0xC0) ~= 0x80 then + return nil + end + num = num * 64 + band(c, 0x3F) + end + local variable = band(b1, 1) == 1 + if not variable and more > 5 then + return nil + end + local bs = BLOCK[bsCode] + if bsCode == 6 then + bs = readu8(b, p) + 1 + p += 1 + elseif bsCode == 7 then + bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 + p += 2 + end + local rate = RATE[rCode] + if rCode == 0 then + rate = si and si.sampleRate or 0 + elseif rCode == 12 then + rate = readu8(b, p) * 1000 + p += 1 + elseif rCode == 13 then + rate = readu8(b, p) * 256 + readu8(b, p + 1) + p += 2 + elseif rCode == 14 then + rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 + p += 2 + end + local bps = BITS[sCode] + if sCode == 0 then + bps = si and si.bitsPerSample or 0 + end + if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then + return nil + end + -- CRC-8 over the header + local c = 0 + for i = pos, p - 1 do + c = CRC8[bxor(c, readu8(b, i)) + 1] + end + if c ~= readu8(b, p) then + return nil + end + return { + offset = pos, + size = p + 1 - pos, + blockSize = bs, + sampleRate = rate or 0, + channels = if chCode < 8 then chCode + 1 else 2, + assignment = chCode, + bps = bps, + variable = variable, + number = num, + } +end + +-- The first valid header at an offset in [pos, limit) +function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? + local lim = math.min(limit, len - 6) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0xFF then + local b1 = readu8(b, pos + 1) + if b1 == 0xF8 or b1 == 0xF9 then + local h = Frame.header(b, pos, len, si) + if h then + return h + end + end + end + pos += 1 + end + return nil +end + +-- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) +local function bits(b: buffer, p: number, n: number): number + if n == 0 then + return 0 + elseif n <= 24 then + return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n) + end + local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16)) + local q = p + n - 16 + return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) +end + +local function sbits(b: buffer, p: number, n: number): number + local v = bits(b, p, n) + if n > 0 and v >= POW2[n] then + v -= POW2[n + 1] + end + return v +end + +-- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. +local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number + local method = bits(b, p, 2) + if method > 1 then + return -1 + end + local porder = bits(b, p + 2, 4) + p += 6 + local pbits = if method == 0 then 4 else 5 + local escape = if method == 0 then 15 else 31 + local parts = POW2[porder + 1] + local psize = rshift(n, porder) + if psize * parts ~= n or psize < order then + return -1 + end + local i = order + 1 + for part = 0, parts - 1 do + if p > lim then + return -1 + end + local k = bits(b, p, pbits) + p += pbits + local stop = (part + 1) * psize + if k == escape then + local nb = bits(b, p, 5) + p += 5 + if nb == 0 then + for j = i, stop do + s[j] = 0 + end + else + local half, full = POW2[nb], POW2[nb + 1] + for j = i, stop do + if p > lim then + return -1 + end + local v = bits(b, p, nb) + p += nb + if v >= half then + v -= full + end + s[j] = v + end + end + elseif k <= 24 then + -- the hot loop: unary quotient + k-bit remainder, zigzag + local pk = POW2[k + 1] + local rk = 32 - k + for j = i, stop do + if p > lim then + return -1 + end + local sh = band(p, 7) + local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh) + local q, r + if w ~= 0 then + q = countlz(w) + local used = q + 1 + k + if used <= 32 - sh then + r = if k == 0 then 0 else rshift(lshift(w, q + 1), rk) + p += used + else + p += q + 1 + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + else + -- a long run of zeros + q = 32 - sh + p += q + while true do + if p > lim then + return -1 + end + local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w2 ~= 0 then + local z = countlz(w2) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + else + -- k = 25..30 (Rice2): the remainder takes two reads + local pk = POW2[k + 1] + for j = i, stop do + if p > lim then + return -1 + end + local q = 0 + while true do + if p > lim then + return -1 + end + local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w ~= 0 then + local z = countlz(w) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + local r = bits(b, p, k) + p += k + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + end + i = stop + 1 + end + return p +end + +local function fixed(s: { number }, n: number, order: number) + if order == 1 then + local a = s[1] + for i = 2, n do + a += s[i] + s[i] = a + end + elseif order == 2 then + local a, c = s[2], s[1] + for i = 3, n do + local v = s[i] + 2 * a - c + s[i] = v + c = a + a = v + end + elseif order == 3 then + local a, c, d = s[3], s[2], s[1] + for i = 4, n do + local v = s[i] + 3 * a - 3 * c + d + s[i] = v + d = c + c = a + a = v + end + elseif order == 4 then + local a, c, d, e = s[4], s[3], s[2], s[1] + for i = 5, n do + local v = s[i] + 4 * a - 6 * c + 4 * d - e + s[i] = v + e = d + d = c + c = a + a = v + end + end +end + +-- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 +local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) + local div = POW2[shift + 1] + local inv = 1 / div + if order <= 4 then + local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0 + local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0 + for i = order + 1, n do + local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv) + s[i] = v + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 8 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0 + local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4] + local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0 + for i = order + 1, n do + local v = s[i] + + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv) + s[i] = v + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 12 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8] + local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0 + local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5] + local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8] + local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0 + for i = order + 1, n do + local v = s[i] + + floor( + ( + c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + + c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12 + ) * inv + ) + s[i] = v + s12 = s11 + s11 = s10 + s10 = s9 + s9 = s8 + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + else + for i = order + 1, n do + local sum = 0 + for j = 1, order do + sum += cf[j] * s[i - j] + end + s[i] += floor(sum * inv) + end + end +end + +-- One subframe into s[1..n]. Returns the new bit position, or -1. +local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number + if p > lim then + return -1 + end + local hdr = bits(b, p, 8) + p += 8 + if hdr >= 128 then + return -1 + end + local typ = rshift(hdr, 1) + local wasted = 0 + if band(hdr, 1) == 1 then + -- unary count of wasted bits (minus one) + while true do + if p > lim or wasted > 32 then + return -1 + end + local bit = bits(b, p, 1) + p += 1 + wasted += 1 + if bit == 1 then + break + end + end + bps -= wasted + if bps < 1 then + return -1 + end + end + if typ == 0 then + local v = sbits(b, p, bps) + p += bps + for i = 1, n do + s[i] = v + end + elseif typ == 1 then + for i = 1, n do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + elseif typ >= 8 and typ <= 12 then + local order = typ - 8 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + fixed(s, n, order) + elseif typ >= 32 then + local order = typ - 31 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + local prec = bits(b, p, 4) + 1 + p += 4 + if prec == 16 then + return -1 + end + local shift = sbits(b, p, 5) + p += 5 + if shift < 0 then + return -1 + end + for j = 1, order do + if p > lim then + return -1 + end + cf[j] = sbits(b, p, prec) + p += prec + end + for j = order + 1, 12 do + cf[j] = 0 -- the unrolled filters read up to 12 coefficients + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + lpc(s, n, cf, order, shift) + else + return -1 + end + if wasted > 0 then + local m = POW2[wasted + 1] + for i = 1, n do + s[i] *= m + end + end + return p +end + +-- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize +-- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. +function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) + local n = h.blockSize + local lim = len * 8 + local p = (h.offset + h.size) * 8 + local asg = h.assignment + for c = 1, h.channels do + local bps = h.bps + if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then + bps += 1 -- the side channel + end + p = subframe(b, p, lim, chans[c], n, bps, cf) + if p < 0 then + return nil, "bad subframe" + end + end + local e = rshift(p + 7, 3) -- byte align + if e + 2 > len then + return nil, "truncated frame" + end + if checkCrc then + local want = readu8(b, e) * 256 + readu8(b, e + 1) + if crc16(b, h.offset, e) ~= want then + return nil, "crc16 mismatch" + end + end + if asg >= 8 then + local l, r = chans[1], chans[2] + if asg == 8 then + for i = 1, n do + r[i] = l[i] - r[i] + end + elseif asg == 9 then + for i = 1, n do + l[i] += r[i] + end + else + for i = 1, n do + local side = r[i] + local m = l[i] * 2 + (side % 2) + l[i] = (m + side) * 0.5 + r[i] = (m - side) * 0.5 + end + end + end + return e + 2, nil +end + +return Frame diff --git a/src/Formats/audio/flac/Meta.luau b/src/Formats/audio/flac/Meta.luau new file mode 100644 index 0000000..0c81354 --- /dev/null +++ b/src/Formats/audio/flac/Meta.luau @@ -0,0 +1,220 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is +-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. +-- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Meta = {} + +local function be16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end +local function be24(b: buffer, p: number): number + return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end +local function be32(b: buffer, p: number): number + return be16(b, p) * 65536 + be16(b, p + 2) +end + +export type StreamInfo = { + minBlockSize: number, + maxBlockSize: number, + minFrameSize: number, -- 0 = unknown + maxFrameSize: number, + sampleRate: number, + channels: number, + bitsPerSample: number, + totalSamples: number, -- 0 = unknown + md5: string, -- 32 hex digits (all zero = not set) +} + +export type SeekPoint = { sample: number, offset: number, samples: number } + +export type Picture = { + type: number, + mime: string, + description: string, + width: number, + height: number, + depth: number, + colors: number, + offset: number, -- the image bytes are buf[offset .. offset + size - 1] + size: number, +} + +export type Info = { + streamInfo: StreamInfo, + seekTable: { SeekPoint }, + vendor: string, + tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " + comments: { { key: string, value: string } }, -- every comment in order + pictures: { Picture }, + firstFrame: number, -- byte offset just after the last metadata block +} + +local function streamInfo(b: buffer, p: number): StreamInfo + local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) + local hex = table.create(16) + for i = 0, 15 do + hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i)) + end + return { + minBlockSize = be16(b, p), + maxBlockSize = be16(b, p + 2), + minFrameSize = be24(b, p + 4), + maxFrameSize = be24(b, p + 7), + sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4), + channels = bit32.band(bit32.rshift(b12, 1), 7) + 1, + bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1, + totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14), + md5 = table.concat(hex), + } +end + +local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean + if p + 4 > e then + return false + end + local vl = readu32(b, p) + p += 4 + if p + vl > e then + return false + end + info.vendor = buffer.readstring(b, p, vl) + p += vl + if p + 4 > e then + return false + end + local n = readu32(b, p) + p += 4 + for _ = 1, n do + if p + 4 > e then + return false + end + local l = readu32(b, p) + p += 4 + if p + l > e then + return false + end + local s = buffer.readstring(b, p, l) + p += l + local eq = string.find(s, "=", 1, true) + if eq then + local key, value = string.upper(string.sub(s, 1, eq - 1)), string.sub(s, eq + 1) + table.insert(info.comments, { key = key, value = value }) + local old = info.tags[key] + info.tags[key] = if old then old .. "; " .. value else value + end + end + return true +end + +local function picture(b: buffer, p: number, e: number): Picture? + if p + 8 > e then + return nil + end + local typ = be32(b, p) + local ml = be32(b, p + 4) + p += 8 + if p + ml + 4 > e then + return nil + end + local mime = buffer.readstring(b, p, ml) + p += ml + local dl = be32(b, p) + p += 4 + if p + dl + 20 > e then + return nil + end + local desc = buffer.readstring(b, p, dl) + p += dl + local pic = { + type = typ, + mime = mime, + description = desc, + width = be32(b, p), + height = be32(b, p + 4), + depth = be32(b, p + 8), + colors = be32(b, p + 12), + offset = p + 20, + size = be32(b, p + 16), + } + if pic.offset + pic.size > e then + return nil + end + return pic +end + +-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) +function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) + if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then + return nil, "Flac: no fLaC marker" + end + local info: Info = { + streamInfo = nil :: any, + seekTable = {}, + vendor = "", + tags = {}, + comments = {}, + pictures = {}, + firstFrame = 0, + } + local p = pos + 4 + while true do + if p + 4 > len then + return nil, "Flac: truncated metadata" + end + local h = readu8(b, p) + local last = h >= 128 + local typ = bit32.band(h, 127) + local size = be24(b, p + 1) + p += 4 + local e = p + size + if e > len then + return nil, "Flac: truncated metadata block" + end + if typ == 0 then + if size < 34 then + return nil, "Flac: bad STREAMINFO" + end + info.streamInfo = streamInfo(b, p) + elseif typ == 3 then + for q = p, e - 18, 18 do + local hi = be32(b, q) + if hi ~= 0xFFFFFFFF then -- placeholder points are all ones + table.insert(info.seekTable, { + sample = hi * 4294967296 + be32(b, q + 4), + offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12), + samples = be16(b, q + 16), + }) + end + end + elseif typ == 4 then + vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + elseif typ == 6 then + local pic = picture(b, p, e) + if pic then + table.insert(info.pictures, pic) + end + elseif typ == 127 then + return nil, "Flac: invalid metadata block type" + end + p = e + if last then + break + end + end + if not info.streamInfo then + return nil, "Flac: no STREAMINFO" + end + local si = info.streamInfo + if si.sampleRate == 0 then + return nil, "Flac: bad STREAMINFO values" + end + info.firstFrame = p + return info, nil +end + +return Meta diff --git a/src/Formats/audio/flac/Stream.luau b/src/Formats/audio/flac/Stream.luau new file mode 100644 index 0000000..b6a5dc5 --- /dev/null +++ b/src/Formats/audio/flac/Stream.luau @@ -0,0 +1,383 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through +-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, +-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed +-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an +-- injected module). Nothing throws: open returns nil, message, code. +local Bytes = require("@formats/core/Bytes") +local Ogg = require("@formats/containers/Ogg") +local Frame = require("@formats/audio/flac/Frame") +local Meta = require("@formats/audio/flac/Meta") + +local Stream = {} + +local writef32, writei32 = buffer.writef32, buffer.writei32 +type Header = any -- Frame.Header +local PAD = Frame.PAD + +export type Decoder = { + sampleRate: number, + channels: number, + bitsPerSample: number, + frames: number, -- total sample frames (per channel); 0 if unknown and not found + duration: number, -- seconds + bitrate: number, -- average bits per second of the audio data + tags: { [string]: string }, + comments: { { key: string, value: string } }, + vendor: string, + md5: string, + seekTable: { any }, + pictures: { any }, + container: string, -- "flac" | "ogg" + read: (Decoder, number, buffer?) -> (buffer, number), + readInt: (Decoder, number, buffer?) -> (buffer, number), + seek: (Decoder, number) -> boolean, + seekSample: (Decoder, number) -> boolean, + position: (Decoder) -> (number, number), +} + +local Dec = {} +Dec.__index = Dec + +-- the sample number of a frame +local function sampleOf(self: any, h: Header): number + return if h.variable then h.number else h.number * self._nominal +end + +-- a header that also matches the stream (guards the sync search against false syncs) +local function plausible(self: any, h: Header): boolean + if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then + return false + end + if self.frames > 0 and sampleOf(self, h) >= self.frames then + return false + end + return true +end + +local function findFrame(self: any, pos: number, limit: number): Header? + local b, len, si = self._b, self._len, self._si + while true do + local h = Frame.find(b, pos, limit, len, si) + if not h then + return nil + end + if plausible(self, h) then + return h + end + pos = h.offset + 1 + end +end + +local function ensure(self: any, n: number) + if n > self._cap then + for c = 1, self.channels do + self._chans[c] = table.create(n, 0) + end + self._cap = n + end +end + +-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. +local function decodeAt(self: any, pos: number): boolean + local b, len = self._b, self._len + while true do + local h = Frame.header(b, pos, len, self._si) + if not h or not plausible(self, h) then + h = findFrame(self, pos, len) + if not h then + self._pos = len + return false + end + end + ensure(self, h.blockSize) + local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc) + if nextPos then + local s = sampleOf(self, h) + local n = h.blockSize + if self.frames > 0 and s + n > self.frames then + n = math.max(0, self.frames - s) + end + self._pos = nextPos + self._fs = s + self._fn = n + self._cur = 0 + return true + end + pos = h.offset + 1 + end +end + +local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) + local ch = self.channels + local want = math.floor(tonumber(maxFrames) or 0) + if not (want >= 0) then + want = 0 -- negative or NaN + end + want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB + local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 + local out = if reuse then dst :: buffer else buffer.create(want * ch * 4) + local got = 0 + local scale = 1 / 2 ^ (self.bitsPerSample - 1) + local stride = ch * 4 + while got < want do + if self._cur >= self._fn then + if self._pos >= self._len or not decodeAt(self, self._pos) then + self._fs += self._cur + self._cur, self._fn = 0, 0 + break + end + end + local take = math.min(want - got, self._fn - self._cur) + local from = self._cur + 1 + local to = self._cur + take + for c = 1, ch do + local s = self._chans[c] + local o = (got * ch + c - 1) * 4 + if asInt then + for i = from, to do + writei32(out, o, s[i]) + o += stride + end + else + for i = from, to do + writef32(out, o, s[i] * scale) + o += stride + end + end + end + self._cur += take + got += take + end + if got < want and not reuse then + local short = buffer.create(got * ch * 4) + buffer.copy(short, 0, out, 0, got * ch * 4) + out = short + end + return out, got +end + +-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is +-- reused when big enough. +function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, false, out) +end + +-- The same as interleaved i32 integer samples (bit-exact, right-aligned) +function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, true, out) +end + +-- seconds, sample frame of the next frame read() returns +function Dec.position(self: any): (number, number) + local s = self._fs + self._cur + return s / self.sampleRate, s +end + +-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets +-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. +function Dec.seekSample(self: any, t: number): boolean + t = math.floor(tonumber(t) or 0) + if not (t >= 0) then + t = 0 -- negative or NaN + end + if self.frames > 0 and t >= self.frames then + self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 + return true + end + if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then + self._cur = t - self._fs + return true + end + local first, len = self._first, self._len + local lo, hi = first, len + for _, sp in self.seekTable do + local o = first + sp.offset + if o < len then + if sp.sample <= t then + lo = math.max(lo, o) + else + hi = math.min(hi, o) + break + end + end + end + local window = math.max(16384, 2 * self._si.maxFrameSize) + while hi - lo > window do + local mid = (lo + hi) // 2 + local h = findFrame(self, mid, hi) + if h and sampleOf(self, h) <= t then + lo = h.offset + else + hi = mid + end + end + local pos = lo + while true do + local h = findFrame(self, pos, len) + if not h then + self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0 + return false + end + local s = sampleOf(self, h) + if s + h.blockSize > t then + if decodeAt(self, h.offset) then + if self._fs <= t and t < self._fs + self._fn then + self._cur = t - self._fs + return true + elseif self._fs > t then + return false -- a hole in the stream: we are at the next frame + end + pos = self._pos + else + return false + end + else + pos = h.offset + h.size + end + end +end + +function Dec.seek(self: any, seconds: number): boolean + return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) +end + +-- Find the total length from the last frame (when STREAMINFO does not give it) +local function scanLength(self: any): number + local len = self._len + local step = math.max(65536, 2 * self._si.maxFrameSize) + local from = len + while from > self._first do + local start = math.max(self._first, from - step) + local best: Header? = nil + local pos = start + while true do + local h = findFrame(self, pos, from) + if not h then + break + end + best = h + pos = h.offset + 1 + end + if best then + local s = sampleOf(self, best) + -- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here + return s + best.blockSize + end + from = start + end + return 0 +end + +local function skipId3(b: buffer, base: number, len: number): number + local p = 0 + while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do + local sz = 0 + for i = 6, 9 do + sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127) + end + local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0 + p += 10 + sz + (if footer then 10 else 0) + end + return p +end + +-- opts.crc16 = false skips the per-frame CRC-16 check +function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) + local b, len, container + if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then + local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) + if not demux then + return nil, (err :: any).message, "CORRUPT" + end + local serial = demux:find("flac") + if not serial then + return nil, "no FLAC stream in the Ogg file", "CORRUPT" + end + -- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet) + local packets, total = {}, 0 + for p in demux:packets(serial) do + local off, size = p.offset, p.size + if #packets == 0 then + if size < 13 then + return nil, "bad Ogg FLAC header", "CORRUPT" + end + off += 9 + size -= 9 + end + table.insert(packets, { p.data, off, size }) + total += size + end + b = buffer.create(total + PAD) + local o = 0 + for _, p in packets do + buffer.copy(b, o, p[1], p[2], p[3]) + o += p[3] + end + len = total + container = "ogg" + else + local start = skipId3(buf, base, srcLen) + if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then + return nil, "not a FLAC file", "CORRUPT" + end + len = srcLen - start + b = buffer.create(len + PAD) + buffer.copy(b, 0, buf, base + start, len) + container = "flac" + end + local info, err = Meta.parse(b, 0, len) + if not info then + return nil, err, "CORRUPT" + end + local si = info.streamInfo + local self = setmetatable({ + sampleRate = si.sampleRate, + channels = si.channels, + bitsPerSample = si.bitsPerSample, + frames = si.totalSamples, + duration = 0, + bitrate = 0, + tags = info.tags, + comments = info.comments, + vendor = info.vendor, + md5 = si.md5, + seekTable = info.seekTable, + pictures = info.pictures, + container = container, + _b = b, + _len = len, + _si = si, + _first = info.firstFrame, + _pos = info.firstFrame, + _chans = {}, + _cap = 0, + _cf = table.create(32, 0), + _crc = not (opts and opts.crc16 == false), + _fs = 0, + _fn = 0, + _cur = 0, + _nominal = math.max(si.maxBlockSize, 1), + }, Dec) + ensure(self, math.max(si.maxBlockSize, 16)) + local h = findFrame(self, info.firstFrame, len) + if h then + if not h.variable then + self._nominal = h.blockSize + end + end + if self.frames == 0 then + self.frames = scanLength(self) + end + self.duration = self.frames / self.sampleRate + if self.duration > 0 then + self.bitrate = (len - info.firstFrame) * 8 / self.duration + end + return self :: any, nil +end + +Stream.Dec = Dec + +return Stream diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau new file mode 100644 index 0000000..bcf2578 --- /dev/null +++ b/src/Formats/audio/flac/init.luau @@ -0,0 +1,131 @@ +--!strict +-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, +-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. +-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals +-- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame +-- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in +-- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when +-- STREAMINFO has none. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams. +-- +-- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) +-- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end +-- local i32, n = dec:readInt(4096) -- bit-exact integer samples +-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Stream = require("@formats/audio/flac/Stream") + +-- ------------------------------------------------------------------------------------------------ contract +local Flac = { + name = "flac", + category = "audio", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, + caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Decoder = Stream.Decoder +export type OpenOptions = { + crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) + maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Flac.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "fLaC" then + return 1 + end + if head == "OggS" then + -- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping) + local nseg = r:peekU8(26) + if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then + return 1 + end + return 0 + end + if string.sub(head, 1, 3) == "ID3" then + -- an ID3v2 tag, then fLaC (mp3 files start with ID3 too) + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Flac.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + local ch = d.channels + local parts, total = {}, 0 + if d.frames > 0 then + local out, n = d:read(d.frames) + table.insert(parts, out) + total = n + end + while true do -- frames past what STREAMINFO / the scan said + local out, n = d:read(65536) + if n == 0 then + break + end + table.insert(parts, out) + total += n + if total > limit then + return nil, Err.new(Err.LIMIT, "stream over the frame limit") + end + end + local a = Types.Audio.new(d.sampleRate, ch, total) + local o = 0 + for _, p in parts do + local n = math.min(buffer.len(p), total * ch * 4 - o) + buffer.copy(a.samples, o, p, 0, n) + o += n + end + a.tags = d.tags + a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts) + if not dec then + return nil, Err.new(code or Err.CORRUPT, tostring(msg)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Flac.Stream = Stream +Flac.Ogg = Ogg + +return Flac diff --git a/src/Formats/audio/mp3/Core.luau b/src/Formats/audio/mp3/Core.luau new file mode 100644 index 0000000..a7bb0a7 --- /dev/null +++ b/src/Formats/audio/mp3/Core.luau @@ -0,0 +1,1628 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, +-- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output. +-- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream +-- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free. +-- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw. +local T = require("@formats/audio/mp3/Tables") + +local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap +local ru8, wu8, ru32, ri16 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.readi16 +local rf, wf = buffer.readf32, buffer.writef32 +local bcopy, bfill, bcreate = buffer.copy, buffer.fill, buffer.create +local min, max = math.min, math.max + +local MAX_BITRESERVOIR_BYTES = 511 +local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up +local SCALE = 1 / 32768 + +---------------------------------------------------------------------------------------------------------------- +-- tables (floats rounded to f32 like the C arrays) + +local F32 = bcreate(4) +local function f32(x: number): number + wf(F32, 0, x) + return rf(F32, 0) +end + +local function fbuf(list: { [number]: number }, n: number): buffer + local b = bcreate(n * 4) + for i = 0, n - 1 do + wf(b, i * 4, list[i]) + end + return b +end + +-- scalefactor band widths: long (8 x 23) | short (8 x 40) | mixed (8 x 40), one u8 buffer +local SFB_LONG, SFB_SHORT, SFB_MIXED = 0, 184, 504 +local SFB = bcreate(824 + 8) +for i = 0, 183 do + wu8(SFB, SFB_LONG + i, T.g_scf_long[i]) +end +for i = 0, 319 do + wu8(SFB, SFB_SHORT + i, T.g_scf_short[i]) + wu8(SFB, SFB_MIXED + i, T.g_scf_mixed[i]) +end + +local TABS = bcreate(2164 * 2) +for i = 0, 2163 do + buffer.writei16(TABS, i * 2, T.tabs[i]) +end +local TAB32, TAB33 = T.tab32, T.tab33 +local TABINDEX, LINBITS = T.tabindex, T.g_linbits +local SCF_PARTITIONS, SCFC_DECODE, GMOD, PREAMP = T.g_scf_partitions, T.g_scfc_decode, T.g_mod, T.g_preamp +local EXPFRAC = { [0] = f32(T.g_expfrac[0]), f32(T.g_expfrac[1]), f32(T.g_expfrac[2]), f32(T.g_expfrac[3]) } +local PAN = {} +for i = 0, 13 do + PAN[i] = f32(T.g_pan[i]) +end +local BITALLOC_CODE = T.g_bitalloc_code_tab +local HALFRATE = T.halfrate + +-- L3_pow_43 for every value a Huffman pair can give (15 + 8191 linbits), evaluated in f32 like the C code +local POW43 = bcreate(8207 * 4) +do + local g = {} + for i = 0, 144 do + g[i] = f32(T.g_pow43[i]) + end + local c43, c29 = f32(4 / 3), f32(2 / 9) + for x0 = 0, 8206 do + local v + if x0 < 129 then + v = g[16 + x0] + else + local x, mult = x0, 256 + if x < 1024 then + mult = 16 + x *= 8 + end + local sign = band(2 * x, 64) + local frac = f32((band(x, 63) - sign) / (band(x, bit32.bnot(63)) + sign)) + v = f32(f32(g[16 + rshift(x + sign, 6)] * f32(1 + f32(frac * f32(c43 + f32(frac * c29))))) * mult) + end + wf(POW43, x0 * 4, v) + end +end + +-- L12 dequantizer: 9.53674316e-07f / x (and two more steps of 2^(-1/3)) for 3, 7, ..., 65535, 3, 5, 9 +local DEQ_L12 = {} +do + local div = { 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 3, 5, 9 } + local base = { f32(9.53674316e-07), f32(7.56931807e-07), f32(6.00777173e-07) } + for i = 0, 17 do + for j = 0, 2 do + DEQ_L12[i * 3 + j] = f32(base[j + 1] / div[i + 1]) + end + end +end + +local AA = fbuf(T.g_aa, 16) +local TWID3 = fbuf(T.g_twid3, 6) +local MDCT_WIN0, MDCT_WIN1 = table.create(18, 0), table.create(18, 0) -- g_mdct_window[2][18], 1-based +for i = 0, 17 do + MDCT_WIN0[i + 1] = f32(T.g_mdct_window[i]) + MDCT_WIN1[i + 1] = f32(T.g_mdct_window[18 + i]) +end +local WINT = table.create(240, 0) -- g_win as a 1-based Luau array (f32 values) +for i = 0, 239 do + WINT[i + 1] = f32(T.g_win[i]) +end + +---------------------------------------------------------------------------------------------------------------- +-- scratch + +local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) -- layer III main data (reservoir + frame) +local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 +local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32 +local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, f32 +local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8 +local ISCF = bcreate(48) -- integer scalefactors, u8 +local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18] +local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32 +local BA = bcreate(64) -- L12 bit allocation +local SCFCOD = bcreate(64) + +-- layer III side info, per granule x channel (0..3) +local GR_P23, GR_BV, GR_SFC, GR_GAIN, GR_BT, GR_MIXED = {}, {}, {}, {}, {}, {} +local GR_NLONG, GR_NSHORT, GR_SFB, GR_PRE, GR_SCALE, GR_C1, GR_SCFSI = {}, {}, {}, {}, {}, {}, {} +local GR_TS, GR_RC, GR_SBG = {}, {}, {} -- [gr * 3 + k] +for i = 0, 3 do + GR_P23[i], GR_BV[i], GR_SFC[i], GR_GAIN[i], GR_BT[i], GR_MIXED[i] = 0, 0, 0, 0, 0, 0 + GR_NLONG[i], GR_NSHORT[i], GR_SFB[i], GR_PRE[i], GR_SCALE[i], GR_C1[i], GR_SCFSI[i] = 0, 0, 0, 0, 0, 0, 0 + for k = 0, 2 do + GR_TS[i * 3 + k], GR_RC[i * 3 + k], GR_SBG[i * 3 + k] = 0, 0, 0 + end +end +local MAXB = { [0] = -1, -1, -1 } +local SCFSIZE = { [0] = 0, 0, 0, 0 } + +-- per-stream state of the frame being decoded (set by decodeFrame) +local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32] +local QMF: buffer = bcreate(4) -- qmf_state[15*2*32] +local PCM: buffer = bcreate(4) + +---------------------------------------------------------------------------------------------------------------- +-- bit reader (bs_t): position and limit in bits + +local bsBuf: buffer = FRAME +local bsPos = 0 +local bsLimit = 0 + +-- n <= 25 +local function getBits(n: number): number + local pos = bsPos + bsPos = pos + n + if pos + n > bsLimit then + return 0 + end + local w = lshift(bswap(ru32(bsBuf, rshift(pos, 3))), band(pos, 7)) + return rshift(w, 32 - n) +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 + +local function readSideInfo(h1: number, h2: number, h3: number): number + local mono = band(h3, 0xC0) == 0xC0 + local mpeg1 = band(h1, 8) ~= 0 + local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + if srIdx ~= 0 then + srIdx -= 1 + end + local grCount = if mono then 1 else 2 + local scfsi = 0 + local mdb + if mpeg1 then + grCount *= 2 + mdb = getBits(9) + scfsi = getBits(7 + grCount) + else + mdb = rshift(getBits(8 + grCount), grCount) + end + local part23sum = 0 + for gr = 0, grCount - 1 do + if mono then + scfsi = lshift(scfsi, 4) + end + local p23 = getBits(12) + GR_P23[gr] = p23 + part23sum += p23 + local bv = getBits(9) + if bv > 288 then + return -1 + end + GR_BV[gr] = bv + GR_GAIN[gr] = getBits(8) + local sfc = getBits(if mpeg1 then 4 else 9) + GR_SFC[gr] = sfc + GR_SFB[gr] = SFB_LONG + srIdx * 23 + GR_NLONG[gr] = 22 + GR_NSHORT[gr] = 0 + local tables + local g3 = gr * 3 + if getBits(1) ~= 0 then + local bt = getBits(2) + if bt == 0 then + return -1 + end + GR_BT[gr] = bt + local mixed = getBits(1) + GR_MIXED[gr] = mixed + GR_RC[g3] = 7 + GR_RC[g3 + 1] = 255 + if bt == 2 then + scfsi = band(scfsi, 0x0F0F) + if mixed == 0 then + GR_RC[g3] = 8 + GR_SFB[gr] = SFB_SHORT + srIdx * 40 + GR_NLONG[gr] = 0 + GR_NSHORT[gr] = 39 + else + GR_SFB[gr] = SFB_MIXED + srIdx * 40 + GR_NLONG[gr] = if mpeg1 then 8 else 6 + GR_NSHORT[gr] = 30 + end + end + tables = lshift(getBits(10), 5) + GR_SBG[g3] = getBits(3) + GR_SBG[g3 + 1] = getBits(3) + GR_SBG[g3 + 2] = getBits(3) + else + GR_BT[gr] = 0 + GR_MIXED[gr] = 0 + tables = getBits(15) + GR_RC[g3] = getBits(4) + GR_RC[g3 + 1] = getBits(3) + GR_RC[g3 + 2] = 255 + end + GR_TS[g3] = rshift(tables, 10) + GR_TS[g3 + 1] = band(rshift(tables, 5), 31) + GR_TS[g3 + 2] = band(tables, 31) + GR_PRE[gr] = if mpeg1 then getBits(1) elseif sfc >= 500 then 1 else 0 + GR_SCALE[gr] = getBits(1) + GR_C1[gr] = getBits(1) + GR_SCFSI[gr] = band(rshift(scfsi, 12), 15) + scfsi = lshift(scfsi, 4) + end + if part23sum + bsPos > bsLimit + mdb * 8 then + return -1 + end + return mdb +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III scalefactors + +local function ldexpQ2(y: number, e: number): number + repeat + local s = if e < 120 then e else 120 + y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) + e -= s + until e <= 0 + return y +end + +-- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) +local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number) + local mpeg1 = band(h1, 8) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local part = ((if nShort ~= 0 then 1 else 0) + (if nLong == 0 then 1 else 0)) * 28 + local scfShift = GR_SCALE[gr] + 1 + local scfsi = GR_SCFSI[gr] + if mpeg1 then + local p = SCFC_DECODE[GR_SFC[gr]] + local hi, lo = rshift(p, 2), band(p, 3) + SCFSIZE[0], SCFSIZE[1], SCFSIZE[2], SCFSIZE[3] = hi, hi, lo, lo + else + local ist = if band(h3, 0x10) ~= 0 and ch ~= 0 then 1 else 0 + local sfc = rshift(GR_SFC[gr], ist) + local k = ist * 12 + while sfc >= 0 do + local modprod = 1 + for i = 3, 0, -1 do + SCFSIZE[i] = (sfc // modprod) % GMOD[k + i] + modprod *= GMOD[k + i] + end + sfc -= modprod + k += 4 + end + part += k + end + -- L3_read_scalefactors + local sp, ip = 0, istOff + for i = 0, 3 do + local cnt = SCF_PARTITIONS[part + i] + if cnt == 0 then + break + end + if mpeg1 and band(scfsi, 8) ~= 0 then + bcopy(ISCF, sp, IST, ip, cnt) + else + local bits = SCFSIZE[i] + if bits == 0 then + bfill(ISCF, sp, 0, cnt) + bfill(IST, ip, 0, cnt) + else + local maxScf = if mpeg1 then -1 else lshift(1, bits) - 1 + for k = 0, cnt - 1 do + local s = getBits(bits) + wu8(IST, ip + k, if s == maxScf then 255 else s) + wu8(ISCF, sp + k, s) + end + end + end + sp += cnt + ip += cnt + scfsi *= 2 + end + wu8(ISCF, sp, 0) + wu8(ISCF, sp + 1, 0) + wu8(ISCF, sp + 2, 0) + + if nShort ~= 0 then + local sh = 3 - scfShift + local g3 = gr * 3 + local s0, s1, s2 = lshift(GR_SBG[g3], sh), lshift(GR_SBG[g3 + 1], sh), lshift(GR_SBG[g3 + 2], sh) + for i = 0, nShort - 1, 3 do + local o = nLong + i + wu8(ISCF, o, band(ru8(ISCF, o) + s0, 255)) + wu8(ISCF, o + 1, band(ru8(ISCF, o + 1) + s1, 255)) + wu8(ISCF, o + 2, band(ru8(ISCF, o + 2) + s2, 255)) + end + elseif GR_PRE[gr] ~= 0 then + for i = 0, 9 do + wu8(ISCF, 11 + i, band(ru8(ISCF, 11 + i) + PREAMP[i], 255)) + end + end + + local gainExp = GR_GAIN[gr] - 4 - 210 - (if band(h3, 0xE0) == 0x60 then 2 else 0) + local gain = ldexpQ2(2048, 44 - gainExp) + for i = 0, nLong + nShort - 1 do + wf(SCF, i * 4, ldexpQ2(gain, lshift(ru8(ISCF, i), scfShift))) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache + +local function huffman(dst: number, gr: number, limit: number) + local b = bsBuf + local one = 0.0 + local ireg = 0 + local bigValCnt = GR_BV[gr] + local sfb = GR_SFB[gr] + local scf = 0 + local pos = bsPos + local nextPtr = rshift(pos, 3) + local cache = lshift(bswap(ru32(b, nextPtr)), band(pos, 7)) + local sh = band(pos, 7) - 8 + nextPtr += 4 + local g3 = gr * 3 + local d = dst * 4 + + while bigValCnt > 0 do + if ireg > 2 then + break + end + local tabNum = GR_TS[g3 + ireg] + local sfbCnt = GR_RC[g3 + ireg] + ireg += 1 + local cb = TABINDEX[tabNum] + local linbits = LINBITS[tabNum] + repeat + local np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + bigValCnt = 0 + break + end + local pairs = if bigValCnt < np then bigValCnt else np + one = rf(SCF, scf) + scf += 4 + for _ = 1, pairs do + local w = 5 + local leaf = ri16(TABS, (cb + rshift(cache, 27)) * 2) + while leaf < 0 do + cache = lshift(cache, w) + sh += w + w = band(leaf, 7) + leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - leaf // 8) * 2) + end + local l = rshift(leaf, 8) + cache = lshift(cache, l) + sh += l + for _ = 1, 2 do + local lsb = band(leaf, 15) + if lsb == 15 and linbits ~= 0 then + lsb += rshift(cache, 32 - linbits) + cache = lshift(cache, linbits) + sh += linbits + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + end + local v = rf(POW43, lsb * 4) * one + if lsb ~= 0 then + if cache >= 0x80000000 then + v = -v + end + cache = lshift(cache, 1) + sh += 1 + end + wf(GRBUF, d, v) + d += 4 + leaf = rshift(leaf, 4) + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + end + bigValCnt -= np + sfbCnt -= 1 + until not (bigValCnt > 0 and sfbCnt >= 0) + end + + -- count1 quadruples + local np = 1 - bigValCnt + local cb1 = if GR_C1[gr] ~= 0 then TAB33 else TAB32 + local dend = 576 * 4 * 2 + while true do + local leaf = cb1[rshift(cache, 28)] + if band(leaf, 8) == 0 then + leaf = cb1[rshift(leaf, 3) + rshift(lshift(cache, 4), 32 - band(leaf, 3))] + end + local l = band(leaf, 7) + cache = lshift(cache, l) + sh += l + if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then + break + end + np -= 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf += 4 + end + if band(leaf, 128) ~= 0 then + wf(GRBUF, d, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + if band(leaf, 64) ~= 0 then + wf(GRBUF, d + 4, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + np -= 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf += 4 + end + if band(leaf, 32) ~= 0 then + wf(GRBUF, d + 8, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + if band(leaf, 16) ~= 0 then + wf(GRBUF, d + 12, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + d += 16 + end + bsPos = limit +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III stereo + +-- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 +local function midside(left: number, n: number) + for i = left * 4, (left + n - 1) * 4, 4 do + local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304) + wf(GRBUF, i, a + c) + wf(GRBUF, i + 2304, a - c) + end +end + +local function intensityStereo(h1: number, h3: number, gr: number) + local mpeg1 = band(h1, 8) ~= 0 + local ms = band(h3, 0x20) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local nSfb = nLong + nShort + local maxBlocks = if nShort ~= 0 then 3 else 1 + local sfb0 = GR_SFB[gr] + -- L3_stereo_top_band on the right channel + MAXB[0], MAXB[1], MAXB[2] = -1, -1, -1 + local right = 576 + for i = 0, nSfb - 1 do + local n = ru8(SFB, sfb0 + i) + for k = right, right + n - 1, 2 do + if rf(GRBUF, k * 4) ~= 0 or rf(GRBUF, k * 4 + 4) ~= 0 then + MAXB[i % 3] = i + break + end + end + right += n + end + if nLong ~= 0 then + local m = max(MAXB[0], MAXB[1], MAXB[2]) + MAXB[0], MAXB[1], MAXB[2] = m, m, m + end + for i = 0, maxBlocks - 1 do + local defaultPos = if mpeg1 then 3 else 0 + local itop = nSfb - maxBlocks + i + local prev = itop - maxBlocks + wu8(IST, 39 + itop, if MAXB[i] >= prev then defaultPos else ru8(IST, 39 + prev)) + end + -- L3_stereo_process + local mpeg2sh = band(GR_SFC[gr + 1], 1) + local maxPos = if mpeg1 then 7 else 64 + local s = if ms then f32(1.41421356) else 1 + local left = 0 + local i = 0 + while true do + local n = ru8(SFB, sfb0 + i) + if n == 0 then + break + end + local ipos = ru8(IST, 39 + i) + if i > MAXB[i % 3] and ipos < maxPos then + local kl, kr + if mpeg1 then + kl, kr = PAN[2 * ipos], PAN[2 * ipos + 1] + else + kl = 1 + kr = ldexpQ2(1, lshift(rshift(ipos + 1, 1), mpeg2sh)) + if band(ipos, 1) ~= 0 then + kl = kr + kr = 1 + end + end + kl, kr = f32(kl * s), f32(kr * s) + for k = left * 4, (left + n - 1) * 4, 4 do + local v = rf(GRBUF, k) + wf(GRBUF, k + 2304, v * kr) + wf(GRBUF, k, v * kl) + end + elseif ms then + midside(left, n) + end + left += n + i += 1 + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III reorder, antialias, IMDCT + +local function reorder(g: number, sfb: number) + local src, dst = g, 0 + while true do + local len = ru8(SFB, sfb) + if len == 0 then + break + end + for i = 0, len - 1 do + local s = (src + i) * 4 + wf(SYN, dst, rf(GRBUF, s)) + wf(SYN, dst + 4, rf(GRBUF, s + len * 4)) + wf(SYN, dst + 8, rf(GRBUF, s + len * 8)) + dst += 12 + end + src += 3 * len + sfb += 3 + end + bcopy(GRBUF, g * 4, SYN, 0, dst) +end + +local AA0 = table.create(8, 0) +local AA1 = table.create(8, 0) +for i = 0, 7 do + AA0[i + 1] = rf(AA, i * 4) + AA1[i + 1] = rf(AA, 32 + i * 4) +end + +local function antialias(g: number, nbands: number) + local o = g * 4 + for _ = 1, nbands do + for i = 0, 7 do + local ui, di = o + (18 + i) * 4, o + (17 - i) * 4 + local u, d = rf(GRBUF, ui), rf(GRBUF, di) + local c0, c1 = AA0[i + 1], AA1[i + 1] + wf(GRBUF, ui, u * c0 - d * c1) + wf(GRBUF, di, u * c1 + d * c0) + end + o += 72 + end +end + +-- BEGIN generated by tools/gen_dsp.py + +-- L3_dct3_9 on 9 values +local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number) + local t0 = s0 + s6 * 0.5 + s0 -= s6 + local t4 = (s4 + s2) * 0.939692616 + local t2 = (s8 + s2) * 0.766044438 + s6 = (s4 - s8) * 0.173648179 + s4 += s8 - s2 + s2 = s0 - s4 * 0.5 + local y4 = s4 + s0 + s8 = t0 - t2 + s6 + s0 = t0 - t4 + t2 + s4 = t0 + t4 - s6 + s3 *= 0.866025388 + t0 = (s5 + s1) * 0.98480773 + t4 = (s5 - s7) * 0.342020154 + t2 = (s1 + s7) * 0.642787635 + s1 = (s1 - s5 - s7) * 0.866025388 + s5 = t0 - s3 - t2 + s7 = t4 - s3 - t0 + s3 = t4 + s3 - t2 + return s4 - s7, s2 + s1, s0 - s3, s8 + s5, y4, s8 - s5, s0 + s3, s2 - s1, s4 + s7 +end + +-- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values) +local function imdct36(g: number, ov: number, W: { number }, nbands: number) + local w0 = W[1] + local w1 = W[2] + local w2 = W[3] + local w3 = W[4] + local w4 = W[5] + local w5 = W[6] + local w6 = W[7] + local w7 = W[8] + local w8 = W[9] + local w9 = W[10] + local w10 = W[11] + local w11 = W[12] + local w12 = W[13] + local w13 = W[14] + local w14 = W[15] + local w15 = W[16] + local w16 = W[17] + local w17 = W[18] + for _ = 1, nbands do + local gb = g * 4 + local g0 = rf(GRBUF, gb + 0) + local g1 = rf(GRBUF, gb + 4) + local g2 = rf(GRBUF, gb + 8) + local g3 = rf(GRBUF, gb + 12) + local g4 = rf(GRBUF, gb + 16) + local g5 = rf(GRBUF, gb + 20) + local g6 = rf(GRBUF, gb + 24) + local g7 = rf(GRBUF, gb + 28) + local g8 = rf(GRBUF, gb + 32) + local g9 = rf(GRBUF, gb + 36) + local g10 = rf(GRBUF, gb + 40) + local g11 = rf(GRBUF, gb + 44) + local g12 = rf(GRBUF, gb + 48) + local g13 = rf(GRBUF, gb + 52) + local g14 = rf(GRBUF, gb + 56) + local g15 = rf(GRBUF, gb + 60) + local g16 = rf(GRBUF, gb + 64) + local g17 = rf(GRBUF, gb + 68) + local c0, c1, c2, c3, c4, c5, c6, c7, c8 = dct3_9(-g0, g1 + g2, -(g3 + g4), g5 + g6, -(g7 + g8), g9 + g10, -(g11 + g12), g13 + g14, -(g15 + g16)) + local s0, s1, s2, s3, s4, s5, s6, s7, s8 = dct3_9(g17, g16 - g15, g13 - g14, g12 - g11, g9 - g10, g8 - g7, g5 - g6, g4 - g3, g1 - g2) + s1, s3, s5, s7 = -s1, -s3, -s5, -s7 + local ob = ov * 4 + do + local ovl = rf(OVL, ob + 0) + local sum = c0 * 0.675590217 + s0 * 0.737277329 + wf(OVL, ob + 0, c0 * 0.737277329 - s0 * 0.675590217) + wf(GRBUF, gb + 0, ovl * w0 - sum * w9) + wf(GRBUF, gb + 68, ovl * w9 + sum * w0) + end + do + local ovl = rf(OVL, ob + 4) + local sum = c1 * 0.60876143 + s1 * 0.793353319 + wf(OVL, ob + 4, c1 * 0.793353319 - s1 * 0.60876143) + wf(GRBUF, gb + 4, ovl * w1 - sum * w10) + wf(GRBUF, gb + 64, ovl * w10 + sum * w1) + end + do + local ovl = rf(OVL, ob + 8) + local sum = c2 * 0.537299633 + s2 * 0.843391478 + wf(OVL, ob + 8, c2 * 0.843391478 - s2 * 0.537299633) + wf(GRBUF, gb + 8, ovl * w2 - sum * w11) + wf(GRBUF, gb + 60, ovl * w11 + sum * w2) + end + do + local ovl = rf(OVL, ob + 12) + local sum = c3 * 0.4617486 + s3 * 0.887010813 + wf(OVL, ob + 12, c3 * 0.887010813 - s3 * 0.4617486) + wf(GRBUF, gb + 12, ovl * w3 - sum * w12) + wf(GRBUF, gb + 56, ovl * w12 + sum * w3) + end + do + local ovl = rf(OVL, ob + 16) + local sum = c4 * 0.382683426 + s4 * 0.923879504 + wf(OVL, ob + 16, c4 * 0.923879504 - s4 * 0.382683426) + wf(GRBUF, gb + 16, ovl * w4 - sum * w13) + wf(GRBUF, gb + 52, ovl * w13 + sum * w4) + end + do + local ovl = rf(OVL, ob + 20) + local sum = c5 * 0.300705791 + s5 * 0.953716934 + wf(OVL, ob + 20, c5 * 0.953716934 - s5 * 0.300705791) + wf(GRBUF, gb + 20, ovl * w5 - sum * w14) + wf(GRBUF, gb + 48, ovl * w14 + sum * w5) + end + do + local ovl = rf(OVL, ob + 24) + local sum = c6 * 0.216439605 + s6 * 0.976296008 + wf(OVL, ob + 24, c6 * 0.976296008 - s6 * 0.216439605) + wf(GRBUF, gb + 24, ovl * w6 - sum * w15) + wf(GRBUF, gb + 44, ovl * w15 + sum * w6) + end + do + local ovl = rf(OVL, ob + 28) + local sum = c7 * 0.130526185 + s7 * 0.991444886 + wf(OVL, ob + 28, c7 * 0.991444886 - s7 * 0.130526185) + wf(GRBUF, gb + 28, ovl * w7 - sum * w16) + wf(GRBUF, gb + 40, ovl * w16 + sum * w7) + end + do + local ovl = rf(OVL, ob + 32) + local sum = c8 * 0.0436193794 + s8 * 0.999048233 + wf(OVL, ob + 32, c8 * 0.999048233 - s8 * 0.0436193794) + wf(GRBUF, gb + 32, ovl * w8 - sum * w17) + wf(GRBUF, gb + 36, ovl * w17 + sum * w8) + end + g += 18 + ov += 9 + end +end + +-- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals +local function dctII(g: number, n: number) + for k = 0, n - 1 do + local y = (g + k) * 4 + local t0_0, t1_0, t2_0, t3_0 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 0), rf(GRBUF, y + 1080), rf(GRBUF, y + 1152), rf(GRBUF, y + 2232) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 10.1900082, (x0 - x3) * 0.50060302 + t0_0 = a + b + t1_0 = (a - b) * 0.502419293 + t2_0 = d + c + t3_0 = (d - c) * 0.502419293 + end + local t0_1, t1_1, t2_1, t3_1 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 72), rf(GRBUF, y + 1008), rf(GRBUF, y + 1224), rf(GRBUF, y + 2160) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 3.40760851, (x0 - x3) * 0.505470932 + t0_1 = a + b + t1_1 = (a - b) * 0.522498608 + t2_1 = d + c + t3_1 = (d - c) * 0.522498608 + end + local t0_2, t1_2, t2_2, t3_2 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 144), rf(GRBUF, y + 936), rf(GRBUF, y + 1296), rf(GRBUF, y + 2088) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 2.05778098, (x0 - x3) * 0.515447319 + t0_2 = a + b + t1_2 = (a - b) * 0.566944063 + t2_2 = d + c + t3_2 = (d - c) * 0.566944063 + end + local t0_3, t1_3, t2_3, t3_3 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 216), rf(GRBUF, y + 864), rf(GRBUF, y + 1368), rf(GRBUF, y + 2016) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.4841646, (x0 - x3) * 0.531042576 + t0_3 = a + b + t1_3 = (a - b) * 0.646821797 + t2_3 = d + c + t3_3 = (d - c) * 0.646821797 + end + local t0_4, t1_4, t2_4, t3_4 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 288), rf(GRBUF, y + 792), rf(GRBUF, y + 1440), rf(GRBUF, y + 1944) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.16943991, (x0 - x3) * 0.553103924 + t0_4 = a + b + t1_4 = (a - b) * 0.788154602 + t2_4 = d + c + t3_4 = (d - c) * 0.788154602 + end + local t0_5, t1_5, t2_5, t3_5 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 360), rf(GRBUF, y + 720), rf(GRBUF, y + 1512), rf(GRBUF, y + 1872) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.972568214, (x0 - x3) * 0.582934976 + t0_5 = a + b + t1_5 = (a - b) * 1.06067765 + t2_5 = d + c + t3_5 = (d - c) * 1.06067765 + end + local t0_6, t1_6, t2_6, t3_6 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 432), rf(GRBUF, y + 648), rf(GRBUF, y + 1584), rf(GRBUF, y + 1800) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.839349627, (x0 - x3) * 0.622504115 + t0_6 = a + b + t1_6 = (a - b) * 1.72244716 + t2_6 = d + c + t3_6 = (d - c) * 1.72244716 + end + local t0_7, t1_7, t2_7, t3_7 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 504), rf(GRBUF, y + 576), rf(GRBUF, y + 1656), rf(GRBUF, y + 1728) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.744536281, (x0 - x3) * 0.674808323 + t0_7 = a + b + t1_7 = (a - b) * 5.10114861 + t2_7 = d + c + t3_7 = (d - c) * 5.10114861 + end + do -- row 0 + local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t0_0 = x0 + x1 + t0_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t0_1 = (xt + x7) * 0.509795606 + t0_2 = (x4 + x3) * 0.541196108 + t0_3 = (x0 - x5) * 0.601344883 + t0_5 = (x0 + x5) * 0.899976194 + t0_6 = (x4 - x3) * 1.30656302 + t0_7 = (xt - x7) * 2.56291556 + end + do -- row 1 + local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t1_0 = x0 + x1 + t1_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t1_1 = (xt + x7) * 0.509795606 + t1_2 = (x4 + x3) * 0.541196108 + t1_3 = (x0 - x5) * 0.601344883 + t1_5 = (x0 + x5) * 0.899976194 + t1_6 = (x4 - x3) * 1.30656302 + t1_7 = (xt - x7) * 2.56291556 + end + do -- row 2 + local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t2_0 = x0 + x1 + t2_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t2_1 = (xt + x7) * 0.509795606 + t2_2 = (x4 + x3) * 0.541196108 + t2_3 = (x0 - x5) * 0.601344883 + t2_5 = (x0 + x5) * 0.899976194 + t2_6 = (x4 - x3) * 1.30656302 + t2_7 = (xt - x7) * 2.56291556 + end + do -- row 3 + local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t3_0 = x0 + x1 + t3_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t3_1 = (xt + x7) * 0.509795606 + t3_2 = (x4 + x3) * 0.541196108 + t3_3 = (x0 - x5) * 0.601344883 + t3_5 = (x0 + x5) * 0.899976194 + t3_6 = (x4 - x3) * 1.30656302 + t3_7 = (xt - x7) * 2.56291556 + end + wf(GRBUF, y + 0, t0_0) + wf(GRBUF, y + 72, t2_0 + t3_0 + t3_1) + wf(GRBUF, y + 144, t1_0 + t1_1) + wf(GRBUF, y + 216, t2_1 + t3_0 + t3_1) + wf(GRBUF, y + 288, t0_1) + wf(GRBUF, y + 360, t2_1 + t3_1 + t3_2) + wf(GRBUF, y + 432, t1_1 + t1_2) + wf(GRBUF, y + 504, t2_2 + t3_1 + t3_2) + wf(GRBUF, y + 576, t0_2) + wf(GRBUF, y + 648, t2_2 + t3_2 + t3_3) + wf(GRBUF, y + 720, t1_2 + t1_3) + wf(GRBUF, y + 792, t2_3 + t3_2 + t3_3) + wf(GRBUF, y + 864, t0_3) + wf(GRBUF, y + 936, t2_3 + t3_3 + t3_4) + wf(GRBUF, y + 1008, t1_3 + t1_4) + wf(GRBUF, y + 1080, t2_4 + t3_3 + t3_4) + wf(GRBUF, y + 1152, t0_4) + wf(GRBUF, y + 1224, t2_4 + t3_4 + t3_5) + wf(GRBUF, y + 1296, t1_4 + t1_5) + wf(GRBUF, y + 1368, t2_5 + t3_4 + t3_5) + wf(GRBUF, y + 1440, t0_5) + wf(GRBUF, y + 1512, t2_5 + t3_5 + t3_6) + wf(GRBUF, y + 1584, t1_5 + t1_6) + wf(GRBUF, y + 1656, t2_6 + t3_5 + t3_6) + wf(GRBUF, y + 1728, t0_6) + wf(GRBUF, y + 1800, t2_6 + t3_6 + t3_7) + wf(GRBUF, y + 1872, t1_6 + t1_7) + wf(GRBUF, y + 1944, t2_7 + t3_6 + t3_7) + wf(GRBUF, y + 2016, t0_7) + wf(GRBUF, y + 2088, t2_7 + t3_7) + wf(GRBUF, y + 2160, t1_7) + wf(GRBUF, y + 2232, t3_7) + end +end + +-- END generated + + +-- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index +local function imdct12(x: number, dst: buffer, d: number, ov: number) + local xb = x * 4 + local x0, x3, x6, x9, x12, x15 = + rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60) + -- L3_idct3(-x0, x6 + x3, x12 + x9) -> co + local c0, c1, c2 = -x0, (x6 + x3), (x12 + x9) + local m1 = (c1 * 0.86602540) + local a1 = (c0 - c2 * 0.5) + local co1 = c0 + c2 + local co0, co2 = a1 + m1, a1 - m1 + -- L3_idct3(x15, x12 - x9, x6 - x3) -> si + c0, c1, c2 = x15, (x12 - x9), (x6 - x3) + m1 = (c1 * 0.86602540) + a1 = (c0 - c2 * 0.5) + local si1 = -(c0 + c2) + local si0, si2 = a1 + m1, a1 - m1 + local ob, db = ov * 4, d * 4 + for i = 0, 2 do + local co = if i == 0 then co0 elseif i == 1 then co1 else co2 + local si = if i == 0 then si0 elseif i == 1 then si1 else si2 + local ovl = rf(OVL, ob + i * 4) + local sum = (co * rf(TWID3, (3 + i) * 4) + si * rf(TWID3, i * 4)) + wf(OVL, ob + i * 4, co * rf(TWID3, i * 4) - si * rf(TWID3, (3 + i) * 4)) + wf(dst, db + i * 4, ovl * rf(TWID3, (2 - i) * 4) - sum * rf(TWID3, (5 - i) * 4)) + wf(dst, db + (5 - i) * 4, ovl * rf(TWID3, (5 - i) * 4) + sum * rf(TWID3, (2 - i) * 4)) + end +end + +local function imdctShort(g: number, ov: number, nbands: number) + for _ = 1, nbands do + bcopy(TMP, 0, GRBUF, g * 4, 72) + bcopy(GRBUF, g * 4, OVL, ov * 4, 24) + imdct12(0, GRBUF, g + 6, ov + 6) + imdct12(1, GRBUF, g + 12, ov + 6) + imdct12(2, OVL, ov, ov + 6) + g += 18 + ov += 9 + end +end + +local function changeSign(g: number) + local o = (g + 18) * 4 + for _ = 0, 15 do + for i = 1, 17, 2 do + wf(GRBUF, o + i * 4, -rf(GRBUF, o + i * 4)) + end + o += 144 + end +end + +local function imdctGr(g: number, ov: number, bt: number, nLongBands: number) + if nLongBands ~= 0 then + imdct36(g, ov, MDCT_WIN0, nLongBands) + g += 18 * nLongBands + ov += 9 * nLongBands + end + if bt == 2 then + imdctShort(g, ov, 32 - nLongBands) + else + imdct36(g, ov, if bt == 3 then MDCT_WIN1 else MDCT_WIN0, 32 - nLongBands) + end +end + +-- L3_decode: one granule, side info at gr = grBase + ch +local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number) + for ch = 0, nch - 1 do + local gr = grBase + ch + local limit = bsPos + GR_P23[gr] + decodeScalefactors(h1, h3, ch * 39, gr, ch) + huffman(ch * 576, gr, limit) + end + if band(h3, 0x10) ~= 0 then + intensityStereo(h1, h3, grBase) + elseif band(h3, 0xE0) == 0x60 then + midside(0, 576) + end + local mySr = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + for ch = 0, nch - 1 do + local gr = grBase + ch + local aaBands = 31 + local nLongBands = if GR_MIXED[gr] ~= 0 then (if mySr == 2 then 4 else 2) else 0 + local g = ch * 576 + if GR_NSHORT[gr] ~= 0 then + aaBands = nLongBands - 1 + reorder(g + nLongBands * 18, GR_SFB[gr] + GR_NLONG[gr]) + end + antialias(g, aaBands) + imdctGr(g, ch * 288, GR_BT[gr], nLongBands) + changeSign(g) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) + + +-- mp3d_synth_pair: z = SYN float index, dst = PCM float index +local function synthPair(dst: number, nch: number, z: number) + local zb = z * 4 + local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 + a += (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 + a += (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459 + a += (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037 + a += (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153 + a += (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574 + a += (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489 + a += rf(SYN, zb + 7 * 256) * 75038 + wf(PCM, dst * 4, a * SCALE) + zb += 8 + a = rf(SYN, zb + 14 * 256) * 104 + a += rf(SYN, zb + 12 * 256) * 1567 + a += rf(SYN, zb + 10 * 256) * 9727 + a += rf(SYN, zb + 8 * 256) * 64019 + a += rf(SYN, zb + 6 * 256) * -9975 + a += rf(SYN, zb + 4 * 256) * -45 + a += rf(SYN, zb + 2 * 256) * 146 + a += rf(SYN, zb) * -5 + wf(PCM, (dst + 16 * nch) * 4, a * SCALE) +end + +-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left +-- channel's slot, dstl = PCM float index, lins = SYN float index +local function synth(xl: number, dstl: number, nch: number, lins: number) + local xr = xl + 576 * (nch - 1) + local dstr = dstl + (nch - 1) + local zlin = lins + 15 * 64 + local zb = zlin * 4 + local xlb, xrb = xl * 4, xr * 4 + wf(SYN, zb + 60 * 4, rf(GRBUF, xlb + 288 * 4)) + wf(SYN, zb + 61 * 4, rf(GRBUF, xrb + 288 * 4)) + wf(SYN, zb + 62 * 4, rf(GRBUF, xlb)) + wf(SYN, zb + 63 * 4, rf(GRBUF, xrb)) + wf(SYN, zb + 124 * 4, rf(GRBUF, xlb + 289 * 4)) + wf(SYN, zb + 125 * 4, rf(GRBUF, xrb + 289 * 4)) + wf(SYN, zb + 126 * 4, rf(GRBUF, xlb + 4)) + wf(SYN, zb + 127 * 4, rf(GRBUF, xrb + 4)) + if nch == 2 then + synthPair(dstr, nch, lins + 4 * 15 + 1) + synthPair(dstr + 32 * nch, nch, lins + 4 * 15 + 64 + 1) + end + synthPair(dstl, nch, lins + 4 * 15) + synthPair(dstl + 32 * nch, nch, lins + 4 * 15 + 64) + + local w = 1 + for i = 14, 0, -1 do + local zi = zb + 16 * i + local s1 = (18 * (31 - i)) * 4 + local s2 = (18 * (1 + i)) * 4 + wf(SYN, zi, rf(GRBUF, xlb + s1)) + wf(SYN, zi + 4, rf(GRBUF, xrb + s1)) + wf(SYN, zi + 8, rf(GRBUF, xlb + s1 + 4)) + wf(SYN, zi + 12, rf(GRBUF, xrb + s1 + 4)) + wf(SYN, zi + 256, rf(GRBUF, xlb + s2 + 4)) + wf(SYN, zi + 260, rf(GRBUF, xrb + s2 + 4)) + wf(SYN, zi - 248, rf(GRBUF, xlb + s2)) + wf(SYN, zi - 244, rf(GRBUF, xrb + s2)) + -- the 8 window steps, even k (a += z w0 - y w1) and odd k (a += y w1 - z w0) in pairs; mono needs lanes 0, 2 + local a0, a1, a2, a3, b0, b1, b2, b3 = 0, 0, 0, 0, 0, 0, 0, 0 + local vz, vy = zi, zi - 15 * 256 + if nch == 2 then + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w += 4 + local z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) + local y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) + b0 += z0 * w1 + y0 * w0 + b1 += z1 * w1 + y1 * w0 + b2 += z2 * w1 + y2 * w0 + b3 += z3 * w1 + y3 * w0 + a0 += z0 * w0 - y0 * w1 + a1 += z1 * w0 - y1 * w1 + a2 += z2 * w0 - y2 * w1 + a3 += z3 * w0 - y3 * w1 + vz -= 256 + vy += 256 + z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) + y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) + b0 += z0 * w3 + y0 * w2 + b1 += z1 * w3 + y1 * w2 + b2 += z2 * w3 + y2 * w2 + b3 += z3 * w3 + y3 * w2 + a0 += y0 * w3 - z0 * w2 + a1 += y1 * w3 - z1 * w2 + a2 += y2 * w3 - z2 * w2 + a3 += y3 * w3 - z3 * w2 + vz -= 256 + vy += 256 + end + wf(PCM, (dstr + (15 - i) * 2) * 4, a1 * SCALE) + wf(PCM, (dstr + (17 + i) * 2) * 4, b1 * SCALE) + wf(PCM, (dstr + (47 - i) * 2) * 4, a3 * SCALE) + wf(PCM, (dstr + (49 + i) * 2) * 4, b3 * SCALE) + else + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w += 4 + local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) + local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) + b0 += z0 * w1 + y0 * w0 + b2 += z2 * w1 + y2 * w0 + a0 += z0 * w0 - y0 * w1 + a2 += z2 * w0 - y2 * w1 + vz -= 256 + vy += 256 + z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) + y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) + b0 += z0 * w3 + y0 * w2 + b2 += z2 * w3 + y2 * w2 + a0 += y0 * w3 - z0 * w2 + a2 += y2 * w3 - z2 * w2 + vz -= 256 + vy += 256 + end + end + wf(PCM, (dstl + (15 - i) * nch) * 4, a0 * SCALE) + wf(PCM, (dstl + (17 + i) * nch) * 4, b0 * SCALE) + wf(PCM, (dstl + (47 - i) * nch) * 4, a2 * SCALE) + wf(PCM, (dstl + (49 + i) * nch) * 4, b2 * SCALE) + end +end + +local function synthGranule(nbands: number, nch: number, pcm: number) + for ch = 0, nch - 1 do + dctII(576 * ch, nbands) + end + bcopy(SYN, 0, QMF, 0, 15 * 64 * 4) + for i = 0, nbands - 1, 2 do + synth(i, pcm + 32 * nch * i, nch, i * 64) + end + if nch == 1 then + local src = nbands * 64 * 4 + for i = 0, 15 * 64 * 4 - 8, 8 do + wf(QMF, i, rf(SYN, src + i)) + end + else + bcopy(QMF, 0, SYN, nbands * 64 * 4, 15 * 64 * 4) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layers I and II + +local ALLOC_L1 = { 76, 4, 32 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } + +local totalBands, stereoBands = 0, 0 + +local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number) + local mode = rshift(h3, 6) + local sb = if mode == 3 then 0 elseif mode == 1 then band(rshift(h3, 4), 3) * 4 + 4 else 32 + local layer1 = band(h1, 6) == 6 + local alloc, nbands + if layer1 then + alloc, nbands = ALLOC_L1, 32 + elseif band(h1, 8) == 0 then + alloc, nbands = ALLOC_L2M2, 30 + else + local srIdx = band(rshift(h2, 2), 3) + local kbps = if mode ~= 3 then rshift(kbpsHdr, 1) else kbpsHdr + if kbps == 0 then + kbps = 192 + end + alloc, nbands = ALLOC_L2M1, 27 + if kbps < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIdx == 2 then 12 else 8 + elseif kbps >= 96 and srIdx ~= 1 then + nbands = 30 + end + end + totalBands = nbands + stereoBands = min(sb, nbands) + local k, baBits, codeOff, ai = 0, 0, 0, 1 + for i = 0, nbands - 1 do + if i == k then + codeOff, baBits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + local ba = BITALLOC_CODE[codeOff + getBits(baBits)] + wu8(BA, 2 * i, ba) + if i < stereoBands then + ba = BITALLOC_CODE[codeOff + getBits(baBits)] + end + wu8(BA, 2 * i + 1, if stereoBands ~= 0 then ba else 0) + end + for i = 0, 2 * nbands - 1 do + wu8(SCFCOD, i, if ru8(BA, i) ~= 0 then (if layer1 then 2 else getBits(2)) else 6) + end + -- L12_read_scalefactors + local so = 0 + for i = 0, 2 * nbands - 1 do + local s = 0 + local ba = ru8(BA, i) + local mask = if ba ~= 0 then 4 + band(rshift(19, ru8(SCFCOD, i)), 3) else 0 + local m = 4 + while m ~= 0 do + if band(mask, m) ~= 0 then + local b = getBits(6) + s = f32(DEQ_L12[ba * 3 - 6 + b % 3] * rshift(lshift(1, 21), b // 3)) + end + wf(L12SCF, so, s) + so += 4 + m = rshift(m, 1) + end + end + for i = stereoBands, nbands - 1 do + wu8(BA, 2 * i + 1, 0) + end +end + +local function l12Dequantize(g: number, groupSize: number): number + local choff = 576 + for j = 0, 3 do + local dst = g + groupSize * j + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + local half = lshift(1, ba - 1) - 1 + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, getBits(ba) - half) + end + else + local mod = lshift(2, ba - 17) + 1 + local code = getBits(mod + 2 - rshift(mod, 3)) + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, code % mod - mod // 2) + code //= mod + end + end + end + dst += choff + choff = 18 - choff + end + end + return groupSize * 4 +end + +local function l12ApplyScf(scfOff: number) + local sb, tb = stereoBands, totalBands + bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4) + for i = 0, tb - 1 do + local d = i * 72 + local s0 = rf(L12SCF, (scfOff + i * 6) * 4) + local s1 = rf(L12SCF, (scfOff + i * 6 + 3) * 4) + for k = 0, 11 do + local p = d + k * 4 + wf(GRBUF, p, rf(GRBUF, p) * s0) + wf(GRBUF, p + 2304, rf(GRBUF, p + 2304) * s1) + end + end +end + +---------------------------------------------------------------------------------------------------------------- +-- API + +local Core = {} + +Core.MAX_FRAME = MAX_FRAME + +export type State = { + overlap: buffer, + qmf: buffer, + reserv: buffer, + reservLen: number, + needReset: boolean, +} + +function Core.newState(): State + return { + overlap = bcreate(2 * 9 * 32 * 4), + qmf = bcreate(15 * 2 * 32 * 4), + reserv = bcreate(MAX_BITRESERVOIR_BYTES + 8), + reservLen = 0, + needReset = false, + } +end + +-- memset(dec, 0): what minimp3 does whenever it has to re-sync +function Core.reset(st: State) + bfill(st.overlap, 0, 0) + bfill(st.qmf, 0, 0) + st.reservLen = 0 + st.needReset = false +end + +Core.lastChannels = 0 + +-- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place) +function Core.upmix(pcm: buffer, n: number) + if buffer.len(pcm) < n * 8 then + return + end + for i = n - 1, 0, -1 do + local v = rf(pcm, i * 4) + wf(pcm, i * 8, v) + wf(pcm, i * 8 + 4, v) + end +end + +-- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm +-- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an +-- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count. +function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number + if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then + st.needReset = true + return 0 + end + if st.needReset then + Core.reset(st) + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + OVL, QMF, PCM = st.overlap, st.qmf, pcm + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + local nch = if band(h3, 0xC0) == 0xC0 then 1 else 2 + Core.lastChannels = nch + local layer = 4 - band(rshift(h1, 1), 3) + local spf = if band(h1, 6) == 6 then 384 elseif band(h1, 14) == 2 then 576 else 1152 + if buffer.len(pcm) < spf * nch * 4 then + return 0 + end + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) -- CRC + end + if layer == 3 then + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + st.needReset = true + return 0 + end + -- L3_restore_reservoir + local frameBytes = (bsLimit - bsPos) // 8 + local reserv = st.reservLen + local have = min(reserv, mdb) + if have > 0 then + bcopy(MAIN, 0, st.reserv, max(0, reserv - mdb), have) + end + bcopy(MAIN, have, FRAME, bsPos // 8, frameBytes) + bfill(MAIN, have + frameBytes, 0, 8) + local success = reserv >= mdb + bsBuf, bsPos, bsLimit = MAIN, 0, (have + frameBytes) * 8 + if success then + local ngr = if band(h1, 8) ~= 0 then 2 else 1 + local p = 0 + for igr = 0, ngr - 1 do + bfill(GRBUF, 0, 0) + l3Decode(h1, h2, h3, igr * nch, nch) + synthGranule(18, nch, p) + p += 576 * nch + end + end + -- L3_save_reservoir + local pos = (bsPos + 7) // 8 + local remains = bsLimit // 8 - pos + if remains > MAX_BITRESERVOIR_BYTES then + pos += remains - MAX_BITRESERVOIR_BYTES + remains = MAX_BITRESERVOIR_BYTES + end + if remains > 0 and pos >= 0 then + bcopy(st.reserv, 0, MAIN, pos, remains) + end + st.reservLen = max(0, remains) + bsBuf = FRAME + return if success then spf else 0 + end + -- layers I / II + local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + bfill(GRBUF, 0, 0) + local i = 0 + local p = 0 + local group = bor(layer, 1) + for igr = 0, 2 do + i += l12Dequantize(i, group) + if i == 12 then + i = 0 + l12ApplyScf(igr) + synthGranule(12, nch, p) + bfill(GRBUF, 0, 0) + p += 384 * nch + end + if bsPos > bsLimit then + st.needReset = true + return 0 + end + end + return spf +end + +-- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its +-- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index. +function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) + local n = min(size, 64) + if size < 4 or off + n > buffer.len(b) then + return -1, 0, 0 + end + bcopy(FRAME, 0, b, off, n) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + return -1, 0, 0 + end + local ngr = (if band(h3, 0xC0) == 0xC0 then 1 else 2) * (if band(h1, 8) ~= 0 then 2 else 1) + local sum = 0 + for gr = 0, ngr - 1 do + sum += GR_P23[gr] + end + return mdb, sum, (bsLimit - bsPos) // 8 +end + +-- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it). +function Core.probeL12(b: buffer, off: number, size: number): boolean + if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then + return false + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local layer = 4 - band(rshift(h1, 1), 3) + local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + -- the samples: 3 calls of l12Dequantize, each 4 groups of (layer | 1) samples per allocated band + local group = bor(layer, 1) + local bits = 0 + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + bits += ba * group + else + local mod = lshift(2, ba - 17) + 1 + bits += mod + 2 - rshift(mod, 3) + end + end + end + return bsPos + 12 * bits <= bsLimit +end + +-- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame +-- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension) +function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number) + if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then + return 0, 0, 0, 0 + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + if readSideInfo(h1, h2, h3) < 0 then + return 0, 0, 0, 0 + end + local t = bsPos // 8 + if t > size or size - t < 8 then + return 0, 0, 0, 0 + end + local tag = buffer.readstring(FRAME, t, 4) + if tag ~= "Xing" and tag ~= "Info" then + return 0, 0, 0, 0 + end + local flags = ru8(FRAME, t + 7) + if band(flags, 1) == 0 then + return -1, 0, 0, 0 + end + t += 8 + if size - t < 4 then + return 0, 0, 0, 0 + end + local frames = bswap(ru32(FRAME, t)) + t += 4 + if band(flags, 2) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t += 4 + end + if band(flags, 4) ~= 0 then + if size - t < 100 then + return 0, 0, 0, 0 + end + t += 100 + end + if band(flags, 8) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t += 4 + end + if size - t < 1 then + return 0, 0, 0, 0 + end + local delay, padding = 0, 0 + if ru8(FRAME, t) ~= 0 then + if size - t <= 35 then + return 0, 0, 0, 0 + end + t += 21 + local t0, t1, t2 = ru8(FRAME, t), ru8(FRAME, t + 1), ru8(FRAME, t + 2) + delay = bor(lshift(t0, 4), rshift(t1, 4)) + 529 + padding = bor(lshift(band(t1, 15), 8), t2) - 529 + end + return 1, frames, delay, padding +end + +return Core diff --git a/src/Formats/audio/mp3/Header.luau b/src/Formats/audio/mp3/Header.luau new file mode 100644 index 0000000..456f171 --- /dev/null +++ b/src/Formats/audio/mp3/Header.luau @@ -0,0 +1,140 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame / +-- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4 +-- inside the buffer. Never throws. +local T = require("@formats/audio/mp3/Tables") + +local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift +local ru8 = buffer.readu8 + +local HALFRATE = T.halfrate +local HZ = { [0] = 44100, 48000, 32000 } + +local H = {} + +H.MAX_FREE_FORMAT_FRAME_SIZE = 2304 +H.MAX_FRAME_SYNC_MATCHES = 10 + +-- hdr_valid +function H.valid(b: buffer, o: number): boolean + if ru8(b, o) ~= 0xFF then + return false + end + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2) + and band(rshift(h1, 1), 3) ~= 0 + and rshift(h2, 4) ~= 15 + and band(rshift(h2, 2), 3) ~= 3 +end +local valid = H.valid + +-- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1 +function H.compare(b: buffer, o1: number, o2: number): boolean + if not valid(b, o2) then + return false + end + local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2) + local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2) + return band(bxor(a1, c1), 0xFE) == 0 + and band(bxor(a2, c2), 0x0C) == 0 + and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0) +end +local compare = H.compare + +-- from the header bytes h1 = byte 1, h2 = byte 2 +function H.bitrateKbps(h1: number, h2: number): number + local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0 + local layer = band(rshift(h1, 1), 3) + return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] +end +local bitrateKbps = H.bitrateKbps + +function H.sampleRate(h1: number, h2: number): number + local hz = HZ[band(rshift(h2, 2), 3)] + if band(h1, 8) == 0 then + hz //= 2 + end + if band(h1, 0x10) == 0 then + hz //= 2 + end + return hz +end +local sampleRate = H.sampleRate + +function H.frameSamples(h1: number): number + if band(h1, 6) == 6 then + return 384 + elseif band(h1, 14) == 2 then + return 576 + end + return 1152 +end +local frameSamples = H.frameSamples + +-- hdr_frame_bytes (without padding); free format = 0 -> freeSize +function H.frameBytes(b: buffer, o: number, freeSize: number): number + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + local hz = sampleRate(h1, h2) + local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz + if band(h1, 6) == 6 then + fb = band(fb, 0xFFFFFFFC) + end + return if fb ~= 0 then fb else freeSize +end +local frameBytes = H.frameBytes + +function H.padding(b: buffer, o: number): number + if band(ru8(b, o + 2), 2) == 0 then + return 0 + end + return if band(ru8(b, o + 1), 6) == 6 then 4 else 1 +end +local padding = H.padding + +-- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal +local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean + local i = 0 + for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do + i += frameBytes(b, o + i, fb) + padding(b, o + i) + if i + 4 > n then + return nmatch > 0 + end + if not compare(b, o, o + i) then + return false + end + end + return true +end + +-- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size) +function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) + for i = 0, n - 5 do + local o = base + i + if valid(b, o) then + local fb = frameBytes(b, o, ffb) + local fap = fb + padding(b, o) + local k = 4 + while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do + if compare(b, o, o + k) then + local f = k - padding(b, o) + local nextfb = f + padding(b, o + k) + if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then + fap = k + fb = f + ffb = f + end + end + k += 1 + end + if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then + return i, fap, ffb + end + ffb = 0 + end + end + return n, 0, ffb +end + +return H diff --git a/src/Formats/audio/mp3/Index.luau b/src/Formats/audio/mp3/Index.luau new file mode 100644 index 0000000..97ca48f --- /dev/null +++ b/src/Formats/audio/mp3/Index.luau @@ -0,0 +1,194 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame +-- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so +-- it knows in advance which frames give output and where each one's samples land. That makes the total length +-- exact and seeking sample-accurate. Never throws. +local Header = require("@formats/audio/mp3/Header") +local Core = require("@formats/audio/mp3/Core") + +local band, rshift = bit32.band, bit32.rshift +local ru8 = buffer.readu8 +local min, max = math.min, math.max + +local compare, frameBytes, padding, findFrame = + Header.compare, Header.frameBytes, Header.padding, Header.findFrame + +local Index = {} + +Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here) +Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode + +export type Index = { + n: number, -- frames + off: buffer, -- u32 byte offset per frame + size: buffer, -- u16 byte size per frame (header and padding included) + flags: buffer, -- u8 FLAG_* + out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame + main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II) + outTotal: number, -- samples (per channel) of a continuous decode, delay not cut + bytes: number, -- audio bytes in indexed frames + -- format of the first frame + sampleRate: number, + channels: number, -- the most channels of any frame + layer: number, + version: number, -- 1, 2 or 2.5 + spf: number, -- samples per frame + -- Xing / Info / LAME + vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none) + tagFrames: number, + delay: number, + padding: number, + skipped: number, -- frames with another sample rate or layer, left out +} + +local function grow(b: buffer, n: number): buffer + local nb = buffer.create(n) + buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) + return nb +end + +function Index.build(b: buffer, start: number, stop: number): Index? + local cap = 1024 + local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2) + local n = 0 + local pos = start + local prev = -1 -- offset of the last decoded header (dec->header), -1 = none + local ffb = 0 -- free format bytes + local reserv = 0 + local outTotal = 0 + local bytes = 0 + local first = true + local skipped = 0 + local outCh = 0 -- the most channels of a frame that gives output + local hz, nch, layer, spf, version = 0, 0, 0, 0, 0 + local vbr, tagFrames, delay, pad = 0, 0, 0, 0 + + while true do + local remaining = stop - pos + if remaining <= 0 then + break + end + local fs = 0 + local reset = false + if remaining > 4 and prev >= 0 and compare(b, prev, pos) then + fs = frameBytes(b, pos, ffb) + padding(b, pos) + if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then + fs = 0 + end + end + if fs == 0 then + reset = true + reserv = 0 + local i + i, fs, ffb = findFrame(b, pos, remaining, 0) + if fs == 0 or i + fs > remaining then + break + end + pos += i + end + if fs < 4 or fs > Core.MAX_FRAME then + -- cannot happen with a well-formed header, but never index an impossible frame + prev = -1 + pos += max(fs, 1) + continue + end + local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3) + local fLayer = 4 - band(rshift(h1, 1), 3) + local fHz = Header.sampleRate(h1, h2) + local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2 + + if first then + first = false + hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) + version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5 + if fLayer == 3 then + local ret, frames, d, p = Core.vbrTag(b, pos, fs) + if ret ~= 0 then + vbr, tagFrames, delay, pad = ret, frames, d, p + if ret < 0 then + delay, pad = 0, 0 + end + -- the tag frame is not audio; the next frame is found again from scratch + prev = -1 + pos += fs + continue + end + end + elseif fHz ~= hz or fLayer ~= layer then + skipped += 1 + prev = pos + pos += fs + continue + end + + local output = true + local mainBytes = 0 + local nextPrev = pos + if fLayer == 3 then + local mdb, p23, mb = Core.probeL3(b, pos, fs) + if mdb < 0 then + output = false + nextPrev = -1 -- mp3dec_init: the next frame re-syncs + else + mainBytes = mb + local have = min(reserv, mdb) + output = reserv >= mdb + local remains = have + mb - (if output then (p23 + 7) // 8 else 0) + reserv = max(0, min(remains, 511)) + end + else + output = Core.probeL12(b, pos, fs) + if not output then + nextPrev = -1 + end + end + + if output and fCh > outCh then + outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated + end + if n == cap then + cap *= 2 + OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) + end + buffer.writeu32(OFF, n * 4, pos) + buffer.writeu16(SIZE, n * 2, fs) + buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0)) + buffer.writeu32(OUT, n * 4, outTotal) + buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535)) + n += 1 + bytes += fs + if output then + outTotal += spf + end + prev = nextPrev + pos += fs + end + + if first then + return nil + end + return { + n = n, + off = OFF, + size = SIZE, + flags = FLAGS, + out = OUT, + main = MAIN, + outTotal = outTotal, + bytes = bytes, + sampleRate = hz, + channels = if outCh > 0 then outCh else nch, + layer = layer, + version = version, + spf = spf, + vbrTag = vbr, + tagFrames = tagFrames, + delay = delay, + padding = pad, + skipped = skipped, + } +end + +return Index diff --git a/src/Formats/audio/mp3/Stream.luau b/src/Formats/audio/mp3/Stream.luau new file mode 100644 index 0000000..4bf0414 --- /dev/null +++ b/src/Formats/audio/mp3/Stream.luau @@ -0,0 +1,233 @@ +--!strict +--!optimize 2 +-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact +-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws. +local Core = require("@formats/audio/mp3/Core") +local Index = require("@formats/audio/mp3/Index") + +local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT +local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32 +local band = bit32.band +local min, max, floor = math.min, math.max, math.floor + +local Stream = {} + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable( + {} :: { + sampleRate: number, + channels: number, + frames: number, + duration: number, + bitrate: number, + tags: { [string]: string }, + id3: any, + layer: number, + version: number, + vbr: boolean, + delay: number, + padding: number, + mpegFrames: number, + _buf: buffer, + _idx: any, + _st: any, + _pcm: buffer, + _cur: number, + _pcmPos: number, + _pcmEnd: number, + _minAbs: number, + _endAbs: number, + _pos: number, + }, + Decoder +)) + +-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build) +function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder + local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels + -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count + local delay = 0 + local total = idx.outTotal + if idx.vbrTag > 0 then + delay = idx.delay + local detected = spf * idx.tagFrames + if detected >= delay then + detected -= delay + end + if idx.padding > 0 and detected >= idx.padding then + detected -= idx.padding + end + total = max(0, total - delay) + total = min(total, detected) + end + delay = min(delay, idx.outTotal) + local self = setmetatable({ + sampleRate = hz, + channels = nch, + frames = total, + duration = total / hz, + bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) / 1000 + 0.5) else 0, + tags = tags, + id3 = id3, + layer = idx.layer, + version = idx.version, + vbr = idx.vbrTag ~= 0, + delay = delay, + padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0, + mpegFrames = idx.n, + _buf = b, + _idx = idx, + _st = Core.newState(), + _pcm = buffer.create(1152 * 2 * 4), + _cur = 0, + _pcmPos = 0, + _pcmEnd = 0, + _minAbs = delay, + _endAbs = delay + total, + _pos = 0, + }, Decoder) + return self +end + + +-- decodes frames until one has samples inside [minAbs, endAbs); false at the end +local function fill(self: Decoder): boolean + local idx = self._idx + local n = idx.n + local spf = idx.spf + local st = self._st + while self._cur < n do + local f = self._cur + self._cur = f + 1 + local flags = ru8(idx.flags, f) + if band(flags, FLAG_RESET) ~= 0 then + Core.reset(st) + end + local a = ru32(idx.out, f * 4) + if a >= self._endAbs then + self._cur = n + return false + end + local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm) + if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then + if Core.lastChannels < self.channels then + Core.upmix(self._pcm, got) + end + local lo = max(a, self._minAbs) + local hi = min(a + spf, self._endAbs) + if hi > lo then + self._pcmPos = lo - a + self._pcmEnd = hi - a + return true + end + end + end + return false +end + +-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream. +-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a +-- smaller out is ignored. +function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number) + local ch = self.channels + local want = tonumber(maxFrames) or 4096 + if want ~= want then + want = 0 + end + want = floor(max(0, min(want, self.frames - self._pos))) + if out and buffer.len(out) < want * ch * 4 then + out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough) + end + local dst = out or buffer.create(want * ch * 4) + local got = 0 + local pcm = self._pcm + while got < want do + if self._pcmPos >= self._pcmEnd then + if not fill(self) then + break + end + end + local k = min(want - got, self._pcmEnd - self._pcmPos) + buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4) + got += k + self._pcmPos += k + end + self._pos += got + if not out and got < want then + local r = buffer.create(got * ch * 4) + buffer.copy(r, 0, dst, 0, got * ch * 4) + dst = r + end + return dst, got +end + +-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier +-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped. +function Decoder.seek(self: Decoder, seconds: number) + local hz = self.sampleRate + local target = floor((tonumber(seconds) or 0) * hz + 0.5) + target = max(0, min(target, self.frames)) + self:seekFrame(target) +end + +-- Seeks to a sample frame (0 .. frames). +function Decoder.seekFrame(self: Decoder, target: number) + target = tonumber(target) or 0 + if target ~= target then + target = 0 + end + target = max(0, min(floor(target), self.frames)) + local idx = self._idx + local abs = self.delay + target + self._pos = target + self._minAbs = abs + self._pcmPos, self._pcmEnd = 0, 0 + Core.reset(self._st) + local n = idx.n + if abs >= self._endAbs or n == 0 then + self._cur = n + return + end + -- last frame starting at or before abs + local lo, hi = 0, n - 1 + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ru32(idx.out, mid * 4) <= abs then + lo = mid + else + hi = mid - 1 + end + end + local j = lo + -- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data + -- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets + local need = if idx.layer == 3 then 511 else 0 + local s, back, acc = j, 0, 0 + while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do + if back >= 2 and acc >= need then + break + end + s -= 1 + back += 1 + if back >= 2 then + acc += ru16(idx.main, s * 2) + end + end + self._cur = s +end + +-- Current position: (seconds, sample frame) +function Decoder.position(self: Decoder): (number, number) + return self._pos / self.sampleRate, self._pos +end + +-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames) +function Decoder.readAll(self: Decoder): (buffer, number) + return self:read(max(0, self.frames - self._pos)) +end + +Stream.Decoder = Decoder + +return Stream diff --git a/src/Formats/audio/mp3/Tables.luau b/src/Formats/audio/mp3/Tables.luau new file mode 100644 index 0000000..40d661d --- /dev/null +++ b/src/Formats/audio/mp3/Tables.luau @@ -0,0 +1,224 @@ +--!strict +-- audio/mp3/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py. +-- Every list is flattened row-major and 0-based (t[0] is the first element), like the C arrays. +local T = {} +T.halfrate = { [0] = 0, + 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, + 48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24, + 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, + 160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, +} +T.g_bitalloc_code_tab = { [0] = 0, + 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +T.g_scf_long = { [0] = 6, + 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12, + 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6, + 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6, + 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6, + 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4, + 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6, + 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6, + 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0, +} +T.g_scf_short = { [0] = 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, + 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, + 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, + 42, 42, 42, 12, 12, 12, 0, +} +T.g_scf_mixed = { [0] = 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, + 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, + 18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, + 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4, + 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, + 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, + 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, + 42, 42, 12, 12, 12, 0, 0, +} +T.g_expfrac = { [0] = 9.31322575e-10, + 7.83145814e-10, 6.58544508e-10, 5.53767716e-10, +} +T.g_scf_partitions = { [0] = 6, + 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8, + 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6, + 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12, + 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0, +} +T.g_scfc_decode = { [0] = 0, + 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19, +} +T.g_mod = { [0] = 5, + 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1, +} +T.g_preamp = { [0] = 1, + 1, 1, 1, 2, 2, 3, 3, 3, 2, +} +T.g_pow43 = { [0] = 0, + -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000, + 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667, + 105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292, + 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550, + 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615, + 495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578, +} +T.tabs = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290, + 288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528, + 528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769, + 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275, + 275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784, + 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291, + 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076, + 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289, + 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769, + 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, + 1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290, + 290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533, + 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041, + 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364, + 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045, + -719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307, + 320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785, + 785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351, + -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136, + 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534, + 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252, + -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375, + 374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865, + 774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259, + 259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726, + -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595, + -2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322, + 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495, + 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242, + 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984, + 909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953, + 938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696, + 651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436, + 436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375, + 359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412, + 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342, + 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152, + 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060, + 1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579, + -1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025, + 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103, + -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707, + 1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751, + 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475, + 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480, + 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475, + 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409, + 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051, + 1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081, + -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898, + 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368, + 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848, + 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828, + -2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103, + 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734, + -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686, + 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821, + -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252, + 1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223, + 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963, + 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844, + 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944, + 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696, + 1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320, + 1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392, + 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789, + 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088, + 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279, + 1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024, + 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623, + 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974, + 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071, + -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310, + 1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434, + 1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402, + 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083, + 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187, + 1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156, + 1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384, + 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849, + -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, + 290, 288, 258, +} +T.tab32 = { [0] = 130, + 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109, + 61, 173, 205, +} +T.tab33 = { [0] = 252, + 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12, +} +T.tabindex = { [0] = 0, + 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842, + 1842, 1842, 1842, 1842, 1842, 1842, 1842, +} +T.g_linbits = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, + 5, 6, 7, 8, 9, 11, 13, +} +T.g_pan = { [0] = 0, + 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0, +} +T.g_aa = { [0] = 0.85749293, + 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997, +} +T.g_twid9 = { [0] = 0.73727734, + 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938, +} +T.g_twid3 = { [0] = 0.79335334, + 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619, +} +T.g_mdct_window = { [0] = 0.99904822, + 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486, + 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143, +} +T.g_sec = { [0] = 10.19000816, + 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861, +} +T.g_win = { [0] = -1, + 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952, + 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1, + 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739, + 3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2, + 14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414, + 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2, + 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970, + 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4, + 7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402, + 545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290, +} +return T diff --git a/src/Formats/audio/mp3/Tags.luau b/src/Formats/audio/mp3/Tags.luau new file mode 100644 index 0000000..329c297 --- /dev/null +++ b/src/Formats/audio/mp3/Tags.luau @@ -0,0 +1,315 @@ +--!strict +--!optimize 2 +-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 / +-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way +-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short. +local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift +local ru8 = buffer.readu8 + +local Tags = {} + +-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions) +local GENRES = { + [0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", + "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", + "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", + "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", + "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", + "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", + "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", + "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", + "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", + "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", + "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", + "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", + "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", + "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", + "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", + "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock", + "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop", +} +Tags.GENRES = GENRES + +-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents) +local FIELDS = { + TIT2 = "title", TT2 = "title", + TPE1 = "artist", TP1 = "artist", + TALB = "album", TAL = "album", + TPE2 = "albumArtist", TP2 = "albumArtist", + TYER = "year", TYE = "year", TDRC = "year", + TRCK = "track", TRK = "track", + TPOS = "disc", TPA = "disc", + TCON = "genre", TCO = "genre", + TCOM = "composer", TCM = "composer", + COMM = "comment", COM = "comment", +} + +local function utf8char(cp: number): string + if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + cp = 0xFFFD + end + return utf8.char(cp) +end + +-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8) +local function decodeText(b: buffer, i: number, j: number, enc: number): string + local out = {} + if enc == 1 or enc == 2 then + local le = false + if enc == 1 and j - i >= 2 then + local b0, b1 = ru8(b, i), ru8(b, i + 1) + if b0 == 0xFF and b1 == 0xFE then + le = true + i += 2 + elseif b0 == 0xFE and b1 == 0xFF then + i += 2 + else + le = true -- no BOM: assume little-endian (what most taggers write) + end + end + local pending = 0 + while i + 1 < j do + local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1)) + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + pending = u + else + if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then + u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00) + end + pending = 0 + table.insert(out, if u == 0 then "\0" else utf8char(u)) + end + end + elseif enc == 3 then + local s = buffer.readstring(b, i, j - i) + if utf8.len(s) then + return s + end + enc = 0 -- invalid UTF-8: fall back to latin-1 + end + if enc == 0 then + for k = i, j - 1 do + local c = ru8(b, k) + table.insert(out, if c < 0x80 then string.char(c) else utf8char(c)) + end + end + return table.concat(out) +end + +-- trim trailing NULs / spaces, join multi-value NUL separators with " / " +local function clean(s: string): string + s = string.gsub(s, "[%z%s]+$", "") + s = string.gsub(s, "%z+", " / ") + return s +end + +-- "(17)", "(17)Rock", "17" -> "Rock" +local function genreName(s: string): string + local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$")) + if n and GENRES[n] then + return GENRES[n] + end + local rest = string.match(s, "^%(%d+%)(.+)$") + return rest or s +end + +local function syncsafe(b: buffer, o: number): number + return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F)) +end + +local function be32(b: buffer, o: number): number + return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3)) +end + +-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer +local function deunsync(b: buffer, i: number, j: number): buffer + local out = buffer.create(math.max(0, j - i)) + local n = 0 + local k = i + while k < j do + local c = ru8(b, k) + buffer.writeu8(out, n, c) + n += 1 + k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1 + end + local r = buffer.create(n) + buffer.copy(r, 0, out, 0, n) + return r +end + +-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0 +function Tags.id3v2Size(b: buffer, o: number, len: number): number + if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then + return 0 + end + if band(ru8(b, o + 5), 15) ~= 0 then + return 0 + end + for k = 6, 9 do + if band(ru8(b, o + k), 0x80) ~= 0 then + return 0 + end + end + local size = syncsafe(b, o + 6) + 10 + if band(ru8(b, o + 5), 16) ~= 0 then + size += 10 + end + return size +end + +local function setField(tags: any, id: string, text: string) + tags.raw[id] = text + local f = FIELDS[id] + if f and tags[f] == nil and text ~= "" then + tags[f] = if f == "genre" then genreName(text) else text + end +end + +-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags +local function parseV2(b: buffer, o: number, size: number, tags: any) + local ver = ru8(b, o + 3) + local flags = ru8(b, o + 5) + if ver < 2 or ver > 4 then + return + end + tags.id3v2 = "2." .. ver + local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b)) + local body = b + local p, e = o + 10, bodyEnd + if band(flags, 0x80) ~= 0 and ver < 4 then + body = deunsync(b, p, e) + p, e = 0, buffer.len(body) + end + if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then + -- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe) + p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p) + end + local hdr = if ver == 2 then 6 else 10 + while p + hdr <= e do + local c0 = ru8(body, p) + if c0 == 0 then + break -- padding + end + local id, fsize, fflags + if ver == 2 then + id = buffer.readstring(body, p, 3) + fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5)) + fflags = 0 + else + id = buffer.readstring(body, p, 4) + fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4) + fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9)) + end + if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then + break + end + local fs, fe = p + hdr, p + hdr + fsize + local fb = body + local skip = false + if ver == 3 then + skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted + elseif ver == 4 then + skip = band(fflags, 0x000C) ~= 0 + if not skip and band(fflags, 0x0001) ~= 0 then + fs += 4 -- data length indicator + end + if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then + fb = deunsync(body, fs, fe) + fs, fe = 0, buffer.len(fb) + end + end + if not skip and fs < fe then + local first = string.sub(id, 1, 1) + local enc = ru8(fb, fs) + if first == "T" and id ~= "TXXX" and id ~= "TXX" then + setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc))) + elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then + -- encoding, language[3], short description (NUL-terminated in the encoding), text + local q = fs + 4 + local wide = enc == 1 or enc == 2 + while q < fe do + if wide then + if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then + q += 2 + break + end + q += 2 + else + if ru8(fb, q) == 0 then + q += 1 + break + end + q += 1 + end + end + if q <= fe then + setField(tags, id, clean(decodeText(fb, q, fe, enc))) + end + end + end + p += hdr + fsize + end +end + +local function v1String(b: buffer, o: number, n: number): string + return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) +end + +-- Parses tags and returns (tags, audio start, audio end) for the buffer b. +-- tags = { title?, artist?, album?, albumArtist?, year?, track?, disc?, genre?, composer?, comment?, +-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } +function Tags.parse(b: buffer): (any, number, number) + local len = buffer.len(b) + local tags: any = { raw = {} } + local start, stop = 0, len + local v2 = Tags.id3v2Size(b, 0, len) + if v2 > 0 then + pcall(parseV2, b, 0, v2, tags) + start = math.min(v2, len) + end + -- mp3dec_skip_id3v1 on what follows the ID3v2 tag + local size = stop - start + if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then + local o = start + size - 128 + tags.id3v1 = true + local v1 = { + title = v1String(b, o + 3, 30), + artist = v1String(b, o + 33, 30), + album = v1String(b, o + 63, 30), + year = v1String(b, o + 93, 4), + } + if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then + v1.comment = v1String(b, o + 97, 28) + v1.track = tostring(ru8(b, o + 126)) + else + v1.comment = v1String(b, o + 97, 30) + end + local g = ru8(b, o + 127) + if GENRES[g] then + v1.genre = GENRES[g] + end + for k, v in v1 do + if tags[k] == nil and v ~= "" then + tags[k] = v + end + end + size -= 128 + if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then + size -= 227 + end + end + if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then + size -= 32 + local t = start + size + 12 + local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24)) + if size >= tagSize then + size -= tagSize + end + tags.ape = true + end + stop = start + size + return tags, start, stop +end + +return Tags diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau new file mode 100644 index 0000000..649970d --- /dev/null +++ b/src/Formats/audio/mp3/init.luau @@ -0,0 +1,130 @@ +--!strict +-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf +-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5 +-- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / +-- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync +-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). +-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Not supported: encoding (see the mp3 encoder in the +-- audio workstream), MPEG-2 multichannel extension, CRC checks. +-- +-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, +-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) +-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Header = require("@formats/audio/mp3/Header") +local Index = require("@formats/audio/mp3/Index") +local Tags = require("@formats/audio/mp3/Tags") +local Stream = require("@formats/audio/mp3/Stream") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp3 = { + name = "mp3", + category = "audio", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) +} +export type Decoder = Stream.Decoder + +-- ------------------------------------------------------------------------------------------------ constants +local MAX_FRAMES = 2 ^ 31 + +-- ------------------------------------------------------------------------------------------------ sniff +-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on +function Mp3.sniff(r: Bytes.Reader): number + local b, p, lim = r.buf, r.pos, r.limit + local id3 = false + for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other) + local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0 + if n <= 0 then + break + end + id3 = true + p += n + end + if p + 4 > lim or not Header.valid(b, p) then + return if id3 then 0.5 else 0 + end + local fb = Header.frameBytes(b, p, 0) + if fb > 0 then + fb += Header.padding(b, p) + if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then + return 0.9 + end + if p + fb == lim then + return 0.6 + end + end + return if id3 then 0.7 else 0.25 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts) -> Types.Audio (the whole stream, through open) +function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mp3.open(r, opts) + if not dec then + return nil, err + end + local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames) + local _, n = dec:read(dec.frames, a.samples) + if n < dec.frames then + return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", n, dec.frames)) + end + a.tags = dec.tags + a.meta.source = { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment) +local function stringTags(t: any): { [string]: string } + local out: { [string]: string } = {} + for k, v in t do + if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then + out[k] = v + end + end + return out +end + +-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err +function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + local b = r.buf + if r.base ~= 0 or r.limit ~= buffer.len(b) then + b = buffer.create(r.limit - r.base) -- the core indexes from offset 0 + buffer.copy(b, 0, r.buf, r.base, r.limit - r.base) + end + local okTags, tags, start, stop = pcall(Tags.parse, b) + if not okTags then + tags, start, stop = { raw = {} }, 0, buffer.len(b) + end + local idx = Index.build(b, start, stop) + if not idx then + return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found") + end + local dec = Stream.new(b, idx, stringTags(tags), { + raw = tags.raw, + id3v2 = tags.id3v2, + id3v1 = tags.id3v1 == true, + ape = tags.ape == true, + }) + if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then + return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end) + +return Mp3 diff --git a/src/Formats/audio/opus/Celt.luau b/src/Formats/audio/opus/Celt.luau new file mode 100644 index 0000000..7bdbc15 --- /dev/null +++ b/src/Formats/audio/opus/Celt.luau @@ -0,0 +1,1864 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, +-- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is +-- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC). +-- +-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch +-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. +local RD = require("@formats/audio/opus/RangeDecoder") +local Mdct = require("@formats/audio/opus/Mdct") +local T = require("@formats/audio/opus/CeltTables") + +local Celt = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos +local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint +local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update +local tell, tellFrac = RD.tell, RD.tellFrac + +local NB_EBANDS = 21 +local EFF_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local MAX_LM = 3 +local DECODE_BUFFER_SIZE = 2048 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local QTHETA_OFFSET_TWOPHASE = 16 +local SPREAD_AGGRESSIVE = 3 +local PREEMPH = 0.85000610 +local COMBFILTER_MINPERIOD = 15 +local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2 + +-- eBands (1-based: EB[i + 1] is eBands[i]) +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, 3.750000, 3.750000, 3.750000, 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { -- [LM][4 * isTransient + 2 * tf_select + flag] + { 0, -1, 0, -1, 0, -1, 0, -1 }, + { 0, -1, 0, -2, 1, 0, 1, -1 }, + { 0, -2, 0, -3, 2, 0, 1, -1 }, + { 0, -2, 0, -3, 3, 0, 1, -1 }, +} +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local TAPSET_ICDF = { 2, 1, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 } +local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 } +local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF } +local COMB_GAINS = { + { 0.3066406250, 0.2170410156, 0.1296386719 }, + { 0.4638671875, 0.2680664062, 0.0 }, + { 0.7998046875, 0.1000976562, 0.0 }, +} + +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +Celt.window = WINDOW + +-- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176 +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end + +-- shared workspace (decoding is not re-entrant) +local NORM_BASE = 1920 +local W = table.create(4096, 0) +local TMP = table.create(256, 0) +local IY = table.create(256, 0) +local FREQ = table.create(960, 0) +local FREQ2 = table.create(960, 0) +local COLLAPSE = table.create(42, 0) +local TF_RES = table.create(21, 0) +local CAP = table.create(21, 0) +local OFFSETS = table.create(21, 0) +local FINE_QUANT = table.create(21, 0) +local PULSES = table.create(21, 0) +local FINE_PRIORITY = table.create(21, 0) +local BITS1 = table.create(21, 0) +local BITS2 = table.create(21, 0) +local THRESH = table.create(21, 0) +local TRIM_OFFSET = table.create(21, 0) + +local function imin(a: number, b: number): number + return if a < b then a else b +end +local function imax(a: number, b: number): number + return if a > b then a else b +end +-- C integer division (truncates toward zero) +local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end + +local function exp2(x: number): number + return exp(0.6931471805599453094 * x) +end + +local function lcg(seed: number): number + return (1664525 * seed + 1013904223) % 4294967296 +end + +local function signed32(x: number): number + return if x >= 2147483648 then x - 4294967296 else x +end + +local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end + +local function bitexactCos(x: number): number + local tmp = (4096 + x * x) // 8192 + local x2 = tmp + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end + +local function bitexactLog2tan(isin: number, icos: number): number + local lc = RD.ilog(icos) + local ls = RD.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- --------------------------------------------------------------------------------------------------------------- +-- energy (quant_bands.c, laplace.c) + +local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number + local val = 0 + local fm = decDecodeBin(dec, 15) + local fl = 0 + if fm >= fs then + val += 1 + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 + 1 + while fs > 1 and fm >= fl + 2 * fs do + fs *= 2 + fl += fs + fs = ((fs - 2) * decay) // 32768 + fs += 1 + val += 1 + end + if fs <= 1 then + local di = rshift(fm - fl, 1) + val += di + fl += 2 * di + end + if fm < fl + fs then + val = -val + else + fl += fs + end + end + decUpdate(dec, fl, imin(fl + fs, 32768), 32768) + return val +end + +local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) + local oldE = st.oldBandE + local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based + local coef, beta + if intra then + coef = 0 + beta = BETA_INTRA + else + beta = BETA_COEF[LM + 1] + coef = PRED_COEF[LM + 1] + end + local prev0, prev1 = 0, 0 + local budget = dec.storage * 8 + for i = start, endb - 1 do + for c = 0, C - 1 do + local t = tell(dec) + local qi + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2) + qi = if band(qi, 1) ~= 0 then -rshift(qi, 1) - 1 else rshift(qi, 1) + elseif budget - t >= 1 then + qi = if decBitLogp(dec, 1) then -1 else 0 + else + qi = -1 + end + local q = qi + local k = i + c * NB_EBANDS + 1 + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + oldE[k] = coef * e + prev + q + prev = prev + q - beta * q + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for i = start, endb - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(dec) + C * extra > dec.storage * 8 then + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[i + c * NB_EBANDS + 1] += offset + end + end +end + +local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for prio = 0, 1 do + local i = start + while i < endb and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[i + c * NB_EBANDS + 1] += offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bit allocation (rate.c) + +local function bits2pulses(bandI: number, LM: number, bits: number): number + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +local function pulses2bits(bandI: number, LM: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, + total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = BITS1, BITS2, THRESH, TRIM_OFFSET + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local N = EB[j + 2] - EB[j + 1] + local bitsj = (C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local N = EB[j + 2] - EB[j + 1] + local bits1j = (C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + if decBitLogp(ec, 1) then + break + end + psum += 8 + bandBits -= 8 + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = start + decUint(ec, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = decBitLogp(ec, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local N = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if N > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * N + (if C == 2 and N > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if N == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- --------------------------------------------------------------------------------------------------------------- +-- PVQ (cwrs.c, vq.c) + +local function cwrsi(n: number, k: number, i: number, iy: { number }): number + local yy = 0 + local idx = 1 + local p, k0, val + while n > 2 do + if k >= n then + local rowBase = n * UK + 1 + p = U[rowBase + k + 1] + local neg = i >= p + if neg then + i -= p + end + k0 = k + local q = U[rowBase + n] + if q > i then + k = n + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + else + p = U[rowBase + k] + while p > i do + k -= 1 + p = U[rowBase + k] + end + end + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + else + p = U[k * UK + n + 1] + local q = U[(k + 1) * UK + n + 1] + if p <= i and i < q then + i -= p + iy[idx] = 0 + idx += 1 + else + local neg = i >= q + if neg then + i -= q + end + k0 = k + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + end + end + n -= 1 + end + -- n == 2 + p = 2 * k + 1 + local neg = i >= p + if neg then + i -= p + end + k0 = k + k = rshift(i + 1, 1) + if k ~= 0 then + i -= 2 * k - 1 + end + val = if neg then k - k0 else k0 - k + iy[idx] = val + yy += val * val + -- n == 1 + val = if i ~= 0 then -k else k + iy[idx + 1] = val + yy += val * val + return yy +end + +local function expRotation1(X: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = X + 1 + for _ = 0, len - stride - 1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p += 1 + end + p = X + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p -= 1 + end +end + +local SPREAD_FACTOR = { 15, 10, 5 } +local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = X + i * len + if dir < 0 then + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, c) + end + expRotation1(x, len, 1, c, s) + else + expRotation1(x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, -c) + end + end + end +end + +local function renormaliseVector(X: number, N: number, gain: number) + local E = 1e-15 + for i = X + 1, X + N do + local v = W[i] + E += v * v + end + local g = gain / sqrt(E) + for i = X + 1, X + N do + W[i] *= g + end +end + +local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number + local iy = IY + local ft = U[N * UK + K + 1] + U[N * UK + K + 2] + local Ryy = cwrsi(N, K, decUint(dec, ft), iy) + local g = gain / sqrt(Ryy) + for i = 1, N do + W[X + i] = iy[i] * g + end + expRotation(X, N, -1, B, K, spread) + if B <= 1 then + return 1 + end + local N0 = N // B + local mask = 0 + for i = 0, B - 1 do + for j = 1, N0 do + if iy[i * N0 + j] ~= 0 then + mask = bor(mask, lshift(1, i)) + break + end + end + end + return mask +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bands (bands.c) + +type Ctx = { + i: number, + intensity: number, + spread: number, + tf_change: number, + ec: RD.Dec, + remaining_bits: number, + seed: number, + disable_inv: boolean, + avoid_split_noise: boolean, +} +local ctx: Ctx = { + i = 0, + intensity = 0, + spread = 0, + tf_change = 0, + ec = (nil :: any), + remaining_bits = 0, + seed = 0, + disable_inv = false, + avoid_split_noise = false, +} + +local function haar1(X: number, N0: number, stride: number) + N0 = rshift(N0, 1) + local s = 0.70710678 + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + local a = X + stride * 2 * j + i + 1 + local b = a + stride + local t1 = s * W[a] + local t2 = s * W[b] + W[a] = t1 + t2 + W[b] = t1 - t2 + end + end +end + +local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[o + j + 1] = W[X + j * stride + i + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[i * N0 + j + 1] = W[X + j * stride + i + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + o + j + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + i * N0 + j + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number + local N2 = 2 * N - 1 + if stereo and N == 2 then + N2 -= 1 + end + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- returns b, fill, inv, imid, iside, delta, itheta, qalloc +local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) + local i = ctx.i + local ec = ctx.ec + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - (if stereo and N == 2 then QTHETA_OFFSET_TWOPHASE else QTHETA_OFFSET) + local qn = computeQn(N, b, offset, pulseCap, stereo) + if stereo and i >= ctx.intensity then + qn = 1 + end + local t0 = tellFrac(ec) + local itheta = 0 + local inv = false + if qn ~= 1 then + if stereo and N > 2 then + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + local fs = decDecode(ec, ft) + local x + if fs < (x0 + 1) * p0 then + x = fs // p0 + else + x = x0 + 1 + (fs - (x0 + 1) * p0) + end + if x <= x0 then + decUpdate(ec, p0 * x, p0 * (x + 1), ft) + else + decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft) + end + itheta = x + elseif B0 > 1 or stereo then + itheta = decUint(ec, qn + 1) + else + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fm = decDecode(ec, ft) + local fs, fl + if fm < rshift(h * (h + 1), 1) then + itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1) + fs = itheta + 1 + fl = rshift(itheta * (itheta + 1), 1) + else + itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1) + fs = qn + 1 - itheta + fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + end + decUpdate(ec, fl, fl + fs, ft) + end + itheta = (itheta * 16384) // qn + elseif stereo then + if b > 16 and ctx.remaining_bits > 16 then + inv = decBitLogp(ec, 2) + end + if ctx.disable_inv then + inv = false + end + itheta = 0 + end + local qalloc = tellFrac(ec) - t0 + b -= qalloc + local imid, iside, delta + if itheta == 0 then + imid = 32767 + iside = 0 + fill = band(fill, lshift(1, B) - 1) + delta = -16384 + elseif itheta == 16384 then + imid = 0 + iside = 32767 + fill = band(fill, lshift(lshift(1, B) - 1, B)) + delta = 16384 + else + imid = bitexactCos(itheta) + iside = bitexactCos(16384 - itheta) + delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid)) + end + return b, fill, inv, imid, iside, delta, itheta, qalloc +end + +local function quantBandN1(X: number, Y: number, lowbandOut: number): number + local x = X + local ec = ctx.ec + for _ = 0, (if Y >= 0 then 1 else 0) do + local sign = 0 + if ctx.remaining_bits >= 8 then + sign = decBits(ec, 1) + ctx.remaining_bits -= 8 + end + W[x + 1] = if sign ~= 0 then -1 else 1 + x = Y + end + if lowbandOut >= 0 then + W[lowbandOut + 1] = W[X + 1] + end + return 1 +end + +local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number + local i = ctx.i + local B0 = B + local cm = 0 + local split = false + if LM ~= -1 and N > 2 then + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + N = rshift(N, 1) + local Y = X + N + LM -= 1 + if B == 1 then + fill = bor(band(fill, 1), lshift(fill, 1)) + end + B = rshift(B + 1, 1) + local _inv, imid, iside, delta, itheta, qalloc + b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill) + local mid = imid / 32768 + local side = iside / 32768 + if B0 > 1 and band(itheta, 0x3fff) ~= 0 then + if itheta > 8192 then + delta -= delta // 2 ^ (4 - LM) + else + delta = imin(0, delta + (N * 8) // 2 ^ (5 - LM)) + end + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local nextLowband2 = if lowband >= 0 then lowband + N else -1 + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))) + else + cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)) + end + else + local q = bits2pulses(i, LM, b) + local currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + while ctx.remaining_bits < 0 and q > 0 do + ctx.remaining_bits += currBits + q -= 1 + currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + end + if q ~= 0 then + cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain) + else + local cmMask = lshift(1, B) - 1 + fill = band(fill, cmMask) + if fill == 0 then + for j = X + 1, X + N do + W[j] = 0 + end + else + local seed = ctx.seed + if lowband < 0 then + for j = X + 1, X + N do + seed = lcg(seed) + W[j] = signed32(seed) // 1048576 + end + cm = cmMask + else + for j = 0, N - 1 do + seed = lcg(seed) + local tmp = if band(seed, 0x8000) ~= 0 then 1 / 256 else -1 / 256 + W[X + j + 1] = W[lowband + j + 1] + tmp + end + cm = fill + end + ctx.seed = seed + renormaliseVector(X, N, gain) + end + end + end + return cm +end + +local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, + gain: number, lowbandScratch: number, fill: number): number + local N0 = N + local NB = N + local B0 = B + local timeDivide = 0 + local recombine = 0 + local longBlocks = B0 == 1 + local tfChange = ctx.tf_change + NB = NB // B + if N == 1 then + return quantBandN1(X, -1, lowbandOut) + end + if tfChange > 0 then + recombine = tfChange + end + if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then + for j = 1, N do + W[lowbandScratch + j] = W[lowband + j] + end + lowband = lowbandScratch + end + for k = 0, recombine - 1 do + if lowband >= 0 then + haar1(lowband, rshift(N, k), lshift(1, k)) + end + fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2)) + end + B = rshift(B, recombine) + NB = lshift(NB, recombine) + while band(NB, 1) == 0 and tfChange < 0 do + if lowband >= 0 then + haar1(lowband, NB, B) + end + fill = bor(fill, lshift(fill, B)) + B = lshift(B, 1) + NB = rshift(NB, 1) + timeDivide += 1 + tfChange += 1 + end + B0 = B + local NB0 = NB + if B0 > 1 and lowband >= 0 then + deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill) + if B0 > 1 then + interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + NB = NB0 + B = B0 + for _ = 0, timeDivide - 1 do + B = rshift(B, 1) + NB = lshift(NB, 1) + cm = bor(cm, rshift(cm, B)) + haar1(X, NB, B) + end + for k = 0, recombine - 1 do + cm = BIT_DEINTERLEAVE[cm + 1] + haar1(X, rshift(N0, k), lshift(1, k)) + end + B = lshift(B, recombine) + if lowbandOut >= 0 then + local n = sqrt(N0) + for j = 1, N0 do + W[lowbandOut + j] = n * W[X + j] + end + end + return band(cm, lshift(1, B) - 1) +end + +local function stereoMerge(X: number, Y: number, mid: number, N: number) + local xp, side = 0, 0 + for j = 1, N do + local y = W[Y + j] + xp += y * W[X + j] + side += y * y + end + xp = mid * xp + local mm = mid * mid + local El = mm + side - 2 * xp + local Er = mm + side + 2 * xp + if Er < 6e-4 or El < 6e-4 then + for j = 1, N do + W[Y + j] = W[X + j] + end + return + end + local lgain = 1 / sqrt(El) + local rgain = 1 / sqrt(Er) + for j = 1, N do + local l = mid * W[X + j] + local r = W[Y + j] + W[X + j] = lgain * (l - r) + W[Y + j] = rgain * (l + r) + end +end + +local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, + lowbandOut: number, lowbandScratch: number, fill: number): number + if N == 1 then + return quantBandN1(X, Y, lowbandOut) + end + local origFill = fill + local inv, imid, iside, delta, itheta, qalloc + b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill) + local mid = imid / 32768 + local side = iside / 32768 + local cm + if N == 2 then + local mbits = b + local sbits = 0 + if itheta ~= 0 and itheta ~= 16384 then + sbits = 8 + end + mbits -= sbits + local c = itheta > 8192 + ctx.remaining_bits -= qalloc + sbits + local x2, y2 = X, Y + if c then + x2, y2 = Y, X + end + local sign = 0 + if sbits ~= 0 then + sign = decBits(ctx.ec, 1) + end + sign = 1 - 2 * sign + cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill) + W[y2 + 1] = -sign * W[x2 + 2] + W[y2 + 2] = sign * W[x2 + 1] + local x0, x1 = mid * W[X + 1], mid * W[X + 2] + local y0, y1 = side * W[Y + 1], side * W[Y + 2] + W[X + 1] = x0 - y0 + W[Y + 1] = x0 + y0 + W[X + 2] = x1 - y1 + W[Y + 2] = x1 + y1 + else + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))) + else + cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)) + end + end + if N ~= 2 then + stereoMerge(X, Y, mid, N) + end + if inv then + for j = Y + 1, Y + N do + W[j] = -W[j] + end + end + return cm +end + +local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, + pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number, + tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number, + seed: number, disableInv: boolean): number + local M = lshift(1, LM) + local B = if shortBlocks then M else 1 + local normOffset = M * EB[start + 1] + local C = if hasY then 2 else 1 + local norm = NORM_BASE + local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset + local lowbandScratch = M * EB[EFF_EBANDS] + local lowbandOffset = 0 + local updateLowband = true + ctx.ec = ec + ctx.intensity = intensity + ctx.seed = seed + ctx.spread = spread + ctx.disable_inv = disableInv + ctx.avoid_split_noise = B > 1 + for i = start, endb - 1 do + ctx.i = i + local last = i == endb - 1 + local X = M * EB[i + 1] + local Y = if hasY then N + M * EB[i + 1] else -1 + local Nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(ec) + if i ~= start then + balance -= t + end + local remainingBits = totalBits - t - 1 + ctx.remaining_bits = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then + lowbandOffset = i + end + if i == start + 1 then + local n1 = M * (EB[start + 2] - EB[start + 1]) + local n2 = M * (EB[start + 3] - EB[start + 2]) + for k = 0, n2 - n1 - 1 do + W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1] + end + if dualStereo then + for k = 0, n2 - n1 - 1 do + W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1] + end + end + end + local tfChange = tfRes[i + 1] + ctx.tf_change = tfChange + if last then + lowbandScratch = -1 + end + local effectiveLowband = -1 + local xcm, ycm + if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then + effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb) + local foldStart = lowbandOffset + repeat + foldStart -= 1 + until M * EB[foldStart + 1] <= effectiveLowband + normOffset + local foldEnd = lowbandOffset - 1 + repeat + foldEnd += 1 + until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb) + xcm, ycm = 0, 0 + local fi = foldStart + repeat + xcm = bor(xcm, collapse[fi * C + 1]) + ycm = bor(ycm, collapse[fi * C + C]) + fi += 1 + until fi >= foldEnd + else + xcm = lshift(1, B) - 1 + ycm = xcm + end + if dualStereo and i == intensity then + dualStereo = false + for j = 1, M * EB[i + 1] - normOffset do + W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j]) + end + end + if dualStereo then + xcm = quantBand(X, Nb, b // 2, B, if effectiveLowband ~= -1 then norm + effectiveLowband else -1, LM, + if last then -1 else norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) + ycm = quantBand(Y, Nb, b // 2, B, if effectiveLowband ~= -1 then norm2 + effectiveLowband else -1, LM, + if last then -1 else norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) + else + local lb = if effectiveLowband ~= -1 then norm + effectiveLowband else -1 + local lo = if last then -1 else norm + M * EB[i + 1] - normOffset + if hasY then + xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm)) + else + xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm)) + end + ycm = xcm + end + collapse[i * C + 1] = band(xcm, 255) + collapse[i * C + C] = band(ycm, 255) + balance += pulses[i + 1] + t + updateLowband = b > Nb * 8 + ctx.avoid_split_noise = false + end + return ctx.seed +end + +local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, + collapse: { number }, pulses: { number }, seed: number) + local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 + for i = start, endb - 1 do + local N0 = EB[i + 2] - EB[i + 1] + local depth = rshift((1 + pulses[i + 1]) // N0, LM) + local thresh = 0.5 * exp2(-0.125 * depth) + local sqrt1 = 1 / sqrt(N0 * 2 ^ LM) + for c = 0, C - 1 do + local k0 = c * NB_EBANDS + i + 1 + local prev1 = prev1logE[k0] + local prev2 = prev2logE[k0] + if C == 1 then + prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1]) + prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1]) + end + local Ediff = max(0, logE[k0] - min(prev1, prev2)) + local r = 2 * exp2(-Ediff) + if LM == 3 then + r *= 1.41421356 + end + r = min(thresh, r) * sqrt1 + local X = c * size + EB[i + 1] * 2 ^ LM + local renorm = false + local cmask = collapse[i * C + c + 1] + for k = 0, 2 ^ LM - 1 do + if band(cmask, lshift(1, k)) == 0 then + for j = 0, N0 - 1 do + seed = lcg(seed) + W[X + j * 2 ^ LM + k + 1] = if band(seed, 0x8000) ~= 0 then r else -r + end + renorm = true + end + end + if renorm then + renormaliseVector(X, N0 * 2 ^ LM, 1) + end + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- synthesis + +local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) + local N = M * SHORT_MDCT + local bound = M * EB[endb + 1] + if silence then + bound = 0 + start = 0 + endb = 0 + end + local f = 1 + local x = X + M * EB[start + 1] + if start ~= 0 then + for _ = 1, M * EB[start + 1] do + freq[f] = 0 + f += 1 + end + end + for i = start, endb - 1 do + local bandEnd = M * EB[i + 2] + local lg = logE[eoff + i + 1] + E_MEANS[i + 1] + local g = exp2(min(32, lg)) + for _ = M * EB[i + 1], bandEnd - 1 do + freq[f] = W[x + 1] * g + f += 1 + x += 1 + end + end + for k = bound + 1, N do + freq[k] = 0 + end +end + +local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) + local M = lshift(1, LM) + local B, NB, shift + if isTransient then + B = M + NB = SHORT_MDCT + shift = MAX_LM + else + B = 1 + NB = SHORT_MDCT * M + shift = MAX_LM - LM + end + local outBase = DECODE_BUFFER_SIZE - N + 1 + local oldE = st.oldBandE + local freq = FREQ + if CC == 2 and C == 1 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + for c = 1, 2 do + local mem = st.mem[c] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + elseif CC == 1 and C == 2 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence) + local f2 = FREQ2 + for k = 1, N do + freq[k] = 0.5 * freq[k] + 0.5 * f2[k] + end + local mem = st.mem[1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + else + for c = 0, CC - 1 do + denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence) + local mem = st.mem[c + 1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + end +end + +-- comb_filter, in place on mem (1-based base index of sample 0) +local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, + tapset0: number, tapset1: number, overlap: number) + if g0 == 0 and g1 == 0 then + return + end + T0 = imax(T0, COMBFILTER_MINPERIOD) + T1 = imax(T1, COMBFILTER_MINPERIOD) + local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1] + local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3] + local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3] + local x1 = mem[base - T1 + 1] + local x2 = mem[base - T1] + local x3 = mem[base - T1 - 1] + local x4 = mem[base - T1 - 2] + if g0 == g1 and T0 == T1 and tapset0 == tapset1 then + overlap = 0 + end + local i = 0 + while i < overlap do + local p = base + i + local x0 = mem[p - T1 + 2] + local w = WINDOW[i + 1] + local f = w * w + local of = 1 - f + mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1]) + + (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3) + + (f * g12) * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + i += 1 + end + if g1 == 0 then + return + end + -- constant part (comb_filter_const) + local p = base + i + x4 = mem[p - T1 - 2] + x3 = mem[p - T1 - 1] + x2 = mem[p - T1] + x1 = mem[p - T1 + 1] + for q = p, base + N - 1 do + local x0 = mem[q - T1 + 2] + mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + end +end + +local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) + local coef0 = PREEMPH + local xbase = DECODE_BUFFER_SIZE - N + for c = 0, CC - 1 do + local x = st.mem[c + 1] + local m = st.preemph[c + 1] + local y = pbase + c + if accum then + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] += tmp * (1 / 32768) + y += CC + end + else + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] = tmp * (1 / 32768) + y += CC + end + end + st.preemph[c + 1] = m + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- decoder state + +local function resetState(st: any) + st.rng = 0 + st.error = 0 + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NONE + st.skip_plc = true + st.postfilter_period = 0 + st.postfilter_period_old = 0 + st.postfilter_gain = 0 + st.postfilter_gain_old = 0 + st.postfilter_tapset = 0 + st.postfilter_tapset_old = 0 + st.preemph[1] = 0 + st.preemph[2] = 0 + for c = 1, st.channels do + local m = st.mem[c] + for k = 1, DECODE_BUFFER_SIZE + OVERLAP do + m[k] = 0 + end + end + for k = 1, 2 * NB_EBANDS do + st.oldBandE[k] = 0 + st.oldLogE[k] = -28 + st.oldLogE2[k] = -28 + st.backgroundLogE[k] = 0 + end +end + +-- celt_decoder_init(48000, channels) +function Celt.new(channels: number): any + local st = { + channels = channels, + stream_channels = channels, + start = 0, + ["end"] = EFF_EBANDS, + disable_inv = channels == 1, + mem = {}, + preemph = { 0, 0 }, + oldBandE = table.create(2 * NB_EBANDS, 0), + oldLogE = table.create(2 * NB_EBANDS, -28), + oldLogE2 = table.create(2 * NB_EBANDS, -28), + backgroundLogE = table.create(2 * NB_EBANDS, 0), + } + for c = 1, channels do + st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0) + end + resetState(st) + return st +end + +Celt.reset = resetState + +-- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) +local function decodeLost(st: any, N: number, LM: number) + local C = st.channels + local start = st.start + local endb = st["end"] + local effEnd = imax(start, imin(endb, EFF_EBANDS)) + for c = 1, C do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + local decay = 2 ^ LM * 0.0625 + if st.last_frame_type ~= FRAME_PLC_NOISE then + decay += max(1, imin(160, st.loss_duration) * 0.0625) + end + local oldE, bg = st.oldBandE, st.backgroundLogE + for c = 0, C - 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + oldE[k] = max(bg[k], oldE[k] - decay) + end + end + local seed = st.rng + for c = 0, C - 1 do + for i = start, effEnd - 1 do + local boffs = N * c + EB[i + 1] * 2 ^ LM + local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + for j = 1, blen do + seed = lcg(seed) + W[boffs + j] = signed32(seed) // 1048576 + end + renormaliseVector(boffs, blen, 1) + end + end + st.rng = seed + celtSynthesis(st, C, C, start, effEnd, false, LM, false, N) + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, C do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT, + st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.skip_plc = true + st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM) + st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM) + st.last_frame_type = FRAME_PLC_NOISE +end + +-- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over +-- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, + dec: RD.Dec?, accum: boolean): number + local CC = st.channels + local C = st.stream_channels + local start = st.start + local endb = st["end"] + local LM = 0 + while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do + LM += 1 + end + if LM > MAX_LM then + return -1 + end + local M = lshift(1, LM) + if len < 0 or len > 1275 then + return -1 + end + local N = M * SHORT_MDCT + local effEnd = imin(endb, EFF_EBANDS) + if buf == nil or len <= 1 then + decodeLost(st, N, LM) + deemphasis(st, CC, N, pcm, pbase, accum) + return frameSize + end + if st.loss_duration == 0 then + st.skip_plc = false + end + if dec == nil then + dec = RD.new(buf :: buffer, off, len) + end + local ec = dec :: RD.Dec + local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i]) + end + end + local totalBits = len * 8 + local t = tell(ec) + local silence + if t >= totalBits then + silence = true + elseif t == 1 then + silence = decBitLogp(ec, 15) + else + silence = false + end + if silence then + t = len * 8 + ec.nbits_total += t - tell(ec) + end + local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0 + if start == 0 and t + 16 <= totalBits then + if decBitLogp(ec, 1) then + local octave = decUint(ec, 6) + postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1 + local qg = decBits(ec, 3) + if tell(ec) + 2 <= totalBits then + postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2) + end + postfilterGain = 0.09375 * (qg + 1) + end + t = tell(ec) + end + local isTransient = false + if LM > 0 and t + 3 <= totalBits then + isTransient = decBitLogp(ec, 3) + t = tell(ec) + end + local shortBlocks = isTransient + local intraEner = if t + 3 <= totalBits then decBitLogp(ec, 3) else false + if not intraEner and st.loss_duration ~= 0 then + local missing = imin(10, rshift(st.loss_duration, LM)) + local safety = if LM == 0 then 1.5 elseif LM == 1 then 0.5 else 0 + for c = 0, 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then + local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k] + local slope = max(E1 - E0, 0.5 * (E2 - E0)) + slope = min(slope, 2) + E0 -= max(0, (1 + missing) * slope) + oldBandE[k] = max(-20, E0) + else + oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k]) + end + oldBandE[k] -= safety + end + end + end + unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM) + + -- tf_decode + local tfRes = TF_RES + do + local budget = ec.storage * 8 + local tt = tell(ec) + local logp = if isTransient then 2 else 4 + local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget + if tfSelectRsv then + budget -= 1 + end + local tfChanged, curr = 0, 0 + for i = start, endb - 1 do + if tt + logp <= budget then + if decBitLogp(ec, logp) then + curr = bit32.bxor(curr, 1) + end + tt = tell(ec) + tfChanged = bor(tfChanged, curr) + end + tfRes[i + 1] = curr + logp = if isTransient then 4 else 5 + end + local tfSelect = 0 + local row = TF_SELECT[LM + 1] + local ti = if isTransient then 4 else 0 + if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then + tfSelect = if decBitLogp(ec, 1) then 1 else 0 + end + for i = start, endb - 1 do + tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1] + end + end + + t = tell(ec) + local spread = 2 + if t + 4 <= totalBits then + spread = decIcdf(ec, SPREAD_ICDF, 1, 5) + end + local cap = CAP + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = OFFSETS + local dynallocLogp = 6 + totalBits *= 8 + t = tellFrac(ec) + for i = start, endb - 1 do + local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM + local quanta = imin(width * 8, imax(48, width)) + local loopLogp = dynallocLogp + local boost = 0 + while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do + local flag = decBitLogp(ec, loopLogp) + t = tellFrac(ec) + if not flag then + break + end + boost += quanta + totalBits -= quanta + loopLogp = 1 + end + offsets[i + 1] = boost + if boost > 0 then + dynallocLogp = imax(2, dynallocLogp - 1) + end + end + local allocTrim = if t + 48 <= totalBits then decIcdf(ec, TRIM_ICDF, 1, 7) else 5 + local bits = len * 64 - tellFrac(ec) - 1 + local antiCollapseRsv = if isTransient and LM >= 2 and bits >= (LM + 2) * 8 then 8 else 0 + bits -= antiCollapseRsv + local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY + local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits, + pulses, fineQuant, finePriority, C, LM, ec) + unquantFineEnergy(st, start, endb, fineQuant, ec, C) + + -- shift the decoder memory by one frame + for c = 1, CC do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + + local collapse = COLLAPSE + st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, + len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv) + + local antiCollapseOn = false + if antiCollapseRsv > 0 then + antiCollapseOn = decBits(ec, 1) ~= 0 + end + unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C) + if antiCollapseOn then + antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng) + end + if silence then + for i = 1, C * NB_EBANDS do + oldBandE[i] = -28 + end + end + + celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) + + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, CC do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT, + st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.postfilter_period = postfilterPitch + st.postfilter_gain = postfilterGain + st.postfilter_tapset = postfilterTapset + if LM ~= 0 then + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + end + + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[NB_EBANDS + i] = oldBandE[i] + end + end + if not isTransient then + for i = 1, 2 * NB_EBANDS do + oldLogE2[i] = oldLogE[i] + oldLogE[i] = oldBandE[i] + end + else + for i = 1, 2 * NB_EBANDS do + oldLogE[i] = min(oldLogE[i], oldBandE[i]) + end + end + local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001 + for i = 1, 2 * NB_EBANDS do + bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i]) + end + for c = 0, 1 do + for i = 0, start - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + for i = endb, NB_EBANDS - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + end + st.rng = ec.rng + deemphasis(st, CC, N, pcm, pbase, accum) + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NORMAL + if tell(ec) > 8 * len then + return -3 + end + if ec.error ~= 0 then + st.error = 1 + end + return frameSize +end + +return Celt diff --git a/src/Formats/audio/opus/CeltTables.luau b/src/Formats/audio/opus/CeltTables.luau new file mode 100644 index 0000000..5dd247f --- /dev/null +++ b/src/Formats/audio/opus/CeltTables.luau @@ -0,0 +1,58 @@ +--!strict +-- audio/opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. +return { +logN400 = { + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, +}, +cache_index50 = { + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, + 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, + 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, + 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, + 343, 343, 343, 351, 351, 370, 376, 382, 387, +}, +cache_bits50 = { + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, + 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, + 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, + 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, + 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, + 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, + 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, + 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, + 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, + 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, + 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, + 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, + 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, + 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, + 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, + 122, 175, 224, 4, 67, 127, 182, 234, +}, +cache_caps50 = { + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, + 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, + 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, + 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, + 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, + 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, + 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +}, +e_prob_model = { + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, + 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135, + 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, + 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, + 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, + 189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, + 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, + 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86, + 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, + 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, + 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, + 184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, + 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, +}, +} diff --git a/src/Formats/audio/opus/Decoder.luau b/src/Formats/audio/opus/Decoder.luau new file mode 100644 index 0000000..88e1b22 --- /dev/null +++ b/src/Formats/audio/opus/Decoder.luau @@ -0,0 +1,466 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching +-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the +-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. +local RD = require("@formats/audio/opus/RangeDecoder") +local Packet = require("@formats/audio/opus/Packet") +local Celt = require("@formats/audio/opus/Celt") +local Silk = require("@formats/audio/opus/Silk") + +local Decoder = {} + +local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY +local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB +local F20, F10, F5, F2_5 = 960, 480, 240, 120 +local min, max = math.min, math.max +local readu8 = buffer.readu8 + +local WINDOW = Celt.window +local TRANS = table.create(F5 * 2, 0) +local REDUND = table.create(F5 * 2, 0) +local SILKTMP = table.create(F10 * 2, 0) +local SILENCE = buffer.create(2) +buffer.writeu8(SILENCE, 0, 0xFF) +buffer.writeu8(SILENCE, 1, 0xFF) +local EMPTY_EC = RD.new(buffer.create(0), 0, 0) +local OFFS = table.create(48, 0) +local SIZES = table.create(48, 0) + +export type State = { + channels: number, + celt: any, + silk: any, + ctrl: any, + stream_channels: number, + frame_size: number, + mode: number, + bandwidth: number, + prev_mode: number, + prev_redundancy: boolean, + last_packet_duration: number, + rangeFinal: number, +} + +function Decoder.new(channels: number): State + return { + channels = channels, + celt = Celt.new(channels), + silk = Silk.new(channels), + ctrl = { + nChannelsAPI = channels, + nChannelsInternal = channels, + API_sampleRate = 48000, + internalSampleRate = 16000, + payloadSize_ms = 20, + }, + stream_channels = channels, + frame_size = 120, + mode = 0, + bandwidth = 0, + prev_mode = 0, + prev_redundancy = false, + last_packet_duration = 0, + rangeFinal = 0, + } +end + +function Decoder.reset(st: State) + Celt.reset(st.celt) + Silk.reset(st.silk) + st.stream_channels = st.channels + st.frame_size = 120 + st.mode = 0 + st.bandwidth = 0 + st.prev_mode = 0 + st.prev_redundancy = false + st.last_packet_duration = 0 + st.rangeFinal = 0 +end + +-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel +local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) + for c = 0, ch - 1 do + for i = 0, overlap - 1 do + local w = WINDOW[i + 1] + w *= w + local k = i * ch + c + out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] + end + end +end + +local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local ch = st.channels + local celt = st.celt + if frameSize < F2_5 then + return -2 + end + frameSize = min(frameSize, 2880) + local data = buf + if len <= 1 then + data = nil + frameSize = min(frameSize, st.frame_size) + end + local audiosize, mode, bandwidth + local dec = EMPTY_EC + if data then + audiosize = st.frame_size + mode = st.mode + bandwidth = st.bandwidth + dec = RD.new(data, off, len) + else + audiosize = frameSize + mode = if st.prev_redundancy then MODE_CELT else st.prev_mode + bandwidth = 0 + if mode == 0 then + for i = 0, audiosize * ch - 1 do + pcm[pbase + i] = 0 + end + return audiosize + end + if audiosize > F20 then + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20)) + if ret < 0 then + return ret + end + pbase += ret * ch + audiosize -= ret + until audiosize <= 0 + return frameSize + elseif audiosize < F20 then + if audiosize > F10 then + audiosize = F10 + elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then + audiosize = F5 + end + end + end + local celtAccum = mode ~= MODE_CELT + local transition = false + if data and st.prev_mode > 0 + and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy) + or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then + transition = true + end + if transition and mode == MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if audiosize > frameSize then + return -1 + end + frameSize = audiosize + + -- SILK + if mode ~= MODE_CELT then + local tooSmall = frameSize < F10 + local sarr, sbase = pcm, pbase + if tooSmall then + sarr, sbase = SILKTMP, 1 + end + if st.prev_mode == MODE_CELT then + Silk.reset(st.silk) + end + local ctrl = st.ctrl + ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000) + if data then + ctrl.nChannelsInternal = st.stream_channels + if mode == MODE_SILK then + ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000 + else + ctrl.internalSampleRate = 16000 + end + end + local lost = if data == nil then 1 else 0 + local decoded = 0 + repeat + local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch) + if ret ~= 0 or n <= 0 then + if lost ~= 0 or n <= 0 then + n = frameSize - decoded + for i = 0, n * ch - 1 do + sarr[sbase + decoded * ch + i] = 0 + end + else + return -3 + end + end + decoded += n + until decoded >= frameSize + if tooSmall then + for i = 0, frameSize * ch - 1 do + pcm[pbase + i] = SILKTMP[i + 1] + end + end + end + + local startBand = 0 + local redundancy, celtToSilk = false, false + local redundancyBytes = 0 + if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then + if mode == MODE_HYBRID then + redundancy = RD.bitLogp(dec, 12) + else + redundancy = true + end + if redundancy then + celtToSilk = RD.bitLogp(dec, 1) + redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3) + len -= redundancyBytes + if len * 8 < RD.tell(dec) then + len = 0 + redundancyBytes = 0 + redundancy = false + end + dec.storage -= redundancyBytes + end + end + if mode ~= MODE_CELT then + startBand = 17 + end + if redundancy then + transition = false + end + if transition and mode ~= MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if bandwidth ~= 0 then + celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21 + end + celt.stream_channels = st.stream_channels + local redundantRng = 0 + if redundancy and celtToSilk then + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + end + celt.start = startBand + local celtRet = 0 + if mode ~= MODE_SILK then + local celtFrameSize = min(F20, frameSize) + if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then + Celt.reset(celt) + end + celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum) + st.rangeFinal = celt.rng + else + if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then + celt.start = 0 + Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum) + end + st.rangeFinal = if data then dec.rng else 0 + end + if redundancy and not celtToSilk then + Celt.reset(celt) + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + local b = pbase + ch * (frameSize - F2_5) + smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch) + end + if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then + for i = 0, F2_5 * ch - 1 do + pcm[pbase + i] = REDUND[1 + i] + end + smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + end + if transition then + if audiosize >= F5 then + for i = 0, ch * F2_5 - 1 do + pcm[pbase + i] = TRANS[1 + i] + end + smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + else + smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch) + end + end + if len <= 1 then + st.rangeFinal = 0 + else + st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng) + end + st.prev_mode = mode + st.prev_redundancy = redundancy and not celtToSilk + if celtRet < 0 then + return celtRet + end + return audiosize +end + +-- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. +-- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) + local ch = st.channels + if buf == nil or len == 0 then + if frameSize % 120 ~= 0 then + return -1, 0 + end + local count = 0 + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count) + if ret <= 0 then + return if ret < 0 then ret else -3, 0 + end + count += ret + until count >= frameSize + st.last_packet_duration = count + return count, 0 + end + local b = buf :: buffer + local toc = readu8(b, off) + local packetMode = Packet.mode(toc) + local packetBandwidth = Packet.bandwidth(toc) + local packetFrameSize = Packet.samplesPerFrame(toc, 48000) + local packetChannels = Packet.channels(toc) + local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited) + if count < 0 then + return -4, 0 + end + if count * packetFrameSize > frameSize then + return -2, 0 + end + st.mode = packetMode + st.bandwidth = packetBandwidth + st.frame_size = packetFrameSize + st.stream_channels = packetChannels + local nb = 0 + for i = 1, count do + local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb) + if ret < 0 then + return ret, 0 + end + nb += ret + end + st.last_packet_duration = nb + return nb, packetOffset +end + +-- --------------------------------------------------------------------------------------------------------------- +-- multistream (channel mapping families 0 / 1 / 255) + +export type MS = { + channels: number, + streams: number, + coupled: number, + mapping: { number }, + decoders: { State }, + tmp: { number }, +} + +function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS + local decs = {} + for s = 0, streams - 1 do + decs[s + 1] = Decoder.new(if s < coupled then 2 else 1) + end + return { + channels = channels, + streams = streams, + coupled = coupled, + mapping = mapping, + decoders = decs, + tmp = table.create(5760 * 2, 0), + } +end + +function Decoder.resetMultistream(ms: MS) + for _, d in ms.decoders do + Decoder.reset(d) + end +end + +-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` +local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == id then + local o = pbase + c + local s = 1 + sc + for _ = 1, n do + pcm[o] = src[s] + o += nch + s += sstride + end + end + end +end + +-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local doPlc = buf == nil or len == 0 + frameSize = min(frameSize, 5760) + if not doPlc and len < 2 * ms.streams - 1 then + return -4 + end + local tmp = ms.tmp + for s = 0, ms.streams - 1 do + local d = ms.decoders[s + 1] + if not doPlc and len <= 0 then + return -3 + end + local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1) + if not doPlc then + off += packetOffset + len -= packetOffset + end + if ret <= 0 then + return if ret < 0 then ret else -3 + end + frameSize = ret + if s < ms.coupled then + copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize) + copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize) + else + copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize) + end + end + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == 255 then + local o = pbase + c + for _ = 1, frameSize do + pcm[o] = 0 + o += nch + end + end + end + return frameSize +end + +-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o +function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + if gain == 1 then + for i = base + 1, base + count do + writef32(out, o, src[i]) + o += 4 + end + else + for i = base + 1, base + count do + writef32(out, o, src[i] * gain) + o += 4 + end + end +end + +-- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the +-- left / right weights of channel c. Writes f32 to out from byte offset o. +function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + local p = base + for _ = 1, n do + local l, r = 0, 0 + for c = 0, srcCh - 1 do + local v = src[p + c + 1] + l += v * matrix[c * 2 + 1] + r += v * matrix[c * 2 + 2] + end + writef32(out, o, l * gain) + writef32(out, o + 4, r * gain) + o += 8 + p += srcCh + end +end + +return Decoder diff --git a/src/Formats/audio/opus/Mdct.luau b/src/Formats/audio/opus/Mdct.luau new file mode 100644 index 0000000..43557fe --- /dev/null +++ b/src/Formats/audio/opus/Mdct.luau @@ -0,0 +1,342 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the +-- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for +-- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. +local Mdct = {} + +local sin, cos, pi = math.sin, math.cos, math.pi + +type Plan = { + n: number, -- FFT size (N / 4) + factors: { number }, + bitrev: { number }, + twr: { number }, + twi: { number }, + trig: { number }, -- MDCT twiddles: (-sin, cos) pairs, N / 2 values + fr: { number }, + fi: { number }, +} + +local FACTORS = { + [0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 }, + [1] = { 5, 48, 3, 16, 4, 4, 4, 1 }, + [2] = { 5, 24, 3, 8, 2, 4, 4, 1 }, + [3] = { 5, 12, 3, 4, 4, 1 }, +} + +local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) + local p = factors[fi] + local m = factors[fi + 1] + if m == 1 then + for j = 0, p - 1 do + f[fpos + 1] = fout + j + fpos += fstride + end + else + for j = 0, p - 1 do + bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) + fpos += fstride + fout += m + end + end +end + +local plans: { Plan } = {} +for shift = 0, 3 do + local N = 1920 // 2 ^ shift + local n = N // 4 + local factors = FACTORS[shift] + local bitrev = table.create(n, 0) + bitrevTable(bitrev, 0, 0, 1, factors, 1) + local twr, twi = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + local ph = -2 * pi * k / n + twr[k + 1] = cos(ph) + twi[k + 1] = sin(ph) + end + local N2, N4 = N // 2, N // 4 + local trig = table.create(N2, 0) + for i = 0, N4 - 1 do + trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N) + trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N) + end + plans[shift + 1] = { + n = n, + factors = factors, + bitrev = bitrev, + twr = twr, + twi = twi, + trig = trig, + fr = table.create(n, 0), + fi = table.create(n, 0), + } +end + +local function bfly2(fr: { number }, fi: { number }, N: number) + local tw = 0.7071067812 + local p = 1 + for _ = 1, N do + -- k = 0 + local tr, ti = fr[p + 4], fi[p + 4] + fr[p + 4] = fr[p] - tr + fi[p + 4] = fi[p] - ti + fr[p] += tr + fi[p] += ti + -- k = 1 + local a, b = fr[p + 5], fi[p + 5] + tr = (a + b) * tw + ti = (b - a) * tw + fr[p + 5] = fr[p + 1] - tr + fi[p + 5] = fi[p + 1] - ti + fr[p + 1] += tr + fi[p + 1] += ti + -- k = 2 + tr = fi[p + 6] + ti = -fr[p + 6] + fr[p + 6] = fr[p + 2] - tr + fi[p + 6] = fi[p + 2] - ti + fr[p + 2] += tr + fi[p + 2] += ti + -- k = 3 + a, b = fr[p + 7], fi[p + 7] + tr = (b - a) * tw + ti = -(b + a) * tw + fr[p + 7] = fr[p + 3] - tr + fi[p + 7] = fi[p + 3] - ti + fr[p + 3] += tr + fi[p + 3] += ti + p += 8 + end +end + +local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + if m == 1 then + local p = 1 + for _ = 1, N do + local r0, i0 = fr[p], fi[p] + local r1, i1 = fr[p + 1], fi[p + 1] + local r2, i2 = fr[p + 2], fi[p + 2] + local r3, i3 = fr[p + 3], fi[p + 3] + local s0r, s0i = r0 - r2, i0 - i2 + r0 += r2 + i0 += i2 + local s1r, s1i = r1 + r3, i1 + i3 + fr[p + 2] = r0 - s1r + fi[p + 2] = i0 - s1i + fr[p] = r0 + s1r + fi[p] = i0 + s1i + s1r, s1i = r1 - r3, i1 - i3 + fr[p + 1] = s0r + s1i + fi[p + 1] = s0i - s1r + fr[p + 3] = s0r - s1i + fi[p + 3] = s0i + s1r + p += 4 + end + else + local m2, m3 = 2 * m, 3 * m + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2, t3 = 1, 1, 1 + for _ = 0, m - 1 do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m3], fi[p + m3] + wr, wi = twr[t3], twi[t3] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local f0r, f0i = fr[p], fi[p] + local s5r, s5i = f0r - s1r, f0i - s1i + f0r += s1r + f0i += s1i + local s3r, s3i = s0r + s2r, s0i + s2i + local s4r, s4i = s0r - s2r, s0i - s2i + fr[p + m2] = f0r - s3r + fi[p + m2] = f0i - s3i + t1 += fstride + t2 += fstride * 2 + t3 += fstride * 3 + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m] = s5r + s4i + fi[p + m] = s5i - s4r + fr[p + m3] = s5r - s4i + fi[p + m3] = s5i + s4r + p += 1 + end + end + end +end + +local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local m2 = 2 * m + local epi3i = twi[fstride * m + 1] + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2 = 1, 1 + for _ = 1, m do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local s3r, s3i = s1r + s2r, s1i + s2i + local s0r, s0i = s1r - s2r, s1i - s2i + t1 += fstride + t2 += fstride * 2 + local f0r, f0i = fr[p], fi[p] + local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 + s0r *= epi3i + s0i *= epi3i + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m2] = fmr + s0i + fi[p + m2] = fmi - s0r + fr[p + m] = fmr - s0i + fi[p + m] = fmi + s0r + p += 1 + end + end +end + +local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] + local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] + for i = 0, N - 1 do + local p0 = i * mm + 1 + local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m + for u = 0, m - 1 do + local s0r, s0i = fr[p0], fi[p0] + local k = u * fstride + local ar, ai = fr[p1], fi[p1] + local wr, wi = twr[k + 1], twi[k + 1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p2], fi[p2] + wr, wi = twr[2 * k + 1], twi[2 * k + 1] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p3], fi[p3] + wr, wi = twr[3 * k + 1], twi[3 * k + 1] + local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p4], fi[p4] + wr, wi = twr[4 * k + 1], twi[4 * k + 1] + local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr + + local s7r, s7i = s1r + s4r, s1i + s4i + local s10r, s10i = s1r - s4r, s1i - s4i + local s8r, s8i = s2r + s3r, s2i + s3i + local s9r, s9i = s2r - s3r, s2i - s3i + + fr[p0] = s0r + (s7r + s8r) + fi[p0] = s0i + (s7i + s8i) + + local s5r = s0r + (s7r * yar + s8r * ybr) + local s5i = s0i + (s7i * yar + s8i * ybr) + local s6r = s10i * yai + s9i * ybi + local s6i = -(s10r * yai + s9r * ybi) + fr[p1] = s5r - s6r + fi[p1] = s5i - s6i + fr[p4] = s5r + s6r + fi[p4] = s5i + s6i + + local s11r = s0r + (s7r * ybr + s8r * yar) + local s11i = s0i + (s7i * ybr + s8i * yar) + local s12r = s9i * yai - s10i * ybi + local s12i = s10r * ybi - s9r * yai + fr[p2] = s11r + s12r + fi[p2] = s11i + s12i + fr[p3] = s11r - s12r + fi[p3] = s11i - s12i + + p0 += 1 + p1 += 1 + p2 += 1 + p3 += 1 + p4 += 1 + end + end +end + +-- in-place forward FFT of bit-reversed input (opus_fft_impl) +local function fftImpl(pl: Plan) + local factors = pl.factors + local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi + local fstride = { 1 } + local L = 0 + local m + repeat + local p = factors[2 * L + 1] + m = factors[2 * L + 2] + fstride[L + 2] = fstride[L + 1] * p + L += 1 + until m == 1 + m = factors[2 * L] + for i = L - 1, 0, -1 do + local m2 = if i ~= 0 then factors[2 * i] else 1 + local radix = factors[2 * i + 1] + if radix == 2 then + bfly2(fr, fi, fstride[i + 1]) + elseif radix == 4 then + bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + elseif radix == 3 then + bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + else + bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + end + m = m2 + end +end + +-- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of +-- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first +-- `overlap` samples (out[outBase] is sample 0). +function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) + local pl = plans[shift + 1] + local N4 = pl.n + local N2 = N4 * 2 + local trig = pl.trig + local bitrev = pl.bitrev + local fr, fi = pl.fr, pl.fi + -- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT) + local xp1 = inBase + local xp2 = inBase + stride * (N2 - 1) + for i = 0, N4 - 1 do + local x1 = inp[xp1] + local x2 = inp[xp2] + local t0, t1 = trig[2 * i + 1], trig[2 * i + 2] + local rev = bitrev[i + 1] + 1 + fi[rev] = x2 * t1 + x1 * t0 + fr[rev] = x1 * t1 - x2 * t0 + xp1 += 2 * stride + xp2 -= 2 * stride + end + fftImpl(pl) + -- post-rotate + local h = outBase + (overlap // 2) + for k = 0, N4 - 1 do + local re = fi[k + 1] + local im = fr[k + 1] + local t0, t1 = trig[2 * k + 1], trig[2 * k + 2] + out[h + 2 * k] = re * t1 + im * t0 + out[h + N2 - 1 - 2 * k] = re * t0 - im * t1 + end + -- mirror on both sides for TDAC + local xp = outBase + overlap - 1 + local yp = outBase + for i = 0, overlap // 2 - 1 do + local x1 = out[xp] + local x2 = out[yp] + local w1 = window[i + 1] + local w2 = window[overlap - i] + out[yp] = x2 * w2 - x1 * w1 + out[xp] = x2 * w1 + x1 * w2 + xp -= 1 + yp += 1 + end +end + +return Mdct diff --git a/src/Formats/audio/opus/Packet.luau b/src/Formats/audio/opus/Packet.luau new file mode 100644 index 0000000..e8b5749 --- /dev/null +++ b/src/Formats/audio/opus/Packet.luau @@ -0,0 +1,235 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding. +local Packet = {} + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +Packet.MODE_SILK_ONLY = 1000 +Packet.MODE_HYBRID = 1001 +Packet.MODE_CELT_ONLY = 1002 + +-- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND) +Packet.BW_NB = 1101 +Packet.BW_MB = 1102 +Packet.BW_WB = 1103 +Packet.BW_SWB = 1104 +Packet.BW_FB = 1105 + +function Packet.mode(toc: number): number + if band(toc, 0x80) ~= 0 then + return Packet.MODE_CELT_ONLY + elseif band(toc, 0x60) == 0x60 then + return Packet.MODE_HYBRID + else + return Packet.MODE_SILK_ONLY + end +end + +function Packet.bandwidth(toc: number): number + if band(toc, 0x80) ~= 0 then + local bw = 1102 + band(rshift(toc, 5), 3) + if bw == 1102 then + bw = 1101 + end + return bw + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x10) ~= 0 then 1105 else 1104 + else + return 1101 + band(rshift(toc, 5), 3) + end +end + +function Packet.channels(toc: number): number + return if band(toc, 4) ~= 0 then 2 else 1 +end + +-- samples per frame at rate Fs +function Packet.samplesPerFrame(toc: number, Fs: number): number + if band(toc, 0x80) ~= 0 then + local a = band(rshift(toc, 3), 3) + return bit32.lshift(Fs, a) // 400 + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x08) ~= 0 then Fs // 50 else Fs // 100 + else + local a = band(rshift(toc, 3), 3) + if a == 3 then + return Fs * 60 // 1000 + end + return bit32.lshift(Fs, a) // 100 + end +end + +-- total samples of a packet at 48 kHz, or -1 if invalid +function Packet.samples(buf: buffer, off: number, len: number): number + if len < 1 then + return -1 + end + local toc = readu8(buf, off) + local c = band(toc, 3) + local count + if c == 0 then + count = 1 + elseif c ~= 3 then + count = 2 + else + if len < 2 then + return -1 + end + count = band(readu8(buf, off + 1), 0x3F) + end + local n = count * Packet.samplesPerFrame(toc, 48000) + if n * 25 > 48000 * 3 then + return -1 + end + return n +end + +local function parseSize(buf: buffer, p: number, len: number): (number, number) + if len < 1 then + return -1, -1 + end + local b0 = readu8(buf, p) + if b0 < 252 then + return 1, b0 + elseif len < 2 then + return -1, -1 + end + return 2, 4 * readu8(buf, p + 1) + b0 +end + +-- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and +-- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in +-- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) + if len < 1 then + return -1, 0, 0 + end + local toc = readu8(buf, off) + local framesize = Packet.samplesPerFrame(toc, 48000) + local p = off + 1 + len -= 1 + local lastSize = len + local count + local cbr = false + local pad = 0 + local c = band(toc, 3) + if c == 0 then + count = 1 + elseif c == 1 then + count = 2 + cbr = true + if not selfDelimited then + if band(len, 1) ~= 0 then + return -1, toc, 0 + end + lastSize = len // 2 + sizes[1] = lastSize + end + elseif c == 2 then + count = 2 + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[1] = s + p += bytes + lastSize = len - s + else + if len < 1 then + return -1, toc, 0 + end + local ch = readu8(buf, p) + p += 1 + count = band(ch, 0x3F) + if count <= 0 or framesize * count > 5760 then + return -1, toc, 0 + end + len -= 1 + if band(ch, 0x40) ~= 0 then + local pb + repeat + if len <= 0 then + return -1, toc, 0 + end + pb = readu8(buf, p) + p += 1 + len -= 1 + local tmp = if pb == 255 then 254 else pb + len -= tmp + pad += tmp + until pb ~= 255 + end + if len < 0 then + return -1, toc, 0 + end + cbr = band(ch, 0x80) == 0 + if not cbr then + lastSize = len + for i = 1, count - 1 do + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[i] = s + p += bytes + lastSize -= bytes + s + end + if lastSize < 0 then + return -1, toc, 0 + end + elseif not selfDelimited then + lastSize = len // count + if lastSize * count ~= len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = lastSize + end + end + end + if selfDelimited then + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + p += bytes + sizes[count] = s + if cbr then + if s * count > len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = s + end + elseif bytes + s > lastSize then + return -1, toc, 0 + end + else + if lastSize > 1275 then + return -1, toc, 0 + end + sizes[count] = lastSize + end + for i = 1, count do + offsets[i] = p + p += sizes[i] + end + return count, toc, pad + (p - off) +end + +return Packet diff --git a/src/Formats/audio/opus/RangeDecoder.luau b/src/Formats/audio/opus/RangeDecoder.luau new file mode 100644 index 0000000..23d96ce --- /dev/null +++ b/src/Formats/audio/opus/RangeDecoder.luau @@ -0,0 +1,214 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/RangeDecoder: Range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus frame from a `buffer` slice +-- [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice backwards. +-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +local RangeDecoder = {} + +export type Dec = { + buf: buffer, + base: number, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local SYM_BITS = 8 +local CODE_BITS = 32 +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1 +local SYM_MAX = 255 +local UINT_BITS = 8 +local WINDOW_SIZE = 32 + +local countlz = bit32.countlz +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8 = buffer.readu8 + +local function ilog(x: number): number + return 32 - countlz(x) +end +RangeDecoder.ilog = ilog + +local function normalize(d: Dec) + local rng, val, rem = d.rng, d.val, d.rem + while rng <= CODE_BOT do + d.nbits_total += SYM_BITS + rng = rng * 256 + local sym = rem + local offs = d.offs + if offs < d.storage then + rem = readu8(d.buf, d.base + offs) + d.offs = offs + 1 + else + rem = 0 + end + sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) + end + d.rng, d.val, d.rem = rng, val, rem +end + +function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec + local d: Dec = { + buf = buf, + base = base, + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) // SYM_BITS) * SYM_BITS, + rng = 128, -- 1 << CODE_EXTRA + val = 0, + rem = 0, + ext = 0, + error = 0, + } + local rem = 0 + if storage > 0 then + rem = readu8(buf, base) + d.offs = 1 + end + d.rem = rem + d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA) + normalize(d) + return d +end + +-- ec_decode: the cumulative frequency of the next symbol, for a total of ft +function RangeDecoder.decode(d: Dec, ft: number): number + local ext = d.rng // ft + d.ext = ext + local s = d.val // ext + return ft - math.min(s + 1, ft) +end + +function RangeDecoder.decodeBin(d: Dec, bits: number): number + local ext = rshift(d.rng, bits) + d.ext = ext + local s = d.val // ext + local ft = lshift(1, bits) + return ft - math.min(s + 1, ft) +end + +function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) + local s = d.ext * (ft - fh) + d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) + if fl > 0 then + d.rng = d.ext * (fh - fl) + else + d.rng -= s + end + normalize(d) +end + +function RangeDecoder.bitLogp(d: Dec, logp: number): boolean + local r = d.rng + local v = d.val + local s = rshift(r, logp) + local ret = v < s + if ret then + d.rng = s + else + d.val = v - s + d.rng = r - s + end + normalize(d) + return ret +end + +-- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) +function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number + local s = d.rng + local v = d.val + local r = rshift(s, ftb) + local ret = -1 + local t + repeat + t = s + ret += 1 + s = r * icdf[off + ret] + until v >= s + d.val = v - s + d.rng = t - s + normalize(d) + return ret +end + +function RangeDecoder.bits(d: Dec, bits: number): number + local window = d.end_window + local available = d.nend_bits + if available < bits then + repeat + local b = 0 + local eo = d.end_offs + if eo < d.storage then + eo += 1 + d.end_offs = eo + b = readu8(d.buf, d.base + d.storage - eo) + end + window = bor(window, lshift(b, available)) + available += SYM_BITS + until available > WINDOW_SIZE - SYM_BITS + end + local ret = band(window, lshift(1, bits) - 1) + if bits == 32 then + ret = window + end + window = rshift(window, bits) + available -= bits + d.end_window = window + d.nend_bits = available + d.nbits_total += bits + return ret +end + +function RangeDecoder.uint(d: Dec, ft0: number): number + local ft = ft0 - 1 + local ftb = ilog(ft) + if ftb > UINT_BITS then + ftb -= UINT_BITS + local ft1 = rshift(ft, ftb) + 1 + local s = RangeDecoder.decode(d, ft1) + RangeDecoder.update(d, s, s + 1, ft1) + local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb)) + if t <= ft then + return t + end + d.error = 1 + return ft + else + local s = RangeDecoder.decode(d, ft0) + RangeDecoder.update(d, s, s + 1, ft0) + return s + end +end + +function RangeDecoder.tell(d: Dec): number + return d.nbits_total - ilog(d.rng) +end + +local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeDecoder.tellFrac(d: Dec): number + local nbits = d.nbits_total * 8 + local l = ilog(d.rng) + local r = rshift(d.rng, l - 16) + local b = rshift(r, 12) - 8 + if r > correction[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +return RangeDecoder diff --git a/src/Formats/audio/opus/Silk.luau b/src/Formats/audio/opus/Silk.luau new file mode 100644 index 0000000..428b06b --- /dev/null +++ b/src/Formats/audio/opus/Silk.luau @@ -0,0 +1,2070 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: +-- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, +-- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see +-- licenses/. +-- +-- local st = Silk.new(apiChannels) +-- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) +-- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } +-- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array +-- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. +-- +-- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values +-- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. +local RD = require("@formats/audio/opus/RangeDecoder") +local T = require("@formats/audio/opus/SilkTables") + +local icdf = RD.icdf +local bitLogp = RD.bitLogp +local countlz = bit32.countlz +local floor = math.floor + +local Silk = {} + +local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +for s = 1, 63 do + P2[s] = 2 ^ s +end +local function p2(s: number): number + if s == 0 then + return 1 + end + return P2[s] +end + +-- C helpers ----------------------------------------------------------------------------------------------------- + +local function s16(x: number): number + x = x % 65536 + if x >= 32768 then + return x - 65536 + end + return x +end + +local function i32(x: number): number + x = x % 4294967296 + if x >= 2147483648 then + return x - 4294967296 + end + return x +end + +local function sat16(x: number): number + if x > 32767 then + return 32767 + elseif x < -32768 then + return -32768 + end + return x +end + +local function addSat32(a: number, b: number): number + local s = a + b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +local function subSat32(a: number, b: number): number + local s = a - b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +-- silk_CLZ32 of a non-negative int32 +local function clz32(x: number): number + return countlz(x) +end + +-- silk_SMULWW (64-bit form): (a * b) >> 16, exact +local function mulww(a: number, b: number): number + return a * (b // 65536) + (a * (b % 65536)) // 65536 +end + +-- floor(a * b / 2^s) for int32 a, b and s >= 16, exact +local function mulshr(a: number, b: number, s: number): number + local t = a * (b // 65536) + (a * (b % 65536)) // 65536 + if s == 16 then + return t + end + return t // P2[s - 16] +end + +local function smmul(a: number, b: number): number + return mulshr(a, b, 32) +end + +-- silk_RSHIFT_ROUND (shift >= 1) +local function rround(a: number, s: number): number + return (a + p2(s - 1)) // P2[s] +end + +local function lshiftSat32(a: number, sh: number): number + if sh == 0 then + return a + end + local m = P2[sh] + local lo, hi = -2147483648 // m, 2147483647 // m + if a < lo then + a = lo + elseif a > hi then + a = hi + end + return a * m +end + +-- C integer division (truncation toward zero) +local function tdiv(a: number, b: number): number + local q = a / b + if q >= 0 then + return floor(q) + end + return -floor(-q) +end + +-- low 32 bits of a * b, as int32 +local function imul32(a: number, b: number): number + a = a % 4294967296 + local ah, al = a // 65536, a % 65536 + return i32(((ah * b) % 65536) * 65536 + al * b) +end + +local function silkRand(seed: number): number + return i32(907633515 + imul32(seed, 196314165)) +end + +local function rshift(a: number, s: number): number + if s == 0 then + return a + end + return a // P2[s] +end + +local function silkINVERSE32_varQ(b32: number, Qres: number): number + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = b32_inv * 65536 + local err_Q32 = i32((536870912 - (b32_nrm * b32_inv) // 65536) * 8) + result = i32(result + mulww(err_Q32, b32_inv)) + local lshift = 61 - b_headrm - Qres + if lshift <= 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return result // P2[lshift] + end + return 0 +end + +local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number + local a_headrm = clz32(math.abs(a32)) - 1 + local a32_nrm = a32 * p2(a_headrm) + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = (a32_nrm * s16(b32_inv)) // 65536 + a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) + result = result + (a32_nrm * s16(b32_inv)) // 65536 + local lshift = 29 + a_headrm - b_headrm - Qres + if lshift < 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return rshift(result, lshift) + end + return 0 +end + +local function silkLog2lin(inLog_Q7: number): number + if inLog_Q7 < 0 then + return 0 + elseif inLog_Q7 >= 3967 then + return 2147483647 + end + local out = p2(inLog_Q7 // 128) + local frac_Q7 = inLog_Q7 % 128 + local t = frac_Q7 + (frac_Q7 * (128 - frac_Q7) * -174) // 65536 + if inLog_Q7 < 2048 then + out = out + (out * t) // 128 + else + out = out + (out // 128) * t + end + return out +end + +local function silkSQRT_APPROX(x: number): number + if x <= 0 then + return 0 + end + local lz = clz32(x) + local rot = 24 - lz + local r + if rot == 0 then + r = x + elseif rot < 0 then + r = bit32.lrotate(x, -rot) + else + r = bit32.rrotate(x, rot) + end + local frac_Q7 = bit32.band(r, 0x7f) + local y = if bit32.band(lz, 1) ~= 0 then 32768 else 46214 + y = y // p2(lz // 2) + y = y + (y * (213 * frac_Q7)) // 65536 + return y +end + +-- silk_sum_sqr_shift: energy, shift +local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) + local shft = 31 - clz32(len) + local nrg = len + local i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + shft = math.max(0, shft + 3 - clz32(nrg)) + nrg = 0 + i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + return nrg, shft +end + +-- LPC helpers --------------------------------------------------------------------------------------------------- + +-- silk_bwexpander (int16 coefficients), ar 1-based +local function bwexpander(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) +end + +local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = i32(mulww(chirp_Q16, ar[i])) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = i32(mulww(chirp_Q16, ar[d])) +end + +-- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) +local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) + local sh = QIN - QOUT + local idx = 0 + local i = 0 + while i < 10 do + local maxabs = 0 + for k = 1, d do + local absval = math.abs(a_QIN[k]) + if absval > maxabs then + maxabs = absval + idx = k - 1 + end + end + maxabs = rround(maxabs, sh) + if maxabs > 32767 then + maxabs = math.min(maxabs, 163838) + local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, (maxabs * (idx + 1)) // 4) + bwexpander32(a_QIN, d, chirp_Q16) + else + break + end + i += 1 + end + if i == 10 then + for k = 1, d do + a_QOUT[k] = sat16(rround(a_QIN[k], sh)) + a_QIN[k] = a_QOUT[k] * P2[sh] + end + else + for k = 1, d do + a_QOUT[k] = s16(rround(a_QIN[k], sh)) + end + end +end + +local A_LIMIT = 16773022 +local INV_GAIN_MIN = 107374 +local Atmp_QA = table.create(16, 0) + +-- RSHIFT_ROUND64(SMULL(a, b), Q) +local function mulRound(a: number, b: number, Q: number): number + if Q == 1 then + local p = a * b + return p // 2 + p % 2 + end + if Q - 1 >= 16 then + return (mulshr(a, b, Q - 1) + 1) // 2 + end + return ((a * b) // P2[Q - 1] + 1) // 2 +end + +local function lpcInversePredGainQA(A_QA: { number }, order: number): number + local invGain_Q30 = 1073741824 + local k = order - 1 + while k > 0 do + local ak = A_QA[k + 1] + if ak > A_LIMIT or ak < -A_LIMIT then + return 0 + end + local rc_Q31 = -(ak * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) + local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) + for n = 0, (k + 1) // 2 - 1 do + local tmp1 = A_QA[n + 1] + local tmp2 = A_QA[k - n] + local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[n + 1] = t64 + t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[k - n] = t64 + end + k -= 1 + end + local a0 = A_QA[1] + if a0 > A_LIMIT or a0 < -A_LIMIT then + return 0 + end + local rc_Q31 = -(a0 * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + return invGain_Q30 +end + +local function lpcInversePredGain(A_Q12: { number }, order: number): number + local DC_resp = 0 + for k = 1, order do + DC_resp += A_Q12[k] + Atmp_QA[k] = A_Q12[k] * 4096 + end + if DC_resp >= 4096 then + return 0 + end + return lpcInversePredGainQA(Atmp_QA, order) +end + +local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } +local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } +local cos_LSF_QA = table.create(16, 0) +local polyP = table.create(9, 0) +local polyQ = table.create(9, 0) +local a32_QA1 = table.create(16, 0) +local LSFCos = T.LSFCosTab_FIX_Q12 + +-- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 +local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) + out[1] = 65536 + out[2] = -cLSF[c0 + 1] + for k = 1, dd - 1 do + local ftmp = cLSF[c0 + 2 * k + 1] + out[k + 2] = out[k] * 2 - (ftmp * out[k + 1] + 32768) // 65536 + for n = k, 2, -1 do + out[n + 1] += out[n - 1] - (ftmp * out[n] + 32768) // 65536 + end + out[2] -= ftmp + end +end + +-- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) +local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) + local ordering = if d == 16 then ordering16 else ordering10 + for k = 1, d do + local nl = NLSF[k] + local f_int = nl // 256 + local f_frac = nl - f_int * 256 + local cos_val = LSFCos[f_int + 1] + local delta = LSFCos[f_int + 2] - cos_val + cos_LSF_QA[ordering[k] + 1] = (cos_val * 256 + delta * f_frac + 8) // 16 + end + local dd = d // 2 + findPoly(polyP, cos_LSF_QA, 0, dd) + findPoly(polyQ, cos_LSF_QA, 1, dd) + for k = 0, dd - 1 do + local Ptmp = polyP[k + 2] + polyP[k + 1] + local Qtmp = polyQ[k + 2] - polyQ[k + 1] + a32_QA1[k + 1] = -Qtmp - Ptmp + a32_QA1[d - k] = Qtmp - Ptmp + end + lpcFit(a_Q12, a32_QA1, 12, 17, d) + local i = 0 + while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do + bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) + for k = 1, d do + a_Q12[k] = s16((a32_QA1[k] + 16) // 32) + end + i += 1 + end +end + +-- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 +local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) + for ix = d, len - 1 do + local base = io + ix - 1 + local acc = 0 + for j = 0, d - 1 do + acc += inp[base - j] * B[j + 1] + end + local out32_Q12 = i32(inp[base + 1] * 4096 - acc) + out[oo + ix] = sat16((out32_Q12 + 2048) // 4096) + end + for j = 0, d - 1 do + out[oo + j] = 0 + end +end + +-- NLSF ---------------------------------------------------------------------------------------------------------- + +local CB_NB_MB = { + nVectors = 32, + order = 10, + quantStepSize_Q16 = 11796, + CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, + pred_Q8 = T.NLSF_PRED_NB_MB_Q8, + ec_sel = T.NLSF_CB2_SELECT_NB_MB, + ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, +} +local CB_WB = { + nVectors = 32, + order = 16, + quantStepSize_Q16 = 9830, + CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_WB, + pred_Q8 = T.NLSF_PRED_WB_Q8, + ec_sel = T.NLSF_CB2_SELECT_WB, + ec_iCDF = T.NLSF_CB2_iCDF_WB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, +} + +local ec_ix = table.create(16, 0) +local pred_Q8 = table.create(16, 0) +local res_Q10 = table.create(16, 0) + +local function nlsfUnpack(CB: any, CB1_index: number) + local order = CB.order + local sel = CB.ec_sel + local pq = CB.pred_Q8 + local p = CB1_index * order // 2 + for i = 0, order - 1, 2 do + p += 1 + local entry = sel[p] + ec_ix[i + 1] = (bit32.band(entry // 2, 7)) * 9 + pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] + ec_ix[i + 2] = (bit32.band(entry // 32, 7)) * 9 + pred_Q8[i + 2] = pq[i + bit32.band(entry // 16, 1) * (order - 1) + 2] + end +end + +local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) + local loops = 0 + while loops < 20 do + local min_diff = NLSF[1] - NDeltaMin[1] + local I = 0 + for i = 1, L - 1 do + local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) + if diff < min_diff then + min_diff = diff + I = i + end + end + local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) + if diff < min_diff then + min_diff = diff + I = L + end + if min_diff >= 0 then + return + end + if I == 0 then + NLSF[1] = NDeltaMin[1] + elseif I == L then + NLSF[L] = 32768 - NDeltaMin[L + 1] + else + local min_center = 0 + for k = 0, I - 1 do + min_center += NDeltaMin[k + 1] + end + min_center += NDeltaMin[I + 1] // 2 + local max_center = 32768 + for k = L, I + 1, -1 do + max_center -= NDeltaMin[k + 1] + end + max_center -= NDeltaMin[I + 1] // 2 + local c = (NLSF[I] + NLSF[I + 1] + 1) // 2 + -- silk_LIMIT_32(c, min_center, max_center) + if min_center > max_center then + if c > min_center then + c = min_center + elseif c < max_center then + c = max_center + end + else + if c > max_center then + c = max_center + elseif c < min_center then + c = min_center + end + end + c = s16(c) + NLSF[I] = s16(c - NDeltaMin[I + 1] // 2) + NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) + end + loops += 1 + end + -- fall back: insertion sort, then clamp + for i = 2, L do + local value = NLSF[i] + local j = i - 1 + while j >= 1 and value < NLSF[j] do + NLSF[j + 1] = NLSF[j] + j -= 1 + end + NLSF[j + 1] = value + end + NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) + for i = 2, L do + NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) + end + NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) + for i = L - 1, 1, -1 do + NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) + end +end + +-- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) +local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) + nlsfUnpack(CB, NLSFIndices[1]) + local order = CB.order + local step = CB.quantStepSize_Q16 + local out_Q10 = 0 + for i = order - 1, 0, -1 do + local pred = (out_Q10 * pred_Q8[i + 1]) // 256 + out_Q10 = NLSFIndices[i + 2] * 1024 + if out_Q10 > 0 then + out_Q10 -= 102 + elseif out_Q10 < 0 then + out_Q10 += 102 + end + out_Q10 = pred + (out_Q10 * step) // 65536 + res_Q10[i + 1] = out_Q10 + end + local base = NLSFIndices[1] * order + local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 + for i = 1, order do + local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 + if v < 0 then + v = 0 + elseif v > 32767 then + v = 32767 + end + pNLSF_Q15[i] = v + end + nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) +end + +-- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- + +local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 +local up2_hq_0 = { 1746, 14986, 39083 - 65536 } +local up2_hq_1 = { 6854, 25769, 55542 - 65536 } +local FIR12 = T.resampler_frac_FIR_12 +local delay_matrix_dec = { + { 4, 0, 2, 0, 0, 0 }, + { 0, 9, 4, 7, 4, 4 }, + { 0, 3, 12, 7, 7, 7 }, +} + +local function rateID(R: number): number + local a = R // 4096 - (if R > 16000 then 1 else 0) + if R > 24000 then + a = a // 2 + end + return math.min(5, a - 1) +end + +local function newResampler(): any + return { + sIIR = table.create(6, 0), + sFIR = table.create(8, 0), + delayBuf = table.create(96, 0), + buf = table.create(2 * 160 + 8, 0), + resampler_function = RES_COPY, + batchSize = 0, + invRatio_Q16 = 0, + inputDelay = 0, + Fs_in_kHz = 0, + Fs_out_kHz = 0, + } +end + +local function copyResampler(dst: any, src: any) + for i = 1, 6 do + dst.sIIR[i] = src.sIIR[i] + end + for i = 1, 8 do + dst.sFIR[i] = src.sFIR[i] + end + for i = 1, 96 do + dst.delayBuf[i] = src.delayBuf[i] + end + dst.resampler_function = src.resampler_function + dst.batchSize = src.batchSize + dst.invRatio_Q16 = src.invRatio_Q16 + dst.inputDelay = src.inputDelay + dst.Fs_in_kHz = src.Fs_in_kHz + dst.Fs_out_kHz = src.Fs_out_kHz +end + +local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number + table.clear(S.sIIR) + table.clear(S.sFIR) + table.clear(S.delayBuf) + for i = 1, 6 do + S.sIIR[i] = 0 + end + for i = 1, 8 do + S.sFIR[i] = 0 + end + for i = 1, 96 do + S.delayBuf[i] = 0 + end + if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then + return -1 -- the decoder only upsamples (or copies) + end + S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 + S.Fs_in_kHz = Fs_Hz_in // 1000 + S.Fs_out_kHz = Fs_Hz_out // 1000 + S.batchSize = S.Fs_in_kHz * 10 + local up2x = 0 + if Fs_Hz_out > Fs_Hz_in then + if Fs_Hz_out == Fs_Hz_in * 2 then + S.resampler_function = RES_UP2 + else + S.resampler_function = RES_IIR_FIR + up2x = 1 + end + else + S.resampler_function = RES_COPY + end + local inv = (Fs_Hz_in * p2(14 + up2x)) // Fs_Hz_out * 4 + while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do + inv += 1 + end + S.invRatio_Q16 = inv + return 0 +end + +-- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] +local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) + local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] + local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] + local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] + for k = 0, len - 1 do + local in32 = inp[io + k] * 1024 + local Y = in32 - s0 + local X = (Y * c00) // 65536 + local out32_1 = s0 + X + s0 = in32 + X + Y = out32_1 - s1 + X = (Y * c01) // 65536 + local out32_2 = s1 + X + s1 = out32_1 + X + Y = out32_2 - s2 + X = Y + (Y * c02) // 65536 + out32_1 = s2 + X + s2 = out32_2 + X + out[oo + 2 * k] = sat16((out32_1 + 512) // 1024) + Y = in32 - s3 + X = (Y * c10) // 65536 + out32_1 = s3 + X + s3 = in32 + X + Y = out32_1 - s4 + X = (Y * c11) // 65536 + out32_2 = s4 + X + s4 = out32_1 + X + Y = out32_2 - s5 + X = Y + (Y * c12) // 65536 + out32_1 = s5 + X + s5 = out32_2 + X + out[oo + 2 * k + 1] = sat16((out32_1 + 512) // 1024) + end + S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 +end + +-- returns the next output index +local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number + local index_Q16 = 0 + while index_Q16 < max_index_Q16 do + local ti = ((index_Q16 % 65536) * 12) // 65536 + local b = index_Q16 // 65536 + 1 -- buf is 1-based + local f0 = ti * 4 + local f1 = (11 - ti) * 4 + local res_Q15 = buf[b] * FIR12[f0 + 1] + + buf[b + 1] * FIR12[f0 + 2] + + buf[b + 2] * FIR12[f0 + 3] + + buf[b + 3] * FIR12[f0 + 4] + + buf[b + 4] * FIR12[f1 + 4] + + buf[b + 5] * FIR12[f1 + 3] + + buf[b + 6] * FIR12[f1 + 2] + + buf[b + 7] * FIR12[f1 + 1] + out[oo] = sat16((res_Q15 + 16384) // 32768) + oo += 1 + index_Q16 += incr + end + return oo +end + +local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) + local buf = S.buf + local sFIR = S.sFIR + for i = 1, 8 do + buf[i] = sFIR[i] + end + local incr = S.invRatio_Q16 + local nSamplesIn + while true do + nSamplesIn = math.min(inLen, S.batchSize) + up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) + oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) + io += nSamplesIn + inLen -= nSamplesIn + if inLen > 0 then + local o = nSamplesIn * 2 + for i = 1, 8 do + buf[i] = buf[o + i] + end + else + break + end + end + local o = nSamplesIn * 2 + for i = 1, 8 do + sFIR[i] = buf[o + i] + end +end + +local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) + local f = S.resampler_function + if f == RES_IIR_FIR then + iirFir(S, out, oo, inp, io, len) + elseif f == RES_UP2 then + up2HQ(S.sIIR, out, oo, inp, io, len) + else + for i = 0, len - 1 do + out[oo + i] = inp[io + i] + end + end +end + +-- silk_resampler: out[1..] from inp[io .. io + inLen - 1] +local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) + local fin = S.Fs_in_kHz + local delay = S.inputDelay + local nSamples = fin - delay + local db = S.delayBuf + for i = 0, nSamples - 1 do + db[delay + i + 1] = inp[io + i] + end + resampleBlock(S, out, 1, db, 1, fin) + resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) + for i = 0, delay - 1 do + db[i + 1] = inp[io + inLen - delay + i] + end +end + +-- Decoder state ------------------------------------------------------------------------------------------------- + +local function newChannel(): any + return { + prev_gain_Q16 = 65536, + exc_Q14 = table.create(320, 0), + sLPC_Q14_buf = table.create(16, 0), + outBuf = table.create(480, 0), + lagPrev = 0, + LastGainIndex = 0, + fs_kHz = 0, + fs_API_hz = 0, + nb_subfr = 0, + frame_length = 0, + subfr_length = 0, + ltp_mem_length = 0, + LPC_order = 0, + prevNLSF_Q15 = table.create(16, 0), + first_frame_after_reset = 1, + pitch_lag_low_bits_iCDF = T.uniform4_iCDF, + pitch_contour_iCDF = T.pitch_contour_iCDF, + nFramesDecoded = 0, + nFramesPerPacket = 0, + ec_prevSignalType = 0, + ec_prevLagIndex = 0, + VAD_flags = { 0, 0, 0 }, + LBRR_flag = 0, + LBRR_flags = { 0, 0, 0 }, + resampler_state = newResampler(), + psNLSF_CB = CB_NB_MB, + indices = { + signalType = 0, + quantOffsetType = 0, + GainsIndices = { 0, 0, 0, 0 }, + NLSFIndices = table.create(17, 0), + NLSFInterpCoef_Q2 = 0, + lagIndex = 0, + contourIndex = 0, + PERIndex = 0, + LTPIndex = { 0, 0, 0, 0 }, + LTP_scaleIndex = 0, + Seed = 0, + }, + sCNG = { + CNG_exc_buf_Q14 = table.create(320, 0), + CNG_smth_NLSF_Q15 = table.create(16, 0), + CNG_synth_state = table.create(16, 0), + CNG_smth_Gain_Q16 = 0, + rand_seed = 3176576, + fs_kHz = 0, + }, + lossCnt = 0, + prevSignalType = 0, + sPLC = { + pitchL_Q8 = 0, + LTPCoef_Q14 = table.create(5, 0), + prevLPC_Q12 = table.create(16, 0), + last_frame_lost = 0, + rand_seed = 0, + randScale_Q14 = 0, + conc_energy = 0, + conc_energy_shift = 0, + prevLTP_scale_Q14 = 0, + prevGain_Q16 = { 65536, 65536 }, + fs_kHz = 0, + nb_subfr = 2, + subfr_length = 20, + }, + -- per-frame decoder control (silk_decoder_control) and scratch + ctrl = { + pitchL = { 0, 0, 0, 0 }, + Gains_Q16 = { 0, 0, 0, 0 }, + PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, + LTPCoef_Q14 = table.create(20, 0), + LTP_scale_Q14 = 0, + }, + pulses = table.create(336, 0), + out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] + } +end + +local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number + local ret = 0 + ch.subfr_length = 5 * fs_kHz + local frame_length = ch.nb_subfr * ch.subfr_length + if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then + ret += resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) + ch.fs_API_hz = fs_API_Hz + end + if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then + if fs_kHz == 8 then + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_NB_iCDF else T.pitch_contour_10_ms_NB_iCDF + else + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_iCDF else T.pitch_contour_10_ms_iCDF + end + if ch.fs_kHz ~= fs_kHz then + ch.ltp_mem_length = 20 * fs_kHz + if fs_kHz == 8 or fs_kHz == 12 then + ch.LPC_order = 10 + ch.psNLSF_CB = CB_NB_MB + else + ch.LPC_order = 16 + ch.psNLSF_CB = CB_WB + end + if fs_kHz == 16 then + ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF + elseif fs_kHz == 12 then + ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF + else + ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF + end + ch.first_frame_after_reset = 1 + ch.lagPrev = 100 + ch.LastGainIndex = 10 + ch.prevSignalType = 0 + local ob, sl = ch.outBuf, ch.sLPC_Q14_buf + for i = 1, 480 do + ob[i] = 0 + end + for i = 1, 16 do + sl[i] = 0 + end + end + ch.fs_kHz = fs_kHz + ch.frame_length = frame_length + end + return ret +end + +-- Bitstream: indices and pulses --------------------------------------------------------------------------------- + +local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } +local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } +local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } + +local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) + local ind = ch.indices + local Ix + if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then + Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 + else + Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) + end + local signalType = Ix // 2 + ind.signalType = signalType + ind.quantOffsetType = Ix % 2 + local gi = ind.GainsIndices + if condCoding == 2 then + gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) + else + gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 + gi[1] += icdf(d, T.uniform8_iCDF, 1, 8) + end + for i = 2, ch.nb_subfr do + gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) + end + local CB = ch.psNLSF_CB + local ni = ind.NLSFIndices + ni[1] = icdf(d, CB.CB1_iCDF, (signalType // 2) * CB.nVectors + 1, 8) + nlsfUnpack(CB, ni[1]) + for i = 1, CB.order do + Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) + if Ix == 0 then + Ix -= icdf(d, T.NLSF_EXT_iCDF, 1, 8) + elseif Ix == 8 then + Ix += icdf(d, T.NLSF_EXT_iCDF, 1, 8) + end + ni[i + 1] = Ix - 4 + end + if ch.nb_subfr == 4 then + ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) + else + ind.NLSFInterpCoef_Q2 = 4 + end + if signalType == 2 then + local absolute = true + if condCoding == 2 and ch.ec_prevSignalType == 2 then + local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) + if delta > 0 then + ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) + absolute = false + end + end + if absolute then + ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (ch.fs_kHz // 2) + ind.lagIndex += icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) + end + ch.ec_prevLagIndex = ind.lagIndex + ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) + ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) + local tab = LTP_gain_iCDF[ind.PERIndex + 1] + for k = 1, ch.nb_subfr do + ind.LTPIndex[k] = icdf(d, tab, 1, 8) + end + if condCoding == 0 then + ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) + else + ind.LTP_scaleIndex = 0 + end + end + ch.ec_prevSignalType = signalType + ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) +end + +local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 +local shellOff = T.shell_code_table_offsets + +local function split(d: any, p: number, tab: { number }): (number, number) + if p > 0 then + local a = icdf(d, tab, shellOff[p + 1] + 1, 8) + return a, p - a + end + return 0, 0 +end + +local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) + local p3a, p3b = split(d, pulses4, shell3) + local p2a, p2b = split(d, p3a, shell2) + local p1a, p1b = split(d, p2a, shell1) + out[o], out[o + 1] = split(d, p1a, shell0) + out[o + 2], out[o + 3] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 4], out[o + 5] = split(d, p1a, shell0) + out[o + 6], out[o + 7] = split(d, p1b, shell0) + p2a, p2b = split(d, p3b, shell2) + p1a, p1b = split(d, p2a, shell1) + out[o + 8], out[o + 9] = split(d, p1a, shell0) + out[o + 10], out[o + 11] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 12], out[o + 13] = split(d, p1a, shell0) + out[o + 14], out[o + 15] = split(d, p1b, shell0) +end + +local sum_pulses = table.create(20, 0) +local nLshifts = table.create(20, 0) +local signIcdf = { 0, 0 } + +-- pulses[1 .. frame_length (rounded up to 16)] +local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) + local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) + local iter = frame_length // 16 + if iter * 16 < frame_length then + iter += 1 + end + local ppb = T.pulses_per_block_iCDF + for i = 1, iter do + nLshifts[i] = 0 + local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) + while s == 17 do + nLshifts[i] += 1 + s = icdf(d, ppb, 9 * 18 + 1 + (if nLshifts[i] == 10 then 1 else 0), 8) + if nLshifts[i] > 30 then + break -- corrupt stream guard + end + end + sum_pulses[i] = s + end + for i = 1, iter do + local o = (i - 1) * 16 + 1 + if sum_pulses[i] > 0 then + shellDecoder(pulses, o, d, sum_pulses[i]) + else + for k = 0, 15 do + pulses[o + k] = 0 + end + end + end + local lsb = T.lsb_iCDF + for i = 1, iter do + local nLS = nLshifts[i] + if nLS > 0 then + local o = (i - 1) * 16 + 1 + for k = 0, 15 do + local abs_q = pulses[o + k] + for _ = 1, nLS do + abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) + end + pulses[o + k] = abs_q + end + sum_pulses[i] += nLS * 32 + end + end + -- silk_decode_signs + local signTab = T.sign_iCDF + local base = 7 * (quantOffsetType + signalType * 2) + local blocks = (frame_length + 8) // 16 + for i = 1, blocks do + local p = sum_pulses[i] + if p > 0 then + signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] + local o = (i - 1) * 16 + 1 + for j = 0, 15 do + local q = pulses[o + j] + if q > 0 then + pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) + end + end + end + end +end + +-- Parameters ---------------------------------------------------------------------------------------------------- + +local pNLSF_Q15 = table.create(16, 0) +local pNLSF0_Q15 = table.create(16, 0) + +local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) + local prev = ch.LastGainIndex + for k = 1, nb_subfr do + if k == 1 and not conditional then + prev = math.max(ind[k], prev - 16) + else + local ind_tmp = ind[k] - 4 + local thr = 8 + prev + if ind_tmp > thr then + prev += ind_tmp * 2 - thr + else + prev += ind_tmp + end + end + if prev < 0 then + prev = 0 + elseif prev > 63 then + prev = 63 + end + gain_Q16[k] = silkLog2lin(math.min((1907825 * prev) // 65536 + 2090, 3967)) + end + ch.LastGainIndex = prev +end + +local CB_lags = { + [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, + [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, +} + +local function decodeParameters(ch: any, ctrl: any, condCoding: number) + local ind = ch.indices + gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) + local order = ch.LPC_order + nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) + nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) + if ch.first_frame_after_reset == 1 then + ind.NLSFInterpCoef_Q2 = 4 + end + local prevNLSF = ch.prevNLSF_Q15 + if ind.NLSFInterpCoef_Q2 < 4 then + local c = ind.NLSFInterpCoef_Q2 + for i = 1, order do + pNLSF0_Q15[i] = prevNLSF[i] + (c * (pNLSF_Q15[i] - prevNLSF[i])) // 4 + end + nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) + else + local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] + for i = 1, order do + a[i] = b[i] + end + end + for i = 1, order do + prevNLSF[i] = pNLSF_Q15[i] + end + if ch.lossCnt ~= 0 then + bwexpander(ctrl.PredCoef_Q12[1], order, 63570) + bwexpander(ctrl.PredCoef_Q12[2], order, 63570) + end + if ind.signalType == 2 then + -- silk_decode_pitch + local fs = ch.fs_kHz + local cbinfo = CB_lags[if fs == 8 then 8 else 0][ch.nb_subfr] + local cb, cbk_size = cbinfo[1], cbinfo[2] + local min_lag, max_lag = 2 * fs, 18 * fs + local lag = min_lag + ind.lagIndex + for k = 0, ch.nb_subfr - 1 do + local v = lag + cb[k * cbk_size + ind.contourIndex + 1] + if v < min_lag then + v = min_lag + elseif v > max_lag then + v = max_lag + end + ctrl.pitchL[k + 1] = v + end + local vq = LTP_vq_Q7[ind.PERIndex + 1] + for k = 0, ch.nb_subfr - 1 do + local Ix = ind.LTPIndex[k + 1] + for i = 1, 5 do + ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 + end + end + ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] + else + for k = 1, ch.nb_subfr do + ctrl.pitchL[k] = 0 + end + for k = 1, 5 * ch.nb_subfr do + ctrl.LTPCoef_Q14[k] = 0 + end + ind.PERIndex = 0 + ctrl.LTP_scale_Q14 = 0 + end +end + +-- Core synthesis ------------------------------------------------------------------------------------------------ + +local sLTP = table.create(320, 0) +local sLTP_Q15 = table.create(640, 0) +local res_Q14 = table.create(80, 0) +local sLPC_Q14 = table.create(96, 0) +local A_Q12_tmp = table.create(16, 0) +local QuantOffsets = { { 100, 240 }, { 32, 100 } } + +-- silk_decode_core: xq[xo .. xo + frame_length - 1] +local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) + local ind = ch.indices + local exc = ch.exc_Q14 + local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] + local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 + local frame_length = ch.frame_length + local subfr_length = ch.subfr_length + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local outBuf = ch.outBuf + + local rand_seed = ind.Seed + for i = 1, frame_length do + rand_seed = silkRand(rand_seed) + local p = pulses[i] + local e = p * 16384 + if e > 0 then + e -= 1280 + elseif e < 0 then + e += 1280 + end + e += offset_Q10 * 16 + if rand_seed < 0 then + e = -e + end + exc[i] = e + rand_seed = i32(rand_seed + p) + end + + local sl = ch.sLPC_Q14_buf + for i = 1, 16 do + sLPC_Q14[i] = sl[i] + end + local pexc = 0 -- C offset into exc + local pxq = xo + local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 + local lag = 0 + for k = 0, ch.nb_subfr - 1 do + local A_Q12 = ctrl.PredCoef_Q12[k // 2 + 1] + for i = 1, order do + A_Q12_tmp[i] = A_Q12[i] + end + local Bo = k * 5 -- C offset into LTPCoef_Q14 + local B = ctrl.LTPCoef_Q14 + local signalType = ind.signalType + local gain = ctrl.Gains_Q16[k + 1] + local Gain_Q10 = gain // 64 + local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) + local gain_adj_Q16 + if gain ~= ch.prev_gain_Q16 then + gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) + for i = 1, 16 do + sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) + end + else + gain_adj_Q16 = 65536 + end + ch.prev_gain_Q16 = gain + if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then + for i = 1, 5 do + B[Bo + i] = 0 + end + B[Bo + 3] = 4096 + signalType = 2 + ctrl.pitchL[k + 1] = ch.lagPrev + end + if signalType == 2 then + lag = ctrl.pitchL[k + 1] + if k == 0 or (k == 2 and NLSF_interpolation_flag) then + local start_idx = ltp_mem_length - lag - order - 2 + if start_idx < 1 then + start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) + end + if k == 2 then + for i = 0, 2 * subfr_length - 1 do + outBuf[ltp_mem_length + i + 1] = xq[xo + i] + end + end + lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) + if k == 0 then + inv_gain_Q31 = ((inv_gain_Q31 * ctrl.LTP_scale_Q14) // 65536) * 4 + end + for i = 0, lag + 1 do + sLTP_Q15[sLTP_buf_idx - i] = (inv_gain_Q31 * sLTP[ltp_mem_length - i]) // 65536 + end + else + if gain_adj_Q16 ~= 65536 then + for i = 0, lag + 1 do + local j = sLTP_buf_idx - i + sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) + end + end + end + end + local presArr, presOff + if signalType == 2 then + local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] + local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] + for i = 1, subfr_length do + local pred = 2 + pred += (sLTP_Q15[pl] * b0) // 65536 + pred += (sLTP_Q15[pl - 1] * b1) // 65536 + pred += (sLTP_Q15[pl - 2] * b2) // 65536 + pred += (sLTP_Q15[pl - 3] * b3) // 65536 + pred += (sLTP_Q15[pl - 4] * b4) // 65536 + pl += 1 + local r = exc[pexc + i] + pred * 2 + res_Q14[i] = r + sLTP_buf_idx += 1 + sLTP_Q15[sLTP_buf_idx] = r * 2 + end + presArr, presOff = res_Q14, 0 + else + presArr, presOff = exc, pexc + end + local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = + A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], + A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] + local wide = order == 16 + local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] + for i = 1, subfr_length do + local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 + local pred = order // 2 + pred += (sLPC_Q14[j - 1] * a0) // 65536 + pred += (sLPC_Q14[j - 2] * a1) // 65536 + pred += (sLPC_Q14[j - 3] * a2) // 65536 + pred += (sLPC_Q14[j - 4] * a3) // 65536 + pred += (sLPC_Q14[j - 5] * a4) // 65536 + pred += (sLPC_Q14[j - 6] * a5) // 65536 + pred += (sLPC_Q14[j - 7] * a6) // 65536 + pred += (sLPC_Q14[j - 8] * a7) // 65536 + pred += (sLPC_Q14[j - 9] * a8) // 65536 + pred += (sLPC_Q14[j - 10] * a9) // 65536 + if wide then + pred += (sLPC_Q14[j - 11] * a10) // 65536 + pred += (sLPC_Q14[j - 12] * a11) // 65536 + pred += (sLPC_Q14[j - 13] * a12) // 65536 + pred += (sLPC_Q14[j - 14] * a13) // 65536 + pred += (sLPC_Q14[j - 15] * a14) // 65536 + pred += (sLPC_Q14[j - 16] * a15) // 65536 + end + pred = i32(pred) + local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) + sLPC_Q14[j] = v + xq[pxq + i - 1] = sat16((mulww(v, Gain_Q10) + 128) // 256) + end + for i = 1, 16 do + sLPC_Q14[i] = sLPC_Q14[subfr_length + i] + end + pexc += subfr_length + pxq += subfr_length + end + for i = 1, 16 do + sl[i] = sLPC_Q14[i] + end +end + +-- PLC / CNG ----------------------------------------------------------------------------------------------------- + +local HARM_ATT_Q15 = { 32440, 31130 } +local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } +local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } + +local function plcReset(ch: any) + local plc = ch.sPLC + plc.pitchL_Q8 = ch.frame_length * 128 + plc.prevGain_Q16[1] = 65536 + plc.prevGain_Q16[2] = 65536 + plc.subfr_length = 20 + plc.nb_subfr = 2 +end + +local function cngReset(ch: any) + local step = tdiv(32767, ch.LPC_order + 1) + local acc = 0 + local cng = ch.sCNG + for i = 1, ch.LPC_order do + acc += step + cng.CNG_smth_NLSF_Q15[i] = acc + end + cng.CNG_smth_Gain_Q16 = 0 + cng.rand_seed = 3176576 +end + +local function plcUpdate(ch: any, ctrl: any) + local plc = ch.sPLC + local nb = ch.nb_subfr + ch.prevSignalType = ch.indices.signalType + local LTP_Gain_Q14 = 0 + local coef = plc.LTPCoef_Q14 + if ch.indices.signalType == 2 then + local j = 0 + while j * ch.subfr_length < ctrl.pitchL[nb] do + if j == nb then + break + end + local t = 0 + local o = (nb - 1 - j) * 5 + for i = 1, 5 do + t += ctrl.LTPCoef_Q14[o + i] + end + if t > LTP_Gain_Q14 then + LTP_Gain_Q14 = t + for i = 1, 5 do + coef[i] = ctrl.LTPCoef_Q14[o + i] + end + plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 + end + j += 1 + end + for i = 1, 5 do + coef[i] = 0 + end + coef[3] = LTP_Gain_Q14 + if LTP_Gain_Q14 < 11469 then + local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q10)) // 1024 + end + elseif LTP_Gain_Q14 > 15565 then + local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q14)) // 16384 + end + end + else + plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 + for i = 1, 5 do + coef[i] = 0 + end + end + local p = ctrl.PredCoef_Q12[2] + for i = 1, ch.LPC_order do + plc.prevLPC_Q12[i] = p[i] + end + plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 + plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] + plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] + plc.subfr_length = ch.subfr_length + plc.nb_subfr = nb +end + +local excBuf = table.create(160, 0) +local plcLTP = table.create(320, 0) +local plcLTP_Q14 = table.create(640, 0) +local A_plc = table.create(16, 0) + +local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) + local plc = ch.sPLC + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local prevGain_Q10_0 = plc.prevGain_Q16[1] // 64 + local prevGain_Q10_1 = plc.prevGain_Q16[2] // 64 + if ch.first_frame_after_reset ~= 0 then + for i = 1, 16 do + plc.prevLPC_Q12[i] = 0 + end + end + -- silk_PLC_energy + local sl, nb = ch.subfr_length, ch.nb_subfr + local exc = ch.exc_Q14 + for k = 0, 1 do + local g = if k == 0 then prevGain_Q10_0 else prevGain_Q10_1 + for i = 0, sl - 1 do + excBuf[k * sl + i + 1] = sat16(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) // 256) + end + end + local energy1, shift1 = sumSqrShift(excBuf, 1, sl) + local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) + local rand_off -- C offset into exc_Q14 + if rshift(energy1, shift2) < rshift(energy2, shift1) then + rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) + else + rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) + end + local B = plc.LTPCoef_Q14 + local rand_scale_Q14 = plc.randScale_Q14 + local att = math.min(1, ch.lossCnt) + 1 + local harm_Gain_Q15 = HARM_ATT_Q15[att] + local rand_Gain_Q15 = if ch.prevSignalType == 2 then PLC_RAND_ATTENUATE_V_Q15[att] else PLC_RAND_ATTENUATE_UV_Q15[att] + bwexpander(plc.prevLPC_Q12, order, 64881) + for i = 1, order do + A_plc[i] = plc.prevLPC_Q12[i] + end + if ch.lossCnt == 0 then + rand_scale_Q14 = 16384 + if ch.prevSignalType == 2 then + for i = 1, 5 do + rand_scale_Q14 -= B[i] + end + rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) + rand_scale_Q14 = s16((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) // 16384) + else + local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) + local down = math.min(1073741824 // 8, invGain_Q30) + down = math.max(1073741824 // 256, down) + down = down * 8 + rand_Gain_Q15 = ((down * s16(rand_Gain_Q15)) // 65536) // 16384 + end + end + local rand_seed = plc.rand_seed + local lag = (plc.pitchL_Q8 + 128) // 256 + local sLTP_buf_idx = ltp_mem_length + local idx = ltp_mem_length - lag - order - 2 + if idx < 1 then + idx = 1 + end + lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) + local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) + inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) + for i = idx + order, ltp_mem_length - 1 do + plcLTP_Q14[i + 1] = (inv_gain_Q30 * plcLTP[i + 1]) // 65536 + end + for _ = 0, ch.nb_subfr - 1 do + local pl = sLTP_buf_idx - lag + 2 + 1 + local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] + for _ = 1, sl do + local pred = 2 + pred += (plcLTP_Q14[pl] * b0) // 65536 + pred += (plcLTP_Q14[pl - 1] * b1) // 65536 + pred += (plcLTP_Q14[pl - 2] * b2) // 65536 + pred += (plcLTP_Q14[pl - 3] * b3) // 65536 + pred += (plcLTP_Q14[pl - 4] * b4) // 65536 + pl += 1 + rand_seed = silkRand(rand_seed) + local ri = (rand_seed // 33554432) % 128 + sLTP_buf_idx += 1 + plcLTP_Q14[sLTP_buf_idx] = i32((pred + (exc[rand_off + ri + 1] * s16(rand_scale_Q14)) // 65536) * 4) + end + for j = 1, 5 do + B[j] = (harm_Gain_Q15 * s16(B[j])) // 32768 + end + rand_scale_Q14 = (s16(rand_scale_Q14) * s16(rand_Gain_Q15)) // 32768 + plc.pitchL_Q8 = plc.pitchL_Q8 + (plc.pitchL_Q8 * 655) // 65536 + plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) + lag = (plc.pitchL_Q8 + 128) // 256 + end + -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 + local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr + local slb = ch.sLPC_Q14_buf + for i = 1, 16 do + plcLTP_Q14[base + i] = slb[i] + end + for i = 0, ch.frame_length - 1 do + local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] + local pred = order // 2 + for t = 1, order do + pred += (plcLTP_Q14[j - t] * A_plc[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) + plcLTP_Q14[j] = v + frame[fo + i] = sat16((mulww(v, prevGain_Q10_1) + 128) // 256) + end + for i = 1, 16 do + slb[i] = plcLTP_Q14[base + ch.frame_length + i] + end + plc.rand_seed = rand_seed + plc.randScale_Q14 = s16(rand_scale_Q14) + for i = 1, 4 do + ctrl.pitchL[i] = lag + end +end + +local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) + local plc = ch.sPLC + if ch.lossCnt ~= 0 then + plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) + plc.last_frame_lost = 1 + else + if plc.last_frame_lost ~= 0 then + local energy, energy_shift = sumSqrShift(frame, fo, length) + if energy_shift > plc.conc_energy_shift then + plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) + elseif energy_shift < plc.conc_energy_shift then + energy = rshift(energy, plc.conc_energy_shift - energy_shift) + end + if energy > plc.conc_energy then + local LZ = clz32(plc.conc_energy) - 1 + plc.conc_energy = i32(plc.conc_energy * p2(LZ)) + energy = rshift(energy, math.max(24 - LZ, 0)) + local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) + local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 + local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 + for i = 0, length - 1 do + frame[fo + i] = (gain_Q16 * frame[fo + i]) // 65536 + gain_Q16 += slope_Q16 + if gain_Q16 > 65536 then + break + end + end + end + end + plc.last_frame_lost = 0 + end +end + +local A_cng = table.create(16, 0) +local CNG_sig = table.create(336, 0) + +local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) + local c = ch.sCNG + if ch.fs_kHz ~= c.fs_kHz then + cngReset(ch) + c.fs_kHz = ch.fs_kHz + end + local order = ch.LPC_order + if ch.lossCnt == 0 and ch.prevSignalType == 0 then + local sm = c.CNG_smth_NLSF_Q15 + for i = 1, order do + sm[i] += ((ch.prevNLSF_Q15[i] - sm[i]) * 16348) // 65536 + end + local max_Gain_Q16, subfr = 0, 0 + for i = 0, ch.nb_subfr - 1 do + if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then + max_Gain_Q16 = ctrl.Gains_Q16[i + 1] + subfr = i + end + end + local eb = c.CNG_exc_buf_Q14 + local sl = ch.subfr_length + for i = (ch.nb_subfr - 1) * sl, 1, -1 do + eb[sl + i] = eb[i] + end + for i = 1, sl do + eb[i] = ch.exc_Q14[subfr * sl + i] + end + for i = 1, ch.nb_subfr do + local g = ctrl.Gains_Q16[i] + c.CNG_smth_Gain_Q16 += ((g - c.CNG_smth_Gain_Q16) * 4634) // 65536 + if mulww(c.CNG_smth_Gain_Q16, 46396) > g then + c.CNG_smth_Gain_Q16 = g + end + end + end + if ch.lossCnt ~= 0 then + local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) + if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then + gain_Q16 = (gain_Q16 // 65536) * (gain_Q16 // 65536) + gain_Q16 = i32((c.CNG_smth_Gain_Q16 // 65536) * (c.CNG_smth_Gain_Q16 // 65536) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) + else + gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) + gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) + end + local gain_Q10 = gain_Q16 // 64 + -- silk_CNG_exc + local exc_mask = 255 + while exc_mask > length do + exc_mask //= 2 + end + local seed = c.rand_seed + for i = 1, length do + seed = silkRand(seed) + local idx = bit32.band((seed // 16777216) % 256, exc_mask) + CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] + end + c.rand_seed = seed + nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) + for i = 1, 16 do + CNG_sig[i] = c.CNG_synth_state[i] + end + for i = 0, length - 1 do + local j = 16 + i + 1 + local pred = order // 2 + for t = 1, order do + pred += (CNG_sig[j - t] * A_cng[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) + CNG_sig[j] = v + frame[fo + i] = sat16(frame[fo + i] + sat16((mulww(v, gain_Q10) + 128) // 256)) + end + for i = 1, 16 do + c.CNG_synth_state[i] = CNG_sig[length + i] + end + else + for i = 1, order do + c.CNG_synth_state[i] = 0 + end + end +end + +-- Frame decode -------------------------------------------------------------------------------------------------- + +-- silk_decode_frame: writes frame_length samples to out[fo ..] +local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number + local L = ch.frame_length + local ctrl = ch.ctrl + ctrl.LTP_scale_Q14 = 0 + if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then + local pulses = ch.pulses + decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) + decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) + decodeParameters(ch, ctrl, condCoding) + decodeCore(ch, ctrl, out, fo, pulses) + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + -- silk_PLC (update) + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcUpdate(ch, ctrl) + ch.lossCnt = 0 + ch.prevSignalType = ch.indices.signalType + ch.first_frame_after_reset = 0 + else + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcConceal(ch, ctrl, out, fo) + ch.lossCnt += 1 + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + end + cng(ch, ctrl, out, fo, L) + plcGlueFrames(ch, out, fo, L) + ch.lagPrev = ctrl.pitchL[ch.nb_subfr] + return L +end + +-- Stereo -------------------------------------------------------------------------------------------------------- + +local function stereoDecodePred(d: any, pred_Q13: { number }) + local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) + local ix02 = n // 5 + local ix12 = n - 5 * ix02 + local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) + local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) + local q = T.stereo_pred_quant_Q13 + for c = 1, 2 do + local a = if c == 1 then ix00 + 3 * ix02 else ix10 + 3 * ix12 + local b = if c == 1 then ix01 else ix11 + local low_Q13 = q[a + 1] + local step_Q13 = ((q[a + 2] - low_Q13) * 6554) // 65536 + pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) + end + pred_Q13[1] -= pred_Q13[2] +end + +-- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) +local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) + x1[1], x1[2] = state.sMid[1], state.sMid[2] + x2[1], x2[2] = state.sSide[1], state.sSide[2] + state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] + state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] + local pred0 = state.pred_prev_Q13[1] + local pred1 = state.pred_prev_Q13[2] + local interp = 8 * fs_kHz + local denom_Q16 = tdiv(65536, interp) + local delta0 = (s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) // 65536 + local delta1 = (s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) // 65536 + for n = 0, frame_length - 1 do + if n < interp then + pred0 += delta0 + pred1 += delta1 + elseif n == interp then + pred0 = pred_Q13[1] + pred1 = pred_Q13[2] + end + local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 + sum = x2[n + 2] * 256 + (sum * s16(pred0)) // 65536 + sum = sum + ((x1[n + 2] * 2048) * s16(pred1)) // 65536 + x2[n + 2] = sat16((sum + 128) // 256) + end + if frame_length <= interp then + -- the second loop never ran; the C code still ends with pred = pred_Q13 + end + state.pred_prev_Q13[1] = pred_Q13[1] + state.pred_prev_Q13[2] = pred_Q13[2] + for n = 0, frame_length - 1 do + local a, b = x1[n + 2], x2[n + 2] + x1[n + 2] = sat16(a + b) + x2[n + 2] = sat16(a - b) + end +end + +-- API ----------------------------------------------------------------------------------------------------------- + +export type State = any + +function Silk.new(apiChannels: number): State + return { + ch = { newChannel(), newChannel() }, + sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, + nChannelsAPI = 0, + nChannelsInternal = 0, + prev_decode_only_middle = 0, + MS_pred_Q13 = { 0, 0 }, + resampOut = table.create(960, 0), + apiChannels = apiChannels, + } +end + +-- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) +function Silk.reset(st: State) + st.ch[1] = newChannel() + st.ch[2] = newChannel() + for _, ch in st.ch do + cngReset(ch) + plcReset(ch) + end + st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } + st.prev_decode_only_middle = 0 +end + +local function initChannel(st: State, n: number) + local ch = newChannel() + cngReset(ch) + plcReset(ch) + st.ch[n] = ch +end + +function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) + local ret = 0 + local nInt = ctrl.nChannelsInternal + local nAPI = ctrl.nChannelsAPI + local chs = st.ch + local decode_only_middle = 0 + local MS_pred_Q13 = st.MS_pred_Q13 + MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 + if nInt ~= 1 and nInt ~= 2 then + return -200, 0 + end + if firstFrame then + for n = 1, nInt do + chs[n].nFramesDecoded = 0 + end + end + if nInt > st.nChannelsInternal then + initChannel(st, 2) + end + local ch1 = chs[1] + local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz + if ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + local ms = ctrl.payloadSize_ms + if ms == 0 or ms == 10 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 2 + elseif ms == 20 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 4 + elseif ms == 40 then + ch.nFramesPerPacket = 2 + ch.nb_subfr = 4 + elseif ms == 60 then + ch.nFramesPerPacket = 3 + ch.nb_subfr = 4 + else + return -203, 0 + end + local fs_kHz_dec = ctrl.internalSampleRate // 1024 + 1 + if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then + return -200, 0 + end + ret += decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) + end + end + if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then + local s = st.sStereo + s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 + s.sSide[1], s.sSide[2] = 0, 0 + copyResampler(chs[2].resampler_state, ch1.resampler_state) + end + st.nChannelsAPI = nAPI + st.nChannelsInternal = nInt + if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then + return -200, 0 + end + if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + for i = 1, ch.nFramesPerPacket do + ch.VAD_flags[i] = if bitLogp(d, 1) then 1 else 0 + end + ch.LBRR_flag = if bitLogp(d, 1) then 1 else 0 + end + for n = 1, nInt do + local ch = chs[n] + ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 + if ch.LBRR_flag ~= 0 then + if ch.nFramesPerPacket == 1 then + ch.LBRR_flags[1] = 1 + else + local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 + for i = 0, ch.nFramesPerPacket - 1 do + ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) + end + end + end + end + if lostFlag == 0 then + -- skip all LBRR data + for i = 0, ch1.nFramesPerPacket - 1 do + for n = 1, nInt do + local ch = chs[n] + if ch.LBRR_flags[i + 1] ~= 0 then + if nInt == 2 and n == 1 then + stereoDecodePred(d, MS_pred_Q13) + if chs[2].LBRR_flags[i + 1] == 0 then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + end + end + local condCoding = if i > 0 and ch.LBRR_flags[i] ~= 0 then 2 else 0 + decodeIndices(ch, d, i, true, condCoding) + decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) + end + end + end + end + end + if nInt == 2 then + local fd = ch1.nFramesDecoded + if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then + stereoDecodePred(d, MS_pred_Q13) + if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + else + decode_only_middle = 0 + end + else + MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] + MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] + end + end + if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then + local c2 = chs[2] + for i = 1, 480 do + c2.outBuf[i] = 0 + end + for i = 1, 16 do + c2.sLPC_Q14_buf[i] = 0 + end + c2.lagPrev = 100 + c2.LastGainIndex = 10 + c2.prevSignalType = 0 + c2.first_frame_after_reset = 1 + end + local has_side + if lostFlag == 0 then + has_side = decode_only_middle == 0 + else + has_side = st.prev_decode_only_middle == 0 + or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) + end + local nSamplesOutDec = ch1.frame_length + for n = 1, nInt do + local ch = chs[n] + if n == 1 or has_side then + local FrameIndex = ch1.nFramesDecoded - (n - 1) + local condCoding + if FrameIndex <= 0 then + condCoding = 0 + elseif lostFlag == 2 then + condCoding = if ch.LBRR_flags[FrameIndex] ~= 0 then 2 else 0 + elseif n > 1 and st.prev_decode_only_middle ~= 0 then + condCoding = 1 + else + condCoding = 2 + end + nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) + else + local o = ch.out + for i = 3, nSamplesOutDec + 2 do + o[i] = 0 + end + end + ch.nFramesDecoded += 1 + end + local o1 = ch1.out + if nAPI == 2 and nInt == 2 then + stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) + else + local sMid = st.sStereo.sMid + o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] + end + local nSamplesOut = (nSamplesOutDec * ctrl.API_sampleRate) // (ch1.fs_kHz * 1000) + local ro = st.resampOut + local scale = 1 / 32768 + for n = 1, math.min(nAPI, nInt) do + resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) + if nAPI == 2 then + local b = outBase + n - 1 + for i = 0, nSamplesOut - 1 do + out[b + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + i] = ro[i + 1] * scale + end + end + end + if nAPI == 2 and nInt == 1 then + if stereo_to_mono then + resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = out[outBase + 2 * i] + end + end + end + if lostFlag == 1 then + for i = 1, st.nChannelsInternal do + chs[i].LastGainIndex = 10 + end + else + st.prev_decode_only_middle = decode_only_middle + end + return ret, nSamplesOut +end + +-- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced +function Silk.prevPitchLag(st: State): number + local ch = st.ch[1] + if ch.prevSignalType == 2 then + local mult = { 6, 4, 3 } + return ch.lagPrev * mult[(ch.fs_kHz - 8) // 4 + 1] + end + return 0 +end + +return Silk diff --git a/src/Formats/audio/opus/SilkTables.luau b/src/Formats/audio/opus/SilkTables.luau new file mode 100644 index 0000000..0322c48 --- /dev/null +++ b/src/Formats/audio/opus/SilkTables.luau @@ -0,0 +1,372 @@ +--!strict +--!optimize 2 +-- audio/opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see +-- licenses/). Multi-dimensional C arrays are flattened row-major; every array is 1-based. +local T = {} +T.LTP_per_index_iCDF = { + 179, 99, 0, +} +T.LTP_gain_iCDF_0 = { + 71, 56, 43, 30, 21, 12, 6, 0, +} +T.LTP_gain_iCDF_1 = { + 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, +} +T.LTP_gain_iCDF_2 = { + 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, + 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, +} +T.LTP_gain_vq_0 = { + 4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14, + 1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33, +} +T.LTP_gain_vq_1 = { + 13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1, + 6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8, + 2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4, + 3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41, +} +T.LTP_gain_vq_2 = { + -6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1, + -9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2, + 9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11, + 5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15, + -1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1, + -1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17, + 5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1, + 0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88, +} +T.NLSF_CB1_WB_Q8 = { + 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, + 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, + 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, + 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, + 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, + 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, + 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, + 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, + 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, + 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, + 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, + 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, + 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, + 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, + 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, + 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, + 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, + 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, + 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, + 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, + 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, + 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, + 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, + 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, + 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, + 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, +} +T.NLSF_CB1_WB_Wght_Q9 = { + 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056, + 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, + 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, + 2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, + 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056, + 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, + 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, + 2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, + 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103, + 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, + 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, + 2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, + 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545, + 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, + 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, + 3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, + 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347, + 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, + 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, + 2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, + 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432, + 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, + 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, + 3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, + 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197, + 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, +} +T.NLSF_CB1_iCDF_WB = { + 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, + 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, + 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, + 5, 4, 3, 0, +} +T.NLSF_CB2_SELECT_WB = { + 0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, + 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, + 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, + 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, + 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, + 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, + 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, + 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, + 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, + 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, + 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, + 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, + 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0, +} +T.NLSF_CB2_iCDF_WB = { + 255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, + 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, + 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, + 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0, +} +T.NLSF_PRED_WB_Q8 = { + 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, + 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, +} +T.NLSF_DELTA_MIN_WB_Q15 = { + 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347, +} +T.NLSF_CB1_NB_MB_Q8 = { + 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, + 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, + 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, + 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, + 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, + 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, + 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, + 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, + 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, + 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, + 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, + 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, + 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, + 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, + 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, + 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, +} +T.NLSF_CB1_Wght_Q9 = { + 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, + 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, + 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, + 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, + 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, + 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, + 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, + 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, + 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, + 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, + 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, + 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, + 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, + 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, + 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, + 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, +} +T.NLSF_CB1_iCDF_NB_MB = { + 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, + 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, + 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, + 12, 11, 5, 0, +} +T.NLSF_CB2_SELECT_NB_MB = { + 16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, + 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, + 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, + 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, + 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, + 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, + 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, + 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139, +} +T.NLSF_CB2_iCDF_NB_MB = { + 255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, + 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, + 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, + 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0, +} +T.NLSF_PRED_NB_MB_Q8 = { + 179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92, +} +T.NLSF_DELTA_MIN_NB_MB_Q15 = { + 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, +} +T.pitch_lag_iCDF = { + 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, + 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +} +T.pitch_delta_iCDF = { + 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, + 0, +} +T.pitch_contour_iCDF = { + 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, + 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0, +} +T.pitch_contour_NB_iCDF = { + 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, +} +T.pitch_contour_10_ms_iCDF = { + 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, +} +T.pitch_contour_10_ms_NB_iCDF = { + 113, 63, 0, +} +T.stereo_pred_quant_Q13 = { + -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, +} +T.stereo_pred_joint_iCDF = { + 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, + 11, 10, 9, 7, 0, +} +T.stereo_only_code_mid_iCDF = { + 64, 0, +} +T.LBRR_flags_2_iCDF = { + 203, 150, 0, +} +T.LBRR_flags_3_iCDF = { + 215, 195, 166, 125, 110, 82, 0, +} +T.lsb_iCDF = { + 120, 0, +} +T.LTPscale_iCDF = { + 128, 64, 0, +} +T.type_offset_VAD_iCDF = { + 232, 158, 10, 0, +} +T.type_offset_no_VAD_iCDF = { + 230, 0, +} +T.NLSF_interpolation_factor_iCDF = { + 243, 221, 192, 181, 0, +} +T.LTPScales_table_Q14 = { + 15565, 12288, 8192, +} +T.uniform3_iCDF = { + 171, 85, 0, +} +T.uniform4_iCDF = { + 192, 128, 64, 0, +} +T.uniform5_iCDF = { + 205, 154, 102, 51, 0, +} +T.uniform6_iCDF = { + 213, 171, 128, 85, 43, 0, +} +T.uniform8_iCDF = { + 224, 192, 160, 128, 96, 64, 32, 0, +} +T.NLSF_EXT_iCDF = { + 100, 40, 16, 7, 3, 1, 0, +} +T.gain_iCDF = { + 224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155, + 61, 11, 2, 0, +} +T.delta_gain_iCDF = { + 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, + 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, + 0, +} +T.LSFCosTab_FIX_Q12 = { + 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, + 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, + 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, + 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, + -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, + -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, + -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192, +} +T.pulses_per_block_iCDF = { + 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105, + 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83, + 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16, + 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19, + 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, + 42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, + 5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, + 6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, + 15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, +} +T.rate_levels_iCDF = { + 241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0, +} +T.shell_code_table0 = { + 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, + 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, + 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, + 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, + 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, + 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, + 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, + 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0, +} +T.shell_code_table1 = { + 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, + 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, + 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, + 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, + 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, + 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, + 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, + 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0, +} +T.shell_code_table2 = { + 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, + 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, + 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, + 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, + 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, + 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, + 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, + 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0, +} +T.shell_code_table3 = { + 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, + 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, + 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, + 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, + 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, + 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, + 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, + 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0, +} +T.shell_code_table_offsets = { + 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135, +} +T.sign_iCDF = { + 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, + 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, + 95, 102, +} +T.CB_lags_stage2_10_ms = { + 0, 1, 0, 0, 0, 1, +} +T.CB_lags_stage3_10_ms = { + 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2, + -2, 3, -2, 3, +} +T.CB_lags_stage2 = { + 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1, + 0, 0, -1, -1, +} +T.CB_lags_stage3 = { + 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, + 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, + -2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, + -2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, + 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, +} +T.resampler_frac_FIR_12 = { + 189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973, + -80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798, + -71, 611, -2143, 5784, -46, 425, -1375, 2996, +} +return T diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau new file mode 100644 index 0000000..08852eb --- /dev/null +++ b/src/Formats/audio/opus/init.luau @@ -0,0 +1,408 @@ +--!strict +-- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a +-- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK +-- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). +-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, +-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms +-- pre-roll), damaged files (concealment). Output is always 48 kHz f32. +-- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is +-- decoded), CELT pitch PLC (noise PLC only). +-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an +-- optional output buffer; decode() fully decodes to an Audio. +-- +-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... +-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio +-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Decoder = require("@formats/audio/opus/Decoder") +local Packet = require("@formats/audio/opus/Packet") +local RangeDecoder = require("@formats/audio/opus/RangeDecoder") +local Celt = require("@formats/audio/opus/Celt") +local Silk = require("@formats/audio/opus/Silk") + +-- ------------------------------------------------------------------------------------------------ contract +local Opus = { + name = "opus", + category = "audio", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files) + stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2) +} + +-- ------------------------------------------------------------------------------------------------ constants +local SAMPLE_RATE = 48000 + +-- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile +local DOWNMIX = { + [3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 }, + [4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 }, + [5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 }, + [6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }, + [7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 }, + [8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 }, +} +local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 +local MAX_PACKET = 5760 -- 120 ms + +export type Head = { + version: number, + channels: number, + preSkip: number, + inputSampleRate: number, + outputGain: number, -- Q7.8 dB + mappingFamily: number, + streams: number, + coupled: number, + mapping: { number }, +} + +-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. +local function parseHead(b: buffer, off: number, size: number): (Head?, string?) + if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then + return nil, "not an OpusHead packet" + end + local version = buffer.readu8(b, off + 8) + if bit32.rshift(version, 4) ~= 0 then + return nil, "unsupported OpusHead version " .. version + end + local channels = buffer.readu8(b, off + 9) + if channels < 1 then + return nil, "OpusHead: zero channels" + end + local head: Head = { + version = version, + channels = channels, + preSkip = buffer.readu16(b, off + 10), + inputSampleRate = buffer.readu32(b, off + 12), + outputGain = buffer.readi16(b, off + 16), + mappingFamily = buffer.readu8(b, off + 18), + streams = 1, + coupled = channels - 1, + mapping = {}, + } + if head.mappingFamily == 0 then + if channels > 2 then + return nil, "OpusHead: mapping family 0 with more than 2 channels" + end + head.mapping = if channels == 2 then { 0, 1 } else { 0 } + else + if head.mappingFamily == 3 then + return nil, "unsupported channel mapping family 3 (projection)" + end + if size < 21 + channels then + return nil, "OpusHead: truncated channel mapping table" + end + head.streams = buffer.readu8(b, off + 19) + head.coupled = buffer.readu8(b, off + 20) + if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then + return nil, "OpusHead: bad stream counts" + end + for c = 0, channels - 1 do + local m = buffer.readu8(b, off + 21 + c) + if m ~= 255 and m >= head.streams + head.coupled then + return nil, "OpusHead: bad channel mapping" + end + head.mapping[c + 1] = m + end + end + return head, nil +end + +-- OpusTags (RFC 7845 section 5.2): vendor string and a table of lower-cased field names to values (repeated +-- fields joined with "; "). +local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }) + local tags = {} + if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then + return "", tags + end + local p = off + 8 + local e = off + size + local vlen = buffer.readu32(b, p) + p += 4 + if p + vlen > e then + return "", tags + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + if p + 4 > e then + return vendor, tags + end + local n = buffer.readu32(b, p) + p += 4 + for _ = 1, n do + if p + 4 > e then + break + end + local l = buffer.readu32(b, p) + p += 4 + if p + l > e then + break + end + local s = buffer.readstring(b, p, l) + p += l + local eq = string.find(s, "=", 1, true) + if eq then + local k = string.lower(string.sub(s, 1, eq - 1)) + local v = string.sub(s, eq + 1) + tags[k] = if tags[k] then tags[k] .. "; " .. v else v + end + end + return vendor, tags +end + +Opus.Decoder = Decoder +Opus.Packet = Packet +Opus.RangeDecoder = RangeDecoder +Opus.Celt = Celt +Opus.Silk = Silk +Opus.parseHead = parseHead +Opus.parseTags = parseTags +Opus.SAMPLE_RATE = SAMPLE_RATE + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when the file starts with an Ogg page whose first packet is an OpusHead +function Opus.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local nseg = r:peekU8(26) + if nseg < 1 then + return 0 + end + return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) +function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Opus.open(r, opts) + if not dec then + return nil, err + end + local ch = dec.channels + local a = Types.Audio.new(SAMPLE_RATE, ch, dec.frames) + local total = 0 + while total < dec.frames do + local pcm, n = dec:read(math.min(65536, dec.frames - total)) + if n == 0 then + break + end + buffer.copy(a.samples, total * ch * 4, pcm, 0, n * ch * 4) + total += n + end + if total < dec.frames then -- a truncated file: keep what decoded + local s = buffer.create(total * ch * 4) + buffer.copy(s, 0, a.samples, 0, total * ch * 4) + a.samples = s + a.frames = total + end + a.tags = dec.tags + a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- Decodes the next packet into the pending buffer. Returns false at the end of the stream. +local function decodeNext(self: any): boolean + local p = self.demux:nextPacket(self.serial) + if p == nil then + return false + end + local n + if p.size > 0 then + n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET) + else + n = -1 + end + if n < 0 then + -- corrupt or empty packet: conceal for its nominal duration + local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1 + if dur <= 0 then + dur = self.lastDuration + end + n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur) + if n < 0 then + n = dur + for i = 1, n * self.channels do + self.pend[i] = 0 + end + end + end + self.lastDuration = n + self.pendStart = self.decoded + self.pendLen = n + self.pendPos = 0 + self.decoded += n + return true +end + +-- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if +-- given and big enough) is filled instead of a new buffer. +function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) + local ch = self.channels + local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 + local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next)) + local reuse = into ~= nil and buffer.len(into) >= want * ch * 4 + local out = if reuse then into :: buffer else buffer.create(want * ch * 4) + local got = 0 + local gain = self.gain + while got < want do + if self.pendPos >= self.pendLen then + if not decodeNext(self) then + break + end + end + -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) + local s = self.pendStart + self.pendPos + if s < self.next then + self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) + continue + end + local n = math.min(self.pendLen - self.pendPos, want - got) + if self.downmix then + Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8) + else + Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4) + end + self.pendPos += n + got += n + self.next += n + end + if got < want then + if not reuse then + local trimmed = buffer.create(got * ch * 4) + buffer.copy(trimmed, 0, out, 0, got * ch * 4) + out = trimmed + end + self.endSample = self.next -- the stream ended early (truncated file) + end + return out, got +end + +-- current playback position in seconds +function Stream.position(self: any): number + return (self.next - self.preSkip) / SAMPLE_RATE +end + +-- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll +function Stream.seek(self: any, seconds: number) + local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 + local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) + p = math.min(p, self.frames) + local target = p + self.preSkip -- decoded-sample index of the wanted sample + Decoder.resetMultistream(self.ms) + self.pendLen, self.pendPos = 0, 0 + local g = target - PREROLL + self.startGranule + local start = -1 + if g > self.startGranule then + start = self.demux:seekGranule(self.serial, g) or -1 + end + if start < 0 then + self.demux:rewind(self.serial) + self.demux:nextPacket(self.serial) -- OpusHead + self.demux:nextPacket(self.serial) -- OpusTags + self.decoded = 0 + else + self.decoded = start - self.startGranule + end + self.pendStart = self.decoded + self.next = target +end + +-- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) +function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("opus") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file") + end + local hp = demux:nextPacket(serial) + if hp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusHead") + end + local head, herr = parseHead(hp.data, hp.offset, hp.size) + if not head then + return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead") + end + local tp = demux:nextPacket(serial) + if tp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusTags") + end + local vendor, tags = parseTags(tp.data, tp.offset, tp.size) + -- granule of the first audio sample: first page granule minus the packets that end on it + local startGranule = 0 + local sum = 0 + while true do + local p = demux:nextPacket(serial) + if p == nil then + break + end + local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0 + sum += math.max(d, 0) + if p.granule ~= -1 then + startGranule = math.max(0, p.granule - sum) + break + end + end + demux:rewind(serial) + demux:nextPacket(serial) + demux:nextPacket(serial) + local info = demux:stream(serial) + local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule + local frames = math.max(0, last - startGranule - head.preSkip) + local downmix = nil + if opts and opts.stereo and head.channels > 2 then + downmix = DOWNMIX[head.channels] + if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally + downmix = table.create(head.channels * 2, 1 / head.channels) + end + end + local self = setmetatable({ + demux = demux, + serial = serial, + head = head, + vendor = vendor, + tags = tags, + sampleRate = SAMPLE_RATE, + channels = if downmix then 2 else head.channels, + sourceChannels = head.channels, + downmix = downmix, + frames = frames, + duration = frames / SAMPLE_RATE, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0, + preSkip = head.preSkip, + startGranule = startGranule, + gain = 10 ^ (head.outputGain / (20 * 256)), + ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping), + pend = table.create(MAX_PACKET * head.channels, 0), + pendStart = 0, + pendLen = 0, + pendPos = 0, + decoded = 0, -- decoded-sample index of the next packet's first sample + next = head.preSkip, -- decoded-sample index of the next sample read() returns + endSample = head.preSkip + frames, + lastDuration = 960, + }, Stream) + return self, nil +end + + +return Opus diff --git a/src/Formats/audio/wav/Codecs.luau b/src/Formats/audio/wav/Codecs.luau new file mode 100644 index 0000000..4094c07 --- /dev/null +++ b/src/Formats/audio/wav/Codecs.luau @@ -0,0 +1,326 @@ +--!strict +--!native +--!optimize 2 +-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). +-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) +-- only calls them with ranges it has checked against the source length and the output size. +local readu8, readi8, readu16, readi16, readu32, readi32 = + buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap +local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32 + +local Codecs = {} + +-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian, +-- from src[off] to dst (f32) starting at sample index d. +function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) + local o = d * 4 + if bytes == 1 then + for i = 0, count - 1 do + writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128) + end + elseif bytes == 2 then + if be then + for i = 0, count - 1 do + local s = off + i * 2 + local v = readi8(src, s) * 256 + readu8(src, s + 1) + writef32(dst, o + i * 4, v / 32768) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768) + end + end + elseif bytes == 3 then + if be then + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2) + writef32(dst, o + i * 4, v / 8388608) + end + else + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s + 2) * 65536 + readu16(src, s) + writef32(dst, o + i * 4, v / 8388608) + end + end + else + if be then + for i = 0, count - 1 do + local v = byteswap(readu32(src, off + i * 4)) + if v >= 0x80000000 then + v -= 0x100000000 + end + writef32(dst, o + i * 4, v / 2147483648) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648) + end + end + end +end + +-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values. +function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, + tmp: buffer) + local o = d * 4 + if bytes == 4 then + if be then + for i = 0, count - 1 do + writeu32(tmp, 0, byteswap(readu32(src, off + i * 4))) + writef32(dst, o + i * 4, readf32(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(src, off + i * 4)) + end + end + else + if be then + for i = 0, count - 1 do + local s = off + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, s + 4))) + writeu32(tmp, 4, byteswap(readu32(src, s))) + writef32(dst, o + i * 4, readf64(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf64(src, off + i * 8)) + end + end + end +end + +-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table +function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) + local o = d * 4 + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) + end +end + +local IMA_STEP = buffer.create(89 * 4) +do + local steps = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, + 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, + 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, + 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, + 20350, 22385, 24623, 27086, 29794, 32767, + } + for i, s in steps do + buffer.writei32(IMA_STEP, (i - 1) * 4, s) + end +end +local IMA_INDEX = buffer.create(16 * 4) +do + local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } + for i, v in t do + buffer.writei32(IMA_INDEX, (i - 1) * 4, v) + end +end + +-- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a +-- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and +-- returns the frame count. +function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number + if avail < 4 * ch then + return 0 + end + -- groups of 8 samples per channel (4 bytes each) after the per-channel headers + local groups = (avail - 4 * ch) // (4 * ch) + local frames = math.min(spb, 1 + groups * 8) + for c = 0, ch - 1 do + local pred = readi16(src, off + c * 4) + local index = readu8(src, off + c * 4 + 2) + if index > 88 then + index = 88 + end + writef32(dst, c * 4, pred / 32768) + local f = 1 + local g = 0 + while f < frames do + local p = off + 4 * ch + (g * ch + c) * 4 + for k = 0, 7 do + if f >= frames then + break + end + local b = readu8(src, p + rshift(k, 1)) + local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + local step = buffer.readi32(IMA_STEP, index * 4) + local diff = rshift(step, 3) + if band(nib, 1) ~= 0 then + diff += rshift(step, 2) + end + if band(nib, 2) ~= 0 then + diff += rshift(step, 1) + end + if band(nib, 4) ~= 0 then + diff += step + end + if band(nib, 8) ~= 0 then + pred -= diff + else + pred += diff + end + if pred > 32767 then + pred = 32767 + elseif pred < -32768 then + pred = -32768 + end + index += buffer.readi32(IMA_INDEX, nib * 4) + if index < 0 then + index = 0 + elseif index > 88 then + index = 88 + end + writef32(dst, (f * ch + c) * 4, pred / 32768) + f += 1 + end + g += 1 + end + end + return frames +end + +local MS_ADAPT = buffer.create(16 * 4) +do + local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } + for i, v in t do + buffer.writei32(MS_ADAPT, (i - 1) * 4, v) + end +end + +-- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch. +-- Returns the frame count (a truncated last block decodes the whole bytes it has). +function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, + coefs: buffer, ncoef: number, state: buffer): number + local hdr = 7 * ch + if avail < hdr or ncoef < 1 then + return 0 + end + local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch) + -- state per channel: c1, c2, idelta, s1, s2 (5 i32) + for c = 0, ch - 1 do + local pi = readu8(src, off + c) + if pi >= ncoef then + pi = ncoef - 1 + end + local idelta = readi16(src, off + ch + c * 2) + local s1 = readi16(src, off + 3 * ch + c * 2) + local s2 = readi16(src, off + 5 * ch + c * 2) + local so = c * 20 + buffer.writei32(state, so, buffer.readi32(coefs, pi * 8)) + buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4)) + buffer.writei32(state, so + 8, idelta) + buffer.writei32(state, so + 12, s1) + buffer.writei32(state, so + 16, s2) + writef32(dst, c * 4, s2 / 32768) + if frames > 1 then + writef32(dst, (ch + c) * 4, s1 / 32768) + end + end + -- nibbles, high first, channels interleaved per nibble + local total = (frames - 2) * ch + for k = 0, total - 1 do + local b = readu8(src, off + hdr + rshift(k, 1)) + local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + local c = k % ch + local so = c * 20 + local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4) + local idelta = buffer.readi32(state, so + 8) + local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16) + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + local sn = if nib >= 8 then nib - 16 else nib + p += sn * idelta + if p > 32767 then + p = 32767 + elseif p < -32768 then + p = -32768 + end + idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256 + if idelta < 16 then + idelta = 16 + elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg + idelta = 2796202 + end + buffer.writei32(state, so + 8, idelta) + buffer.writei32(state, so + 12, p) + buffer.writei32(state, so + 16, s1) + writef32(dst, (2 * ch + k) * 4, p / 32768) + end + return frames +end + +-- copy frames from a block cache into the output: count f32 values +function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) + buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) +end + +-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"), +-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller. +function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) + local so = s * 4 + if kind == "f32" then + buffer.copy(dst, off, src, so, count * 4) + elseif kind == "s16" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + writei16(dst, off + i * 2, v) + end + elseif kind == "s24" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5) + if v > 8388607 then + v = 8388607 + elseif v < -8388608 then + v = -8388608 + elseif v ~= v then + v = 0 + end + if v < 0 then + v += 16777216 + end + local o = off + i * 3 + writeu16(dst, o, v % 65536) + writeu8(dst, o + 2, v // 65536) + end + elseif kind == "s32" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5) + if v > 2147483647 then + v = 2147483647 + elseif v < -2147483648 then + v = -2147483648 + elseif v ~= v then + v = 0 + end + writei32(dst, off + i * 4, v) + end + else -- u8 + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5) + if v > 127 then + v = 127 + elseif v < -128 then + v = -128 + elseif v ~= v then + v = 0 + end + writeu8(dst, off + i, v + 128) + end + end +end + +return Codecs diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau new file mode 100644 index 0000000..81ef5b4 --- /dev/null +++ b/src/Formats/audio/wav/init.luau @@ -0,0 +1,650 @@ +--!strict +--!optimize 2 +-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no +-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder. +-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE +-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF +-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has). +-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when +-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags, +-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request. +-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. +-- +-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames +-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio +-- local file = Wav.encode(audio, { sampleFormat = "s24" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Riff = require("@formats/containers/Riff") +local Codecs = require("@formats/audio/wav/Codecs") + +-- ------------------------------------------------------------------------------------------------ contract +local Wav = { + name = "wav", + category = "audio", + extensions = { "wav", "wave", "rf64", "bw64" }, + mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Tags = { [string]: string } +export type OpenOptions = { + maxBytes: number?, -- unused (the file is already in memory); kept for symmetry +} +export type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16" + rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB + extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg + channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count) + tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...) + rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF) +} + +-- ------------------------------------------------------------------------------------------------ constants +Wav.FORMAT_PCM = 1 +Wav.FORMAT_MS_ADPCM = 2 +Wav.FORMAT_FLOAT = 3 +Wav.FORMAT_ALAW = 6 +Wav.FORMAT_MULAW = 7 +Wav.FORMAT_IMA_ADPCM = 0x11 +Wav.FORMAT_EXTENSIBLE = 0xFFFE + +local FORMAT_NAMES = { + [1] = "pcm", + [2] = "ms_adpcm", + [3] = "float", + [6] = "alaw", + [7] = "mulaw", + [0x11] = "ima_adpcm", +} + +-- LIST/INFO ids -> tag names +local INFO_TAGS = { + INAM = "title", + IART = "artist", + IPRD = "album", + ICMT = "comment", + ICRD = "date", + IGNR = "genre", + ITRK = "track", + IPRT = "track", + ISFT = "encoder", + ICOP = "copyright", + IENG = "engineer", + ISBJ = "subject", + IKEY = "keywords", +} + +-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear) +local ALAW, MULAW = buffer.create(1024), buffer.create(1024) +do + for i = 0, 255 do + local a = bit32.bxor(i, 0x55) + local t = bit32.band(a, 15) + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg > 0 then + t = bit32.lshift(t * 2 + 1 + 32, seg + 2) + else + t = bit32.lshift(t * 2 + 1, 3) + end + if bit32.band(a, 0x80) == 0 then + t = -t + end + buffer.writef32(ALAW, i * 4, t / 32768) + local u = bit32.band(bit32.bnot(i), 255) + local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4)) + local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 + buffer.writef32(MULAW, i * 4, v / 32768) + end +end + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable( + {} :: { + sampleRate: number, + channels: number, + frames: number, + duration: number, + bitrate: number, + tags: Tags, + format: string, + formatTag: number, + bitsPerSample: number, + blockAlign: number, + container: string, + dataOffset: number, + dataSize: number, + truncated: boolean, + channelMask: number?, + validBits: number?, + _buf: buffer, + _pos: number, + _be: boolean, + _bytes: number, + _kind: string, + _spb: number, + _cache: buffer?, + _cacheBlock: number, + _cacheFrames: number, + _coefs: buffer?, + _ncoef: number, + _state: buffer?, + _tmp: buffer, + }, + Decoder +)) + +local function trimTag(s: string): string + -- strip trailing NULs / spaces + local e = #s + while e > 0 do + local c = string.byte(s, e) + if c ~= 0 and c ~= 32 then + break + end + e -= 1 + end + local z = string.find(s, "\0", 1, true) + if z and z <= e then + e = z - 1 + end + return string.sub(s, 1, e) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Wav.sniff(r: Bytes.Reader): number + return if Riff.sniff(r) == "WAVE" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file +function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Wav.open(r, opts) + if not dec then + return nil, err + end + local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames) + local _, n = dec:read(dec.frames, a.samples) + if n < dec.frames then + local s = buffer.create(n * dec.channels * 4) + buffer.copy(s, 0, a.samples, 0, n * dec.channels * 4) + a.samples, a.frames = s, n + end + a.tags = dec.tags + a.meta.source = { + format = "wav", + codec = dec.format, + bitDepth = dec.bitsPerSample, + container = dec.container, + channelMask = dec.channelMask, + truncated = dec.truncated, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 } +-- ffmpeg's default speaker masks per channel count (av_channel_layout_default) +local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F } +local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag +-- tags -> LIST/INFO ids (the first id per name) +local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } +local BLOCK = 65536 -- frames per data piece when streaming a Decoder + +-- the body of the encoder: { buffer } pieces of the file | nil, Err +local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") + end + local o: EncodeOptions = opts or {} + local kind = o.sampleFormat or "s16" + local bytes: number? = SAMPLE_BYTES[kind] + if not bytes then + return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32") + end + local rate: number, ch: number = value.sampleRate, value.channels + if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad sample rate") + end + if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad channel count") + end + local isAudio = type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)") + end + local frameBytes = bytes * ch + local pieces: { buffer } = {} + local frames: number = 0 + if isAudio then + frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4)) + if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels") + end + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + -- pieces of at most 256 MiB + local per = math.max(1, 0x10000000 // frameBytes) + local f0 = 0 + while f0 < frames do + local n = math.min(per, frames - f0) + local b = buffer.create(n * frameBytes) + Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind) + table.insert(pieces, b) + f0 += n + end + else + local tmp = buffer.create(BLOCK * ch * 4) + while true do + local ok, out, n = pcall(value.read, value, BLOCK, tmp) + if not ok then + return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out)) + end + if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then + break + end + n = math.min(n, buffer.len(out) // (ch * 4)) + local b = buffer.create(n * frameBytes) + Codecs.quantize(out, 0, b, 0, n * ch, kind) + table.insert(pieces, b) + frames += n + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + end + end + local dataSize = frames * frameBytes + local bits = bytes * 8 + local float = kind == "f32" + local tag = if float then 3 else 1 + local extensible = ch > 2 or rate > 48000 or (not float and bits > 16) + if o.extensible ~= nil then + extensible = o.extensible + end + local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold }) + local fmt = Bytes.writer(40) + fmt:u16le(if extensible then 0xFFFE else tag) + fmt:u16le(ch) + fmt:u32le(rate) + fmt:u32le(rate * frameBytes) + fmt:u16le(frameBytes) + fmt:u16le(bits) + if extensible then + fmt:u16le(22) + fmt:u16le(bits) + fmt:u32le(o.channelMask or MASKS[ch] or 0) + fmt:u16le(tag) + fmt:string(GUID_TAIL) + elseif float then + fmt:u16le(0) -- cbSize + end + w:chunk("fmt ", fmt:finish()) + if float then + local fact = Bytes.writer(4) + fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg) + w:chunk("fact", fact:finish()) + end + local tags = o.tags or value.tags + if type(tags) == "table" then + local items = {} + local keys = {} + for k in tags do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + local v = tags[k] + local id = TAG_IDS[k] or (if #k == 4 and string.upper(k) == k then k else nil) + if id and type(v) == "string" and v ~= "" then + table.insert(items, { id, v }) + end + end + if #items > 0 then + w:list("INFO", items) + end + end + w:chunk("data", pieces) + local _ = dataSize + return w:finish({ parts = asParts }) +end + +-- encode(audio or decoder, opts?) -> buffer | nil, Err +function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + return encodeParts(value, opts, false) +end + +-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other +-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB +function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?) + return encodeParts(value, opts, true) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range +function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" or type(r) == "string" then + r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any) + end + local f, ferr = Riff.read(r, { openEnded = { data = true } }) + if not f then + return nil, ferr + end + if f.form ~= "WAVE" then + return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8) + end + local buf = f.buf + local magic = f.container + local be = f.bigEndian + + local fmt: any = nil + local tags: Tags = {} + local dataOff, dataSize = -1, 0 + local truncated = false + local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil + local factFrames: number? = nil + local function u16(o: number): number + return Riff.u16(f, o) + end + local function u32(o: number): number + return Riff.u32(f, o) + end + local function i16(o: number): number + local v = u16(o) + return if v >= 32768 then v - 65536 else v + end + for _, c in f.chunks do + local id, size, body, avail = c.id, c.size, c.offset, c.avail + if id == "fmt " and avail >= 14 then + fmt = { + tag = u16(body), + channels = u16(body + 2), + rate = u32(body + 4), + byteRate = u32(body + 8), + blockAlign = u16(body + 12), + bits = if avail >= 16 then u16(body + 14) else 8, + body = body, + avail = avail, + } + elseif id == "fact" and avail >= 4 then + factFrames = u32(body) + elseif id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, sc in Riff.list(f, c) do + local name = INFO_TAGS[sc.id] + if sc.avail > 0 then + local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) + if v ~= "" then + tags[name or sc.id] = v + end + end + end + elseif id == "data" and dataOff < 0 then + dataOff = body + dataSize = avail + truncated = c.truncated + end + local _ = size + end + + if not fmt then + return nil, Err.new(Err.CORRUPT, "no fmt chunk") + end + if dataOff < 0 then + return nil, Err.new(Err.CORRUPT, "no data chunk") + end + local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits + local channelMask: number? = nil + local validBits: number? = nil + if tag == 0xFFFE then + if fmt.avail < 40 then + return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension") + end + local valid = u16(fmt.body + 18) + channelMask = u32(fmt.body + 20) + tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag + -- valid bits < container bits: the samples are left-justified, so decoding the container is right + validBits = valid + end + if ch < 1 or ch > 255 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate > 4000000 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local name: string? = FORMAT_NAMES[tag] + if not name then + return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag)) + end + + local dec = setmetatable({}, Decoder) :: any + dec.sampleRate = rate + dec.channels = ch + dec.tags = tags + dec.format = name + dec.formatTag = tag + dec.bitsPerSample = bits + dec.container = magic + dec.dataOffset = dataOff + dec.dataSize = dataSize + dec.channelMask = channelMask + dec._buf = buf + dec._pos = 0 + dec._be = be + dec._tmp = buffer.create(8) + dec._cacheBlock = -1 + dec._cacheFrames = 0 + dec._ncoef = 0 + + local blockAlign: number = fmt.blockAlign + local frames: number + if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then + local bytes + if name == "alaw" or name == "mulaw" then + bytes = 1 + elseif name == "float" then + if bits ~= 32 and bits ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits) + end + bytes = bits // 8 + else + if bits < 1 or bits > 32 then + return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits) + end + -- container: from blockAlign when it is consistent, else from the bit depth + bytes = (bits + 7) // 8 + if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then + bytes = blockAlign // ch + end + end + blockAlign = bytes * ch + dec._bytes = bytes + dec._kind = name + frames = dataSize // blockAlign + dec._spb = 1 + elseif name == "ima_adpcm" or name == "ms_adpcm" then + if blockAlign < 1 then + return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0") + end + local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0 + if name == "ima_adpcm" then + if bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits) + end + if blockAlign < 4 * ch then + return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small") + end + local computed = (blockAlign - 4 * ch) * 2 // ch + 1 + if spb < 1 or spb > computed then + spb = computed + end + else + if blockAlign < 7 * ch then + return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small") + end + local computed = (blockAlign - 7 * ch) * 2 // ch + 2 + if spb < 2 or spb > computed then + spb = computed + end + -- coefficients from the fmt extension, else the 7 standard pairs + local c1 = { 256, 512, 0, 192, 240, 460, 392 } + local c2 = { 0, -256, 0, 64, 0, -208, -232 } + local ncoef = 7 + if fmt.avail >= 22 then + local k = u16(fmt.body + 20) + if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then + ncoef = k + c1, c2 = {}, {} + for i = 1, k do + c1[i] = i16(fmt.body + 22 + (i - 1) * 4) + c2[i] = i16(fmt.body + 24 + (i - 1) * 4) + end + end + end + local coefs = buffer.create(ncoef * 8) + for i = 1, ncoef do + buffer.writei32(coefs, (i - 1) * 8, c1[i]) + buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i]) + end + dec._coefs = coefs + dec._ncoef = ncoef + dec._state = buffer.create(20 * ch) + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + dec._kind = name + dec._spb = spb + dec._cache = buffer.create(spb * ch * 4) + local full = dataSize // blockAlign + frames = full * spb + local rest = dataSize - full * blockAlign + if rest > 0 then + -- a partial last block: the frames it holds whole + if name == "ima_adpcm" then + if rest >= 4 * ch then + frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + elseif rest >= 7 * ch then + frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) + end + end + -- fact: the true length (the last block is padded) + if factFrames and factFrames > 0 and factFrames < frames then + frames = factFrames + end + else + return nil, Err.new(Err.UNSUPPORTED, "format " .. name) + end + if ds64Frames and ds64Frames > 0 and ds64Frames < frames then + frames = ds64Frames + end + dec.blockAlign = blockAlign + dec.frames = frames + dec.duration = frames / rate + dec.truncated = truncated + dec.validBits = validBits + dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb) + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples +-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end). +function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number) + local ch = self.channels + local req = math.floor(tonumber(maxFrames) or 0) + if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT) + req = 0 + end + local want = math.max(0, math.min(req, self.frames - self._pos)) + local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4 + then out + else buffer.create(want * ch * 4) + if want == 0 then + return dst, 0 + end + local kind = self._kind + if self._spb == 1 then + local off = self.dataOffset + self._pos * self.blockAlign + local count = want * ch + if kind == "pcm" then + Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be) + elseif kind == "float" then + Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp) + elseif kind == "alaw" then + Codecs.law(self._buf, off, dst, 0, count, ALAW) + else + Codecs.law(self._buf, off, dst, 0, count, MULAW) + end + self._pos += want + return dst, want + end + -- block formats: decode a block into the cache, copy out of it + local spb, ba = self._spb, self.blockAlign + local cache = self._cache :: buffer + local done = 0 + while done < want do + local block = self._pos // spb + if block ~= self._cacheBlock then + local off = self.dataOffset + block * ba + local avail = math.min(ba, self.dataOffset + self.dataSize - off) + local got + if kind == "ima_adpcm" then + got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache) + else + got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef, + self._state :: buffer) + end + self._cacheBlock = block + self._cacheFrames = got + end + local inBlock = self._pos - block * spb + local k = math.min(want - done, self._cacheFrames - inBlock) + if k <= 0 then + break + end + Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch) + done += k + self._pos += k + end + return dst, done +end + +-- Moves to a time in seconds (clamped to the stream). +function Decoder.seek(self: Decoder, seconds: number) + local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +-- Moves to a frame index (clamped). +function Decoder.seekFrame(self: Decoder, frame: number) + local f = math.floor(tonumber(frame) or 0) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +-- Current position in seconds. +function Decoder.position(self: Decoder): number + return self._pos / self.sampleRate +end + +-- Current position in frames. +function Decoder.tell(self: Decoder): number + return self._pos +end + +return Wav diff --git a/src/Formats/codecs/Text/init.luau b/src/Formats/codecs/Text/init.luau new file mode 100644 index 0000000..11d9da4 --- /dev/null +++ b/src/Formats/codecs/Text/init.luau @@ -0,0 +1,53 @@ +--!strict +--!optimize 2 +-- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +-- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +local Text = {} + +-- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD) +Text.CP1252 = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +function Text.trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +-- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 +function Text.toUtf8(text: string, warnings: { string }?): string + if string.sub(text, 1, 3) == "\239\187\191" then + text = string.sub(text, 4) + end + if utf8.len(text) then + return text + end + if warnings then + table.insert(warnings, "text is not UTF-8: read as Windows-1252") + end + local out = table.create(#text) + for i = 1, #text do + local b = string.byte(text, i) + if b < 0x80 then + out[i] = string.char(b) + else + out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b) + end + end + return table.concat(out) +end + +function Text.lines(text: string): { string } + text = string.gsub(text, "\r\n?", "\n") + local out = {} + for line in string.gmatch(text .. "\n", "([^\n]*)\n") do + table.insert(out, line) + end + return out +end + +return Text diff --git a/src/Formats/codecs/Url/init.luau b/src/Formats/codecs/Url/init.luau new file mode 100644 index 0000000..026ecb5 --- /dev/null +++ b/src/Formats/codecs/Url/init.luau @@ -0,0 +1,216 @@ +--!strict +--!optimize 2 +-- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +-- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI +-- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its +-- init.luau. Never throws. +local Url = {} + +export type Location = { url: string, playable: boolean, reason: string?, [string]: any } + +export type Parts = { + scheme: string?, + authority: string?, + path: string, + query: string?, + fragment: string?, +} + +-- Splits a URI reference into its five components (RFC 3986 appendix B). +function Url.split(ref: string): Parts + local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") + if not scheme then + rest = ref + end + local s = rest :: string + local fragment, query, authority + local i = string.find(s, "#", 1, true) + if i then + fragment = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + i = string.find(s, "?", 1, true) + if i then + query = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + if string.sub(s, 1, 2) == "//" then + local j = string.find(s, "/", 3, true) + if j then + authority = string.sub(s, 3, j - 1) + s = string.sub(s, j) + else + authority = string.sub(s, 3) + s = "" + end + end + return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } +end + +-- Recomposes components (RFC 3986 section 5.3). +function Url.join(p: Parts): string + local out = {} + if p.scheme then + table.insert(out, p.scheme .. ":") + end + if p.authority then + table.insert(out, "//" .. p.authority) + end + table.insert(out, p.path) + if p.query then + table.insert(out, "?" .. p.query) + end + if p.fragment then + table.insert(out, "#" .. p.fragment) + end + return table.concat(out) +end + +-- RFC 3986 section 5.2.4 +function Url.removeDotSegments(path: string): string + local input = path + local output = {} + while input ~= "" do + if string.sub(input, 1, 3) == "../" then + input = string.sub(input, 4) + elseif string.sub(input, 1, 2) == "./" then + input = string.sub(input, 3) + elseif string.sub(input, 1, 3) == "/./" then + input = string.sub(input, 3) + elseif input == "/." then + input = "/" + elseif string.sub(input, 1, 4) == "/../" then + input = string.sub(input, 4) + table.remove(output) + elseif input == "/.." then + input = "/" + table.remove(output) + elseif input == "." or input == ".." then + input = "" + else + -- move the first segment (with its leading "/", up to the next "/") to the output + local j = string.find(input, "/", 2, true) + local seg = if j then string.sub(input, 1, j - 1) else input + table.insert(output, seg) + input = string.sub(input, #seg + 1) + end + end + return table.concat(output) +end + +-- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +function Url.resolve(ref: string, base: string): string + local r, b = Url.split(ref), Url.split(base) + local t: Parts = { path = "" } + if r.scheme then + t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query + else + if r.authority then + t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query + else + if r.path == "" then + t.path = b.path + t.query = if r.query then r.query else b.query + else + if string.sub(r.path, 1, 1) == "/" then + t.path = Url.removeDotSegments(r.path) + else + -- merge (5.2.3) + local merged + if b.authority and b.path == "" then + merged = "/" .. r.path + else + local k = string.match(b.path, "^.*()/") + merged = (if k then string.sub(b.path, 1, k) else "") .. r.path + end + t.path = Url.removeDotSegments(merged) + end + t.query = r.query + end + t.authority = b.authority + end + t.scheme = b.scheme + end + t.fragment = r.fragment + return Url.join(t) +end + +-- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), +-- leaving existing %XX escapes and the reserved delimiters alone. +function Url.encodeUnsafe(s: string): string + return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string + return string.format("%%%02X", string.byte(c)) + end)) +end + +-- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? +function Url.isWindowsPath(s: string): boolean + return string.match(s, "^%a:[\\/]") ~= nil + or string.match(s, "^%a:$") ~= nil + or string.sub(s, 1, 2) == "\\\\" + or string.sub(s, 1, 1) == "\\" +end + +-- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. +function Url.scheme(s: string): string? + if Url.isWindowsPath(s) then + return nil + end + local scheme = string.match(s, "^([%a][%w+%.%-]*):") + return if scheme then string.lower(scheme) else nil +end + +-- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's +-- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and +-- schemes other than http(s) are not playable (reason says why). +function Url.locate(raw: string, base: string?, baseScheme: string?): Location + local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) + if Url.isWindowsPath(loc) then + return { url = loc, playable = false, reason = "local path" } + end + local scheme = Url.scheme(loc) + local url = loc + if not scheme and baseScheme == "windows" and base then + -- a playlist on a Windows disk: relative entries are paths next to it + local dir = string.match(base, "^(.*[\\/])") or "" + return { url = dir .. loc, playable = false, reason = "local path" } + end + if scheme then + if scheme == "http" or scheme == "https" then + url = Url.encodeUnsafe(Url.resolve(loc, loc)) + end + elseif base and baseScheme then + -- a relative reference: Windows separators become URL ones + url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) + scheme = baseScheme + else + return { url = loc, playable = false, reason = "relative path without a base URL" } + end + if scheme == "http" or scheme == "https" then + return { url = url, playable = true } + elseif scheme == "file" then + return { url = url, playable = false, reason = "local path" } + end + return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } +end + +-- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" +-- for a Windows path); a non-absolute base is ignored (with a warning) +function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) + if type(baseUrl) ~= "string" or baseUrl == "" then + return nil, nil + end + local s = Url.scheme(baseUrl) + if s and Url.split(baseUrl).authority ~= nil or s == "file" then + return Url.encodeUnsafe(baseUrl), s + elseif Url.isWindowsPath(baseUrl) then + return baseUrl, "windows" + end + if warnings then + table.insert(warnings, "base URL is not absolute: " .. baseUrl) + end + return nil, nil +end + +return Url diff --git a/src/Formats/containers/Ogg/Mux.luau b/src/Formats/containers/Ogg/Mux.luau new file mode 100644 index 0000000..1e5ea79 --- /dev/null +++ b/src/Formats/containers/Ogg/Mux.luau @@ -0,0 +1,208 @@ +--!strict +--!native +--!optimize 2 +-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in formats-luau. +-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or +-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last +-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages +-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. +-- +-- local mux = Mux.new({ pageSize = 4096 }) +-- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...) +-- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page +-- s:packet(tags, 0, { flush = true }) +-- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate) +-- local out = mux:finish() -- closes every stream with an eos page +-- +-- Never throws: a bad argument returns false, Err. +local Err = require("@formats/core/Err") +local Page = require("@formats/containers/Ogg/Page") + +local CRC = Page.CRC_TABLE +local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32 +local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift + +local Mux = {} +Mux.__index = Mux +local Stream = {} +Stream.__index = Stream + +export type Options = { + pageSize: number?, -- close a page once its data reaches this many bytes (default 4096; at most 255 * 255) +} +export type PacketOptions = { + flush: boolean?, -- close the page after this packet (headers; default false) + eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed) +} + +-- new(opts?) -> Mux +function Mux.new(opts: Options?): any + local size = opts and opts.pageSize or 4096 + if type(size) ~= "number" or size < 1 then + size = 4096 + end + return setmetatable({ + pageSize = math.min(size, 255 * 255), + chunks = {} :: { buffer }, + total = 0, + streams = {} :: { any }, + nextSerial = 1, + }, Mux) +end + +-- stream(serial?) -> Stream (serials must be unique in the file) +function Mux.stream(self: any, serial: number?): any + local sr = serial or self.nextSerial + self.nextSerial = math.max(self.nextSerial, sr + 1) + local s = setmetatable({ + mux = self, + serial = sr % 4294967296, + seq = 0, + lacing = {} :: { number }, + parts = {} :: { any }, -- buffer, offset, length triples of the page data + dataLen = 0, + granule = -1, + continued = false, -- the page being built starts with the tail of a packet + first = true, + ended = false, + lastGranule = -1, + }, Stream) + table.insert(self.streams, s) + return s +end + +-- the CRC of a page (the crc field written as zero) +local function crc(b: buffer, n: number): number + local c = 0 + for i = 0, n - 1 do + c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1]) + end + return c +end + +-- close the page being built (also when empty, for eos) +function Stream._flush(self: any, eos: boolean) + local nseg = #self.lacing + local n = 27 + nseg + self.dataLen + local b = buffer.create(n) + buffer.writestring(b, 0, "OggS") + local flags = (if self.continued then 1 else 0) + (if self.first then 2 else 0) + (if eos then 4 else 0) + writeu8(b, 5, flags) + local g = self.granule + if g < 0 then + writeu32(b, 6, 0xFFFFFFFF) + writei32(b, 10, -1) + else + writeu32(b, 6, g % 4294967296) + writeu32(b, 10, (g // 4294967296) % 4294967296) + end + writeu32(b, 14, self.serial) + writeu32(b, 18, self.seq % 4294967296) + writeu8(b, 26, nseg) + for i = 1, nseg do + writeu8(b, 26 + i, self.lacing[i]) + end + local o = 27 + nseg + local parts = self.parts + for i = 1, #parts, 3 do + buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2]) + o += parts[i + 2] + end + writeu32(b, 22, crc(b, n)) + local m = self.mux + table.insert(m.chunks, b) + m.total += n + self.seq += 1 + self.first = false + self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1 + self.continued = false + if eos then + self.ended = true + end +end + +-- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet +-- (-1: unknown, not recommended); offset / length select a range of data. +function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) + if self.ended then + return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return false, Err.new(Err.ARG, "packet: data must be a buffer or a string") + end + if type(granule) ~= "number" then + return false, Err.new(Err.ARG, "packet: granule must be a number") + end + local off = offset or 0 + local len = length or (buffer.len(b) - off) + if off < 0 or len < 0 or off + len > buffer.len(b) then + return false, Err.new(Err.ARG, "packet: range outside the buffer") + end + local pageSize = self.mux.pageSize + local left = len + local pos = off + -- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255) + while true do + if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then + self:_flush(false) + self.continued = pos > off -- the next page starts inside this packet + end + local seg = math.min(left, 255) + table.insert(self.lacing, seg) + if seg > 0 then + table.insert(self.parts, b) + table.insert(self.parts, pos) + table.insert(self.parts, seg) + end + self.dataLen += seg + pos += seg + left -= seg + if seg < 255 then + break + end + end + if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page + self.granule = granule + self.lastGranule = granule + end + local eos = opts and opts.eos or false + if eos then + self:_flush(true) + elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then + self:_flush(false) + end + return true, nil +end + +-- flush(): close the current page now (if it holds anything) +function Stream.flush(self: any) + if not self.ended and #self.lacing > 0 then + self:_flush(false) + end +end + +-- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written) +function Mux.finish(self: any): buffer + for _, s in self.streams do + if not s.ended then + if #s.lacing == 0 then + s.granule = s.lastGranule + end + s:_flush(true) + end + end + local out = buffer.create(self.total) + local o = 0 + for _, c in self.chunks do + buffer.copy(out, o, c, 0, buffer.len(c)) + o += buffer.len(c) + end + return out +end + +return Mux diff --git a/src/Formats/containers/Ogg/Page.luau b/src/Formats/containers/Ogg/Page.luau new file mode 100644 index 0000000..acf9125 --- /dev/null +++ b/src/Formats/containers/Ogg/Page.luau @@ -0,0 +1,185 @@ +--!strict +--!native +--!optimize 2 +-- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header +-- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset, +-- forwards or backwards). Nothing here throws: invalid or truncated data gives nil. +-- +-- A page header (27 bytes + segment table): +-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) +-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 +local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift + +local Page = {} + +export type Info = { + offset: number, -- byte offset of "OggS" + size: number, -- header + segment table + data + headerSize: number, -- 27 + segment count + nsegs: number, + flags: number, + continued: boolean, + bos: boolean, + eos: boolean, + granule: number, -- -1 when no packet finishes on this page + serial: number, + sequence: number, +} + +-- CRC table, MSB-first +local CRC = table.create(256, 0) +for i = 0, 255 do + local r = lshift(i, 24) + for _ = 1, 8 do + if band(r, 0x80000000) ~= 0 then + r = bxor(lshift(r, 1), 0x04C11DB7) + else + r = lshift(r, 1) + end + end + CRC[i + 1] = r +end +Page.CRC_TABLE = CRC + +-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc +local function crcRange(b: buffer, from: number, to: number, crc: number): number + for i = from, to - 1 do + crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) + end + return crc +end + +-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +function Page.crc32(b: buffer, offset: number?, len: number?): number + local o = offset or 0 + local n = len or (buffer.len(b) - o) + if o < 0 or n < 0 or o + n > buffer.len(b) then + return 0 + end + return crcRange(b, o, o + n, 0) +end + +-- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic", +-- "version", "crc"). verify = false skips the CRC check. +function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) + local size = buffer.len(b) + if pos < 0 or pos + 27 > size then + return nil, "short" + end + if readu32(b, pos) ~= 0x5367674F then -- "OggS" + return nil, "magic" + end + if readu8(b, pos + 4) ~= 0 then + return nil, "version" + end + local nsegs = readu8(b, pos + 26) + local hsize = 27 + nsegs + if pos + hsize > size then + return nil, "short" + end + local dlen = 0 + for i = pos + 27, pos + hsize - 1 do + dlen += readu8(b, i) + end + local total = hsize + dlen + if pos + total > size then + return nil, "short" + end + if verify ~= false then + local c = crcRange(b, pos, pos + 22, 0) + for _ = 1, 4 do + c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1]) + end + c = crcRange(b, pos + 26, pos + total, c) + if c ~= readu32(b, pos + 22) then + return nil, "crc" + end + end + local flags = readu8(b, pos + 5) + return { + offset = pos, + size = total, + headerSize = hsize, + nsegs = nsegs, + flags = flags, + continued = band(flags, 1) ~= 0, + bos = band(flags, 2) ~= 0, + eos = band(flags, 4) ~= 0, + granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6), + serial = readu32(b, pos + 14), + sequence = readu32(b, pos + 18), + }, nil +end + +-- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the +-- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped. +function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lim = math.min(limit or size, size - 27 + 1) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos += 1 + end + return nil +end + +-- The last valid page starting at an offset in [floor, pos] (searching backwards). +function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lo = math.max(floor or 0, 0) + if pos > size - 27 then + pos = size - 27 + end + while pos >= lo do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos -= 1 + end + return nil +end + +-- The identification of a codec from a stream's first packet (the bos page's packet) +function Page.codec(b: buffer, off: number, len: number): string + local function is(s: string, at: number): boolean + if at + #s > len then + return false + end + for i = 1, #s do + if readu8(b, off + at + i - 1) ~= string.byte(s, i) then + return false + end + end + return true + end + if is("OpusHead", 0) then + return "opus" + elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then + return "flac" + elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then + return "vorbis" + elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then + return "theora" + elseif is("Speex ", 0) then + return "speex" + elseif is("fishead", 0) then + return "skeleton" + elseif is("fLaC", 0) then + return "flac-old" -- pre-1.1.1 Ogg FLAC mapping + end + return "unknown" +end + +return Page diff --git a/src/Formats/containers/Ogg/init.luau b/src/Formats/containers/Ogg/init.luau new file mode 100644 index 0000000..367f468 --- /dev/null +++ b/src/Formats/containers/Ogg/init.luau @@ -0,0 +1,456 @@ +--!strict +--!native +--!optimize 2 +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604 +-- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and +-- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture +-- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial); +-- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad +-- input gives nil, err). +-- +-- local demux, err = Ogg.open(buf) +-- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end +-- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator +-- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil +-- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target) +-- +-- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux) +-- local s = mux:stream(serial?) -- one logical stream +-- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages +-- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes +-- local file = mux:finish() -- every stream ends with an eos page +local Err = require("@formats/core/Err") +local Page = require("@formats/containers/Ogg/Page") +local Mux = require("@formats/containers/Ogg/Mux") + +local readu8 = buffer.readu8 +type PageInfo = any -- Page.Info (the sibling module is untyped here: required through `script` in Roblox) + +local Ogg = {} +Ogg.Page = Page +Ogg.Mux = Mux +Ogg.muxer = Mux.new + +export type Packet = { + data: buffer, -- the packet bytes are data[offset .. offset + size - 1] + offset: number, + size: number, + granule: number, -- the page granule if this is the last packet finishing on its page, else -1 + pageGranule: number, -- the granule of the page the packet finishes on (may be -1) + bos: boolean, -- first packet of the stream + eos: boolean, -- last packet of the stream (last packet finishing on an eos page) + pageOffset: number, -- byte offset of the page the packet finishes on + gap: boolean, -- data was lost before this packet (a missing page / bad CRC in between) +} + +export type Stream = { + serial: number, + codec: string, -- "opus" | "flac" | "vorbis" | "theora" | "speex" | "skeleton" | "flac-old" | "unknown" + firstPacket: buffer, -- a copy of the identification packet + bosOffset: number, -- byte offset of the bos page + lastGranule: number, -- the last known granule of the stream (-1 if none) +} + +-- Reader: the packet cursor of one logical stream +local Reader = {} +Reader.__index = Reader + +local function newReader(d: any, serial: number, start: number): any + return setmetatable({ + demux = d, + buf = d.buf, + serial = serial, + start = start, -- the bos page offset + pagePos = start, -- where to look for the next page + page = nil :: PageInfo?, + seg = 0, -- next segment index on the page + dataPos = 0, -- byte offset of the next segment's data + lastComplete = -1, -- index of the last segment ending a packet on this page + firstPacketOnPage = true, + parts = {} :: { number }, -- pending partial packet: offset, len pairs + partLen = 0, + lastSeq = -1, + gap = false, + ended = false, + total = 0, + }, Reader) +end + +-- Load the next page of this serial; false at the end of the data +function Reader._nextPage(self: any): boolean + local b, d = self.buf, self.demux + while true do + local p = Page.find(b, self.pagePos, nil, d.verify) + if not p then + return false + end + self.pagePos = p.offset + p.size + if p.serial == self.serial then + if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then + -- a page is missing: drop the partial packet + self.parts, self.partLen = {}, 0 + self.gap = true + end + self.lastSeq = p.sequence + self.page = p + self.seg = 0 + self.dataPos = p.offset + p.headerSize + self.firstPacketOnPage = true + local lc = -1 + local base = p.offset + 27 + for i = 0, p.nsegs - 1 do + if readu8(b, base + i) < 255 then + lc = i + end + end + self.lastComplete = lc + if p.continued then + if self.partLen == 0 and #self.parts == 0 then + -- the start of this packet is not ours (after a seek or a loss): skip its tail + local s = 0 + while s < p.nsegs do + local l = readu8(b, base + s) + self.dataPos += l + s += 1 + if l < 255 then + break + end + end + self.seg = s + self.firstPacketOnPage = false + end + elseif #self.parts > 0 then + -- a fresh packet while one was pending: the pending one is lost + self.parts, self.partLen = {}, 0 + self.gap = true + end + return true + end + end +end + +-- The next packet, or nil at the end of the stream +function Reader.nextPacket(self: any): Packet? + if self.ended then + return nil + end + local b = self.buf + while true do + local p = self.page + if p and self.seg < p.nsegs then + local base = p.offset + 27 + local start = self.dataPos + local len = 0 + local s = self.seg + local complete = false + while s < p.nsegs do + local l = readu8(b, base + s) + s += 1 + len += l + if l < 255 then + complete = true + break + end + end + self.seg = s + self.dataPos = start + len + if complete then + local data, off, size = b, start, len + local parts = self.parts + if #parts > 0 then + size = self.partLen + len + data = buffer.create(size) + off = 0 + local o = 0 + for i = 1, #parts, 2 do + buffer.copy(data, o, b, parts[i], parts[i + 1]) + o += parts[i + 1] + end + buffer.copy(data, o, b, start, len) + self.parts, self.partLen = {}, 0 + end + local last = (s - 1) == self.lastComplete + local pkt = { + data = data, + offset = off, + size = size, + granule = if last then p.granule else -1, + pageGranule = p.granule, + bos = p.bos and self.firstPacketOnPage, + eos = p.eos and last, + pageOffset = p.offset, + gap = self.gap, + } + self.firstPacketOnPage = false + self.gap = false + self.total += 1 + if pkt.eos then + self.ended = true + end + return pkt + else + -- the packet continues on a later page + table.insert(self.parts, start) + table.insert(self.parts, len) + self.partLen += len + end + else + if p and p.eos then + self.ended = true + return nil + end + if not self:_nextPage() then + self.ended = true + return nil + end + end + end +end + +-- Back to the start of the stream (the identification packet comes next) +function Reader.rewind(self: any) + self.pagePos = self.start + self.page = nil + self.seg = 0 + self.parts, self.partLen = {}, 0 + self.lastSeq = -1 + self.gap = false + self.ended = false +end + +-- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them +function Reader._at(self: any, p: PageInfo) + self:rewind() + self.pagePos = p.offset + self:_nextPage() -- loads p (it is a valid page of this serial) + local b = self.buf + local base = p.offset + 27 + local dp = p.offset + p.headerSize + for i = 0, self.lastComplete do + dp += readu8(b, base + i) + end + self.seg = self.lastComplete + 1 + self.dataPos = dp + self.parts, self.partLen = {}, 0 + self.firstPacketOnPage = false + self.gap = false + self.ended = false +end + +-- Seek so that the next packet is the first one that starts at or before granule g: positions after the last +-- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the +-- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start +-- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil). +function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) + local b, d = self.buf, self.demux + local serial = self.serial + local verify = d.verify + local function nextOf(pos: number, limit: number?): PageInfo? + while true do + local p = Page.find(b, pos, limit, verify) + if not p then + return nil + end + if p.serial == serial and p.granule ~= -1 then + return p + end + pos = p.offset + p.size + end + end + local lo, hi = self.start, buffer.len(b) + local best: PageInfo? = nil + while hi - lo > 65536 do + local mid = (lo + hi) // 2 + local p = nextOf(mid, hi) + if p and p.granule <= g then + best = p + lo = p.offset + else + hi = mid + end + end + local pos = lo + while true do + local p = nextOf(pos) + if not p or p.granule > g then + break + end + best = p + pos = p.offset + p.size + end + if not best then + self:rewind() + return -1, nil + end + self:_at(best) + return best.granule, nil +end + +-- Demux +local Demux = {} +Demux.__index = Demux + +-- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied +-- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll = +-- true lists every bos page in the file (chained streams), not just the first group +function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) + local buf: buffer + if type(src) == "buffer" then + buf = src + elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + buf = src.buf + else + local n = math.max(0, src.limit - src.base) + buf = buffer.create(n) + buffer.copy(buf, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader") + end + local verify = not (opts and opts.verify == false) + local first = Page.find(buf, 0, nil, verify) + if not first then + return nil, Err.new(Err.CORRUPT, "no Ogg page found") + end + local d = setmetatable({ + buf = buf, + size = buffer.len(buf), + verify = verify, + _streams = {} :: { Stream }, + _bySerial = {} :: { [number]: Stream }, + _readers = {} :: { [number]: any }, + _lastDone = false, + }, Demux) + -- the bos pages (at the start of the file, and later ones for chains if scanAll) + local pos = first.offset + local scanAll = opts and opts.scanAll + while true do + local p = Page.find(buf, pos, nil, verify) + if not p then + break + end + if p.bos and not d._bySerial[p.serial] then + local st = { + serial = p.serial, + codec = "unknown", + firstPacket = buffer.create(0), + bosOffset = p.offset, + lastGranule = -1, + } + table.insert(d._streams, st) + d._bySerial[p.serial] = st + local r = newReader(d, p.serial, p.offset) + local pk = r:nextPacket() + if pk then + local c = buffer.create(pk.size) + buffer.copy(c, 0, pk.data, pk.offset, pk.size) + st.firstPacket = c + st.codec = Page.codec(c, 0, pk.size) + end + elseif not p.bos and not scanAll then + break + end + pos = p.offset + p.size + end + if #d._streams == 0 then + return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page") + end + return d, nil +end + +-- Scan backwards from the end for each stream's last granule +function Demux._scanLast(self: any) + if self._lastDone then + return + end + self._lastDone = true + local b = self.buf + local need = #self._streams + local pos = self.size - 27 + while need > 0 do + local p = Page.findBack(b, pos, 0, self.verify) + if not p then + break + end + local st = self._bySerial[p.serial] + if st and st.lastGranule == -1 and p.granule ~= -1 then + st.lastGranule = p.granule + need -= 1 + end + pos = p.offset - 1 + end +end + +-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule } +function Demux.streams(self: any): { Stream } + self:_scanLast() + return self._streams +end + +function Demux.stream(self: any, serial: number): Stream? + self:_scanLast() + return self._bySerial[serial] +end + +-- The serial of the first stream of a codec, or nil +function Demux.find(self: any, codec: string): number? + for _, s in self._streams do + if s.codec == codec then + return s.serial + end + end + return nil +end + +-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err +function Demux.reader(self: any, serial: number): (any, Err.Err?) + local r = self._readers[serial] + if r then + return r, nil + end + local st = self._bySerial[serial] + if not st then + return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial)) + end + r = newReader(self, serial, st.bosOffset) + self._readers[serial] = r + return r, nil +end + +function Demux.nextPacket(self: any, serial: number): Packet? + local r = self:reader(serial) + return if r then r:nextPacket() else nil +end + +function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?) + local r, err = self:reader(serial) + if not r then + return nil, err + end + return r:seekGranule(g) +end + +function Demux.rewind(self: any, serial: number) + local r = self:reader(serial) + if r then + r:rewind() + end +end + +-- for p in demux:packets(serial) do ... end (continues from the stream's current position) +function Demux.packets(self: any, serial: number): () -> Packet? + local r = self:reader(serial) + return function() + return if r then r:nextPacket() else nil + end +end + +-- Copy a packet's bytes into a fresh buffer of its own +function Ogg.copy(p: Packet): buffer + local c = buffer.create(p.size) + buffer.copy(c, 0, p.data, p.offset, p.size) + return c +end + +return Ogg diff --git a/src/Formats/containers/Riff/init.luau b/src/Formats/containers/Riff/init.luau new file mode 100644 index 0000000..63fd4d1 --- /dev/null +++ b/src/Formats/containers/Riff/init.luau @@ -0,0 +1,372 @@ +--!strict +-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently +-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from +-- wav-luau fd9a909 (same author, no third-party code); the writer is new. +-- +-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer +-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false +-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf +-- local c = Riff.find(f, "fmt ") +-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type) +-- +-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX) +-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } }) +-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB +-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB +-- +-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past +-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a +-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of +-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err. +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 Riff = {} + +export type Chunk = { + id: string, + offset: number, -- absolute offset of the body in the file's buffer + size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks + declared: number, -- the raw size field + avail: number, -- body bytes present in the file (<= size) + truncated: boolean, -- declared past the end of the file + streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end) +} +export type File = { + container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64) + form: string, -- the form type: "WAVE", "AVI ", "WEBP", ... + bigEndian: boolean, + buf: buffer, + base: number, -- absolute offset of the file's first byte + limit: number, -- absolute offset past its last byte + size: number, -- the RIFF size field (ds64-resolved) + chunks: { Chunk }, + ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?, +} +export type ReadOptions = { + openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data) + maxChunks: number?, -- stop after this many chunks (default 100000) +} + +-- ------------------------------------------------------------------------------------------------ read +local function printable4(b: buffer, p: number, limit: number): boolean + if p + 4 > limit then + return false + end + for i = 0, 3 do + local c = readu8(b, p + i) + if c < 32 or c > 126 then + return false + end + end + return true +end + +local function u32(b: buffer, o: number, be: boolean): number + local v = readu32(b, o) + return if be then bit32.byteswap(v) else v +end + +-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil +function Riff.sniff(r: any): string? + local magic = r:peek(4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil + end + local form = r:peek(4, 8) + return if #form == 4 then form else nil +end + +-- walk the chunks of [p, limit) into list; returns the list +local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk } + local openEnded = opts and opts.openEnded + local maxChunks = opts and opts.maxChunks or 100000 + while p + 8 <= limit and #list < maxChunks do + local id = readstring(b, p, 4) + local declared = u32(b, p + 4, be) + local size = declared + local body = p + 8 + local avail = limit - body + if declared == 0xFFFFFFFF and ds64 then + if id == "data" then + size = ds64.dataSize + elseif ds64.table[id] then + size = ds64.table[id] + end + end + local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false } + table.insert(list, c) + if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then + c.streamed = size == 0 or size == 0xFFFFFFFF + c.truncated = not c.streamed + c.size, c.avail = avail, avail + break + end + if size > avail then + c.truncated = true + break + end + local nextPos = body + size + size % 2 + -- an odd-sized chunk written without its pad byte: the next id starts right after the body + if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then + nextPos = body + size + end + p = nextPos + end + return list +end + +-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer. +function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) + local r = if type(src) == "buffer" then Bytes.reader(src) else src + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader") + end + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base) + end + local magic = readstring(b, base, 4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base) + end + local be = magic == "RIFX" + local f: File = { + container = if magic == "BW64" then "RF64" else magic, + form = readstring(b, base + 8, 4), + bigEndian = be, + buf = b, + base = base, + limit = limit, + size = u32(b, base + 4, be), + chunks = {}, + ds64 = nil, + } + -- RF64: the ds64 chunk comes first + if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then + local sz = readu32(b, base + 16) + local o = base + 20 + if sz >= 24 and o + 24 <= limit then + local d = { + riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296, + dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296, + sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296, + table = {} :: { [string]: number }, + } + if sz >= 28 and o + 28 <= limit then + local n = readu32(b, o + 24) + local q = o + 28 + for _ = 1, math.min(n, 1000) do + if q + 12 > limit or q + 12 > o + sz then + break + end + d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296 + q += 12 + end + end + f.ds64 = d + if f.size == 0xFFFFFFFF then + f.size = d.riffSize + end + end + end + walk(b, base + 12, limit, be, opts, f.ds64, f.chunks) + return f, nil +end + +-- find(file, id, from?) -> the first chunk with that id (after index from), and its index +function Riff.find(f: File, id: string, from: number?): (Chunk?, number?) + for i = (from or 0) + 1, #f.chunks do + if f.chunks[i].id == id then + return f.chunks[i], i + end + end + return nil, nil +end + +-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil +function Riff.listType(f: File, c: Chunk): string? + if c.avail < 4 then + return nil + end + return readstring(f.buf, c.offset, 4) +end + +-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type) +function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk } + if c.avail < 4 then + return {} + end + return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil, {}) +end + +-- body(file, chunk) -> a Reader over the chunk's available body +function Riff.body(f: File, c: Chunk): Bytes.Reader + return Bytes.reader(f.buf, c.offset, c.avail) +end + +-- u16 / u32 in the file's byte order (for chunk bodies) +function Riff.u16(f: File, o: number): number + if f.bigEndian then + return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1) + end + return readu16(f.buf, o) +end +function Riff.u32(f: File, o: number): number + return u32(f.buf, o, f.bigEndian) +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +export type WriteOptions = { + bigEndian: boolean?, -- RIFX (default false) + rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto" + sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames) + rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF) +} + +-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file +function Riff.writer(form: string, opts: WriteOptions?): any + return setmetatable({ + form = string.sub(form .. " ", 1, 4), + be = opts and opts.bigEndian or false, + rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto", + sampleCount = opts and opts.sampleCount or 0, + threshold = opts and opts.rf64Threshold or 0xFFFFFFFF, + chunks = {} :: { any }, + }, Writer) +end + +-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a +-- list of buffers written one after the other (a data chunk bigger than one buffer) +function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?) + local parts = {} + local n = 0 + if type(body) == "table" then + for _, b in body do + table.insert(parts, { b, 0, buffer.len(b) }) + n += buffer.len(b) + end + else + local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body + local o = offset or 0 + n = length or (buffer.len(b) - o) + parts[1] = { b, o, n } + end + table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n }) +end + +-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style) +function Writer.list(self: any, listType: string, items: { { any } }) + local w = Bytes.writer() + w:string(string.sub(listType .. " ", 1, 4)) + for _, it in items do + local v = it[2] + local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v + local n = buffer.len(data) + w:string(string.sub(it[1] .. " ", 1, 4)) + if self.be then + w:u32be(n) + else + w:u32le(n) + end + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + end + self:chunk("LIST", w:finish()) +end + +-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied) +function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?) + local total = 4 -- the form type + local big = false + local dataSize = 0 + for _, c in self.chunks do + total += 8 + c.length + c.length % 2 + if c.length > 0xFFFFFFFE then + big = true + end + if c.id == "data" then + dataSize = c.length + end + end + local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold)) + if not rf64 and (big or total > 0xFFFFFFFF) then + return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64") + end + if rf64 and self.be then + return nil, Err.new(Err.ARG, "RF64 is little-endian only") + end + if rf64 then + total += 36 -- ds64 + end + local asParts = opts and opts.parts + if not asParts and total + 8 > 0x40000000 then + return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })") + end + local out: { buffer } = {} + local w = Bytes.writer(if asParts then 256 else total + 8) + local function size32(v: number) + if self.be then + w:u32be(v) + else + w:u32le(v) + end + end + if rf64 then + w:string("RF64") + w:u32le(0xFFFFFFFF) + w:string(self.form) + w:string("ds64") + w:u32le(28) + w:u64le(total) + w:u64le(dataSize) + w:u64le(self.sampleCount) + w:u32le(0) -- no table: only data may be over 4 GiB + else + w:string(if self.be then "RIFX" else "RIFF") + size32(total) + w:string(self.form) + end + for _, c in self.chunks do + w:string(c.id) + if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then + w:u32le(0xFFFFFFFF) + else + size32(c.length) + end + for _, p in c.parts do + if asParts then + table.insert(out, w:finish()) + w = Bytes.writer(64) + if p[2] == 0 and p[3] == buffer.len(p[1]) then + table.insert(out, p[1]) + else + local cp = buffer.create(p[3]) + buffer.copy(cp, 0, p[1], p[2], p[3]) + table.insert(out, cp) + end + else + w:bytes(p[1], p[2], p[3]) + end + end + if c.length % 2 == 1 then + w:u8(0) + end + end + if asParts then + if w:tell() > 0 then + table.insert(out, w:finish()) + end + return out, nil + end + return w:finish(), nil +end + +return Riff diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau new file mode 100644 index 0000000..1545ce2 --- /dev/null +++ b/src/Formats/containers/Zip/init.luau @@ -0,0 +1,668 @@ +--!strict +--!optimize 2 +-- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from +-- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an +-- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor +-- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, +-- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly +-- (codecs/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/Deflate compress, stored +-- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. +-- +-- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader +-- for _, e in zip:list() do print(e.name, e.size) end +-- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked +-- +-- local w = Zip.writer() +-- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds +-- local file = w:finish({ comment = "..." }) +-- +-- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native +-- code it reaches (Deflate, Crc32) does not throw either. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/Deflate") + +local Zip = {} +Zip.version = "1.1.0" + +export type Entry = { + name: string, -- the path with "\" turned into "/" + rawName: string, -- the name bytes as stored + index: number, -- position in the central directory, 1-based + size: number, -- uncompressed size + compressedSize: number, + crc32: number, + method: number, -- 0 stored, 8 deflate (others are listed but not readable) + flags: number, -- general purpose bits (1 encrypted, 8 data descriptor, 2048 UTF-8 name) + offset: number, -- local header offset (already corrected for a prefix such as a self-extractor stub) + isDir: boolean, + utf8: boolean, + comment: string, + modified: { year: number, month: number, day: number, hour: number, min: number, sec: number }, + mtime: number, -- the modification time as Unix seconds (the DOS time read as UTC) + time: number, -- the raw DOS time and date + date: number, + attributes: number, -- external attributes + -- central-directory lengths of the name and extra field (a fallback when the local header is wrong) + cdNameLen: number, + cdExtraLen: number, +} + +-- ------------------------------------------------------------------------------------------------ read +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 +local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50 + +local function readu64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +local function sigAt(b: buffer, o: number, sig: number): boolean + return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig +end + +local function normalize(name: string): string + name = string.gsub(name, "\\", "/") + name = string.gsub(name, "^%./", "") + name = string.gsub(name, "^/+", "") + return name +end + +local function basename(name: string): string + return string.match(name, "([^/]*)/*$") or name +end + +-- junk that shares a basename with real files: macOS resource forks +local function isJunk(name: string): boolean + local l = string.lower(name) + return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._" +end + +local Archive = {} +Archive.__index = Archive + + +-- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) +function Zip.isZip(buf: buffer | string): boolean + local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf + return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) +end + +local function findEocd(b: buffer): number? + local n = buffer.len(b) + local fallback = nil + local stop = math.max(0, n - 22 - 65535) + for p = n - 22, stop, -1 do + if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then + if p + 22 + readu16(b, p + 20) == n then + return p + end + fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking + end + end + return fallback +end + +local function parse(b: buffer): (any, Err.Err?) + local n = buffer.len(b) + if n < 22 then + return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record") + end + local eocd = findEocd(b) + if not eocd then + return nil, Err.new(Err.CORRUPT, "no end of central directory record") + end + local count = readu16(b, eocd + 10) + local cdSize = readu32(b, eocd + 12) + local cdOff = readu32(b, eocd + 16) + local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22) + local comment = buffer.readstring(b, eocd + 22, commentLen) + local cdEnd = eocd + -- ZIP64: the locator sits just before the end record + local zip64 = false + if sigAt(b, eocd - 20, SIG_Z64_LOC) then + local z = readu64(b, eocd - 20 + 8) + if not sigAt(b, z, SIG_Z64_EOCD) then + -- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data) + local guess = eocd - 20 - 56 + if sigAt(b, guess, SIG_Z64_EOCD) then + z = guess + else + z = -1 + end + end + if z >= 0 and z + 56 <= n then + zip64 = true + count = readu64(b, z + 32) + cdSize = readu64(b, z + 40) + cdOff = readu64(b, z + 48) + cdEnd = z + end + end + if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then + return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record") + end + -- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset + local delta = 0 + if count > 0 and not sigAt(b, cdOff, SIG_CD) then + delta = cdEnd - (cdOff + cdSize) + if not sigAt(b, cdOff + delta, SIG_CD) then + return nil, Err.new(Err.CORRUPT, "central directory not found") + end + end + local entries: { any } = table.create(math.min(count, 65536)) + local p = cdOff + delta + for i = 1, count do + if not sigAt(b, p, SIG_CD) or p + 46 > n then + return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p) + end + local flags = readu16(b, p + 8) + local method = readu16(b, p + 10) + local time, date = readu16(b, p + 12), readu16(b, p + 14) + local crc = readu32(b, p + 16) + local csize, usize = readu32(b, p + 20), readu32(b, p + 24) + local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32) + local disk = readu16(b, p + 34) + local off = readu32(b, p + 42) + if p + 46 + nameLen + extraLen + cmtLen > n then + return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p) + end + local raw = buffer.readstring(b, p + 46, nameLen) + -- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order + local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen + while q + 4 <= qe do + local id, sz = readu16(b, q), readu16(b, q + 2) + if id == 0x0001 then + local r, re = q + 4, math.min(q + 4 + sz, qe) + if usize == 0xFFFFFFFF and r + 8 <= re then + usize = readu64(b, r) + r += 8 + end + if csize == 0xFFFFFFFF and r + 8 <= re then + csize = readu64(b, r) + r += 8 + end + if off == 0xFFFFFFFF and r + 8 <= re then + off = readu64(b, r) + r += 8 + end + if disk == 0xFFFF and r + 4 <= re then + disk = readu32(b, r) + end + end + q += 4 + sz + end + local name = normalize(raw) + entries[i] = { + name = name, + rawName = raw, + index = i, + size = usize, + compressedSize = csize, + crc32 = crc, + method = method, + flags = flags, + offset = off + delta, + isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\", + utf8 = bit32.band(flags, 0x800) ~= 0, + comment = buffer.readstring(b, qe, cmtLen), + modified = { + year = 1980 + bit32.rshift(date, 9), + month = bit32.band(bit32.rshift(date, 5), 15), + day = bit32.band(date, 31), + hour = bit32.rshift(time, 11), + min = bit32.band(bit32.rshift(time, 5), 63), + sec = bit32.band(time, 31) * 2, + }, + mtime = Zip.unixTime(time, date), + time = time, + date = date, + attributes = readu32(b, p + 38), + cdNameLen = nameLen, + cdExtraLen = extraLen, + } + p = qe + cmtLen + end + local exact, lower, base = {}, {}, {} + for _, e in entries do + if not e.isDir then + exact[e.name] = exact[e.name] or e + local l = string.lower(e.name) + lower[l] = lower[l] or e + if not isJunk(e.name) then + local bn = basename(l) + local prev = base[bn] + -- prefer the shallowest path, then the first in directory order + if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then + base[bn] = e + end + end + end + end + return setmetatable({ + buf = b, + entries = entries, + comment = comment, + zip64 = zip64, + _exact = exact, + _lower = lower, + _base = base, + }, Archive) +end + +-- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a +-- part of a bigger buffer) +function Zip.open(src: any): (any, Err.Err?) + local b: buffer + if type(src) == "string" then + b = buffer.fromstring(src) + elseif type(src) == "buffer" then + b = src + elseif type(src) == "table" and type(src.buf) == "buffer" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + b = src.buf + else + local n = math.max(0, src.limit - src.base) + b = buffer.create(n) + buffer.copy(b, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader") + end + local ok, res, err = pcall(parse, b) + if not ok then + return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")") + end + return res, err +end + +-- every entry (directories included), in central directory order +function Archive.list(self: any): { Entry } + return self.entries +end + +-- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename +-- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and +-- macOS "__MACOSX/" / "._" files never match by basename. +function Archive.find(self: any, name: string): Entry? + local n = normalize(name) + local e = self._exact[n] + if e then + return e + end + local l = string.lower(n) + e = self._lower[l] + if e then + return e + end + return self._base[basename(l)] +end + +local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any) + local n = buffer.len(b) + if dataStart > n then + return nil, "data starts past the end" + end + if e.method == 0 then + if dataStart + e.size > n then + return nil, "truncated stored data" + end + local out = buffer.create(e.size) + buffer.copy(out, 0, b, dataStart, e.size) + return out + end + local len = math.min(e.compressedSize, n - dataStart) + local out, err = Deflate.inflate(b, dataStart, len, e.size) + if not out then + -- a wrong size in the directory: inflate without it and let the CRC decide + local out2 = Deflate.inflate(b, dataStart, n - dataStart) + if out2 then + return out2 + end + return nil, if type(err) == "table" then err.message else tostring(err) + end + return out +end + +-- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers +-- get the local extra length wrong) +function Zip._starts(b: buffer, e: Entry): { number } + local o = e.offset + local starts = {} + if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then + table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28)) + end + local alt = o + 30 + e.cdNameLen + e.cdExtraLen + if alt ~= starts[1] then + table.insert(starts, alt) + end + if alt ~= o + 30 + e.cdNameLen then + table.insert(starts, o + 30 + e.cdNameLen) + end + return starts +end + +-- read(entry | name, verify = true) -> buffer | nil, Err +function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?) + local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry + if not e then + return nil, Err.new(Err.ARG, "no entry " .. tostring(entry)) + end + if e.isDir then + return buffer.create(0), nil + end + if bit32.band(e.flags, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted") + end + if e.method ~= 0 and e.method ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method)) + end + local b = self.buf + local n = buffer.len(b) + local o = e.offset + if o < 0 or o + 30 > n then + return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o) + end + local starts = Zip._starts(b, e) + local firstErr: string? = nil + local code = Err.CORRUPT + for _, s in starts do + local out, err = extract(b, e, s) + if out then + if verify == false then + return out, nil + end + if buffer.len(out) ~= e.size then + err = string.format("size %d, expected %d", buffer.len(out), e.size) + else + local c = Deflate.crc32(out) + if c == e.crc32 then + return out, nil + end + err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32) + end + end + firstErr = firstErr or err + end + return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr)) +end + +-- readString(entry | name, verify?) -> string | nil, Err +function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?) + local out, err = self:read(entry, verify) + if not out then + return nil, err + end + return buffer.tostring(out), nil +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +export type AddOptions = { + method: ("deflate" | "store")?, -- default "deflate" (stored instead when deflate does not make it smaller) + level: number?, -- deflate level 0..9 (default 6) + mtime: number?, -- modification time, Unix seconds (UTC); default 1980-01-01 00:00:00 (reproducible output) + comment: string?, + utf8: boolean?, -- set the UTF-8 name flag (default: when the name is not plain ASCII) + attributes: number?, -- external attributes (default: Unix 0644 for files, 0755 + MS-DOS directory for dirs) +} +export type FinishOptions = { + comment: string?, -- the archive comment + zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them) +} + +-- writer() -> Writer +function Zip.writer(): any + return setmetatable({ files = {} :: { any } }, Writer) +end + +-- days from 1970-01-01 to y-m-d (proleptic Gregorian) +local function civil(z: number): (number, number, number) + z += 719468 + local era = (if z >= 0 then z else z - 146096) // 146097 + local doe = z - era * 146097 + local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 + local y = yoe + era * 400 + local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) + local mp = (5 * doy + 2) // 153 + local d = doy - (153 * mp + 2) // 5 + 1 + local m = if mp < 10 then mp + 3 else mp - 9 + return (if m <= 2 then y + 1 else y), m, d +end +local function daysFrom(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = if m > 2 then m - 3 else m + 9 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end + +-- Unix seconds -> DOS time, date (clamped to 1980..2107) +function Zip.dosTime(t: number?): (number, number) + if type(t) ~= "number" or t ~= t then + return 0, 0x21 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = civil(days) + if y < 1980 then + return 0, 0x21 + elseif y > 2107 then + y, m, d, rem = 2107, 12, 31, 86399 + end + local time = (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 + return time, (y - 1980) * 512 + m * 32 + d +end + +-- DOS time, date -> Unix seconds (UTC) +function Zip.unixTime(time: number, date: number): number + local y = 1980 + bit32.rshift(date, 9) + local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12) + local d = math.clamp(bit32.band(date, 31), 1, 31) + return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +local function isAscii(s: string): boolean + return string.find(s, "[\128-\255]") == nil +end + +-- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) +function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?) + if type(name) ~= "string" or name == "" or #name > 65535 then + return false, Err.new(Err.ARG, "add: bad entry name") + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + elseif data == nil and string.sub(name, -1) == "/" then + b = buffer.create(0) + else + return false, Err.new(Err.ARG, "add: data must be a buffer or a string") + end + local o: AddOptions = opts or {} + local method = o.method or "deflate" + if method ~= "deflate" and method ~= "store" then + return false, Err.new(Err.ARG, "add: method must be deflate or store") + end + local isDir = string.sub(name, -1) == "/" + local n = buffer.len(b) + local comp, code = b, 0 + if method == "deflate" and n > 0 and not isDir then + local z, zerr = Deflate.compress(b, { level = o.level or 6 }) + if not z then + return false, zerr + end + if buffer.len(z) < n then + comp, code = z, 8 + end + end + local time, date = Zip.dosTime(o.mtime) + table.insert(self.files, { + name = name, + method = code, + crc = if n > 0 then Crc32.of(b) else 0, + size = n, + data = comp, + dataOffset = 0, + dataLength = buffer.len(comp), + time = time, + date = date, + comment = o.comment or "", + utf8 = if o.utf8 ~= nil then o.utf8 else not isAscii(name), + attributes = o.attributes or (if isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err +function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?) + local b = archive.buf + local start: number? = nil + for _, s in Zip._starts(b, e) do + if s >= 0 and s + e.compressedSize <= buffer.len(b) then + start = s + break + end + end + if not start or bit32.band(e.flags, 1) ~= 0 then + return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data") + end + local name = newName or e.name + table.insert(self.files, { + name = name, + method = e.method, + crc = e.crc32, + size = e.size, + data = b, + dataOffset = start, + dataLength = e.compressedSize, + time = e.time or 0, + date = e.date or 0x21, + comment = e.comment or "", + utf8 = e.utf8 or not isAscii(name), + attributes = e.attributes or (if e.isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- finish(opts?) -> the archive | nil, Err +function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?) + local comment = opts and opts.comment or "" + if #comment > 65535 then + return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes") + end + local force = opts and opts.zip64 or false + local total = 22 + #comment + 98 + for _, f in self.files do + total += 30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment + end + if total > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB") + end + local w = Bytes.writer(total) + local offsets = {} + for i, f in self.files do + local off = w:tell() + offsets[i] = off + local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local flags = if f.utf8 then 0x800 else 0 + w:u32le(SIG_LOCAL) + w:u16le(if big then 45 else 20) + w:u16le(flags) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if big then 0xFFFFFFFF else f.dataLength) + w:u32le(if big then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if big then 20 else 0) + w:string(f.name) + if big then + w:u16le(1) + w:u16le(16) + w:u64le(f.size) + w:u64le(f.dataLength) + end + w:bytes(f.data, f.dataOffset, f.dataLength) + end + local cdOff = w:tell() + for i, f in self.files do + local off = offsets[i] + local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local bigOff = force or off >= 0xFFFFFFFF + local extra = (if bigSize then 16 else 0) + (if bigOff then 8 else 0) + local version = if bigSize or bigOff then 45 else 20 + w:u32le(SIG_CD) + w:u16le(0x0300 + version) -- made by: Unix + w:u16le(version) + w:u16le(if f.utf8 then 0x800 else 0) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if bigSize then 0xFFFFFFFF else f.dataLength) + w:u32le(if bigSize then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if extra > 0 then extra + 4 else 0) + w:u16le(#f.comment) + w:u16le(0) -- disk + w:u16le(0) -- internal attributes + w:u32le(f.attributes) + w:u32le(if bigOff then 0xFFFFFFFF else off) + w:string(f.name) + if extra > 0 then + w:u16le(1) + w:u16le(extra) + if bigSize then + w:u64le(f.size) + w:u64le(f.dataLength) + end + if bigOff then + w:u64le(off) + end + end + w:string(f.comment) + end + local cdSize = w:tell() - cdOff + local count = #self.files + local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF + if z64 then + local rec = w:tell() + w:u32le(SIG_Z64_EOCD) + w:u64le(44) + w:u16le(0x032D) + w:u16le(45) + w:u32le(0) + w:u32le(0) + w:u64le(count) + w:u64le(count) + w:u64le(cdSize) + w:u64le(cdOff) + w:u32le(SIG_Z64_LOC) + w:u32le(0) + w:u64le(rec) + w:u32le(1) + end + w:u32le(SIG_EOCD) + w:u16le(0) + w:u16le(0) + w:u16le(if z64 then 0xFFFF else count) + w:u16le(if z64 then 0xFFFF else count) + w:u32le(if z64 then 0xFFFFFFFF else cdSize) + w:u32le(if z64 then 0xFFFFFFFF else cdOff) + w:u16le(#comment) + w:string(comment) + return w:finish(), nil +end + +return Zip diff --git a/src/Formats/image/bmp/Pixels.luau b/src/Formats/image/bmp/Pixels.luau new file mode 100644 index 0000000..331b198 --- /dev/null +++ b/src/Formats/image/bmp/Pixels.luau @@ -0,0 +1,247 @@ +--!strict +--!native +--!optimize 2 +-- image/bmp/Pixels: the pixel loops (native), decode and encode. Absorbed from bmp-luau b86aed6 (same author, no +-- third-party code); the encoder loops are new. They never throw: the caller (init.luau) validates every size first, and +-- hands in a source buffer that holds every byte an uncompressed loop can read (a truncated file is copied into a +-- zero-padded buffer). The RLE loop checks each read against its end offset. Output: RGBA8, top-down rows, one +-- u32 per pixel (R | G << 8 | B << 16 | A << 24, little-endian = bytes R, G, B, A). +local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift + +local Pixels = {} + +-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) +function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer) + local mask = lshift(1, bpp) - 1 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + if bpp == 8 then + for x = 0, w - 1 do + writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4)) + end + elseif bpp == 4 then + for x = 0, w - 1 do + local b = readu8(src, so + rshift(x, 1)) + local i = if band(x, 1) == 0 then rshift(b, 4) else band(b, 15) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + else + for x = 0, w - 1 do + local bit = x * bpp + local b = readu8(src, so + rshift(bit, 3)) + local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + end + end +end + +-- 24 bpp BI_RGB: B, G, R +function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = so + x * 3 + writeu32(dst, d + x * 4, + bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000)) + end + end +end + +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, + topDown: boolean): number + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local p = readu32(src, so + x * 4) + -- swap R and B: B G R A -> R G B A + writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) + aor = bor(aor, p) + end + end + return rshift(aor, 24) +end + +-- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry +-- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). +-- Returns the OR of every masked alpha value (before scaling). +function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, + mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number + local bytes = rshift(bpp, 3) + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = so + x * bytes + local p + if bytes == 2 then + p = readu16(src, s) + elseif bytes == 4 then + p = readu32(src, s) + else + p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16)) + end + local a = band(rshift(p, sha), ma) + aor = bor(aor, a) + local o = d + x * 4 + writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr))) + writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg))) + writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb))) + writeu8(dst, o + 3, readu8(ta, a)) + end + end + return aor +end + +-- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +function Pixels.opaque(dst: buffer, n: number) + for i = 0, n - 1 do + writeu8(dst, i * 4 + 3, 255) + end +end + +-- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a +-- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the +-- decode and keeps what was drawn. Returns the number of pixels written. +function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer): number + local x, y = 0, 0 + local written = 0 + local row = (if topDown then 0 else h - 1) * w * 4 + local rowStep = if topDown then w * 4 else -w * 4 + while y < h and pos + 1 < stop do + local n = readu8(src, pos) + local v = readu8(src, pos + 1) + pos += 2 + if n > 0 then + -- encoded run: n pixels of index v (RLE4: alternating high / low nibble) + local e = math.min(x + n, w) + if rle4 then + local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, if band(i - x, 1) == 0 then hi else lo) + end + else + local c = readu32(pal, v * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, c) + end + end + if e > x then + written += e - x + end + x += n + elseif v == 0 then + -- end of line + x = 0 + y += 1 + row += rowStep + elseif v == 1 then + break -- end of bitmap + elseif v == 2 then + -- delta: right dx, up (in file rows) dy + if pos + 1 >= stop then + break + end + local dx, dy = readu8(src, pos), readu8(src, pos + 1) + pos += 2 + x += dx + y += dy + row += rowStep * dy + else + -- absolute run of v pixels, padded to a 16-bit boundary + local nb = if rle4 then rshift(v + 1, 1) else v + if pos + nb > stop then + break + end + local e = math.min(x + v, w) + for i = x, e - 1 do + local k = i - x + local idx + if rle4 then + local b = readu8(src, pos + rshift(k, 1)) + idx = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + else + idx = readu8(src, pos + k) + end + writeu32(dst, row + i * 4, readu32(pal, idx * 4)) + end + if e > x then + written += e - x + end + x += v + pos += nb + band(nb, 1) + end + end + return written +end + +-- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) +function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + writeu8(dst, d, band(rshift(v, 16), 255)) + writeu8(dst, d + 1, band(rshift(v, 8), 255)) + writeu8(dst, d + 2, band(v, 255)) + d += 3 + end + end +end + +-- rgba8 -> 32 bpp BGRA, bottom-up +function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * w * 4 + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A + writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) + end + end +end + +-- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up +function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0) + end + end +end + +-- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any +-- alpha is below 255; stops counting at max + 1 colours +function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) + local seen: { [number]: boolean } = {} + local list: { number } = {} + local alpha = false + for i = 0, n - 1 do + local v = readu32(src, i * 4) + if v < 0xFF000000 then + alpha = true + end + local c = band(v, 0xFFFFFF) + if #list <= max and not seen[c] then + seen[c] = true + list[#list + 1] = c + end + end + return list, alpha +end + +return Pixels diff --git a/src/Formats/image/bmp/init.luau b/src/Formats/image/bmp/init.luau new file mode 100644 index 0000000..335b8e8 --- /dev/null +++ b/src/Formats/image/bmp/init.luau @@ -0,0 +1,424 @@ +--!strict +--!optimize 2 +-- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a +-- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3 +-- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or +-- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap), +-- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the +-- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit +-- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max). +-- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance +-- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with +-- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output. +-- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pixels = require("@formats/image/bmp/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmp = { + name = "bmp", + category = "image", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Info = { + width: number, + height: number, + bitsPerPixel: number, + compression: number, + topDown: boolean, + headerSize: number, + os2: boolean, +} + +export type DecodeOptions = { + maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx) +} +export type EncodeOptions = { + bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32 + header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAX_PIXELS = 2 ^ 26 +local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "png", "alphabitfields" } + +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz + +-- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer) +local function whole(r: Bytes.Reader): buffer + if r.base == 0 and r.limit == buffer.len(r.buf) then + return r.buf + end + local n = r.limit - r.base + local b = buffer.create(n) + buffer.copy(b, 0, r.buf, r.base, n) + return b +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmp.sniff(r: Bytes.Reader): number + if r:peek(2) ~= "BM" then + return 0 + end + -- a known header size: a strong match; "BM" alone is weak + local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 + if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err +local function parseHeader(buf: buffer): (Info?, any) + local n = buffer.len(buf) + if n < 18 then + return nil, Err.new(Err.TRUNCATED, "file too short") + end + if readu8(buf, 0) ~= 0x42 or readu8(buf, 1) ~= 0x4D then + return nil, Err.new(Err.CORRUPT, "not a BMP file (no BM signature)") + end + local hs = readu32(buf, 14) + if hs < 12 or 14 + hs > n then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + local info: Info = { + width = 0, + height = 0, + bitsPerPixel = 0, + compression = 0, + topDown = false, + headerSize = hs, + os2 = false, + } + if hs == 12 then + info.width = readu16(buf, 18) + info.height = readu16(buf, 20) + info.bitsPerPixel = readu16(buf, 24) + info.os2 = true + else + if hs < 16 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + info.width = readi32(buf, 18) + local h = readi32(buf, 22) + info.bitsPerPixel = readu16(buf, 28) + if hs >= 20 then + info.compression = readu32(buf, 30) + end + if h < 0 then + info.topDown = true + h = -h + end + info.height = h + -- OS/2 2.x headers: 16 / 64 bytes, or any size that is not a Windows one + info.os2 = not (hs == 40 or hs == 52 or hs == 56 or hs == 108 or hs == 124) + end + return info +end + +-- info(r) -> Info | nil, Err: the header without decoding the pixels +function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?) + return parseHeader(whole(r)) +end + +-- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate +-- the top bits instead, which can differ by 1). m = 0 -> { empty }. +local function scaleTable(m: number, empty: number): buffer + local t = buffer.create(m + 1) + if m == 0 then + buffer.writeu8(t, 0, empty) + else + for v = 0, m do + buffer.writeu8(t, v, (v * 255) // m) + end + end + return t +end + +-- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16) +local function channel(mask: number, empty: number): (number, number, buffer) + if mask == 0 then + return 0, 0, scaleTable(0, empty) + end + local sh = countrz(mask) + local m = rshift(mask, sh) + -- holes in the mask: use the lowest contiguous run of bits + local bits = 0 + while bits < 32 and band(m, lshift(1, bits)) ~= 0 do + bits += 1 + end + if bits > 16 then + sh += bits - 16 + bits = 16 + end + m = lshift(1, bits) - 1 + return sh, m, scaleTable(m, empty) +end + +-- decode(r, opts?) -> rgba8 Image | nil, Err +function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local buf = whole(r) + local info, herr = parseHeader(buf) + if not info then + return nil, herr + end + local n = buffer.len(buf) + local hs, w, h, bpp, comp = info.headerSize, info.width, info.height, info.bitsPerPixel, info.compression + if w <= 0 or h <= 0 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. "x" .. h) + end + local maxPixels = (opts and opts.maxPixels) or MAX_PIXELS + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "image too large (" .. w .. "x" .. h .. ")") + end + if info.os2 and hs ~= 12 and (comp == 3 or comp == 4) then + return nil, Err.new(Err.UNSUPPORTED, "OS/2 Huffman / RLE24 compression is not supported") + end + if comp == 4 or comp == 5 then + return nil, Err.new(Err.UNSUPPORTED, "embedded " .. (if comp == 4 then "JPEG" else "PNG") .. " is not supported") + end + if comp > 6 then + return nil, Err.new(Err.CORRUPT, "unknown compression " .. comp) + end + local valid = (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 or bpp == 16 or bpp == 24 or bpp == 32) + if not valid then + return nil, Err.new(Err.CORRUPT, "unsupported bit depth " .. bpp) + end + if (comp == 1 and bpp ~= 8) or (comp == 2 and bpp ~= 4) then + return nil, Err.new(Err.CORRUPT, "RLE compression " .. comp .. " with " .. bpp .. " bpp") + end + if (comp == 3 or comp == 6) and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + return nil, Err.new(Err.CORRUPT, "BITFIELDS with " .. bpp .. " bpp") + end + + -- masks: in the v2+ header, or right after a 40-byte header + local palStart = 14 + hs + local rm: number, gm: number, bm: number, am: number = 0, 0, 0, 0 + local hasMasks = false + if comp == 3 or comp == 6 then + hasMasks = true + if hs >= 52 then + rm, gm, bm = readu32(buf, 54), readu32(buf, 58), readu32(buf, 62) + if hs >= 56 then + am = readu32(buf, 66) + end + else + local count = if comp == 6 then 4 else 3 + if palStart + count * 4 > n then + return nil, Err.new(Err.TRUNCATED, "truncated bit masks") + end + rm, gm, bm = readu32(buf, palStart), readu32(buf, palStart + 4), readu32(buf, palStart + 8) + if comp == 6 then + am = readu32(buf, palStart + 12) + end + palStart += count * 4 + end + if comp == 3 and hs < 56 then + am = 0 + end + if rm == 0 and gm == 0 and bm == 0 then + hasMasks = false -- all-zero masks: use the defaults + end + end + + -- palette + local entrySize = if hs == 12 then 3 else 4 + local declared = if hs >= 36 then readu32(buf, 46) else 0 + local palCount = 0 + if bpp <= 8 then + palCount = if declared == 0 or declared > lshift(1, bpp) then lshift(1, bpp) else declared + end + local off = readu32(buf, 10) + local pixelEnd = palStart + palCount * entrySize + if off < palStart or off >= n then + -- bad bfOffBits: the pixels start after the palette as declared + off = math.min(pixelEnd, n) + elseif bpp <= 8 and off < pixelEnd then + -- palette shorter than declared: it ends where the pixels start + palCount = (off - palStart) // entrySize + end + palCount = math.max(0, math.min(palCount, (n - palStart) // entrySize)) + local pal = buffer.create(256 * 4) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + for i = 0, palCount - 1 do + local p = palStart + i * entrySize + local bb, gg, rr = readu8(buf, p), readu8(buf, p + 1), readu8(buf, p + 2) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + + local img = Types.Image.new(w, h, "rgba8") + local pixels = img.pixels + img.meta.source = { + format = "bmp", + bitDepth = bpp, + compression = COMPRESSION_NAMES[comp], + topDown = info.topDown, + headerSize = hs, + paletteSize = palCount, + os2 = info.os2, + } + if bpp <= 8 and palCount > 0 then + local palette: { { number } } = {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), 255 } + end + img.meta.palette = palette + end + if hs >= 40 then + local xp, yp = readi32(buf, 38), readi32(buf, 42) + if xp > 0 and yp > 0 then + img.meta.dpi = { x = xp * 0.0254, y = yp * 0.0254 } + end + end + + if comp == 1 or comp == 2 then + Pixels.rle(buf, off, n, comp == 2, pixels, w, h, info.topDown, pal) + return img, nil + end + + -- uncompressed: make sure every row is readable (a truncated file reads as zeros) + local stride = ((w * bpp + 31) // 32) * 4 + local need = stride * h + local src, base = buf, off + if off + need > n then + src = buffer.create(need) + buffer.copy(src, 0, buf, off, n - off) + base = 0 + end + + if bpp <= 8 then + Pixels.indexed(src, base, stride, bpp, pixels, w, h, info.topDown, pal) + elseif bpp == 24 and not hasMasks then + Pixels.bgr24(src, base, stride, pixels, w, h, info.topDown) + elseif bpp == 32 and (not hasMasks or (rm == 0xFF0000 and gm == 0xFF00 and bm == 0xFF and (am == 0xFF000000 or am == 0))) then + local aor = Pixels.bgra32(src, base, stride, pixels, w, h, info.topDown) + if aor == 0 or (hasMasks and am == 0) then + Pixels.opaque(pixels, w * h) + end + else + if not hasMasks then + if bpp == 16 then + rm, gm, bm, am = 0x7C00, 0x3E0, 0x1F, 0 + else + rm, gm, bm, am = 0xFF0000, 0xFF00, 0xFF, 0 + end + end + local shr, mr, tr = channel(rm, 0) + local shg, mg, tg = channel(gm, 0) + local shb, mb, tb = channel(bm, 0) + local sha, ma, ta = channel(am, 255) + local aor = + Pixels.masked(src, base, stride, bpp, pixels, w, h, info.topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta) + if ma ~= 0 and aor == 0 then + Pixels.opaque(pixels, w * h) + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(img, opts?) -> buffer | nil, Err +function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 0x7FFFFFFF or h > 0x7FFFFFFF then + return nil, Err.new(Err.ARG, "encode: bad image size") + end + if buffer.len(img.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "encode: the pixel buffer is smaller than width * height * 4") + end + local want = opts and opts.bitDepth or "auto" + if want ~= "auto" and want ~= 8 and want ~= 24 and want ~= 32 then + return nil, Err.new(Err.ARG, "encode: bitDepth must be 8, 24, 32 or auto") + end + local headerKind = opts and opts.header or "v4" + if headerKind ~= "v4" and headerKind ~= "info" then + return nil, Err.new(Err.ARG, "encode: header must be v4 or info") + end + local colours, alpha = Pixels.colours(img.pixels, w * h, 256) + local bpp: number + if want == "auto" then + bpp = if alpha then 32 elseif #colours <= 256 then 8 else 24 + else + bpp = want :: number + if bpp == 8 and #colours > 256 then + return nil, Err.new(Err.ARG, "encode: more than 256 colours for 8 bpp") + end + end + local v4 = bpp == 32 and headerKind == "v4" + local hs = if v4 then 108 else 40 + local stride = ((w * bpp + 31) // 32) * 4 + local palCount = if bpp == 8 then #colours else 0 + local off = 14 + hs + palCount * 4 + local imageSize = stride * h + if off + imageSize > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "encode: the file would be over 1 GiB") + end + local out = buffer.create(off + imageSize) + local o = Bytes.writer(off) + o:string("BM") + o:u32le(off + imageSize) + o:u32le(0) + o:u32le(off) + o:u32le(hs) + o:i32le(w) + o:i32le(h) + o:u16le(1) + o:u16le(bpp) + o:u32le(if v4 then 3 else 0) -- BI_BITFIELDS / BI_RGB + o:u32le(imageSize) + local dpi = img.meta and img.meta.dpi + local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + xp, yp = math.floor((dpi.x :: number) * 39.3701 + 0.5), math.floor((dpi.y :: number) * 39.3701 + 0.5) + end + o:i32le(xp) + o:i32le(yp) + o:u32le(palCount) + o:u32le(palCount) + if v4 then + o:u32le(0x00FF0000) + o:u32le(0x0000FF00) + o:u32le(0x000000FF) + o:u32le(0xFF000000) + o:string("BGRs") -- LCS_sRGB (stored little-endian: 'sRGB') + o:fill(0, 36 + 12) -- endpoints, gamma + end + local idx: { [number]: number } = {} + for i, c in colours do + if i > palCount then + break + end + idx[c] = i - 1 + o:u8(band(rshift(c, 16), 255)) + o:u8(band(rshift(c, 8), 255)) + o:u8(band(c, 255)) + o:u8(0) + end + buffer.copy(out, 0, o.buf, 0, off) + if bpp == 8 then + Pixels.encode8(img.pixels, w, h, out, off, stride, idx) + elseif bpp == 24 then + Pixels.encode24(img.pixels, w, h, out, off, stride) + else + Pixels.encode32(img.pixels, w, h, out, off) + end + return out, nil +end + +return Bmp diff --git a/src/Formats/image/png/Apng.luau b/src/Formats/image/png/Apng.luau new file mode 100644 index 0000000..32c0551 --- /dev/null +++ b/src/Formats/image/png/Apng.luau @@ -0,0 +1,82 @@ +--!strict +--!native +--!optimize 2 +-- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source / +-- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the +-- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle. +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Apng = {} + +local function div255(x: number): number + return (x + 128) * 257 // 65536 +end + +-- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas +local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) + for y = 0, fh - 1 do + local so = y * fw * 4 + local co = ((fy + y) * cw + fx) * 4 + if not over then + bcopy(canvas, co, src, so, fw * 4) + else + for x = 0, fw - 1 do + local s, c = so + x * 4, co + x * 4 + local fa = readu8(src, s + 3) + if fa == 255 then + writeu32(canvas, c, readu32(src, s)) + elseif fa ~= 0 then + local ba = readu8(canvas, c + 3) + local oa = fa + div255((255 - fa) * ba) + if ba == 255 then + for k = 0, 2 do + writeu8(canvas, c + k, div255(fa * readu8(src, s + k) + (255 - fa) * readu8(canvas, c + k))) + end + else + local den = 255 * oa + for k = 0, 2 do + writeu8(canvas, c + k, (255 * fa * readu8(src, s + k) + (255 - fa) * ba * readu8(canvas, c + k)) // den) + end + end + writeu8(canvas, c + 3, oa) + end + end + end + end +end + +-- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend }) +function Apng.composite(w: number, h: number, frames: { any }): { buffer } + local canvas = bcreate(w * h * 4) + local saved = bcreate(w * h * 4) + local out: { buffer } = {} + for i, f in frames do + local fi = f.image + local fw, fh = fi.width, fi.height + local dispose, over = f.dispose, f.blend == "over" + if i == 1 then + over = false -- the canvas starts transparent black: source and over differ only in hidden colour + if dispose == "previous" then + dispose = "background" + end + end + if dispose == "previous" then + bcopy(saved, 0, canvas, 0) + end + blend(canvas, w, fi.pixels, fw, fh, f.x, f.y, over) + local snap = bcreate(w * h * 4) + bcopy(snap, 0, canvas, 0) + out[i] = snap + if dispose == "background" then + for y = 0, fh - 1 do + bfill(canvas, ((f.y + y) * w + f.x) * 4, 0, fw * 4) + end + elseif dispose == "previous" then + bcopy(canvas, 0, saved, 0) + end + end + return out +end + +return Apng diff --git a/src/Formats/image/png/init.luau b/src/Formats/image/png/init.luau index f29ea0f..5c42219 100644 --- a/src/Formats/image/png/init.luau +++ b/src/Formats/image/png/init.luau @@ -3,7 +3,11 @@ -- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), -- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha -- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). --- Not supported: APNG animation (the default image is decoded), colour management (gAMA / cHRM / sRGB / iCCP are +-- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose / +-- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not +-- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode +-- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked. +-- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are -- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. -- ------------------------------------------------------------------------------------------------ requires @@ -14,6 +18,7 @@ local Deflate = require("@formats/codecs/Deflate") local Types = require("@formats/Types") local Decode = require("@formats/image/png/Decode") local Encode = require("@formats/image/png/Encode") +local Apng = require("@formats/image/png/Apng") -- ------------------------------------------------------------------------------------------------ contract local Png = { @@ -22,7 +27,7 @@ local Png = { extensions = { "png", "apng" }, mime = { "image/png", "image/apng" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" }, - caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } }, + caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } }, } export type DecodeOptions = { @@ -32,6 +37,8 @@ export type DecodeOptions = { export type EncodeOptions = { level: number?, -- deflate level 0..9 (default 6) colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one + apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when + -- img.frames is a non-empty list } -- ------------------------------------------------------------------------------------------------ constants @@ -95,6 +102,66 @@ function Png.info(r: Bytes.Reader): (Header?, Err.Err?) return header(r) end +type FrameControl = { + width: number, + height: number, + x: number, + y: number, + num: number, + den: number, + dispose: number, + blend: number, + chunks: { { number } }, -- fdAT payloads: offset, length + len: number, +} +local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" } + +-- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split +-- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h) +local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err? + -- the inflated size: every (pass) row has a filter byte + local channels = Decode.CHANNELS[ct] + local expected = 0 + if interlace == 0 then + expected = ht * (Decode.rowBytes(w, channels, depth) + 1) + else + for _, pass in Decode.PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + expected += ph * (Decode.rowBytes(pw, channels, depth) + 1) + end + end + end + local z: buffer + if #chunks == 1 then + z = b + else + z = buffer.create(total) + local w0 = 0 + for _, c in chunks do + buffer.copy(z, w0, b, c[1], c[2]) + w0 += c[2] + end + end + local zo = if #chunks == 1 then chunks[1][1] else 0 + local raw, zerr = Deflate.zlib(z, zo, total, expected) + if not raw then + -- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows + local loose = Deflate.zlib(z, zo, total) + if not loose or buffer.len(loose) < expected then + return zerr or Err.new(Err.CORRUPT, "bad image data") + end + raw = loose + end + local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, interlace, pal, tr, out) + if not ok then + return Err.new(Err.CORRUPT, tostring(derr)) + end + return nil +end + function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) local checkCrc = opts and opts.checkCrc or false local maxPixels = opts and opts.maxPixels or 2 ^ 26 @@ -118,6 +185,12 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local idatLen = 0 local text: { [string]: string } = {} local iccCompressed: buffer? = nil + -- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter + local plays: number? = nil + local fctls: { FrameControl } = {} + local seq = 0 + local idatInAnim = false + local animPixels = 0 local p = r.base + 8 local first = true while p + 12 <= n do @@ -162,6 +235,9 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E elseif typ == "IDAT" then table.insert(idat, { d, len }) idatLen += len + if #fctls == 1 and #idat == 1 then + idatInAnim = true + end elseif typ == "tEXt" then local s = buffer.readstring(b, d, len) local z = string.find(s, "\0", 1, true) @@ -172,6 +248,58 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local cb = buffer.create(len) buffer.copy(cb, 0, b, d, len) iccCompressed = cb + elseif typ == "acTL" then + if len >= 8 and plays == nil and #idat == 0 then + plays = be32(b, d + 4) + end + elseif typ == "fcTL" and plays ~= nil then + if len < 26 then + return nil, Err.new(Err.CORRUPT, "short fcTL", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fcTL sequence %d, expected %d", be32(b, d), seq), p) + end + seq += 1 + local f: FrameControl = { + width = be32(b, d + 4), + height = be32(b, d + 8), + x = be32(b, d + 12), + y = be32(b, d + 16), + num = readu8(b, d + 20) * 256 + readu8(b, d + 21), + den = readu8(b, d + 22) * 256 + readu8(b, d + 23), + dispose = readu8(b, d + 24), + blend = readu8(b, d + 25), + chunks = {}, + len = 0, + } + if f.width == 0 or f.height == 0 or f.x + f.width > w or f.y + f.height > ht then + return nil, Err.new(Err.CORRUPT, "fcTL frame outside the image", p) + end + if f.dispose > 2 or f.blend > 1 then + return nil, Err.new(Err.CORRUPT, "bad fcTL dispose / blend op", p) + end + if #idat == 0 and (f.width ~= w or f.height ~= ht or f.x ~= 0 or f.y ~= 0) then + return nil, Err.new(Err.CORRUPT, "the fcTL before IDAT must cover the image", p) + end + animPixels += f.width * f.height + if animPixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("the animation frames are over the %d pixel limit", maxPixels)) + end + table.insert(fctls, f) + elseif typ == "fdAT" and plays ~= nil then + if len < 4 then + return nil, Err.new(Err.CORRUPT, "short fdAT", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fdAT sequence %d, expected %d", be32(b, d), seq), p) + end + seq += 1 + local f = fctls[#fctls] + if not f or (#fctls == 1 and idatInAnim) then + return nil, Err.new(Err.CORRUPT, "fdAT without its fcTL", p) + end + table.insert(f.chunks, { d + 4, len - 4 }) + f.len += len - 4 elseif typ == "IEND" then break -- a missing IEND is tolerated (truncated tail after the data) elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then @@ -185,46 +313,45 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if ct == 3 and palCount == 0 then return nil, Err.new(Err.CORRUPT, "palette image without PLTE") end - -- the inflated size: every (pass) row has a filter byte - local channels = Decode.CHANNELS[ct] - local expected = 0 - if h.interlace == 0 then - expected = ht * (Decode.rowBytes(w, channels, depth) + 1) - else - for _, pass in Decode.PASSES do - local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] - local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 - local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0 - if pw > 0 and ph > 0 then - expected += ph * (Decode.rowBytes(pw, channels, depth) + 1) - end - end - end - local z: buffer - if #idat == 1 then - z = b - else - z = buffer.create(idatLen) - local w0 = 0 - for _, c in idat do - buffer.copy(z, w0, b, c[1], c[2]) - w0 += c[2] - end - end - local zo, zl = if #idat == 1 then idat[1][1] else 0, idatLen - local raw, zerr = Deflate.zlib(z, zo, zl, expected) - if not raw then - -- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows - local loose = Deflate.zlib(z, zo, zl) - if not loose or buffer.len(loose) < expected then - return nil, zerr - end - raw = loose - end local img = Types.Image.new(w, ht, "rgba8") - local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, h.interlace, pal, tr, img.pixels) - if not ok then - return nil, Err.new(Err.CORRUPT, tostring(derr)) + local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels) + if ierr then + return nil, ierr + end + if plays ~= nil and #fctls > 0 then + local last = fctls[#fctls] + if #fctls > 1 and #last.chunks == 0 then + fctls[#fctls] = nil -- a truncated file: the last frame never got its data + end + local frames: { Types.Frame } = {} + for i, f in fctls do + local fimg: Types.Image + if i == 1 and idatInAnim then + fimg = Types.Image.new(w, ht, "rgba8") + buffer.copy(fimg.pixels, 0, img.pixels) + else + if #f.chunks == 0 then + return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data") + end + fimg = Types.Image.new(f.width, f.height, "rgba8") + local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels) + if ferr then + ferr.message = "frame " .. i .. ": " .. ferr.message + return nil, ferr + end + end + frames[i] = { + image = fimg, + delay = f.num / (if f.den == 0 then 100 else f.den), + x = f.x, + y = f.y, + dispose = DISPOSE[f.dispose] :: any, + blend = if f.blend == 1 then "over" :: "over" else "source" :: "source", + } + end + img.frames = frames + img.loops = plays + img.meta.apngDefaultHidden = not idatInAnim end if ct == 3 then local palette: { { number } } = {} @@ -243,37 +370,131 @@ end -- ------------------------------------------------------------------------------------------------ encode local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } +local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 } +local BLEND_CODES: { [string]: number } = { source = 0, over = 1 } + +-- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds +local function delayFraction(delay: number): (number, number) + for den = 1, 1000 do + local num = math.floor(delay * den + 0.5) + if num > 65535 then + break + end + if math.abs(num / den - delay) < 1e-9 then + return num, den + end + end + if delay * 1000 <= 65535 then + return math.floor(delay * 1000 + 0.5), 1000 + elseif delay * 100 <= 65535 then + return math.floor(delay * 100 + 0.5), 100 + end + return math.min(65535, math.floor(delay + 0.5)), 1 +end + +local function validImage(im: any): boolean + return type(im) == "table" + and im.format == "rgba8" + and type(im.pixels) == "buffer" + and type(im.width) == "number" + and type(im.height) == "number" + and im.width >= 1 + and im.height >= 1 + and im.width % 1 == 0 + and im.height % 1 == 0 + and buffer.len(im.pixels) >= im.width * im.height * 4 +end + +-- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list +local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?) + local frames = img.frames + local mode = if opts then opts.apng else nil + if mode == false then + return nil, nil + end + if frames ~= nil and type(frames) ~= "table" then + return nil, Err.new(Err.ARG, "png encode: frames must be a list") + end + if frames == nil or #frames == 0 then + if mode then + return { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: any }, nil + end + return nil, nil + end + for i, f in frames do + local label = "png encode: frame " .. i + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, label .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x % 1 ~= 0 or y % 1 ~= 0 or x + f.image.width > img.width or y + f.image.height > img.height then + return nil, Err.new(Err.ARG, label .. ": rectangle outside the image") + end + if f.delay ~= nil and (type(f.delay) ~= "number" or not (f.delay >= 0)) then + return nil, Err.new(Err.ARG, label .. ": bad delay") + end + if f.dispose ~= nil and DISPOSE_CODES[f.dispose] == nil then + return nil, Err.new(Err.ARG, label .. ": bad dispose " .. tostring(f.dispose)) + end + if f.blend ~= nil and BLEND_CODES[f.blend] == nil then + return nil, Err.new(Err.ARG, label .. ": bad blend " .. tostring(f.blend)) + end + end + return frames, nil +end function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) - if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + if not validImage(img) then return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image") end local w, h = img.width, img.height - if w < 1 or h < 1 or buffer.len(img.pixels) < w * h * 4 then - return nil, Err.new(Err.ARG, "png encode: bad image size or pixel buffer") - end local level = opts and opts.level or 6 if type(level) ~= "number" or level < 0 or level > 9 then return nil, Err.new(Err.ARG, "png encode: level must be 0..9") end + local frames, ferr = animationFrames(img, opts) + if ferr then + return nil, ferr + end + local loops = img.loops or 0 + if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then + return nil, Err.new(Err.ARG, "png encode: loops must be an integer 0..2^32-1") + end local want = opts and opts.colorType or "auto" local ctName: string = want if want == "auto" then - ctName = Encode.pickColorType(img.pixels, w, h) + -- the smallest colour type that holds the image and every frame + local alpha, color = false, false + local function scan(im: Types.Image) + local c = Encode.pickColorType(im.pixels, im.width, im.height) + alpha = alpha or c == "rgba" or c == "graya" + color = color or c == "rgba" or c == "rgb" + end + scan(img) + if frames then + for _, f in frames do + scan(f.image) + end + end + ctName = if color then (if alpha then "rgba" else "rgb") else (if alpha then "graya" else "gray") end local ct = CT_CODES[ctName] if ct == nil then return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want)) end - local raw = Encode.filter(img.pixels, w, h, ct) - local z = Deflate.zlibCompress(raw, { level = level }) :: buffer + local function zdata(im: Types.Image): buffer + return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer + end - local out = Bytes.writer(buffer.len(z) + 128) - local function chunk(typ: string, data: buffer?) - local len = if data then buffer.len(data) else 0 + local out = Bytes.writer(w * h + 128) + local function chunk(typ: string, data: buffer?, prefix: number?) + local len = (if data then buffer.len(data) else 0) + (if prefix then 4 else 0) out:u32be(len) local start = out:tell() out:string(typ) + if prefix then + out:u32be(prefix) + end if data then out:bytes(data) end @@ -289,6 +510,12 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) ihdr:u8(0) ihdr:u8(0) chunk("IHDR", ihdr:finish()) + if frames then + local actl = Bytes.writer(8) + actl:u32be(#frames) + actl:u32be(loops) + chunk("acTL", actl:finish()) + end if img.meta and img.meta.text then for k, v in img.meta.text do local t = Bytes.writer() @@ -298,9 +525,70 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) chunk("tEXt", t:finish()) end end - chunk("IDAT", z) + if not frames then + chunk("IDAT", zdata(img)) + chunk("IEND", nil) + return out:finish(), nil + end + -- frame 1 is the default image when it covers the canvas with the same pixels; otherwise the default image is + -- written first, outside the animation + local f1 = frames[1] + local f1i = f1.image + local inAnim = f1i == img + or ((f1.x or 0) == 0 and (f1.y or 0) == 0 and f1i.width == w and f1i.height == h and buffer.len(f1i.pixels) >= w * h * 4 and buffer.readstring(f1i.pixels, 0, w * h * 4) == buffer.readstring(img.pixels, 0, w * h * 4)) + local seq = 0 + if not inAnim then + chunk("IDAT", zdata(img)) + end + for i, f in frames do + local fi = f.image + local num, den = delayFraction(f.delay or 0) + local fc = Bytes.writer(26) + fc:u32be(seq) + fc:u32be(fi.width) + fc:u32be(fi.height) + fc:u32be(f.x or 0) + fc:u32be(f.y or 0) + fc:u16be(num) + fc:u16be(den) + fc:u8(DISPOSE_CODES[f.dispose or "none"]) + fc:u8(BLEND_CODES[f.blend or "source"]) + chunk("fcTL", fc:finish()) + seq += 1 + if i == 1 and inAnim then + chunk("IDAT", zdata(img)) + else + chunk("fdAT", zdata(fi), seq) + seq += 1 + end + end chunk("IEND", nil) return out:finish(), nil end +-- ------------------------------------------------------------------------------------------------ extras +-- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a +-- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }. +function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") + end + local frames, ferr = animationFrames(img, { apng = true }) + if not frames then + return nil, ferr + end + local w, h = img.width, img.height + local list = {} + for i, f in frames do + list[i] = { image = f.image, x = f.x or 0, y = f.y or 0, dispose = f.dispose or "none", blend = f.blend or "source" } + end + local out = {} + for i, b in Apng.composite(w, h, list) do + local im = Types.Image.new(w, h, "rgba8") + im.pixels = b + out[i] = im + end + return out, nil +end + return Png diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau new file mode 100644 index 0000000..d023619 --- /dev/null +++ b/src/Formats/playlist/m3u/init.luau @@ -0,0 +1,369 @@ +--!strict +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no +-- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain +-- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / +-- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media +-- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, +-- codecs/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base +-- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, +-- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. +-- +-- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) +-- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" +-- local out = M3u.encode(pl, { title = "My Mix" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local M3u = { + name = "m3u", + category = "playlist", + extensions = { "m3u", "m3u8" }, + mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + caps = { decode = true, encode = true, hls = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; nil when unknown (-1 in the file) + playable: boolean, -- an http(s) URL the player can fetch + reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... + -- HLS + bandwidth: number?, -- master: BANDWIDTH + codecs: string?, -- master: CODECS + attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +export type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, -- media: sum of the segment durations + segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" +} + +export type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: / PLS has none + hls: Hls?, +} + +export type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries + maxBytes: number?, -- refuse bigger files (default 64 MB) +} +export type EncodeOptions = { + title: string?, -- #PLAYLIST: (default: the playlist's title) +} + +-- ------------------------------------------------------------------------------------------------ constants +local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } + +-- The extension of a URL's path (lower case), or nil +local function extension(url: string): string? + local p = Url.split(url).path + local ext = string.match(p, "%.([%w]+)$") + return if ext then string.lower(ext) else nil +end + +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas +local function attributes(s: string): { [string]: string } + local out = {} + local i, n = 1, #s + while i <= n do + local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) + if not key then + break + end + i = (eq :: number) + 1 + local value + if string.sub(s, i, i) == '"' then + local j = string.find(s, '"', i + 1, true) or (n + 1) + value = string.sub(s, i + 1, j - 1) + i = j + 1 + else + local j = string.find(s, ",", i, true) or (n + 1) + value = Text.trim(string.sub(s, i, j - 1)) + i = j + end + out[string.upper(key)] = value + local c = string.find(s, ",", i, true) + if not c then + break + end + i = c + 1 + end + return out +end + +-- #EXTINF:[ attr="v" ...], +local function extinf(rest: string): (number?, string?) + -- the first comma outside quoted attribute values + local comma, quoted = nil, false + for i = 1, #rest do + local c = string.byte(rest, i) + if c == 34 then + quoted = not quoted + elseif c == 44 and not quoted then + comma = i + break + end + end + local head = if comma then string.sub(rest, 1, comma - 1) else rest + local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil + local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") + return duration(d), if title and title ~= "" then title else nil +end + + +-- ------------------------------------------------------------------------------------------------ sniff +function M3u.sniff(r: Bytes.Reader): number + local s = r:peek(512) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + s = (string.match(s, "^%s*(.*)$") :: string) + if string.sub(s, 1, 7) == "#EXTM3U" then + return 0.95 + end + if string.find(s, "^#EXTINF:") or string.find(s, "^#EXT%-X%-") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parseM3u(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "m3u", entries = {}, warnings = warnings, meta = {} } + local pendingDur, pendingTitle = nil, nil + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local upper = string.upper(string.sub(l, 1, 10)) + if string.sub(upper, 1, 8) == "#EXTINF:" then + pendingDur, pendingTitle = extinf(string.sub(l, 9)) + elseif string.sub(upper, 1, 10) == "#PLAYLIST:" then + res.title = Text.trim(string.sub(l, 11)) + end + -- #EXTM3U, #EXTGRP, #EXTALB, ... and plain comments: ignored + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + e.title = pendingTitle + e.duration = pendingDur + pendingDur, pendingTitle = nil, nil + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + return res +end + +local function parseHls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local hls: Hls = { master = false, endList = false, encrypted = false } + local res: Result = { kind = "playlist", format = "hls", entries = {}, warnings = warnings, hls = hls, meta = {} } + local pendingDur, pendingTitle, pendingRange = nil, nil, nil + local pendingStream: { [string]: string }? = nil + local lastRangeEnd: number? = nil + local total = 0 + local formats = {} + local fmp4 = false + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local tag, rest = string.match(l, "^(#[%w%-]+):?(.*)$") + tag = if tag then string.upper(tag) else nil + if tag == "#EXT-X-STREAM-INF" then + hls.master = true + pendingStream = attributes(rest :: string) + elseif tag == "#EXT-X-MEDIA" then + hls.master = true + local a = attributes(rest :: string) + if a.URI then + local e: Entry = Url.locate(a.URI, base, baseScheme) + e.title = a.NAME + e.attributes = a + e.codecs = a.CODECS + table.insert(res.entries, e) + end + elseif tag == "#EXT-X-TARGETDURATION" then + hls.targetDuration = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-MEDIA-SEQUENCE" then + hls.mediaSequence = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-ENDLIST" then + hls.endList = true + elseif tag == "#EXT-X-KEY" then + local a = attributes(rest :: string) + if a.METHOD and string.upper(a.METHOD) ~= "NONE" then + if not hls.encrypted then + table.insert(warnings, ("line %d: encrypted segments (METHOD=%s) are not supported"):format(n, a.METHOD)) + end + hls.encrypted = true + end + elseif tag == "#EXT-X-MAP" then + fmp4 = true + elseif tag == "#EXTINF" then + pendingDur, pendingTitle = extinf(rest :: string) + elseif tag == "#EXT-X-BYTERANGE" then + local len, off = string.match(rest :: string, "^%s*(%d+)@?(%d*)") + if len then + local o = tonumber(off) or lastRangeEnd + pendingRange = { length = tonumber(len) :: number, offset = o } + lastRangeEnd = (o or 0) + (tonumber(len) :: number) + end + end + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + if pendingStream then + e.attributes = pendingStream + e.bandwidth = tonumber(pendingStream.BANDWIDTH) + e.codecs = pendingStream.CODECS + e.title = pendingStream.NAME + pendingStream = nil + else + e.title = pendingTitle + e.duration = pendingDur + e.byteRange = pendingRange + if pendingDur then + total += pendingDur + end + local ext = extension(e.url) or "?" + formats[ext] = true + if e.playable and (UNSUPPORTED_SEGMENTS[ext] or fmp4) then + e.playable = false + e.reason = "segment format " .. (if fmp4 then "fmp4" else ext) + end + if e.playable and hls.encrypted then + e.playable = false + e.reason = "encrypted" + end + end + pendingDur, pendingTitle, pendingRange = nil, nil, nil + table.insert(res.entries, e) + if e.reason == "relative path without a base URL" or (e.reason and string.sub(e.reason, 1, 7) == "scheme ") then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + if not hls.master then + hls.totalDuration = total + local list = {} + for ext in formats do + table.insert(list, ext) + end + table.sort(list) + hls.segmentFormat = if #list == 1 then list[1] elseif #list == 0 then nil else "mixed" + local bad = {} + for _, ext in list do + if UNSUPPORTED_SEGMENTS[ext] then + table.insert(bad, "." .. ext) + end + end + if fmp4 then + table.insert(bad, "fMP4 (EXT-X-MAP)") + end + if #bad > 0 then + table.insert(warnings, "HLS segments are " .. table.concat(bad, ", ") + .. ": only mp3 segments can be played (concatenated)") + end + if not hls.endList then + table.insert(warnings, "live HLS playlist (no EXT-X-ENDLIST): it has to be reloaded for new segments") + end + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local ls = Text.lines(t) + local res = if string.find(t, "#EXT%-X%-") then parseHls(ls, base, baseScheme, warnings) else parseM3u(ls, base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "m3u", hls = res.format == "hls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:<seconds>,<title>). Durations are rounded; unknown = -1. +-- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. +local function serialize(entries: { any }, opts: { title: string? }?): string + local out = { "#EXTM3U" } + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + if opts and opts.title then + table.insert(out, "#PLAYLIST:" .. clean(opts.title)) + end + for _, e in entries or {} do + if type(e) ~= "table" or type(e.url) ~= "string" then + continue + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + if e.title or d then + table.insert(out, ("#EXTINF:%d,%s"):format(secs, clean(tostring(e.title or "")))) + end + table.insert(out, clean(e.url)) + end + return table.concat(out, "\n") .. "\n" +end + +-- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of +-- entries ({ url, title?, duration? }) +function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local title = if opts and opts.title then opts.title else value.title + return buffer.fromstring(serialize(entries, { title = if type(title) == "string" then title else nil })), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +M3u.Url = Url + +return M3u diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau new file mode 100644 index 0000000..ea24213 --- /dev/null +++ b/src/Formats/playlist/pls/init.luau @@ -0,0 +1,237 @@ +--!strict +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case +-- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a +-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/Url), local / +-- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. +-- +-- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) +-- local out = Pls.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local Pls = { + name = "pls", + category = "playlist", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; nil when unknown (-1 in the file) + playable: boolean, -- an http(s) URL the player can fetch + reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... + -- HLS + bandwidth: number?, -- master: BANDWIDTH + codecs: string?, -- master: CODECS + attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +export type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, -- media: sum of the segment durations + segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" +} + +export type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: / PLS has none + hls: Hls?, +} + +export type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries + maxBytes: number?, -- refuse bigger files (default 64 MB) +} + +-- ------------------------------------------------------------------------------------------------ constants +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas +local function attributes(s: string): { [string]: string } + local out = {} + local i, n = 1, #s + while i <= n do + local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) + if not key then + break + end + i = (eq :: number) + 1 + local value + if string.sub(s, i, i) == '"' then + local j = string.find(s, '"', i + 1, true) or (n + 1) + value = string.sub(s, i + 1, j - 1) + i = j + 1 + else + local j = string.find(s, ",", i, true) or (n + 1) + value = Text.trim(string.sub(s, i, j - 1)) + i = j + end + out[string.upper(key)] = value + local c = string.find(s, ",", i, true) + if not c then + break + end + i = c + 1 + end + return out +end + +-- #EXTINF:<duration>[ attr="v" ...],<title> +local function extinf(rest: string): (number?, string?) + -- the first comma outside quoted attribute values + local comma, quoted = nil, false + for i = 1, #rest do + local c = string.byte(rest, i) + if c == 34 then + quoted = not quoted + elseif c == 44 and not quoted then + comma = i + break + end + end + local head = if comma then string.sub(rest, 1, comma - 1) else rest + local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil + local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") + return duration(d), if title and title ~= "" then title else nil +end + + +-- ------------------------------------------------------------------------------------------------ sniff +function Pls.sniff(r: Bytes.Reader): number + local s = r:peek(64) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + local first = string.match(s, "^%s*([^\r\n]*)") + return if first and string.lower(Text.trim(first)) == "[playlist]" then 0.95 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} } + local files, titles, lengths = {}, {}, {} + local declared = nil + for _, line in ls do + local l = Text.trim(line) + if l == "" or string.sub(l, 1, 1) == ";" or string.sub(l, 1, 1) == "#" or string.sub(l, 1, 1) == "[" then + continue + end + local key, value = string.match(l, "^([^=]-)%s*=%s*(.*)$") + if not key then + continue + end + local k = string.lower(Text.trim(key :: string)) + local name, idx = string.match(k, "^(%a+)(%d+)$") + local i = tonumber(idx) + if name == "file" and i then + files[i] = value + elseif name == "title" and i then + titles[i] = value + elseif name == "length" and i then + lengths[i] = value + elseif k == "numberofentries" then + declared = tonumber(value) + end + end + local order = {} + for i in files do + table.insert(order, i) + end + table.sort(order) + for _, i in order do + local e: Entry = Url.locate(files[i], base, baseScheme) + local t = titles[i] and Text.trim(titles[i]) + e.title = if t and t ~= "" then t else nil + e.duration = duration(lengths[i]) + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("File%d: %s: %s"):format(i, e.reason, e.url)) + end + end + if declared and declared ~= #order then + table.insert(warnings, ("NumberOfEntries=%d but %d files"):format(declared, #order)) + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local res = parsePls(Text.lines(t), base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "pls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a +-- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. +function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + local out = { "[playlist]" } + local n = 0 + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + n += 1 + table.insert(out, string.format("File%d=%s", n, clean(e.url))) + if type(e.title) == "string" then + table.insert(out, string.format("Title%d=%s", n, clean(e.title))) + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + table.insert(out, string.format("Length%d=%d", n, secs)) + end + end + table.insert(out, "NumberOfEntries=" .. n) + table.insert(out, "Version=2") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Pls diff --git a/src/Formats/playlist/xspf/init.luau b/src/Formats/playlist/xspf/init.luau new file mode 100644 index 0000000..b18034c --- /dev/null +++ b/src/Formats/playlist/xspf/init.luau @@ -0,0 +1,214 @@ +--!strict +-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/Xml. New in formats-luau (playlist-luau +-- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, +-- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, +-- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; +-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/Url), and are classified like the other +-- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. +-- +-- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) +-- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end +-- local out = Xspf.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Url = require("@formats/codecs/Url") +local Xml = require("@formats/codecs/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local Xspf = { + name = "xspf", + category = "playlist", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative locations + maxBytes: number?, -- refuse bigger files (default 64 MB) +} + +-- ------------------------------------------------------------------------------------------------ constants +local NS = "http://xspf.org/ns/0/" +local PLAYLIST_FIELDS = { "title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license" } +local TRACK_FIELDS = { "title", "creator", "album", "annotation", "info", "image" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +-- the text of the first child element with this local name, trimmed (nil when missing or empty) +local function field(node: any, name: string): string? + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + local s = trim(Xml.text(c)) + return if s ~= "" then s else nil + end + end + return nil +end + +local function elements(node: any, name: string): { any } + local out = {} + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + table.insert(out, c) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Xspf.sniff(r: Bytes.Reader): number + local s = r:peek(1024) + local i = string.find(s, "<%w*:?playlist[%s>]") + if i and string.find(s, NS, 1, true) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd +-- tracks become warnings) +function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local doc, err = Xml.decode(r:string(n)) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or Xml.localName(root.name) ~= "playlist" then + return nil, Err.new(Err.CORRUPT, "the root element is not <playlist>") + end + local warnings: { string } = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local function withXmlBase(node: any, b: string?, s: string?): (string?, string?) + local xb = node.attrs and node.attrs["xml:base"] + if type(xb) ~= "string" or xb == "" then + return b, s + end + local l = Url.locate(xb, b, s) + if Url.scheme(l.url) then + return l.url, Url.scheme(l.url) + end + return b, s + end + local pbase, pscheme = withXmlBase(root, base, baseScheme) + local pl: any = { + kind = "playlist", + format = "xspf", + entries = {}, + warnings = warnings, + title = field(root, "title"), + meta = { source = { format = "xspf", version = root.attrs and root.attrs.version } }, + } + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + pl.meta[k] = field(root, k) + end + end + local nLocal = 0 + for _, list in elements(root, "trackList") do + for i, track in elements(list, "track") do + local tbase, tscheme = withXmlBase(track, pbase, pscheme) + local locs = {} + for _, l in elements(track, "location") do + local s = trim(Xml.text(l)) + if s ~= "" then + table.insert(locs, s) + end + end + if #locs == 0 then + table.insert(warnings, string.format("track %d: no location", i)) + else + local e: any = Url.locate(locs[1], tbase, tscheme) + for _, k in TRACK_FIELDS do + e[k] = field(track, k) + end + local d = tonumber(field(track, "duration")) + e.duration = if d and d >= 0 and d == d and d ~= math.huge then d / 1000 else nil + e.trackNum = tonumber(field(track, "trackNum")) + if #locs > 1 then + local all = {} + for _, l in locs do + table.insert(all, Url.locate(l, tbase, tscheme).url) + end + e.locations = all + end + if e.reason == "local path" then + nLocal += 1 + elseif e.reason then + table.insert(warnings, string.format("track %d: %s: %s", i, e.reason, e.url)) + end + table.insert(pl.entries, e) + end + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + return pl, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list +-- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. +function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local root = Xml.element("playlist", { version = "1", xmlns = NS }) + local function add(parent: any, name: string, v: any) + if type(v) == "string" and v ~= "" then + Xml.append(parent, Xml.element(name, nil, { v })) + elseif type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then + Xml.append(parent, Xml.element(name, nil, { tostring(math.floor(v + 0.5)) })) + end + end + local title = if opts and opts.title then opts.title else value.title + add(root, "title", title) + local meta = if type(value.meta) == "table" then value.meta else {} + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + add(root, k, meta[k]) + end + end + local list = Xml.append(root, Xml.element("trackList")) + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + local tr = Xml.append(list, Xml.element("track")) + add(tr, "location", e.url) + if type(e.locations) == "table" then + for i = 2, #e.locations do + add(tr, "location", e.locations[i]) + end + end + for _, k in TRACK_FIELDS do + add(tr, k, e[k]) + end + local d = tonumber(e.duration) + if d and d >= 0 then + add(tr, "duration", d * 1000) + end + add(tr, "trackNum", tonumber(e.trackNum)) + end + end + local s = Xml.encode(Xml.document(root), { indent = if opts and opts.indent ~= nil then opts.indent else 2 }) + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "encode: the XML serializer failed") + end + return buffer.fromstring(s), nil +end + +return Xspf diff --git a/tests/archive/zip.luau b/tests/archive/zip.luau new file mode 100644 index 0000000..26efdec --- /dev/null +++ b/tests/archive/zip.luau @@ -0,0 +1,268 @@ +-- archive/zip + containers/Zip tests: generated archives (comment with a fake end record, data descriptors, +-- force_zip64, an all-ZIP64 archive, 66000 entries, a prefix stub, a wrong local header, unicode, empty) read entry by +-- entry against Python's zipfile listing (and every Webamp demo skin when SKINS_DIR is set); lookup rules; bad CRC, +-- encrypted and unsupported entries; the writer (stored / deflated, levels, UTF-8 names, DOS times, comments, ZIP64, +-- raw copies) read back; the Archive API (list / read / add / remove / write, create, encode of a table) and the api; +-- corrupt input never throws. The writer's output was also checked by hand: `unzip -t`, Python zipfile and 7z read it. +-- Ported from zip-luau tests/zip.luau. Fixtures: tools/fixtures/zip.py. +local T = require("@tests/T") +local Zip = require("@formats/containers/Zip") +local ZipF = require("@formats/archive/zip") +local Deflate = require("@formats/codecs/Deflate") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Fx = require("@tests/gen/zip_cases") + +local t = T.suite("zip") + +local function dataOf(a: any): string + if a.data then + return a.data + end + return buffer.tostring(Deflate.zlib(buffer.fromstring(a.dataZ)) :: buffer) +end + +-- open an archive and compare it with zipfile's listing; read every entry +local function verify(a: any, label: string): (any, number) + local z, err = Zip.open(dataOf(a)) + t:check(z, label .. ": open: " .. tostring(err)) + local list = z:list() + t:eq(#list, a.count, label .. ": entries") + local bytes = 0 + for i, want in a.entries do + local e = list[i] + t:check(e.rawName == want[1] or e.name == string.gsub(want[1], "\\", "/"), label .. ": name " .. e.rawName) + t:check(e.size == want[2] and e.crc32 == want[3] and e.method == want[4], label .. ": " .. e.name .. " size / crc / method") + local data, rerr = z:read(e) + t:check(data, label .. ": read " .. e.name .. ": " .. tostring(rerr)) + t:check(buffer.len(data :: buffer) == want[2] and Crc32.of(data :: buffer) == want[3], label .. ": " .. e.name .. " content") + bytes += want[2] + end + return z, bytes +end + +local byName = {} +for _, a in Fx.archives do + byName[a.name] = a + a.zip = verify(a, a.name) +end +t:note("%d generated archives match Python zipfile", #Fx.archives) +local total, nent = 0, 0 +for _, s in Fx.skins do + local _, bytes = verify(s, s.name) + total += bytes + nent += s.count +end +if #Fx.skins > 0 then + t:note("%d skins, %d entries, %.2f MB read and CRC-checked", #Fx.skins, nent, total / 1e6) +else + t:note("(no skins: set SKINS_DIR to the Webamp demo skins)") +end + +-- lookup and specifics +do + local z = byName.basic.zip + t:eq(z:find("readme.txt").name, "readme.txt", "find exact") + t:eq(z:find("README.TXT").name, "readme.txt", "find case-insensitive") + t:eq(z:find("main.bmp").name, "Skin/Main.BMP", "find by basename skips __MACOSX") + t:eq(z:find("skin\\MAIN.bmp").name, "Skin/Main.BMP", "find with backslashes") + t:check(z:find("__MACOSX/Skin/._Main.BMP") ~= nil, "junk still found by its full path") + t:check(z:find("Skin/") == nil, "directories are not found") + t:check(z:find("nope.bmp") == nil, "missing") + t:eq(z:find("deep.txt").name, "Skin/sub/deep.txt", "basename in a deeper folder") + t:eq(z:readString("DEEP.TXT"), "deep", "readString by name") + t:eq(z:readString("Other/\u{fc}nicode.txt"), "h\u{e9}llo", "unicode basename") + local u = z:find("sk\u{ef}n/\u{fc}nicode.txt") + t:check(u and u.utf8 and z:readString(u) == "h\u{e9}llo", "unicode name") + local m = z:find("readme.txt").modified + t:check(m.year == 2020 and m.month == 5 and m.day == 17 and m.hour == 13 and m.min == 37 and m.sec == 42, "dos time") + t:eq(z:find("readme.txt").mtime, 1589722662, "mtime (unix seconds)") + local _, e = z:read("nope") + t:check(e and e.code == Err.ARG, "read a missing name") + t:eq(string.sub(byName.comment.zip.comment, 1, 14), "a comment with", "archive comment") + t:check(byName.zip64_by_hand.zip.zip64 and byName.many.zip.zip64, "zip64 records detected") + t:check(bit32.band(byName.descriptors.zip:list()[1].flags, 8) ~= 0, "data descriptor flag") + t:check(not byName.basic.zip.zip64, "basic is not zip64") + t:eq(byName.many.zip:readString("d/65999.txt"), "65999", "last of 66000 entries") + t:eq(#byName.empty.zip:list(), 0, "empty archive") + t:check(Zip.isZip(byName.basic.data) and Zip.isZip(byName.empty.data) and not Zip.isZip("GIF89a"), "isZip") + -- a sub-range reader + local s = byName.basic.data + local big = buffer.create(#s + 10) + buffer.writestring(big, 4, s) + local zs = Zip.open(Bytes.reader(big, 4, #s)) + t:check(zs and zs:readString("readme.txt") ~= nil, "open a sub-range Reader") +end + +-- a bad CRC, encrypted and unsupported entries +do + local data = buffer.fromstring(byName.basic.data) + local z = Zip.open(byName.basic.data) + local st = z:find("stored.bin") + local p = st.offset + 30 + buffer.readu16(data, st.offset + 26) + buffer.readu16(data, st.offset + 28) + 10 + buffer.writeu8(data, p, bit32.bxor(buffer.readu8(data, p), 0xFF)) + local z2 = Zip.open(data) + local out, err = z2:read("stored.bin") + t:check(out == nil and err.code == Err.CHECKSUM, "stored CRC mismatch: " .. tostring(err)) + t:check(z2:read("stored.bin", false) ~= nil, "verify = false") + local e = table.clone(z:find("readme.txt")) + e.flags = 1 + local _, ee = z:read(e) + t:check(ee and ee.code == Err.UNSUPPORTED, "encrypted refused") + e.flags, e.method = 0, 12 + local _, merr = z:read(e) + t:check(merr and merr.code == Err.UNSUPPORTED and string.find(merr.message, "method 12", 1, true), "bzip2 refused: " .. tostring(merr)) + local _, oe = Zip.open(5 :: any) + t:check(oe and oe.code == Err.ARG, "a non-buffer argument") +end + +-- the writer +do + local rand = T.rng(5) + local w = Zip.writer() + local files = {} + local text = string.rep("the quick brown fox jumps over the lazy dog ", 2000) + local noise = buffer.create(5000) + for i = 0, 4999 do + buffer.writeu8(noise, i, rand(2147483648) // 8388608) + end + local function put(name: string, data: any, opts: any?) + t:check(w:add(name, data, opts), "add " .. name) + table.insert(files, { name, if type(data) == "string" then data elseif data then buffer.tostring(data) else "" }) + end + put("text.txt", text, { level = 9, mtime = 1589722662 }) + put("stored.txt", text, { method = "store" }) + put("noise.bin", noise) -- deflate is not smaller: stored + put("empty.txt", "") + put("dir/", nil) + put("dir/\u{fc}nicode.txt", "h\u{e9}llo", { comment = "a file comment" }) + put("level0.txt", text, { level = 0 }) + local out, err = w:finish({ comment = "archive comment" }) + t:check(out, "finish: " .. tostring(err)) + local z = Zip.open(out :: buffer) + t:check(z, "our archive opens") + local list = z:list() + t:eq(#list, #files, "entry count") + for i, f in files do + t:eq(list[i].name, f[1], "name " .. i) + t:eq(z:readString(list[i]), f[2], "content " .. f[1]) + end + t:eq(list[1].method, 8, "deflated") + t:check(list[1].compressedSize < #text // 10, "compressed") + t:eq(list[2].method, 0, "stored") + t:eq(list[3].method, 0, "incompressible data is stored") + t:check(list[5].isDir, "directory entry") + t:check(list[6].utf8 and not list[1].utf8, "UTF-8 flag only for non-ASCII names") + t:eq(list[6].comment, "a file comment", "entry comment") + t:eq(list[1].mtime, 1589722662, "mtime round trip") + local md = list[1].modified + t:check(md.year == 2020 and md.month == 5 and md.day == 17 and md.hour == 13 and md.min == 37 and md.sec == 42, "dos time written") + t:check(list[2].modified.year == 1980 and list[2].modified.month == 1 and list[2].modified.day == 1, "default time 1980-01-01") + t:eq(z.comment, "archive comment", "archive comment written") + t:check(not z.zip64, "small archive is not ZIP64") + -- forced ZIP64 + local w64 = Zip.writer() + w64:add("a.txt", text) + w64:add("b.txt", "bee", { method = "store" }) + local z64 = Zip.open(w64:finish({ zip64 = true }) :: buffer) + t:check(z64 and z64.zip64 and z64:readString("a.txt") == text and z64:readString("b.txt") == "bee", "forced ZIP64 round trip") + -- over 65535 entries: the ZIP64 end record + local wm = Zip.writer() + for i = 0, 65999 do + wm:add(string.format("d/%05d.txt", i), tostring(i), { method = "store" }) + end + local zm = Zip.open(wm:finish() :: buffer) + t:check(zm and zm.zip64 and #zm:list() == 66000 and zm:readString("d/65999.txt") == "65999", "66000 entries") + -- dates + for _, s in { 315532800, 946684799, 1700000000, 4354819198 } do + local tm, dt = Zip.dosTime(s) + t:eq(Zip.unixTime(tm, dt), s - s % 2, "dos time of " .. s) + end + t:check(select(2, Zip.dosTime(0)) == 0x21, "before 1980 clamps") + -- bad arguments + t:check(not w:add("", "x"), "empty name") + t:check(not w:add("x", 5 :: any), "bad data") + t:check(not w:add("x", "y", { method = "lzma" } :: any), "bad method") +end + +-- the Archive (archive/zip) +do + t:eq(ZipF.name, "zip", "name") + t:eq(ZipF.category, "archive", "category") + local a, err = ZipF.decode(Bytes.reader(buffer.fromstring(byName.basic.data))) + t:check(a and a.kind == "archive" and a.format == "zip", "decode: " .. tostring(err)) + local list = a:list() + t:eq(#list, byName.basic.count, "list") + t:check(list[1].name == "readme.txt" and list[1].method == "deflate" and not list[1].dir and list[1].mtime == 1589722662, "entry fields") + t:check(list[4].dir, "dir entry") + local rd = a:read("readme.txt") + t:check(rd and Crc32.of(rd :: buffer) == byName.basic.entries[1][3], "read") + t:check(a:read("MAIN.bmp") ~= nil, "read by the lookup rules") + -- edit: replace, add, remove, then write; unchanged entries are copied raw + a:add("readme.txt", "replaced") + a:add("new/one.txt", string.rep("x", 1000), { level = 9 }) + t:check(a:remove("Skin/stored.bin") and not a:remove("nope"), "remove") + local out = a:write() :: buffer + local b = ZipF.decode(Bytes.reader(out)) :: any + t:check(b, "rewritten archive opens") + t:eq(buffer.tostring(b:read("readme.txt")), "replaced", "replaced entry") + t:eq(buffer.tostring(b:read("new/one.txt")), string.rep("x", 1000), "added entry") + t:check(b:read("Skin/stored.bin") == nil, "removed entry") + t:check(b:read("Skin/Main.BMP") and Crc32.of(b:read("Skin/Main.BMP")) == byName.basic.entries[2][3], "copied entry") + local names = {} + for _, e in b:list() do + table.insert(names, e.name) + end + t:eq(table.concat(names, ","), "readme.txt,Skin/Main.BMP,Skin/,Skin/sub/deep.txt,empty.txt,__MACOSX/Skin/._Main.BMP,Sk\u{ef}n/\u{fc}nicode.txt,new/one.txt", "order kept") + -- create, encode of a table, encode of another Archive + local c = ZipF.create() + c:add("hello.txt", "hi") + local cz = ZipF.decode(Bytes.reader(ZipF.encode(c) :: buffer)) :: any + t:eq(buffer.tostring(cz:read("hello.txt")), "hi", "create + encode") + local tz = ZipF.decode(Bytes.reader(ZipF.encode({ ["b.txt"] = "bee", ["a.txt"] = buffer.fromstring("ay") }) :: buffer)) :: any + t:check(tz:list()[1].name == "a.txt" and buffer.tostring(tz:read("b.txt")) == "bee", "encode a { name = data } table") + local _, ee = ZipF.encode(5 :: any) + t:check(ee and ee.code == Err.ARG, "encode a number") + -- comments survive a rewrite + local cm = ZipF.decode(Bytes.reader(buffer.fromstring(byName.comment.data))) :: any + t:eq(string.sub(Zip.open(cm:write()).comment, 1, 14), "a comment with", "comment kept on write") + -- the api + local la = F.archive.load(byName.basic.data) + t:check(la and la.kind == "archive" and #la:list() == byName.basic.count, "F.archive.load") + t:eq(F.detect(byName.basic.data), "zip", "F.detect") + local saved = F.save(la, nil, { format = "zip" }) + t:check(saved and #Zip.open(saved):list() == byName.basic.count, "F.save zip") + local saved2 = F.save(la) + t:check(saved2 ~= nil, "F.save without a format uses the source format") +end + +-- corrupt archives never throw +local samples = {} +for _, a in Fx.archives do + if a.data then + table.insert(samples, a.data) + end +end +t:fuzz("open + read every entry", function(b: buffer) + local z = Zip.open(b) + if z then + for _, e in z:list() do + z:read(e) + end + end + return z +end, samples, { mutations = 40 }) +t:fuzz("archive decode + write", function(b: buffer) + local a = ZipF.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 10, garbage = 50 }) + +t:done() diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau new file mode 100644 index 0000000..c1d2305 --- /dev/null +++ b/tests/audio/flac.luau @@ -0,0 +1,203 @@ +-- audio/flac tests: every fixture from tools/fixtures/flac.py (flac 0-8, 4-32 bits, 1-6 channels, odd rates and block +-- sizes, LPC order 32, wasted bits, every stereo mode, ffmpeg's encoder, Ogg FLAC, ID3v2 in front) decoded bit-exact +-- against `flac -d`; sample-accurate seeking; f32 scaling and output reuse; decode() to an Audio from a sub-range +-- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass. +-- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py. +local T = require("@tests/T") +local Flac = require("@formats/audio/flac") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/flac_cases") + +local t = T.suite("flac") + +local function open(b: any, opts: any?): (any, any) + return Flac.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts) +end +local byName = {} +for _, c in Cases do + byName[c.name] = c +end + +t:eq(Flac.name, "flac", "name") +t:check(Flac.caps.decode and not Flac.caps.encode, "caps") + +local seekChecks = 0 +for _, fx in Cases do + local name = fx.name + local dec, err = open(fx.data) + t:check(dec, name .. ": open: " .. tostring(err)) + t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels and dec.bitsPerSample == fx.bps, name .. ": format") + t:eq(dec.frames, fx.frames, name .. ": frames") + t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration") + t:eq(dec.container, if fx.ogg then "ogg" else "flac", name .. ": container") + local ch = dec.channels + local all = table.create(fx.frames * ch, 0) + local crc, n, k = 0, 0, 0 + local sizes = { 4096, 1, 777, 10000, 3 } + while true do + k += 1 + local out, got = dec:readInt(sizes[k % #sizes + 1]) + if got == 0 then + break + end + crc = Crc32.of(out, 0, got * ch * 4, crc) + for i = 0, got * ch - 1 do + all[n * ch + i + 1] = buffer.readi32(out, i * 4) + end + n += got + end + t:eq(n, fx.frames, name .. ": decoded frames") + t:eq(crc, fx.crc, name .. ": samples identical to flac -d") + t:eq(select(2, dec:position()), fx.frames, name .. ": position at end") + -- f32 scaling, output reuse + dec:seekSample(0) + local reuse = buffer.create(100 * ch * 4) + local f, gotf = dec:read(100, reuse) + t:check(f == reuse, name .. ": output buffer reused") + local scale = 2 ^ (fx.bps - 1) + local bad = 0 + for i = 0, math.min(gotf, 100) * ch - 1 do + if math.abs(buffer.readf32(f, i * 4) - all[i + 1] / scale) >= 1e-7 then + bad += 1 + end + end + t:eq(bad, 0, name .. ": f32 samples") + -- seeking + local rand = T.rng(99) + local targets = { 0, 1, fx.frames - 1, fx.frames // 2, 4096, 4095, 4097, 1152, 1151 } + for _ = 1, 12 do + table.insert(targets, rand(fx.frames)) + end + for _, s in targets do + if s >= 0 and s < fx.frames then + t:check(dec:seekSample(s), name .. ": seek " .. s) + t:eq(select(2, dec:position()), s, name .. ": position after seek " .. s) + local out, got = dec:readInt(50) + t:eq(got, math.min(50, fx.frames - s), name .. ": read after seek") + local diff = 0 + for i = 0, got * ch - 1 do + if buffer.readi32(out, i * 4) ~= all[s * ch + i + 1] then + diff += 1 + end + end + t:eq(diff, 0, name .. ": samples after seek " .. s) + seekChecks += 1 + end + end + dec:seek(dec.duration / 3) + local _, pos = dec:position() + t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds") + dec:seek(dec.duration + 5) + t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") + for key, v in fx.tags or {} do + t:eq(dec.tags[key], v, name .. ": tag " .. key) + end + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") +end +t:note("%d fixtures bit-exact against flac -d, %d seeks", #Cases, seekChecks) + +-- decode() from a sub-range Reader +for _, name in { "s16_l5", "ogg_s16", "id3", "s24_96k" } do + local fx = byName[name] + local big = buffer.create(#fx.data + 13) + buffer.writestring(big, 6, fx.data) + local a, err = Flac.decode(Bytes.reader(big, 6, #fx.data)) + t:check(a and a.kind == "audio" and a.frames == fx.frames and a.channels == fx.channels, name .. ": decode: " .. tostring(err)) + local d = open(fx.data) + local ref = d:read(fx.frames) + t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read") + t:eq(a.meta.source.bitDepth, fx.bps, name .. ": meta.source") +end + +-- tags and pictures +do + local dec = open(byName.s16_noseek.data) + t:check(#dec.pictures == 1 and dec.pictures[1].mime == "image/png" and dec.pictures[1].width == 1, "picture") + t:eq(#dec.seekTable, 0, "no seek table") + t:check(string.find(dec.vendor, "reference libFLAC", 1, true), "vendor") + t:eq(#dec.md5, 32, "md5") +end + +-- STREAMINFO without a total length: found from the last frame +for _, name in { "s16_l5", "varblock", "bs17" } do + local fx = byName[name] + local b = buffer.fromstring(fx.data) + buffer.writeu8(b, 8 + 13, bit32.band(buffer.readu8(b, 8 + 13), 0xF0)) + buffer.writeu32(b, 8 + 14, 0) + local dec = open(b) + t:check(dec and dec.frames == fx.frames, name .. ": length from the last frame") + local crc, n = 0, 0 + while true do + local out, got = dec:readInt(5000) + if got == 0 then + break + end + crc = Crc32.of(out, 0, got * dec.channels * 4, crc) + n += got + end + t:check(n == fx.frames and crc == fx.crc, name .. ": decode without total length") +end + +-- sniff, errors, the api +do + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xxfLaC"))), 1, "sniff ID3 + fLaC") + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xx\255\251"))), 0, "sniff ID3 + mp3") + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") + local _, e1 = open("fLaC") + t:check(e1 and Err.is(e1), "no metadata: " .. tostring(e1)) + local _, e2 = open(buffer.create(0)) + t:check(e2 and e2.code == Err.CORRUPT, "empty") + local fx = byName.ogg_s16 + t:eq(F.detect(fx.data), "flac", "F.detect Ogg FLAC") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames, "F.audio.load") + local d = F.audio.open(byName.s16_l3.data) + t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open") + local _, se = F.save(a, nil, { format = "flac" }) + t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se)) +end + +-- a damaged frame is dropped, the rest decodes +do + local src = buffer.fromstring(byName.s16_l5.data) + local len = buffer.len(src) + buffer.writeu8(src, len // 2, bit32.bxor(buffer.readu8(src, len // 2), 0x55)) + local d = open(src) + local total = 0 + while true do + local _, got = d:read(4096) + if got == 0 then + break + end + total += got + end + t:check(total < d.frames and total >= d.frames - 2 * 4096, "one damaged frame dropped: " .. total) +end + +-- fuzz +local samples = {} +for _, name in { "s16_l5", "ogg_s16", "id3", "varblock", "s32_rice2", "u8_mono", "bits4" } do + table.insert(samples, byName[name].data) +end +t:fuzz("open + read + seek", function(b: buffer) + local d = Flac.open(Bytes.reader(b)) + if d then + local guard = 0 + while select(2, d:read(4096)) > 0 and guard < 200 do + guard += 1 + end + d:seek(0.1) + d:read(100) + d:seekSample(d.frames // 2) + d:read(100) + end + return d +end, samples, { mutations = 12, keepHeader = 42 }) +t:fuzz("decode", function(b: buffer) + return Flac.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 60 }) + +t:done() diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau new file mode 100644 index 0000000..f973803 --- /dev/null +++ b/tests/audio/mp3.luau @@ -0,0 +1,518 @@ +-- audio/mp3 tests: every fixture against its minimp3 reference decode (exact length, SNR > 90 dB on windows, block +-- energies) and against ffmpeg (length, SNR > 75 dB), lame-written streams against ffmpeg; chunked reads, reads into +-- a caller buffer, sample-accurate seeking; robustness (garbage, corruption, truncation, mono / stereo switches, API +-- misuse); ID3v1 / v2.2 / 2.3 / 2.4 and APE tags; the contract, sniff, decode to Audio, the fuzz no-throw pass. +-- Ported from mp3-luau tests/decode.luau, robust.luau, tags.luau. Fixtures: tools/fixtures/mp3.py. +local T = require("@tests/T") +local Mp3 = require("@formats/audio/mp3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/mp3_cases") + +local t = T.suite("mp3") + +local function open(b: buffer | string, opts: any?): (any, any) + local buf = if type(b) == "string" then buffer.fromstring(b) else b + return Mp3.open(Bytes.reader(buf), opts) +end + +local byName: { [string]: any } = {} +for _, c in Cases do + byName[c.name] = c +end +local function file(name: string): buffer + return buffer.fromstring(byName[name].data) +end + +-- the reference format written by the minimp3 harness (see tools/fixtures/mp3.py) +local function parseRef(s: string): any + local b = buffer.fromstring(s) + local hz, ch, frames, W, N = buffer.readu32(b, 8), buffer.readu32(b, 12), buffer.readu32(b, 16), buffer.readu32(b, 20), buffer.readu32(b, 24) + local p = 28 + local windows = {} + for _ = 1, N do + local start = buffer.readu32(b, p) + p += 4 + local pcm = buffer.create(W * ch * 4) + buffer.copy(pcm, 0, b, p, W * ch * 4) + p += W * ch * 4 + table.insert(windows, { start = start, pcm = pcm }) + end + local B, nb = buffer.readu32(b, p), buffer.readu32(b, p + 4) + p += 8 + local energies = {} + for i = 1, nb do + energies[i] = buffer.readf64(b, p) + p += 8 + end + return { hz = hz, channels = ch, frames = frames, W = W, windows = windows, block = B, energies = energies } +end + +local function snr(x: buffer, xo: number, ref: buffer, ro: number, n: number): number + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(ref, (ro + i) * 4) + local d = buffer.readf32(x, (xo + i) * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge + end + if sig == 0 then + return -math.huge + end + return 10 * math.log10(sig / err) +end + +local function maxDiff(x: buffer, xo: number, y: buffer, yo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(x, (xo + i) * 4) - buffer.readf32(y, (yo + i) * 4)) + if d > m then + m = d + end + end + return m +end + +local rand = T.rng(12345) + +-- ------------------------------------------------------------------------------------------------ contract +t:eq(Mp3.name, "mp3", "name") +t:eq(Mp3.category, "audio", "category") +t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions") +t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps") + +-- ------------------------------------------------------------------------------------------------ decode vs references +for _, c in Cases do + local name = c.name + local buf = buffer.fromstring(c.data) + local dec, err = open(buf) + t:check(dec, name .. ": open (" .. tostring(err) .. ")") + local ch = dec.channels + local ref = if c.ref then parseRef(c.ref) else nil + if ref then + t:eq(dec.sampleRate, ref.hz, name .. ": sample rate") + t:eq(ch, ref.channels, name .. ": channels") + t:eq(dec.frames, ref.frames, name .. ": frames vs minimp3") + t:check(math.abs(dec.duration - ref.frames / ref.hz) < 1e-9, name .. ": duration") + else + t:eq(dec.sampleRate, c.rate, name .. ": sample rate") + t:eq(ch, c.channels, name .. ": channels") + t:eq(dec.frames, c.srcFrames, name .. ": gapless length = the encoder's input") + end + t:eq(dec.frames, c.ffFrames, name .. ": frames vs ffmpeg") + t:check(dec.bitrate > 0, name .. ": bitrate") + + -- whole decode in chunks of varied sizes + local all = buffer.create(dec.frames * ch * 4) + local total = 0 + while true do + local pcm, n = dec:read(1 + rand(3000)) + if n == 0 then + break + end + t:check(buffer.len(pcm) == n * ch * 4, name .. ": chunk size") + buffer.copy(all, total * ch * 4, pcm, 0, n * ch * 4) + total += n + end + t:eq(total, dec.frames, name .. ": decoded frames") + t:eq(dec:position(), total / dec.sampleRate, name .. ": position at the end") + local _, n0 = dec:read(100) + t:eq(n0, 0, name .. ": read after the end") + + local worst, worstFF = math.huge, math.huge + if ref then + for _, w in ref.windows do + local s = snr(all, w.start * ch, w.pcm, 0, ref.W * ch) + worst = math.min(worst, s) + t:check(s > 90, string.format("%s: window at %d SNR %.1f dB vs minimp3", name, w.start, s)) + end + for bi, e in ref.energies do + local a = (bi - 1) * ref.block + local bEnd = math.min(ref.frames, a + ref.block) + local sum = 0 + for i = a * ch, bEnd * ch - 1 do + local v = buffer.readf32(all, i * 4) + sum += v * v + end + t:check(math.abs(sum - e) <= 1e-5 * e + 1e-9, string.format("%s: block %d energy", name, bi)) + end + end + for _, w in c.ff do + local pcm = buffer.fromstring(w.pcm) + local s = snr(all, w.start * ch, pcm, 0, buffer.len(pcm) // 4) + worstFF = math.min(worstFF, s) + t:check(s > 75, string.format("%s: window at %d SNR %.1f dB vs ffmpeg", name, w.start, s)) + end + + -- reading into a caller buffer (reused when big enough, ignored when too small) + dec:seek(0) + local out = buffer.create(500 * ch * 4) + local got, n1 = dec:read(500, out) + t:check(got == out and n1 == 500, name .. ": read into out") + t:eq(maxDiff(out, 0, all, 0, 500 * ch), 0, name .. ": out matches") + local got2, n2 = dec:read(600, out) + t:check(got2 ~= out and n2 == 600 and maxDiff(got2, 0, all, 500 * ch, 600 * ch) == 0, name .. ": small out ignored") + + -- seeks: every window, then random targets, compared with the straight decode (bit-identical) + local targets = {} + for _, w in c.ff do + table.insert(targets, w.start) + end + for _ = 1, 12 do + table.insert(targets, rand(dec.frames)) + end + table.insert(targets, dec.frames - 1) + for _, tg in targets do + dec:seekFrame(tg) + local _, pf = dec:position() + t:eq(pf, tg, name .. ": position after seek") + local want = math.min(1152, dec.frames - tg) + local pcm, n = dec:read(want) + t:eq(n, want, string.format("%s: read after seek to %d", name, tg)) + t:eq(maxDiff(pcm, 0, all, tg * ch, n * ch), 0, string.format("%s: seek to %d bit-identical", name, tg)) + end + dec:seek(dec.duration / 3) + local _, pf = dec:position() + local pcm, n = dec:read(64) + t:check(n == 64 and maxDiff(pcm, 0, all, pf * ch, 64 * ch) == 0, name .. ": seek seconds") + dec:seek(1e9) + t:eq(select(2, dec:read(10)), 0, name .. ": seek past the end") + dec:seek(-5) + local pcm0, n3 = dec:read(256) + t:check(n3 == 256 and maxDiff(pcm0, 0, all, 0, 256 * ch) == 0, name .. ": seek back to the start") + + -- decode to Audio, also from a sub-range of a bigger buffer + local big = buffer.create(buffer.len(buf) + 17) + buffer.copy(big, 9, buf) + local a, aerr = Mp3.decode(Bytes.reader(big, 9, buffer.len(buf))) + t:check(a and a.kind == "audio" and a.frames == dec.frames and a.channels == ch, name .. ": decode (" .. tostring(aerr) .. ")") + t:eq(maxDiff(a.samples, 0, all, 0, dec.frames * ch), 0, name .. ": decode = stream") + t:check(a.meta.source.format == "mp3" and a.meta.source.layer == dec.layer, name .. ": meta.source") + t:eq(Mp3.sniff(Bytes.reader(buf)) > 0.5, true, name .. ": sniff") + + t:note("%-20s L%d MPEG-%s %5d Hz %d ch %6d frames %3d kbps SNR minimp3 %s, ffmpeg %.1f dB", name, dec.layer, tostring(dec.version), dec.sampleRate, ch, dec.frames, dec.bitrate, if ref then string.format("%.1f", worst) else "-", worstFF) +end + +-- ------------------------------------------------------------------------------------------------ robustness +local function concat(...: buffer): buffer + local n = 0 + for _, b in { ... } do + n += buffer.len(b) + end + local out = buffer.create(n) + local o = 0 + for _, b in { ... } do + buffer.copy(out, o, b, 0) + o += buffer.len(b) + end + return out +end +local function slice(b: buffer, i: number, j: number): buffer + local out = buffer.create(j - i) + buffer.copy(out, 0, b, i, j - i) + return out +end +-- decodes everything; checks every sample is finite; returns pcm, frames, decoder +local function decodeAll(b: buffer, label: string): (buffer?, number, any) + local ok, dec, err = pcall(open, b) + t:check(ok, label .. ": open does not throw (" .. tostring(dec) .. ")") + if not dec then + return nil, 0, err + end + local ok2, pcm, n = pcall(dec.readAll, dec) + t:check(ok2, label .. ": decode does not throw (" .. tostring(pcm) .. ")") + local bad = 0 + for i = 0, n * dec.channels - 1 do + local v = buffer.readf32(pcm, i * 4) + if v ~= v or v == math.huge or v == -math.huge then + bad += 1 + end + end + t:eq(bad, 0, label .. ": finite samples") + return pcm, n, dec +end + +-- the same pseudo-random sequence as mp3-luau's robust.luau (its junk is known not to chain into frames) +local orandRaw = T.rng(777) +local function orand(n: number): number -- 1..n + return orandRaw(n) + 1 +end +local base = file("l3_cbr128_js") +local refPcm, refN, refDec = decodeAll(base, "base") +assert(refPcm) + +-- garbage before the first frame (with fake sync words): same output, bit for bit +do + local junk = buffer.create(5000) + for i = 0, 4999 do + buffer.writeu8(junk, i, (orand(256) - 1)) + end + for i = 0, 4999, 97 do + buffer.writeu8(junk, i, 0xFF) + if i + 1 < 5000 then + buffer.writeu8(junk, i + 1, 0xFB) + end + end + local pcm, n, dec = decodeAll(concat(junk, base), "garbage prefix") + t:check(n == refN and dec.frames == refN, string.format("garbage prefix: same length (%d %d vs %d)", n, dec.frames, refN)) + t:check(pcm and maxDiff(pcm, 0, refPcm, 0, n * 2) == 0, "garbage prefix: same samples") +end +-- garbage in the middle: re-syncs, keeps going +do + local half = buffer.len(base) // 2 + local junk = buffer.create(3333) + for i = 0, 3332 do + buffer.writeu8(junk, i, (orand(256) - 1)) + end + local _, n = decodeAll(concat(slice(base, 0, half), junk, slice(base, half, buffer.len(base))), "garbage middle") + t:check(math.abs(n - refN) <= 4 * 1152, string.format("garbage middle: %d frames vs %d", n, refN)) +end +-- corrupt bytes all over the stream +do + local b = buffer.create(buffer.len(base)) + buffer.copy(b, 0, base) + for _ = 1, 60 do + buffer.writeu8(b, 1000 + orand(buffer.len(b) - 1001), (orand(256) - 1)) + end + local _, n = decodeAll(b, "corrupt bytes") + t:check(n > refN // 2, "corrupt bytes: most frames decode") +end +-- truncated anywhere +for _ = 1, 25 do + local cut = orand(buffer.len(base)) + local _, n = decodeAll(slice(base, 0, cut), "truncated at " .. cut) + t:check(n <= refN, "truncated: not longer") +end +-- a stereo stream (no Xing tag) then a mono one of the same rate -> stereo, the mono part in both channels +do + local stereo = file("l3_noreservoir") + local mono = file("l3_vbr_v7_mono") + local _, stereoN = decodeAll(stereo, "stereo alone") + local _, monoN = decodeAll(mono, "mono alone") + local pcm, n, dec = decodeAll(concat(stereo, mono), "stereo then mono") + t:check(dec and dec.channels == 2, "switch: stereo output") + t:check(n >= stereoN + monoN, "switch: both parts decode") + local same = true + for i = n - 3000, n - 2000 do + if buffer.readf32(pcm :: buffer, i * 8) ~= buffer.readf32(pcm :: buffer, i * 8 + 4) then + same = false + end + end + t:check(same, "switch: mono part duplicated") +end +-- bad input and API misuse +do + local d, err = open(buffer.create(0)) + t:check(d == nil and Err.is(err) and err.code == Err.CORRUPT, "empty buffer") + d = open(string.rep("not an mp3 file at all ", 500)) + t:check(d == nil, "text") + t:check(open(buffer.create(100000)) == nil, "zeros") + local ffs = buffer.create(100000) + buffer.fill(ffs, 0, 0xFF) + t:check(pcall(function() + local dd = open(ffs) + if dd then + dd:readAll() + end + end), "all 0xFF") + local _, lerr = open(base, { maxFrames = 1000 }) + t:check(lerr and lerr.code == Err.LIMIT, "maxFrames") + local dec = refDec + dec:seek(0) + t:eq(select(2, dec:read(-5)), 0, "read(-5)") + t:eq(select(2, dec:read(nil :: any)), 4096, "read(nil) = 4096 frames") + dec:seek(nil :: any) + t:eq(select(2, dec:position()), 0, "seek(nil)") + dec:seek(0 / 0) + t:check(select(2, dec:position()) >= 0, "seek(nan)") + t:eq(select(2, dec:read(0 / 0)), 0, "read(nan)") + t:eq(Mp3.sniff(Bytes.reader(buffer.fromstring("RIFF....WAVEfmt "))), 0, "sniff a WAV") + t:eq(Mp3.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") +end + +-- ------------------------------------------------------------------------------------------------ tags +local function eq(a: any, b: any, label: string) + t:eq(a, b, label) +end +do + local dec = assert(open(file("l3_tags"))) + local tg = dec.tags + eq(dec.id3.id3v2, "2.3", "fixture id3v2") + eq(tg.title, "Test Title", "fixture title") + eq(tg.artist, "Some Artist", "fixture artist") + eq(tg.album, "An Album", "fixture album") + eq(tg.year, "2001", "fixture year") + eq(tg.track, "7", "fixture track") + eq(tg.genre, "Rock", "fixture genre") + eq(tg.comment, "hello", "fixture comment") + t:check(dec.id3.id3v1, "fixture id3v1") + for k, v in tg do + t:check(type(k) == "string" and type(v) == "string", "tags are strings") + end +end + +local audio = file("l3_mpeg25_8k") +local plain = assert(open(audio)) +local plainPcm, plainN = plain:readAll() + +local function syncsafe(n: number): string + return string.char(bit32.band(bit32.rshift(n, 21), 127), bit32.band(bit32.rshift(n, 14), 127), bit32.band(bit32.rshift(n, 7), 127), bit32.band(n, 127)) +end +local function be32(n: number): string + return string.char(bit32.rshift(n, 24), bit32.band(bit32.rshift(n, 16), 255), bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255)) +end +local function le32(n: number): string + return string.char(bit32.band(n, 255), bit32.band(bit32.rshift(n, 8), 255), bit32.band(bit32.rshift(n, 16), 255), bit32.rshift(n, 24)) +end +local function be24(n: number): string + return string.char(bit32.rshift(n, 16), bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255)) +end +local function utf16le(s: string): string + local out = { "\xFF\xFE" } + for _, cp in utf8.codes(s) do + if cp >= 0x10000 then + local v = cp - 0x10000 + local hi, lo = 0xD800 + bit32.rshift(v, 10), 0xDC00 + bit32.band(v, 0x3FF) + table.insert(out, string.char(bit32.band(hi, 255), bit32.rshift(hi, 8), bit32.band(lo, 255), bit32.rshift(lo, 8))) + else + table.insert(out, string.char(bit32.band(cp, 255), bit32.rshift(cp, 8))) + end + end + return table.concat(out) +end +local function withAudio(prefix: string, suffix: string?): buffer + return buffer.fromstring(prefix .. buffer.tostring(audio) .. (suffix or "")) +end +local function sameAudio(dec: any, label: string) + eq(dec.frames, plain.frames, label .. ": frames") + local pcm, n = dec:readAll() + t:check(n == plainN and maxDiff(pcm, 0, plainPcm, 0, n) == 0, label .. ": same samples") +end + +-- ID3v2.4: UTF-8, syncsafe frame sizes, an extended header, multi-value TPE1, numeric TCON, padding +do + local function frame(id: string, body: string): string + return id .. syncsafe(#body) .. "\0\0" .. body + end + local frames = frame("TIT2", "\3Ünïcödé ★ title") .. frame("TPE1", "\3One\0Two") .. frame("TCON", "\3(17)") .. frame("TDRC", "\0" .. "1999-05-01") .. frame("COMM", "\3eng\0a comment") .. string.rep("\0", 64) + local body = syncsafe(6) .. "\1\0" .. frames + local tag = "ID3\4\0\x40" .. syncsafe(#body) .. body + local dec = assert(open(withAudio(tag))) + eq(dec.id3.id3v2, "2.4", "v2.4 version") + eq(dec.tags.title, "Ünïcödé ★ title", "v2.4 title") + eq(dec.tags.artist, "One / Two", "v2.4 multi-value") + eq(dec.tags.genre, "Rock", "v2.4 genre") + eq(dec.tags.year, "1999-05-01", "v2.4 TDRC") + eq(dec.tags.comment, "a comment", "v2.4 COMM") + sameAudio(dec, "v2.4") + t:check(Mp3.sniff(Bytes.reader(withAudio(tag))) >= 0.7, "sniff behind an ID3v2 tag") +end +-- ID3v2.3: UTF-16 with BOM (incl. a surrogate pair), latin-1, whole-tag unsynchronisation +do + local function frame(id: string, body: string): string + return id .. be32(#body) .. "\0\0" .. body + end + local frames = frame("TIT2", "\1" .. utf16le("Grüße 𝄞")) .. frame("TALB", "\0Caf\xE9") .. frame("TRCK", "\0" .. "3/12") .. frame("TCON", "\0" .. "Electronic") + local unsync = string.gsub(frames, "\xFF", "\xFF\0") + local tag = "ID3\3\0\x80" .. syncsafe(#unsync) .. unsync + local dec = assert(open(withAudio(tag))) + eq(dec.id3.id3v2, "2.3", "v2.3 version") + eq(dec.tags.title, "Grüße 𝄞", "v2.3 UTF-16 title") + eq(dec.tags.album, "Café", "v2.3 latin-1 album") + eq(dec.tags.track, "3/12", "v2.3 track") + eq(dec.tags.genre, "Electronic", "v2.3 genre") + eq(dec.id3.raw.TALB, "Café", "raw frame") + sameAudio(dec, "v2.3") +end +-- ID3v2.2: 3-character ids, 24-bit sizes +do + local function frame(id: string, body: string): string + return id .. be24(#body) .. body + end + local frames = frame("TT2", "\0Old Title") .. frame("TP1", "\0Old Artist") .. frame("TCO", "\0(8)") .. frame("COM", "\0eng\0old comment") + local tag = "ID3\2\0\0" .. syncsafe(#frames) .. frames + local dec = assert(open(withAudio(tag))) + eq(dec.id3.id3v2, "2.2", "v2.2 version") + eq(dec.tags.title, "Old Title", "v2.2 title") + eq(dec.tags.artist, "Old Artist", "v2.2 artist") + eq(dec.tags.genre, "Jazz", "v2.2 genre") + eq(dec.tags.comment, "old comment", "v2.2 comment") + sameAudio(dec, "v2.2") +end +-- ID3v1.1 alone (track byte), then APEv2 + ID3v1 at the end +do + local function pad(s: string, n: number): string + return s .. string.rep("\0", n - #s) + end + local v1 = "TAG" .. pad("V1 Title", 30) .. pad("V1 Artist", 30) .. pad("V1 Album", 30) .. "1987" .. pad("v1 comment", 28) .. "\0\9" .. "\17" + local dec = assert(open(withAudio("", v1))) + t:check(dec.id3.id3v1, "v1 flag") + eq(dec.tags.title, "V1 Title", "v1 title") + eq(dec.tags.artist, "V1 Artist", "v1 artist") + eq(dec.tags.album, "V1 Album", "v1 album") + eq(dec.tags.year, "1987", "v1 year") + eq(dec.tags.comment, "v1 comment", "v1 comment") + eq(dec.tags.track, "9", "v1.1 track") + eq(dec.tags.genre, "Rock", "v1 genre") + sameAudio(dec, "v1") + local item = "\5\0\0\0" .. "\0\0\0\0" .. "Title\0" .. "hello" + local size = #item + 32 + local function apeHdr(isHeader: boolean): string + local flags = if isHeader then "\0\0\0\xA0" else "\0\0\0\x80" + return "APETAGEX" .. "\xD0\7\0\0" .. le32(size) .. "\1\0\0\0" .. flags .. string.rep("\0", 8) + end + local ape = apeHdr(true) .. item .. apeHdr(false) + local dec2 = assert(open(withAudio("", ape .. v1))) + t:check(dec2.id3.ape, "ape flag") + eq(dec2.tags.title, "V1 Title", "ape + v1 title") + sameAudio(dec2, "ape + v1") +end +-- a truncated ID3v2 tag never throws +do + local tag = "ID3\3\0\0" .. syncsafe(5000) .. "TIT2" .. be32(4000) .. "\0\0\0abc" + local ok, dec = pcall(open, withAudio(tag)) + t:check(ok, "truncated tag does not throw") + t:check(dec == nil or dec.frames <= plain.frames, "truncated tag") +end + +-- ------------------------------------------------------------------------------------------------ through the api +do + local F = require("@formats") + local data = byName.l3_tags.data + t:eq(F.detect(data), "mp3", "F.detect") + local a, err = F.audio.load(data) + t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err)) + local dec = F.audio.open(data) + t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open") + local _, serr = F.save(a, nil, { format = "mp3" }) + t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, name in { "l3_cbr32_mono", "l3_mpeg2_22k", "l3_mpeg25_8k", "l2_64_mono", "l2_mpeg2_24k", "l3_tags", "lame_cbr64_mono_22k" } do + local s = byName[name].data + table.insert(samples, string.sub(s, 1, math.min(#s, 6000))) + end + t:fuzz("open + read + seek", function(b: buffer) + local dec = Mp3.open(Bytes.reader(b)) + if dec then + dec:read(1 + rand(5000)) + dec:seek(dec.duration * rand(100) / 100) + dec:read(1 + rand(5000)) + dec:seekFrame(rand(dec.frames + 1)) + dec:readAll() + end + Mp3.sniff(Bytes.reader(b)) + return dec + end, samples, { mutations = 12 }) + t:fuzz("decode", function(b: buffer) + return Mp3.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau new file mode 100644 index 0000000..c876dce --- /dev/null +++ b/tests/audio/opus.luau @@ -0,0 +1,445 @@ +-- audio/opus tests: every fixture (opusenc / ffmpeg libopus: CELT frame sizes and bitrates, SILK NB / MB / WB, hybrid, +-- mode transitions, 5.1 multistream, a long tagged file) through open / read against opusdec --float (frame counts, +-- SNR per fixture), CELT-only and SILK-only decoding with the private decoders alone, SILK packet loss concealment, +-- tags, seeking, the stereo downmix, decode() to an Audio, the contract, sniff, error codes, random / bit-flipped +-- packets through the packet decoder, and the fuzz no-throw pass over whole files. +-- Ported from opus-luau tests/opus.luau, celt.luau, silk.luau, fuzz.luau. Fixtures: tools/fixtures/opus.py. +local T = require("@tests/T") +local Opus = require("@formats/audio/opus") +local Packet = require("@formats/audio/opus/Packet") +local Celt = require("@formats/audio/opus/Celt") +local Silk = require("@formats/audio/opus/Silk") +local RD = require("@formats/audio/opus/RangeDecoder") +local Decoder = require("@formats/audio/opus/Decoder") +local Ogg = require("@formats/containers/Ogg") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") + +local t = T.suite("opus") + +local FX: { [string]: any } = {} +for _, f in + { + require("@tests/gen/opus_celt_st_128"), + require("@tests/gen/opus_celt_st_32"), + require("@tests/gen/opus_celt_st_64"), + require("@tests/gen/opus_celt_st_256"), + require("@tests/gen/opus_celt_mono_64"), + require("@tests/gen/opus_celt_fs2_5"), + require("@tests/gen/opus_celt_fs5"), + require("@tests/gen/opus_celt_fs10"), + require("@tests/gen/opus_celt_fs40"), + require("@tests/gen/opus_celt_fs60"), + require("@tests/gen/opus_silk_nb"), + require("@tests/gen/opus_silk_mb"), + require("@tests/gen/opus_silk_wb"), + require("@tests/gen/opus_silk_wb_st"), + require("@tests/gen/opus_silk_nb_st"), + require("@tests/gen/opus_hybrid_swb"), + require("@tests/gen/opus_hybrid_fb"), + require("@tests/gen/opus_hybrid_st"), + require("@tests/gen/opus_mix_st_24"), + require("@tests/gen/opus_surround51"), + require("@tests/gen/opus_long_128"), + require("@tests/gen/opus_ff_cbr"), + require("@tests/gen/opus_ff_voip"), + require("@tests/gen/opus_ff_lowdelay"), + } +do + FX[f.name] = { data = buffer.fromstring(f.data), ref = buffer.fromstring(f.ref), raw = f.data } +end + +-- SNR in dB of f32 samples against a reference over n samples; returns snr, max abs error +local function snr(out: buffer, ref: buffer, n: number, outOff: number?, refOff: number?): (number, number) + local oo, ro = outOff or 0, refOff or 0 + local sig, err, maxe = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(ref, ro + i * 4) + local e = buffer.readf32(out, oo + i * 4) - r + sig += r * r + err += e * e + if math.abs(e) > maxe then + maxe = math.abs(e) + end + end + if err == 0 then + return 999, 0 + end + return 10 * math.log10(sig / err), maxe +end + +-- the packets of the first stream: { data, offset, size } +local function packets(buf: buffer): { any } + local d = Ogg.open(buf) + local out = {} + for p in d:packets(d:streams()[1].serial) do + table.insert(out, p) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ contract +t:eq(Opus.name, "opus", "name") +t:eq(Opus.category, "audio", "category") +t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps") +t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file") +t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg") +t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") + +-- ------------------------------------------------------------------------------------------------ open / read vs opusdec +-- name, minimum SNR (dB). CELT is float-exact (> 130 dB in practice), SILK bit-exact; hybrid / transitions mix both. +local cases = { + { "celt_st_128", 100 }, { "celt_st_32", 100 }, { "celt_st_64", 100 }, { "celt_st_256", 100 }, + { "celt_mono_64", 100 }, { "celt_fs2_5", 100 }, { "celt_fs5", 100 }, { "celt_fs10", 100 }, + { "celt_fs40", 100 }, { "celt_fs60", 100 }, { "ff_cbr", 100 }, { "ff_lowdelay", 100 }, + { "silk_nb", 90 }, { "silk_nb_st", 90 }, { "silk_mb", 90 }, { "silk_wb", 90 }, { "silk_wb_st", 90 }, + { "hybrid_swb", 60 }, { "hybrid_fb", 60 }, { "hybrid_st", 60 }, { "mix_st_24", 60 }, { "ff_voip", 60 }, + { "surround51", 100 }, { "long_128", 100 }, +} +for _, case in cases do + local name, minSnr = case[1], case[2] + local fx = FX[name] + local dec, err = Opus.open(Bytes.reader(fx.data)) + t:check(dec, name .. ": open: " .. tostring(err)) + local ch = dec.channels + local refFrames = buffer.len(fx.ref) // 4 // ch + t:eq(dec.frames, refFrames, name .. ": frames") + t:check(dec.sampleRate == 48000 and type(dec.duration) == "number" and type(dec.bitrate) == "number" and type(dec.tags) == "table", name .. ": Decoder fields") + local out = buffer.create(dec.frames * ch * 4 + 4096) + local total = 0 + local t0 = os.clock() + while true do + local pcm, n = dec:read(1000 + total % 3001) + if n == 0 then + break + end + t:eq(buffer.len(pcm), n * ch * 4, name .. ": read buffer size") + buffer.copy(out, total * ch * 4, pcm, 0, n * ch * 4) + total += n + end + local dt = os.clock() - t0 + t:eq(total, refFrames, name .. ": decoded frames") + local db, maxe = snr(out, fx.ref, refFrames * ch) + t:note("%-12s %d ch %7d frames SNR %6.1f dB max err %.2g %.0fx real time", name, ch, total, db, maxe, dec.duration / math.max(dt, 1e-6)) + t:check(db >= minSnr, string.format("%s: SNR %.1f >= %d dB", name, db, minSnr)) + t:check(math.abs(dec:position() - dec.duration) < 1e-9, name .. ": position at end") +end + +-- read into a caller buffer, decode() to an Audio, a sub-range Reader +do + local fx = FX.hybrid_st + local dec = Opus.open(Bytes.reader(fx.data)) + local into = buffer.create(4096 * 2 * 4) + local pcm, n = dec:read(4096, into) + t:check(pcm == into and n == 4096, "read(n, out) reuses out") + local big = buffer.create(buffer.len(fx.data) + 33) + buffer.copy(big, 17, fx.data) + local a, err = Opus.decode(Bytes.reader(big, 17, buffer.len(fx.data))) + t:check(a, "decode from a sub-range: " .. tostring(err)) + t:check(a.kind == "audio" and a.sampleRate == 48000 and a.channels == 2, "decode: an Audio") + t:eq(a.frames, buffer.len(fx.ref) // 8, "decode: frames") + t:check(snr(a.samples, fx.ref, a.frames * 2) >= 60, "decode: samples") + t:eq(a.meta.source.format, "opus", "decode: meta.source") +end + +-- ------------------------------------------------------------------------------------------------ tags, seeking +do + local dec = Opus.open(Bytes.reader(FX.long_128.data)) + t:eq(dec.tags.title, "Long Test", "tags: title") + t:eq(dec.tags.artist, "opus-luau", "tags: artist") + t:check(dec.sampleRate == 48000 and dec.channels == 2, "info") + t:check(math.abs(dec.duration - 12) < 0.01, "duration ~12 s") + t:check(dec.bitrate > 100000 and dec.bitrate < 200000, "bitrate ~128 kbps: " .. dec.bitrate) + -- 80 ms pre-roll makes the decoder state converge after a seek + local ref = FX.long_128.ref + for _, s in { 0, 0.001, 1.5, 3.21, 6.0, 9.99, 11.7, 2.0, 0.05 } do + dec:seek(s) + local p = math.floor(s * 48000 + 0.5) + t:check(math.abs(dec:position() - p / 48000) < 1e-9, string.format("seek %.3f: position", s)) + local pcm, n = dec:read(12000) + t:eq(n, math.min(12000, dec.frames - p), string.format("seek %.3f: read", s)) + local db = snr(pcm, ref, n * 2, 0, p * 2 * 4) + t:check(db > 50, string.format("seek %.3f: SNR %.1f > 50 dB", s, db)) + end + dec:seek(100) + local _, n = dec:read(100) + t:eq(n, 0, "seek past the end reads nothing") + dec:seek(0) + local _, n2 = dec:read(100) + t:eq(n2, 100, "seek back to 0") + dec:seek(0 / 0) + t:eq(dec:position(), 0, "seek(nan) goes to 0") +end + +-- stereo downmix of the 5.1 file: the same matrix applied to the reference +do + local fx = FX.surround51 + local dec = Opus.open(Bytes.reader(fx.data), { stereo = true }) + t:check(dec.channels == 2 and dec.sourceChannels == 6, "downmix: 2 output channels") + local pcm, n = dec:read(dec.frames) + t:eq(n, dec.frames, "downmix: all frames") + local m = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 } + local exp = buffer.create(n * 8) + for i = 0, n - 1 do + local l, r = 0, 0 + for c = 0, 5 do + local v = buffer.readf32(fx.ref, (i * 6 + c) * 4) + l += v * m[c * 2 + 1] + r += v * m[c * 2 + 2] + end + buffer.writef32(exp, i * 8, l) + buffer.writef32(exp, i * 8 + 4, r) + end + local db = snr(pcm, exp, n * 2) + t:check(db > 100, string.format("downmix SNR %.1f", db)) +end + +-- ------------------------------------------------------------------------------------------------ CELT alone +do + local endbands = { [Packet.BW_NB] = 13, [Packet.BW_MB] = 17, [Packet.BW_WB] = 17, [Packet.BW_SWB] = 19, [Packet.BW_FB] = 21 } + for _, name in { "celt_st_128", "celt_st_32", "celt_st_64", "celt_st_256", "celt_mono_64", "celt_fs2_5", "celt_fs5", "celt_fs10", "celt_fs40", "celt_fs60", "ff_cbr", "ff_lowdelay" } do + local fx = FX[name] + local pk = packets(fx.data) + local head = pk[1] + local channels = buffer.readu8(head.data, head.offset + 9) + local preskip = buffer.readu16(head.data, head.offset + 10) + local st = Celt.new(channels) + local out = {} + local total = 0 + local offs, sizes = {}, {} + local allOk = true + for p = 3, #pk do + local P = pk[p] + local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes) + allOk = allOk and count > 0 and Packet.mode(toc) == Packet.MODE_CELT_ONLY + local fs48 = Packet.samplesPerFrame(toc, 48000) + st["end"] = endbands[Packet.bandwidth(toc)] + st.stream_channels = Packet.channels(toc) + for f = 1, count do + local ret = Celt.decode(st, P.data, offs[f], sizes[f], out, 1 + total * channels, fs48, nil, false) + allOk = allOk and ret == fs48 + total += fs48 + end + end + t:check(allOk, name .. ": every packet is CELT-only and decodes") + local refFrames = buffer.len(fx.ref) // 4 // channels + t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": CELT sample count") + local n = refFrames * channels + local ob = buffer.create(n * 4) + for i = 0, n - 1 do + buffer.writef32(ob, i * 4, out[preskip * channels + i + 1]) + end + local db = snr(ob, fx.ref, n) + t:check(db > 60, string.format("%s: CELT alone SNR %.1f > 60 dB", name, db)) + end +end + +-- ------------------------------------------------------------------------------------------------ SILK alone +do + local rates = { [Packet.BW_NB] = 8000, [Packet.BW_MB] = 12000, [Packet.BW_WB] = 16000 } + local function decodeSilk(name: string, hybridOk: boolean?, lose: boolean?): ({ number }, number, number, number) + local pk = packets(FX[name].data) + local channels = buffer.readu8(pk[1].data, pk[1].offset + 9) + local preskip = buffer.readu16(pk[1].data, pk[1].offset + 10) + local st = Silk.new(channels) + local out = {} + local total = 0 + local offs, sizes = {}, {} + local allOk = true + for p = 3, #pk do + local P = pk[p] + local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes) + local mode = Packet.mode(toc) + allOk = allOk and count > 0 and (mode == Packet.MODE_SILK_ONLY or (hybridOk == true and mode == Packet.MODE_HYBRID)) + local fs48 = Packet.samplesPerFrame(toc, 48000) + local lostPacket = lose and p % 7 == 0 and p < #pk - 80 + local ctrl = { + nChannelsAPI = channels, + nChannelsInternal = Packet.channels(toc), + API_sampleRate = 48000, + internalSampleRate = if mode == Packet.MODE_HYBRID then 16000 else rates[Packet.bandwidth(toc)], + payloadSize_ms = math.max(10, fs48 // 48), + } + for f = 1, count do + local lost = if lostPacket or sizes[f] <= 1 then 1 else 0 + local ec = RD.new(P.data, offs[f], sizes[f]) + local decoded = 0 + repeat + local ret, n = Silk.decode(st, ctrl, lost, decoded == 0, ec, out, 1 + (total + decoded) * channels) + allOk = allOk and ret == 0 + decoded += n + until decoded >= fs48 or n <= 0 + total += decoded + end + end + t:check(allOk, name .. ": every packet is SILK and decodes") + return out, total, channels, preskip + end + for _, name in { "silk_nb", "silk_nb_st", "silk_mb", "silk_wb", "silk_wb_st" } do + local out, total, channels, preskip = decodeSilk(name) + local ref = FX[name].ref + local refFrames = buffer.len(ref) // 4 // channels + t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": SILK sample count") + local n = refFrames * channels + local ob = buffer.create(n * 4) + for i = 0, n - 1 do + buffer.writef32(ob, i * 4, out[preskip * channels + i + 1]) + end + local db = snr(ob, ref, n) + t:check(db > 90, string.format("%s: SILK alone SNR %.1f > 90 dB", name, db)) + end + local _, total = decodeSilk("hybrid_swb", true) + t:check(total > 0, "hybrid_swb: SILK layer decodes") + -- packet loss concealment: every 7th packet lost; output bounded, the last second matches again + for _, name in { "silk_nb", "silk_wb_st" } do + local out, tot, channels, preskip = decodeSilk(name, false, true) + local finite = true + for i = 1, tot * channels do + local v = out[i] + if v ~= v or math.abs(v) > 1 then + finite = false + end + end + t:check(finite, name .. ": PLC output bounded") + local ref = FX[name].ref + local refFrames = buffer.len(ref) // 4 // channels + local n = 48000 * channels + local from = (refFrames - 48000) * channels + local ob = buffer.create(n * 4) + for i = 0, n - 1 do + buffer.writef32(ob, i * 4, out[preskip * channels + from + i + 1]) + end + local db = snr(ob, ref, n, 0, from * 4) + t:check(db > 15, string.format("%s: recovers after losses (last second SNR %.1f)", name, db)) + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local d, err = Opus.open(Bytes.reader(buffer.fromstring("not an ogg file at all"))) + t:check(d == nil and err and err.code == Err.CORRUPT, "garbage is CORRUPT: " .. tostring(err)) + local _, e2 = Opus.open(Bytes.reader(FX.celt_st_128.data, 0, 40)) + t:check(e2 and Err.is(e2), "a cut header is an Err: " .. tostring(e2)) + local _, e3 = Opus.decode(Bytes.reader(buffer.create(0))) + t:check(e3 and Err.is(e3), "empty decode is an Err") + -- a truncated file opens and decodes its first half + local file = FX.hybrid_st.data + local cut = buffer.create(buffer.len(file) // 2) + buffer.copy(cut, 0, file, 0, buffer.len(cut)) + local dec = Opus.open(Bytes.reader(cut)) + t:check(dec, "truncated file opens") + local total = 0 + while true do + local _, n = dec:read(4096) + if n == 0 then + break + end + total += n + end + t:check(total > 0, "truncated file decodes its first half") + local a = Opus.decode(Bytes.reader(cut)) + t:check(a and a.frames == total, "decode of a truncated file keeps what decoded") + -- damaged packets (CRC checks off, so they reach the decoder) never throw + for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "surround51" } do + local g = buffer.create(buffer.len(FX[name].data)) + buffer.copy(g, 0, FX[name].data) + local seed = 12345 + for i = 400, buffer.len(g) - 1, 97 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writeu8(g, i, bit32.bxor(buffer.readu8(g, i), seed % 256)) + end + local dd = Opus.open(Bytes.reader(g), { verify = false }) + t:check(dd, name .. ": damaged file opens") + local ok, e = pcall(function() + while true do + local _, n = dd:read(4096) + if n == 0 then + break + end + end + end) + t:check(ok, name .. ": damaged data decodes without error: " .. tostring(e)) + end +end + +-- ------------------------------------------------------------------------------------------------ packet fuzz +-- random packets (every TOC config, random payloads) and bit-flipped real packets: never throw, output finite +do + local rand = T.rng(987654321) + local pcm = table.create(5760 * 2, 0) + local decoded, rejected, bad = 0, 0, 0 + local function run(dec: any, b: buffer, len: number) + local ok, n = pcall(Decoder.decode, dec, b, 0, len, pcm, 1, 5760) + if not ok then + bad += 1 + return + end + if n > 0 then + decoded += 1 + for i = 1, n * dec.channels do + local v = pcm[i] + if v ~= v or v == math.huge or v == -math.huge then + bad += 1 + break + end + end + else + rejected += 1 + end + end + for _, ch in { 1, 2 } do + local dec = Decoder.new(ch) + for i = 1, 1500 do + local len = 1 + rand(if rand(4) == 0 then 1275 else 120) + local b = buffer.create(len) + for k = 0, len - 1 do + buffer.writeu8(b, k, rand(256)) + end + buffer.writeu8(b, 0, (i * 7 + ch) % 256) -- cycle through every TOC + run(dec, b, len) + if rand(50) == 0 then + Decoder.decode(dec, nil, 0, 0, pcm, 1, 960) -- concealment in between + end + end + end + for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "mix_st_24", "celt_fs2_5" } do + local pk = packets(FX[name].data) + local dec = Decoder.new(2) + for p = 3, #pk do + local P = pk[p] + local b = buffer.create(P.size) + buffer.copy(b, 0, P.data, P.offset, P.size) + for _ = 1, 1 + rand(4) do + local k = 1 + rand(math.max(1, P.size - 1)) + if k < P.size then + buffer.writeu8(b, k, bit32.bxor(buffer.readu8(b, k), bit32.lshift(1, rand(8)))) + end + end + run(dec, b, P.size) + end + end + t:eq(bad, 0, "packet fuzz: no throws, finite output") + t:note("packet fuzz: %d packets decoded, %d rejected", decoded, rejected) +end + +-- ------------------------------------------------------------------------------------------------ fuzz (whole files) +do + local samples = {} + for _, name in { "hybrid_fb", "silk_nb", "celt_fs5" } do + table.insert(samples, string.sub(FX[name].raw, 1, 6000)) + end + t:fuzz("open + read", function(b: buffer) + local dec = Opus.open(Bytes.reader(b), { verify = false }) + if dec then + dec:read(2000) + dec:seek(0.01) + dec:read(500) + end + return dec + end, samples, { mutations = 12, keepHeader = 4 }) + t:fuzz("decode", function(b: buffer) + return Opus.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/wav.luau b/tests/audio/wav.luau new file mode 100644 index 0000000..dda6de4 --- /dev/null +++ b/tests/audio/wav.luau @@ -0,0 +1,314 @@ +-- audio/wav tests: every format / container / damaged variant from tools/fixtures/wav.py decoded in reads of mixed +-- sizes against ffmpeg's (or sox's) f32 decode, with tags, seeking and output-buffer reuse; hand-built files (header +-- parsing, errors, argument clamping, EXTENSIBLE with valid bits, the truncated flag); the encoder byte-exact against +-- ffmpeg -bitexact (u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64), round trips from an Audio and from a +-- streaming Decoder, tags, encodeParts, the RF64 switch; the api (F.audio.load / open / save); the fuzz pass. +-- Ported from wav-luau tests/core.luau + tests/decode.luau. Fixtures: tools/fixtures/wav.py. +local T = require("@tests/T") +local Wav = require("@formats/audio/wav") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local Cases = require("@tests/gen/wav_cases") +local Enc = require("@tests/gen/wav_enc") + +local t = T.suite("wav") +local TOL = 2e-6 + +local function open(s: any): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Wav.open(Bytes.reader(b)) +end + +-- little-endian packers (no string.pack on LuaJIT) +local function u16(v: number): string + local b = buffer.create(2) + buffer.writeu16(b, 0, v % 65536) + return buffer.tostring(b) +end +local function u32(v: number): string + local b = buffer.create(4) + buffer.writeu32(b, 0, v % 4294967296) + return buffer.tostring(b) +end +local function i32(v: number): string + local b = buffer.create(4) + buffer.writei32(b, 0, v) + return buffer.tostring(b) +end +local function f32(v: number): string + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return buffer.tostring(b) +end +local function i16s(...: number): string + local out = {} + for i, v in { ... } do + out[i] = u16(if v < 0 then v + 65536 else v) + end + return table.concat(out) +end + +local function chunk(id: string, body: string): string + local s = id .. u32(#body) .. body + return if #body % 2 == 1 then s .. "\0" else s +end +local function fmt(tag: number, ch: number, rate: number, bits: number, extra: string?): string + local ba = ch * ((bits + 7) // 8) + return chunk("fmt ", u16(tag) .. u16(ch) .. u32(rate) .. u32(rate * ba) .. u16(ba) .. u16(bits) .. (extra or "")) +end +local function riff(...: string): string + local body = "WAVE" .. table.concat({ ... }) + return "RIFF" .. u32(#body) .. body +end + +-- the contract +t:eq(Wav.name, "wav", "name") +t:eq(Wav.category, "audio", "category") +t:check(Wav.caps.decode and Wav.caps.encode and Wav.open ~= nil, "caps / open") + +-- ------------------------------------------------------------------------------------------------ fixtures +local function readAll(dec: any, sizes: { number }): (buffer, number) + local out = buffer.create(dec.frames * dec.channels * 4) + local got, i = 0, 0 + while true do + i += 1 + local c, n = dec:read(sizes[(i - 1) % #sizes + 1]) + if n == 0 then + break + end + buffer.copy(out, got * dec.channels * 4, c, 0, n * dec.channels * 4) + got += n + end + return out, got +end +local function maxDiff(a: buffer, aOff: number, b: buffer, bOff: number, count: number): number + local m = 0 + for i = 0, count - 1 do + local d = math.abs(buffer.readf32(a, (aOff + i) * 4) - buffer.readf32(b, (bOff + i) * 4)) + if d > m then + m = d + end + end + return m +end + +local samples = {} +for _, fx in Cases do + local name = fx.name + table.insert(samples, fx.file) + local ref = buffer.fromstring(fx.ref) + local dec, err = open(fx.file) + t:check(dec, name .. ": open: " .. tostring(err)) + t:eq(dec.channels, fx.channels, name .. ": channels") + t:eq(dec.sampleRate, fx.rate, name .. ": rate") + t:eq(dec.format, fx.format, name .. ": format") + t:eq(dec.container, fx.container, name .. ": container") + t:eq(dec.frames, fx.frames, name .. ": frames") + t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration") + t:check(dec.bitrate > 0, name .. ": bitrate") + for k, v in fx.tags or {} do + t:eq(dec.tags[k], v, name .. ": tag " .. k) + end + local out, got = readAll(dec, { 1, 7, 333, 1000, 4096 }) + t:eq(got, fx.frames, name .. ": frames read") + local d = maxDiff(out, 0, ref, 0, got * fx.channels) + t:check(d <= TOL, string.format("%s: max sample error %g", name, d)) + t:eq(dec:position(), fx.frames / fx.rate, name .. ": position at the end") + for _, f0 in { 1234, 0, fx.frames - 20, 517, 2047 } do + local f = math.min(f0, fx.frames) + dec:seek(f / fx.rate) + t:eq(dec:tell(), f, name .. ": seek to " .. f) + local c, n = dec:read(50) + t:eq(n, math.min(50, fx.frames - f), name .. ": read after seek " .. f) + t:check(maxDiff(c, 0, ref, f * fx.channels, n * fx.channels) <= TOL, name .. ": samples after seek " .. f) + end + dec:seek(0) + local reuse = buffer.create(64 * fx.channels * 4) + local b2, n2 = dec:read(64, reuse) + t:check(b2 == reuse and n2 == 64, name .. ": output buffer reused") + -- decode() = the whole stream as an Audio, also from a sub-range reader + local big = buffer.create(#fx.file + 9) + buffer.writestring(big, 5, fx.file) + local a, aerr = Wav.decode(Bytes.reader(big, 5, #fx.file)) + t:check(a and a.kind == "audio" and a.frames == fx.frames, name .. ": decode: " .. tostring(aerr)) + t:check(maxDiff(a.samples, 0, ref, 0, a.frames * fx.channels) <= TOL, name .. ": decode samples") + t:eq(a.meta.source.codec, fx.format, name .. ": meta.source.codec") +end +t:note("%d fixture files match ffmpeg / sox", #Cases) + +-- ------------------------------------------------------------------------------------------------ hand-built files +do + local dec = open(riff(fmt(1, 2, 8000, 16), chunk("data", i16s(16384, -16384, 32767, -32768)))) + t:check(dec, "open minimal") + t:check(dec.frames == 2 and dec.channels == 2 and dec.sampleRate == 8000 and dec.bitrate == 8000 * 4 * 8, "minimal fields") + t:check(dec.duration == 2 / 8000 and dec.blockAlign == 4 and dec.bitsPerSample == 16 and not dec.truncated, "minimal more") + local out, n = dec:read(10) + t:eq(n, 2, "read clamps to the stream") + t:check(buffer.readf32(out, 0) == 0.5 and buffer.readf32(out, 4) == -0.5, "s16 values") + t:check(buffer.readf32(out, 8) == 32767 / 32768 and buffer.readf32(out, 12) == -1, "s16 extremes") + t:eq(select(2, dec:read(10)), 0, "end of stream = 0 frames") + dec:seek(-5) + t:eq(dec:tell(), 0, "seek negative") + dec:seek(1e9) + t:eq(dec:tell(), 2, "seek past the end") + dec:seek(0 / 0) + t:eq(dec:tell(), 0, "seek NaN") + dec:seekFrame(1) + t:eq(dec:position(), 1 / 8000, "seekFrame / position") + t:eq(select(2, dec:read(-3)), 0, "read negative") + t:eq(select(2, dec:read(0 / 0)), 0, "read NaN") + local b, n5 = dec:read(1, buffer.create(2)) + t:check(n5 == 1 and buffer.len(b) == 8, "too-small output buffer is replaced") +end +do + local dec = open(riff(fmt(1, 1, 8000, 16), "data" .. u32(1000) .. i16s(1, 2, 3) .. "\9")) + t:check(dec and dec.frames == 3 and dec.truncated, "truncated: whole frames, flagged") +end +do -- EXTENSIBLE: 24 valid bits in a 32-bit container + local guid = u16(1) .. "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" + local ext = u16(22) .. u16(24) .. u32(3) .. guid + local dec = open(riff(fmt(0xFFFE, 2, 48000, 32, ext), chunk("data", i32(0x40000000) .. i32(-0x40000000)))) + t:check(dec and dec.format == "pcm" and dec.validBits == 24 and dec.channelMask == 3, "extensible fields") + local out = dec:read(1) + t:check(buffer.readf32(out, 0) == 0.5 and buffer.readf32(out, 4) == -0.5, "extensible values") + local guidF = u16(3) .. string.sub(guid, 3) + local fd = open(riff(fmt(0xFFFE, 1, 48000, 32, u16(22) .. u16(32) .. u32(4) .. guidF), chunk("data", f32(0.25)))) + t:check(fd and fd.format == "float" and buffer.readf32(fd:read(1), 0) == 0.25, "extensible float") + local _, e = open(riff(fmt(0xFFFE, 1, 8000, 16), chunk("data", "\0\0"))) + t:check(e and e.code == Err.CORRUPT, "extensible without extension") +end +do -- tags + local info = "INFO" .. "INAM" .. u32(3) .. "abc\0" .. "IART" .. u32(6) .. "xy\0\0\0\0" .. "IXYZ" .. u32(2) .. "zz" .. "ITRK" .. u32(2) .. "7\0" + local dec = open(riff(fmt(1, 1, 8000, 8), chunk("LIST", info), chunk("data", "\128\128\128"))) + t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.IXYZ == "zz" and dec.tags.track == "7", "tags") + t:check(dec and dec.frames == 3, "8-bit odd data") +end +do -- 8-bit, A-law and mu-law values + local o = open(riff(fmt(1, 1, 8000, 8), chunk("data", "\0\128\255"))):read(3) + t:check(buffer.readf32(o, 0) == -1 and buffer.readf32(o, 4) == 0 and buffer.readf32(o, 8) == 127 / 128, "u8 values") + local m = open(riff(fmt(7, 1, 8000, 8), chunk("data", "\255\127\0\128"))):read(4) + t:check(buffer.readf32(m, 0) == 0 and buffer.readf32(m, 4) == 0, "mu-law zero") + t:check(buffer.readf32(m, 8) == -32124 / 32768 and buffer.readf32(m, 12) == 32124 / 32768, "mu-law extremes") + local a = open(riff(fmt(6, 1, 8000, 8), chunk("data", "\213\85\42\170"))):read(4) + t:check(buffer.readf32(a, 0) == 8 / 32768 and buffer.readf32(a, 4) == -8 / 32768, "A-law smallest") + t:check(buffer.readf32(a, 8) == -32256 / 32768 and buffer.readf32(a, 12) == 32256 / 32768, "A-law extremes") +end +do -- errors: nil, Err + local function fails(s: any, code: string, pattern: string, label: string) + local ok, dec, err = pcall(open, s) + t:check(ok, label .. ": threw " .. tostring(dec)) + t:check(dec == nil and Err.is(err) and err.code == code and string.find(err.message, pattern) ~= nil, label .. ": " .. tostring(err)) + end + fails("RIFF", Err.TRUNCATED, "too short", "too short") + fails("RIFF\0\0\0\0AVI LIST", Err.CORRUPT, "not a WAVE", "AVI") + fails("OggS\0\0\0\0WAVEfmt ", Err.CORRUPT, "not a RIFF", "ogg") + fails(riff(chunk("data", "\0\0")), Err.CORRUPT, "no fmt", "no fmt") + fails(riff(fmt(1, 2, 8000, 16)), Err.CORRUPT, "no data", "no data") + fails(riff(fmt(0x55, 2, 8000, 16), chunk("data", "")), Err.UNSUPPORTED, "format 0x0055", "mp3 in wav") + fails(riff(fmt(1, 0, 8000, 16), chunk("data", "")), Err.CORRUPT, "channel", "0 channels") + fails(riff(fmt(1, 1, 0, 16), chunk("data", "")), Err.CORRUPT, "sample rate", "rate 0") + fails(riff(fmt(3, 1, 8000, 16), chunk("data", "")), Err.UNSUPPORTED, "float size", "float16") + fails(riff(fmt(1, 1, 8000, 40), chunk("data", "")), Err.UNSUPPORTED, "PCM size", "pcm 40") + fails(riff(fmt(0x11, 2, 8000, 4), chunk("data", "")), Err.CORRUPT, "block", "ima block too small") + t:eq(Wav.sniff(Bytes.reader(buffer.fromstring(riff(fmt(1, 1, 8000, 8))))), 1, "sniff") + t:eq(Wav.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0AVI "))), 0, "sniff AVI") +end + +-- ------------------------------------------------------------------------------------------------ encoder +do + for _, c in Enc do + local a = Types.Audio.new(c.rate, c.channels, c.frames) + buffer.writestring(a.samples, 0, c.samples) + local out, err = Wav.encode(a, { sampleFormat = c.kind, rf64 = if c.rf64 then true else nil }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local same = buffer.tostring(out :: buffer) == c.file + if not same then + t:note("%s: ours %s", c.name, T.hex(out :: buffer, 80)) + t:note("%s: ffmpeg %s", c.name, T.hex(buffer.fromstring(c.file), 80)) + end + t:check(same, c.name .. ": identical to ffmpeg -bitexact") + -- and back + local back = Wav.decode(Bytes.reader(out :: buffer)) + t:check(back and back.frames == c.frames and buffer.tostring(back.samples) == c.samples, c.name .. ": round trip") + -- from a streaming Decoder (our own, over ffmpeg's file) + local dec = Wav.open(Bytes.reader(buffer.fromstring(c.file))) + local out2 = Wav.encode(dec, { sampleFormat = c.kind, rf64 = if c.rf64 then true else nil }) + t:check(out2 and buffer.tostring(out2) == c.file, c.name .. ": encode from a Decoder") + end + t:note("encoder: %d files identical to ffmpeg -bitexact", #Enc) + -- clamping and rounding + local a = Types.Audio.new(8000, 1, 6) + for i, v in { 2, -2, 0.5 / 32768, -0.5 / 32768, 1.5 / 32768, 0 / 0 } do + buffer.writef32(a.samples, (i - 1) * 4, v) + end + local d = Wav.decode(Bytes.reader(Wav.encode(a) :: buffer)) :: any + local want = { 32767, -32768, 1, 0, 2, 0 } + for i, w in want do + t:eq(math.floor(buffer.readf32(d.samples, (i - 1) * 4) * 32768 + 0.5), w, "s16 rounding / clamping " .. i) + end + -- tags + a.tags = { title = "Hello", artist = "Someone", IXYZ = "kept", comment = "" } + local tg = Wav.decode(Bytes.reader(Wav.encode(a, { sampleFormat = "u8" }) :: buffer)) :: any + t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.IXYZ == "kept" and tg.tags.comment == nil, "tag round trip") + -- encodeParts, and RF64 chosen automatically past the threshold + local big = Types.Audio.new(44100, 2, 3000) + for i = 0, 3000 * 2 - 1 do + buffer.writef32(big.samples, i * 4, ((i * 37) % 200 - 100) / 128) + end + local parts = Wav.encodeParts(big, { rf64Threshold = 1000 }) :: { buffer } + t:check(#parts >= 2, "encodeParts: pieces") + local w = Bytes.writer() + for _, p in parts do + w:bytes(p) + end + local joined = w:finish() + t:eq(buffer.readstring(joined, 0, 4), "RF64", "auto RF64 past the threshold") + local rd = Wav.open(Bytes.reader(joined)) :: any + t:check(rd.container == "RF64" and rd.frames == 3000, "RF64 reads back") + t:check(buffer.tostring(rd:read(3000)) == buffer.tostring(Wav.decode(Bytes.reader(Wav.encode(big) :: buffer)).samples), "RF64 samples") + t:eq(buffer.readstring(Wav.encode(big) :: buffer, 0, 4), "RIFF", "plain RIFF below the threshold") + -- bad arguments + local _, e1 = Wav.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode {}: " .. tostring(e1)) + local _, e2 = Wav.encode(a, { sampleFormat = "s12" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat") + local bad = Types.Audio.new(8000, 2, 10) + bad.frames = 99 + local _, e3 = Wav.encode(bad) + t:check(e3 and e3.code == Err.ARG, "short samples buffer") +end + +-- ------------------------------------------------------------------------------------------------ api +do + local c = Enc[1] + local a, err = F.audio.load(c.file) + t:check(a and a.kind == "audio" and a.frames == c.frames, "F.audio.load: " .. tostring(err)) + local dec = F.audio.open(c.file) + t:check(dec and dec.sampleRate == c.rate and type(dec.read) == "function", "F.audio.open") + local out = F.save(a, nil, { format = "wav", sampleFormat = "s16" }) + t:check(out and buffer.tostring(out) == c.file, "F.save wav") + t:eq(F.detect(c.file), "wav", "F.detect") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +t:fuzz("open + read + seek", function(b: buffer) + local dec = Wav.open(Bytes.reader(b)) + if dec then + for _ = 1, 100 do + local _, n = dec:read(1000) + if n == 0 then + break + end + end + dec:seek(dec.duration / 2) + dec:read(17) + end + return dec +end, samples, { mutations = 12 }) +t:fuzz("header mutations", function(b: buffer) + return Wav.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 50, keepHeader = 0 }) + +t:done() diff --git a/tests/codecs/url.luau b/tests/codecs/url.luau new file mode 100644 index 0000000..82075b3 --- /dev/null +++ b/tests/codecs/url.luau @@ -0,0 +1,108 @@ +-- codecs/Url + codecs/Text tests: every example of RFC 3986 section 5.4 (normal and abnormal), dot-segment removal, +-- splitting, encoding and the location helpers (ported from playlist-luau tests/url.luau); random references against +-- Python's urllib.parse.urljoin; Url.locate / Url.base; Windows-1252 decoding against Python's cp1252 codec; lines, +-- BOM, trim; the fuzz pass. Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") +local Ref = require("@tests/gen/playlist_url") +local Cp = require("@tests/gen/playlist_cp1252") + +local t = T.suite("url") +local function eq(got: any, want: any, label: string) + t:eq(got, want, label) +end + +local BASE = "http://a/b/c/d;p?q" +local cases = { + -- 5.4.1 normal + { "g:h", "g:h" }, { "g", "http://a/b/c/g" }, { "./g", "http://a/b/c/g" }, { "g/", "http://a/b/c/g/" }, + { "/g", "http://a/g" }, { "//g", "http://g" }, { "?y", "http://a/b/c/d;p?y" }, { "g?y", "http://a/b/c/g?y" }, + { "#s", "http://a/b/c/d;p?q#s" }, { "g#s", "http://a/b/c/g#s" }, { "g?y#s", "http://a/b/c/g?y#s" }, + { ";x", "http://a/b/c/;x" }, { "g;x", "http://a/b/c/g;x" }, { "g;x?y#s", "http://a/b/c/g;x?y#s" }, + { "", "http://a/b/c/d;p?q" }, { ".", "http://a/b/c/" }, { "./", "http://a/b/c/" }, { "..", "http://a/b/" }, + { "../", "http://a/b/" }, { "../g", "http://a/b/g" }, { "../..", "http://a/" }, { "../../", "http://a/" }, + { "../../g", "http://a/g" }, + -- 5.4.2 abnormal + { "../../../g", "http://a/g" }, { "../../../../g", "http://a/g" }, { "/./g", "http://a/g" }, + { "/../g", "http://a/g" }, { "g.", "http://a/b/c/g." }, { ".g", "http://a/b/c/.g" }, { "g..", "http://a/b/c/g.." }, + { "..g", "http://a/b/c/..g" }, { "./../g", "http://a/b/g" }, { "./g/.", "http://a/b/c/g/" }, + { "g/./h", "http://a/b/c/g/h" }, { "g/../h", "http://a/b/c/h" }, { "g;x=1/./y", "http://a/b/c/g;x=1/y" }, + { "g;x=1/../y", "http://a/b/c/y" }, { "g?y/./x", "http://a/b/c/g?y/./x" }, { "g?y/../x", "http://a/b/c/g?y/../x" }, + { "g#s/./x", "http://a/b/c/g#s/./x" }, { "g#s/../x", "http://a/b/c/g#s/../x" }, { "http:g", "http:g" }, +} +for _, c in cases do + eq(Url.resolve(c[1], BASE), c[2], "resolve " .. c[1]) +end +-- base with an empty path +eq(Url.resolve("g", "http://a"), "http://a/g", "empty base path") +eq(Url.resolve("g", "http://a?x"), "http://a/g", "empty base path with query") + +eq(Url.removeDotSegments("/a/b/c/./../../g"), "/a/g", "remove_dot_segments 1") +eq(Url.removeDotSegments("mid/content=5/../6"), "mid/6", "remove_dot_segments 2") + +local p = Url.split("https://user@host:8080/p/a.mp3?x=1&y#frag") +eq(p.scheme, "https", "split scheme") +eq(p.authority, "user@host:8080", "split authority") +eq(p.path, "/p/a.mp3", "split path") +eq(p.query, "x=1&y", "split query") +eq(p.fragment, "frag", "split fragment") +eq(Url.join(p), "https://user@host:8080/p/a.mp3?x=1&y#frag", "join") +local q = Url.split("a/b") +eq(q.scheme, nil, "relative has no scheme") +eq(q.authority, nil, "relative has no authority") + +eq(Url.encodeUnsafe("a b/ü%20?x=\"1\"#f"), "a%20b/%C3%BC%20?x=%221%22#f", "encodeUnsafe") +eq(Url.isWindowsPath("C:\\Music\\a.mp3"), true, "windows drive") +eq(Url.isWindowsPath("d:/x.mp3"), true, "windows drive with slash") +eq(Url.isWindowsPath("\\\\server\\share\\a.mp3"), true, "UNC") +eq(Url.isWindowsPath("http://x/a"), false, "http is not windows") +eq(Url.scheme("C:\\a.mp3"), nil, "a drive letter is not a scheme") +eq(Url.scheme("HTTPS://x"), "https", "scheme lower-cased") +eq(Url.scheme("music/a.mp3"), nil, "relative has no scheme") + + +-- Python's urljoin +for _, c in Ref do + eq(Url.resolve(c[1], c[2]), c[3], "urljoin " .. c[1] .. " against " .. c[2]) +end +t:note("%d random references resolve as urllib.parse.urljoin", #Ref) + +-- locate / base +do + local w = {} + local base, scheme = Url.base("https://h/a/list.m3u", w) + t:check(base == "https://h/a/list.m3u" and scheme == "https", "base") + local l = Url.locate(" b c.mp3 ", base, scheme) + t:check(l.url == "https://h/a/b%20c.mp3" and l.playable, "locate relative") + t:check(Url.locate("C:\\x.mp3", base, scheme).reason == "local path", "locate windows") + t:check(Url.locate("ftp://x/y", base, scheme).reason == "scheme ftp", "locate ftp") + local nb, ns = Url.base("lists/x.m3u", w) + t:check(nb == nil and ns == nil and #w == 1, "a relative base is ignored with a warning") + t:check(select(2, Url.base("C:\\Music\\l.m3u")) == "windows", "windows base") +end + +-- Text +do + for _, c in Cp do + eq(Text.toUtf8("x" .. string.char(c[1]) .. "y"), "x" .. c[2] .. "y", string.format("cp1252 0x%02x", c[1])) + end + local w = {} + Text.toUtf8("\150", w) + t:check(#w == 1, "cp1252 warning") + eq(Text.toUtf8("\239\187\191abc"), "abc", "BOM stripped") + eq(Text.toUtf8("h\u{e9}"), "h\u{e9}", "UTF-8 kept") + local ls = Text.lines("a\r\nb\rc\nd") + t:check(#ls == 4 and ls[1] == "a" and ls[2] == "b" and ls[3] == "c" and ls[4] == "d", "lines") + eq(Text.trim(" x y \t"), "x y", "trim") +end + +t:fuzz("resolve + locate", function(b: buffer) + local s = buffer.tostring(b) + Url.resolve(s, "http://a/b/c/d;p?q") + Url.resolve("g/../h", s) + Url.locate(s, "http://h/", "http") + return Text.lines(Text.toUtf8(s)) +end, { "http://a/b/../c?x#y", "C:\\a\\b.mp3", "\239\187\191#EXTM3U\r\n" }, { mutations = 30 }) + +t:done() diff --git a/tests/containers/ogg.luau b/tests/containers/ogg.luau new file mode 100644 index 0000000..0df5c7c --- /dev/null +++ b/tests/containers/ogg.luau @@ -0,0 +1,263 @@ +-- containers/Ogg tests: real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files, +-- checked packet by packet against the independent Python parser of tools/fixtures/ogg.py; seeking on each; a big +-- multiplexed file written with the muxer (bisection seeks); muxer edge cases (lacing at 255 multiples, page breaks, +-- continued packets, flush, eos); a sub-range Reader; truncated / garbage input never throws. The muxer was also +-- checked by hand against opus-tools: an opusenc file remuxed through it passes opusinfo and decodes identically. +-- Ported from ogg-luau tests/ogg.luau. Fixtures: tools/fixtures/ogg.py. +local T = require("@tests/T") +local Ogg = require("@formats/containers/Ogg") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/ogg_cases") + +local t = T.suite("ogg") + +-- seek expectations from a packet list: { size, crc, granule, bos, eos } +local function expectSeek(list: { any }, g: number): (number, number) + local start, idx = -1, 1 + for i, p in list do + if p[3] ~= -1 and p[3] <= g then + start, idx = p[3], i + 1 + end + end + return start, idx +end + +local samples = {} +for _, fx in Cases do + local buf = buffer.fromstring(fx.data) + table.insert(samples, fx.data) + local d, err = Ogg.open(buf) + t:check(d, fx.name .. ": open " .. tostring(err)) + local streams = d:streams() + t:eq(#streams, #fx.streams, fx.name .. ": stream count") + for si, es in fx.streams do + local s = streams[si] + t:eq(s.serial, es.serial, fx.name .. ": serial") + t:eq(s.codec, es.codec, fx.name .. ": codec") + t:eq(s.lastGranule, es.lastGranule, fx.name .. ": lastGranule") + t:eq(buffer.len(s.firstPacket), es.packets[1][1], fx.name .. ": first packet") + local n, gaps = 0, 0 + for p in d:packets(s.serial) do + n += 1 + if p.gap then + gaps += 1 + end + local e = es.packets[n] + t:check(e, fx.name .. ": too many packets") + t:eq(p.size, e[1], fx.name .. ": packet " .. n .. " size") + t:eq(Crc32.of(p.data, p.offset, p.size), e[2], fx.name .. ": packet " .. n .. " bytes") + t:eq(p.granule, e[3], fx.name .. ": packet " .. n .. " granule") + t:check(p.bos == e[4] and p.eos == e[5], fx.name .. ": packet " .. n .. " bos/eos") + end + t:eq(n, #es.packets, fx.name .. ": packet count") + t:eq(gaps, if fx.name == "mux_lost" and s.serial == 7 then 1 else 0, fx.name .. ": gap flags") + t:check(d:nextPacket(s.serial) == nil, fx.name .. ": end stays at end") + end + if #fx.streams > 1 then + local counts = {} + for i in streams do + counts[i] = 0 + end + local d2 = Ogg.open(buf) + local live = #streams + while live > 0 do + live = 0 + for i, s in streams do + local p = d2:nextPacket(s.serial) + if p then + live += 1 + counts[i] += 1 + t:eq(p.size, fx.streams[i].packets[counts[i]][1], fx.name .. ": interleaved read") + end + end + end + for i in streams do + t:eq(counts[i], #fx.streams[i].packets, fx.name .. ": interleaved count") + end + end + -- seeking + for _, es in fx.streams do + local serial = es.serial + local last = es.lastGranule + local targets = { -5, 0, 1, last // 3, last // 2, last - 1, last, last + 100 } + for _, p in es.packets do + if p[3] > 0 then + table.insert(targets, p[3]) + table.insert(targets, p[3] - 1) + end + end + for _, g in targets do + local start = d:seekGranule(serial, g) + local eStart, eIdx = expectSeek(es.packets, g) + if start == -1 then + eIdx = 1 -- rewound: the identification packet comes next + end + t:eq(start, eStart, fx.name .. ": seek " .. g .. " start") + local p = d:nextPacket(serial) + local e = es.packets[eIdx] + if e then + t:check(p and p.size == e[1] and Crc32.of(p.data, p.offset, p.size) == e[2], fx.name .. ": packet after seek " .. g) + else + t:check(p == nil, fx.name .. ": seek past the end") + end + end + end + -- a Reader over a sub-range of a bigger buffer + local big = buffer.create(#fx.data + 20) + buffer.writestring(big, 11, fx.data) + local ds = Ogg.open(Bytes.reader(big, 11, #fx.data)) + t:check(ds and #ds:streams() == #fx.streams, fx.name .. ": open from a sub-range Reader") + local n = 0 + for _ in ds:packets(fx.streams[1].serial) do + n += 1 + end + t:eq(n, #fx.streams[1].packets, fx.name .. ": packets from a sub-range Reader") + t:note("%-14s ok (%d streams)", fx.name, #streams) +end + +-- the muxer: a big file with 3 streams, random packet sizes, page breaks by size and count; read back + seeks +do + local rand = T.rng(12345) + local mux = Ogg.muxer({ pageSize = 4096 }) + local S = {} + for k = 1, 3 do + S[k] = { stream = mux:stream(1000 + k), serial = 1000 + k, granNow = 0, pk = {} } + end + local npk = 2500 + for i = 1, npk do + for k, st in S do + local size = if i == 1 then 30 else (if rand(50) == 0 then rand(3000) else rand(300)) + local tag = rand(256) + local b = buffer.create(size) + for j = 0, size - 1 do + buffer.writeu8(b, j, (tag + j + 1) % 256) + end + st.granNow += if i == 1 then 0 else (k * 120) + local ok, e = st.stream:packet(b, st.granNow, { flush = i == 1, eos = i == npk }) + t:check(ok, "mux packet: " .. tostring(e)) + table.insert(st.pk, { size, tag, st.granNow, Crc32.of(b) }) + end + end + local file = mux:finish() + local d = Ogg.open(file) + t:check(d and #d:streams() == 3, "big: 3 streams") + for _, st in S do + t:eq(d:stream(st.serial).lastGranule, st.granNow, "big: lastGranule") + local n = 0 + for p in d:packets(st.serial) do + n += 1 + local e = st.pk[n] + t:check(p.size == e[1] and Crc32.of(p.data, p.offset, p.size) == e[4], "big: packet " .. n) + t:check(p.bos == (n == 1) and p.eos == (n == npk), "big: bos / eos " .. n) + end + t:eq(n, npk, "big: count") + for q = 0, 100 do + local g = math.floor(st.granNow * q / 100) + local start = d:seekGranule(st.serial, g) + local p = d:nextPacket(st.serial) + t:check(start and start <= g and start >= 0, "big: seek start") + local idx + for i, e in st.pk do + if e[3] == start then + idx = i + 1 + break + end + end + local e = st.pk[idx] + if e then + t:check(p and p.size == e[1], "big: packet after seek") + else + t:check(p == nil, "big: end after seek") + end + end + end + t:note("muxer: 3 x %d packets, %d bytes, read back and seeked", npk, buffer.len(file)) + table.insert(samples, buffer.readstring(file, 0, math.min(buffer.len(file), 20000))) +end + +-- muxer edge cases: lacing at multiples of 255, a packet over 255 segments (continued pages), empty packets, +-- headers alone on their pages, finish() without eos, eos twice +do + local mux = Ogg.muxer({ pageSize = 1000 }) + local s = mux:stream(42) + local sizes = { 19, 0, 255, 510, 254, 256, 255 * 255, 255 * 255 + 1, 70000, 1, 0, 3000 } + local crcs = {} + for i, n in sizes do + local b = buffer.create(n) + for j = 0, n - 1 do + buffer.writeu8(b, j, (j * 7 + i) % 256) + end + crcs[i] = Crc32.of(b) + t:check(s:packet(b, i * 10, { flush = i <= 2 }), "edge: packet " .. i) + end + local file = mux:finish() + local ok, e = s:packet("late", 999) + t:check(not ok and e and e.code == Err.ARG, "edge: packet after the end is Err.ARG") + local d = Ogg.open(file) :: any + local i = 0 + local pages = 0 + local pos = 0 + while true do + local p = Ogg.Page.find(file, pos) + if not p then + break + end + pages += 1 + t:check(p.nsegs <= 255, "edge: segments per page") + if pages == 1 then + t:check(p.bos and p.nsegs == 1 and p.granule == 10, "edge: the first packet alone on the bos page") + end + pos = p.offset + p.size + end + for p in d:packets(42) do + i += 1 + t:eq(p.size, sizes[i], "edge: size " .. i) + t:eq(Crc32.of(p.data, p.offset, p.size), crcs[i], "edge: bytes " .. i) + t:eq(p.eos, i == #sizes, "edge: eos " .. i) + end + t:eq(i, #sizes, "edge: packet count") + t:check(pages > 70, "edge: page breaks (" .. pages .. " pages)") + t:eq(d:stream(42).lastGranule, #sizes * 10, "edge: last granule") + t:eq(d:stream(42).codec, "unknown", "edge: codec") + -- strings, ranges and bad arguments + local m2 = Ogg.muxer() + local s2 = m2:stream() + t:check(s2:packet("OpusHead" .. string.rep("\0", 11), 0, { flush = true }), "string packet") + t:check(s2:packet(buffer.fromstring("xxabcxx"), 5, nil, 2, 3), "range packet") + t:check(not s2:packet(buffer.create(3), 5, nil, 2, 3), "bad range") + t:check(not s2:packet(42 :: any, 5), "bad data") + local d2 = Ogg.open(m2:finish()) :: any + t:eq(d2:streams()[1].codec, "opus", "codec of a muxed OpusHead") + t:eq(d2:streams()[1].serial, 1, "default serial") + d2:nextPacket(1) + local p = d2:nextPacket(1) + t:eq(buffer.readstring(p.data, p.offset, p.size), "abc", "range packet bytes") + t:check(d2:nextPacket(1) == nil, "empty eos page ends the stream") +end + +-- errors and garbage +do + local _, e1 = Ogg.open(buffer.create(0)) + t:check(e1 and e1.code == Err.CORRUPT, "empty: " .. tostring(e1)) + t:check(Ogg.open(buffer.fromstring(string.rep("OggS", 100))) == nil, "garbage") + local _, e2 = Ogg.open(42 :: any) + t:check(e2 and e2.code == Err.ARG, "not a buffer: " .. tostring(e2)) +end + +-- fuzz: open + read every packet + seek never throws +t:fuzz("open + read + seek", function(b: buffer) + local d = Ogg.open(b) + if d then + for _, s in d:streams() do + for _ in d:packets(s.serial) do + end + d:seekGranule(s.serial, s.lastGranule // 2) + d:nextPacket(s.serial) + end + end + return d +end, samples, { mutations = 6 }) + +t:done() diff --git a/tests/containers/riff.luau b/tests/containers/riff.luau new file mode 100644 index 0000000..82c8cf3 --- /dev/null +++ b/tests/containers/riff.luau @@ -0,0 +1,114 @@ +-- containers/Riff tests: the writer (RIFF, RIFX, forced RF64 with ds64, LIST/INFO, odd pad bytes, parts) read back by +-- the reader; lenient reading (missing pad byte, truncated chunk, open-ended data of size 0 / 0xFFFFFFFF, the ds64 +-- table, a sub-range Reader); errors; the fuzz pass. The WAVE form is checked against ffmpeg in tests/audio/wav.luau. +local T = require("@tests/T") +local Riff = require("@formats/containers/Riff") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") + +local t = T.suite("riff") + +local function u32(v: number): string + local b = buffer.create(4) + buffer.writeu32(b, 0, v) + return buffer.tostring(b) +end + +-- writer -> reader +local samples = {} +for _, mode in { "riff", "rifx", "rf64" } do + local w = Riff.writer("TEST", { bigEndian = mode == "rifx", rf64 = mode == "rf64", sampleCount = 77 }) + w:chunk("abcd", "odd") + w:chunk("efgh", buffer.fromstring("xxevenxx"), 2, 4) + w:list("INFO", { { "INAM", "name" }, { "IART", buffer.fromstring("raw") } }) + w:chunk("data", { buffer.fromstring("12345"), buffer.fromstring("678") }) + local file = w:finish() :: buffer + table.insert(samples, buffer.tostring(file)) + local f, err = Riff.read(Bytes.reader(file)) + t:check(f, mode .. ": read: " .. tostring(err)) + t:eq(f.container, if mode == "rifx" then "RIFX" elseif mode == "rf64" then "RF64" else "RIFF", mode .. ": container") + t:eq(f.form, "TEST", mode .. ": form") + t:eq(f.size, buffer.len(file) - 8, mode .. ": RIFF size") + local ids = {} + for _, c in f.chunks do + table.insert(ids, c.id) + end + t:eq(table.concat(ids, ","), if mode == "rf64" then "ds64,abcd,efgh,LIST,data" else "abcd,efgh,LIST,data", mode .. ": chunks") + local a = Riff.find(f, "abcd") :: any + t:check(a.size == 3 and buffer.readstring(file, a.offset, 3) == "odd", mode .. ": odd chunk") + local e = Riff.find(f, "efgh") :: any + t:eq(buffer.readstring(file, e.offset, e.size), "even", mode .. ": range chunk") + local l = Riff.find(f, "LIST") :: any + t:eq(Riff.listType(f, l), "INFO", mode .. ": list type") + local subs = Riff.list(f, l) + t:check(#subs == 2 and subs[1].id == "INAM" and buffer.readstring(file, subs[1].offset, subs[1].size) == "name\0", mode .. ": INFO item") + t:check(subs[2].size == 3 and subs[2].avail == 3, mode .. ": raw item") + local d = Riff.find(f, "data") :: any + t:check(d.size == 8 and buffer.readstring(file, d.offset, 8) == "12345678", mode .. ": data parts") + t:eq(buffer.tostring(Riff.body(f, d):bytes(8)), "12345678", mode .. ": body reader") + if mode == "rf64" then + t:check(f.ds64 and f.ds64.dataSize == 8 and f.ds64.sampleCount == 77 and d.declared == 0xFFFFFFFF, "rf64: ds64") + end + -- parts: the same bytes + local parts = w:finish({ parts = true }) :: { buffer } + local j = Bytes.writer() + for _, p in parts do + j:bytes(p) + end + t:check(buffer.tostring(j:finish()) == buffer.tostring(file), mode .. ": parts join to the file") +end +t:check(not Riff.writer("WAVE", { bigEndian = true, rf64 = true }):finish(), "RIFX RF64 refused") + +-- lenient reading +do + -- a missing pad byte after an odd chunk + local body = "WAVE" .. "abcd" .. u32(5) .. "12345" .. "next" .. u32(2) .. "ok" + local f = Riff.read(buffer.fromstring("RIFF" .. u32(#body) .. body)) :: any + t:check(#f.chunks == 2 and f.chunks[2].id == "next", "missing pad byte detected") + -- truncated + local tb = "WAVE" .. "data" .. u32(100) .. "short" + local ft = Riff.read(buffer.fromstring("RIFF" .. u32(#tb) .. tb)) :: any + t:check(ft.chunks[1].truncated and ft.chunks[1].avail == 5 and ft.chunks[1].size == 100, "truncated chunk") + -- open-ended + for _, sz in { 0, 0xFFFFFFFF } do + local ob = "WAVE" .. "data" .. u32(sz) .. "abcdefLIST" + local fo = Riff.read(buffer.fromstring("RIFF" .. u32(0) .. ob), { openEnded = { data = true } }) :: any + t:check(#fo.chunks == 1 and fo.chunks[1].streamed and fo.chunks[1].size == 10, "open-ended data " .. sz) + end + -- ds64 table + local ds = "ds64" .. u32(40) .. u32(0) .. u32(0) .. u32(4) .. u32(0) .. u32(0) .. u32(0) .. u32(1) .. "big " .. u32(3) .. u32(0) + local rb = "WAVE" .. ds .. "big " .. u32(0xFFFFFFFF) .. "xyz" .. "\0" + local fr = Riff.read(buffer.fromstring("RF64" .. u32(0xFFFFFFFF) .. rb)) :: any + t:check(fr.ds64 and fr.ds64.table["big "] == 3 and fr.chunks[2].size == 3, "ds64 table") + -- a sub-range reader + local s = samples[1] + local big = buffer.create(#s + 7) + buffer.writestring(big, 3, s) + local fs = Riff.read(Bytes.reader(big, 3, #s)) :: any + t:check(fs and fs.form == "TEST" and #fs.chunks == 4 and fs.base == 3, "sub-range reader") + t:eq(Riff.sniff(Bytes.reader(buffer.fromstring(s))), "TEST", "sniff") +end + +-- errors +do + local _, e1 = Riff.read(buffer.fromstring("RIFF")) + t:check(e1 and e1.code == Err.TRUNCATED, "too short") + local _, e2 = Riff.read(buffer.fromstring("OggS00000000")) + t:check(e2 and e2.code == Err.CORRUPT, "not RIFF") + local _, e3 = Riff.read(42 :: any) + t:check(e3 and e3.code == Err.ARG, "not a buffer") +end + +t:fuzz("read + list", function(b: buffer) + local f = Riff.read(Bytes.reader(b), { openEnded = { data = true } }) + if f then + for _, c in f.chunks do + if c.id == "LIST" then + Riff.list(f, c) + end + end + end + return f +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/fixtures/bmpsuite/b/badbitcount.bmp b/tests/fixtures/bmpsuite/b/badbitcount.bmp new file mode 100644 index 0000000..d4fa4e8 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badbitcount.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badbitssize.bmp b/tests/fixtures/bmpsuite/b/badbitssize.bmp new file mode 100644 index 0000000..0a99a60 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badbitssize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/baddens1.bmp b/tests/fixtures/bmpsuite/b/baddens1.bmp new file mode 100644 index 0000000..a6150a6 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/baddens1.bmp differ diff --git a/tests/fixtures/bmpsuite/b/baddens2.bmp b/tests/fixtures/bmpsuite/b/baddens2.bmp new file mode 100644 index 0000000..f2c1dfb Binary files /dev/null and b/tests/fixtures/bmpsuite/b/baddens2.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badfilesize.bmp b/tests/fixtures/bmpsuite/b/badfilesize.bmp new file mode 100644 index 0000000..da52cb5 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badfilesize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badheadersize.bmp b/tests/fixtures/bmpsuite/b/badheadersize.bmp new file mode 100644 index 0000000..2a4083a Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badheadersize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badpalettesize.bmp b/tests/fixtures/bmpsuite/b/badpalettesize.bmp new file mode 100644 index 0000000..7d9d1b7 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badpalettesize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badplanes.bmp b/tests/fixtures/bmpsuite/b/badplanes.bmp new file mode 100644 index 0000000..92d2855 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badplanes.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle.bmp b/tests/fixtures/bmpsuite/b/badrle.bmp new file mode 100644 index 0000000..cbf8fdc Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle4.bmp b/tests/fixtures/bmpsuite/b/badrle4.bmp new file mode 100644 index 0000000..632787a Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle4.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle4bis.bmp b/tests/fixtures/bmpsuite/b/badrle4bis.bmp new file mode 100644 index 0000000..130b7e6 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle4bis.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle4ter.bmp b/tests/fixtures/bmpsuite/b/badrle4ter.bmp new file mode 100644 index 0000000..8107a33 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle4ter.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrlebis.bmp b/tests/fixtures/bmpsuite/b/badrlebis.bmp new file mode 100644 index 0000000..893eb11 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrlebis.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrleter.bmp b/tests/fixtures/bmpsuite/b/badrleter.bmp new file mode 100644 index 0000000..04d5874 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrleter.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badwidth.bmp b/tests/fixtures/bmpsuite/b/badwidth.bmp new file mode 100644 index 0000000..9fca005 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badwidth.bmp differ diff --git a/tests/fixtures/bmpsuite/b/pal8badindex.bmp b/tests/fixtures/bmpsuite/b/pal8badindex.bmp new file mode 100644 index 0000000..efe16c0 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/pal8badindex.bmp differ diff --git a/tests/fixtures/bmpsuite/b/reallybig.bmp b/tests/fixtures/bmpsuite/b/reallybig.bmp new file mode 100644 index 0000000..101e0b4 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/reallybig.bmp differ diff --git a/tests/fixtures/bmpsuite/b/rgb16-880.bmp b/tests/fixtures/bmpsuite/b/rgb16-880.bmp new file mode 100644 index 0000000..72e7ce0 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/rgb16-880.bmp differ diff --git a/tests/fixtures/bmpsuite/b/rletopdown.bmp b/tests/fixtures/bmpsuite/b/rletopdown.bmp new file mode 100644 index 0000000..21a909f Binary files /dev/null and b/tests/fixtures/bmpsuite/b/rletopdown.bmp differ diff --git a/tests/fixtures/bmpsuite/b/shortfile.bmp b/tests/fixtures/bmpsuite/b/shortfile.bmp new file mode 100644 index 0000000..7396079 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/shortfile.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal1.bmp b/tests/fixtures/bmpsuite/g/pal1.bmp new file mode 100644 index 0000000..4776f82 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal1.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal1bg.bmp b/tests/fixtures/bmpsuite/g/pal1bg.bmp new file mode 100644 index 0000000..466d0ba Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal1bg.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal1wb.bmp b/tests/fixtures/bmpsuite/g/pal1wb.bmp new file mode 100644 index 0000000..56cb932 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal1wb.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal4.bmp b/tests/fixtures/bmpsuite/g/pal4.bmp new file mode 100644 index 0000000..7fd3630 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal4.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal4gs.bmp b/tests/fixtures/bmpsuite/g/pal4gs.bmp new file mode 100644 index 0000000..813268c Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal4gs.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal4rle.bmp b/tests/fixtures/bmpsuite/g/pal4rle.bmp new file mode 100644 index 0000000..a5672ae Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal4rle.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8-0.bmp b/tests/fixtures/bmpsuite/g/pal8-0.bmp new file mode 100644 index 0000000..ab8815a Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8-0.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8.bmp b/tests/fixtures/bmpsuite/g/pal8.bmp new file mode 100644 index 0000000..96b2f86 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8gs.bmp b/tests/fixtures/bmpsuite/g/pal8gs.bmp new file mode 100644 index 0000000..66a0d70 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8gs.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8nonsquare.bmp b/tests/fixtures/bmpsuite/g/pal8nonsquare.bmp new file mode 100644 index 0000000..0aa8de0 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8nonsquare.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8os2.bmp b/tests/fixtures/bmpsuite/g/pal8os2.bmp new file mode 100644 index 0000000..14901b3 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8os2.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8rle.bmp b/tests/fixtures/bmpsuite/g/pal8rle.bmp new file mode 100644 index 0000000..d431014 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8rle.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8topdown.bmp b/tests/fixtures/bmpsuite/g/pal8topdown.bmp new file mode 100644 index 0000000..4b2f8e0 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8topdown.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8v4.bmp b/tests/fixtures/bmpsuite/g/pal8v4.bmp new file mode 100644 index 0000000..34ebb80 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8v4.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8v5.bmp b/tests/fixtures/bmpsuite/g/pal8v5.bmp new file mode 100644 index 0000000..c54647a Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8v5.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8w124.bmp b/tests/fixtures/bmpsuite/g/pal8w124.bmp new file mode 100644 index 0000000..b7cc2d8 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8w124.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8w125.bmp b/tests/fixtures/bmpsuite/g/pal8w125.bmp new file mode 100644 index 0000000..06efed7 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8w125.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8w126.bmp b/tests/fixtures/bmpsuite/g/pal8w126.bmp new file mode 100644 index 0000000..112aa9f Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8w126.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16-565.bmp b/tests/fixtures/bmpsuite/g/rgb16-565.bmp new file mode 100644 index 0000000..c03a279 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16-565.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16-565pal.bmp b/tests/fixtures/bmpsuite/g/rgb16-565pal.bmp new file mode 100644 index 0000000..e7632e3 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16-565pal.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16.bmp b/tests/fixtures/bmpsuite/g/rgb16.bmp new file mode 100644 index 0000000..6bfe47a Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16bfdef.bmp b/tests/fixtures/bmpsuite/g/rgb16bfdef.bmp new file mode 100644 index 0000000..30fe8bb Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16bfdef.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb24.bmp b/tests/fixtures/bmpsuite/g/rgb24.bmp new file mode 100644 index 0000000..40f8bb0 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb24.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb24pal.bmp b/tests/fixtures/bmpsuite/g/rgb24pal.bmp new file mode 100644 index 0000000..102e971 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb24pal.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb32.bmp b/tests/fixtures/bmpsuite/g/rgb32.bmp new file mode 100644 index 0000000..5d57eaa Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb32.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb32bf.bmp b/tests/fixtures/bmpsuite/g/rgb32bf.bmp new file mode 100644 index 0000000..20fa9a1 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb32bf.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb32bfdef.bmp b/tests/fixtures/bmpsuite/g/rgb32bfdef.bmp new file mode 100644 index 0000000..d7e64e5 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb32bfdef.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal1huffmsb.bmp b/tests/fixtures/bmpsuite/q/pal1huffmsb.bmp new file mode 100644 index 0000000..0ade234 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal1huffmsb.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal1p1.bmp b/tests/fixtures/bmpsuite/q/pal1p1.bmp new file mode 100644 index 0000000..b68321c Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal1p1.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal2.bmp b/tests/fixtures/bmpsuite/q/pal2.bmp new file mode 100644 index 0000000..983e9fa Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal2color.bmp b/tests/fixtures/bmpsuite/q/pal2color.bmp new file mode 100644 index 0000000..27fe727 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal2color.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal4rlecut.bmp b/tests/fixtures/bmpsuite/q/pal4rlecut.bmp new file mode 100644 index 0000000..2f32d1d Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal4rlecut.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal4rletrns.bmp b/tests/fixtures/bmpsuite/q/pal4rletrns.bmp new file mode 100644 index 0000000..58994e9 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal4rletrns.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8offs.bmp b/tests/fixtures/bmpsuite/q/pal8offs.bmp new file mode 100644 index 0000000..8673e97 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8offs.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2-hs.bmp b/tests/fixtures/bmpsuite/q/pal8os2-hs.bmp new file mode 100644 index 0000000..018a3c4 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2-hs.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2-sz.bmp b/tests/fixtures/bmpsuite/q/pal8os2-sz.bmp new file mode 100644 index 0000000..7f1455d Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2-sz.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2sp.bmp b/tests/fixtures/bmpsuite/q/pal8os2sp.bmp new file mode 100644 index 0000000..e532c89 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2sp.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2-16.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2-16.bmp new file mode 100644 index 0000000..95a1d23 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2-16.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2-40sz.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2-40sz.bmp new file mode 100644 index 0000000..d1e66b6 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2-40sz.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2-sz.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2-sz.bmp new file mode 100644 index 0000000..6fe566e Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2-sz.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2.bmp new file mode 100644 index 0000000..1324a40 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8oversizepal.bmp b/tests/fixtures/bmpsuite/q/pal8oversizepal.bmp new file mode 100644 index 0000000..93b8187 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8oversizepal.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8rlecut.bmp b/tests/fixtures/bmpsuite/q/pal8rlecut.bmp new file mode 100644 index 0000000..840d31c Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8rlecut.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8rletrns.bmp b/tests/fixtures/bmpsuite/q/pal8rletrns.bmp new file mode 100644 index 0000000..a2af88d Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8rletrns.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb16-231.bmp b/tests/fixtures/bmpsuite/q/rgb16-231.bmp new file mode 100644 index 0000000..6300f69 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb16-231.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb16-3103.bmp b/tests/fixtures/bmpsuite/q/rgb16-3103.bmp new file mode 100644 index 0000000..6e01226 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb16-3103.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb16faketrns.bmp b/tests/fixtures/bmpsuite/q/rgb16faketrns.bmp new file mode 100644 index 0000000..62fb393 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb16faketrns.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24jpeg.bmp b/tests/fixtures/bmpsuite/q/rgb24jpeg.bmp new file mode 100644 index 0000000..87d73d7 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24jpeg.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24largepal.bmp b/tests/fixtures/bmpsuite/q/rgb24largepal.bmp new file mode 100644 index 0000000..d5e418c Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24largepal.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24lprof.bmp b/tests/fixtures/bmpsuite/q/rgb24lprof.bmp new file mode 100644 index 0000000..b868b88 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24lprof.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24png.bmp b/tests/fixtures/bmpsuite/q/rgb24png.bmp new file mode 100644 index 0000000..e87ec7a Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24png.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24prof.bmp b/tests/fixtures/bmpsuite/q/rgb24prof.bmp new file mode 100644 index 0000000..627e676 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24prof.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24prof2.bmp b/tests/fixtures/bmpsuite/q/rgb24prof2.bmp new file mode 100644 index 0000000..f9f61b8 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24prof2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24rle24.bmp b/tests/fixtures/bmpsuite/q/rgb24rle24.bmp new file mode 100644 index 0000000..360aee6 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24rle24.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32-111110.bmp b/tests/fixtures/bmpsuite/q/rgb32-111110.bmp new file mode 100644 index 0000000..ec07d89 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32-111110.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32-7187.bmp b/tests/fixtures/bmpsuite/q/rgb32-7187.bmp new file mode 100644 index 0000000..887ba52 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32-7187.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32-xbgr.bmp b/tests/fixtures/bmpsuite/q/rgb32-xbgr.bmp new file mode 100644 index 0000000..c6c05e1 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32-xbgr.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32fakealpha.bmp b/tests/fixtures/bmpsuite/q/rgb32fakealpha.bmp new file mode 100644 index 0000000..cb544da Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32fakealpha.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32h52.bmp b/tests/fixtures/bmpsuite/q/rgb32h52.bmp new file mode 100644 index 0000000..db6e453 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32h52.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba16-1924.bmp b/tests/fixtures/bmpsuite/q/rgba16-1924.bmp new file mode 100644 index 0000000..6564098 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba16-1924.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba16-4444.bmp b/tests/fixtures/bmpsuite/q/rgba16-4444.bmp new file mode 100644 index 0000000..051ff23 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba16-4444.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba16-5551.bmp b/tests/fixtures/bmpsuite/q/rgba16-5551.bmp new file mode 100644 index 0000000..73e2cd5 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba16-5551.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-1.bmp b/tests/fixtures/bmpsuite/q/rgba32-1.bmp new file mode 100644 index 0000000..3c1e264 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-1.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-1010102.bmp b/tests/fixtures/bmpsuite/q/rgba32-1010102.bmp new file mode 100644 index 0000000..1a918ce Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-1010102.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-2.bmp b/tests/fixtures/bmpsuite/q/rgba32-2.bmp new file mode 100644 index 0000000..829c7c7 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-61754.bmp b/tests/fixtures/bmpsuite/q/rgba32-61754.bmp new file mode 100644 index 0000000..d5936fd Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-61754.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-81284.bmp b/tests/fixtures/bmpsuite/q/rgba32-81284.bmp new file mode 100644 index 0000000..1f9fc29 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-81284.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32abf.bmp b/tests/fixtures/bmpsuite/q/rgba32abf.bmp new file mode 100644 index 0000000..d9bb018 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32abf.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32h56.bmp b/tests/fixtures/bmpsuite/q/rgba32h56.bmp new file mode 100644 index 0000000..343baa3 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32h56.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba64.bmp b/tests/fixtures/bmpsuite/q/rgba64.bmp new file mode 100644 index 0000000..2e78d44 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba64.bmp differ diff --git a/tests/fixtures/bmpsuite/ref.txt b/tests/fixtures/bmpsuite/ref.txt new file mode 100644 index 0000000..1dd7e15 --- /dev/null +++ b/tests/fixtures/bmpsuite/ref.txt @@ -0,0 +1,27 @@ +g/pal1.bmp pal1.png +g/pal1bg.bmp pal1bg.png +g/pal1wb.bmp pal1.png +g/pal4.bmp pal4.png +g/pal4gs.bmp pal4gs.png +g/pal4rle.bmp pal4.png +g/pal8-0.bmp pal8.png +g/pal8.bmp pal8.png +g/pal8gs.bmp pal8gs.png +g/pal8nonsquare.bmp pal8nonsquare-v.png +g/pal8os2.bmp pal8.png +g/pal8rle.bmp pal8.png +g/pal8topdown.bmp pal8.png +g/pal8v4.bmp pal8.png +g/pal8v5.bmp pal8.png +g/pal8w124.bmp pal8w124.png +g/pal8w125.bmp pal8w125.png +g/pal8w126.bmp pal8w126.png +g/rgb16-565.bmp rgb16-565.png +g/rgb16-565pal.bmp rgb16-565.png +g/rgb16.bmp rgb16.png +g/rgb16bfdef.bmp rgb16.png +g/rgb24.bmp rgb24.png +g/rgb24pal.bmp rgb24.png +g/rgb32.bmp rgb24.png +g/rgb32bf.bmp rgb24.png +g/rgb32bfdef.bmp rgb24.png diff --git a/tests/fixtures/bmpsuite/ref/pal1.png b/tests/fixtures/bmpsuite/ref/pal1.png new file mode 100644 index 0000000..89a433e Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal1.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal1bg.png b/tests/fixtures/bmpsuite/ref/pal1bg.png new file mode 100644 index 0000000..20c4bb8 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal1bg.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal4.png b/tests/fixtures/bmpsuite/ref/pal4.png new file mode 100644 index 0000000..188bb04 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal4.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal4gs.png b/tests/fixtures/bmpsuite/ref/pal4gs.png new file mode 100644 index 0000000..a2558fa Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal4gs.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8.png b/tests/fixtures/bmpsuite/ref/pal8.png new file mode 100644 index 0000000..6dd9961 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8gs.png b/tests/fixtures/bmpsuite/ref/pal8gs.png new file mode 100644 index 0000000..a537e3a Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8gs.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8nonsquare-v.png b/tests/fixtures/bmpsuite/ref/pal8nonsquare-v.png new file mode 100644 index 0000000..124736c Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8nonsquare-v.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8w124.png b/tests/fixtures/bmpsuite/ref/pal8w124.png new file mode 100644 index 0000000..92bd357 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8w124.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8w125.png b/tests/fixtures/bmpsuite/ref/pal8w125.png new file mode 100644 index 0000000..7e5e6b4 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8w125.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8w126.png b/tests/fixtures/bmpsuite/ref/pal8w126.png new file mode 100644 index 0000000..1422f6e Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8w126.png differ diff --git a/tests/fixtures/bmpsuite/ref/rgb16-565.png b/tests/fixtures/bmpsuite/ref/rgb16-565.png new file mode 100644 index 0000000..04a3121 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/rgb16-565.png differ diff --git a/tests/fixtures/bmpsuite/ref/rgb16.png b/tests/fixtures/bmpsuite/ref/rgb16.png new file mode 100644 index 0000000..d954584 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/rgb16.png differ diff --git a/tests/fixtures/bmpsuite/ref/rgb24.png b/tests/fixtures/bmpsuite/ref/rgb24.png new file mode 100644 index 0000000..86a9c94 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/rgb24.png differ diff --git a/tests/fixtures/mp3/l2_192_st.mp2 b/tests/fixtures/mp3/l2_192_st.mp2 new file mode 100644 index 0000000..1f21386 Binary files /dev/null and b/tests/fixtures/mp3/l2_192_st.mp2 differ diff --git a/tests/fixtures/mp3/l2_192_st.ref b/tests/fixtures/mp3/l2_192_st.ref new file mode 100644 index 0000000..242de95 Binary files /dev/null and b/tests/fixtures/mp3/l2_192_st.ref differ diff --git a/tests/fixtures/mp3/l2_32k_st.mp2 b/tests/fixtures/mp3/l2_32k_st.mp2 new file mode 100644 index 0000000..883fd29 Binary files /dev/null and b/tests/fixtures/mp3/l2_32k_st.mp2 differ diff --git a/tests/fixtures/mp3/l2_32k_st.ref b/tests/fixtures/mp3/l2_32k_st.ref new file mode 100644 index 0000000..93442bd Binary files /dev/null and b/tests/fixtures/mp3/l2_32k_st.ref differ diff --git a/tests/fixtures/mp3/l2_64_mono.mp2 b/tests/fixtures/mp3/l2_64_mono.mp2 new file mode 100644 index 0000000..1fade63 Binary files /dev/null and b/tests/fixtures/mp3/l2_64_mono.mp2 differ diff --git a/tests/fixtures/mp3/l2_64_mono.ref b/tests/fixtures/mp3/l2_64_mono.ref new file mode 100644 index 0000000..16a7899 Binary files /dev/null and b/tests/fixtures/mp3/l2_64_mono.ref differ diff --git a/tests/fixtures/mp3/l2_mpeg2_24k.mp2 b/tests/fixtures/mp3/l2_mpeg2_24k.mp2 new file mode 100644 index 0000000..5d1b4d4 Binary files /dev/null and b/tests/fixtures/mp3/l2_mpeg2_24k.mp2 differ diff --git a/tests/fixtures/mp3/l2_mpeg2_24k.ref b/tests/fixtures/mp3/l2_mpeg2_24k.ref new file mode 100644 index 0000000..ffd2f5d Binary files /dev/null and b/tests/fixtures/mp3/l2_mpeg2_24k.ref differ diff --git a/tests/fixtures/mp3/l3_cbr128_js.mp3 b/tests/fixtures/mp3/l3_cbr128_js.mp3 new file mode 100644 index 0000000..c05f3a2 Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr128_js.mp3 differ diff --git a/tests/fixtures/mp3/l3_cbr128_js.ref b/tests/fixtures/mp3/l3_cbr128_js.ref new file mode 100644 index 0000000..1504f13 Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr128_js.ref differ diff --git a/tests/fixtures/mp3/l3_cbr320_st.mp3 b/tests/fixtures/mp3/l3_cbr320_st.mp3 new file mode 100644 index 0000000..9482361 Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr320_st.mp3 differ diff --git a/tests/fixtures/mp3/l3_cbr320_st.ref b/tests/fixtures/mp3/l3_cbr320_st.ref new file mode 100644 index 0000000..0947033 Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr320_st.ref differ diff --git a/tests/fixtures/mp3/l3_cbr32_mono.mp3 b/tests/fixtures/mp3/l3_cbr32_mono.mp3 new file mode 100644 index 0000000..686399b Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr32_mono.mp3 differ diff --git a/tests/fixtures/mp3/l3_cbr32_mono.ref b/tests/fixtures/mp3/l3_cbr32_mono.ref new file mode 100644 index 0000000..74289d1 Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr32_mono.ref differ diff --git a/tests/fixtures/mp3/l3_mpeg25_11k_st.mp3 b/tests/fixtures/mp3/l3_mpeg25_11k_st.mp3 new file mode 100644 index 0000000..0414318 Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_11k_st.mp3 differ diff --git a/tests/fixtures/mp3/l3_mpeg25_11k_st.ref b/tests/fixtures/mp3/l3_mpeg25_11k_st.ref new file mode 100644 index 0000000..dfc30a1 Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_11k_st.ref differ diff --git a/tests/fixtures/mp3/l3_mpeg25_8k.mp3 b/tests/fixtures/mp3/l3_mpeg25_8k.mp3 new file mode 100644 index 0000000..df4f89a Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_8k.mp3 differ diff --git a/tests/fixtures/mp3/l3_mpeg25_8k.ref b/tests/fixtures/mp3/l3_mpeg25_8k.ref new file mode 100644 index 0000000..297f56f Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_8k.ref differ diff --git a/tests/fixtures/mp3/l3_mpeg2_16k_mono.mp3 b/tests/fixtures/mp3/l3_mpeg2_16k_mono.mp3 new file mode 100644 index 0000000..9dce08a Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_16k_mono.mp3 differ diff --git a/tests/fixtures/mp3/l3_mpeg2_16k_mono.ref b/tests/fixtures/mp3/l3_mpeg2_16k_mono.ref new file mode 100644 index 0000000..30a8ce3 Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_16k_mono.ref differ diff --git a/tests/fixtures/mp3/l3_mpeg2_22k.mp3 b/tests/fixtures/mp3/l3_mpeg2_22k.mp3 new file mode 100644 index 0000000..1ca1882 Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_22k.mp3 differ diff --git a/tests/fixtures/mp3/l3_mpeg2_22k.ref b/tests/fixtures/mp3/l3_mpeg2_22k.ref new file mode 100644 index 0000000..33e441e Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_22k.ref differ diff --git a/tests/fixtures/mp3/l3_noreservoir.mp3 b/tests/fixtures/mp3/l3_noreservoir.mp3 new file mode 100644 index 0000000..4b1808b Binary files /dev/null and b/tests/fixtures/mp3/l3_noreservoir.mp3 differ diff --git a/tests/fixtures/mp3/l3_noreservoir.ref b/tests/fixtures/mp3/l3_noreservoir.ref new file mode 100644 index 0000000..1436d63 Binary files /dev/null and b/tests/fixtures/mp3/l3_noreservoir.ref differ diff --git a/tests/fixtures/mp3/l3_tags.mp3 b/tests/fixtures/mp3/l3_tags.mp3 new file mode 100644 index 0000000..2366d67 Binary files /dev/null and b/tests/fixtures/mp3/l3_tags.mp3 differ diff --git a/tests/fixtures/mp3/l3_tags.ref b/tests/fixtures/mp3/l3_tags.ref new file mode 100644 index 0000000..250a1f7 Binary files /dev/null and b/tests/fixtures/mp3/l3_tags.ref differ diff --git a/tests/fixtures/mp3/l3_vbr_v2_48k.mp3 b/tests/fixtures/mp3/l3_vbr_v2_48k.mp3 new file mode 100644 index 0000000..9d9048b Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v2_48k.mp3 differ diff --git a/tests/fixtures/mp3/l3_vbr_v2_48k.ref b/tests/fixtures/mp3/l3_vbr_v2_48k.ref new file mode 100644 index 0000000..26f9031 Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v2_48k.ref differ diff --git a/tests/fixtures/mp3/l3_vbr_v7_mono.mp3 b/tests/fixtures/mp3/l3_vbr_v7_mono.mp3 new file mode 100644 index 0000000..2291d6b Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v7_mono.mp3 differ diff --git a/tests/fixtures/mp3/l3_vbr_v7_mono.ref b/tests/fixtures/mp3/l3_vbr_v7_mono.ref new file mode 100644 index 0000000..12ed1a2 Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v7_mono.ref differ diff --git a/tests/image/apng.luau b/tests/image/apng.luau new file mode 100644 index 0000000..60befc2 --- /dev/null +++ b/tests/image/apng.luau @@ -0,0 +1,171 @@ +-- image/png APNG tests: animated PNGs from ffmpeg's encoder and hand-written ones (every dispose / blend op, sub-rects, +-- palette + tRNS, grey, RGB, a hidden default image) decoded into frames and composited, compared with ffmpeg's +-- composited canvases (CRC-32); the APNG encoder's round trips; bad sequence numbers / rectangles; the fuzz pass. +-- Fixtures: tools/fixtures/apng.py. +local T = require("@tests/T") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/apng_cases") + +local t = T.suite("apng") + +t:check(Png.caps.animation == true, "caps.animation") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Png.decode(Bytes.reader(b), opts) +end + +local DISPOSE = { [0] = "none", [1] = "background", [2] = "previous" } + +local function canvasCrc(b: buffer, opaque: boolean): number + if opaque then + local c = buffer.create(buffer.len(b)) + buffer.copy(c, 0, b) + for i = 3, buffer.len(c) - 1, 4 do + buffer.writeu8(c, i, 255) + end + b = c + end + return Crc32.of(b) +end + +local function same(a: Types.Image, b: Types.Image): boolean + return a.width == b.width and a.height == b.height and buffer.tostring(a.pixels) == buffer.tostring(b.pixels) +end + +for _, c in Cases do + local img, err = decode(c.data, { checkCrc = true }) + t:check(img, c.name .. ": " .. tostring(err)) + t:eq(img.width, c.width, c.name .. ": width") + t:check(img.frames ~= nil, c.name .. ": frames") + t:eq(#img.frames, #c.crcs, c.name .. ": frame count") + t:eq(img.loops, c.plays, c.name .. ": loops") + if c.frames then + for i, e in c.frames do + local f = img.frames[i] + t:check(f.x == e.x and f.y == e.y and f.image.width == e.w and f.image.height == e.h, c.name .. ": frame " .. i .. " rect") + t:check(math.abs(f.delay - e.num / (if e.den == 0 then 100 else e.den)) < 1e-12, c.name .. ": frame " .. i .. " delay") + t:eq(f.dispose, DISPOSE[e.dispose], c.name .. ": frame " .. i .. " dispose") + t:eq(f.blend, if e.blend == 1 then "over" else "source", c.name .. ": frame " .. i .. " blend") + end + end + if c.defaultCrc then + t:eq(Crc32.of(img.pixels), c.defaultCrc, c.name .. ": hidden default image") + t:check(img.meta.apngDefaultHidden == true, c.name .. ": apngDefaultHidden") + else + t:check(img.meta.apngDefaultHidden == false, c.name .. ": default image is frame 1") + t:check(buffer.tostring(img.pixels) == buffer.tostring(img.frames[1].image.pixels), c.name .. ": pixels = frame 1") + end + local canv, cerr = Png.composite(img) + t:check(canv, c.name .. ": composite " .. tostring(cerr)) + for i, want in c.crcs do + t:eq(canvasCrc(canv[i].pixels, c.opaque), want, c.name .. ": composited frame " .. i .. (if c.ffmpeg then " vs ffmpeg" else " vs reference")) + end + -- round trip through the encoder: the same frames, rectangles, ops, delays, loops and default image + local enc, eerr = Png.encode(img) + t:check(enc, c.name .. ": encode " .. tostring(eerr)) + local back, berr = Png.decode(Bytes.reader(enc :: buffer), { checkCrc = true }) + t:check(back, c.name .. ": decode our APNG " .. tostring(berr)) + t:check(same(back, img), c.name .. ": round trip default image") + t:eq(back.loops, img.loops, c.name .. ": round trip loops") + t:eq(#back.frames, #img.frames, c.name .. ": round trip frame count") + t:eq(back.meta.apngDefaultHidden, img.meta.apngDefaultHidden, c.name .. ": round trip hidden default") + for i, f in img.frames do + local g = back.frames[i] + t:check(same(g.image, f.image) and g.x == f.x and g.y == f.y and g.dispose == f.dispose and g.blend == f.blend, c.name .. ": round trip frame " .. i) + t:check(math.abs(g.delay - f.delay) < 1e-9, c.name .. ": round trip delay " .. i) + end +end +t:note("%d APNGs match the reference canvases and round-trip", #Cases) + +-- encoder: frames built here (sub-rects, delays in seconds), opts.apng, validation +do + local function solid(w: number, h: number, r: number, g: number, b: number, a: number): Types.Image + local im = Types.Image.new(w, h) + for i = 0, w * h - 1 do + buffer.writeu8(im.pixels, i * 4, r) + buffer.writeu8(im.pixels, i * 4 + 1, g) + buffer.writeu8(im.pixels, i * 4 + 2, b) + buffer.writeu8(im.pixels, i * 4 + 3, a) + end + return im + end + local base = solid(8, 6, 10, 20, 30, 255) + base.frames = { + { image = base, delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" }, + { image = solid(3, 2, 200, 0, 0, 128), delay = 1 / 30, x = 5, y = 4, dispose = "background", blend = "over" }, + { image = solid(1, 1, 0, 255, 0, 255), delay = 70, x = 7, y = 0, dispose = "previous", blend = "source" }, + } + base.loops = 5 + local enc = Png.encode(base) :: buffer + local back = decode(enc) + t:check(back and #back.frames == 3 and back.loops == 5, "built APNG decodes") + t:check(math.abs(back.frames[2].delay - 1 / 30) < 1e-9 and back.frames[3].delay == 70 and back.frames[1].delay == 0.1, "delays") + t:eq(back.meta.source.colorType, "rgba", "colour type covers every frame (alpha in frame 2 only)") + local canv = Png.composite(back) :: { Types.Image } + -- frame 2 over: 128 alpha red over opaque (10, 20, 30) + local o = (4 * 8 + 5) * 4 + t:eq(buffer.readu8(canv[2].pixels, o + 3), 255, "over: alpha") + t:eq(buffer.readu8(canv[2].pixels, o), (128 * 200 + 127 * 10 + 128) * 257 // 65536, "over: red") + t:eq(buffer.readu32(canv[3].pixels, o), 0, "background dispose cleared frame 2's rect") + -- one frame + opts.apng; a still image stays a PNG + local still = solid(4, 4, 1, 2, 3, 255) + local plain = decode(Png.encode(still) :: buffer) + t:check(plain.frames == nil, "still image: no acTL") + local one = decode(Png.encode(still, { apng = true }) :: buffer) + t:check(one.frames and #one.frames == 1 and same(one.frames[1].image, still), "opts.apng: a one-frame APNG") + -- bad frames + local function bad(frames: any, label: string) + local im = solid(4, 4, 0, 0, 0, 255) + im.frames = frames + local r, e = Png.encode(im) + t:check(r == nil and e and e.code == Err.ARG, label .. ": " .. tostring(e)) + end + bad({ { image = still, x = 0, y = 0 }, { image = still, x = 1, y = 0 } }, "frame outside the canvas") + bad({ { image = still }, { image = {} } }, "frame without an image") + bad({ { image = still }, { image = still, dispose = "explode" } }, "bad dispose") + bad({ { image = still }, { image = still, blend = "add" } }, "bad blend") + bad({ { image = still }, { image = still, delay = -1 } }, "negative delay") +end + +-- crafted bad input: a broken sequence number, a frame outside the canvas +do + local c = Cases[1] + local s = c.data + -- find the second fcTL and bump its sequence number (fix the CRC so checkCrc does not mask it) + local first = string.find(s, "fcTL", 1, true) :: number + local second = string.find(s, "fcTL", first + 4, true) :: number + local b = buffer.fromstring(s) + local d = second + 3 -- 0-based offset of the chunk data + buffer.writeu32(b, d, bit32.byteswap(bit32.byteswap(buffer.readu32(b, d)) + 1)) + local _, e = Png.decode(Bytes.reader(b)) + t:check(e and e.code == Err.CORRUPT, "bad sequence: " .. tostring(e)) + local b2 = buffer.fromstring(s) + buffer.writeu32(b2, d + 12, bit32.byteswap(c.width)) -- x offset = the canvas width + local _, e2 = Png.decode(Bytes.reader(b2)) + t:check(e2 and e2.code == Err.CORRUPT, "frame outside the canvas: " .. tostring(e2)) + local _, e3 = decode(s, { maxPixels = c.width * c.height + 1 }) + t:check(e3 and e3.code == Err.LIMIT, "maxPixels counts the frames: " .. tostring(e3)) + t:check(Png.composite({} :: any) == nil, "composite of a non-image") +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + local img = Png.decode(Bytes.reader(b)) + if img and img.frames then + Png.composite(img) + end + return img + end, samples, { mutations = 30, keepHeader = 8 }) +end + +t:done() diff --git a/tests/image/bmp.luau b/tests/image/bmp.luau new file mode 100644 index 0000000..967c732 --- /dev/null +++ b/tests/image/bmp.luau @@ -0,0 +1,479 @@ +-- image/bmp tests: synthesized BMPs (every header type, bit depth and compression, row order, palettes, masks and alpha +-- rules, the RLE escapes, the lenient paths, errors), the BMP Suite against Pillow (g/ must match, q/ and b/ must not +-- throw), the encoder byte-exact against Pillow (24 bpp, 8 bpp paletted, 32 bpp BI_RGB) plus the V4 alpha header and +-- round trips (the V4 output was also checked by hand: Pillow and ImageMagick read the same RGBA), the api, and the +-- fuzz passes. Ported from bmp-luau tests/core.luau + tests/files.luau. +-- Fixtures: tools/fixtures/bmp.py. +local T = require("@tests/T") +local BmpF = require("@formats/image/bmp") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local Suite = require("@tests/gen/bmp_suite") +local Enc = require("@tests/gen/bmp_enc") + +local t = T.suite("bmp") +local function check(cond: any, label: string) + t:check(cond, label) +end + +-- the bmp-luau API on top of the contract (the ported tests below use it): decode(string | buffer) -> image with the +-- old fields | nil, message +local Bmp = {} +function Bmp.decode(s: any, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + if type(b) ~= "buffer" then + return nil, "expected a buffer or a string" + end + local img, err = BmpF.decode(Bytes.reader(b), opts) + if not img then + return nil, (err :: any).message + end + local src = img.meta.source :: any + local o = img :: any + o.bitsPerPixel, o.compression, o.topDown = src.bitDepth, src.compression, src.topDown + o.paletteSize, o.headerSize = src.paletteSize, src.headerSize + return img, nil +end +function Bmp.info(s: string): any + return BmpF.info(Bytes.reader(buffer.fromstring(s))) +end +function Bmp.isBmp(s: string): boolean + return BmpF.sniff(Bytes.reader(buffer.fromstring(s))) > 0 +end + +local function le(v: number, n: number): string + local b = buffer.create(4) + buffer.writeu32(b, 0, v % 4294967296) + return buffer.readstring(b, 0, n) +end +local function u16(v: number): string + return le(v, 2) +end +local function u32(v: number): string + return le(v, 4) +end +local function i32(v: number): string + return le(if v < 0 then v + 4294967296 else v, 4) +end + +-- Builds a BMP. o: w, h (negative = top-down), bpp, comp, hs (12, 40, 52, 56, 108, 124), palette ({ {r,g,b} }), +-- clrUsed, masks ({r,g,b[,a]}: in the header for hs >= 52, else after it), pixels (string), off / bfSize overrides. +local function make(o): string + local hs = o.hs or 40 + local hdr + if hs == 12 then + hdr = u32(12) .. u16(o.w) .. u16(o.h) .. u16(1) .. u16(o.bpp) + else + hdr = u32(hs) .. i32(o.w) .. i32(o.h) .. u16(1) .. u16(o.bpp) .. u32(o.comp or 0) .. u32(o.sizeImage or #o.pixels) + .. i32(2835) .. i32(2835) .. u32(o.clrUsed or 0) .. u32(0) + if hs >= 52 then + local m = o.masks or {} + hdr ..= u32(m[1] or 0) .. u32(m[2] or 0) .. u32(m[3] or 0) + if hs >= 56 then + hdr ..= u32(m[4] or 0) + end + end + hdr ..= string.rep("\0", hs - #hdr) + end + local extra = "" + if hs == 40 and o.masks then + for _, m in o.masks do + extra ..= u32(m) + end + end + local pal = "" + for _, c in o.palette or {} do + pal ..= string.char(c[3], c[2], c[1]) .. (if hs == 12 then "" else "\0") + end + local off = o.off or (14 + #hdr + #extra + #pal) + local body = hdr .. extra .. pal .. o.pixels + local size = o.bfSize or (14 + #body) + return "BM" .. u32(size) .. u32(0) .. u32(off) .. body +end + +local function px(img, x, y): (number, number, number, number) + local o = (y * img.width + x) * 4 + local b = img.pixels + return buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3) +end + +local function is(img, x, y, r, g, b, a, label) + local pr, pg, pb, pa = px(img, x, y) + check(pr == r and pg == g and pb == b and pa == a, + ("%s: (%d,%d) = %d,%d,%d,%d, want %d,%d,%d,%d"):format(label, x, y, pr, pg, pb, pa, r, g, b, a)) +end + +local function decode(s: string, label: string): any + local img, err = Bmp.decode(s) + check(img ~= nil, label .. ": " .. tostring(err)) + return img +end + +-- 24 bpp, bottom-up, row padding (w = 3 -> 9 bytes + 3 padding) +do + -- file rows: bottom row first. bottom = red green blue, top = white black grey + local bottom = "\0\0\255" .. "\0\255\0" .. "\255\0\0" .. "\0\0\0" + local top = "\255\255\255" .. "\0\0\0" .. "\128\128\128" .. "\0\0\0" + local img = decode(make({ w = 3, h = 2, bpp = 24, pixels = bottom .. top }), "rgb24") + check(img.width == 3 and img.height == 2 and buffer.len(img.pixels) == 24, "rgb24 size") + check(img.compression == "rgb" and img.bitsPerPixel == 24 and not img.topDown, "rgb24 fields") + is(img, 0, 1, 255, 0, 0, 255, "rgb24 bottom-left red") + is(img, 1, 1, 0, 255, 0, 255, "rgb24 green") + is(img, 2, 1, 0, 0, 255, 255, "rgb24 blue") + is(img, 0, 0, 255, 255, 255, 255, "rgb24 top-left white") + is(img, 2, 0, 128, 128, 128, 255, "rgb24 grey") + -- top-down (negative height): the first file row is the top + local td = decode(make({ w = 3, h = -2, bpp = 24, pixels = bottom .. top }), "rgb24 top-down") + check(td.topDown and td.height == 2, "top-down fields") + is(td, 0, 0, 255, 0, 0, 255, "top-down first row on top") + is(td, 0, 1, 255, 255, 255, 255, "top-down second row") + -- string and buffer input are the same + local b = Bmp.decode(buffer.fromstring(make({ w = 3, h = 2, bpp = 24, pixels = bottom .. top }))) + check(b and buffer.tostring(b.pixels) == buffer.tostring(img.pixels), "buffer input") +end + +local PAL = { { 0, 0, 0 }, { 255, 255, 255 }, { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } } + +-- 1 bpp: 10 pixels per row (2 bytes + 2 padding), MSB first +do + local row = string.char(0xA5, 0x80) .. "\0\0" -- 1010 0101 | 10 + local img = decode(make({ w = 10, h = 1, bpp = 1, palette = { { 10, 20, 30 }, { 40, 50, 60 } }, pixels = row }), "pal1") + local want = { 1, 0, 1, 0, 0, 1, 0, 1, 1, 0 } + for x = 0, 9 do + local c = if want[x + 1] == 1 then 40 else 10 + is(img, x, 0, c, c + 10, c + 20, 255, "pal1 x" .. x) + end + check(img.paletteSize == 2, "pal1 palette size") +end + +-- 2 bpp (non-standard, as in the BMP Suite's q/pal2.bmp) +do + local img = decode(make({ w = 4, h = 1, bpp = 2, palette = PAL, clrUsed = 4, pixels = string.char(0x1B) .. "\0\0\0" }), "pal2") + is(img, 0, 0, 0, 0, 0, 255, "pal2 0") + is(img, 1, 0, 255, 255, 255, 255, "pal2 1") + is(img, 2, 0, 255, 0, 0, 255, "pal2 2") + is(img, 3, 0, 0, 255, 0, 255, "pal2 3") +end + +-- 4 bpp, odd width; palette shorter than 16 (clrUsed = 5): index 7 is past it -> opaque black +do + local img = decode(make({ w = 3, h = 1, bpp = 4, palette = PAL, clrUsed = 5, pixels = string.char(0x24, 0x70, 0, 0) }), "pal4") + is(img, 0, 0, 255, 0, 0, 255, "pal4 x0 = 2") + is(img, 1, 0, 0, 0, 255, 255, "pal4 x1 = 4") + is(img, 2, 0, 0, 0, 0, 255, "pal4 x2 = 7 (past the palette)") + check(img.paletteSize == 5, "pal4 palette size") +end + +-- 8 bpp with clrUsed = 0 but only 3 entries before bfOffBits (a palette shorter than 2^bpp) +do + local s = make({ w = 4, h = 1, bpp = 8, palette = { PAL[3], PAL[4], PAL[5] }, pixels = string.char(0, 1, 2, 200) }) + local img = decode(s, "pal8 short") + check(img.paletteSize == 3, "pal8 short palette size " .. img.paletteSize) + is(img, 0, 0, 255, 0, 0, 255, "pal8 0") + is(img, 2, 0, 0, 0, 255, 255, "pal8 2") + is(img, 3, 0, 0, 0, 0, 255, "pal8 200 -> black") +end + +-- OS/2 1.x core header: 16-bit dimensions, 3-byte palette entries +do + local img = decode(make({ hs = 12, w = 2, h = 2, bpp = 8, palette = PAL, pixels = string.char(1, 2, 0, 0, 3, 4, 0, 0) }), "core") + check(img.headerSize == 12 and img.paletteSize == 5, "core fields") + is(img, 0, 1, 255, 255, 255, 255, "core bottom-left") + is(img, 1, 1, 255, 0, 0, 255, "core bottom-right") + is(img, 0, 0, 0, 255, 0, 255, "core top-left") + is(img, 1, 0, 0, 0, 255, 255, "core top-right") + local img24 = decode(make({ hs = 12, w = 1, h = 1, bpp = 24, pixels = "\1\2\3\0" }), "core 24") + is(img24, 0, 0, 3, 2, 1, 255, "core 24") +end + +-- 16 bpp: BI_RGB = 555; BITFIELDS 565; v3 header with a 4444 alpha mask. Scaling is v * 255 // max (as Pillow). +do + local p555 = 31 * 1024 + 16 * 32 + 1 -- r 31, g 16, b 1 + local img = decode(make({ w = 1, h = 1, bpp = 16, pixels = u16(p555) .. "\0\0" }), "555") + is(img, 0, 0, 255, 131, 8, 255, "555") + local p565 = 1 * 2048 + 63 * 32 + 30 + local img2 = decode(make({ w = 1, h = 1, bpp = 16, comp = 3, masks = { 0xF800, 0x7E0, 0x1F }, pixels = u16(p565) .. "\0\0" }), "565") + is(img2, 0, 0, 8, 255, 246, 255, "565") + check(img2.compression == "bitfields", "565 compression name") + local m4444 = { 0x0F00, 0x00F0, 0x000F, 0xF000 } + local img3 = decode(make({ hs = 56, w = 2, h = 1, bpp = 16, comp = 3, masks = m4444, pixels = u16(0x8F00) .. u16(0x00F0) }), "4444") + is(img3, 0, 0, 255, 0, 0, 136, "4444 alpha") + is(img3, 1, 0, 0, 255, 0, 0, "4444 transparent") + -- an alpha mask whose values are all zero: opaque + local img4 = decode(make({ hs = 56, w = 1, h = 1, bpp = 16, comp = 3, masks = m4444, pixels = u16(0x0F00) .. "\0\0" }), "4444 zero alpha") + is(img4, 0, 0, 255, 0, 0, 255, "4444 all-zero alpha -> opaque") + -- v4 header with BI_RGB: masks in the header are ignored -> 555 + local img5 = decode(make({ hs = 108, w = 1, h = 1, bpp = 16, masks = { 0xF800, 0x7E0, 0x1F }, pixels = u16(p555) .. "\0\0" }), "v4 555") + is(img5, 0, 0, 255, 131, 8, 255, "v4 BI_RGB 16 -> 555") +end + +-- 32 bpp +do + -- BI_RGB, alpha bytes all zero -> opaque + local img = decode(make({ w = 2, h = 1, bpp = 32, pixels = "\1\2\3\0\4\5\6\0" }), "rgb32 zero alpha") + is(img, 0, 0, 3, 2, 1, 255, "rgb32 opaque 0") + is(img, 1, 0, 6, 5, 4, 255, "rgb32 opaque 1") + -- BI_RGB with alpha bytes used (as browsers do) + local img2 = decode(make({ w = 2, h = 1, bpp = 32, pixels = "\1\2\3\128\4\5\6\0" }), "rgb32 alpha") + is(img2, 0, 0, 3, 2, 1, 128, "rgb32 alpha 128") + is(img2, 1, 0, 6, 5, 4, 0, "rgb32 alpha 0") + -- BITFIELDS in an unusual order (R in the top byte), no alpha mask -> opaque even with bytes there + local img3 = decode(make({ w = 1, h = 1, bpp = 32, comp = 3, masks = { 0xFF000000, 0xFF0000, 0xFF00 }, pixels = "\9\3\2\1" }), "rgb32 bf") + is(img3, 0, 0, 1, 2, 3, 255, "rgb32 bitfields order") + -- standard BITFIELDS without an alpha mask: the 4th byte is ignored + local img4 = decode(make({ w = 1, h = 1, bpp = 32, comp = 3, masks = { 0xFF0000, 0xFF00, 0xFF }, pixels = "\1\2\3\77" }), "rgb32 bf std") + is(img4, 0, 0, 3, 2, 1, 255, "rgb32 std bitfields opaque") + -- ALPHABITFIELDS (compression 6) after a 40-byte header + local img5 = decode(make({ w = 1, h = 1, bpp = 32, comp = 6, masks = { 0xFF, 0xFF00, 0xFF0000, 0xFF000000 }, pixels = "\1\2\3\4" }), "alphabf") + is(img5, 0, 0, 1, 2, 3, 4, "alphabitfields RGBA") + check(img5.compression == "alphabitfields", "alphabitfields name") + -- v5 header with BITFIELDS + alpha mask; 10-bit channels (1010102) + local v = 1023 + 512 * 1024 + 0 * 1048576 + 3 * 1073741824 + local img6 = decode(make({ hs = 124, w = 1, h = 1, bpp = 32, comp = 3, masks = { 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 }, pixels = u32(v) }), "1010102") + is(img6, 0, 0, 255, 127, 0, 255, "1010102") + -- v4 header with BI_RGB 32: alpha byte used + local img7 = decode(make({ hs = 108, w = 1, h = -1, bpp = 32, pixels = "\1\2\3\200" }), "v4 rgb32") + is(img7, 0, 0, 3, 2, 1, 200, "v4 rgb32 alpha") + -- 24 bpp with BITFIELDS (Pillow accepts it) + local img8 = decode(make({ w = 1, h = 1, bpp = 24, comp = 3, masks = { 0xFF, 0xFF00, 0xFF0000 }, pixels = "\1\2\3\0" }), "rgb24 bf") + is(img8, 0, 0, 1, 2, 3, 255, "rgb24 bitfields") +end + +-- RLE8: run, absolute (odd length, padded), end of line, delta, end of bitmap; skipped pixels are transparent +do + local pal = PAL + local stream = string.char( + 3, 2, -- row 0 (bottom): 3 x red + 0, 3, 1, 3, 4, 0, -- absolute 3: white green blue + pad + 0, 0, -- EOL (row 0 is 6 wide: x = 6, w = 8: x 6..7 skipped) + 0, 2, 2, 1, -- delta right 2, up 1: row 2, x = 2 + 2, 4, -- 2 x blue at row 2 x 2..3 + 0, 1 -- EOB: row 3 never written + ) + local img = decode(make({ w = 8, h = 4, bpp = 8, comp = 1, palette = pal, pixels = stream }), "rle8") + check(img.compression == "rle8", "rle8 name") + for x = 0, 2 do + is(img, x, 3, 255, 0, 0, 255, "rle8 run " .. x) + end + is(img, 3, 3, 255, 255, 255, 255, "rle8 abs 0") + is(img, 4, 3, 0, 255, 0, 255, "rle8 abs 1") + is(img, 5, 3, 0, 0, 255, 255, "rle8 abs 2") + is(img, 6, 3, 0, 0, 0, 0, "rle8 EOL skipped -> transparent") + is(img, 0, 2, 0, 0, 0, 0, "rle8 row 1 skipped by the delta") + is(img, 1, 1, 0, 0, 0, 0, "rle8 delta skip") + is(img, 2, 1, 0, 0, 255, 255, "rle8 after delta 0") + is(img, 3, 1, 0, 0, 255, 255, "rle8 after delta 1") + is(img, 4, 1, 0, 0, 0, 0, "rle8 after the run") + is(img, 0, 0, 0, 0, 0, 0, "rle8 EOB: top row empty") + -- a run past the row end is clipped; truncated data keeps what was drawn + local img2 = decode(make({ w = 2, h = 1, bpp = 8, comp = 1, palette = pal, pixels = string.char(5, 2, 0) }), "rle8 clip") + is(img2, 1, 0, 255, 0, 0, 255, "rle8 clipped run") + -- top-down RLE (out of spec, accepted) + local img3 = decode(make({ w = 1, h = -2, bpp = 8, comp = 1, palette = pal, pixels = string.char(1, 2, 0, 0, 1, 3, 0, 1) }), "rle8 top-down") + is(img3, 0, 0, 255, 0, 0, 255, "rle8 top-down row 0") + is(img3, 0, 1, 0, 255, 0, 255, "rle8 top-down row 1") +end + +-- RLE4: alternating nibbles in a run, an odd absolute run (3 pixels in 2 bytes, padded to 4) +do + local stream = string.char(5, 0x23, 0, 3, 0x14, 0x30, 0, 0, 0, 1) + local img = decode(make({ w = 8, h = 1, bpp = 4, comp = 2, palette = PAL, pixels = stream }), "rle4") + check(img.compression == "rle4", "rle4 name") + local want = { 2, 3, 2, 3, 2, 1, 4, 3 } + for x = 0, 7 do + local c = PAL[want[x + 1] + 1] + is(img, x, 0, c[1], c[2], c[3], 255, "rle4 x" .. x) + end +end + +-- leniency: bad bfSize, bad biSizeImage, bad bfOffBits, truncated pixels +do + local pixels = "\0\0\255" .. "\0\0\0" .. "\255\0\0" .. "\0\0\0" + local base = decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels }), "lenient base") + local function same(img, label) + check(img and buffer.tostring(img.pixels) == buffer.tostring(base.pixels), label) + end + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, bfSize = 0 })), "bfSize 0") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, bfSize = 999999 })), "bfSize too big") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, sizeImage = 0 })), "biSizeImage 0") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, sizeImage = 123456 })), "biSizeImage wrong") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, off = 0 })), "bfOffBits 0") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, off = 99999 })), "bfOffBits past the end") + -- truncated: the missing (top) rows read as zeros = opaque black + local t = decode(make({ w = 1, h = 3, bpp = 24, pixels = string.sub(pixels, 1, 5) }), "truncated") + is(t, 0, 2, 255, 0, 0, 255, "truncated: bottom row intact") + is(t, 0, 1, 0, 0, 0, 255, "truncated: partial row zero-filled") + is(t, 0, 0, 0, 0, 0, 255, "truncated: missing row black") + local t2 = decode(make({ w = 4, h = 4, bpp = 8, palette = PAL, pixels = "" }), "no pixel data") + is(t2, 3, 3, 0, 0, 0, 255, "no pixel data: index 0") +end + +-- info / isBmp +do + local s = make({ hs = 124, w = 7, h = -5, bpp = 32, comp = 3, masks = { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, pixels = "" }) + local info = Bmp.info(s) + check(info and info.width == 7 and info.height == 5 and info.topDown and info.bitsPerPixel == 32, "info fields") + check(info and info.compression == 3 and info.headerSize == 124 and not info.os2, "info compression / header") + check(Bmp.isBmp(s) and not Bmp.isBmp("\137PNG") and not Bmp.isBmp(""), "isBmp") +end + +-- errors: nil + message, never a throw +do + local function fails(s: any, pattern: string, label: string, opts: any?) + local ok, img, err = pcall(Bmp.decode, s, opts) + check(ok, label .. ": threw " .. tostring(img)) + check(img == nil and type(err) == "string" and string.find(err, pattern) ~= nil, label .. ": " .. tostring(err)) + end + fails("", "too short", "empty") + fails(123, "expected a buffer", "not a buffer") + fails("\137PNG\r\n\26\n" .. string.rep("\0", 40), "not a BMP", "png") + fails("BM" .. string.rep("\0", 12) .. u32(200) .. string.rep("\0", 20), "header size", "header past the end") + fails("BM" .. string.rep("\0", 12) .. u32(8) .. string.rep("\0", 40), "header size", "header too small") + fails(make({ w = 0, h = 1, bpp = 24, pixels = "" }), "bad size", "zero width") + fails(make({ w = -4, h = 1, bpp = 24, pixels = "" }), "bad size", "negative width") + fails(make({ w = 1, h = 0, bpp = 24, pixels = "" }), "bad size", "zero height") + fails(make({ w = 1, h = 1, bpp = 3, pixels = "\0\0\0\0" }), "bit depth", "bpp 3") + fails(make({ w = 1, h = 1, bpp = 64, pixels = string.rep("\0", 8) }), "bit depth", "bpp 64") + fails(make({ w = 1, h = 1, bpp = 24, comp = 1, pixels = "" }), "RLE", "RLE8 with 24 bpp") + fails(make({ w = 1, h = 1, bpp = 8, comp = 3, pixels = "" }), "BITFIELDS", "BITFIELDS with 8 bpp") + fails(make({ w = 1, h = 1, bpp = 24, comp = 4, pixels = "" }), "JPEG", "jpeg") + fails(make({ w = 1, h = 1, bpp = 24, comp = 5, pixels = "" }), "PNG", "png in bmp") + fails(make({ w = 1, h = 1, bpp = 24, comp = 9, pixels = "" }), "compression", "unknown compression") + fails(make({ w = 1, h = 1, bpp = 32, comp = 3, pixels = "" }), "masks", "truncated bit masks") + fails(make({ w = 100000, h = 100000, bpp = 24, pixels = "" }), "too large", "too large") + fails(make({ w = 100, h = 100, bpp = 24, pixels = "" }), "too large", "maxPixels option", { maxPixels = 9999 }) +end + +-- fuzz: truncations and byte flips of every kind of file above must never throw +do + local seeds = { + make({ w = 3, h = 2, bpp = 24, pixels = string.rep("\1\2\3", 8) }), + make({ w = 10, h = 3, bpp = 1, palette = PAL, clrUsed = 2, pixels = string.rep("\170\85\0\0", 3) }), + make({ w = 5, h = 2, bpp = 4, palette = PAL, pixels = string.rep("\18\52\5\0", 2) }), + make({ hs = 12, w = 2, h = 2, bpp = 8, palette = PAL, pixels = string.char(1, 2, 0, 0, 3, 4, 0, 0) }), + make({ hs = 56, w = 2, h = 1, bpp = 16, comp = 3, masks = { 0x0F00, 0xF0, 0xF, 0xF000 }, pixels = "\1\2\3\4" }), + make({ hs = 124, w = 2, h = -2, bpp = 32, comp = 3, masks = { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, pixels = string.rep("\1\2\3\4", 4) }), + make({ w = 8, h = 4, bpp = 8, comp = 1, palette = PAL, pixels = string.char(3, 2, 0, 3, 1, 3, 4, 0, 0, 0, 0, 2, 2, 1, 2, 4, 0, 1) }), + make({ w = 8, h = 1, bpp = 4, comp = 2, palette = PAL, pixels = string.char(5, 0x23, 0, 3, 0x14, 0x30, 0, 0, 0, 1) }), + } + local state = 12345 + local function rand(n: number): number + state = (state * 1103515245 + 12345) % 2147483648 + return state % n + end + local runs = 0 + for _, s in seeds do + for cut = 0, #s do + local ok, img = pcall(Bmp.decode, string.sub(s, 1, cut)) + check(ok, "truncated at " .. cut .. " threw: " .. tostring(img)) + runs += 1 + end + for _ = 1, 400 do + local b = buffer.fromstring(s) + for _ = 1, 1 + rand(4) do + buffer.writeu8(b, rand(#s), rand(256)) + end + local ok, img = pcall(Bmp.decode, b, { maxPixels = 2 ^ 20 }) + check(ok, "corrupted file threw: " .. tostring(img)) + if ok and img then + check(buffer.len(img.pixels) == img.width * img.height * 4, "corrupted file: pixel buffer size") + end + runs += 1 + end + end + t:note("fuzz: %d decodes, no throw", runs) +end + + +-- ------------------------------------------------------------------------------------------------ the BMP Suite +do + local nMatch, nOther = 0, 0 + local samples = {} + for _, e in Suite do + local ok, img, err = pcall(BmpF.decode, Bytes.reader(buffer.fromstring(e.data))) + t:check(ok, e.name .. ": threw " .. tostring(img)) + local same = img and e.w and img.width == e.w and img.height == e.h and Crc32.of(img.pixels) == e.crc + if e.mode == "match" then + t:check(same, e.name .. ": matches Pillow (" .. tostring(err) .. ")") + nMatch += 1 + else + t:check(img == nil or buffer.len(img.pixels) == img.width * img.height * 4, e.name .. ": pixel buffer size") + nOther += 1 + end + if #samples < 30 then + table.insert(samples, e.data) + end + end + t:note("BMP Suite: %d g/ files match Pillow, %d q/ + b/ files decode or fail cleanly", nMatch, nOther) + t:fuzz("decode (suite)", function(b: buffer) + return BmpF.decode(Bytes.reader(b), { maxPixels = 2 ^ 20 }) + end, samples, { mutations = 6 }) +end + +-- ------------------------------------------------------------------------------------------------ encoder +do + for _, c in Enc do + local img = Types.Image.new(c.w, c.h) + buffer.writestring(img.pixels, 0, c.rgba) + local opts: any = if c.mode == "RGBA" then { header = "info" } elseif c.mode == "RGB" then { bitDepth = 24 } else nil + local out, err = BmpF.encode(img, opts) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local same = buffer.tostring(out :: buffer) == c.bmp + if not same then + t:note("%s ours %s", c.name, T.hex(out :: buffer, 70)) + t:note("%s pillow %s", c.name, T.hex(buffer.fromstring(c.bmp), 70)) + end + t:check(same, c.name .. ": identical to Pillow") + local back = BmpF.decode(Bytes.reader(out :: buffer)) :: any + t:check(back and buffer.tostring(back.pixels) == c.rgba, c.name .. ": round trip") + -- the default 32 bpp header (V4 BITFIELDS) round-trips too + if c.mode == "RGBA" then + local v4 = BmpF.encode(img) :: buffer + t:eq(buffer.readu32(v4, 14), 108, c.name .. ": V4 header") + local b2 = BmpF.decode(Bytes.reader(v4)) :: any + t:check(b2 and buffer.tostring(b2.pixels) == c.rgba and b2.meta.source.compression == "bitfields", c.name .. ": V4 round trip") + end + end + t:note("encoder: %d files identical to Pillow", #Enc) + -- forced depths, dpi, errors + local img = Types.Image.new(5, 4) + for i = 0, 19 do + buffer.writeu32(img.pixels, i * 4, 0xFF000000 + i * 0x010203) + end + for _, d in { 8, 24, 32 } do + local out = BmpF.encode(img, { bitDepth = d }) :: buffer + local back = BmpF.decode(Bytes.reader(out)) :: any + t:check(back.meta.source.bitDepth == d and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "bitDepth " .. d) + end + img.meta.dpi = { x = 300, y = 150 } + local withDpi = BmpF.decode(Bytes.reader(BmpF.encode(img) :: buffer)) :: any + t:check(math.abs(withDpi.meta.dpi.x - 300) < 0.1 and math.abs(withDpi.meta.dpi.y - 150) < 0.1, "dpi round trip") + local many = Types.Image.new(300, 1) + for i = 0, 299 do + buffer.writeu32(many.pixels, i * 4, 0xFF000000 + i) + end + local _, e1 = BmpF.encode(many, { bitDepth = 8 }) + t:check(e1 and e1.code == Err.ARG, "8 bpp with 300 colours") + t:eq(buffer.readu16(BmpF.encode(many) :: buffer, 28), 24, "auto: 300 opaque colours -> 24 bpp") + local _, e2 = BmpF.encode({} :: any) + t:check(e2 and e2.code == Err.ARG, "not an image") + local _, e3 = BmpF.encode(img, { bitDepth = 16 } :: any) + t:check(e3 and e3.code == Err.ARG, "bitDepth 16") + -- the api + local c = Enc[1] + local loaded = F.image.load(c.bmp) + t:check(loaded and loaded.width == c.w and buffer.tostring(loaded.pixels) == c.rgba, "F.image.load") + t:eq(F.detect(c.bmp), "bmp", "F.detect") + local saved = F.save(loaded, nil, { format = "bmp" }) + t:check(saved and buffer.tostring(saved) == c.bmp, "F.save bmp") + -- a sub-range reader + local big = buffer.create(#c.bmp + 5) + buffer.writestring(big, 3, c.bmp) + local sub = BmpF.decode(Bytes.reader(big, 3, #c.bmp)) :: any + t:check(sub and buffer.tostring(sub.pixels) == c.rgba, "decode from a sub-range") +end + +t:done() diff --git a/tests/playlist/m3u.luau b/tests/playlist/m3u.luau new file mode 100644 index 0000000..3229e53 --- /dev/null +++ b/tests/playlist/m3u.luau @@ -0,0 +1,357 @@ +-- playlist/m3u tests (+ the PLS parts of the ported suite): M3U / M3U8 (EXTINF, comments, BOM, CRLF / CR, +-- Windows-1252, relative / absolute / local locations), PLS, HLS master and media playlists, detection, serialize round +-- trips, bad input; Python-written playlists (tools/fixtures/playlist.py) decode to their entries, and our M3U8 output +-- decodes back; the api; the fuzz pass. Ported from playlist-luau tests/playlist.luau. Fixtures: +-- tools/fixtures/playlist.py. +local T = require("@tests/T") +local M3u = require("@formats/playlist/m3u") +local Pls = require("@formats/playlist/pls") +local Bytes = require("@formats/core/Bytes") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("m3u") +local function eq(got: any, want: any, label: string) + t:eq(got, want, label) +end +local function has(list: { string }, pattern: string): boolean + for _, w in list do + if string.find(w, pattern) then + return true + end + end + return false +end + +-- the playlist-luau API on top of the two formats (the ported tests below use it) +local Playlist = {} +function Playlist.detect(text: string): string + if type(text) ~= "string" then + return "m3u" + end + local r = Bytes.reader(buffer.fromstring(text)) + if Pls.sniff(r) > 0 then + return "pls" + end + return if string.find(text, "#EXT%-X%-") then "hls" else "m3u" +end +function Playlist.parse(text: any, baseUrl: string?): any + if type(text) ~= "string" then + return { kind = "m3u", entries = {}, warnings = { "expected a string" } } + end + local kind = Playlist.detect(text) + local mod = if kind == "pls" then Pls else M3u + local pl = mod.decode(Bytes.reader(buffer.fromstring(text)), { baseUrl = baseUrl }) :: any + pl.kind = pl.format -- the old field + return pl +end +function Playlist.serialize(entries: any, opts: any?): string + return buffer.tostring(M3u.encode(entries, opts) :: buffer) +end + +-- M3U8 with EXTINF, comments, blank lines, BOM, CRLF +do + local text = "\239\187\191#EXTM3U\r\n#PLAYLIST:My Mix\r\n\r\n# a comment\r\n#EXTINF:123,Daft Punk - One More Time\r\n" + .. "music/one more time.mp3\r\n#EXTINF:-1,Radio\r\nhttp://radio.example/stream\r\n" + .. "#EXTINF:61.5 tvg-id=\"x\" group-title=\"a,b\",Grouped, with comma\r\n../other/b.mp3\r\n" + .. "#EXTGRP:ignored\r\n/abs/c.mp3\r\n https://cdn.example/d.mp3?x=1 \r\n" + local pl = Playlist.parse(text, "https://host.example/lists/m.m3u8") + eq(pl.kind, "m3u", "kind") + eq(pl.title, "My Mix", "#PLAYLIST") + eq(#pl.entries, 5, "entry count") + local e = pl.entries + eq(e[1].url, "https://host.example/lists/music/one%20more%20time.mp3", "relative resolved + encoded") + eq(e[1].title, "Daft Punk - One More Time", "EXTINF title") + eq(e[1].duration, 123, "EXTINF duration") + eq(e[1].playable, true, "https playable") + eq(e[2].url, "http://radio.example/stream", "absolute kept") + eq(e[2].duration, nil, "duration -1 = unknown") + eq(e[2].title, "Radio", "title 2") + eq(e[3].url, "https://host.example/other/b.mp3", "dot-dot resolved") + eq(e[3].duration, 61.5, "fractional duration with attributes") + eq(e[3].title, "Grouped, with comma", "title after the attributes keeps its commas") + eq(e[4].url, "https://host.example/abs/c.mp3", "absolute path") + eq(e[4].title, nil, "EXTINF does not leak to the next entry") + eq(e[5].url, "https://cdn.example/d.mp3?x=1", "trimmed absolute") + eq(#pl.warnings, 0, "no warnings") +end + +-- plain M3U (no header), CR line endings, Windows paths, relative without base, other schemes +do + local text = "C:\\Music\\Song A.mp3\rD:/Other/b.mp3\r\\\\server\\share\\c.mp3\rsongs\\d.mp3\rftp://x/e.mp3\rfile:///home/u/f.mp3" + local pl = Playlist.parse(text) + eq(#pl.entries, 6, "plain count") + eq(pl.entries[1].url, "C:\\Music\\Song A.mp3", "windows path kept as is") + eq(pl.entries[1].playable, false, "windows path unplayable") + eq(pl.entries[1].reason, "local path", "windows path reason") + eq(pl.entries[2].reason, "local path", "drive with slash") + eq(pl.entries[3].reason, "local path", "UNC") + eq(pl.entries[4].url, "songs\\d.mp3", "relative without base kept") + eq(pl.entries[4].reason, "relative path without a base URL", "relative without base reason") + eq(pl.entries[5].reason, "scheme ftp", "ftp unplayable") + eq(pl.entries[6].reason, "local path", "file: is local") + eq(has(pl.warnings, "relative path without a base URL"), true, "warning for relative") + eq(has(pl.warnings, "4 local paths"), true, "local paths summary") + -- with a URL base, Windows separators in relative entries become slashes; drive paths stay local + local pl2 = Playlist.parse(text, "http://h/x/list.m3u") + eq(pl2.entries[4].url, "http://h/x/songs/d.mp3", "backslash relative resolved") + eq(pl2.entries[4].playable, true, "backslash relative playable") + eq(pl2.entries[1].url, "C:\\Music\\Song A.mp3", "windows path untouched with a base") + -- with a Windows base, relative entries are paths next to the playlist + local pl3 = Playlist.parse("a.mp3\nsub\\b.mp3", "C:\\Music\\list.m3u") + eq(pl3.entries[1].url, "C:\\Music\\a.mp3", "windows base") + eq(pl3.entries[2].url, "C:\\Music\\sub\\b.mp3", "windows base sub") + eq(pl3.entries[1].playable, false, "windows base unplayable") + -- file: base + local pl4 = Playlist.parse("a.mp3", "file:///C:/Music/list.m3u") + eq(pl4.entries[1].url, "file:///C:/Music/a.mp3", "file base") + eq(pl4.entries[1].reason, "local path", "file base local") + -- a relative base is not used + local pl5 = Playlist.parse("a.mp3", "lists/x.m3u") + eq(has(pl5.warnings, "not absolute"), true, "relative base warning") +end + +-- Windows-1252 text (a classic .m3u), and UTF-8 kept +do + local pl = Playlist.parse("#EXTM3U\n#EXTINF:10,Bj\246rk \150 J\243ga\nhttp://x/j.mp3\n") + eq(pl.entries[1].title, "Björk – Jóga", "cp1252 transcoded") + eq(has(pl.warnings, "Windows%-1252"), true, "cp1252 warning") + local pl2 = Playlist.parse("#EXTINF:10,Björk – Jóga\nhttp://x/j.mp3") + eq(pl2.entries[1].title, "Björk – Jóga", "utf-8 kept") + eq(#pl2.warnings, 0, "utf-8 no warning") + local pl3 = Playlist.parse("http://x/Björk.mp3") + eq(pl3.entries[1].url, "http://x/Bj%C3%B6rk.mp3", "utf-8 url encoded") +end + +-- PLS +do + local text = "[playlist]\r\nNumberOfEntries=3\r\nFile2=http://s.example:8000/live\r\nTitle2=(#1) Some Radio\r\nLength2=-1\r\n" + .. "File1=music/a.mp3\r\nTitle1=Artist - Song\r\nLength1=200\r\n; comment\r\nfile10 = http://x/z.mp3\r\nVersion=2\r\n" + local pl = Playlist.parse(text, "http://h/p/list.pls") + eq(pl.kind, "pls", "pls kind") + eq(#pl.entries, 3, "pls count") + eq(pl.entries[1].url, "http://h/p/music/a.mp3", "pls order by index + resolved") + eq(pl.entries[1].title, "Artist - Song", "pls title") + eq(pl.entries[1].duration, 200, "pls length") + eq(pl.entries[2].url, "http://s.example:8000/live", "pls 2") + eq(pl.entries[2].duration, nil, "pls length -1") + eq(pl.entries[3].url, "http://x/z.mp3", "pls key case / spaces / index 10") + eq(pl.entries[3].title, nil, "pls no title") + eq(#pl.warnings, 0, "pls no warnings") + local bad = Playlist.parse("[Playlist]\nNumberOfEntries=2\nFile1=http://a/1.mp3\n") + eq(bad.kind, "pls", "pls case-insensitive header") + eq(has(bad.warnings, "NumberOfEntries=2 but 1"), true, "pls count mismatch warning") +end + +-- HLS master playlist: variants with attributes (quoted commas), EXT-X-MEDIA audio renditions +do + local text = [[#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="English",LANGUAGE="en",URI="audio/en.m3u8" +#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS="mp4a.40.2,avc1.4d401e",RESOLUTION=640x360,AUDIO="aud" +low/index.m3u8 +#EXT-X-STREAM-INF:BANDWIDTH=320000,CODECS="mp4a.40.34" +http://other.example/hi/index.m3u8 +]] + local pl = Playlist.parse(text, "https://cdn.example/show/master.m3u8") + eq(pl.kind, "hls", "hls kind") + assert(pl.hls) + eq(pl.hls.master, true, "master") + eq(#pl.entries, 3, "variants + rendition") + eq(pl.entries[1].url, "https://cdn.example/show/audio/en.m3u8", "rendition url") + eq(pl.entries[1].title, "English", "rendition name") + eq(pl.entries[2].url, "https://cdn.example/show/low/index.m3u8", "variant 1 url") + eq(pl.entries[2].bandwidth, 128000, "variant 1 bandwidth") + eq(pl.entries[2].codecs, "mp4a.40.2,avc1.4d401e", "variant codecs keeps its comma") + eq((pl.entries[2].attributes :: any).RESOLUTION, "640x360", "variant attributes") + eq(pl.entries[3].bandwidth, 320000, "variant 2 bandwidth") + eq(pl.entries[3].url, "http://other.example/hi/index.m3u8", "variant 2 absolute") + eq(#pl.warnings, 0, "master no warnings") +end + +-- HLS media playlist with mp3 segments (VOD) +do + local text = [[#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-TARGETDURATION:10 +#EXT-X-MEDIA-SEQUENCE:7 +#EXTINF:10.0, +seg7.mp3 +#EXTINF:9.5,Part two +seg8.mp3?token=a +#EXT-X-BYTERANGE:1000@0 +#EXTINF:4, +all.mp3 +#EXT-X-BYTERANGE:500 +#EXTINF:2, +all.mp3 +#EXT-X-ENDLIST +]] + local pl = Playlist.parse(text, "https://h/radio/list.m3u8") + assert(pl.hls) + eq(pl.kind, "hls", "media kind") + eq(pl.hls.master, false, "media not master") + eq(pl.hls.targetDuration, 10, "target duration") + eq(pl.hls.mediaSequence, 7, "media sequence") + eq(pl.hls.endList, true, "endlist") + eq(pl.hls.totalDuration, 25.5, "total duration") + eq(pl.hls.segmentFormat, "mp3", "segment format") + eq(#pl.entries, 4, "segments") + eq(pl.entries[1].url, "https://h/radio/seg7.mp3", "segment url") + eq(pl.entries[1].duration, 10, "segment duration") + eq(pl.entries[1].title, nil, "empty title is nil") + eq(pl.entries[2].title, "Part two", "segment title") + eq(pl.entries[2].url, "https://h/radio/seg8.mp3?token=a", "segment query") + eq(pl.entries[2].playable, true, "mp3 segments playable") + eq((pl.entries[3].byteRange :: any).length, 1000, "byterange length") + eq((pl.entries[3].byteRange :: any).offset, 0, "byterange offset") + eq((pl.entries[4].byteRange :: any).offset, 1000, "byterange continues") + eq(#pl.warnings, 0, "mp3 VOD no warnings") +end + +-- HLS media playlists with unsupported segments, live, encrypted, fMP4 +do + local ts = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6,\na.ts\n#EXTINF:6,\nb.ts\n", "http://h/x.m3u8") + assert(ts.hls) + eq(ts.entries[1].playable, false, "ts unplayable") + eq(ts.entries[1].reason, "segment format ts", "ts reason") + eq(ts.hls.segmentFormat, "ts", "ts format") + eq(has(ts.warnings, "HLS segments are %.ts"), true, "ts warning") + eq(has(ts.warnings, "live HLS"), true, "live warning") + local aac = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6,\na.aac\n#EXTINF:6,\nb.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + assert(aac.hls) + eq(aac.hls.segmentFormat, "mixed", "mixed format") + eq(has(aac.warnings, "%.aac"), true, "aac warning") + eq(aac.entries[2].playable, true, "mp3 among aac still playable") + local m4s = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:4,\n1.m4s\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + eq(m4s.entries[1].playable, false, "m4s unplayable") + eq(has(m4s.warnings, "%.m4s") and has(m4s.warnings, "fMP4"), true, "m4s + fmp4 warning") + local enc = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-KEY:METHOD=AES-128,URI=\"k\"\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + assert(enc.hls) + eq(enc.hls.encrypted, true, "encrypted") + eq(enc.entries[1].playable, false, "encrypted unplayable") + eq(has(enc.warnings, "encrypted"), true, "encrypted warning") + local none = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + eq(none.entries[1].playable, true, "METHOD=NONE is clear") +end + +-- detection +do + eq(Playlist.detect("[playlist]\nFile1=a"), "pls", "detect pls") + eq(Playlist.detect("\239\187\191 [PLAYLIST]\r\n"), "pls", "detect pls with BOM / spaces") + eq(Playlist.detect("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\na.m3u8"), "hls", "detect hls master") + eq(Playlist.detect("#EXTM3U\n#EXT-X-TARGETDURATION:5\n"), "hls", "detect hls media") + eq(Playlist.detect("#EXTM3U\n#EXTINF:1,a\na.mp3"), "m3u", "detect m3u") + eq(Playlist.detect("a.mp3"), "m3u", "detect plain") +end + +-- serialize: M3U8, round trip +do + local entries = { + { url = "http://x/a.mp3", title = "A - B", duration = 61.6 }, + { url = "http://x/b.mp3" }, + { url = "http://x/c.mp3", title = "multi\nline" }, + { url = "http://x/d.mp3", duration = 5 }, + { title = "no url" }, + } + local text = Playlist.serialize(entries :: any, { title = "Mix" }) + eq(text, "#EXTM3U\n#PLAYLIST:Mix\n#EXTINF:62,A - B\nhttp://x/a.mp3\nhttp://x/b.mp3\n#EXTINF:-1,multi line\nhttp://x/c.mp3\n" + .. "#EXTINF:5,\nhttp://x/d.mp3\n", "serialize text") + local back = Playlist.parse(text) + eq(#back.entries, 4, "round trip count") + eq(back.title, "Mix", "round trip title") + eq(back.entries[1].title, "A - B", "round trip title 1") + eq(back.entries[1].duration, 62, "round trip duration") + eq(back.entries[2].title, nil, "round trip no title") + eq(back.entries[3].duration, nil, "round trip unknown duration") + eq(Playlist.serialize({}), "#EXTM3U\n", "serialize empty") + -- parse -> serialize -> parse keeps everything of a real playlist + local pl = Playlist.parse("#EXTM3U\n#EXTINF:100,X - Y\nhttp://h/1.mp3\n#EXTINF:-1,Live\nhttp://h/live\n") + local again = Playlist.parse(Playlist.serialize(pl.entries)) + for i, e in pl.entries do + eq(again.entries[i].url, e.url, "rt url " .. i) + eq(again.entries[i].title, e.title, "rt title " .. i) + eq(again.entries[i].duration, e.duration, "rt duration " .. i) + end +end + +-- bad input never throws +do + local inputs: { any } = { "", "\n\n\n", "#EXTM3U", "#EXTINF:abc,\n", "[playlist]\n=\nFile=\nFilex1=y", "#EXT-X-STREAM-INF:\n", + "#EXT-X-STREAM-INF:BANDWIDTH=\"unterminated\n", "#EXT-X-BYTERANGE:x\n#EXT-X-TARGETDURATION:\n", "\255\254\0\0", 42, nil } + for i = 1, 11 do + local ok, pl = pcall(Playlist.parse, inputs[i], "http://h/") + eq(ok, true, "bad input " .. i .. " threw " .. tostring(pl)) + eq(type(pl.entries), "table", "bad input " .. i .. " entries") + end + eq(#Playlist.parse("").entries, 0, "empty text") + eq(has(Playlist.parse(42 :: any).warnings, "expected a string"), true, "non-string warning") + local ok = pcall(Playlist.serialize, { 1, "x", { url = 5 } } :: any) + eq(ok, true, "serialize skips junk") + -- random bytes + local state = 7 + for _ = 1, 300 do + local t = table.create(80) + for k = 1, 80 do + state = (state * 1103515245 + 12345) % 2147483648 + t[k] = string.char(({ 10, 13, 35, 44, 58, 61, 34, 92, 47, 46, 65, 120, 200 })[state % 13 + 1]) + end + local s = "#EXTM3U\n#EXT-X-" .. table.concat(t) + local ok2, err = pcall(Playlist.parse, s, "http://h/a/") + eq(ok2, true, "fuzz threw " .. tostring(err)) + local ok3, err3 = pcall(Playlist.parse, "[playlist]\n" .. table.concat(t), "http://h/a/") + eq(ok3, true, "fuzz pls threw " .. tostring(err3)) + end +end + + +-- Python-written playlists +for _, c in Cases do + local pl = M3u.decode(Bytes.reader(buffer.fromstring(c.m3u))) :: any + eq(#pl.entries, #c.entries, c.name .. ": entries") + for i, e in c.entries do + local g = pl.entries[i] + eq(g.url, e.url, c.name .. ": url " .. i) + eq(g.duration, e.duration, c.name .. ": duration " .. i) + if e.title then + eq(g.title, e.title, c.name .. ": title " .. i) + end + end + local back = M3u.decode(Bytes.reader(M3u.encode(pl, { title = c.title }) :: buffer)) :: any + eq(back.title, c.title, c.name .. ": #PLAYLIST round trip") + for i, e in pl.entries do + eq(back.entries[i].url, e.url, c.name .. ": round trip url " .. i) + eq(back.entries[i].title, e.title, c.name .. ": round trip title " .. i) + end +end +t:note("%d Python-written M3U8 files decode to their entries", #Cases) + +-- the contract and the api +do + eq(M3u.name, "m3u", "name") + eq(M3u.category, "playlist", "category") + local c = Cases[1] + eq(F.detect(c.m3u), "m3u", "F.detect") + local pl = F.playlist.load(c.m3u, { baseUrl = "http://x/" }) + t:check(pl and pl.kind == "playlist" and pl.format == "m3u" and #pl.entries == #c.entries, "F.playlist.load") + local saved = F.save(pl, nil, { format = "m3u8" }) + t:check(saved and string.sub(buffer.tostring(saved), 1, 7) == "#EXTM3U", "F.save m3u8") + local hls = F.playlist.load("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", { baseUrl = "http://h/x.m3u8" }) + t:check(hls and hls.format == "hls" and hls.hls.endList, "F.playlist.load HLS") + t:eq(M3u.sniff(Bytes.reader(buffer.fromstring("\239\187\191 #EXTM3U\n"))), 0.95, "sniff with BOM") + t:eq(M3u.sniff(Bytes.reader(buffer.fromstring("a.mp3\n"))), 0, "plain lists are found by extension") + local _, e = M3u.encode(5 :: any) + t:check(e ~= nil, "encode a number") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.m3u) +end +table.insert(samples, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS=\"mp4a.40.2\"\nlo.m3u8\n#EXT-X-MEDIA:TYPE=AUDIO,URI=\"a.m3u8\",NAME=\"x\"\n") +table.insert(samples, "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-BYTERANGE:100@0\n#EXTINF:6,\na.mp3\n#EXT-X-KEY:METHOD=AES-128\n#EXT-X-ENDLIST\n") +t:fuzz("decode", function(b: buffer) + return M3u.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/playlist/pls.luau b/tests/playlist/pls.luau new file mode 100644 index 0000000..39ddd5c --- /dev/null +++ b/tests/playlist/pls.luau @@ -0,0 +1,69 @@ +-- playlist/pls tests: Python-written PLS files (tools/fixtures/playlist.py) decode to their entries; keys in any case +-- and order, gaps in the numbering, comments, NumberOfEntries mismatches, Windows-1252, relative locations; the +-- writer round-trips (titles, unknown lengths, line breaks); the api; the fuzz pass. (The playlist-luau PLS cases run +-- in tests/playlist/m3u.luau.) Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Pls = require("@formats/playlist/pls") +local Bytes = require("@formats/core/Bytes") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("pls") +local function decode(s: string, base: string?): any + return Pls.decode(Bytes.reader(buffer.fromstring(s)), { baseUrl = base }) +end + +for _, c in Cases do + local pl = decode(c.pls) + t:eq(#pl.entries, #c.entries, c.name .. ": entries") + t:eq(#pl.warnings, 0, c.name .. ": no warnings") + for i, e in c.entries do + local g = pl.entries[i] + t:eq(g.url, e.url, c.name .. ": url " .. i) + t:eq(g.title, e.title, c.name .. ": title " .. i) + t:eq(g.duration, e.duration, c.name .. ": duration " .. i) + t:check(g.playable, c.name .. ": playable " .. i) + end + local back = decode(buffer.tostring(Pls.encode(pl) :: buffer)) + t:eq(#back.entries, #pl.entries, c.name .. ": round trip count") + for i, e in pl.entries do + local g = back.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration, c.name .. ": round trip " .. i) + end +end +t:note("%d Python-written PLS files decode to their entries and round-trip", #Cases) + +do + local pl = decode("; comment\n[PlayList]\nversion=2\nTITLE2=Second\nfile2=b.mp3\nFile10=http://x/ten.mp3\nLength2=7\nFile1=a.mp3\nnumberofentries=4\n", "http://h/dir/list.pls") + t:eq(#pl.entries, 3, "entries sorted by number") + t:eq(pl.entries[1].url, "http://h/dir/a.mp3", "relative resolved") + t:check(pl.entries[2].title == "Second" and pl.entries[2].duration == 7, "case-insensitive keys") + t:eq(pl.entries[3].url, "http://x/ten.mp3", "gap in numbering") + t:check(string.find(pl.warnings[1], "NumberOfEntries=4", 1, true) ~= nil, "count mismatch warning") + local cp = decode("[playlist]\nFile1=http://x/a.mp3\nTitle1=Bj\246rk\nNumberOfEntries=1\n") + t:eq(cp.entries[1].title, "Bj\u{f6}rk", "Windows-1252 text") + local loc = decode("[playlist]\nFile1=C:\\Music\\a.mp3\nNumberOfEntries=1\n") + t:check(not loc.entries[1].playable and loc.entries[1].reason == "local path", "local path") + -- the writer + local out = buffer.tostring(Pls.encode({ { url = "http://a/1.mp3", title = "One\nTwo", duration = 61.6 }, { url = "http://a/2.mp3" }, { url = 5 } } :: any) :: buffer) + t:eq(out, "[playlist]\nFile1=http://a/1.mp3\nTitle1=One Two\nLength1=62\nFile2=http://a/2.mp3\nLength2=-1\nNumberOfEntries=2\nVersion=2\n", "writer output") + t:check(select(2, Pls.encode(5 :: any)) ~= nil, "encode a number") + t:eq(Pls.sniff(Bytes.reader(buffer.fromstring("\239\187\191 [playlist]\r\nFile1=a"))), 0.95, "sniff") + t:eq(Pls.sniff(Bytes.reader(buffer.fromstring("#EXTM3U"))), 0, "sniff m3u") + -- the api + t:eq(F.detect(Cases[1].pls), "pls", "F.detect") + local a = F.playlist.load(Cases[1].pls) + t:check(a and a.format == "pls", "F.playlist.load") + local m = F.convert(Cases[1].pls, "m3u") + t:check(m and string.sub(buffer.tostring(m), 1, 7) == "#EXTM3U", "F.convert pls -> m3u") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.pls) +end +t:fuzz("decode", function(b: buffer) + return Pls.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/playlist/xspf.luau b/tests/playlist/xspf.luau new file mode 100644 index 0000000..8cb2aef --- /dev/null +++ b/tests/playlist/xspf.luau @@ -0,0 +1,89 @@ +-- playlist/xspf tests: XSPF files written by Python's xml.etree.ElementTree (tools/fixtures/playlist.py) decode to +-- their entries; every track field, multiple locations, xml:base, relative / local locations, a prefixed namespace; +-- the writer round-trips (and escapes; its output was also checked by hand with ElementTree); errors (malformed XML, +-- another root); the api; the fuzz pass. +-- Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Xspf = require("@formats/playlist/xspf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("xspf") +local function decode(s: string, base: string?): (any, any) + return Xspf.decode(Bytes.reader(buffer.fromstring(s)), { baseUrl = base }) +end + +for _, c in Cases do + local pl, err = decode(c.xspf) + t:check(pl, c.name .. ": decode: " .. tostring(err)) + t:eq(pl.title, c.title, c.name .. ": title") + t:eq(#pl.entries, #c.entries, c.name .. ": entries") + for i, e in c.entries do + local g = pl.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration and g.playable, c.name .. ": entry " .. i) + end + local back = decode(buffer.tostring(Xspf.encode(pl) :: buffer)) + t:eq(back.title, pl.title, c.name .. ": round trip title") + for i, e in pl.entries do + local g = back.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration, c.name .. ": round trip " .. i) + end +end +t:note("%d ElementTree-written XSPF files decode to their entries and round-trip", #Cases) + +do + local text = [[<?xml version="1.0" encoding="UTF-8"?> +<x:playlist version="1" xmlns:x="http://xspf.org/ns/0/" xml:base="http://media.example/base/"> + <x:title> My & list </x:title><x:creator>Me</x:creator> + <x:trackList> + <x:track><x:location>a%20b.mp3</x:location><x:location>http://mirror.example/a.mp3</x:location> + <x:title>A</x:title><x:creator>Artist</x:creator><x:album>Album</x:album><x:duration>1500</x:duration> + <x:trackNum>3</x:trackNum><x:image>cover.jpg</x:image><x:extension application="x"><y/></x:extension></x:track> + <x:track xml:base="http://other.example/dir/"><x:location>../b.mp3</x:location></x:track> + <x:track><x:title>no location</x:title></x:track> + <x:track><x:location>C:\Music\c.mp3</x:location></x:track> + </x:trackList> +</x:playlist>]] + local pl = decode(text, "http://ignored.example/") + t:eq(pl.title, "My & list", "title (entity, trimmed)") + t:eq(pl.meta.creator, "Me", "playlist creator") + t:eq(#pl.entries, 3, "a track without a location is skipped") + local a = pl.entries[1] + t:eq(a.url, "http://media.example/base/a%20b.mp3", "xml:base on the playlist") + t:check(a.title == "A" and a.creator == "Artist" and a.album == "Album" and a.duration == 1.5 and a.trackNum == 3 and a.image == "cover.jpg", "track fields") + t:check(a.locations and #a.locations == 2 and a.locations[2] == "http://mirror.example/a.mp3", "multiple locations") + t:eq(pl.entries[2].url, "http://other.example/b.mp3", "xml:base on a track") + t:check(not pl.entries[3].playable and pl.entries[3].reason == "local path", "local path") + t:check(#pl.warnings >= 2, "warnings for the missing location and the local path") + -- writer: escaping, extra fields, a plain entry list + local out = buffer.tostring(Xspf.encode({ { url = "http://x/a?b=1&c=2", title = "<A & B>", duration = 2.5, creator = "C" } } :: any) :: buffer) + t:check(string.find(out, "http://x/a?b=1&c=2", 1, true) ~= nil and string.find(out, "<A & B>", 1, true) ~= nil, "escaping") + local back = decode(out) + t:check(back.entries[1].url == "http://x/a?b=1&c=2" and back.entries[1].title == "<A & B>" and back.entries[1].duration == 2.5 and back.entries[1].creator == "C", "writer round trip") + -- errors + local _, e1 = decode("<playlist><trackList>") + t:check(e1 and Err.is(e1), "malformed XML: " .. tostring(e1)) + local _, e2 = decode("<html/>") + t:check(e2 and e2.code == Err.CORRUPT, "another root") + t:check(select(2, Xspf.encode(5 :: any)) ~= nil, "encode a number") + t:eq(Xspf.sniff(Bytes.reader(buffer.fromstring(Cases[1].xspf))), 0.95, "sniff") + t:eq(Xspf.sniff(Bytes.reader(buffer.fromstring("<playlist/>"))), 0, "sniff without the namespace") + -- the api + t:eq(F.detect(Cases[1].xspf), "xspf", "F.detect") + local la = F.playlist.load(Cases[1].xspf) + t:check(la and la.format == "xspf" and #la.entries == #Cases[1].entries, "F.playlist.load") + local m = F.convert(Cases[1].m3u, "xspf") + t:check(m and #decode(buffer.tostring(m)).entries == #Cases[1].entries, "F.convert m3u -> xspf") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.xspf) +end +t:fuzz("decode", function(b: buffer) + return Xspf.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 0923cd7..e5fa3aa 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1,12 +1,25 @@ -- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs. -- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), zstd / brotli / -- bzip2 / lzma (their *_bench corpora) and fonts (glyph outlines + rasterization: glyphs per second). +-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py, +-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time), +-- tools/fixtures/flac.py; wav encodes / decodes a generated tone. local Deflate = require("@formats/codecs/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") local Png = require("@formats/image/png") local B = require("@tests/gen/deflate_bench") local PB = require("@tests/gen/png_bench") +local Mp3 = require("@formats/audio/mp3") +local MC = require("@tests/gen/mp3_cases") +local Opus = require("@formats/audio/opus") +local OpusCelt = require("@tests/gen/opus_celt_st_128") +local OpusSilk = require("@tests/gen/opus_silk_wb_st") +local OpusHybrid = require("@tests/gen/opus_hybrid_st") +local Flac = require("@formats/audio/flac") +local FC = require("@tests/gen/flac_cases") +local Wav = require("@formats/audio/wav") +local Types = require("@formats/Types") local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" @@ -19,6 +32,7 @@ local function bench(label: string, n: number, bytes: number, f: () -> ()) dt = math.min(dt, os.clock() - t0) end print(string.format("%-8s %-30s %8.2f ms %7.1f MB/s", runtime, label, dt * 1000, bytes / dt / 1e6)) + return dt end local z = buffer.fromstring(B.zlib) @@ -130,6 +144,52 @@ do end) end end +for _, name in { "l3_cbr128_js", "l3_vbr_v2_48k", "l2_192_st" } do + for _, c in MC do + if c.name == name then + local b = buffer.fromstring(c.data) + local dec = assert(Mp3.open(Bytes.reader(b))) + local secs = dec.duration + local dt = bench("mp3 decode " .. name, 5, dec.frames * dec.channels * 4, function() + local d = assert(Mp3.open(Bytes.reader(b))) + d:readAll() + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt)) + end + end +end +for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", OpusHybrid } } do + local b = buffer.fromstring(c[2].data) + bench("opus decode " .. c[1] .. " (3 s st)", 3, #c[2].ref, function() + Opus.decode(Bytes.reader(b)) + end) +end +for _, name in { "s16_long", "s24_96k" } do + for _, c in FC do + if c.name == name then + local b = buffer.fromstring(c.data) + local dec = assert(Flac.open(Bytes.reader(b))) + local secs = dec.duration + local dt = bench("flac decode " .. name, 5, dec.frames * dec.channels * 4, function() + Flac.decode(Bytes.reader(b)) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt)) + end + end +end +do + local a = Types.Audio.new(44100, 2, 44100 * 10) + for i = 0, 44100 * 20 - 1 do + buffer.writef32(a.samples, i * 4, math.sin(i * 0.01) * 0.5) + end + bench("wav encode s16 (10 s stereo)", 5, buffer.len(a.samples), function() + Wav.encode(a) + end) + local file = assert(Wav.encode(a)) + bench("wav decode s16 (10 s stereo)", 5, buffer.len(a.samples), function() + Wav.decode(Bytes.reader(file)) + end) +end do local Json = require("@formats/codecs/Json") local JB = require("@tests/gen/json_bench") diff --git a/tools/fixtures/_bmp_reference.py b/tools/fixtures/_bmp_reference.py new file mode 100644 index 0000000..7b6ae6d --- /dev/null +++ b/tools/fixtures/_bmp_reference.py @@ -0,0 +1,134 @@ +# BMP reference decodes with Pillow (run by tools/fixtures/bmp.py inside a nix python with pillow): reads a JSON request +# on stdin, writes JSON on stdout. Ported from bmp-luau tools/mkfixtures.py (its Pillow rules: see "expected"). +# {"root": dir, "files": [rel...], "refs": {rel: png}, "encode": [{"name", "mode", "w", "h", "rgba" (hex), "palette"?}]} +# -> {"files": [{"name", "w", "h", "crc"} or {"name", "error"}], "encode": [{"name", "bmp" (hex)}]} +# Expected pixels: Pillow's RGBA, with these rules (Pillow differs from browsers there): +# - 32 bpp BI_RGB: the 4th byte is alpha (Pillow ignores it), unless every one is 0 (then opaque). +# - 32 bpp with an alpha mask whose values are all 0: opaque. +# - RLE: decoded by rle_reference below over Pillow's palette (Pillow's RLE decoder has bugs); skipped pixels are +# transparent black. +# - Files Pillow cannot read (unusual BITFIELDS in the suite's g/): the suite's own reference PNG. +import io, json, os, struct, sys, zlib +from PIL import Image, ImageFile + +# truncated files (a bad bfSize / short pixel array, as in some skins): Pillow fills the missing rows with 0 +ImageFile.LOAD_TRUNCATED_IMAGES = True + +# RLE: Pillow's decoder mishandles odd RLE4 absolute runs, an end of line at x = 0 and an end of bitmap before the +# last row (as in the Winamp base skin), so the reference for RLE files is this spec decoder over Pillow's palette. +# Pixels the stream skips (delta, early end of line / bitmap) are transparent black, as in browsers. +# (Pillow's own RLE decode still has to load without failing, for the palette: pad its output with index 0) +from PIL import BmpImagePlugin +_set_as_raw = BmpImagePlugin.BmpRleDecoder.set_as_raw +def _padded(self, data, rawmode=None, extra=()): + need = self.state.xsize * self.state.ysize + return _set_as_raw(self, data + b"\0" * max(0, need - len(data)), rawmode, extra) +BmpImagePlugin.BmpRleDecoder.set_as_raw = _padded + +def rle_reference(im, raw, w, h, rle4): + off = struct.unpack_from("<I", raw, 10)[0] + top = struct.unpack_from("<i", raw, 22)[0] < 0 + if im.mode == "P": + p = im.getpalette() or [] + pal = [tuple(p[i * 3:i * 3 + 3]) + (255,) for i in range(len(p) // 3)] + elif im.mode == "L": + pal = [(i, i, i, 255) for i in range(256)] + else: + pal = [(0, 0, 0, 255), (255, 255, 255, 255)] + pal += [(0, 0, 0, 255)] * (256 - len(pal)) + out = bytearray(w * h * 4) + def put(x, y, i): + if x < w and y < h: + r = y if top else h - 1 - y + out[(r * w + x) * 4:(r * w + x) * 4 + 4] = bytes(pal[i]) + p, x, y, n = off, 0, 0, len(raw) + while y < h and p + 1 < n: + c, v = raw[p], raw[p + 1] + p += 2 + if c: + for k in range(c): + put(x + k, y, (v >> 4 if k % 2 == 0 else v & 15) if rle4 else v) + x += c + elif v == 0: + x, y = 0, y + 1 + elif v == 1: + break + elif v == 2: + if p + 1 >= n: + break + x, y = x + raw[p], y + raw[p + 1] + p += 2 + else: + nb = (v + 1) // 2 if rle4 else v + if p + nb > n: + break + for k in range(v): + b = raw[p + k // 2] if rle4 else raw[p + k] + put(x + k, y, (b >> 4 if k % 2 == 0 else b & 15) if rle4 else b) + x += v + p += nb + (nb & 1) + return bytes(out) + +def expected(path, raw, root): + try: + im = Image.open(path) + im.load() + except Exception: + ref = REFS.get(os.path.relpath(path, root)) + if not ref: + raise + ref = os.path.join(root, "ref", ref) + im = Image.open(ref) + im.load() + w, h = im.size + hs = struct.unpack_from("<I", raw, 14)[0] + comp = struct.unpack_from("<I", raw, 30)[0] if hs >= 40 else 0 + if comp in (1, 2) and im.format == "BMP": + return w, h, rle_reference(im, raw, w, h, comp == 2), True + rgba = bytearray(im.convert("RGBA").tobytes()) + if hs >= 40: + bpp, comp = struct.unpack_from("<HI", raw, 28) + if bpp == 32 and comp in (0, 3, 6): + alpha = None + if comp == 0: + off = struct.unpack_from("<I", raw, 10)[0] + top = struct.unpack_from("<i", raw, 22)[0] < 0 + alpha = bytearray(w * h) + for y in range(h): + r = y if top else h - 1 - y + alpha[y * w:(y + 1) * w] = raw[off + r * w * 4 + 3: off + (r + 1) * w * 4: 4] + else: + alpha = rgba[3::4] + if not any(alpha): + alpha = b"\xff" * (w * h) + rgba[3::4] = alpha + return w, h, bytes(rgba), False + + +req = json.load(sys.stdin) +REFS = req.get("refs", {}) +out = {"files": [], "encode": []} +for rel in req["files"]: + p = os.path.join(req["root"], rel) + raw = open(p, "rb").read() + try: + w, h, rgba, _ = expected(p, raw, req["root"]) + out["files"].append({"name": rel, "w": w, "h": h, "crc": zlib.crc32(rgba)}) + except Exception as e: + out["files"].append({"name": rel, "error": str(e)}) +for e in req.get("encode", []): + rgba = bytes.fromhex(e["rgba"]) + im = Image.frombytes("RGBA", (e["w"], e["h"]), rgba) + if e["mode"] == "RGB": + im = im.convert("RGB") + elif e["mode"] == "P": + pal = e["palette"] # [[r, g, b], ...] in first-appearance order + idx = {tuple(c): i for i, c in enumerate(pal)} + p = Image.new("P", im.size) + p.putpalette([v for c in pal for v in c]) + p.putdata([idx[px[:3]] for px in im.getdata()]) + im = p + b = io.BytesIO() + im.save(b, "BMP") + out["encode"].append({"name": e["name"], "bmp": b.getvalue().hex()}) +json.dump(out, sys.stdout) diff --git a/tools/fixtures/apng.py b/tools/fixtures/apng.py new file mode 100644 index 0000000..2f1f583 --- /dev/null +++ b/tools/fixtures/apng.py @@ -0,0 +1,220 @@ +# APNG fixtures (tools/fixtures.py). +# tests/gen/apng_cases.luau animated PNGs with the reference composited canvases (CRC-32 of each full rgba8 frame) +# - made by ffmpeg's apng encoder (sub-rectangles, dispose / blend chosen by ffmpeg, -plays) +# - written here by hand: every dispose op (none / background / previous) and blend op (source / over) on +# sub-rectangles with partial alpha, a hidden default image (IDAT not part of the animation), palette + tRNS, +# grey, RGB, a first frame with dispose previous, split fdATs +# The reference canvases come from ffmpeg (`-f apng -i x -f rawvideo -pix_fmt rgba`); a small compositor here +# (the same integer blend as ffmpeg's pngdec.c) must agree with ffmpeg, so a broken reference is caught too. +# Files ffmpeg cannot represent (the hidden default image) use the compositor here alone. +import os, random, struct, subprocess, tempfile, zlib + + +def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + + +CH = {0: 1, 2: 3, 3: 1, 6: 4} + + +def raw_rows(px, w, h, ct, rng): + """px: list of h rows of w sample tuples -> filtered (random filter per row) scanlines""" + ch = CH[ct] + out = bytearray() + prev = None + for y in range(h): + row = bytes(s for p in px[y] for s in p) + ft = rng.randrange(5) + out.append(ft) + for i, x in enumerate(row): + a = row[i - ch] if i >= ch else 0 + b = prev[i] if prev else 0 + c = prev[i - ch] if prev and i >= ch else 0 + if ft == 4: + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c) + else: + pred = (0, a, b, (a + b) // 2)[ft] + out.append((x - pred) & 255) + prev = row + return bytes(out) + + +def to_rgba(ct, s, plte=None, trns=None): + if ct == 6: + return tuple(s) + if ct == 2: + return (s[0], s[1], s[2], 255) + if ct == 0: + return (s[0], s[0], s[0], 255) + c = plte[s[0]] + a = trns[s[0]] if trns and s[0] < len(trns) else 255 + return (c[0], c[1], c[2], a) + + +def apng(w, h, ct, frames, plays=0, default=None, plte=None, trns=None, rng=None, split=1): + """frames: list of dict(x, y, w, h, px, num, den, dispose, blend); default: px of a hidden default image""" + rng = rng or random.Random(1) + out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, ct, 0, 0, 0)) + out += chunk(b"acTL", struct.pack(">II", len(frames), plays)) + if plte: + out += chunk(b"PLTE", b"".join(bytes(c) for c in plte)) + if trns: + out += chunk(b"tRNS", bytes(trns)) + seq = 0 + if default is not None: + out += chunk(b"IDAT", zlib.compress(raw_rows(default, w, h, ct, rng))) + for i, f in enumerate(frames): + out += chunk(b"fcTL", struct.pack(">IIIIIHHBB", seq, f["w"], f["h"], f["x"], f["y"], f["num"], f["den"], f["dispose"], f["blend"])) + seq += 1 + z = zlib.compress(raw_rows(f["px"], f["w"], f["h"], ct, rng)) + step = max(1, -(-len(z) // split)) + for k in range(0, len(z), step): + if i == 0 and default is None: + out += chunk(b"IDAT", z[k:k + step]) + else: + out += chunk(b"fdAT", struct.pack(">I", seq) + z[k:k + step]) + seq += 1 + return out + chunk(b"IEND", b"") + + +def div255(x): + return ((x + 128) * 257) >> 16 + + +def composite(w, h, ct, frames, plte=None, trns=None): + """full rgba8 canvases (bytes), blending like ffmpeg's pngdec.c (APNG spec semantics)""" + canvas = [(0, 0, 0, 0)] * (w * h) + outs = [] + for i, f in enumerate(frames): + dispose, blend = f["dispose"], f["blend"] + if i == 0: + blend = 0 + if dispose == 2: + dispose = 1 + saved = list(canvas) + for yy in range(f["h"]): + for xx in range(f["w"]): + src = to_rgba(ct, f["px"][yy][xx], plte, trns) + k = (f["y"] + yy) * w + f["x"] + xx + if blend == 0 or src[3] == 255: + canvas[k] = src + elif src[3] == 0: + pass + else: + fa, bg = src[3], canvas[k] + ba = bg[3] + oa = fa + div255((255 - fa) * ba) + if ba == 255: + canvas[k] = tuple(div255(fa * src[c] + (255 - fa) * bg[c]) for c in range(3)) + (oa,) + else: + canvas[k] = tuple((255 * fa * src[c] + (255 - fa) * ba * bg[c]) // (255 * oa) for c in range(3)) + (oa,) + outs.append(b"".join(bytes(p) for p in canvas)) + if dispose == 1: + for yy in range(f["h"]): + for xx in range(f["w"]): + canvas[(f["y"] + yy) * w + f["x"] + xx] = (0, 0, 0, 0) + elif dispose == 2: + canvas = saved + return outs + + +def ffmpeg_frames(ctx, data, w, h): + with tempfile.TemporaryDirectory() as tmp: + p = os.path.join(tmp, "in.png") + with open(p, "wb") as f: + f.write(data) + raw = subprocess.run(["ffmpeg", "-v", "error", "-f", "apng", "-i", p, "-f", "rawvideo", "-pix_fmt", "rgba", "-fps_mode", "passthrough", "-"], + capture_output=True, check=True).stdout + n = w * h * 4 + return [raw[i:i + n] for i in range(0, len(raw), n)] + + +def sprite(rng, w, h, ct, alpha=True, ncolors=None): + px = [] + for y in range(h): + row = [] + for x in range(w): + if ct == 3: + row.append((rng.randrange(ncolors),)) + elif ct == 0: + row.append(((x * 17 + y * 5 + rng.randrange(8)) & 255,)) + elif ct == 2: + row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255)) + else: + a = rng.choice((0, 255, 255, rng.randrange(256))) if alpha else 255 + row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255, a)) + px.append(row) + return px + + +def frame(rng, ct, x, y, w, h, dispose, blend, num=1, den=10, **kw): + return {"x": x, "y": y, "w": w, "h": h, "px": sprite(rng, w, h, ct, **kw), "num": num, "den": den, "dispose": dispose, "blend": blend} + + +def generate(ctx): + rng = random.Random(77) + cases = [] + + def add(name, data, w, h, frames_meta, refs, default_crc=None, plays=0, ffmpeg=True, opaque=False): + c = {"name": name, "data": data, "width": w, "height": h, "plays": plays, + "frames": [{"x": f["x"], "y": f["y"], "w": f["w"], "h": f["h"], "num": f["num"], "den": f["den"], "dispose": f["dispose"], "blend": f["blend"]} for f in frames_meta], + "crcs": [zlib.crc32(r) for r in refs], "ffmpeg": ffmpeg, "opaque": opaque} + if default_crc is not None: + c["defaultCrc"] = default_crc + cases.append(c) + + def hand(name, w, h, ct, frames, plays=0, plte=None, trns=None, split=1): + data = apng(w, h, ct, frames, plays=plays, plte=plte, trns=trns, rng=rng, split=split) + mine = composite(w, h, ct, frames, plte, trns) + ref = ffmpeg_frames(ctx, data, w, h) + if ct in (0, 2): # ffmpeg decodes to an opaque pixel format: disposed pixels come out opaque black + mine = [bytes(v if i % 4 != 3 else 255 for i, v in enumerate(m)) for m in mine] + if ref != mine: + for fi, (a, b) in enumerate(zip(ref, mine)): + if a != b: + k = next(j for j in range(len(a)) if a[j] != b[j]) + print("apng fixture mismatch:", name, fi, k // 4 % w, k // 4 // w, a[k - k % 4:k - k % 4 + 4], b[k - k % 4:k - k % 4 + 4], frames[fi]["dispose"], frames[fi]["blend"], frames[fi - 1]["dispose"] if fi else None, sum(1 for j in range(0, len(a), 4) if a[j:j + 4] != b[j:j + 4])) + raise RuntimeError("apng fixture %s: ffmpeg and the reference compositor disagree (%d vs %d frames)" % (name, len(ref), len(mine))) + add(name, data, w, h, frames, ref, plays=plays, opaque=ct in (0, 2)) + + # every dispose x blend on sub-rectangles over a semi-transparent background + W, H = 20, 16 + fr = [frame(rng, 6, 0, 0, W, H, 0, 0)] + for d in (0, 1, 2): + for b in (0, 1): + fr.append(frame(rng, 6, rng.randrange(8), rng.randrange(6), 1 + rng.randrange(12), 1 + rng.randrange(10), d, b, num=rng.randrange(1, 200), den=rng.choice((0, 100, 1000)))) + fr.append(frame(rng, 6, 3, 2, 9, 7, 2, 1)) + fr.append(frame(rng, 6, 0, 0, W, H, 0, 1)) + hand("rgba-dispose-blend", W, H, 6, fr, plays=3, split=2) + # first frame dispose previous (= background), then over + hand("first-previous", 12, 9, 6, [frame(rng, 6, 0, 0, 12, 9, 2, 1), frame(rng, 6, 2, 2, 5, 4, 0, 1), frame(rng, 6, 0, 0, 3, 3, 1, 0)]) + # palette + tRNS, over + pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(40)] + trns = [rng.choice((0, 128, 255, rng.randrange(256))) for _ in range(30)] + hand("palette-trns", 17, 13, 3, [frame(rng, 3, 0, 0, 17, 13, 1, 0, ncolors=40)] + [frame(rng, 3, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(12), 1 + rng.randrange(8), rng.randrange(3), rng.randrange(2), ncolors=40) for _ in range(5)], plte=pal, trns=trns) + # grey and RGB (no alpha: over = source) + hand("gray", 15, 11, 0, [frame(rng, 0, 0, 0, 15, 11, 0, 0)] + [frame(rng, 0, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)], plays=1) + hand("rgb", 15, 11, 2, [frame(rng, 2, 0, 0, 15, 11, 1, 0)] + [frame(rng, 2, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)]) + # a single-frame APNG + hand("one-frame", 7, 5, 6, [frame(rng, 6, 0, 0, 7, 5, 0, 0)]) + + # hidden default image (not part of the animation): ffmpeg's demuxer cannot express it, so the compositor here + dpx = sprite(rng, 10, 8, 6) + fr = [frame(rng, 6, 0, 0, 10, 8, 0, 0), frame(rng, 6, 2, 1, 4, 5, 1, 1), frame(rng, 6, 5, 3, 5, 5, 0, 1)] + data = apng(10, 8, 6, fr, default=dpx, rng=rng) + add("hidden-default", data, 10, 8, fr, composite(10, 8, 6, fr), default_crc=zlib.crc32(b"".join(bytes(p) for row in dpx for p in row)), ffmpeg=False) + + # ffmpeg's own encoder (it picks sub-rectangles, dispose and blend ops) + for name, src, pix, plays in ( + ("ffmpeg-testsrc", "testsrc=size=40x30:rate=10", "rgb24", 0), + ("ffmpeg-rgba", "testsrc2=size=36x28:rate=8,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(mod(X+T*40,20),10),255,90)'", "rgba", 2), + ): + data = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", src, "-frames:v", "7", "-pix_fmt", pix, "-plays", str(plays), "-f", "apng", "-"], + capture_output=True, check=True).stdout + w, h = struct.unpack(">II", data[16:24]) + ref = ffmpeg_frames(ctx, data, w, h) + cases.append({"name": name, "data": data, "width": w, "height": h, "plays": plays, "crcs": [zlib.crc32(r) for r in ref], "ffmpeg": True, "opaque": pix == "rgb24"}) + + ctx.emit("apng_cases", cases) diff --git a/tools/fixtures/bmp.py b/tools/fixtures/bmp.py new file mode 100644 index 0000000..ead8316 --- /dev/null +++ b/tools/fixtures/bmp.py @@ -0,0 +1,69 @@ +# BMP fixtures (tools/fixtures.py): image/bmp. Ported from bmp-luau tools/fixtures.sh + mkfixtures.py. +# tests/gen/bmp_suite.luau the BMP Suite 2.8 (tests/fixtures/bmpsuite: g/ must match, q/ and b/ must not throw; +# public domain, see licenses/) with Pillow's reference RGBA (tools/fixtures/_bmp_reference.py) +# tests/gen/bmp_enc.luau encoder references: images saved by Pillow as 24 bpp RGB, 8 bpp P (palette in first-appearance +# order) and 32 bpp RGBA (BI_RGB); our encoder must write the same bytes +# (bmp-luau also tested the Winamp skins of the Webamp demo; those are not redistributable and are not used here.) +import json, os, random + +INPUTS = ["tests/fixtures/bmpsuite", "tools/fixtures/_bmp_reference.py"] + + +def image(rng, w, h, ncolours, alpha): + pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(ncolours)] + px = bytearray() + for y in range(h): + for x in range(w): + c = pal[(x * 7 + y * 13 + rng.randrange(3)) % ncolours] if ncolours else (rng.randrange(256), rng.randrange(256), rng.randrange(256)) + px += bytes(c) + bytes([rng.randrange(256) if alpha else 255]) + return bytes(px) + + +def first_appearance(rgba): + seen, pal = set(), [] + for i in range(0, len(rgba), 4): + c = tuple(rgba[i:i + 3]) + if c not in seen: + seen.add(c) + pal.append(list(c)) + return pal + + +def generate(ctx): + root = os.path.join(ctx.root, "tests", "fixtures", "bmpsuite") + refs = {} + for line in open(os.path.join(root, "ref.txt")).read().split("\n"): + if line: + a, b = line.split() + refs[a] = b + files = [d + "/" + f for d in ("g", "q", "b") for f in sorted(os.listdir(os.path.join(root, d)))] + rng = random.Random(11) + enc = [] + for name, w, h, ncol, alpha, mode in (("rgb-37x23", 37, 23, 0, False, "RGB"), ("rgb-1x1", 1, 1, 0, False, "RGB"), + ("rgb-640x3", 640, 3, 0, False, "RGB"), ("pal-5-13x9", 13, 9, 5, False, "P"), + ("pal-256-64x64", 64, 64, 256, False, "P"), ("pal-1-3x3", 3, 3, 1, False, "P"), + ("pal-17-50x7", 50, 7, 17, False, "P"), ("rgba-21x11", 21, 11, 0, True, "RGBA"), + ("rgba-pal-9x9", 9, 9, 4, True, "RGBA")): + rgba = image(rng, w, h, ncol, alpha) + if mode == "P": + pal = first_appearance(rgba) + assert len(pal) <= 256 + enc.append({"name": name, "mode": mode, "w": w, "h": h, "rgba": rgba.hex(), **({"palette": pal} if mode == "P" else {})}) + req = {"root": root, "files": files, "refs": refs, "encode": enc} + code = open(os.path.join(ctx.root, "tools", "fixtures", "_bmp_reference.py")).read() + res = json.loads(ctx.python(["pillow"], code, input=json.dumps(req).encode())) + suite = [] + for f in res["files"]: + mode = "match" if f["name"].startswith("g/") else "nocrash" + if mode == "match" and "error" in f: + raise RuntimeError("pillow cannot read %s: %s" % (f["name"], f["error"])) + e = {"name": f["name"], "mode": mode, "data": ctx.read(os.path.join("tests", "fixtures", "bmpsuite", f["name"]))} + if "w" in f: + e.update(w=f["w"], h=f["h"], crc=f["crc"]) + suite.append(e) + ctx.emit("bmp_suite", suite) + out = [] + for e, r in zip(enc, res["encode"]): + out.append({"name": e["name"], "mode": e["mode"], "w": e["w"], "h": e["h"], "rgba": bytes.fromhex(e["rgba"]), + "bmp": bytes.fromhex(r["bmp"])}) + ctx.emit("bmp_enc", out) diff --git a/tools/fixtures/flac.py b/tools/fixtures/flac.py new file mode 100644 index 0000000..222236e --- /dev/null +++ b/tools/fixtures/flac.py @@ -0,0 +1,286 @@ +# FLAC fixtures (tools/fixtures.py): audio/flac. Ported from flac-luau tools/gen_fixtures.py. +# tests/gen/flac_cases.luau streams from the reference encoder (flac 0-8, 4-32 bits, 1-6 channels, odd rates and +# block sizes, LPC order 32, wasted bits, Rice2, Ogg FLAC, tags + a picture), ffmpeg's +# encoder (every stereo mode), a spliced variable-block stream, an ID3v2 tag in front; +# each with the zlib CRC-32 of `flac -d`'s samples (i32 LE, interleaved) +import base64, math, os, random, struct, tempfile, zlib + +CTX = None +TMP = None +CASES = [] + + +def signal(secs, rate, ch, bits, kind="music", seed=1, wasted=0): + """Interleaved ints in the signed `bits` range.""" + rnd = random.Random(seed) + n = int(secs * rate) + top = (1 << (bits - 1)) - 1 + out = [] + notes = [(rnd.uniform(80, 900), rnd.uniform(0, n), rnd.uniform(0.2, 0.6) * rate) for _ in range(int(secs * 6) + 2)] + for i in range(n): + t = i / rate + for c in range(ch): + if kind == "silence": + v = 0.0 + elif kind == "noise": + v = rnd.uniform(-0.9, 0.9) + elif kind == "smooth": # slow polynomial-like curves (high fixed orders) + v = 0.8 * math.sin(2 * math.pi * (1000 + 300 * c) * t) + elif kind == "loudnoise": # full scale tone + strong noise: large Rice parameters at 32 bits + v = 0.6 * math.sin(2 * math.pi * 440 * t) + 0.08 * (rnd.random() - 0.5) + elif kind == "square": # constant runs + v = 0.5 if (i // 300) % 2 else -0.25 + else: + v = 0.0 + for f, st, dur in notes: + if st <= i < st + dur: + e = math.exp(-3 * (i - st) / dur) * min(1.0, (i - st) / 200) + v += 0.2 * e * (math.sin(2 * math.pi * f * (1 + 0.003 * c) * t) + + 0.4 * math.sin(4 * math.pi * f * t + c) + 0.15 * math.sin(6 * math.pi * f * t)) + v += 0.002 * (rnd.random() - 0.5) + 0.05 * math.sin(2 * math.pi * 55 * t) + x = int(max(-1.0, min(1.0, v)) * top) + if wasted: + x = (x >> wasted) << wasted + out.append(x) + return out + + +def write_wav(path, ints, ch, rate, bits): + container = (bits + 7) // 8 * 8 + data = bytearray() + for v in ints: + x = v << (container - bits) + if container == 8: + data.append((x + 128) & 255) + else: + data += x.to_bytes(container // 8, "little", signed=True) + guid = b"\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71" + fmt = struct.pack("<HHIIHHHHI16s", 0xFFFE, ch, rate, rate * ch * container // 8, ch * container // 8, container, + 22, bits, 0, guid) + body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data) + open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body) + + +def read_ref(flac_path, bits): + """Reference ints from flac -d.""" + if bits in (8, 16, 24, 32): + raw = flac_path + ".raw" + CTX.nix("flac", ["flac", "-s", "-f", "-d", "--force-raw-format", "--endian=little", "--sign=signed", flac_path, "-o", raw]) + d = open(raw, "rb").read() + w = bits // 8 + return [int.from_bytes(d[i:i + w], "little", signed=True) for i in range(0, len(d), w)] + wav = flac_path + ".wav" + CTX.nix("flac", ["flac", "-s", "-f", "-d", flac_path, "-o", wav]) + d = open(wav, "rb").read() + container = struct.unpack_from("<H", d, 34)[0] + i = 12 + while d[i:i + 4] != b"data": + i += 8 + struct.unpack_from("<I", d, i + 4)[0] + size = struct.unpack_from("<I", d, i + 4)[0] + d = d[i + 8:i + 8 + size] + w = container // 8 + out = [] + for j in range(0, len(d), w): + x = d[j] - 128 if w == 1 else int.from_bytes(d[j:j + w], "little", signed=True) + out.append(x >> (container - bits)) + return out + + +def crc_ints(ints): + return zlib.crc32(b"".join(struct.pack("<i", v) for v in ints)) + + +def emit(name, path, rate, ch, bits, note, ogg=False, tags=None, prefix=b""): + ref = read_ref(path, bits) + data = prefix + open(path, "rb").read() + c = {"name": name, "note": note, "data": data, "rate": rate, "channels": ch, "bps": bits, "frames": len(ref) // ch, + "crc": crc_ints(ref), "ogg": ogg} + if tags: + c["tags"] = tags + CASES.append(c) + + +def flac(name, secs, rate, ch, bits, args, kind="music", wasted=0, note=None, ogg=False, tags=None, seed=1): + wav = os.path.join(TMP, name + ".wav") + out = os.path.join(TMP, name + (".oga" if ogg else ".flac")) + write_wav(wav, signal(secs, rate, ch, bits, kind, seed, wasted), ch, rate, bits) + CTX.nix("flac", ["flac", "-s", "-f"] + args + [wav, "-o", out]) + emit(name, out, rate, ch, bits, note or "flac " + " ".join(args), ogg=ogg, tags=tags) + return out + + +CRC8 = [] +for i in range(256): + c = i + for _ in range(8): + c = ((c << 1) ^ 0x07) & 0xFF if c & 0x80 else (c << 1) & 0xFF + CRC8.append(c) + + +def crc8(d): + c = 0 + for x in d: + c = CRC8[c ^ x] + return c + + +def crc16(d): + c = 0 + for x in d: + c ^= x << 8 + for _ in range(8): + c = ((c << 1) ^ 0x8005) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF + return c + + +def utf8num(n): + if n < 0x80: + return bytes([n]) + out = [] + lim = 0x3F + while True: + out.append(0x80 | (n & 0x3F)) + n >>= 6 + lim >>= 1 + if n <= lim: + break + k = len(out) + 1 + first = ((0xFF00 >> k) & 0xFF) | n + return bytes([first]) + bytes(reversed(out)) + + +def frames_of(data): + """(offset, header_len, end) of each frame of a fixed-blocksize native stream (CRC-validated).""" + p = 4 + while True: + h = data[p] + size = int.from_bytes(data[p + 1:p + 4], "big") + p += 4 + size + if h & 0x80: + break + syncs = [] + for i in range(p, len(data) - 1): + if data[i] == 0xFF and data[i + 1] == 0xF8: + syncs.append(i) + frames, start = [], syncs[0] + k = 1 + while start < len(data): + found = None + for e in syncs[k:] + [len(data)]: + if e > start and crc16(data[start:e - 2]) == int.from_bytes(data[e - 2:e], "big"): + found = e + break + frames.append((start, found)) + k = syncs.index(found) + 1 if found in syncs else len(syncs) + start = found + return p, frames + + +def make_varblock(): + """Frames of two encodes (block 4096 and 1152) spliced every 36864 samples, headers rewritten as variable.""" + ints = signal(2.0, 44100, 2, 16, "music", 4) + wav = os.path.join(TMP, "vb.wav") + write_wav(wav, ints, 2, 44100, 16) + enc = {} + for bs in (4096, 1152): + out = os.path.join(TMP, "vb%d.flac" % bs) + CTX.nix("flac", ["flac", "-s", "-f", "-5", "--no-seektable", "--no-padding", "-b", str(bs), wav, "-o", out]) + enc[bs] = open(out, "rb").read() + first, fa = frames_of(enc[4096]) + _, fb = frames_of(enc[1152]) + out = bytearray(enc[4096][:first]) + sample, use, maxf = 0, 4096, 0 + total = len(ints) // 2 + while sample < total: + frames = fa if use == 4096 else fb + fi = sample // use + for j in range(fi, min(fi + 36864 // use, len(frames))): + a, e = frames[j] + fr = enc[use][a:e] + # old header: 4 bytes, the coded frame number, optional fields; rebuild with the sample number + b0 = fr[4] + nl = 1 if b0 < 0x80 else (2 if b0 < 0xE0 else 3 if b0 < 0xF0 else 4 if b0 < 0xF8 else 5 if b0 < 0xFC else 6) + bscode = fr[2] >> 4 + extra = {6: 1, 7: 2}.get(bscode, 0) + {12: 1, 13: 2, 14: 2}.get(fr[2] & 15, 0) + hlen = 4 + nl + extra + hdr = bytes([0xFF, 0xF9]) + fr[2:4] + utf8num(sample + (j - fi) * use) + fr[4 + nl:hlen] + body = hdr + bytes([crc8(hdr)]) + fr[hlen + 1:-2] + body += crc16(body).to_bytes(2, "big") + out += body + maxf = max(maxf, len(body)) + sample = (fi + min(36864 // use, len(frames) - fi)) * use + use = 1152 if use == 4096 else 4096 + # STREAMINFO: min block 1152, max 4096, frame sizes unknown + out[8:10] = (1152).to_bytes(2, "big") + out[10:12] = (4096).to_bytes(2, "big") + out[12:18] = bytes(6) + path = os.path.join(TMP, "varblock.flac") + open(path, "wb").write(bytes(out)) + emit("varblock", path, 44100, 2, 16, "variable block size: 4096 / 1152 frames spliced, sample-number headers") + + +def ffmpeg(name, secs, rate, ch, bits, args, kind="music"): + wav = os.path.join(TMP, name + ".wav") + out = os.path.join(TMP, name + ".flac") + write_wav(wav, signal(secs, rate, ch, bits, kind, 5), ch, rate, bits) + CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + args + [out]) + emit(name, out, rate, ch, bits, "ffmpeg " + " ".join(args)) + + +def generate(ctx): + global CTX, TMP + CTX = ctx + TMP = tempfile.mkdtemp() + CASES.clear() + for lv in range(9): + flac("s16_l%d" % lv, 0.4, 44100, 2, 16, ["-%d" % lv]) + flac("s16_long", 3.0, 44100, 2, 16, ["-5", "-S", "0.5s"], seed=2, + note="flac -5, 3 s, seek points every 0.5 s (bench + seek)") + png = os.path.join(TMP, "p.png") + open(png, "wb").write(base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")) + flac("s16_noseek", 2.0, 44100, 2, 16, ["-6", "--no-seektable", "-T", "ARTIST=Some One", "-T", "TITLE=Test Tone", + "--picture", png], seed=3, + note="no seektable (bisection seek), tags, a picture", tags={"ARTIST": "Some One", "TITLE": "Test Tone"}) + flac("u8_mono", 0.5, 22050, 1, 8, ["-5"]) + flac("s24_96k", 0.3, 96000, 2, 24, ["-8"]) + flac("s24_l0", 0.3, 48000, 2, 24, ["-0"]) + flac("s32", 0.2, 48000, 2, 32, ["-5"]) + flac("s32_l8", 0.2, 48000, 2, 32, ["-8"], kind="noise", note="flac -8, 32-bit noise (verbatim / escapes)") + flac("ch6", 0.3, 48000, 6, 16, ["-5"]) + flac("ch3_24", 0.2, 44100, 3, 24, ["-7"]) + flac("rate37000", 0.4, 37000, 1, 16, ["-5"]) + flac("rate11025", 0.4, 11025, 2, 16, ["-3"]) + flac("rate352800", 0.05, 352800, 2, 24, ["-5", "--lax"]) + flac("rate100001", 0.1, 100001, 1, 16, ["-5", "--lax"], note="a rate only STREAMINFO can hold") + flac("rate7", 30.0, 7, 1, 16, ["-5", "--lax", "-b", "16"], note="7 Hz") + flac("bs17", 0.2, 44100, 1, 16, ["-5", "--lax", "-b", "17"]) + flac("bs4609", 0.5, 44100, 2, 16, ["-8", "--lax", "-b", "4609"]) + flac("bs65535", 1.6, 44100, 2, 16, ["-5", "--lax", "-b", "65535", "-r", "15"]) + flac("lpc32", 0.3, 44100, 2, 16, ["--lax", "-b", "1001", "-l", "32", "-r", "0,8", "-e", "-p"], + note="LPC order 32, block 1001, exhaustive") + flac("bits12", 0.3, 44100, 2, 12, ["-5"]) + flac("bits20", 0.3, 44100, 2, 20, ["-8"]) + flac("bits4", 0.3, 8000, 1, 4, ["-5", "--lax"]) + flac("wasted", 0.3, 44100, 2, 16, ["-5"], wasted=3, note="low 3 bits zero (wasted bits)") + flac("smooth", 0.3, 44100, 2, 24, ["-2"], kind="smooth", note="flac -2, 24-bit pure tones (fixed order 4)") + flac("s32_rice2", 0.2, 48000, 2, 32, ["-5"], kind="loudnoise", note="32-bit tone + noise (Rice2, k > 24)") + make_varblock() + flac("silence", 0.3, 44100, 2, 16, ["-5"], kind="silence") + flac("square", 0.3, 44100, 2, 16, ["-5"], kind="square") + flac("noise16", 0.3, 44100, 2, 16, ["-5"], kind="noise") + flac("ogg_s16", 1.0, 44100, 2, 16, ["-5", "--ogg"], ogg=True, note="Ogg FLAC") + for mode in ("left_side", "right_side", "mid_side", "indep"): + ffmpeg("ff_" + mode, 0.3, 44100, 2, 16, ["-c:a", "flac", "-ch_mode", mode]) + ffmpeg("ff_l12", 0.4, 44100, 2, 16, ["-c:a", "flac", "-compression_level", "12"]) + ffmpeg("ff_s24", 0.3, 48000, 2, 24, ["-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", + "-compression_level", "8"]) + ffmpeg("ff_exact", 0.3, 44100, 2, 16, ["-c:a", "flac", "-exact_rice_parameters", "1", "-multi_dim_quant", "1", + "-lpc_type", "cholesky", "-lpc_passes", "2"]) + # an ID3v2 tag in front of fLaC + src = os.path.join(TMP, "s16_l5.flac") + id3 = b"ID3\x04\x00\x00" + bytes([0, 0, 0, 20]) + b"TIT2\x00\x00\x00\x0a\x00\x00\x03hello id3" + emit("id3", src, 44100, 2, 16, "s16_l5 with an ID3v2 tag in front", prefix=id3) + + + ctx.emit("flac_cases", CASES) diff --git a/tools/fixtures/mp3.py b/tools/fixtures/mp3.py new file mode 100644 index 0000000..f69d502 --- /dev/null +++ b/tools/fixtures/mp3.py @@ -0,0 +1,75 @@ +# MP3 fixtures (tools/fixtures.py). Ported from mp3-luau tools/make_fixtures.sh + make_refs.py. +# tests/gen/mp3_cases.luau the committed streams in tests/fixtures/mp3/ (made by ffmpeg's libmp3lame / mp2 encoders +# from a synthetic test signal: tones, a chirp, noise, clicks) with their minimp3 reference +# decodes (*.ref, from the minimp3 C harness: see the format below), plus streams lame +# encodes here; each with ffmpeg's decode of three windows and its length. +# .ref layout (little-endian): "MP3REF1\0", u32 hz, channels, frames, window frames W, window count N, then +# N x (u32 start frame, W x channels f32), then u32 block size B, u32 block count, f64 sum of squares per block. +import math, os, random, struct, tempfile + +INPUTS = ["tests/fixtures/mp3"] +DIR = os.path.join("tests", "fixtures", "mp3") + + +def ffmpeg_windows(ctx, data, ch, starts, W): + with tempfile.TemporaryDirectory() as tmp: # a file, not a pipe: ffmpeg applies the LAME gapless info only when it can seek + path = os.path.join(tmp, "in.mp3") + with open(path, "wb") as f: + f.write(data) + out = ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(ch), "pipe:1"]) + frames = len(out) // (4 * ch) + wins = [] + for s in starts: + s = max(0, min(frames - W, s)) + wins.append({"start": s, "pcm": out[s * ch * 4:(s + W) * ch * 4]}) + return frames, wins + + +def ref_windows(ref): + hz, ch, frames, W, N = struct.unpack_from("<5I", ref, 8) + p, starts = 28, [] + for _ in range(N): + starts.append(struct.unpack_from("<I", ref, p)[0]) + p += 4 + W * ch * 4 + return ch, W, starts + + +def wav(rate, ch, secs, seed): + rnd = random.Random(seed) + fr = bytearray() + for i in range(int(secs * rate)): + t = i / rate + for c in range(ch): + v = 0.25 * math.sin(2 * math.pi * (330 * (c + 1) + 200 * t) * t) + 0.04 * (rnd.random() - 0.5) + if (i // 2000) % 7 == 3: + v += 0.3 * math.sin(2 * math.pi * 4000 * t) * (1 - (i % 2000) / 2000) + fr += struct.pack("<h", int(max(-1, min(1, v)) * 32767)) + hdr = b"RIFF" + struct.pack("<I", 36 + len(fr)) + b"WAVEfmt " + struct.pack("<IHHIIHH", 16, 1, ch, rate, rate * ch * 2, ch * 2, 16) + return hdr + b"data" + struct.pack("<I", len(fr)) + bytes(fr) + + +def generate(ctx): + cases = [] + for fn in sorted(os.listdir(os.path.join(ctx.root, DIR))): + if not fn.endswith((".mp3", ".mp2")): + continue + name = fn[:-4] + data = ctx.read(os.path.join(DIR, fn)) + ref = ctx.read(os.path.join(DIR, name + ".ref")) + ch, W, starts = ref_windows(ref) + frames, wins = ffmpeg_windows(ctx, data, ch, starts, W) + cases.append({"name": name, "data": data, "ref": ref, "ffFrames": frames, "ff": wins}) + # streams the lame CLI writes here (no minimp3 reference: ffmpeg only) + for name, rate, ch, args in (("lame_v5_st", 44100, 2, ["-V", "5"]), ("lame_cbr64_mono_22k", 22050, 1, ["-b", "64", "-m", "m"]), + ("lame_abr96_48k", 48000, 2, ["--abr", "96"])): + src = wav(rate, ch, 1.2, len(name)) + with tempfile.TemporaryDirectory() as tmp: # a file: lame writes the LAME (gapless) tag only when it can seek + path = os.path.join(tmp, "out.mp3") + ctx.nix("lame", ["lame", "--quiet", "--resample", str(rate / 1000)] + args + ["-", path], input=src) + with open(path, "rb") as f: + data = f.read() + W = 1152 + frames, wins = ffmpeg_windows(ctx, data, ch, [0, 20000, 10 ** 9], W) + cases.append({"name": name, "data": data, "ffFrames": frames, "ff": wins, "channels": ch, "rate": rate, + "srcFrames": int(1.2 * rate)}) + ctx.emit("mp3_cases", cases) diff --git a/tools/fixtures/ogg.py b/tools/fixtures/ogg.py new file mode 100644 index 0000000..3698da6 --- /dev/null +++ b/tools/fixtures/ogg.py @@ -0,0 +1,209 @@ +# Ogg fixtures (tools/fixtures.py): containers/Ogg. Ported from ogg-luau tools/gen_fixtures.py. +# tests/gen/ogg_cases.luau real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files +# (lacing edge cases, junk, a corrupt page copy, a lost page), each with the packet list +# from the small independent parser below: { size, crc32, granule, bos, eos } +import math, os, random, struct, tempfile, wave, zlib + +# --- CRC + writer ----------------------------------------------------------------------------------------- +def _crc_table(): + t = [] + for i in range(256): + r = i << 24 + for _ in range(8): + r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1) + r &= 0xFFFFFFFF + t.append(r) + return t + + +CRC = _crc_table() + + +def ogg_crc(data): + c = 0 + for x in data: + c = ((c << 8) & 0xFFFFFFFF) ^ CRC[(c >> 24) ^ x] + return c + + +def page(serial, seq, granule, flags, segs, data): + h = struct.pack("<4sBBqIIIB", b"OggS", 0, flags, granule, serial, seq, 0, len(segs)) + bytes(segs) + p = bytearray(h + data) + struct.pack_into("<I", p, 22, ogg_crc(p)) + return bytes(p) + + +def mux_stream(serial, packets, max_segs=255, granule_of=None): + """Pages for one stream; packets = list of (bytes, granule). Pages break after max_segs lacing values.""" + pages = [] + segs, data, seq, cont, gran = [], b"", 0, False, -1 + first = True + + def flush(eos=False, next_cont=False): + nonlocal segs, data, seq, cont, gran, first + flags = (1 if cont else 0) | (2 if first else 0) | (4 if eos else 0) + pages.append(page(serial, seq, gran, flags, segs, data)) + seq += 1 + first = False + segs, data, gran = [], b"", -1 + cont = next_cont + + for i, (pkt, g) in enumerate(packets): + n = len(pkt) + lac = [255] * (n // 255) + [n % 255] + pos = 0 + for j, l in enumerate(lac): + if len(segs) == max_segs: + flush(next_cont=j > 0) + segs.append(l) + data += pkt[pos:pos + l] + pos += l + gran = g + if i == 0 or (i % 7 == 3): # bos page holds only the first packet; break pages now and then + flush() + flush(eos=True) + return pages + + +# --- reference parser --------------------------------------------------------------------------------------- +def parse(data): + """{serial: [ (bytes, granule, bos, eos) ]} with resync + CRC check, like the library.""" + out, partial, order, seqs = {}, {}, [], {} + pos = 0 + while True: + i = data.find(b"OggS", pos) + if i < 0 or i + 27 > len(data): + break + nseg = data[i + 26] + segs = data[i + 27:i + 27 + nseg] + total = 27 + nseg + sum(segs) + if len(segs) < nseg or i + total > len(data): + pos = i + 1 + continue + p = bytearray(data[i:i + total]) + crc = struct.unpack_from("<I", p, 22)[0] + p[22:26] = b"\0\0\0\0" + if ogg_crc(p) != crc: + pos = i + 1 + continue + flags, gran, serial = p[5], struct.unpack_from("<q", p, 6)[0], struct.unpack_from("<I", p, 14)[0] + if serial not in out: + out[serial] = [] + order.append(serial) + partial[serial] = None + seq = struct.unpack_from("<I", p, 18)[0] + if serial in seqs and seq != seqs[serial] + 1: + partial[serial] = None + seqs[serial] = seq + body = 27 + nseg + last_complete = max([k for k, l in enumerate(segs) if l < 255], default=-1) + cur = partial[serial] if (flags & 1) else None + if not (flags & 1): + cur = None + skip = (flags & 1) and partial[serial] is None + first_on_page = True + for k, l in enumerate(segs): + chunk = bytes(p[body:body + l]) + body += l + if skip: + if l < 255: + skip = False + first_on_page = False + continue + cur = (cur or b"") + chunk + if l < 255: + last = k == last_complete + out[serial].append((cur, gran if last else -1, bool(flags & 2) and first_on_page, + bool(flags & 4) and last)) + first_on_page = False + cur = None + partial[serial] = cur + pos = i + total + return order, out + + +def codec(pkt): + if pkt.startswith(b"OpusHead"): + return "opus" + if pkt[:5] == b"\x7fFLAC": + return "flac" + if pkt[:7] == b"\x01vorbis": + return "vorbis" + return "unknown" + + + +def case(name, data, note): + order, streams = parse(data) + ss = [] + for s in order: + pk = streams[s] + gs = [g for _, g, _, _ in pk if g != -1] + ss.append({"serial": s, "codec": codec(pk[0][0]), "lastGranule": gs[-1] if gs else -1, + "packets": [[len(b), zlib.crc32(b), g, bos, eos] for b, g, bos, eos in pk]}) + return {"name": name, "note": note, "data": data, "streams": ss} + + +def tone_wav(path, secs, rate=48000, ch=2): + rnd = random.Random(1) + with wave.open(path, "wb") as w: + w.setnchannels(ch) + w.setsampwidth(2) + w.setframerate(rate) + fr = bytearray() + for i in range(int(secs * rate)): + t = i / rate + for c in range(ch): + v = 0.3 * math.sin(2 * math.pi * (220 * (c + 1) + 40 * math.sin(t)) * t) + 0.05 * (rnd.random() - 0.5) + fr += struct.pack("<h", int(v * 32767)) + w.writeframes(bytes(fr)) + + + +def generate(ctx): + tmp = tempfile.mkdtemp() + cases = [] + wav = os.path.join(tmp, "a.wav") + tone_wav(wav, 12) + opus = os.path.join(tmp, "a.opus") + ctx.nix("opus-tools", ["opusenc", "--quiet", "--bitrate", "48", wav, opus]) + cases.append(case("opus_stereo", open(opus, "rb").read(), "opusenc 48 kb/s, 12 s stereo")) + wav2 = os.path.join(tmp, "b.wav") + tone_wav(wav2, 1.5, 44100, 1) + oflac = os.path.join(tmp, "b.oga") + ctx.nix("flac", ["flac", "-s", "--ogg", "-5", "-o", oflac, wav2]) + cases.append(case("flac_ogg", open(oflac, "rb").read(), "flac --ogg -5, 1.5 s mono")) + vorb = os.path.join(tmp, "c.ogg") + ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav2, "-ac", "2", "-c:a", "vorbis", "-strict", "-2", vorb]) + cases.append(case("vorbis_ffmpeg", open(vorb, "rb").read(), "ffmpeg native vorbis, 1.5 s stereo")) + + # two interleaved streams, lacing edge cases, junk, a corrupt page, a dropped page + rnd = random.Random(7) + sizes = [0, 1, 254, 255, 256, 509, 510, 511, 765, 4000, 70000, 0, 0, 3, 65025, 255 * 255 + 1] + a = [(b"OpusHead" + bytes(11), 0)] + [(bytes(rnd.randrange(256) for _ in range(n)), 100 * (i + 1)) + for i, n in enumerate(sizes)] + b = [(b"\x7fFLAC" + bytes(40), 0)] + [(bytes(rnd.randrange(256) for _ in range(rnd.randrange(1, 900))), 50 * (i + 1)) + for i in range(60)] + pa = mux_stream(0x1234ABCD, a, max_segs=255) + pb = mux_stream(7, b, max_segs=17) + out = pa[:1] + pb[:1] # bos pages first + ra, rb = pa[1:], pb[1:] + while ra or rb: + if rb and (not ra or rnd.random() < 0.5): + out.append(rb.pop(0)) + else: + out.append(ra.pop(0)) + blob = bytearray() + for k, pg in enumerate(out): + if k == 5: + blob += b"junkOggSjunk" + bytes(40) + if k == 9: # a corrupt copy before the real page + bad = bytearray(pg) + bad[len(bad) // 2] ^= 0xFF + blob += bad + blob += pg + blob += b"OggS\0trailing-truncated" + cases.append(case("mux_edge", bytes(blob), "2 streams, lacing edges, junk, a corrupt page copy, truncated tail")) + lost = [pg for pg in out if not (struct.unpack_from("<I", pg, 14)[0] == 7 and struct.unpack_from("<I", pg, 18)[0] == 5)] + cases.append(case("mux_lost", b"".join(lost), "mux_edge without page 5 of serial 7")) + ctx.emit("ogg_cases", cases) diff --git a/tools/fixtures/opus.py b/tools/fixtures/opus.py new file mode 100644 index 0000000..a442852 --- /dev/null +++ b/tools/fixtures/opus.py @@ -0,0 +1,66 @@ +# Opus fixtures (tools/fixtures.py): audio/opus. Ported from opus-luau tools/fixtures.sh. +# tests/gen/opus_<name>.luau { name, data = the .opus file, ref = opusdec --float output (f32 LE interleaved) } +# Sources: 48 kHz signals synthesised by ffmpeg (aevalsrc: tones, vibrato, chirps, noise bursts, clicks, a speech-like +# harmonic source with moving formants), encoded by opusenc (CELT-only frame sizes / bitrates, forced SILK NB / MB / +# WB, hybrid SWB / FB, a 5.1 mapping-family-1 stream, a long tagged file) and ffmpeg libopus (CBR, voip, lowdelay). +import os, tempfile + +MUSIC = ("0.25*sin(2*PI*(220+30*sin(2*PI*5*t))*t)+0.15*sin(2*PI*(100*t+700*t*t))+0.3*exp(-25*mod(t,0.375))*(random(0)-0.5)" + "+0.4*lt(mod(t,0.5),0.0006)") +MUSIC2 = ("0.2*sin(2*PI*330*t)+0.1*sin(2*PI*1320*t)*lt(mod(t,0.25),0.125)+0.25*exp(-40*mod(t+0.1,0.375))*(random(1)-0.5)" + "+0.12*sin(2*PI*(3000-2500*t/3)*t)") +F0 = "(120+40*sin(2*PI*0.7*t))" +FM = "(600+300*sin(2*PI*1.3*t))" +SPEECH = ("(0.5+0.5*sin(2*PI*2.1*t))*(sin(2*PI*{f0}*t)*0.3+sin(2*PI*2*{f0}*t)*0.25+sin(2*PI*3*{f0}*t)*0.2*exp(-abs(3*{f0}-{fm})/400)" + "+sin(2*PI*5*{f0}*t)*0.15*exp(-abs(5*{f0}-{fm}*2)/400)+sin(2*PI*8*{f0}*t)*0.08+0.02*(random(2)-0.5))").format(f0=F0, fm=FM) +SOURCES = { + "music": (MUSIC + "|" + MUSIC2, 3), + "mono": (MUSIC + "+0.5*" + SPEECH, 3), + "speech": (SPEECH, 3), + "speechst": (SPEECH + "|0.7*" + SPEECH + "+0.1*sin(2*PI*440*t)", 3), + "mixst": (MUSIC + "+" + SPEECH + "|" + MUSIC2 + "+0.6*" + SPEECH, 3), + "surround": (MUSIC + "|" + MUSIC2 + "|" + SPEECH + "|0.3*sin(2*PI*55*t)|0.5*" + MUSIC2 + "|0.5*" + MUSIC, 2), + "long": (MUSIC + "+0.3*" + SPEECH + "|" + MUSIC2 + "+0.3*" + SPEECH, 12), +} +# name, source, encoder ("enc" = opusenc, "ff" = ffmpeg libopus), arguments +CASES = [ + ("celt_st_128", "music", "enc", ["--music", "--bitrate", "128"]), + ("celt_st_32", "music", "enc", ["--music", "--bitrate", "32"]), + ("celt_st_64", "mixst", "enc", ["--music", "--bitrate", "64"]), + ("celt_st_256", "music", "enc", ["--music", "--bitrate", "256"]), + ("celt_mono_64", "mono", "enc", ["--music", "--bitrate", "64"]), + ("celt_fs2_5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "2.5"]), + ("celt_fs5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "5"]), + ("celt_fs10", "mixst", "enc", ["--music", "--bitrate", "96", "--framesize", "10"]), + ("celt_fs40", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "40"]), + ("celt_fs60", "mixst", "enc", ["--music", "--bitrate", "160", "--framesize", "60"]), + ("silk_nb", "speech", "enc", ["--speech", "--bitrate", "8", "--max-delay", "0"]), + ("silk_mb", "speech", "enc", ["--speech", "--bitrate", "12", "--set-ctl-int", "4008=1102"]), + ("silk_wb", "speech", "enc", ["--speech", "--bitrate", "20", "--framesize", "40", "--set-ctl-int", "4008=1103"]), + ("silk_wb_st", "speechst", "enc", ["--speech", "--bitrate", "28", "--framesize", "60", "--set-ctl-int", "4008=1103"]), + ("silk_nb_st", "speechst", "enc", ["--speech", "--bitrate", "12", "--framesize", "10", "--set-ctl-int", "4008=1101"]), + ("hybrid_swb", "speech", "enc", ["--speech", "--bitrate", "24"]), + ("hybrid_fb", "speech", "enc", ["--speech", "--bitrate", "36", "--framesize", "10"]), + ("hybrid_st", "speechst", "enc", ["--speech", "--bitrate", "40"]), + ("mix_st_24", "mixst", "enc", ["--bitrate", "24"]), + ("surround51", "surround", "enc", ["--bitrate", "192"]), + ("long_128", "long", "enc", ["--bitrate", "128", "--comment", "TITLE=Long Test", "--artist", "opus-luau"]), + ("ff_cbr", "mixst", "ff", ["-b:a", "96k", "-vbr", "off"]), + ("ff_voip", "speechst", "ff", ["-b:a", "32k", "-application", "voip"]), + ("ff_lowdelay", "music", "ff", ["-b:a", "128k", "-application", "lowdelay", "-frame_duration", "5"]), +] + + +def generate(ctx): + tmp = tempfile.mkdtemp() + for name, (expr, secs) in SOURCES.items(): + ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='%s':s=48000:d=%d" % (expr, secs), + "-c:a", "pcm_s16le", os.path.join(tmp, name + ".wav")]) + for name, src, enc, args in CASES: + wav, opus, ref = (os.path.join(tmp, x) for x in (src + ".wav", name + ".opus", name + ".f32")) + if enc == "enc": + ctx.nix("opus-tools", ["opusenc", "--quiet"] + args + [wav, opus]) + else: + ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-i", wav, "-c:a", "libopus"] + args + [opus]) + ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", opus, ref]) + ctx.emit("opus_" + name, {"name": name, "data": open(opus, "rb").read(), "ref": open(ref, "rb").read()}) diff --git a/tools/fixtures/playlist.py b/tools/fixtures/playlist.py new file mode 100644 index 0000000..4af9918 --- /dev/null +++ b/tools/fixtures/playlist.py @@ -0,0 +1,66 @@ +# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/Url, codecs/Text. +# tests/gen/playlist_url.luau random relative references resolved by Python's urllib.parse.urljoin (RFC 3986) +# tests/gen/playlist_cp1252.luau every Windows-1252 byte decoded by Python's cp1252 codec (undefined bytes: U+FFFD) +# tests/gen/playlist_cases.luau playlists written here (M3U8 with EXTINF, PLS via configparser-style lines, XSPF via +# xml.etree.ElementTree) with the entries they hold: { url, title?, duration? } +import random, urllib.parse, xml.etree.ElementTree as ET + +BASES = ["http://a/b/c/d;p?q", "https://host.example/lists/m.m3u8", "http://h/x/", "https://cdn.example/a/b/c/list.pls", + "http://a"] +SEGS = ["g", "h", "..", ".", "music", "a b", "x.mp3", "s;p", "%41", "ü"] + + +def ref(rng): + parts = [rng.choice(SEGS) for _ in range(rng.randrange(1, 5))] + r = "/".join(parts) + k = rng.randrange(6) + if k == 0: + r = "/" + r + elif k == 1: + r = "./" + r + if rng.random() < 0.2: + r += "?y=" + rng.choice(SEGS) + if rng.random() < 0.15: + r += "#" + rng.choice(["s", "f/../x"]) + return r + + +def generate(ctx): + rng = random.Random(8) + cases = [] + for _ in range(400): + base = rng.choice(BASES) + r = ref(rng) + if " " in r or "ü" in r or (base == "http://a" and r.startswith(".")): + continue # raw spaces / UTF-8 are encoded first by the playlist code; urljoin keeps a leading "." here + cases.append([r, base, urllib.parse.urljoin(base, r)]) + ctx.emit("playlist_url", cases) + ctx.emit("playlist_cp1252", [[b, bytes([b]).decode("cp1252", errors="replace")] for b in range(0x80, 0x100)]) + + out = [] + for n in range(12): + ents = [] + for i in range(rng.randrange(1, 9)): + e = {"url": "http://media.example/%d/track%d.mp3" % (n, i)} + if rng.random() < 0.8: + e["title"] = rng.choice(["Song %d" % i, "Björk – Jóga", "A, B & C", "x <y> \"z\""]) + if rng.random() < 0.7: + e["duration"] = rng.randrange(1, 600) + ents.append(e) + m3u = "#EXTM3U\n" + "".join(("#EXTINF:%d,%s\n" % (e.get("duration", -1), e.get("title", "")) if ("title" in e or "duration" in e) else "") + e["url"] + "\n" for e in ents) + pls = "[playlist]\n" + "".join("File%d=%s\n" % (i + 1, e["url"]) + ("Title%d=%s\n" % (i + 1, e["title"]) if "title" in e else "") + ("Length%d=%d\n" % (i + 1, e.get("duration", -1))) for i, e in enumerate(ents)) + "NumberOfEntries=%d\nVersion=2\n" % len(ents) + root = ET.Element("playlist", {"version": "1", "xmlns": "http://xspf.org/ns/0/"}) + ET.SubElement(root, "title").text = "List %d" % n + tl = ET.SubElement(root, "trackList") + for e in ents: + t = ET.SubElement(tl, "track") + ET.SubElement(t, "location").text = e["url"] + if "title" in e: + ET.SubElement(t, "title").text = e["title"] + if "duration" in e: + ET.SubElement(t, "duration").text = str(e["duration"] * 1000) + xspf = ET.tostring(root, encoding="UTF-8", xml_declaration=True) + expect = [{k: v for k, v in e.items()} for e in ents] + # M3U loses a title when there is no EXTINF text; PLS keeps only what it wrote + out.append({"name": "list%d" % n, "m3u": m3u, "pls": pls, "xspf": xspf, "title": "List %d" % n, "entries": expect}) + ctx.emit("playlist_cases", out) diff --git a/tools/fixtures/wav.py b/tools/fixtures/wav.py new file mode 100644 index 0000000..8f8281a --- /dev/null +++ b/tools/fixtures/wav.py @@ -0,0 +1,199 @@ +# WAV fixtures (tools/fixtures.py): audio/wav. Ported from wav-luau tools/mkfixtures.py. +# tests/gen/wav_cases.luau a short synthetic stereo signal in every supported format and container (ffmpeg / sox), +# plus hand-patched variants (data size 0 / 0xFFFFFFFF, truncation, odd chunks with and +# without the pad byte, tags after the data), with ffmpeg's (or sox's) f32le decode +# tests/gen/wav_enc.luau encoder references: random samples at each depth, written by ffmpeg with -bitexact +# (PCM u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64); our encoder must +# produce the same bytes +import os, random, struct, tempfile + +CTX = None + + +def build_cases(): + work = tempfile.mkdtemp() + RATE, DUR = 16000, 0.2 + SRC = "aevalsrc=0.6*sin(2*PI*440*t)+0.25*sin(2*PI*3100*t*t*10)|0.5*sin(2*PI*660*t)+0.2*(random(1)*2-1):s=%d:d=%g" % (RATE, DUR) + + def run(*args): + CTX.nix(["ffmpeg", "sox"], list(args)) + + def path(n): + return os.path.join(work, n) + + def ffenc(name, *args, ac=2): + run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", str(ac), *args, path(name)) + return path(name) + + def ref(p): + return CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", p, "-f", "f32le", "-c:a", "pcm_f32le", "-"]) + + def soxref(p): + # ffmpeg cannot read every RIFX file: sox decodes those (through its 32-bit integer pipeline) + return CTX.nix("sox", ["sox", p, "-t", "raw", "-e", "floating-point", "-b", "32", "-L", "-"]) + + def chunks(d): + be = d[:4] == b"RIFX" + p, out = 12, [] + while p + 8 <= len(d): + cid = d[p:p + 4] + size = struct.unpack_from(">I" if be else "<I", d, p + 4)[0] + out.append((cid, p, size)) + if size == 0xFFFFFFFF: + break + p += 8 + size + (size & 1) + return out + + def find(d, cid): + for c, p, s in chunks(d): + if c == cid: + return p, s + raise KeyError(cid) + + entries = [] + + def add(name, data, refdata, channels, fmt, container="RIFF", tags=None): + frames = len(refdata) // (4 * channels) + # ADPCM: ffmpeg decodes the padding of the last block too; the fact chunk holds the true length + if b"fact" in data[:200]: + fp, _ = find(data, b"fact") + frames = min(frames, struct.unpack_from("<I", data, fp + 8)[0]) + entries.append(dict(name=name, file=data, ref=refdata, channels=channels, rate=RATE, frames=frames, + format=fmt, container=container, tags=tags)) + + def plain(name, fmt, *args, ac=2, tags=None): + p = ffenc(name + ".wav", *args, ac=ac) + d = open(p, "rb").read() + add(name, d, ref(p), ac, fmt, tags=tags) + return p, d + + # formats + plain("u8", "pcm", "-c:a", "pcm_u8") + p16, d16 = plain("s16", "pcm", "-c:a", "pcm_s16le") + plain("s16_mono_tags", "pcm", "-c:a", "pcm_s16le", "-metadata", "title=Hello Title", "-metadata", "artist=Some Artist", + "-metadata", "album=An Album", "-metadata", "genre=Test", ac=1, + tags={"title": "Hello Title", "artist": "Some Artist", "album": "An Album", "genre": "Test"}) + plain("s24_ext", "pcm", "-c:a", "pcm_s24le") + plain("s32_ext", "pcm", "-c:a", "pcm_s32le") + plain("f32", "float", "-c:a", "pcm_f32le") + plain("f64", "float", "-c:a", "pcm_f64le") + plain("alaw", "alaw", "-c:a", "pcm_alaw") + plain("mulaw_mono", "mulaw", "-c:a", "pcm_mulaw", ac=1) + plain("ima", "ima_adpcm", "-c:a", "adpcm_ima_wav") + plain("ima_mono", "ima_adpcm", "-c:a", "adpcm_ima_wav", ac=1) + plain("ms", "ms_adpcm", "-c:a", "adpcm_ms") + plain("ms_mono", "ms_adpcm", "-c:a", "adpcm_ms", ac=1) + plain("s16_6ch_ext", "pcm", "-c:a", "pcm_s16le", ac=6) + + # containers + p = ffenc("rf64.wav", "-c:a", "pcm_s16le", "-rf64", "always") + add("rf64", open(p, "rb").read(), ref(p), 2, "pcm", container="RF64") + for name, args in (("rifx_s16", ["-b", "16"]), ("rifx_s24", ["-b", "24"]), ("rifx_f32", ["-e", "floating-point", "-b", "32"])): + p = path(name + ".wav") + run("sox", path("s24_ext.wav"), "-B", *args, p) + add(name, open(p, "rb").read(), soxref(p), 2, "float" if "f32" in name else "pcm", container="RIFX") + + # streamed output: data size 0xFFFFFFFF + p = path("pipe.wav") + with open(p, "wb") as f: + f.write(CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-f", "lavfi", "-i", SRC, "-c:a", "pcm_s16le", "-f", "wav", "pipe:1"])) + d = open(p, "rb").read() + assert find(d, b"data")[1] == 0xFFFFFFFF + add("streamed_ffffffff", d, ref(p16), 2, "pcm") + + # data size 0 + r16 = ref(p16) + dp, _ = find(d16, b"data") + d = bytearray(d16) + struct.pack_into("<I", d, dp + 4, 0) + add("datasize_0", bytes(d), r16, 2, "pcm") + + # truncated mid-frame: 1000 whole frames + 3 bytes + add("truncated_s16", d16[:dp + 8 + 1000 * 4 + 3], r16[:1000 * 2 * 4], 2, "pcm") + + # truncated IMA ADPCM: one whole block, then a partial block with its headers + 3 whole groups + 5 bytes + pima = path("ima.wav") + dima = open(pima, "rb").read() + fp, _ = find(dima, b"fmt ") + ba = struct.unpack_from("<H", dima, fp + 8 + 12)[0] + spb = (ba - 8) * 2 // 2 + 1 + dp, _ = find(dima, b"data") + cut = dp + 8 + ba + 8 + 3 * 8 + 5 + frames = spb + 1 + 3 * 8 + rima = ref(pima) + assert len(rima) >= frames * 8 + add("truncated_ima", dima[:cut], rima[:frames * 2 * 4], 2, "ima_adpcm") + + # odd-sized chunks before the data, padded and unpadded + fp, fs = find(d16, b"fmt ") + head, rest = d16[:fp + 8 + fs], d16[fp + 8 + fs:] + def riff(body): + return b"RIFF" + struct.pack("<I", len(body) + 4) + b"WAVE" + body + odd_padded = riff(head[12:] + b"junk" + struct.pack("<I", 3) + b"abc\0" + rest) + add("odd_chunk_padded", odd_padded, r16, 2, "pcm") + odd_unpadded = riff(head[12:] + b"abcd" + struct.pack("<I", 5) + b"12345" + rest) + add("odd_chunk_unpadded", odd_unpadded, r16, 2, "pcm") + + # 8-bit mono, odd frame count (odd data size, pad byte), LIST/INFO after the data + p = path("u8odd.wav") + run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", "1", "-af", "atrim=end_sample=3199", + "-c:a", "pcm_u8", "-map_metadata", "-1", "-fflags", "+bitexact", p) + d = open(p, "rb").read() + dp, ds = find(d, b"data") + assert ds % 2 == 1, ds + info = b"INFO" + b"INAM" + struct.pack("<I", 5) + b"Odd!\0\0" + b"IART" + struct.pack("<I", 4) + b"Me\0\0" + body = d[12:dp + 8 + ds] + b"\0" + b"LIST" + struct.pack("<I", len(info)) + info + add("u8_odd_list_after", riff(body), ref(p), 1, "pcm", tags={"title": "Odd!", "artist": "Me"}) + + + return entries + + +def raw_samples(rng, kind, n): + """n random samples as (raw little-endian bytes, the same values as f32 little-endian)""" + raw, f32 = bytearray(), bytearray() + for i in range(n): + if kind == "u8": + v = rng.randrange(256); raw.append(v); x = (v - 128) / 128 + elif kind == "s16": + v = rng.randrange(-32768, 32768); raw += struct.pack("<h", v); x = v / 32768 + elif kind == "s24": + v = rng.randrange(-8388608, 8388608); raw += struct.pack("<i", v)[:3]; x = v / 8388608 + elif kind == "s32": + v = rng.randrange(-8388608, 8388608) * 256; raw += struct.pack("<i", v); x = v / 2147483648 + else: + x = struct.unpack("<f", struct.pack("<f", rng.uniform(-1, 1)))[0]; raw += struct.pack("<f", x) + f32 += struct.pack("<f", x) + if kind in ("s16", "s24", "s32", "u8"): + # the extremes too + pass + return bytes(raw), bytes(f32) + + +FF = {"u8": ("u8", "pcm_u8"), "s16": ("s16le", "pcm_s16le"), "s24": ("s24le", "pcm_s24le"), "s32": ("s32le", "pcm_s32le"), + "f32": ("f32le", "pcm_f32le")} + + +def generate(ctx): + global CTX + CTX = ctx + ctx.emit("wav_cases", [{k: v for k, v in e.items() if v is not None} for e in build_cases()]) + rng = random.Random(3) + tmp = tempfile.mkdtemp() + enc = [] + for kind, ch, rate, frames, extra in (("s16", 2, 44100, 1001, []), ("s24", 2, 44100, 777, []), ("s32", 2, 44100, 500, []), + ("f32", 2, 44100, 640, []), ("u8", 1, 8000, 999, []), ("s16", 6, 48000, 300, []), + ("f32", 6, 8000, 120, []), ("s16", 1, 96000, 256, []), ("s16", 3, 8000, 50, []), + ("s16", 4, 8000, 50, []), ("s16", 5, 8000, 50, []), ("s16", 7, 8000, 50, []), + ("s16", 8, 8000, 50, []), ("s24", 1, 22050, 333, []), + ("s16", 2, 44100, 441, ["-rf64", "always"]), ("f32", 1, 44100, 100, ["-rf64", "always"])): + raw, f32 = raw_samples(rng, kind, frames * ch) + src = os.path.join(tmp, "in.raw") + open(src, "wb").write(raw) + out = os.path.join(tmp, "out.wav") + fmt, codec = FF[kind] + ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-f", fmt, "-ar", str(rate), "-ac", str(ch), "-i", src, + "-c:a", codec] + extra + ["-fflags", "+bitexact", "-flags:a", "+bitexact", "-map_metadata", "-1", out]) + enc.append({"name": "%s-%dch-%d%s" % (kind, ch, rate, "-rf64" if extra else ""), "kind": kind, "channels": ch, + "rate": rate, "frames": frames, "rf64": bool(extra), "samples": f32, "file": open(out, "rb").read()}) + ctx.emit("wav_enc", enc) diff --git a/tools/fixtures/zip.py b/tools/fixtures/zip.py new file mode 100644 index 0000000..3a66642 --- /dev/null +++ b/tools/fixtures/zip.py @@ -0,0 +1,161 @@ +# ZIP fixtures (tools/fixtures.py): containers/Zip + archive/zip. Ported from zip-luau tools/fixtures.py. +# tests/gen/zip_cases.luau generated archives with Python zipfile's view of every entry ({ name, size, crc, method }): +# stored and deflate entries, an archive comment holding a fake end record, data descriptors, +# force_zip64, a hand-built all-ZIP64 archive, 66000 entries (ZIP64 end record), a prefix +# stub, a wrong local extra length, unicode names, empty; plus every .wsz skin in $SKINS_DIR +# when it is set (the Webamp demo skins; not redistributable, so not committed). Archives +# over 1 MB are stored zlib-compressed (dataZ) +import io, os, random, struct, sys, zipfile, zlib + +SKINS = os.environ.get("SKINS_DIR", "") +TEXT = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % i for i in range(3000)) + + +class Unseekable(io.RawIOBase): + def __init__(self): + self.buf = bytearray() + def writable(self): + return True + def write(self, b): + self.buf += b + return len(b) + +def mk(files, comment=b"", stream=False, force64=False): + out = Unseekable() if stream else io.BytesIO() + with zipfile.ZipFile(out, "w") as z: + for name, data, method in files: + zi = zipfile.ZipInfo(name, (2020, 5, 17, 13, 37, 42)) + zi.compress_type = method + if force64: + with z.open(zi, "w", force_zip64=True) as f: + f.write(data) + else: + z.writestr(zi, data) + z.comment = comment + return bytes(out.buf if stream else out.getvalue()) + +def zip64_by_hand(files): + # every size / offset field is 0xFFFFFFFF with the values in ZIP64 extras, plus the ZIP64 end record + locator + local, cd = bytearray(), bytearray() + for name, data in files: + n = name.encode() + c = zlib.compressobj(9, zlib.DEFLATED, -15) + comp = c.compress(data) + c.flush() + crc = zlib.crc32(data) + off = len(local) + lx = struct.pack("<HHQQ", 1, 16, len(data), len(comp)) + local += struct.pack("<IHHHHHIIIHH", 0x04034b50, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(lx)) + n + lx + comp + cx = struct.pack("<HHQQQ", 1, 24, len(data), len(comp), off) + cd += struct.pack("<IHHHHHHIIIHHHHHII", 0x02014b50, 45, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(cx), 0, 0, 0, 0, 0xFFFFFFFF) + n + cx + cdoff = len(local) + z64 = len(local) + len(cd) + rec = struct.pack("<IQHHIIQQQQ", 0x06064b50, 44, 45, 45, 0, 0, len(files), len(files), len(cd), cdoff) + loc = struct.pack("<IIQI", 0x07064b50, 0, z64, 1) + eocd = struct.pack("<IHHHHIIH", 0x06054b50, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0) + return bytes(local + cd + rec + loc + eocd) + + +def entries(data, limit=None): + z = zipfile.ZipFile(io.BytesIO(data)) + return len(z.infolist()), [[i.filename, i.file_size, i.CRC, i.compress_type] for i in z.infolist()[:limit]] + + +def generate(ctx): + S, D = zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED + rng = random.Random(3) + TEXT = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % i for i in range(3000)) + + class Unseekable(io.RawIOBase): + def __init__(self): + self.buf = bytearray() + def writable(self): + return True + def write(self, b): + self.buf += b + return len(b) + + def mk(files, comment=b"", stream=False, force64=False): + out = Unseekable() if stream else io.BytesIO() + with zipfile.ZipFile(out, "w") as z: + for name, data, method in files: + zi = zipfile.ZipInfo(name, (2020, 5, 17, 13, 37, 42)) + zi.compress_type = method + if force64: + with z.open(zi, "w", force_zip64=True) as f: + f.write(data) + else: + z.writestr(zi, data) + z.comment = comment + return bytes(out.buf if stream else out.getvalue()) + + def zip64_by_hand(files): + # every size / offset field is 0xFFFFFFFF with the values in ZIP64 extras, plus the ZIP64 end record + locator + local, cd = bytearray(), bytearray() + for name, data in files: + n = name.encode() + c = zlib.compressobj(9, zlib.DEFLATED, -15) + comp = c.compress(data) + c.flush() + crc = zlib.crc32(data) + off = len(local) + lx = struct.pack("<HHQQ", 1, 16, len(data), len(comp)) + local += struct.pack("<IHHHHHIIIHH", 0x04034b50, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(lx)) + n + lx + comp + cx = struct.pack("<HHQQQ", 1, 24, len(data), len(comp), off) + cd += struct.pack("<IHHHHHHIIIHHHHHII", 0x02014b50, 45, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(cx), 0, 0, 0, 0, 0xFFFFFFFF) + n + cx + cdoff = len(local) + z64 = len(local) + len(cd) + rec = struct.pack("<IQHHIIQQQQ", 0x06064b50, 44, 45, 45, 0, 0, len(files), len(files), len(cd), cdoff) + loc = struct.pack("<IIQI", 0x07064b50, 0, z64, 1) + eocd = struct.pack("<IHHHHIIH", 0x06054b50, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0) + return bytes(local + cd + rec + loc + eocd) + + S, D = zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED + basic = [ + ("readme.txt", TEXT, D), + ("Skin/Main.BMP", rng.randbytes(5000) + bytes(20000), D), + ("Skin/stored.bin", rng.randbytes(3000), S), + ("Skin/", b"", S), + ("Skin/sub/deep.txt", b"deep", D), + ("empty.txt", b"", D), + ("__MACOSX/Skin/._Main.BMP", b"\0\5\x16\7junk", S), + ("Skïn/ünicode.txt", "héllo".encode(), D), + ] + archives = [] # (label, bytes, expect: list of (name, size, crc) or None for "parse with zipfile") + REF = {} # label -> the archive zipfile reads for the expected listing (when zipfile cannot read the real one) + def add(label, data, ref=None): + archives.append((label, data)) + if ref is not None: + REF[label] = ref + + add("basic", mk(basic)) + # zipfile itself takes the fake end record in this comment (it searches for the last signature) + add("comment", mk(basic[:3], comment=b"a comment with a fake end record PK\x05\x06" + b"\0" * 18 + b" and more" * 100), mk(basic[:3])) + add("descriptors", mk(basic[:6], stream=True)) + add("force_zip64", mk(basic[:6], force64=True)) + add("zip64_by_hand", zip64_by_hand([("a.txt", TEXT), ("b/c.bin", rng.randbytes(4000)), ("z.txt", b"")])) + add("prefixed", b"MZ" + b"\x90" * 3000 + mk(basic[:3])) + add("empty", mk([])) + w = bytearray(mk([("x.txt", TEXT, D), ("y.txt", b"why" * 1000, S)])) + struct.pack_into("<H", w, 28, 7) # first local header: wrong extra length (the central directory has 0) + add("wrong_local_extra", bytes(w), mk([("x.txt", TEXT, D), ("y.txt", b"why" * 1000, S)])) + many = mk([("d/%05d.txt" % i, b"%d" % i, S) for i in range(66000)]) + add("many", many) + + skins = [] + if os.path.isdir(SKINS): + for name in sorted(os.listdir(SKINS)): + if name.lower().endswith(".wsz"): + with open(os.path.join(SKINS, name), "rb") as f: + skins.append((name, f.read())) + + + out = {"archives": [], "skins": []} + for key, group in (("archives", archives), ("skins", skins)): + for label, data in group: + count, ents = entries(REF.get(label, data), 200 if label == "many" else None) + c = {"name": label, "count": count, "entries": ents} + if len(data) > 1000000: + c["dataZ"] = zlib.compress(data, 9) # big archives (66000 entries): zlib, inflated by the test + else: + c["data"] = data + out[key].append(c) + ctx.emit("zip_cases", out)