diff --git a/README.md b/README.md index 0fcb581..b2500f1 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ local tune = F.music.load(modBytes) -- MOD / S3M / XM / IT / MIDI `F.load`, `F.open`, `F.save`, `F.saveString`, `F.convert`, `F.detect`, `F.formats`, `F.format(name)`; the category facades `F.image`, `F.audio`, `F.video`, `F.model`, `F.cad`, `F.font`, `F.archive`, `F.data`, `F.vector`, `F.layered`, `F.subtitle`, `F.music`, `F.playlist`; editing in `F.ops.image`, `F.ops.mesh`, `F.ops.layers`, -`F.ops.audio`, `F.ops.vector.rasterize`; `F.host`, `F.plugins`, `F.Err`, `F.Types`. Options and the hooks the api +`F.ops.audio`, `F.ops.music` (also `F.music.new` / `addPattern` / `setCell` / ...), `F.ops.vector.rasterize`; `F.host`, `F.plugins`, `F.Err`, `F.Types`. Options and the hooks the api hands to formats (decodeImage / encodeImage / openAudio / plugins): [docs/API.md](docs/API.md). ## Host notes diff --git a/docs/API.md b/docs/API.md index 7c2318a..7077b3d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -12,6 +12,8 @@ string is a path only when `opts.path = true` or when it does not look like file `opts.data = true` to force bytes. Roblox and the luau CLI have no file system: pass buffers or strings. `F.save(value, dest?, opts?)` returns a `buffer`, or writes the file `dest` (extension = format) and returns `true`. +Formats that write extra files (`caps.extraFiles`: BMFont pages) put them next to `dest`; without a destination they +come back as a third value `{ [file name] = buffer }` (or in the caller's `opts.files` table). ## Loading and saving @@ -19,16 +21,22 @@ string is a path only when `opts.path = true` or when it does not look like file |---|---| | `F.load(src, opts?)` | the category's standard value (`Image`, `Audio`, `Scene`, `Font`, `Archive`, `Vector`, `Layered`, `Subtitles`, `Module` / `Midi`, `Playlist`, data values, a `VideoDecoder`) | | `F.open(src, opts?)` | a streaming decoder: audio `Decoder`, `VideoDecoder`, or a container `Demuxer` | -| `F.save(value, dest?, opts?)` | `buffer` / `true` | +| `F.save(value, dest?, opts?)` | `buffer` / `true` (+ the extra files, see above) | | `F.saveString(value, opts?)` | the encoded bytes as a string | | `F.convert(src, format, opts?)` | load + save (`opts` go to both; `opts.out = path` writes a file) | -| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension) | +| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension); a format's optional `variant(r)` can name the flavour (`"webm"` for a WebM file read by mkv) | | `F.formats(category?)` | `{ { name, category, extensions, mime, caps } }` without loading any format (also [FORMATS.md](FORMATS.md)) | | `F.format(name)` | the format module itself (`sniff` / `decode` / `encode` / `open` and extras such as `png.info`) | Common options: `format` (a name or extension: what to decode as / encode to; without it, saving uses the source format), `category`, `name` (a file name hint for detection), `path` / `data`, size limits (`maxPixels`, `maxBytes`, `maxFrames`, ...), and each format's own options (documented in its `init.luau`: `level`, `quality`, `bitrate`, ...). +`bitrate` is in bits per second for every encoder (values below 1000 are read as kbit/s). + +Across categories: a Module or Midi saved to an audio format is rendered first (render options in `opts`: +`F.convert(modBytes, "wav", { sampleRate = 22050 })`), and `F.audio.open` / `F.audio.load` render music bytes; a +VideoDecoder saved to an image format (`gif`, `apng`, `webp`) becomes an animated Image of its frames (`frames`, +`fps`, `maxFrames` = 300, `maxPixels` = 2^25); an Image saves to a video format as a frames-backed video. ## Category facades @@ -43,6 +51,8 @@ one category. Extras: - `F.cad.toBodies`, `F.cad.fromBodies`, `F.cad.tessellate`: STEP B-rep calls through the injected kernel (`F.plugins.brep`). - `F.data.null`: the JSON / YAML / TOML / msgpack / CBOR null. +- `F.music.new`, `addPattern`, `setCell`, `getCell`, `addSample`, `addInstrument`, `note`: build and edit tracker + modules (`ops/MusicOps`, also `F.ops.music`): `F.music.new({ format = "mod", channels = 4 })`. ## Editing: `F.ops` @@ -54,6 +64,7 @@ arguments. | `F.ops.image` | `ops/ImageOps` | `convert` (pixel formats), `crop`, `resize` (nearest / bilinear / Lanczos-3), `flip`, `rotate90`, `rotate`, `blit`, `composite`, `premultiply` / `unpremultiply`, `getPixel` / `setPixel` / `fill`, `new` / `copy`, animations: `coalesce` (frames on full canvases), `fromFrames`, `frameCount`, `durations` | | `F.ops.mesh` | `ops/MeshOps` | `triangulate`, `transform`, `computeNormals`, `computeTangents`, `weld` / `unweld`, `bounds`, `merge`, `scale` / `setUnit` / `setUp`, `voxelsToPrimitive`, `meshVoxels` | | `F.ops.layers` | `ops/LayerOps` | `flatten(layered, { frame })`, `flattenFrames`, `leaves` | +| `F.ops.music` | `ops/MusicOps` | `new`, `addPattern`, `setCell` / `getCell`, `addSample` (from an Audio), `addInstrument`, `note` (`"C-4"` -> 49) | | `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/audio/Resample`), `trim`, `concat`, `fade` | | `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` | diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2acc70d..dfcdb88 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -46,7 +46,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | -| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | +| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary", extraFiles: true | `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` | | font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` | diff --git a/docs/STYLE.md b/docs/STYLE.md index 1e7e242..46ba287 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -20,7 +20,7 @@ The reference implementation to copy is **PNG**: src/Formats/ init.luau Registry.luau (generated) api (layer 6) ops/ ops (layer 5.5) editing on the standard types (F.ops.image / - mesh / layers / audio; ImageOps, MeshOps, ...) + mesh / layers / audio / music; ImageOps, ...) // formats (layer 5) image audio video model cad font archive data vector layered subtitle music playlist containers/ containers (layer 4) Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ... @@ -126,7 +126,10 @@ Rules: - `open(r, opts)` (audio / video) returns the streaming Decoder / VideoDecoder / Demuxer from `Types.luau`. If a format has `open` but no `decode`, `F.load` decodes the whole stream through it. - Options are a typed table with defaults documented on each field (`level: number?, -- 0..9, default 6`). -- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module. +- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module. Two optional ones the + api calls: `variant(r) -> string?` (a more precise name for `F.detect`: video/mkv gives `"webm"`), and encoders + that write extra files into `opts.files` declare `caps.extraFiles = true` (the api then returns them from + `F.save` without a destination). - No globals, no state between calls, no host access (no files, no `game`). ### Conventions shared by every format diff --git a/docs/guide/README.md b/docs/guide/README.md index 233334d..d1fff6c 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -193,7 +193,7 @@ Every call takes an optional `opts` table. The options every format understands: | `maxPixels`, `maxBytes`, `maxFrames`, ... | size limits; going over returns `LIMIT` | Each format adds its own options, such as `quality` for JPEG, `lossless` for WebP, `level` for PNG and zip, or -`bitrate` for MP3. The type pages list them. +`bitrate` (bits per second) for MP3 and Opus. The type pages list them. ```luau local img = assert(F.load(pngBytes)) @@ -252,7 +252,7 @@ file instead of returning a buffer. ```luau local webp = assert(F.convert(pngBytes, "webp", { lossless = true })) -local mp3 = assert(F.convert(wavBytes, "mp3", { bitrate = 128 })) +local mp3 = assert(F.convert(wavBytes, "mp3", { bitrate = 128000 })) assert(F.detect(webp) == "webp" and F.detect(mp3) == "mp3") ``` diff --git a/docs/guide/audio.md b/docs/guide/audio.md index 454473c..94271f6 100644 --- a/docs/guide/audio.md +++ b/docs/guide/audio.md @@ -10,7 +10,7 @@ local song = assert(F.audio.load(flacBytes)) -- Audio: the whole file print(song.sampleRate, song.channels, song.frames) -- 44100 2 44100 print(song.tags.title, song.tags.artist) -- Docs Tone formats-luau local quieter = F.ops.audio.gainDb(song, -6) -local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192 })) -- a buffer +local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192000 })) -- a buffer assert(F.detect(mp3) == "mp3") ``` @@ -174,12 +174,15 @@ Encoder options: |---|---| | wav | `sampleFormat = "u8" \| "s16" \| "s24" \| "s32" \| "f32"` (default `"s16"`), `rf64`, `extensible`, `channelMask`, `tags` | | flac | `level` 0..8 (default 5), `bits` 4..24 (default: the source depth, else 16), `blockSize`, `seekInterval`, `padding` | -| mp3 | `bitrate` **in kbps** (default 128), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` | +| mp3 | `bitrate` (default 128000; one of the layer's rates), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` | | vorbis | `quality` -1..10 (default 3) | -| opus | `bitrate` **in bits per second** (default 64000 per channel); CELT only; resampled to 48 kHz | +| opus | `bitrate` (default 64000 per channel, 6000..510000); CELT only; resampled to 48 kHz | | aiff, au, voc | `sampleFormat` (see each format's `init.luau`) | | m4a, caf | ALAC (lossless); m4a and caf also keep tags | +`bitrate` is in **bits per second** for every encoder (`bitrate = 192000`), as the Decoder's `bitrate` field is. A +value below 1000 is read as kbit/s (`bitrate = 192` is 192000), so older code that passed kbit/s to MP3 still works. + Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the format has tags. ## Formats @@ -242,7 +245,6 @@ visualisers. ## Gotchas -- **Bitrate units differ.** MP3 takes kbps (`bitrate = 192`); Opus takes bits per second (`bitrate = 96000`). - `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. - `read(n, out)` returns a new buffer when `out` is too small. Always use the buffer it returns. - Opus always decodes at 48 kHz. Resample with `F.ops.audio.resample` if you need another rate. @@ -250,5 +252,5 @@ visualisers. number. - `F.save(decoder)` without `opts.format` or a destination fails with `Err.ARG`, because a Decoder has no source format. -- `F.audio.load` does not take music files (MOD, MIDI). Use `F.music.open(src)` for their audio - ([music.md](music.md)). +- Music files (MOD, S3M, XM, IT, MIDI) are audio too: `F.audio.open` / `F.audio.load` render them, with the + render options in `opts` ([music.md](music.md)). diff --git a/docs/guide/font.md b/docs/guide/font.md index f6590d3..d784a96 100644 --- a/docs/guide/font.md +++ b/docs/guide/font.md @@ -219,8 +219,18 @@ local again = assert(F.font.load(bin, { pages = baked.pages })) assert(again:advance(again:glyphIndex(string.byte("H"))) == baked:advance(baked:glyphIndex(string.byte("H")))) ``` -`F.save(ttf, nil, { format = "bmfont", px = 16 })` bakes too, but returns only the descriptor: the page images are -not written anywhere. Use `bake` when you need the pages. +`F.save(ttf, dest, { format = "bmfont", px = 16, chars = ... })` bakes too, and writes the page PNGs next to the +`.fnt`, named after it (`ui.fnt` gets `ui_0.png`, ...; `file` sets another prefix). Without a destination it +returns the pages as a third value, `{ [page file name] = PNG buffer }` (the names the descriptor uses), or puts +them into your `opts.files` table when you pass one. A BMFont whose pages are loaded saves them the same way. + +```luau +local ttf = assert(F.font.load(ttfBytes)) +local fnt, _, pages = F.save(ttf, nil, { format = "bmfont", px = 16, chars = "Hi", file = "hud" }) +assert(fnt and pages and F.detect(pages["hud_0.png"]) == "png") +local bm = assert(F.font.load(fnt, { loadPage = function(file) return pages[file] end })) +assert(bm:rasterize(bm:glyphIndex(string.byte("H")))) +``` ## Formats diff --git a/docs/guide/layered.md b/docs/guide/layered.md index 67c0eab..043f2fc 100644 --- a/docs/guide/layered.md +++ b/docs/guide/layered.md @@ -58,7 +58,8 @@ assert(flat.width == 48 and F.detect(png) == "png") **Groups.** A group with `blend = "passThrough"` blends its children straight onto what is below (as Photoshop's pass-through and Aseprite's plain groups). Any other blend first composites the children on their own transparent -canvas, then blends that result with the group's mode and opacity. +canvas, then blends that result with the group's mode and opacity. A group's mask applies either way: on a +pass-through group it limits, pixel by pixel, how much of the children's effect reaches the canvas. **Format extras.** @@ -164,7 +165,6 @@ doc.layers = { L.layer("Paper", paper), L.group("Art", { inkLayer, shadeLayer }) local mask = assert(F.ops.image.new(32, 16, "gray8")) F.ops.image.fill(mask, 255, 255, 255) -- show the top half -doc.layers[2].blend = "normal" -- an isolated group (masks need one, see Gotchas) doc.layers[2].mask = { image = mask, x = 0, y = 0, default = 0 } -- hide the rest local flat = assert(F.ops.layers.flatten(doc)) @@ -244,6 +244,4 @@ See [FORMATS.md](../FORMATS.md) for the capability matrix. not rendered, so the result can differ from Photoshop's `meta.composite`. - Linked Aseprite cels share one Image table between frames: copy it (`F.ops.image.copy`) before editing a single frame. -- `flatten` ignores the mask of a `passThrough` group (Photoshop applies it). Give a masked group a real blend mode - such as `"normal"` to isolate it. - Pixels are straight (not premultiplied) alpha, like every Image. diff --git a/docs/guide/music.md b/docs/guide/music.md index 8055e38..369929d 100644 --- a/docs/guide/music.md +++ b/docs/guide/music.md @@ -142,8 +142,8 @@ end | `F.music.load(src, opts?)` / `F.load` | a Module, a Midi or a SoundFont | | `F.music.open(src, opts?)` / `F.open` | the rendered audio Decoder (decode and render options together) | -`F.audio.open` and `F.audio.load` do not take music files; use `F.music.open`, or `F.open`, which detects any -category. +Every music file that renders is also audio: `F.audio.open(src)` gives the same rendered Decoder as `F.music.open`, +and `F.audio.load(src)` the whole render as an Audio. Decode and render options go in the same `opts`. | Option | Formats | Meaning | |---|---|---| @@ -157,6 +157,8 @@ assert(dec.sampleRate == 22050 and dec.channels == 2) assert(math.abs(dec.duration - 3) < 0.01) -- 2 s of notes + the 1 s release tail local d2 = assert(F.open(modBytes)) -- any category: a Decoder for a module assert(d2.channels == 2) +local d3 = assert(F.audio.open(midiBytes, { sampleRate = 22050 })) -- music is audio too +assert(d3.sampleRate == 22050) ``` ## Rendering @@ -199,20 +201,20 @@ assert(first.frames == 22050) A Midi is plain data: build one with `F.Types.Midi.new(division?)` and save it as `.mid`. Events need absolute ticks; the writer sorts nothing, so keep each track's events in tick order. A track's `name` is read from its -track-name meta event (0x03); the writer writes events only, so put the name in an event. +track-name meta event (0x03); the writer writes `track.name` as one at tick 0 when the track has no 0x03 event of +its own. ```luau local m = F.Types.Midi.new(480) -- 480 ticks per quarter note, SMF type 1 local events = { { tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- tempo: 500000 us per quarter - { tick = 0, type = "meta", meta = 0x03, data = { string.byte("Arpeggio", 1, -1) } }, -- the track name { tick = 0, type = "program", channel = 0, data = { 0 } }, } for i, note in { 60, 64, 67, 72 } do table.insert(events, { tick = (i - 1) * 240, type = "noteOn", channel = 0, data = { note, 100 } }) table.insert(events, { tick = i * 240, type = "noteOff", channel = 0, data = { note, 0 } }) end -table.insert(m.tracks, { events = events }) +table.insert(m.tracks, { name = "Arpeggio", events = events }) -- written as a 0x03 event local bytes = assert(F.save(m, nil, { format = "midi" })) local back = assert(F.music.load(bytes)) assert(back.tracks[1].name == "Arpeggio" and back.meta.length == 1) -- 4 eighth notes at 120 BPM @@ -232,6 +234,69 @@ local _, err = F.save(song, nil, { format = "it" }) assert(err.code == F.Err.UNSUPPORTED) -- read only ``` +Saving a Module or a Midi to an **audio** format renders it first, with the render options (see +[Rendering](#rendering)) taken from the same `opts`; `F.convert` does the same from music bytes: + +```luau +local song = assert(F.music.load(modBytes)) +local wav = assert(F.save(song, nil, { format = "wav", sampleRate = 22050 })) +assert((assert(F.audio.load(wav))).sampleRate == 22050) +local flac = assert(F.convert(midiBytes, "flac", { soundfont = sf2Bytes, tail = 0.5 })) +assert(F.detect(flac) == "flac") +``` + +### Building a module + +`F.music` has a small builder for tracker modules, so you never touch the pattern buffers or the sample tuning +fields yourself. Pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, and +sample and instrument numbers 1-based (0 = none in a cell). Every call returns `nil, Err.ARG` for bad arguments. + +| Call | Returns | +|---|---| +| `F.music.new({ format?, channels?, title?, speed?, tempo? })` | an empty Module: `format` `"mod"` (default), `"xm"`, `"s3m"` or `"it"`; 4 channels by default | +| `F.music.addPattern(m, rows?, { order? }?)` | the new pattern's number; `rows` default 64 (MOD needs 64); appended to `m.order` unless `order = false` | +| `F.music.setCell(m, pattern, row, channel, cell)` | `true`; `cell = { note, instrument, volume, effect, param }`, missing fields 0 | +| `F.music.getCell(m, pattern, row, channel)` | the cell, with `note` as a number | +| `F.music.addSample(m, spec)` | the new sample's number | +| `F.music.addInstrument(m, spec)` | the new instrument's number (XM / IT only; MOD and S3M cells name samples) | +| `F.music.note(name)` | the note number: `"C-4"` = 49, `"C#4"` / `"Db4"` = 50, `"off"` 255, `"cut"` 254, `"fade"` 253 | + +`addSample` takes `audio` (a mono or stereo Audio) or `data` (f32 frames) with `length` and `channels`; `rate` +(the Hz the sample plays at on C-4 for MOD / XM, C-5 for S3M / IT; default the Audio's rate, else 8363), `loop` +(`"none"`, `"forward"`, `"pingpong"`), `loopStart` / `loopEnd` (frames), `volume` 0..64, `pan` 0..256 and `bits` +(8 or 16, what a writer stores). MOD files keep only a finetune of -1..+7/8 semitone, so give MOD samples a rate +near 8363 Hz. `addInstrument` takes `name`, `sample` (every note) or `samples` (a `{ [note] = sample }` keymap), +`fadeout`, and a volume `envelope = { points = { { tick, 0..64 }, ... }, sustain?, loopStart?, loopEnd? }`. + +```luau +local tone = F.Types.Audio.new(8363, 1, 8363) -- 1 s of a 440 Hz sine at MOD's C-4 rate +for i = 0, 8362 do + buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(i / 8363 * 2 * math.pi * 440)) +end +local song = assert(F.music.new({ format = "mod", channels = 4, title = "beeps" })) +local s = assert(F.music.addSample(song, { name = "sine", audio = tone, loop = "forward" })) +local p = assert(F.music.addPattern(song)) -- pattern 0, 64 rows, in the order list +for row = 0, 63, 8 do + assert(F.music.setCell(song, p, row, 1, { note = if row % 16 == 0 then "C-4" else "G-4", instrument = s })) +end +assert(F.music.setCell(song, p, 63, 2, { effect = 0xC, param = 0 })) -- effect C00: volume 0 +assert(F.music.getCell(song, p, 8, 1).note == F.music.note("G-4")) +local mod = assert(F.save(song)) -- a .mod (the module's format) +local wav = assert(F.save(song, nil, { format = "wav" })) -- or rendered +assert(F.detect(mod) == "mod" and F.detect(wav) == "wav") + +local xm = assert(F.music.new({ format = "xm", channels = 2 })) +local smp = assert(F.music.addSample(xm, { audio = tone })) +local lead = assert(F.music.addInstrument(xm, { + name = "lead", sample = smp, fadeout = 512, + envelope = { points = { { 0, 64 }, { 10, 40 }, { 40, 0 } }, sustain = 2 }, +})) +local p2 = assert(F.music.addPattern(xm, 32)) +assert(F.music.setCell(xm, p2, 0, 1, { note = "C-4", instrument = lead })) +assert(F.music.setCell(xm, p2, 16, 1, { note = "off" })) +assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead") +``` + | Format | Encoder options | |---|---| | midi | `runningStatus` (default true: the bytes python's mido writes) | @@ -252,11 +317,8 @@ See [FORMATS.md](../FORMATS.md) for each format's capabilities. ## Gotchas -- **Saving music as audio needs a render.** `F.save(song, nil, { format = "wav" })` and `F.convert(modBytes, "wav")` - fail with `UNKNOWN_FORMAT` ("no format named wav for music"). Render first: - `F.save(song:render(), nil, { format = "wav" })`. -- `F.audio.open(midiBytes)` fails with `UNKNOWN_FORMAT`; use `F.music.open` or `F.open`. -- `track.name` is not written: add a meta 0x03 event to name a track. +- Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav", + loop = true })` would render up to `maxDuration` (an hour by default), so leave `loop` off when saving. - A Midi you build yourself has no `render` method; `F.format("midi").render(midi, opts)` renders it. - MIDI event ticks are absolute, not the deltas stored in the file. Pitch bend `data` is `{ lsb, msb }`, not a signed value: `(msb * 128 + lsb) - 8192`. diff --git a/docs/guide/recipes.md b/docs/guide/recipes.md index aab1bee..d632022 100644 --- a/docs/guide/recipes.md +++ b/docs/guide/recipes.md @@ -112,7 +112,7 @@ end `F.convert` streams audio: the encoder reads the decoder as it goes. ```luau -local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192 })) -- MP3 bit rates are in kbit/s +local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192000 })) -- bit rates are in bit/s local dec = assert(F.audio.open(mp3)) assert(dec.sampleRate == 44100 and dec.channels == 2) assert(math.abs(dec.duration - 1) < 0.1) diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..cbabe27 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -51,7 +51,7 @@ Times: `VideoFrame.pts` / `duration`, `seek` and every `duration` field are **se | `pts` | seconds from the start of the stream | | `duration` | seconds | | `keyframe` | true for frames that decode on their own | -| `index` | 1-based, counted in output order since the decoder was opened | +| `index` | 1-based position in output order; after `seek` it restarts at the frame's own position (`round(pts * frameRate) + 1`) | A `yuv420p` image holds three planes in one buffer: Y (`width * height` bytes, rows top down), then U and then V, each `ceil(width / 2) * ceil(height / 2)` bytes. `image.meta.yuv` gives the matrix (`"bt601"` / `"bt709"`) and the @@ -95,6 +95,7 @@ assert(r and g and b) | `width`, `height`, `frameRate` | video tracks | | `sampleRate`, `channels`, `bitsPerSample` | audio tracks | | `config` | codec configuration bytes (avcC, CodecPrivate, Vorbis headers, ...) | +| `codecDelay`, `playDuration` | audio: seconds of encoder priming to drop, and seconds to play after it (an MP4 edit list; Matroska `CodecDelay`) | | `duration`, `language`, `name`, `default` | when the container has them | A Packet is `{ track, pts, dts?, duration?, keyframe, data }`: `data` is a buffer of the compressed bytes. @@ -142,7 +143,8 @@ v:reset() assert(v:nextFrame().pts == 0) ``` -The audio track is an ordinary audio Decoder: read it, or turn it into an Audio. +The audio track is an ordinary audio Decoder: read it, or turn it into an Audio. Encoder priming and an MP4 edit +list's end padding are cut as ffmpeg cuts them, so a 1 s AAC track decodes to 1 s of samples. ```luau local v = assert(F.video.open(webmBytes)) @@ -151,6 +153,8 @@ assert(a.sampleRate == 44100 and a.channels == 1) local sound = assert(F.ops.audio.toAudio(a)) local ogg = assert(F.save(sound, nil, { format = "vorbis" })) -- the soundtrack on its own assert(F.detect(ogg) == "vorbis") +local aac = assert(F.ops.audio.toAudio(assert(F.video.open(mp4Bytes)).audio)) +assert(aac.frames == 44100) -- 1 s: the AAC priming and padding cut by the edit list ``` Animated images open as videos (`codec = "frames"`, rgba8 frames, no demuxer). `F.video.fromImage(img)` does the same @@ -192,7 +196,7 @@ local mkv = assert(F.save(assert(F.video.open(mp4Bytes)), nil, { format = "mkv" local back = assert(F.video.open(mkv)) assert(back.codec == "h264" and back.audio ~= nil) local webm = assert(F.save(assert(F.video.open(webmBytes)), nil, { format = "webm" })) -assert(F.detect(webm) == "mkv") -- WebM is the mkv format +assert(F.detect(webm) == "webm" and F.format("webm").name == "mkv") -- WebM: the mkv format local avi = assert(F.convert(mp4Bytes, "avi", { quality = 80 })) -- decoded, re-encoded as MJPEG assert(F.video.open(avi).codec == "mjpeg") local y4m = assert(F.save(assert(F.video.fromFrames({ F.Types.Image.new(16, 16) }, 0.04)), nil, { format = "y4m" })) @@ -204,6 +208,30 @@ assert(F.detect(gifAvi) == "avi") A VideoDecoder is consumed as it is saved: open the source again to save it twice. Uneven frame delays (a GIF's) become a constant frame rate with repeated frames. +### As an animated image + +Saving a video to an image format (`gif`, `apng`, `webp`) collects its frames, from the decoder's current position, +into an animated Image and writes that. Each frame keeps its own duration as its delay. + +| Option | Default | Meaning | +|---|---|---| +| `frames` | all (up to the cap) | how many frames to keep | +| `fps` | the source's timing | the output frame rate: frames are picked at `1 / fps` steps; a source frame that covers several steps is held longer instead of repeated | +| `maxFrames` | 300 | the cap on frames written | +| `maxPixels` | 2^25 | a cap on `frames * width * height` (memory: 4 bytes per pixel and frame) | + +Past a cap the rest of the video is left unread (no error). + +```luau +local gif = assert(F.convert(aviBytes, "gif", { fps = 5 })) -- every other frame of a 10 fps clip, 0.2 s each +local anim = assert(F.image.load(gif)) +assert(F.detect(gif) == "gif" and #anim.frames > 1 and math.abs(anim.frames[1].delay - 0.2) < 1e-9) +local v = assert(F.video.open(aviBytes)) +v:seek(0.5) -- start half a second in +local apng = assert(F.save(v, nil, { format = "apng", frames = 3 })) +assert(#F.image.load(apng).frames == 3) +``` + ## The codec registry `F.video.codecs` maps codec ids to entries `{ id, name, fourcc?, matroska?, new?, encode? }`. Containers use it to @@ -295,9 +323,8 @@ See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as c - The only video encoder is Motion-JPEG. H.264, VP8 and the others are copied (remuxed) or decoded, never encoded; `F.save(v, nil, { format = "webm" })` needs a WebM-compatible source. - Saving consumes the decoder, and so does iterating `v.demuxer:packets()`: they share the read position. -- `frame.index` keeps counting after `seek`; use `frame.pts` to know where you are. -- A video does not save to an image format: `F.save(v, nil, { format = "gif" })` and `F.convert(aviBytes, "gif")` - fail with `UNKNOWN_FORMAT`. Collect `v:toRGBA(frame)` images and save `F.ops.image.fromFrames(images, delay)`. +- Saving a video as GIF / APNG / WebP holds every collected frame in memory as rgba8: keep `maxFrames` / + `maxPixels` low for big videos, or pick fewer frames with `fps`. - Packet times are ticks, frame times are seconds. Divide by `track.timescale`. - `nextFrame` returns yuv420p by default. Convert with `v:toRGBA(frame)` or open with `{ rgba = true }` before handing pixels to `F.host.toEditableImage` / `toImageData`, which need rgba8. diff --git a/examples/audio.luau b/examples/audio.luau index 173b7bf..99a5120 100644 --- a/examples/audio.luau +++ b/examples/audio.luau @@ -22,8 +22,7 @@ print(string.format("edited: %d frames, %.2f s, peak %.2f", both.frames, both.fr -- 3. encode: lossless and lossy for _, fmt in { "wav", "flac", "mp3", "vorbis", "opus" } do local opts = { format = fmt } - if fmt == "mp3" then opts.bitrate = 128 end -- kbit/s - if fmt == "opus" then opts.bitrate = 64000 end -- bit/s + if fmt == "mp3" or fmt == "opus" then opts.bitrate = 128000 end -- bit/s (values below 1000: kbit/s) local bytes = assert(F.save(both, nil, opts)) local dec = assert(F.audio.open(bytes)) print(string.format("%-6s %6d bytes %5d Hz %d ch %.2f s title=%s", fmt, buffer.len(bytes), dec.sampleRate, dec.channels, diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index a375d4a..988b668 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -513,7 +513,7 @@ local list: { Entry } = { extensions = { "fnt" }, mime = { "application/x-bmfont" }, deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, load = function() return require("@formats/font/bmfont") end, diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 63e3d79..9ec4443 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -190,6 +190,9 @@ export type Track = { sampleRate: number?, channels: number?, bitsPerSample: number?, + codecDelay: number?, -- seconds of decoder output to drop at the start (encoder priming: Matroska CodecDelay, the + -- first edit's media time of an MP4 audio track) + playDuration: number?, -- seconds to play after the codec delay (an MP4 edit list's length: the end padding cut) config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...) [string]: any, } diff --git a/src/Formats/audio/mp3/Stream.luau b/src/Formats/audio/mp3/Stream.luau index b080873..d720d99 100644 --- a/src/Formats/audio/mp3/Stream.luau +++ b/src/Formats/audio/mp3/Stream.luau @@ -68,7 +68,7 @@ function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): 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, + bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s tags = tags, id3 = id3, layer = idx.layer, diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 5bcaffa..8875cbc 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -44,7 +44,8 @@ export type OpenOptions = { export type Decoder = Stream.Decoder export type EncodeOptions = { layer: number?, -- 3 (MP3, default) or 2 (MP2) - bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96) + bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for + -- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit) mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II, -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) @@ -208,9 +209,13 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if layer == 2 and mode == "joint" then mode = "stereo" end + -- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) + if type(bitrate) == "number" and bitrate >= 1000 then + bitrate /= 1000 + end if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then - return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, rate)) + return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.bitrate), layer, rate)) end if layer == 2 and mpeg1 then -- the standard's allowed bit rate / mode combinations diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau index 3195ab7..36406b7 100644 --- a/src/Formats/audio/opus/Encode.luau +++ b/src/Formats/audio/opus/Encode.luau @@ -15,7 +15,8 @@ local CeltEncoder = require("@formats/codecs/audio/Opus/CeltEncoder") local Encode = {} export type Options = { - bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant) + bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant); values below 1000 + -- are kbit/s (96 = 96000), as for every encoder's bitrate option tags: { [string]: string }?, -- default: the audio's tags vendor: string?, -- OpusTags vendor (default "formats-luau") serial: number?, -- Ogg stream serial (default 0x4f707573) @@ -39,6 +40,9 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) end local bitrate = o.bitrate or 64000 * ch + if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then + bitrate *= 1000 -- kbit/s + end if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end diff --git a/src/Formats/codecs/image/Blend.luau b/src/Formats/codecs/image/Blend.luau index 162ec6f..68c4405 100644 --- a/src/Formats/codecs/image/Blend.luau +++ b/src/Formats/codecs/image/Blend.luau @@ -273,14 +273,40 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n end end --- lerp(dst, from, t, n): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity) -local function lerp(dst: buffer, from: buffer, t: number, n: number) +-- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity); +-- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is +-- also scaled by the mask value of each pixel +local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) if blen(dst) < n * 4 or blen(from) < n * 4 then return end - for i = 0, n * 4 - 1 do - local a = readu8(from, i) - writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) + if mask == nil or w == nil or w <= 0 then + for i = 0, n * 4 - 1 do + local a = readu8(from, i) + writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) + end + return + end + local mbuf: buffer? = mask.pixels + local mw, mh = floor(tonumber(mask.width) or 0), floor(tonumber(mask.height) or 0) + local mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) + local mdef = (tonumber(mask.default) or 255) / 255 + if type(mbuf) ~= "buffer" or mw <= 0 or mh <= 0 or blen(mbuf) < mw * mh then + mbuf = nil + end + for p = 0, n - 1 do + local px, py = p % w, p // w + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + local tt = t * mv + local o = p * 4 + for k = o, o + 3 do + local a = readu8(from, k) + writeu8(dst, k, floor(a + (readu8(dst, k) - a) * tt + 0.5)) + end end end Blend.composite = composite @@ -330,8 +356,10 @@ local function compose(layers: { any }, canvas: buffer, w: number, h: number, hi local before = buffer.create(w * h * 4) buffer.copy(before, 0, canvas, 0, w * h * 4) compose(l.children, canvas, w, h, hidden) - if opacity < 1 then - lerp(canvas, before, opacity, w * h) + -- the group's opacity and mask limit how much of its effect reaches the canvas (as in Photoshop) + local gm = maskOf(l) + if opacity < 1 or gm ~= nil then + lerp(canvas, before, opacity, w * h, w, gm) end continue end @@ -360,7 +388,7 @@ end -- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: -- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group --- opacity then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. +-- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. -- hidden = true includes invisible layers. function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) if blen(canvas) >= w * h * 4 then diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..a2cf402 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -466,6 +466,11 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec if img then local t = (pts or 0) / scale - start if t + 1e-9 >= skipUntil then + if index < 0 then + -- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); + -- without a frame rate, counted from the seek) + index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0 + end index += 1 local d = defaultDur if lastPts and t > (lastPts :: number) and defaultDur == 0 then @@ -502,6 +507,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec flushed = false skipUntil = seconds lastPts = nil + index = -1 -- recomputed from the first frame's time if self.audio then pcall(self.audio.seek, self.audio, seconds) end diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index 0646754..ac51aee 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -325,16 +325,23 @@ local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Er end -- ------------------------------------------------------------------------------------------------ trim --- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay: --- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself) -function AudioWrap.trim(dec: any, skip: number): any - if skip <= 0 then +-- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's +-- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus +-- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding) +function AudioWrap.trim(dec: any, skip: number, length: number?): any + if skip <= 0 and length == nil then return dec end + skip = math.max(0, skip) local rate = dec.sampleRate local w: any = setmetatable({}, { __index = dec }) w.frames = math.max(0, (dec.frames or 0) - skip) - w.duration = math.max(0, (dec.duration or 0) - skip / rate) + if length then + w.frames = if (dec.frames or 0) > 0 then math.min(w.frames, length) else length + end + w.duration = w.frames / rate + local cap = length or math.huge + local delivered = 0 local function drop() local left = skip while left > 0 do @@ -351,15 +358,23 @@ function AudioWrap.trim(dec: any, skip: number): any started = true drop() end - return dec:read(n, out) + local want = math.min(n, cap - delivered) + if want <= 0 then + return out or buffer.create(0), 0 + end + local b, got = dec:read(want, out) + delivered += got + return b, got end function w.seek(_: any, seconds: number) started = true if seconds <= 0 then dec:seek(0) drop() + delivered = 0 else dec:seek(seconds + skip / rate) + delivered = math.floor(seconds * rate + 0.5) end end function w.position(_: any): number diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau index 617033a..e7d4294 100644 --- a/src/Formats/font/bmfont/init.luau +++ b/src/Formats/font/bmfont/init.luau @@ -20,7 +20,7 @@ local Bmfont = { extensions = { "fnt" }, mime = { "application/x-bmfont" }, deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, } export type DecodeOptions = { @@ -31,6 +31,11 @@ export type EncodeOptions = { variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" px: number?, -- fonts without a BMFont description are baked first (see bake) chars: (string | { number })?, + file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font") + name: string?, -- the destination's file name (set by the api) + files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes + -- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages + encodeImage: ((img: any, format: string) -> (buffer?, any))?, } export type BakeOptions = { px: number?, -- pixels per em (default 32) @@ -237,16 +242,42 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "expected a Font") end local d = type(font.meta) == "table" and font.meta.bmfont or nil + local pages = font.pages if d == nil then - local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars }) + -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" + local file = opts and opts.file + if file == nil and opts and type(opts.name) == "string" then + file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") + if file == "" then + file = nil + end + end + local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file }) if not baked then return nil, err end d = baked.meta.bmfont + pages = baked.pages end if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end + -- the page images into opts.files, under the names the descriptor gives them + local files = opts and opts.files + local encodeImage = opts and opts.encodeImage + if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then + for i, name in d.pages do + local img = pages[i] + if type(img) == "table" and type(name) == "string" and name ~= "" then + local ext = string.lower(string.match(name, "%.([%w]+)$") or "png") + local bytes, eerr = encodeImage(img, ext) + if not bytes then + return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr)) + end + files[name] = bytes + end + end + end local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text" if variant == "text" then return buffer.fromstring(Parse.writeText(d)), nil diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 4f90979..5774bf3 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -12,7 +12,7 @@ -- local s = F.saveString(img, { format = "png" }) -- local buf = F.convert(src, "png", opts?) -- load + save -- F.formats() -- the capability list (also docs/FORMATS.md) --- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / vector.rasterize +-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / music / vector -- -- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). local Err = require("@formats/core/Err") @@ -129,6 +129,20 @@ local function detect(buf: buffer, name: string?, category: string?, format: str return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) end +-- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that +-- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered = +-- true: open the format, which renders it, instead of decoding it) +local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean) + local entry, err = detect(buf, name, o.category, o.format) + if not entry and o.category == "audio" then + local e = detect(buf, name, "music", o.format) + if e and e.caps.render then + return e, nil, true + end + end + return entry, err, false +end + local function tag(value: any, formatName: string) if type(value) == "table" then local meta = value.meta @@ -273,8 +287,13 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?) local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) -- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is -- already the decoder's own (its first packet returns nothing) - if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then - dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5)) + -- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does) + if dec and fmt ~= "opus" and fmt ~= "vorbis" then + local skip = if type(track.codecDelay) == "number" and track.codecDelay > 0 then math.floor(track.codecDelay * dec.sampleRate + 0.5) else 0 + local length = if type(track.playDuration) == "number" and track.playDuration > 0 then math.floor(track.playDuration * dec.sampleRate + 0.5) else nil + if skip > 0 or length then + dec = AudioWrap.trim(dec, skip, length) + end end return dec, oerr end @@ -314,7 +333,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) o = table.clone(o) o.name = name -- formats may use the file name (single-stream archives name their entry after it) end - local entry, derr = detect(buf, name, o.category, o.format) + local entry, derr, rendered = detectFor(buf, name, o) if not entry then return nil, derr end @@ -328,7 +347,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) o.resolve = siblings(name) end local value, err - if m.decode then + if m.decode and not rendered then local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) @@ -362,7 +381,7 @@ function F.open(src: any, opts: Options?): (any, Err.Err?) if not buf then return nil, ierr end - local entry, derr = detect(buf, name, o.category, o.format) + local entry, derr = detectFor(buf, name, o) if not entry and o.category == "video" and o.format == nil then entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos end @@ -398,6 +417,91 @@ end local encodeTextures: (scene: any) -> Err.Err? +-- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil, +-- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are +-- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap +-- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is. +local function videoToImage(v: any, o: Options): (any, Err.Err?) + if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then + return nil, Err.new(Err.ARG, "save: not a VideoDecoder") + end + local cap = o.maxFrames or 300 + local want = o.frames + local fps = o.fps + if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then + return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000") + end + local limit = math.floor(if want then math.min(want, cap) else cap) + local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1) + limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h)))) + local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1 + local images: { any }, delays: { number } = {}, {} + local t0: number? = nil + local taken = 0 -- output slots used (fps mode) + while #images < limit do + local ok, f, ferr = pcall(v.nextFrame, v) + if not ok then + return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f)) + end + if f == nil then + if ferr then + return nil, ferr + end + break + end + local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur + local delay = dur + if fps then + local start: number = t0 or f.pts + t0 = start + local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken + delay = slots / fps + taken += math.max(0, slots) + end + if delay > 0 then + local rok, img = pcall(v.toRGBA, v, f) + if not rok or type(img) ~= "table" then + return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8") + end + table.insert(images, img) + table.insert(delays, delay) + end + end + if #images == 0 then + return nil, Err.new(Err.ARG, "save: the video has no frames") + end + local img, ierr = ImageOps.fromFrames(images, delays) + if not img then + return nil, ierr + end + img.loops = if type(v.loops) == "number" then v.loops else 0 + img.meta.source = { format = v.format } + return img, nil +end + +-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) | +-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ... +local function renderMusic(value: any, o: Options): (any, Err.Err?) + local ok, dec, err + if value.kind == "midi" then + local m, merr = F.format("midi") + if not m then + return nil, merr + end + ok, dec, err = pcall(m.render, value, o) + else + local Tracker: any = require("@formats/codecs/audio/Tracker") + ok, dec, err = pcall(Tracker.render, value, o) + end + if not ok then + return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec)) + end + if dec == nil then + return nil, err or Err.new(Err.ARG, "render failed") + end + return dec, nil +end + -- the writable format for a value: opts.format, the destination's extension, or the source format local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?) local category = o.category @@ -415,6 +519,12 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr if not entry and category == "image" and type(value) == "table" and value.kind == "image" then entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") end + if not entry and category == "video" and type(value) == "table" and value.kind == "video" then + entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif") + end + if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav") + end if not entry then return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) end @@ -452,8 +562,10 @@ function encodeTextures(scene: any): Err.Err? return nil end --- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err -function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) +-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files +-- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the +-- caller's opts.files); with a dest they are written next to it. +function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?) local o: Options = opts or {} local entry, m, err, key = encoderFor(value, dest, o) if not entry then @@ -468,6 +580,8 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) if o.files == nil then o.files = {} end + elseif o.files == nil and entry.caps.extraFiles then + o.files = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages end if entry.category == "video" and type(value) == "table" and value.kind == "image" then local v, verr = F.video.fromImage(value) @@ -476,6 +590,20 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) end value = v end + if entry.category == "image" and type(value) == "table" and value.kind == "video" then + local img, ierr = videoToImage(value, o) + if not img then + return nil, ierr + end + value = img + end + if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts + if not dec then + return nil, rerr + end + value = dec + end if type(value) == "table" and value.kind == "scene" then local terr = encodeTextures(value) if terr then @@ -505,6 +633,9 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) end return true end + if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then + return buf, nil, o.files + end return buf end @@ -518,7 +649,7 @@ function F.saveString(value: any, opts: Options?): (string?, Err.Err?) end -- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. -function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?) +function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?) local o: Options = opts or {} local value, err = F.load(src, o) if value == nil then @@ -541,6 +672,14 @@ function F.detect(src: any, opts: Options?): (string?, Err.Err?) if not entry then return nil, err end + -- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm) + local m = module(entry) + if m and type(m.variant) == "function" then + local ok, v = pcall(m.variant, Bytes.reader(buf)) + if ok and type(v) == "string" then + return v, nil + end + end return entry.name, nil end @@ -616,6 +755,14 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do return a, b end end +-- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker +-- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module +for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do + local name: string = fn + F.music[name] = function(...: any): (any, Err.Err?) + return (F.ops.music :: any)[name](...) + end +end -- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited -- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) @@ -687,6 +834,7 @@ end -- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves -- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, -- concat, fade, peak, rms +-- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music) -- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector local OPS: { [string]: () -> any } = { image = function() @@ -701,6 +849,9 @@ local OPS: { [string]: () -> any } = { audio = function() return require("@formats/ops/AudioOps") end, + music = function() + return require("@formats/ops/MusicOps") + end, vector = function() return { rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?) diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau index c5114ec..124eaef 100644 --- a/src/Formats/music/midi/Smf.luau +++ b/src/Formats/music/midi/Smf.luau @@ -3,7 +3,8 @@ -- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps -- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are -- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the --- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code). +-- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track +-- has none. Written from the SMF 1.0 specification (no third-party code). local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -323,6 +324,21 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) return order[a] < order[c] end) end + -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own + if type(track.name) == "string" and track.name ~= "" then + local named = false + for _, ev in list do + if ev.type == "meta" and ev.meta == 0x03 then + named = true + break + end + end + if not named then + local bytes = { string.byte(track.name, 1, math.min(#track.name, 4096)) } + list = table.clone(list) + table.insert(list, 1, { tick = 0, type = "meta", meta = 0x03, data = bytes }) + end + end w:string("MTrk") local lenAt = w:tell() w:u32be(0) diff --git a/src/Formats/ops/MusicOps.luau b/src/Formats/ops/MusicOps.luau new file mode 100644 index 0000000..1d1cae0 --- /dev/null +++ b/src/Formats/ops/MusicOps.luau @@ -0,0 +1,368 @@ +--!strict +-- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the +-- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name, +-- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample / +-- addInstrument / note in the api (also F.ops.music). +-- +-- local M = require("@formats/ops/MusicOps") +-- local song = M.new({ format = "mod", channels = 4, title = "demo" }) +-- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1 +-- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list +-- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 }) +-- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod +-- +-- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample +-- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 +-- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering +-- (MOD / XM 0..35, S3M / IT 1..26 = A..Z). Never throws: bad arguments return nil, Err.ARG. +local Err = require("@formats/core/Err") +local Tracker = require("@formats/codecs/audio/Tracker") + +local MusicOps = {} + +local FORMATS = { mod = true, xm = true, s3m = true, it = true } + +local function bad(what: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, what) +end + +local function isModule(m: any): boolean + return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table" +end + +local function int(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi +end + +-- ------------------------------------------------------------------------------------------------ module +export type NewOptions = { + format: string?, -- "mod" (default), "xm", "s3m", "it": the effect family (mod and xm can be saved) + channels: number?, -- 1..32 for mod, else 1..64 (default 4) + title: string?, + speed: number?, -- ticks per row (default 6) + tempo: number?, -- BPM (default 125) +} + +-- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format +function MusicOps.new(opts: NewOptions?): (any, Err.Err?) + local o: NewOptions = opts or {} + local format = o.format or "mod" + if not FORMATS[format] then + return bad("new: format must be mod, xm, s3m or it") + end + local channels = o.channels or 4 + if not int(channels, 1, if format == "mod" then 32 else 64) then + return bad("new: bad channel count") + end + local m = Tracker.newModule(format, channels) + m.title = if type(o.title) == "string" then o.title else "" + if o.speed ~= nil then + if not int(o.speed, 1, 255) then + return bad("new: speed must be 1..255") + end + m.speed = o.speed + end + if o.tempo ~= nil then + if type(o.tempo) ~= "number" or o.tempo < 32 or o.tempo > 1000 then + return bad("new: tempo must be 32..1000") + end + m.tempo = o.tempo + end + m.meta = { source = { format = format } } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ patterns +-- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64). +-- The pattern is appended to the order list unless opts.order == false. +function MusicOps.addPattern(m: any, rows: number?, opts: { order: boolean? }?): (number?, Err.Err?) + if not isModule(m) then + return bad("addPattern: needs a tracker Module") + end + local n = rows or 64 + if not int(n, 1, 1024) then + return bad("addPattern: rows must be 1..1024") + end + table.insert(m.patterns, Tracker.newPattern(n, m.channels)) + local index = #m.patterns - 1 + if not (opts and opts.order == false) then + table.insert(m.order, index) + end + return index, nil +end + +local NAMES: { [string]: number } = { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } +local SPECIAL: { [string]: number } = { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } + +-- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50, +-- "Db4" = 50, "off", "cut", "fade" +function MusicOps.note(v: any): (number?, Err.Err?) + if type(v) == "number" then + if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then + return v, nil + end + return bad("note: number must be 0..120 or 253..255") + end + if type(v) ~= "string" then + return bad("note: expected a number or a name") + end + local s = string.lower(v) + if SPECIAL[s] then + return SPECIAL[s], nil + end + local letter, acc, oct = string.match(s, "^([a-g])([#b%-]?)(%d)$") + if not letter then + return bad("note: bad name " .. v) + end + local n = NAMES[letter :: string] + (if acc == "#" then 1 elseif acc == "b" then -1 else 0) + local num = 1 + (tonumber(oct) :: number) * 12 + n + if num < 1 or num > 120 then + return bad("note: out of range " .. v) + end + return num, nil +end + +export type Cell = { + note: (number | string)?, -- 0 / nil = none + instrument: number?, -- 1-based sample (MOD / S3M) or instrument (XM / IT); 0 = none + volume: number?, -- the volume column as the format stores it (0 = none) + effect: number?, -- the format's effect number (MOD / XM 0..35; S3M / IT 1..26) + param: number?, -- 0..255 +} + +local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Err.Err?) + if not isModule(m) then + return bad("needs a tracker Module") + end + local p: any = if int(pattern, 0, 1e6) then m.patterns[pattern + 1] else nil + if p == nil then + return bad("no pattern " .. tostring(pattern)) + end + if not int(row, 0, p.rows - 1) then + return bad("row " .. tostring(row) .. " outside 0.." .. (p.rows - 1)) + end + if not int(channel, 1, m.channels) then + return bad("channel " .. tostring(channel) .. " outside 1.." .. m.channels) + end + return p, nil +end + +-- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0) +function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, cell: Cell): (boolean?, Err.Err?) + local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + if type(cell) ~= "table" then + return bad("setCell: cell must be a table") + end + local note = 0 + if cell.note ~= nil then + local n, nerr = MusicOps.note(cell.note) + if not n then + return nil, nerr + end + note = n + end + for _, k in { "instrument", "volume", "effect", "param" } do + local v = (cell :: any)[k] + if v ~= nil and not int(v, 0, 255) then + return bad("setCell: " .. k .. " must be 0..255") + end + end + Tracker.setCell(m, pattern, row, channel, note, cell.instrument or 0, cell.volume or 0, cell.effect or 0, cell.param or 0) + return true, nil +end + +-- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err +function MusicOps.getCell(m: any, pattern: number, row: number, channel: number): (Cell?, Err.Err?) + local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel) + return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil +end + +-- ------------------------------------------------------------------------------------------------ samples +export type SampleSpec = { + name: string?, + audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate + data: buffer?, -- or raw f32 frames (interleaved when channels = 2) ... + length: number?, -- ... with their frame count (default: the whole buffer) + channels: number?, -- 1 (default) or 2, for data + rate: number?, -- Hz the sample plays at on C-4 (MOD / XM) or C-5 (S3M / IT); default the Audio's, else 8363 + loop: string?, -- "none" (default), "forward", "pingpong" + loopStart: number?, -- frames (default 0) + loopEnd: number?, -- frames, exclusive (default the length) + volume: number?, -- 0..64 (default 64) + pan: number?, -- 0..256 (XM / IT; nil = the channel's) + bits: number?, -- 8 or 16: what writers store (default 8 for MOD, else 16) +} + +local LOOPS: { [string]: number } = { none = 0, forward = 1, pingpong = 2 } + +-- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for +-- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune, +-- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD). +function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) + if not isModule(m) then + return bad("addSample: needs a tracker Module") + end + if type(spec) ~= "table" then + return bad("addSample: spec must be a table") + end + local data: buffer, length: number, channels: number + local rate = spec.rate + local a = spec.audio + if a ~= nil then + if type(a) ~= "table" or a.kind ~= "audio" or type(a.samples) ~= "buffer" or not int(a.frames, 0, 2 ^ 31) or (a.channels ~= 1 and a.channels ~= 2) or buffer.len(a.samples) < a.frames * a.channels * 4 then + return bad("addSample: audio must be a mono or stereo Audio") + end + data, length, channels = a.samples, a.frames, a.channels + rate = rate or a.sampleRate + elseif type(spec.data) == "buffer" then + channels = spec.channels or 1 + if channels ~= 1 and channels ~= 2 then + return bad("addSample: channels must be 1 or 2") + end + local d: buffer = spec.data + length = spec.length or buffer.len(d) // (4 * channels) + if not int(length, 0, 2 ^ 31) or buffer.len(d) < length * channels * 4 then + return bad("addSample: data shorter than length") + end + data = d + else + return bad("addSample: needs audio or data") + end + rate = rate or 8363 + if type(rate) ~= "number" or rate < 1 or rate > 1e7 then + return bad("addSample: bad rate") + end + local s = Tracker.newSample(spec.name) + local copy = buffer.create(length * channels * 4) + buffer.copy(copy, 0, data, 0, length * channels * 4) + s.data, s.length, s.channels = copy, length, channels + s.bits = spec.bits or (if m.format == "mod" then 8 else 16) + if s.bits ~= 8 and s.bits ~= 16 then + return bad("addSample: bits must be 8 or 16") + end + s.c5speed = rate + local semis = 12 * math.log(rate / 8363) / math.log(2) + local rn = math.floor(semis + 0.5) + if rn < -96 or rn > 95 then + return bad("addSample: rate out of range") + end + s.relativeNote = rn + s.finetune = math.clamp(math.floor((semis - rn) * 128 + 0.5), -128, 127) + local lt = LOOPS[spec.loop or "none"] + if lt == nil then + return bad("addSample: loop must be none, forward or pingpong") + end + if lt > 0 then + local ls, le = spec.loopStart or 0, spec.loopEnd or length + if not int(ls, 0, length) or not int(le, 0, length) or le - ls < 1 then + return bad("addSample: bad loop") + end + s.loopStart, s.loopEnd, s.loopType = ls, le, lt + end + if spec.volume ~= nil then + if type(spec.volume) ~= "number" or spec.volume < 0 or spec.volume > 64 then + return bad("addSample: volume must be 0..64") + end + s.volume = spec.volume + end + if spec.pan ~= nil then + if type(spec.pan) ~= "number" or spec.pan < 0 or spec.pan > 256 then + return bad("addSample: pan must be 0..256") + end + s.pan = spec.pan + end + table.insert(m.samples, s) + return #m.samples, nil +end + +-- ------------------------------------------------------------------------------------------------ instruments +export type InstrumentSpec = { + name: string?, + sample: number?, -- the sample every note plays (1-based) + samples: { [number]: number }?, -- or a keymap: note number -> sample number (other notes: none) + fadeout: number?, -- volume fade per tick after key off, as the format stores it (XM 0..4095, IT 0..1024) + envelope: { points: { { number } }, sustain: number?, loopStart: number?, loopEnd: number? }?, -- volume + -- envelope: points { tick, 0..64 } with ticks increasing; sustain / loop points are 1-based point indexes +} + +-- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD / +-- S3M cells name samples directly). +function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err?) + if not isModule(m) then + return bad("addInstrument: needs a tracker Module") + end + if m.format ~= "xm" and m.format ~= "it" then + return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") + end + if type(spec) ~= "table" then + return bad("addInstrument: spec must be a table") + end + local ins = Tracker.newInstrument(spec.name) + if spec.sample ~= nil then + if not int(spec.sample, 1, #m.samples) then + return bad("addInstrument: no sample " .. tostring(spec.sample)) + end + for n = 1, 120 do + ins.sampleMap[n] = spec.sample + end + elseif type(spec.samples) == "table" then + for note, smp in spec.samples do + if not int(note, 1, 120) or not int(smp, 0, #m.samples) then + return bad("addInstrument: bad keymap entry") + end + ins.sampleMap[note] = smp + end + end + if spec.fadeout ~= nil then + if not int(spec.fadeout, 0, 65535) then + return bad("addInstrument: bad fadeout") + end + ins.fadeout = spec.fadeout + end + local e = spec.envelope + if e ~= nil then + if type(e) ~= "table" or type(e.points) ~= "table" or #e.points == 0 then + return bad("addInstrument: envelope needs points") + end + local env = Tracker.newEnvelope() + local last = -1 + for i, pt in e.points do + local tick: any, value: any = nil, nil + if type(pt) == "table" then + tick, value = pt[1], pt[2] + end + if not int(tick, 0, 65535) or type(value) ~= "number" or value < 0 or value > 64 or (tick :: number) <= last then + return bad("addInstrument: envelope point " .. i .. " must be { tick, 0..64 } with increasing ticks") + end + last = tick :: number + env.ticks[i], env.values[i] = tick, value + end + env.enabled = true + local n = #e.points + if e.sustain ~= nil then + if not int(e.sustain, 1, n) then + return bad("addInstrument: bad sustain point") + end + env.sustain, env.susStart, env.susEnd = true, e.sustain, e.sustain + end + if e.loopStart ~= nil or e.loopEnd ~= nil then + local ls, le = e.loopStart or 1, e.loopEnd or n + if not int(ls, 1, n) or not int(le, ls, n) then + return bad("addInstrument: bad envelope loop") + end + env.loop, env.loopStart, env.loopEnd = true, ls, le + end + ins.volEnv = env + end + table.insert(m.instruments, ins) + return #m.instruments, nil +end + +return MusicOps diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index fd07900..25f2d32 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -553,7 +553,9 @@ end export type Options = { maxPackets: number? } -- parse(buf, base, limit, opts) -> a Demux | nil, Err -function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?) +-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data +-- offset | nil, Err +function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) local id, size, data = Ebml.header(buf, base, limit) if id ~= ID.EBML or not size or not data then return nil, Err.new(Err.CORRUPT, "not an EBML file", base) @@ -567,6 +569,14 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): docType = Ebml.string(buf, o, n) end end + return docType, size, data +end + +function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?) + local docType, size, data = Parse.docType(buf, base, limit) + if not docType then + return nil, size + end if docType ~= "matroska" and docType ~= "webm" then return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) end diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 1a94272..8e009e9 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -67,6 +67,15 @@ function Mkv.sniff(r: Bytes.Reader): number return 0.5 end +-- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) +function Mkv.variant(r: Bytes.Reader): string? + local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) + if ok and docType == "webm" then + return "webm" + end + return nil +end + -- ------------------------------------------------------------------------------------------------ encode -- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) -- or a Demuxer diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 0dcf3e8..48b57c7 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -154,6 +154,9 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) if it.skip and it.skip > 0 then t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg end + if it.playDuration and it.playDuration > 0 and it.timescale > 0 then + t.playDuration = it.playDuration / it.timescale -- the edit's length: the end padding is not played + end end table.insert(tracks, t) table.insert(src, it) @@ -272,6 +275,8 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) for _, d in durations do playDuration += d end + elseif s.kind == "audio" and s.track and s.copied and type(s.track.playDuration) == "number" then + playDuration = math.floor(s.track.playDuration * scale + 0.5) -- keep the source's end trim end local t: any = { kind = s.kind, diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau index b03c97a..c2d711c 100644 --- a/tests/audio/mp3.luau +++ b/tests/audio/mp3.luau @@ -193,7 +193,7 @@ for _, c in Cases do 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) + 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 // 1000, if ref then string.format("%.1f", worst) else "-", worstFF) end -- ------------------------------------------------------------------------------------------------ robustness diff --git a/tests/audio/mp3_encode.luau b/tests/audio/mp3_encode.luau index 2403a4e..7eb71cf 100644 --- a/tests/audio/mp3_encode.luau +++ b/tests/audio/mp3_encode.luau @@ -102,6 +102,13 @@ do local f1 = Mp3.encode(a, { bitrate = 128 }) :: buffer local f2 = Mp3.encode(Pcm.audioDecoder(a), { bitrate = 128 }) :: buffer t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + -- bitrate in bit/s (the documented unit), and the old kbit/s values below 1000: the same file + local f4 = Mp3.encode(a, { bitrate = 128000 }) :: buffer + t:check(f4 ~= nil and buffer.tostring(f1) == buffer.tostring(f4), "bitrate 128000 bit/s = 128 kbit/s") + local d4 = Mp3.open(Bytes.reader(f4)) :: any + t:check(math.abs(d4.bitrate - 128000) < 1000, "the decoder reports bit/s: " .. tostring(d4.bitrate)) + local _, e5 = Mp3.encode(a, { bitrate = 127000 }) + t:check(e5 and e5.code == Err.ARG and string.find(e5.message, "127000 bit/s", 1, true) ~= nil, "127000 bit/s refused: " .. tostring(e5)) a.tags = { title = "Ünïcode title", artist = "An Artist", album = "Album", track = "4", comment = "made here" } local f3 = Mp3.encode(a, { layer = 2 }) :: buffer t:eq(buffer.readstring(f3, 0, 3), "ID3", "an ID3v2 tag in front") @@ -169,6 +176,7 @@ do t:eq(code({}, nil), Err.ARG, "junk") t:eq(code(a, { layer = 1 }), Err.ARG, "layer I") t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps") + t:eq(code(a, { bitrate = 100000 }), Err.ARG, "100000 bit/s") t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode") t:eq(code(a, { sampleRate = 44000 }), Err.ARG, "opts.sampleRate 44 kHz") t:eq(code(a, { layer = 2, sampleRate = 8000 }), Err.ARG, "layer II at 8 kHz") diff --git a/tests/audio/opus_encode.luau b/tests/audio/opus_encode.luau index c3aeff4..f1c6507 100644 --- a/tests/audio/opus_encode.luau +++ b/tests/audio/opus_encode.luau @@ -85,6 +85,9 @@ do t:check(again, "encode from a decoder: " .. tostring(err)) local back = Opus.decode(Bytes.reader(again :: buffer)) :: any t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length") + -- values below 1000 are kbit/s: the same file as the bit/s value + local kb = Opus.encode(Opus.open(Bytes.reader(files[1] :: buffer)) :: any, { bitrate = 64 }) + t:check(kb ~= nil and buffer.tostring(kb :: buffer) == buffer.tostring(again :: buffer), "bitrate 64 = 64000 bit/s") end -- errors diff --git a/tests/font/bmfont.luau b/tests/font/bmfont.luau index 46ae665..5f4bb60 100644 --- a/tests/font/bmfont.luau +++ b/tests/font/bmfont.luau @@ -137,6 +137,32 @@ do -- an outline font saved as fnt is baked on the way local fnt = F.convert(Fx.ttf, "fnt", { px = 16 }) t:check(fnt and string.sub(buffer.tostring(fnt), 1, 9) == "info face", "F.convert ttf -> fnt (text)") + -- the baked pages: returned as the third value without a destination ({ [page file] = PNG bytes }) ... + local desc, derr, pages = F.save(ttf, nil, { format = "bmfont", px = 16, chars = "Hi" }) + t:check(desc and derr == nil and type(pages) == "table", "F.save(ttf, bmfont) returns the pages") + local png = pages and pages["font_0.png"] + t:check(png and F.detect(png) == "png", "page 0 as PNG under the descriptor's name") + local again = F.font.load(desc, { loadPage = function(file: string): any + return pages and pages[file] + end }) + local hg = again and again:rasterize(again:glyphIndex(string.byte("H"))) + local ref = Bmfont.bake(ttf, { px = 16, chars = "Hi" }) + local rg = ref:rasterize(ref:glyphIndex(string.byte("H"))) + t:check(hg and rg and Crc32.of(hg.pixels) == Crc32.of(rg.pixels), "the saved page gives the baked glyph back") + -- ... or into the caller's opts.files (then not returned), named after opts.name / opts.file + local mine = {} + local d2, _, p2 = F.save(ttf, nil, { format = "bmfont", px = 16, chars = "Hi", files = mine, name = "ui.fnt" }) + t:check(d2 and p2 == nil and mine["ui_0.png"] ~= nil, "opts.files filled, pages named after opts.name") + t:check(string.find(buffer.tostring(d2), 'file="ui_0.png"', 1, true) ~= nil, "descriptor names the page") + local _, _, p3 = F.save(ttf, nil, { format = "bmfont", px = 16, chars = "Hi", file = "x" }) + t:check(p3 and p3["x_0.png"] ~= nil, "opts.file sets the prefix") + -- a loaded BMFont with its pages: re-saved with them; without pages: the descriptor alone + local _, _, p4 = F.save(again, nil, { format = "bmfont" }) + t:check(p4 == nil or p4["font_0.png"] ~= nil, "lazy pages not loaded: descriptor only") + local _, _, p5 = F.save(ref, nil, { format = "bmfont" }) + t:check(p5 and p5["font_0.png"] ~= nil, "a baked font re-saved with its pages") + -- direct calls without the hooks: no pages, no error + t:check(Bmfont.encode(ttf, { px = 16, chars = "Hi", files = {} }) ~= nil, "encode without encodeImage") end -- 6. errors and validation diff --git a/tests/music/midi.luau b/tests/music/midi.luau index a906337..78f4aa6 100644 --- a/tests/music/midi.luau +++ b/tests/music/midi.luau @@ -169,6 +169,23 @@ do t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil") end +-- track.name is written as a 0x03 meta event at tick 0 when the track has none; an existing one wins +do + local m = Types.Midi.new(96) + local notes = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } }, { tick = 96, type = "noteOff", channel = 0, data = { 60, 0 } } } + m.tracks[1] = { name = "Lead", events = notes } + m.tracks[2] = { name = "Ignored", events = { { tick = 0, type = "meta", meta = 0x03, data = { string.byte("Bass", 1, -1) } } } } + m.tracks[3] = { name = "", events = {} } + local back = decode(Midi.encode(m) :: buffer) + t:eq(back.tracks[1].name, "Lead", "track.name written") + local first = back.tracks[1].events[1] + t:check(first.type == "meta" and first.meta == 0x03 and first.tick == 0, "as a 0x03 event at tick 0") + t:eq(#back.tracks[1].events, 4, "name + 2 notes + end of track") + t:eq(back.tracks[2].name, "Bass", "the track's own 0x03 event wins") + t:eq(back.tracks[3].name, nil, "empty name: nothing written") + t:eq(#m.tracks[1].events, 2, "the caller's events are not changed") +end + -- crafted bad files for _, c in Bad do local ok, m, err = pcall(decode, c.data) diff --git a/tests/ops/layerops.luau b/tests/ops/layerops.luau index 1a12b03..03e43c2 100644 --- a/tests/ops/layerops.luau +++ b/tests/ops/layerops.luau @@ -110,6 +110,19 @@ do g.opacity = 0.5 local r3 = get(LayerOps.flatten(doc({ bottom, g }))) t:check(math.abs(r3 - 150) <= 1, "pass-through opacity mixes before / after: " .. r3) + -- a pass-through group's mask limits its effect: black hides it, grey mixes, outside the mask = its default + g.opacity = 1 + local m = Types.Image.new(1, 1, "gray8") + g.mask = { image = m, x = 0, y = 0, default = 255 } + t:eq((get(LayerOps.flatten(doc({ bottom, g })))), 200, "pass-through: black mask hides the group") + buffer.writeu8(m.pixels, 0, 128) + local r4 = get(LayerOps.flatten(doc({ bottom, g }))) + t:check(math.abs(r4 - 150) <= 1, "pass-through: grey mask mixes: " .. r4) + g.mask = { image = m, x = 3, y = 3, default = 0 } + t:eq((get(LayerOps.flatten(doc({ bottom, g })))), 200, "pass-through: outside the mask, default black") + g.mask.disabled = true + t:check(math.abs(get(LayerOps.flatten(doc({ bottom, g }))) - 100) <= 1, "pass-through: disabled mask ignored") + g.mask = nil end -- frames, leaves, flattenFrames do diff --git a/tests/ops/musicops.luau b/tests/ops/musicops.luau new file mode 100644 index 0000000..e9bf392 --- /dev/null +++ b/tests/ops/musicops.luau @@ -0,0 +1,157 @@ +-- ops/MusicOps tests (F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note) and the +-- music-as-audio bridges of the api: F.save / F.convert of a Module or a Midi to an audio format (rendered, render +-- options through opts), F.audio.open / F.audio.load of music bytes. Everything is built here (no fixtures). +local T = require("@tests/T") +local F = require("@formats") +local Err = require("@formats/core/Err") + +local t = T.suite("musicops") + +-- a 1 s 440 Hz sine at 8363 Hz (MOD's C-4 rate) +local function sine(rate: number, frames: number): any + local a = F.Types.Audio.new(rate, 1, frames) + for i = 0, frames - 1 do + buffer.writef32(a.samples, i * 4, math.sin(i / rate * 2 * math.pi * 440) * 0.5) + end + return a +end + +-- note names +do + t:eq(F.music.note("C-0"), 1, "C-0") + t:eq(F.music.note("C-4"), 49, "C-4") + t:eq(F.music.note("c#4"), 50, "C#4") + t:eq(F.music.note("Db4"), 50, "Db4") + t:eq(F.music.note("B-9"), 120, "B-9") + t:eq(F.music.note("off"), 255, "key off") + t:eq(F.music.note("cut"), 254, "note cut") + t:eq(F.music.note(61), 61, "a number") + for _, badNote in { "H-4", "C-", 121, "Cb0", {}, -1 } do + local n, e = F.music.note(badNote) + t:check(n == nil and e and e.code == Err.ARG, "bad note " .. tostring(badNote)) + end +end + +-- a MOD built from scratch: saved, reloaded, rendered +local a = sine(8363, 8363) +local song = assert(F.music.new({ format = "mod", channels = 4, title = "demo", speed = 3 })) +do + t:eq(song.kind, "music", "kind") + t:eq(song.meta.source.format, "mod", "source format") + local s = assert(F.music.addSample(song, { name = "sine", audio = a, loop = "forward", volume = 48 })) + t:eq(s, 1, "sample number") + local p = assert(F.music.addPattern(song)) + t:eq(p, 0, "pattern number") + t:eq(#song.order, 1, "appended to the order") + t:check(F.music.setCell(song, p, 0, 1, { note = "C-4", instrument = s }), "setCell") + t:check(F.music.setCell(song, p, 32, 2, { note = "E-4", instrument = s, effect = 0xC, param = 32 }), "setCell 2") + local c = assert(F.music.getCell(song, p, 32, 2)) + t:check(c.note == 53 and c.instrument == 1 and c.effect == 0xC and c.param == 32 and c.volume == 0, "getCell") + -- bad arguments + local _, e1 = F.music.setCell(song, p, 64, 1, {}) + t:check(e1 and e1.code == Err.ARG, "row out of range") + local _, e2 = F.music.setCell(song, p, 0, 5, {}) + t:check(e2 and e2.code == Err.ARG, "channel out of range") + local _, e3 = F.music.setCell(song, 7, 0, 1, {}) + t:check(e3 and e3.code == Err.ARG, "no such pattern") + local _, e4 = F.music.setCell(song, p, 0, 1, { param = 300 }) + t:check(e4 and e4.code == Err.ARG, "param out of range") + local _, e5 = F.music.addInstrument(song, { sample = 1 }) + t:check(e5 and e5.code == Err.ARG, "MOD has no instruments") + local _, e6 = F.music.new({ format = "mid" }) + t:check(e6 and e6.code == Err.ARG, "unknown tracker format") + local _, e7 = F.music.addSample(song, { audio = F.Types.Audio.new(8000, 3, 4) }) + t:check(e7 and e7.code == Err.ARG, "3-channel sample") + local _, e8 = F.music.addPattern({} :: any) + t:check(e8 and e8.code == Err.ARG, "not a module") + + local mod = assert(F.save(song)) -- the source format + t:eq(F.detect(mod), "mod", "saved as MOD") + local back = assert(F.music.load(mod)) + t:eq(back.title, "demo", "title round trip") + t:check(back.samples[1].loopType == 1 and back.samples[1].volume == 48, "sample loop / volume round trip") + local c2 = assert(F.music.getCell(back, 0, 32, 2)) + t:check(c2.note == 53 and c2.instrument == 1 and c2.effect == 0xC and c2.param == 32, "cells round trip") + local dec = assert(song:render({ sampleRate = 22050 })) + local au = assert(F.ops.audio.toAudio(dec)) + t:check(au.frames > 22050 and F.ops.audio.peak(au) > 0.05, "renders sound") +end + +-- an XM with an instrument and a volume envelope +do + local xm = assert(F.music.new({ format = "xm", channels = 2 })) + local s = assert(F.music.addSample(xm, { audio = a, rate = 16726 })) -- an octave up: relativeNote 12 + t:eq(xm.samples[s].relativeNote, 12, "rate -> relativeNote") + t:eq(xm.samples[s].finetune, 0, "rate -> finetune") + local i = assert(F.music.addInstrument(xm, { name = "lead", sample = s, fadeout = 512, envelope = { points = { { 0, 64 }, { 10, 32 }, { 40, 0 } }, sustain = 2 } })) + local p = assert(F.music.addPattern(xm, 32)) + assert(F.music.setCell(xm, p, 0, 1, { note = "C-4", instrument = i })) + assert(F.music.setCell(xm, p, 16, 1, { note = "off" })) + local back = assert(F.music.load(assert(F.save(xm)))) + t:check(back.format == "xm" and #back.instruments == 1 and back.instruments[1].name == "lead", "XM instrument round trip") + t:check(back.instruments[1].volEnv and back.instruments[1].volEnv.enabled and #back.instruments[1].volEnv.ticks == 3, "XM envelope round trip") + local _, ebad = F.music.addInstrument(xm, { sample = 9 }) + t:check(ebad and ebad.code == Err.ARG, "instrument on a missing sample") + local _, eenv = F.music.addInstrument(xm, { envelope = { points = { { 5, 10 }, { 5, 20 } } } }) + t:check(eenv and eenv.code == Err.ARG, "envelope ticks must increase") +end + +-- music saved and converted as audio: rendered, with the render options from opts +do + local wav = assert(F.save(song, nil, { format = "wav", sampleRate = 22050 })) + local au = assert(F.audio.load(wav)) + t:check(au.sampleRate == 22050 and au.channels == 2 and au.frames > 0, "F.save(module, wav) renders") + local mod = assert(F.save(song)) + local w2 = assert(F.convert(mod, "wav", { sampleRate = 11025 })) + t:eq(F.detect(w2), "wav", "F.convert(mod, wav)") + t:eq((assert(F.audio.load(w2))).sampleRate, 11025, "convert passes sampleRate to the render") + t:check(F.audio.save(song, nil, { format = "flac" }) ~= nil, "F.audio.save(module)") + + local m = F.Types.Midi.new(480) + table.insert(m.tracks, { events = { + { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } }, + { tick = 480, type = "noteOff", channel = 0, data = { 60, 0 } }, + } }) + local mw = assert(F.save(m, nil, { format = "wav", tail = 0.5 })) -- a hand-built Midi (no render method) + local ma = assert(F.audio.load(mw)) + t:eq(ma.frames, math.floor(1.0 * 44100 + 0.5), "Midi rendered: 0.5 s of notes + 0.5 s tail") + local mid = assert(F.save(m, nil, { format = "midi" })) + t:eq(F.detect(assert(F.convert(mid, "wav"))), "wav", "F.convert(midi, wav)") + + -- F.audio.open / load of music bytes: the rendered Decoder + local d1 = assert(F.audio.open(mid, { tail = 0 })) + t:check(d1.channels == 2 and d1.sampleRate == 44100 and d1.frames == 22050, "F.audio.open(midi)") + local d2 = assert(F.audio.open(mod)) + t:check(d2.channels == 2 and d2.frames > 0, "F.audio.open(mod)") + local a2 = assert(F.audio.load(mod, { sampleRate = 8000 })) + t:check(a2.kind == "audio" and a2.sampleRate == 8000, "F.audio.load(mod)") + local d3 = assert(F.audio.open(mod, { format = "mod" })) + t:check(d3.frames > 0, "F.audio.open with format = mod") + -- still an error for data no format reads + local _, e = F.audio.open(buffer.fromstring("not audio at all")) + t:check(e and e.code == Err.UNKNOWN_FORMAT, "unknown data") + -- and a soundfont is not audio + local _, e2 = F.audio.save(m, nil, { format = "png" }) + t:check(e2 ~= nil, "music to a non-audio format fails") +end + +-- no throws on random cell / sample arguments +do + local rng = T.rng(7) + local ok = true + for _ = 1, 300 do + local vals = { rng(300) - 20, "C-4", nil, {}, -1, 0.5, 1e9 } + local pick = function(): any + return vals[rng(#vals) + 1] + end + local pok = pcall(function() + F.music.setCell(song, pick(), pick(), pick(), { note = pick(), instrument = pick(), param = pick() }) + F.music.getCell(song, pick(), pick(), pick()) + F.music.addSample(song, { data = buffer.create(rng(16)), length = pick(), loop = "forward", loopStart = pick(), loopEnd = pick() }) + end) + ok = ok and pok + end + t:check(ok, "random arguments never throw") +end + +t:done() diff --git a/tests/video/_common.luau b/tests/video/_common.luau index 39902ed..63988d0 100644 --- a/tests/video/_common.luau +++ b/tests/video/_common.luau @@ -152,6 +152,21 @@ function C.audio(t: any, v: any, c: any, label: string, exact: boolean?, minSnr: end local n = got * a.channels t:check(n == want or n * 4 == c.pcmBytes, label .. ": " .. n .. " samples read of " .. want) + -- the whole stream: as long as ffmpeg's decode (priming and end padding trimmed the same way: MP4 edit lists). + -- Not yet for Matroska / WebM, where ffmpeg also cuts the end padding of the last packets (Vorbis, MP2: a few + -- hundred frames) and we do not. + if c.pcmBytes and v.format ~= "mkv" and v.format ~= "webm" then + local total = got + while true do + local _, k = a:read(4096) + if not k or k <= 0 then + break + end + total += k + end + t:eq(total * a.channels * 4, c.pcmBytes, label .. ": decoded length = ffmpeg's (" .. total .. " frames)") + a:seek(0) + end n = math.min(n, want) if exact then local same = true @@ -180,6 +195,12 @@ function C.seek(t: any, v: any, c: any, label: string, at: number) v:seek(at) local f = v:nextFrame() t:check(f ~= nil and f.pts >= at - 1e-6 and f.pts < at + 0.2, label .. ": seek to " .. at .. " lands at " .. tostring(f and f.pts)) + if f and v.frameRate > 0 then + -- frame.index restarts at the seek position (not counted on from before the seek) + t:eq(f.index, math.floor(f.pts * v.frameRate + 0.5) + 1, label .. ": frame index after seeking") + local g = v:nextFrame() + t:check(g == nil or g.index == f.index + 1, label .. ": index counts on after the seek") + end if f and C.EXACT[v.codec] and c.frames then local idx = math.floor(f.pts * v.frameRate + 0.5) + 1 t:eq(Crc32.of(f.image.pixels), c.frames[idx], label .. ": the frame after seeking equals ffmpeg's frame " .. idx) diff --git a/tests/video/encode.luau b/tests/video/encode.luau index ef009a7..d258c28 100644 --- a/tests/video/encode.luau +++ b/tests/video/encode.luau @@ -113,4 +113,61 @@ do t:check(out ~= nil and buffer.tostring(out) == gifAvi.data, "gif.avi: F.convert(gif, 'avi') again byte for byte") end end +-- frame.index after seek on a demuxed video (MJPEG AVI at 10 fps): the frame's own position, then counting on +local function gradient(n: number): { any } + local imgs = {} + for i = 1, n do + local im = assert(F.ops.image.new(16, 8)) + F.ops.image.fill(im, i * 12, 0, 255 - i * 12) + imgs[i] = im + end + return imgs +end +local avi = assert(F.save(assert(F.video.fromFrames(gradient(20), 0.1)), nil, { format = "avi", quality = 90 })) +do + local v = assert(F.video.open(avi)) + for i = 1, 3 do + t:eq((v:nextFrame() :: any).index, i, "index before seeking " .. i) + end + v:seek(1.0) + local f = v:nextFrame() :: any + t:check(f.index == 11 and math.abs(f.pts - 1.0) < 1e-6, "seek(1.0): frame 11") + t:eq((v:nextFrame() :: any).index, 12, "then 12") + v:seek(0.25) + t:eq((v:nextFrame() :: any).index, 4, "seek back to 0.25: frame 4 (0.3 s)") + v:reset() + t:eq((v:nextFrame() :: any).index, 1, "reset: frame 1") +end + +-- a video saved as an animated image (GIF / APNG / WebP): every frame with its timing, or frames / fps / maxFrames +do + local gif = assert(F.convert(avi, "gif")) + t:eq(F.detect(gif), "gif", "convert(avi, gif)") + local g = assert(F.image.load(gif)) + t:check(#g.frames == 20 and math.abs(g.frames[1].delay - 0.1) < 1e-9 and g.width == 16 and g.height == 8, "gif: 20 frames of 0.1 s") + local g2 = assert(F.image.load(assert(F.convert(avi, "gif", { fps = 5 })))) + t:check(#g2.frames == 10 and math.abs(g2.frames[1].delay - 0.2) < 1e-9, "fps = 5: 10 frames of 0.2 s") + local g3 = assert(F.image.load(assert(F.convert(avi, "gif", { fps = 20 })))) + local total = 0 + for _, fr in g3.frames do + total += fr.delay + end + t:check(#g3.frames == 20 and math.abs(total - 2) < 0.02, "fps above the source: frames held, total 2 s") + t:eq(#(assert(F.image.load(assert(F.convert(avi, "gif", { frames = 4 })))) :: any).frames, 4, "frames = 4") + t:eq(#(assert(F.image.load(assert(F.convert(avi, "gif", { maxFrames = 7 })))) :: any).frames, 7, "maxFrames = 7") + t:eq(#(assert(F.image.load(assert(F.convert(avi, "gif", { maxPixels = 16 * 8 * 5 })))) :: any).frames, 5, "maxPixels caps the frames") + local apng = assert(F.save(assert(F.video.open(avi)), nil, { format = "apng" })) + local a = assert(F.image.load(apng)) + t:check(F.detect(apng) == "png" and #a.frames == 20, "save(video, apng)") + local webp = assert(F.save(assert(F.video.open(avi)), nil, { format = "webp" })) + t:check(F.detect(webp) == "webp" and #(assert(F.image.load(webp)) :: any).frames == 20, "save(video, webp)") + -- the frames are the decoded pictures: the GIF's first frame is the MJPEG frame (lossy, palette) + local v = assert(F.video.open(avi)) + local first = v:toRGBA(v:nextFrame()) + local r1 = buffer.readu8(first.pixels, 0) + t:check(math.abs(buffer.readu8(g.pixels, 0) - r1) <= 8, "gif frame 1 matches the decoded frame") + local _, e = F.save(assert(F.video.open(avi)), nil, { format = "gif", fps = -1 }) + t:check(e and e.code == F.Err.ARG, "bad fps") +end + t:done() diff --git a/tests/video/mkv.luau b/tests/video/mkv.luau index 560eb66..996ffd9 100644 --- a/tests/video/mkv.luau +++ b/tests/video/mkv.luau @@ -88,6 +88,16 @@ do t:eq(len, 160, "lacing: EBML-laced frame size") end +-- F.detect names WebM files (DocType webm) "webm", Matroska files "mkv"; both open through the mkv format +do + t:eq(F.detect(byName["vp8_opus.webm"].data), "webm", "detect: webm") + t:eq(F.detect(byName["mjpeg_pcm.mkv"].data), "mkv", "detect: mkv") + t:eq(Mkv.variant(Bytes.reader(buffer.fromstring(byName["vp8_opus.webm"].data))), "webm", "variant: webm") + t:eq(Mkv.variant(Bytes.reader(buffer.fromstring(byName["mjpeg_pcm.mkv"].data))), nil, "variant: matroska") + t:eq(Mkv.variant(Bytes.reader(buffer.fromstring("\26\69\223\163"))), nil, "variant: truncated") + t:eq(F.format("webm").name, "mkv", "format(webm) is mkv") +end + -- 4. our muxer: remux WebM (VP8 + Opus copied) and read it back packet for packet do local src = byName["vp8_opus.webm"] diff --git a/tests/video/mp4.luau b/tests/video/mp4.luau index 9ff4d7a..fa314a5 100644 --- a/tests/video/mp4.luau +++ b/tests/video/mp4.luau @@ -62,6 +62,16 @@ for _, job in { { "mjpeg_aac.mp4", "mp4" }, { "mjpeg_pcm.mov", "mov" }, { "h264_ end end t:check(same, "write " .. job[1] .. ": same packets and times") + -- copied AAC keeps its edit list: priming and end padding cut as in the source (ffmpeg's length) + local at = a:track("audio") + if at and at.codec == "aac" then + local bt = b:track("audio") + t:check(bt and bt.playDuration and math.abs(bt.playDuration - at.playDuration) < 1e-3 and math.abs((bt.codecDelay or 0) - (at.codecDelay or 0)) < 1e-6, "write " .. job[1] .. ": edit list kept") + if v2.audio and src.pcmBytes then + local all = assert(F.ops.audio.toAudio(v2.audio)) + t:eq(all.frames * all.channels * 4, src.pcmBytes, "write " .. job[1] .. ": AAC length = ffmpeg's decode of the source") + end + end end end end diff --git a/tools/lint_types_baseline.txt b/tools/lint_types_baseline.txt index c67f579..cd5b025 100644 --- a/tools/lint_types_baseline.txt +++ b/tools/lint_types_baseline.txt @@ -1 +1 @@ -93 +92