Decode Ogg Vorbis through a pinned stb_vorbis
audio/ogg_vorbis inspects Ogg Vorbis portably: audio/ogg's reader checks every page, then the identification, comment and setup headers are parsed and the setup header's mode table is read backwards from its framing bit, so each audio packet's block size and every granule position are checked. The exact frame count is the final granule position. Chained or multiplexed streams, timeline offsets, more than two channels and rates outside 8-192 kHz are Unsupported; truncation, CRC errors and granule mismatches are Malformed. Vorbis comments are copied and read by index or case-insensitive field name. audio/vorbis decodes through stb_vorbis 1.24 (nothings/stb 9600522d, public domain or MIT), compiled by native/ziran_vorbis.c into libziran_vorbis.a: open from memory or a file, float and s16 streaming, whole-file decode, exact seek and rewind. The read call keeps decoding past frames that return no samples, which stb_vorbis' own interleaved reader treats as the end. audio/vorbis_resample adds the best-sinc resampler. The CLI detects Vorbis next to Opus for inspect, decode, resample and transcode. Vorbis contracts decode five FFmpeg/libvorbis fixtures within 0.501 PCM16 steps of FFmpeg, check exact lengths, streaming, s16, seeks, comments, synthetic and malformed streams and 600 corrupted decodes, and pass under ASan and UBSan. The Windows and Android runs cover the Vorbis fixtures too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
5ea3f6f1ae
commit
ce5837f80e
34 files changed
+1445
-110
No files matched your search
@@ -1,23 +1,24 @@
|
||||
ZIRAN ?= ziran
|
||||
CMAKE ?= cmake
|
||||
.PHONY: all test sanitize-test android-test windows-test
|
||||
# libziran_mp3.a (dr_mp3 from the pinned dr_libs source) into DIR:
|
||||
# $(call mp3_archive,DIR,CMAKE-ARGUMENTS)
|
||||
mp3_archive = mkdir -p $(1) && $(CMAKE) -S native -B $(1) -DDR_LIBS_DIR="$$($(ZIRAN) pkg path dr_libs --offline)" $(2) >$(1)/configure.log && $(CMAKE) --build $(1) --target ziran_mp3 >$(1)/build.log
|
||||
LINUX_MP3 := build/native/linux
|
||||
# libziran_mp3.a (dr_mp3 from the pinned dr_libs source) and
|
||||
# libziran_vorbis.a (stb_vorbis from the pinned stb source) into DIR:
|
||||
# $(call decoder_archives,DIR,CMAKE-ARGUMENTS)
|
||||
decoder_archives = mkdir -p $(1) && $(CMAKE) -S native -B $(1) -DDR_LIBS_DIR="$$($(ZIRAN) pkg path dr_libs --offline)" -DSTB_DIR="$$($(ZIRAN) pkg path stb --offline)" $(2) >$(1)/configure.log && $(CMAKE) --build $(1) --target ziran_mp3 ziran_vorbis >$(1)/build.log
|
||||
LINUX_NATIVE := build/native/linux
|
||||
SANITIZE := -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all
|
||||
|
||||
all:
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY sh -c '$(call mp3_archive,$(LINUX_MP3),-DCMAKE_BUILD_TYPE=Release) && LDLIBS="-L$(LINUX_MP3) -lziran_mp3 -lopus -lsamplerate -lm" $(ZIRAN) build --target=c --exe --root src --module-path src --entry audio:main -o build/bin src/audio.zi'
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY sh -c '$(call decoder_archives,$(LINUX_NATIVE),-DCMAKE_BUILD_TYPE=Release) && LDLIBS="-L$(LINUX_NATIVE) -lziran_mp3 -lziran_vorbis -lopus -lsamplerate -lm" $(ZIRAN) build --target=c --exe --root src --module-path src --entry audio:main -o build/bin src/audio.zi'
|
||||
|
||||
test:
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN='$(ZIRAN)' sh -c '$(call mp3_archive,$(LINUX_MP3),-DCMAKE_BUILD_TYPE=Release) && sh tests/audio.sh'
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN='$(ZIRAN)' sh -c '$(call decoder_archives,$(LINUX_NATIVE),-DCMAKE_BUILD_TYPE=Release) && sh tests/audio.sh'
|
||||
|
||||
# The native contracts (Opus, sinc and every MP3 contract) with dr_mp3 and
|
||||
# the generated C under AddressSanitizer and UndefinedBehaviorSanitizer;
|
||||
# dr_mp3 keeps its assertions (Debug).
|
||||
# The native contracts (Opus, sinc and every MP3 and Vorbis contract) with
|
||||
# dr_mp3, stb_vorbis and the generated C under AddressSanitizer and
|
||||
# UndefinedBehaviorSanitizer; both decoders keep their assertions (Debug).
|
||||
sanitize-test:
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY sh -c '$(call mp3_archive,build/native/sanitize,-DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="$(SANITIZE)") && CFLAGS="$(SANITIZE)" LDFLAGS="-fsanitize=address,undefined" LDLIBS="-Lbuild/native/sanitize -lziran_mp3 -lopus -lsamplerate -lm" $(ZIRAN) build --target=c --exe --root tests --module-path src --entry contracts:main -o build/tests/sanitize tests/contracts.zi && ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1 build/tests/sanitize/contracts'
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY sh -c '$(call decoder_archives,build/native/sanitize,-DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="$(SANITIZE)") && CFLAGS="$(SANITIZE)" LDFLAGS="-fsanitize=address,undefined" LDLIBS="-Lbuild/native/sanitize -lziran_mp3 -lziran_vorbis -lopus -lsamplerate -lm" $(ZIRAN) build --target=c --exe --root tests --module-path src --entry contracts:main -o build/tests/sanitize tests/contracts.zi && ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1 build/tests/sanitize/contracts'
|
||||
|
||||
# Needs `make test` fixtures; ANDROID_SERIAL=SERIAL also runs them on a device.
|
||||
android-test:
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Audio for Ziran
|
||||
|
||||
Reusable Opus encoding/decoding, MP3 decoding, Ogg Opus and MPEG audio
|
||||
inspection, best-quality sinc sample-rate conversion and WAV I/O, with a
|
||||
native `audio` command. There is
|
||||
Reusable Opus encoding/decoding, MP3 and Ogg Vorbis decoding, Ogg Opus, Ogg
|
||||
Vorbis and MPEG audio inspection, best-quality sinc sample-rate conversion and
|
||||
WAV I/O, with a native `audio` command. There is
|
||||
no Kryon, Raylib, audio-device or runtime subprocess dependency. GUI hosts
|
||||
choose their own playback sink and call the same modules as command-line tools.
|
||||
|
||||
@@ -10,9 +10,10 @@ choose their own playback sink and call the same modules as command-line tools.
|
||||
|
||||
Install Ziran, CMake plus the development/link libraries for **libopus** and
|
||||
**libsamplerate** (`libopus-dev` and `libsamplerate0-dev` on Debian-family
|
||||
Linux). The MP3 decoder is compiled from the pinned `dr_libs` source: `make`
|
||||
builds `build/native/linux/libziran_mp3.a` through `native/CMakeLists.txt`
|
||||
before the CLI. Then run:
|
||||
Linux). The MP3 and Vorbis decoders are compiled from the pinned `dr_libs`
|
||||
and `stb` sources: `make` builds `build/native/linux/libziran_mp3.a` and
|
||||
`build/native/linux/libziran_vorbis.a` through `native/CMakeLists.txt` before
|
||||
the CLI. Then run:
|
||||
|
||||
```sh
|
||||
make
|
||||
@@ -26,10 +27,14 @@ build/bin/audio resample input.wav speech.wav --rate 16000
|
||||
build/bin/audio inspect song.mp3
|
||||
build/bin/audio decode song.mp3 song.wav
|
||||
build/bin/audio resample song.mp3 song-48k.wav --rate 48000
|
||||
build/bin/audio inspect music.ogg
|
||||
build/bin/audio decode music.ogg music.wav
|
||||
build/bin/audio resample music.ogg music-48k.wav --rate 48000
|
||||
```
|
||||
|
||||
Formats are chosen from the content, not the file name: `OggS` is Ogg
|
||||
Opus, `RIFF` is WAV, anything else is read as MPEG audio. `inspect` on an
|
||||
Formats are chosen from the content, not the file name: `OggS` whose first
|
||||
packet is a Vorbis identification header is Ogg Vorbis, any other `OggS` is
|
||||
Ogg Opus, `RIFF` is WAV, anything else is read as MPEG audio. `inspect` on an
|
||||
MP3 prints the MPEG version and layer, channels, rate, exact frames and
|
||||
duration, bitrate, VBR or CBR, the LAME delay/padding and the frame count:
|
||||
|
||||
@@ -37,15 +42,29 @@ duration, bitrate, VBR or CBR, the LAME delay/padding and the frame count:
|
||||
MP3: MPEG-1 Layer III, 2 channels, 44100 Hz, 13230 frames, 0.300 s, 128000 bps CBR, delay 1105, padding 641, 13 MPEG frames
|
||||
```
|
||||
|
||||
On Ogg Vorbis it prints the channels, rate, exact frames and duration, the
|
||||
nominal bitrate hint, the block sizes, mode count, end trim and packet and
|
||||
comment counts, then the vendor string and each comment (control bytes shown
|
||||
as `?`):
|
||||
|
||||
```text
|
||||
Vorbis: 1 channels, 32000 Hz, 9600 frames, 0.300 s, 52000 bps nominal, blocks 256/2048, 2 modes, end trim 0, 13 packets, 4 comments
|
||||
Vorbis vendor: ffmpeg
|
||||
Vorbis comment: encoder=Lavc libvorbis
|
||||
Vorbis comment: title=Ziran fixture
|
||||
Vorbis comment: artist=Ziran audio
|
||||
Vorbis comment: DESCRIPTION=Vorbis comments, ünïcödé
|
||||
```
|
||||
|
||||
The CLI supports PCM16 and IEEE float32 RIFF WAV input, and mapping-family-0
|
||||
Ogg Opus (mono/stereo) with the exact 19-byte version-1 identification header.
|
||||
Other Opus header versions/extensions are outside this bounded profile.
|
||||
Decoded Opus WAV output is PCM16 at 48 kHz; decoded MP3 WAV output is
|
||||
PCM16 at the stream's own rate. `resample`
|
||||
Decoded Opus WAV output is PCM16 at 48 kHz; decoded MP3 and Vorbis WAV
|
||||
output is PCM16 at the stream's own rate. `resample`
|
||||
accepts either format and writes PCM16 WAV at the requested 8000–192000 Hz
|
||||
rate. `transcode` decodes WAV/Opus and encodes Opus; it is a lossy re-encode
|
||||
when its source is already Opus or MP3. Other audio formats belong to
|
||||
separate modules; existing `std/vorbis` and `std/vorbis_linux` support is independent.
|
||||
rate. `transcode` decodes WAV, Opus, Vorbis or MP3 and encodes Opus; it is a
|
||||
lossy re-encode unless its source is WAV. Ziran's whole-file `std/vorbis` and
|
||||
`std/vorbis_linux` are independent of `audio/vorbis`.
|
||||
|
||||
Encoder options are `--bitrate` in bits/second (6000–510000), `--vbr`
|
||||
`on|off|constrained`, `--bandwidth` `auto|narrow|wide|superwide|full`,
|
||||
@@ -82,8 +101,9 @@ not play audio or open audio devices.
|
||||
## Callable modules
|
||||
|
||||
Exports are `audio/types`, `audio/ogg`, `audio/wav`, `audio/opus`,
|
||||
`audio/resample`, `audio/pipeline`, `audio/mpeg_audio`, `audio/mp3` and
|
||||
`audio/mp3_resample`.
|
||||
`audio/resample`, `audio/pipeline`, `audio/mpeg_audio`, `audio/mp3`,
|
||||
`audio/mp3_resample`, `audio/ogg_vorbis`, `audio/vorbis` and
|
||||
`audio/vorbis_resample`.
|
||||
Full-pipeline native consumers declare `links = ["opus", "samplerate", "m"]` in their
|
||||
root manifest's `[package]` table, or use equivalent linker flags in a custom
|
||||
host. Ziran does not inherit system links from dependencies. Codec-only consumers need
|
||||
@@ -91,6 +111,9 @@ only `links = ["opus", "m"]`; `audio/opus` does not import the resampler.
|
||||
MP3 decode-only consumers link `libziran_mp3.a` and `-lm`
|
||||
(`links = ["ziran_mp3", "m"]` with the archive's directory in `LDFLAGS`);
|
||||
`audio/mp3_resample` adds `samplerate`. `audio/mpeg_audio` is portable.
|
||||
Vorbis decode-only consumers likewise link `libziran_vorbis.a` and `-lm`
|
||||
(`links = ["ziran_vorbis", "m"]`); `audio/vorbis_resample` adds
|
||||
`samplerate`, and `audio/ogg_vorbis` is portable.
|
||||
|
||||
```zi
|
||||
Types :: #import "audio/types"
|
||||
@@ -187,6 +210,73 @@ decoders have one owner and must not be copied or shared across threads.
|
||||
For streaming at another rate, pass `Mp3DecoderRead` chunks to
|
||||
`SincOpen`/`SincProcess`.
|
||||
|
||||
## Ogg Vorbis
|
||||
|
||||
`audio/vorbis` decodes Ogg Vorbis (Vorbis I, floor 1, mono and stereo,
|
||||
8–192 kHz) through [stb_vorbis](https://github.com/nothings/stb) (public
|
||||
domain or MIT; its `LICENSE` is in the pinned source). The manifest pins
|
||||
`stb` at commit `9600522de53973336fa033a289858a4354cbb04c` (stb_vorbis 1.24)
|
||||
as a `source = true` dependency. `native/ziran_vorbis.c` is stb_vorbis' one
|
||||
implementation unit, built without stdio, the pushdata API, integer
|
||||
conversion or comment parsing, plus open, read and seek calls.
|
||||
Redistributors ship stb's `LICENSE` alongside the binary.
|
||||
|
||||
- `VorbisProbe([]u8) -> bool` and `VorbisInspect([]u8, *VorbisInfo) -> s32`
|
||||
(`audio/ogg_vorbis`, portable); `VorbisInspectComments([]u8, *VorbisInfo,
|
||||
*VorbisComments)` also copies the comment header
|
||||
- `VorbisDecoderOpen(*VorbisDecoder, input:[]u8, max_frames:s64) -> s32`, or
|
||||
`VorbisDecoderOpenFile(*VorbisDecoder, path, max_frames)`, which reads the
|
||||
file (at most 256 MiB) into the decoder
|
||||
- `VorbisDecoderRead(*VorbisDecoder, []float32, frames:*s64)` and
|
||||
`VorbisDecoderReadS16(*VorbisDecoder, []s16, frames:*s64)`: interleaved
|
||||
chunks of whole frames
|
||||
- `VorbisDecoderSeek(*VorbisDecoder, frame:s64)`, `VorbisDecoderRewind`, and
|
||||
the idempotent `VorbisDecoderClose`
|
||||
- `VorbisDecode([]u8, max_frames, *PCM)` and
|
||||
`VorbisDecodeS16([]u8, max_frames, *Vec(s16), *VorbisInfo)`: whole file
|
||||
- `VorbisDecodeResampled([]u8, max_frames, rate, *PCM)`
|
||||
(`audio/vorbis_resample`): whole file through `audio/resample`'s best sinc
|
||||
- `VorbisVendor`, `VorbisCommentCount`, `VorbisComment(*VorbisComments,
|
||||
index)` and `VorbisCommentValue(*VorbisComments, field)`, which matches the
|
||||
field name without regard to ASCII case; an open decoder holds its
|
||||
stream's comments in `decoder.comments`
|
||||
|
||||
`VorbisInfo` gives channels, rate, exact PCM `frames`, the header's nominal,
|
||||
maximum and minimum bitrate hints (0 when unset), the short and long block
|
||||
sizes, the mode count, audio `packets`, the comment count and `end_trim`;
|
||||
`VorbisSeconds` converts frames to seconds. `frames` is the final granule
|
||||
position, which trims the last packet, so the duration is exact without
|
||||
decoding; libvorbisfile's `ov_pcm_total` agrees on every fixture.
|
||||
|
||||
Inspection reads the whole stream before stb_vorbis sees it, because
|
||||
stb_vorbis checks neither page CRCs nor serial numbers. `audio/ogg`'s reader
|
||||
checks every page (capture, CRC, one serial, sequence, BOS/EOS, lacing).
|
||||
The identification header must be a 30-byte version-0 header on its own BOS
|
||||
page; the comment header's vendor, comments and framing bit must fit its
|
||||
packet; the setup header must end its page. The mode table is read
|
||||
backwards from the setup header's framing bit, as FFmpeg's and liboggz's
|
||||
parsers do, so every audio packet's block size, and with it each page's
|
||||
granule position, is checked: the timeline must start at zero, and the
|
||||
final granule may only trim frames that were decoded. Truncation (even one
|
||||
byte), CRC errors, trailing bytes, non-audio packets and granule mismatches
|
||||
are `Malformed`; chained or multiplexed streams (a second beginning-of-stream
|
||||
page), a timeline not starting at zero, more than two channels and rates
|
||||
outside 8000–192000 Hz are `Unsupported`. Floor 0 streams (pre-2004
|
||||
encoders) fail to open in stb_vorbis and return `Malformed`. A decoder that
|
||||
ends before the final granule position fails the read with `Malformed`.
|
||||
|
||||
Reads behave like `DecoderRead`: caller-owned interleaved scratch of whole
|
||||
frames, `OK` with zero frames at the logical end, and a failed read may have
|
||||
filled a prefix. `ziran_vorbis_read` keeps decoding past frames that return
|
||||
no samples, which stb_vorbis' own interleaved reader treats as the end. S16
|
||||
samples are the float output through `Pcm16`, as for MP3. Seeks land on the
|
||||
exact requested frame: stb_vorbis bisects the pages for the one holding it,
|
||||
then decodes forward from the packet before, so the samples after a seek
|
||||
are bit-identical to a linear decode. Input bytes are borrowed until close.
|
||||
Live decoders have one owner and must not be copied or shared across
|
||||
threads. For streaming at another rate, pass `VorbisDecoderRead` chunks to
|
||||
`SincOpen`/`SincProcess`.
|
||||
|
||||
## Incremental APIs and ownership
|
||||
|
||||
`DecoderOpen(*Decoder, input:[]u8, max_frames:s64) -> s32` validates the
|
||||
@@ -224,14 +314,15 @@ only the explicit state APIs stream PCM.
|
||||
|
||||
The manifest pins the codec sources as `source = true` dependencies:
|
||||
`libopus` (xiph/opus v1.5.2), `libsamplerate` (libsndfile/libsamplerate
|
||||
0.2.2) and `dr_libs` (mackron/dr_libs, dr_mp3 0.7.5). An NDK CMake build
|
||||
includes `native/AudioCodecs.cmake` and calls
|
||||
`ziran_audio_codecs("<libopus>" "<libsamplerate>")` and
|
||||
`ziran_audio_mp3("<dr_libs>")` with the paths from `ziran pkg path NAME`.
|
||||
They define static, position-independent `opus`, `samplerate` and
|
||||
`ziran_mp3` targets (float API; no programs, tests or DNN extensions) to
|
||||
link into the app's native library. `native/CMakeLists.txt` builds whichever
|
||||
of `OPUS_DIR`+`SAMPLERATE_DIR` and `DR_LIBS_DIR` it is given. Generate the
|
||||
0.2.2), `dr_libs` (mackron/dr_libs, dr_mp3 0.7.5) and `stb` (nothings/stb,
|
||||
stb_vorbis 1.24). An NDK CMake build includes `native/AudioCodecs.cmake` and
|
||||
calls `ziran_audio_codecs("<libopus>" "<libsamplerate>")`,
|
||||
`ziran_audio_mp3("<dr_libs>")` and `ziran_audio_vorbis("<stb>")` with the
|
||||
paths from `ziran pkg path NAME`. They define static, position-independent
|
||||
`opus`, `samplerate`, `ziran_mp3` and `ziran_vorbis` targets (float API; no
|
||||
programs, tests or DNN extensions) to link into the app's native library.
|
||||
`native/CMakeLists.txt` builds whichever of `OPUS_DIR`+`SAMPLERATE_DIR`,
|
||||
`DR_LIBS_DIR` and `STB_DIR` it is given. Generate the
|
||||
app's C with `--target-os android` and `--target-cpu` (`arm64`, `x64`, or
|
||||
`none` for 32-bit ABIs) plus Breeze's Android defines, `--define
|
||||
ANDROID_BUILD` and the ABI's `__aarch64__`, `__arm__`, `__i386__` or
|
||||
@@ -244,35 +335,39 @@ NDK 28.2.13676358 at API 21 for arm64-v8a, armeabi-v7a, x86 and x86_64
|
||||
(`ANDROID_NDK_HOME`, `ANDROID_API` and `ANDROID_ABIS` override this). With
|
||||
`ANDROID_SERIAL=SERIAL` it runs inspect, decode, resample and encode on that
|
||||
device and compares the output with the Linux CLI, including the nine MP3
|
||||
fixtures (inspect and decode) and an MP3 resampled to 48 kHz. On a Moto e6
|
||||
play (armeabi-v7a, Android 9), decoded and resampled PCM16 matched Linux
|
||||
exactly, MP3 included, and the device-encoded stream decoded on Linux at the
|
||||
source duration. The other three ABIs are build-tested only. Native
|
||||
consumers link `libziran_mp3.a` from `ziran_audio_mp3` with `-lm`.
|
||||
and six Vorbis fixtures (inspect and decode) and an MP3 and a Vorbis stream
|
||||
resampled to 48 kHz. On a Moto e6 play (armeabi-v7a, Android 9), decoded and
|
||||
resampled PCM16 matched Linux exactly, MP3 and Vorbis included, and the
|
||||
device-encoded stream decoded on Linux at the source duration. The other three ABIs are build-tested only. Native
|
||||
consumers link `libziran_mp3.a` from `ziran_audio_mp3` and
|
||||
`libziran_vorbis.a` from `ziran_audio_vorbis` with `-lm`.
|
||||
|
||||
## Windows
|
||||
|
||||
The same recipe builds static `libopus.a`, `libsamplerate.a` and
|
||||
`libziran_mp3.a` for x86_64 MinGW. With the pinned sources from `ziran pkg path`:
|
||||
The same recipe builds static `libopus.a`, `libsamplerate.a`,
|
||||
`libziran_mp3.a` and `libziran_vorbis.a` for x86_64 MinGW. With the pinned
|
||||
sources from `ziran pkg path`:
|
||||
|
||||
```sh
|
||||
cmake -S native -B build/windows/native -DCMAKE_SYSTEM_NAME=Windows \
|
||||
-DCMAKE_SYSTEM_PROCESSOR=AMD64 -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc \
|
||||
-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY -DCMAKE_BUILD_TYPE=Release \
|
||||
-DOPUS_DIR="$(ziran pkg path libopus)" -DSAMPLERATE_DIR="$(ziran pkg path libsamplerate)" \
|
||||
-DDR_LIBS_DIR="$(ziran pkg path dr_libs)"
|
||||
-DDR_LIBS_DIR="$(ziran pkg path dr_libs)" -DSTB_DIR="$(ziran pkg path stb)"
|
||||
cmake --build build/windows/native
|
||||
```
|
||||
|
||||
The archives are `build/windows/native/libopus/libopus.a`,
|
||||
`build/windows/native/libsamplerate/src/libsamplerate.a` and
|
||||
`build/windows/native/libziran_mp3.a` (a CMake consumer calls
|
||||
`ziran_audio_codecs`/`ziran_audio_mp3` and links the `opus`/`ziran_mp3`
|
||||
targets). Generate C with
|
||||
`build/windows/native/libsamplerate/src/libsamplerate.a`,
|
||||
`build/windows/native/libziran_mp3.a` and
|
||||
`build/windows/native/libziran_vorbis.a` (a CMake consumer calls
|
||||
`ziran_audio_codecs`/`ziran_audio_mp3`/`ziran_audio_vorbis` and links the
|
||||
`opus`/`ziran_mp3`/`ziran_vorbis` targets). Generate C with
|
||||
`--define _WIN32 --define __x86_64__`; no other define is needed. libopus
|
||||
keeps its default stack protector and `_FORTIFY_SOURCE=2`, so a MinGW link
|
||||
adds GCC's `-lssp` after the archives: decoder-only consumers link
|
||||
`libopus.a -lssp -lm` (plus `libziran_mp3.a` before it for MP3),
|
||||
`libopus.a -lssp -lm` (plus `libziran_mp3.a` and `libziran_vorbis.a`
|
||||
before it for MP3 and Vorbis),
|
||||
full-pipeline consumers `libopus.a libsamplerate.a -lssp -lm`. With `-static -static-libgcc` the programs import only
|
||||
`kernel32`, `msvcrt` and `advapi32`.
|
||||
|
||||
@@ -285,7 +380,10 @@ CLI. The decoder-only program streams nine mono/stereo fixtures through
|
||||
MP3 fixtures the same way through `Mp3DecoderRead`, also requires a
|
||||
mid-stream `Mp3DecoderSeek` and a rewind to reproduce the first pass, and
|
||||
rejects a truncated MP3; their inspection lines and PCM16 matched Linux
|
||||
bit-exactly. Its Opus inspection
|
||||
bit-exactly. The six Vorbis fixtures take the same path through
|
||||
`VorbisDecoderRead` and `VorbisDecoderSeek`, and a truncated Vorbis file is
|
||||
rejected; their inspection and comment lines and PCM16 matched Linux
|
||||
bit-exactly too. Its Opus inspection
|
||||
lines, five malformed-stream rejections and decoded frame counts matched
|
||||
Linux; PCM16 differed by at most 2 LSBs against the system libopus build
|
||||
(3 of 9 bit-exact). The full-pipeline program encoded `voice.wav` with the
|
||||
@@ -343,9 +441,29 @@ s16 reads equal the whole-file decode; seeks forward and back on an 8-second
|
||||
garbage, silence, text, WAV, tags alone, free format, mid-stream tags and
|
||||
mono/stereo changes are rejected, and 600 corrupted-payload decodes return a
|
||||
status without crashing. `tests/portable.zi` checks inspection of synthetic
|
||||
streams in the `.zx` engine and Go. `make sanitize-test` runs the native
|
||||
contracts with dr_mp3 (assertions on) and the generated C under
|
||||
AddressSanitizer and UndefinedBehaviorSanitizer.
|
||||
streams in the `.zx` engine and Go.
|
||||
|
||||
Vorbis tests (`tests/vorbis_contracts.zi`, run by the native contracts)
|
||||
decode the committed FFmpeg/libvorbis fixtures in `tests/fixtures/vorbis`
|
||||
(44.1 kHz stereo and mono, 22.05 kHz, 48 kHz, and a 32 kHz stream with
|
||||
title, artist and UTF-8 comments; the README there lists the commands)
|
||||
against FFmpeg's own PCM16 decode over the frames both hold: at most 1 PCM16
|
||||
step and 0.35 steps RMS; measured, at most 0.501 steps (the reference's own
|
||||
rounding) and 0.29 RMS. Lengths equal the final granule positions, which
|
||||
ffprobe and libvorbisfile also report; FFmpeg's own decode ends up to a block
|
||||
away from them. Irregular streamed chunks, rewinds and s16 reads equal the
|
||||
whole-file decode, and seeks forward and back on an 8-second stream and two
|
||||
short ones (into the end-trimmed tail too) return bit-identical samples.
|
||||
Comments read back verbatim and by field name. Truncation, garbage, silence,
|
||||
text, WAV, a CRC error, trailing bytes and synthetic streams with a timeline
|
||||
offset, six channels, a 4 kHz rate, a granule past the decoded frames or no
|
||||
audio are rejected; chained streams are `Unsupported`; an Ogg Opus stream is
|
||||
not Vorbis and still inspects as Opus; and 600 decodes of fixtures with
|
||||
corrupted setup-header or audio bytes behind refreshed CRCs return a status
|
||||
without crashing. `tests/portable.zi` checks Vorbis inspection of a synthetic
|
||||
stream in the `.zx` engine and Go. `make sanitize-test` runs the native
|
||||
contracts with dr_mp3 and stb_vorbis (assertions on) and the generated C
|
||||
under AddressSanitizer and UndefinedBehaviorSanitizer.
|
||||
|
||||
References: [Opus public API 1.5](https://www.opus-codec.org/docs/opus_api-1.5.pdf),
|
||||
[RFC 7845 Ogg Opus](https://www.rfc-editor.org/rfc/rfc7845.html),
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
# Static libopus, libsamplerate and MP3 decoder recipe for native consumers
|
||||
# (Linux, Android NDK, Windows MinGW and other cross builds). Sources are this
|
||||
# package's pinned `libopus`, `libsamplerate` and `dr_libs` source
|
||||
# dependencies (`ziran pkg path NAME`).
|
||||
# Static libopus, libsamplerate, MP3 and Vorbis decoder recipe for native
|
||||
# consumers (Linux, Android NDK, Windows MinGW and other cross builds).
|
||||
# Sources are this package's pinned `libopus`, `libsamplerate`, `dr_libs` and
|
||||
# `stb` source dependencies (`ziran pkg path NAME`).
|
||||
# include("<audio-package>/native/AudioCodecs.cmake")
|
||||
# ziran_audio_codecs("<libopus-source>" "<libsamplerate-source>")
|
||||
# ziran_audio_mp3("<dr_libs-source>")
|
||||
# Defines static, position-independent targets `opus`, `samplerate` and
|
||||
# `ziran_mp3`. Each function is independent; call only what is linked.
|
||||
# ziran_audio_vorbis("<stb-source>")
|
||||
# Defines static, position-independent targets `opus`, `samplerate`,
|
||||
# `ziran_mp3` and `ziran_vorbis`. Each function is independent; call only
|
||||
# what is linked.
|
||||
include_guard(GLOBAL)
|
||||
|
||||
function(ziran_audio_codecs opus_dir samplerate_dir)
|
||||
@@ -52,3 +54,19 @@ function(ziran_audio_mp3 dr_libs_dir)
|
||||
target_compile_options(ziran_mp3 PRIVATE -ffunction-sections -fdata-sections)
|
||||
set_target_properties(ziran_mp3 PROPERTIES POSITION_INDEPENDENT_CODE ON C_STANDARD 99)
|
||||
endfunction()
|
||||
|
||||
# stb_vorbis is a single source file; ziran_vorbis.c is its one
|
||||
# implementation unit plus the open/read/seek calls audio/vorbis binds. Link
|
||||
# `libziran_vorbis.a` (and `-lm`).
|
||||
function(ziran_audio_vorbis stb_dir)
|
||||
if(TARGET ziran_vorbis)
|
||||
message(FATAL_ERROR "ziran_audio_vorbis: ziran_vorbis target already exists")
|
||||
endif()
|
||||
if(NOT EXISTS "${stb_dir}/stb_vorbis.c" OR NOT EXISTS "${stb_dir}/LICENSE")
|
||||
message(FATAL_ERROR "No stb source at ${stb_dir}")
|
||||
endif()
|
||||
add_library(ziran_vorbis STATIC "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/ziran_vorbis.c")
|
||||
target_include_directories(ziran_vorbis PRIVATE "${stb_dir}")
|
||||
target_compile_options(ziran_vorbis PRIVATE -ffunction-sections -fdata-sections)
|
||||
set_target_properties(ziran_vorbis PROPERTIES POSITION_INDEPENDENT_CODE ON C_STANDARD 99)
|
||||
endfunction()
|
||||
@@ -1,6 +1,7 @@
|
||||
# Standalone build of the static codec archives, used by the Makefile and
|
||||
# tests/android.sh / tests/windows.sh. OPUS_DIR with SAMPLERATE_DIR builds
|
||||
# `opus` and `samplerate`; DR_LIBS_DIR builds `ziran_mp3`.
|
||||
# `opus` and `samplerate`; DR_LIBS_DIR builds `ziran_mp3`; STB_DIR builds
|
||||
# `ziran_vorbis`.
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
project(ziran_audio_native C)
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/AudioCodecs.cmake")
|
||||
@@ -13,7 +14,11 @@ if(DEFINED DR_LIBS_DIR)
|
||||
ziran_audio_mp3("${DR_LIBS_DIR}")
|
||||
list(APPEND codec_targets ziran_mp3)
|
||||
endif()
|
||||
if(DEFINED STB_DIR)
|
||||
ziran_audio_vorbis("${STB_DIR}")
|
||||
list(APPEND codec_targets ziran_vorbis)
|
||||
endif()
|
||||
if(NOT codec_targets)
|
||||
message(FATAL_ERROR "Pass OPUS_DIR and SAMPLERATE_DIR, DR_LIBS_DIR, or both")
|
||||
message(FATAL_ERROR "Pass OPUS_DIR and SAMPLERATE_DIR, DR_LIBS_DIR, STB_DIR, or several")
|
||||
endif()
|
||||
add_custom_target(codecs ALL DEPENDS ${codec_targets})
|
||||
@@ -0,0 +1,86 @@
|
||||
/* The one translation unit for stb_vorbis (nothings/stb, public domain or
|
||||
* MIT; see LICENSE in the pinned `stb` source dependency), built for
|
||||
* whole-stream memory input only: no stdio, no pushdata API, no integer
|
||||
* conversion and no comment parsing, which audio/ogg_vorbis does itself.
|
||||
* audio/vorbis validates the Ogg container (CRC, one serial, page order,
|
||||
* headers and granules) before stb_vorbis sees the bytes, because
|
||||
* stb_vorbis checks neither CRCs nor serial numbers.
|
||||
*
|
||||
* The read call is the one piece written against stb_vorbis internals:
|
||||
* stb_vorbis_get_samples_float_interleaved stops at the first frame that
|
||||
* yields no samples, which a long first block followed by short blocks
|
||||
* produces mid-stream, so it would end early. ziran_vorbis_read keeps
|
||||
* decoding until stb_vorbis reports the end of the stream or an error. */
|
||||
#define STB_VORBIS_NO_STDIO
|
||||
#define STB_VORBIS_NO_PUSHDATA_API
|
||||
#define STB_VORBIS_NO_INTEGER_CONVERSION
|
||||
#define STB_VORBIS_NO_COMMENTS
|
||||
#include "stb_vorbis.c"
|
||||
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Opens stb_vorbis over borrowed, validated Ogg Vorbis bytes and reports its
|
||||
* rate and channel count for the caller to compare with its own inspection.
|
||||
* Returns NULL when stb_vorbis rejects the stream or allocation fails. */
|
||||
void *ziran_vorbis_open(const void *data, size_t size, int32_t *rate, int32_t *channels) {
|
||||
stb_vorbis *f;
|
||||
int error = 0;
|
||||
if (data == NULL || size == 0 || size > INT_MAX || rate == NULL || channels == NULL) return NULL;
|
||||
f = stb_vorbis_open_memory((const unsigned char *)data, (int)size, &error, NULL);
|
||||
if (f == NULL) return NULL;
|
||||
*rate = (int32_t)f->sample_rate;
|
||||
*channels = (int32_t)f->channels;
|
||||
return f;
|
||||
}
|
||||
|
||||
void ziran_vorbis_close(void *handle) {
|
||||
if (handle != NULL) stb_vorbis_close((stb_vorbis *)handle);
|
||||
}
|
||||
|
||||
/* Decodes the next packet into the channel buffers. Zero-sample frames are
|
||||
* frames; only the end of the stream or a decode error returns 0. */
|
||||
static int ziran_vorbis_frame(stb_vorbis *f) {
|
||||
int len, left, right;
|
||||
if (!vorbis_decode_packet(f, &len, &left, &right)) {
|
||||
f->channel_buffer_start = f->channel_buffer_end = 0;
|
||||
return 0;
|
||||
}
|
||||
len = vorbis_finish_frame(f, len, left, right);
|
||||
f->channel_buffer_start = left;
|
||||
f->channel_buffer_end = left + len;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Fills OUTPUT with up to FRAMES interleaved float frames and returns how
|
||||
* many it wrote; fewer only at the end of the stream or on a decode error.
|
||||
* Every decoded packet consumes input, so the loop ends. */
|
||||
int64_t ziran_vorbis_read(void *handle, float *output, int64_t frames) {
|
||||
stb_vorbis *f = (stb_vorbis *)handle;
|
||||
int64_t done = 0;
|
||||
int channels, i, j;
|
||||
if (f == NULL || output == NULL || frames <= 0) return 0;
|
||||
channels = f->channels;
|
||||
while (done < frames) {
|
||||
int64_t available = f->channel_buffer_end - f->channel_buffer_start;
|
||||
int count = available > frames - done ? (int)(frames - done) : (int)available;
|
||||
for (j = 0; j < count; ++j)
|
||||
for (i = 0; i < channels; ++i)
|
||||
*output++ = f->channel_buffers[i][f->channel_buffer_start + j];
|
||||
f->channel_buffer_start += count;
|
||||
done += count;
|
||||
if (done == frames || !ziran_vorbis_frame(f)) break;
|
||||
}
|
||||
f->current_playback_loc += done;
|
||||
return done;
|
||||
}
|
||||
|
||||
/* Sample-exact seek: the next read starts at FRAME (0 rewinds). Returns 1 on
|
||||
* success. */
|
||||
int32_t ziran_vorbis_seek(void *handle, int64_t frame) {
|
||||
stb_vorbis *f = (stb_vorbis *)handle;
|
||||
if (f == NULL || frame < 0) return 0;
|
||||
if (frame == 0) return stb_vorbis_seek_start(f) ? 1 : 0;
|
||||
return stb_vorbis_seek64(f, frame) ? 1 : 0;
|
||||
}
|
||||
+20
-7
@@ -7,6 +7,8 @@
|
||||
#import "resample"
|
||||
#import "mpeg_audio"
|
||||
#import "mp3"
|
||||
#import "ogg_vorbis"
|
||||
#import "vorbis"
|
||||
#import "std/file"
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/file_tree_linux"
|
||||
@@ -14,17 +16,17 @@
|
||||
#import "std/text_tools"
|
||||
|
||||
Help :: () {
|
||||
print("audio inspect INPUT.opus|INPUT.mp3\n")
|
||||
print("audio inspect INPUT.opus|INPUT.ogg|INPUT.mp3\n")
|
||||
print("audio encode INPUT.wav OUTPUT.opus [options]\n")
|
||||
print("audio decode INPUT.opus|INPUT.mp3 OUTPUT.wav\n")
|
||||
print("audio transcode INPUT.wav|INPUT.opus|INPUT.mp3 OUTPUT.opus [options]\n")
|
||||
print("audio resample INPUT.wav|INPUT.opus|INPUT.mp3 OUTPUT.wav --rate HZ\n")
|
||||
print("audio decode INPUT.opus|INPUT.ogg|INPUT.mp3 OUTPUT.wav\n")
|
||||
print("audio transcode INPUT.wav|INPUT.opus|INPUT.ogg|INPUT.mp3 OUTPUT.opus [options]\n")
|
||||
print("audio resample INPUT.wav|INPUT.opus|INPUT.ogg|INPUT.mp3 OUTPUT.wav --rate HZ\n")
|
||||
print("options: --bitrate 6000..510000 --vbr on|off|constrained\n")
|
||||
print(" --bandwidth auto|narrow|wide|superwide|full\n")
|
||||
print(" --application audio|voice|lowdelay --complexity 0..10\n")
|
||||
print(" --frame-ms 5|10|20|40|60\n")
|
||||
print("Formats are detected from content: Ogg Opus, RIFF WAV, else MPEG audio (MP3; MPEG-1/2/2.5 Layers I-III).\n")
|
||||
print("Native C: libopus, dr_mp3 and libsamplerate best sinc. Whole-file input cap 256 MiB; PCM cap 10 min at 48 kHz.\n")
|
||||
print("Formats are detected from content: Ogg Vorbis, Ogg Opus, RIFF WAV, else MPEG audio (MP3; MPEG-1/2/2.5 Layers I-III).\n")
|
||||
print("Native C: libopus, stb_vorbis, dr_mp3 and libsamplerate best sinc. Whole-file input cap 256 MiB; PCM cap 10 min at 48 kHz.\n")
|
||||
}
|
||||
// Stage beside the destination; failures leave an existing destination intact.
|
||||
// A pre-existing .audio-part file causes an explicit error, never deletion.
|
||||
@@ -93,7 +95,17 @@ main :: (argc: s32, argv: **u8) -> s32 {
|
||||
defer { unused UnmapFile(input) }
|
||||
if input.length > MaxBytes { print("audio limit exceeded\n"); return LimitExceeded }
|
||||
bytes := MappedBytes(input)
|
||||
is_ogg := Magic(bytes, 0, "OggS")
|
||||
is_vorbis := VorbisProbe(bytes)
|
||||
is_ogg := Magic(bytes, 0, "OggS") && !is_vorbis
|
||||
if inspecting && is_vorbis {
|
||||
info: VorbisInfo
|
||||
comments: VorbisComments
|
||||
code := VorbisInspectComments(bytes, *info, *comments)
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
VorbisPrintInfo(*info)
|
||||
VorbisPrintComments(*comments)
|
||||
return 0
|
||||
}
|
||||
if inspecting && !is_ogg {
|
||||
info: Mp3Info
|
||||
code := Mp3Inspect(bytes, *info)
|
||||
@@ -111,6 +123,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
|
||||
pcm: PCM
|
||||
code: s32
|
||||
if Magic(bytes, 0, "RIFF") && command != "decode" { code = WavDecode(bytes, MaxFrames, *pcm) }
|
||||
else if command != "encode" && is_vorbis { code = VorbisDecode(bytes, MaxFrames, *pcm) }
|
||||
else if command != "encode" && is_ogg { code = Decode(bytes, MaxFrames, *pcm) }
|
||||
else if command != "encode" { code = Mp3Decode(bytes, MaxFrames, *pcm) }
|
||||
else { code = Unsupported }
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
// Portable Ogg Vorbis inspection (Vorbis I, mono and stereo). audio/ogg's
|
||||
// OggReader checks the container (capture, CRC, one serial, page order,
|
||||
// BOS/EOS, lacing); this module checks the identification, comment and setup
|
||||
// headers and reads every audio packet's block size from the setup header's
|
||||
// mode table, so the exact duration, the zero-based timeline and the end trim
|
||||
// are known without a codec library. audio/vorbis decodes what it accepts.
|
||||
#import "types"
|
||||
#import "std/vec"
|
||||
#import "ogg"
|
||||
|
||||
// `frames` is the exact PCM frame count a decoder returns: the final granule
|
||||
// position, which trims the last packet(s). Bitrates are the header's hints,
|
||||
// 0 when unset.
|
||||
VorbisInfo :: struct {
|
||||
channels: s32
|
||||
rate: s32
|
||||
frames: s64
|
||||
nominal_bitrate: s32
|
||||
maximum_bitrate: s32
|
||||
minimum_bitrate: s32
|
||||
short_block: s32 // blocksize_0
|
||||
long_block: s32 // blocksize_1
|
||||
modes: s32
|
||||
packets: s64 // audio packets
|
||||
comments: s64 // user comments in the comment header
|
||||
end_trim: s64 // decodable frames past the final granule position
|
||||
}
|
||||
// An owned copy of the comment header: the vendor string, then each user
|
||||
// comment ("FIELD=value", UTF-8 by the specification; not validated here).
|
||||
// Free it with VorbisCommentsFree (or let the vectors go out of scope).
|
||||
VorbisComments :: struct {
|
||||
text: Vec(u8) // vendor bytes, then each comment's bytes
|
||||
vendor: s64 // vendor length
|
||||
spans: Vec(s64) // start and length of each comment in text
|
||||
}
|
||||
// 24 hours at 48 kHz, as for Opus and MP3 incremental decoding.
|
||||
VorbisMaxStreamFrames :: 4147200000
|
||||
|
||||
#scope_file
|
||||
Ilog :: (value: s64) -> s64 {
|
||||
bits: s64
|
||||
while value > 0 { bits += 1; value = value >> 1 }
|
||||
return bits
|
||||
}
|
||||
// Chained or multiplexed streams: a beginning-of-stream page after the
|
||||
// first. Pages are walked by their headers only; OggReader checks the rest.
|
||||
Chained :: (input: []u8) -> bool {
|
||||
at: s64
|
||||
while input.count - at >= 27 && Magic(input, at, "OggS") {
|
||||
segments := cast(s64)input[at + 26]
|
||||
if input.count - at - 27 < segments { return false }
|
||||
size: s64
|
||||
for i: cast(s64)0..segments - 1 { size += input[at + 27 + i] }
|
||||
if at > 0 && (input[at + 5] & 2) != 0 { return true }
|
||||
at += 27 + segments + size
|
||||
}
|
||||
return false
|
||||
}
|
||||
Identification :: (packet: []u8, info: *VorbisInfo) -> s32 {
|
||||
if packet.count != 30 || packet[0] != 1 || !Magic(packet, 1, "vorbis") { return Malformed }
|
||||
if Little(packet, 7, 4) != 0 { return Unsupported }
|
||||
channels := cast(s64)packet[11]
|
||||
rate := cast(s64)Little(packet, 12, 4)
|
||||
short := cast(s64)(packet[28] & 15); long := cast(s64)(packet[28] >> 4)
|
||||
if channels == 0 || rate == 0 || short < 6 || long > 13 || short > long || (packet[29] & 1) == 0 { return Malformed }
|
||||
if channels > 2 || rate < 8000 || rate > 192000 { return Unsupported }
|
||||
info.channels = cast(s32)channels; info.rate = cast(s32)rate
|
||||
info.short_block = cast(s32)(1 << short); info.long_block = cast(s32)(1 << long)
|
||||
rates: [3]s32
|
||||
for i: 0..2 {
|
||||
value := cast(s64)Little(packet, 16 + i * 4, 4)
|
||||
if value >= 2147483648 { value -= 4294967296 }
|
||||
rates[i] = ifx value > 0 then cast(s32)value else 0
|
||||
}
|
||||
info.maximum_bitrate = rates[0]; info.nominal_bitrate = rates[1]; info.minimum_bitrate = rates[2]
|
||||
return OK
|
||||
}
|
||||
// Vendor, user comments and the framing bit; COMMENTS may be null.
|
||||
CommentHeader :: (packet: []u8, comments: *VorbisComments, count: *s64) -> s32 {
|
||||
if packet.count < 16 || packet[0] != 3 || !Magic(packet, 1, "vorbis") { return Malformed }
|
||||
vendor := cast(s64)Little(packet, 7, 4)
|
||||
if vendor > packet.count - 16 { return Malformed }
|
||||
offset := 11 + vendor
|
||||
total := cast(s64)Little(packet, offset, 4); offset += 4
|
||||
if total > (packet.count - offset) / 4 { return Malformed }
|
||||
copy: VorbisComments
|
||||
if comments != null {
|
||||
for i: cast(s64)11..offset - 5 { if !VecPush(copy.text, packet[i]) { return AllocationFailed } }
|
||||
copy.vendor = vendor
|
||||
}
|
||||
index: s64
|
||||
while index < total {
|
||||
if packet.count - offset < 4 { return Malformed }
|
||||
size := cast(s64)Little(packet, offset, 4); offset += 4
|
||||
if size > packet.count - offset { return Malformed }
|
||||
if comments != null {
|
||||
if !VecPush(copy.spans, copy.text.count) || !VecPush(copy.spans, size) { return AllocationFailed }
|
||||
for i: offset..offset + size - 1 { if !VecPush(copy.text, packet[i]) { return AllocationFailed } }
|
||||
}
|
||||
offset += size; index += 1
|
||||
}
|
||||
if offset >= packet.count || (packet[offset] & 1) == 0 { return Malformed }
|
||||
if comments != null {
|
||||
VecSwap(comments.text, copy.text); VecSwap(comments.spans, copy.spans)
|
||||
comments.vendor = copy.vendor
|
||||
}
|
||||
<<count = total
|
||||
return OK
|
||||
}
|
||||
// Bit INDEX counted backwards from the packet's last bit (Vorbis packs
|
||||
// fields least significant bit first), and a WIDTH-bit field read the same
|
||||
// way, which yields the field's value.
|
||||
BackBit :: (packet: []u8, index: s64) -> s64 {
|
||||
position := packet.count * 8 - 1 - index
|
||||
return (cast(s64)packet[position >> 3] >> (position & 7)) & 1
|
||||
}
|
||||
BackBits :: (packet: []u8, index: s64, width: s64) -> s64 {
|
||||
value: s64
|
||||
for i: cast(s64)0..width - 1 { value = (value << 1) | BackBit(packet, index + i) }
|
||||
return value
|
||||
}
|
||||
// The mode table closes the setup header, so it is read backwards from the
|
||||
// framing bit, as FFmpeg's and liboggz's parsers do: each mode is a block
|
||||
// flag, two zero 16-bit fields and an 8-bit mapping, and the largest count
|
||||
// whose preceding 6-bit field agrees is the table. Codebooks, floors and
|
||||
// residues are left to the decoder.
|
||||
SetupModes :: (packet: []u8, long_blocks: []bool, modes: *s32) -> s32 {
|
||||
if packet.count < 8 || packet[0] != 5 || !Magic(packet, 1, "vorbis") { return Malformed }
|
||||
limit := packet.count * 8 - 56
|
||||
at: s64
|
||||
while at < limit && BackBit(packet, at) == 0 { at += 1 }
|
||||
if at >= limit { return Malformed }
|
||||
at += 1
|
||||
start := at
|
||||
count: s64; found: s64
|
||||
while limit - at >= 47 && count < 64 {
|
||||
if BackBits(packet, at, 8) > 63 || BackBits(packet, at + 8, 16) != 0 || BackBits(packet, at + 24, 16) != 0 { break }
|
||||
at += 41; count += 1
|
||||
if BackBits(packet, at, 6) + 1 == count { found = count }
|
||||
}
|
||||
if found == 0 { return Malformed }
|
||||
for i: cast(s64)0..found - 1 { long_blocks[i] = BackBit(packet, start + (found - 1 - i) * 41 + 40) == 1 }
|
||||
<<modes = cast(s32)found
|
||||
return OK
|
||||
}
|
||||
// Validates the whole stream into INFO (and COMMENTS when not null).
|
||||
Walk :: (input: []u8, info: *VorbisInfo, comments: *VorbisComments) -> s32 {
|
||||
if input.count > MaxBytes { return LimitExceeded }
|
||||
if !VorbisProbe(input) { return Malformed }
|
||||
if Chained(input) { return Unsupported }
|
||||
reader := OggReader.{.input = input}
|
||||
metadata: VorbisInfo
|
||||
long_blocks: [64]bool
|
||||
mode_bits: s64; mode_mask: s64
|
||||
index: s64
|
||||
previous: s64 // the previous audio packet's block size; 0 before the first
|
||||
total: s64
|
||||
granule: s64
|
||||
while !reader.done {
|
||||
code := NextPacket(*reader)
|
||||
if code != OK { return code }
|
||||
if reader.done { break }
|
||||
packet := reader.packet[0:reader.packet_count]
|
||||
if index == 0 {
|
||||
code = Identification(packet, *metadata)
|
||||
if code == OK && (!reader.page_last || reader.flags != 2 || reader.granule != 0) { code = Malformed }
|
||||
} else if index == 1 {
|
||||
code = CommentHeader(packet, comments, *metadata.comments)
|
||||
if code == OK && reader.granule != 0 { code = Malformed }
|
||||
} else if index == 2 {
|
||||
code = SetupModes(packet, long_blocks[:], *metadata.modes)
|
||||
// The first audio packet begins a new page.
|
||||
if code == OK && (!reader.page_last || reader.granule != 0) { code = Malformed }
|
||||
mode_bits = Ilog(metadata.modes - 1); mode_mask = (1 << mode_bits) - 1
|
||||
} else {
|
||||
if packet.count == 0 || (packet[0] & 1) != 0 { return Malformed }
|
||||
mode := (cast(s64)packet[0] >> 1) & mode_mask
|
||||
if mode >= metadata.modes { return Malformed }
|
||||
size := cast(s64)(ifx long_blocks[mode] then metadata.long_block else metadata.short_block)
|
||||
// A packet returns the frames between its window's center and
|
||||
// the previous window's; the first returns none.
|
||||
if previous != 0 { total += (previous + size) / 4 }
|
||||
previous = size; metadata.packets += 1
|
||||
if total > VorbisMaxStreamFrames { return LimitExceeded }
|
||||
if reader.last_complete {
|
||||
position := reader.granule
|
||||
if (reader.flags & 4) == 0 {
|
||||
// A timeline not starting at zero, or a gap.
|
||||
if position != total { return Unsupported }
|
||||
} else if position < granule || position > total { return Malformed }
|
||||
granule = position
|
||||
}
|
||||
}
|
||||
if code != OK { return code }
|
||||
index += 1
|
||||
}
|
||||
if index < 4 || granule <= 0 { return Malformed }
|
||||
metadata.frames = granule; metadata.end_trim = total - granule
|
||||
<<info = metadata
|
||||
return OK
|
||||
}
|
||||
Lower :: (byte: u8) -> u8 { return ifx byte >= 65 && byte <= 90 then byte + 32 else byte }
|
||||
// One labelled line with control bytes shown as '?', so a comment cannot
|
||||
// break the line-based output.
|
||||
PrintText :: (label: string, text: string) {
|
||||
line: Vec(u8)
|
||||
for i: cast(s64)0..text.count - 1 { unused VecPush(line, ifx text[i] < 32 || text[i] == 127 then cast(u8)63 else text[i]) }
|
||||
print("%", label)
|
||||
print("%\n", TextView(VecSlice(line, 0, line.count)))
|
||||
}
|
||||
|
||||
#scope_export
|
||||
// True when the first Ogg packet is a Vorbis identification header; Ogg
|
||||
// Opus and other Ogg codecs are not.
|
||||
VorbisProbe :: (input: []u8) -> bool {
|
||||
if input.count < 28 || !Magic(input, 0, "OggS") { return false }
|
||||
body := 27 + cast(s64)input[26]
|
||||
return body < input.count && input[body] == 1 && Magic(input, body + 1, "vorbis")
|
||||
}
|
||||
// Validates every page and header of a single logical Ogg Vorbis stream
|
||||
// before any decoder sees it, clearing INFO on failure. Truncation, CRC
|
||||
// errors, bad headers, packets that are not audio, granule positions that
|
||||
// disagree with the packets' block sizes and non-Vorbis input are Malformed;
|
||||
// chained or multiplexed streams, a timeline not starting at zero, more than
|
||||
// two channels and rates outside 8000..192000 Hz are Unsupported.
|
||||
VorbisInspect :: (input: []u8, info: *VorbisInfo) -> s32 {
|
||||
<<info = VorbisInfo.{}
|
||||
return Walk(input, info, null)
|
||||
}
|
||||
// VorbisInspect that also copies the comment header into COMMENTS, which is
|
||||
// unchanged on failure.
|
||||
VorbisInspectComments :: (input: []u8, info: *VorbisInfo, comments: *VorbisComments) -> s32 {
|
||||
<<info = VorbisInfo.{}
|
||||
return Walk(input, info, comments)
|
||||
}
|
||||
VorbisCommentsFree :: (comments: *VorbisComments) {
|
||||
VecFree(comments.text); VecFree(comments.spans); comments.vendor = 0
|
||||
}
|
||||
VorbisCommentCount :: (comments: *VorbisComments) -> s64 { return comments.spans.count / 2 }
|
||||
// The returned strings borrow COMMENTS until it is freed or refilled.
|
||||
VorbisVendor :: (comments: *VorbisComments) -> string {
|
||||
return TextView(VecSlice(comments.text, 0, comments.vendor))
|
||||
}
|
||||
// Comment INDEX (0..VorbisCommentCount-1) as stored, "" when out of range.
|
||||
VorbisComment :: (comments: *VorbisComments, index: s64) -> string {
|
||||
if index < 0 || index >= VorbisCommentCount(comments) { return "" }
|
||||
start := comments.spans[index * 2]
|
||||
return TextView(VecSlice(comments.text, start, start + comments.spans[index * 2 + 1]))
|
||||
}
|
||||
// The value of the first comment whose field name equals FIELD, ignoring
|
||||
// ASCII case (Vorbis field names are case-insensitive), or "".
|
||||
VorbisCommentValue :: (comments: *VorbisComments, field: string) -> string {
|
||||
for index: cast(s64)0..VorbisCommentCount(comments) - 1 {
|
||||
start := comments.spans[index * 2]; size := comments.spans[index * 2 + 1]
|
||||
if size > field.count && comments.text[start + field.count] == 61 {
|
||||
same := true
|
||||
for i: cast(s64)0..field.count - 1 { if Lower(comments.text[start + i]) != Lower(field[i]) { same = false } }
|
||||
if same { return TextView(VecSlice(comments.text, start + field.count + 1, start + size)) }
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
VorbisSeconds :: (info: *VorbisInfo) -> float64 {
|
||||
if info.rate <= 0 { return 0.0 }
|
||||
return cast(float64)info.frames / cast(float64)info.rate
|
||||
}
|
||||
// One summary line, shared by the CLI and the Windows decode check.
|
||||
VorbisPrintInfo :: (info: *VorbisInfo) {
|
||||
if info.rate <= 0 { print("Vorbis: no stream\n"); return }
|
||||
milliseconds := (info.frames * 1000 + info.rate / 2) / info.rate
|
||||
fraction := milliseconds % 1000
|
||||
print("Vorbis: % channels, % Hz, % frames, %.", info.channels, info.rate, info.frames, milliseconds / 1000)
|
||||
if fraction < 100 { print("0") }
|
||||
if fraction < 10 { print("0") }
|
||||
print("% s, % bps nominal, blocks %/%, % modes, end trim %, % packets, % comments\n", fraction, info.nominal_bitrate, info.short_block, info.long_block, info.modes, info.end_trim, info.packets, info.comments)
|
||||
}
|
||||
// The vendor and each comment on its own line.
|
||||
VorbisPrintComments :: (comments: *VorbisComments) {
|
||||
PrintText("Vorbis vendor: ", VorbisVendor(comments))
|
||||
for index: cast(s64)0..VorbisCommentCount(comments) - 1 { PrintText("Vorbis comment: ", VorbisComment(comments, index)) }
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
// Ogg Vorbis decoding (Vorbis I, mono and stereo, 8-192 kHz) through
|
||||
// stb_vorbis (the pinned `stb` source dependency, compiled by
|
||||
// native/ziran_vorbis.c into libziran_vorbis.a). Native C only: link
|
||||
// `libziran_vorbis.a -lm`. audio/ogg_vorbis validates the whole stream
|
||||
// first, so stb_vorbis, which checks neither CRCs nor serial numbers, only
|
||||
// sees one complete logical stream whose timeline starts at zero.
|
||||
#import "types"
|
||||
#import "std/vec"
|
||||
#import "std/file"
|
||||
#import "ogg_vorbis"
|
||||
#scope_file
|
||||
vorbis :: #system_library "ziran_vorbis";
|
||||
NativeOpen :: (data: *u8, size: usize, rate: *s32, channels: *s32) -> *void #foreign vorbis "ziran_vorbis_open";
|
||||
NativeClose :: (state: *void) #foreign vorbis "ziran_vorbis_close";
|
||||
NativeRead :: (state: *void, output: *float32, frames: s64) -> s64 #foreign vorbis "ziran_vorbis_read";
|
||||
NativeSeek :: (state: *void, frame: s64) -> s32 #foreign vorbis "ziran_vorbis_seek";
|
||||
// Frames the next read requests: the caller's whole frames, capped at the
|
||||
// logical end; -1 rejects a closed decoder or a partial-frame buffer.
|
||||
Wanted :: (decoder: *VorbisDecoder, samples: s64) -> s64 {
|
||||
if decoder.handle == null || samples <= 0 || samples % decoder.info.channels != 0 { return -1 }
|
||||
wanted := samples / decoder.info.channels
|
||||
left := decoder.info.frames - decoder.position
|
||||
return ifx wanted < left then wanted else left
|
||||
}
|
||||
// stb_vorbis ending before the final granule position is truncated or
|
||||
// corrupt audio; the caller discards that read.
|
||||
Advance :: (decoder: *VorbisDecoder, wanted: s64, got: s64, frames: *s64) -> s32 {
|
||||
if got != wanted { return Malformed }
|
||||
decoder.position += wanted; <<frames = wanted
|
||||
return OK
|
||||
}
|
||||
|
||||
#scope_export
|
||||
// Single-owner native state over borrowed bytes (or bytes it read itself
|
||||
// with VorbisDecoderOpenFile). Do not copy a live decoder or call it
|
||||
// concurrently; keep borrowed input alive and unchanged until close.
|
||||
// `comments` holds the stream's comment header while the decoder is open.
|
||||
VorbisDecoder :: struct {
|
||||
handle: *void
|
||||
info: VorbisInfo
|
||||
comments: VorbisComments
|
||||
position: s64 // next PCM frame a read returns
|
||||
owned: Vec(u8)
|
||||
}
|
||||
VorbisDecoderClose :: (decoder: *VorbisDecoder) {
|
||||
if decoder.handle != null { NativeClose(decoder.handle) }
|
||||
decoder.handle = null; decoder.info = VorbisInfo.{}; decoder.position = 0
|
||||
VorbisCommentsFree(*decoder.comments)
|
||||
VecFree(decoder.owned)
|
||||
}
|
||||
// Inspects INPUT, then opens stb_vorbis over it. MAX_FRAMES bounds the
|
||||
// declared duration.
|
||||
VorbisDecoderOpen :: (decoder: *VorbisDecoder, input: []u8, max_frames: s64) -> s32 {
|
||||
if decoder.handle != null || max_frames <= 0 || max_frames > VorbisMaxStreamFrames { return Invalid }
|
||||
metadata: VorbisInfo
|
||||
comments: VorbisComments
|
||||
code := VorbisInspectComments(input, *metadata, *comments)
|
||||
if code != OK { return code }
|
||||
if metadata.frames > max_frames { return LimitExceeded }
|
||||
rate: s32; channels: s32
|
||||
handle := NativeOpen(*input[0], cast(usize)input.count, *rate, *channels)
|
||||
if handle == null { return Malformed }
|
||||
if rate != metadata.rate || channels != metadata.channels { NativeClose(handle); return Malformed }
|
||||
decoder.handle = handle; decoder.info = metadata; decoder.position = 0
|
||||
VecSwap(decoder.comments.text, comments.text); VecSwap(decoder.comments.spans, comments.spans)
|
||||
decoder.comments.vendor = comments.vendor
|
||||
return OK
|
||||
}
|
||||
// Reads the whole file (at most MaxBytes) into the decoder, which then owns
|
||||
// it until VorbisDecoderClose.
|
||||
VorbisDecoderOpenFile :: (decoder: *VorbisDecoder, path: string, max_frames: s64) -> s32 {
|
||||
if decoder.handle != null || max_frames <= 0 || max_frames > VorbisMaxStreamFrames { return Invalid }
|
||||
VecFree(decoder.owned)
|
||||
if !ReadFileInto(path, *decoder.owned) { VecFree(decoder.owned); return IOFailure }
|
||||
if decoder.owned.count > MaxBytes { VecFree(decoder.owned); return LimitExceeded }
|
||||
code := VorbisDecoderOpen(decoder, VecSlice(decoder.owned, 0, decoder.owned.count), max_frames)
|
||||
if code != OK { VecFree(decoder.owned) }
|
||||
return code
|
||||
}
|
||||
// Fills interleaved float frames. OK with zero frames is the logical end.
|
||||
// An error may leave a filled prefix: discard it, then rewind or close.
|
||||
VorbisDecoderRead :: (decoder: *VorbisDecoder, output: []float32, frames: *s64) -> s32 {
|
||||
<<frames = 0
|
||||
wanted := Wanted(decoder, output.count)
|
||||
if wanted < 0 { return Invalid }
|
||||
if wanted == 0 { return OK }
|
||||
return Advance(decoder, wanted, NativeRead(decoder.handle, *output[0], wanted), frames)
|
||||
}
|
||||
// The same stream as interleaved PCM16: the float samples converted with
|
||||
// Pcm16, so they equal the WAV output of the same decode. A NaN, which only a
|
||||
// corrupt stream can produce, becomes silence.
|
||||
VorbisDecoderReadS16 :: (decoder: *VorbisDecoder, output: []s16, frames: *s64) -> s32 {
|
||||
<<frames = 0
|
||||
wanted := Wanted(decoder, output.count)
|
||||
if wanted < 0 { return Invalid }
|
||||
channels := cast(s64)decoder.info.channels
|
||||
scratch: [4096]float32
|
||||
done: s64
|
||||
while done < wanted {
|
||||
count := wanted - done
|
||||
if count > 2048 { count = 2048 }
|
||||
got: s64
|
||||
code := Advance(decoder, count, NativeRead(decoder.handle, *scratch[0], count), *got)
|
||||
if code != OK { return code }
|
||||
for i: cast(s64)0..count * channels - 1 {
|
||||
value := cast(float64)scratch[i]
|
||||
output[done * channels + i] = ifx value != value then cast(s16)0 else Pcm16(value)
|
||||
}
|
||||
done += count
|
||||
}
|
||||
<<frames = done
|
||||
return OK
|
||||
}
|
||||
// Moves to exact PCM frame FRAME (0..frames): the next read returns the
|
||||
// same samples a read from the start would. stb_vorbis bisects the pages
|
||||
// for the one holding FRAME, then decodes forward from the packet before it,
|
||||
// so the window overlap is primed. An error leaves the decoder to rewind or
|
||||
// close.
|
||||
VorbisDecoderSeek :: (decoder: *VorbisDecoder, frame: s64) -> s32 {
|
||||
if decoder.handle == null || frame < 0 || frame > decoder.info.frames { return Invalid }
|
||||
if frame < decoder.info.frames && NativeSeek(decoder.handle, frame) == 0 { return Malformed }
|
||||
decoder.position = frame
|
||||
return OK
|
||||
}
|
||||
VorbisDecoderRewind :: (decoder: *VorbisDecoder) -> s32 { return VorbisDecoderSeek(decoder, 0) }
|
||||
|
||||
// Whole-file float decode at the stream's own rate, bounded by MaxFrames.
|
||||
// OUTPUT is unchanged on an error.
|
||||
VorbisDecode :: (input: []u8, max_frames: s64, output: *PCM) -> s32 {
|
||||
decoder: VorbisDecoder
|
||||
code := VorbisDecoderOpen(*decoder, input, max_frames)
|
||||
if code != OK { return code }
|
||||
defer { VorbisDecoderClose(*decoder) }
|
||||
if decoder.info.frames > MaxFrames { return LimitExceeded }
|
||||
samples: Vec(float32)
|
||||
count := decoder.info.frames * decoder.info.channels
|
||||
if !VecResize(samples, count) { return AllocationFailed }
|
||||
frames: s64
|
||||
code = VorbisDecoderRead(*decoder, VecSlice(samples, 0, count), *frames)
|
||||
if code != OK { return code }
|
||||
output.rate = decoder.info.rate; output.channels = decoder.info.channels
|
||||
SwapSamples(output, *samples)
|
||||
return OK
|
||||
}
|
||||
// Whole-file interleaved s16 decode; INFO describes the samples. Both
|
||||
// outputs are unchanged on an error.
|
||||
VorbisDecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *VorbisInfo) -> s32 {
|
||||
decoder: VorbisDecoder
|
||||
code := VorbisDecoderOpen(*decoder, input, max_frames)
|
||||
if code != OK { return code }
|
||||
defer { VorbisDecoderClose(*decoder) }
|
||||
if decoder.info.frames > MaxFrames { return LimitExceeded }
|
||||
samples: Vec(s16)
|
||||
count := decoder.info.frames * decoder.info.channels
|
||||
if !VecResize(samples, count) { return AllocationFailed }
|
||||
frames: s64
|
||||
code = VorbisDecoderReadS16(*decoder, VecSlice(samples, 0, count), *frames)
|
||||
if code != OK { return code }
|
||||
<<info = decoder.info
|
||||
VecSwap(samples, <<output)
|
||||
return OK
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Whole-file Ogg Vorbis decode converted to another rate with
|
||||
// audio/resample's best sinc. Kept apart from audio/vorbis so decode-only
|
||||
// consumers need no libsamplerate; streaming callers feed VorbisDecoderRead
|
||||
// chunks to SincOpen/SincProcess.
|
||||
#import "types"
|
||||
#import "vorbis"
|
||||
#import "resample"
|
||||
|
||||
// OUTPUT holds float PCM at RATE (8000..192000), or the decoded PCM itself
|
||||
// when the stream is already at RATE. OUTPUT is unchanged on an error.
|
||||
VorbisDecodeResampled :: (input: []u8, max_frames: s64, rate: s32, output: *PCM) -> s32 {
|
||||
if rate < 8000 || rate > 192000 { return Invalid }
|
||||
decoded: PCM
|
||||
code := VorbisDecode(input, max_frames, *decoded)
|
||||
if code != OK { return code }
|
||||
if decoded.rate == rate {
|
||||
output.rate = rate; output.channels = decoded.channels
|
||||
SwapSamples(output, *decoded.samples)
|
||||
return OK
|
||||
}
|
||||
return Resample(*decoded, rate, output)
|
||||
}
|
||||
+20
-12
@@ -1,8 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Android NDK build of the pinned libopus/libsamplerate/dr_libs sources and
|
||||
# the audio CLI for every ABI Breeze ships, then (with ANDROID_SERIAL) a device
|
||||
# run that decodes, inspects, resamples and encodes the `make test` fixtures
|
||||
# and the committed MP3 fixtures and checks them against the Linux CLI. Invoke through build-queue (`make android-test`).
|
||||
# Android NDK build of the pinned libopus/libsamplerate/dr_libs/stb sources
|
||||
# and the audio CLI for every ABI Breeze ships, then (with ANDROID_SERIAL) a
|
||||
# device run that decodes, inspects, resamples and encodes the `make test`
|
||||
# fixtures and the committed MP3 and Vorbis fixtures and checks them against
|
||||
# the Linux CLI. Invoke through build-queue (`make android-test`).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
root=$(pwd)
|
||||
@@ -17,8 +18,11 @@ bin=$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin
|
||||
opus=$("$ZIRAN" pkg path libopus --offline)
|
||||
samplerate=$("$ZIRAN" pkg path libsamplerate --offline)
|
||||
dr_libs=$("$ZIRAN" pkg path dr_libs --offline)
|
||||
stb=$("$ZIRAN" pkg path stb --offline)
|
||||
fixtures=build/tests/fixtures
|
||||
mp3s="cbr.mp3 vbr.mp3 mono.mp3 mpeg2.mp3 mpeg25.mp3 noxing.mp3 id3.mp3 layer2.mp2 long.mp3"
|
||||
# Vorbis copies are prefixed: mono and long also name MP3 fixtures.
|
||||
oggs="vorbis-stereo.ogg vorbis-mono.ogg vorbis-rate22.ogg vorbis-rate48.ogg vorbis-comments.ogg vorbis-long.ogg"
|
||||
for name in short.opus voice.opus chirp.opus voice.wav chirp.wav; do
|
||||
test -f "$fixtures/$name" || { echo "missing $fixtures/$name; run make test first" >&2; exit 1; }
|
||||
done
|
||||
@@ -37,17 +41,18 @@ for abi in $abis; do
|
||||
mkdir -p "$out"
|
||||
"$CMAKE" -S native -B "$out/native" -DCMAKE_TOOLCHAIN_FILE="$toolchain" \
|
||||
-DANDROID_ABI="$abi" -DANDROID_PLATFORM="android-$api" -DCMAKE_BUILD_TYPE=Release \
|
||||
-DOPUS_DIR="$opus" -DSAMPLERATE_DIR="$samplerate" -DDR_LIBS_DIR="$dr_libs" >"$out/cmake.log"
|
||||
-DOPUS_DIR="$opus" -DSAMPLERATE_DIR="$samplerate" -DDR_LIBS_DIR="$dr_libs" -DSTB_DIR="$stb" >"$out/cmake.log"
|
||||
"$CMAKE" --build "$out/native" --parallel 2 >>"$out/cmake.log"
|
||||
libopus=$(find "$out/native" -name libopus.a | head -n 1)
|
||||
libsamplerate=$(find "$out/native" -name libsamplerate.a | head -n 1)
|
||||
libmp3=$out/native/libziran_mp3.a
|
||||
test -n "$libopus" && test -n "$libsamplerate" && test -f "$libmp3"
|
||||
CC="$bin/$triple$api-clang" CFLAGS="-O2 -Wno-parentheses-equality" LDLIBS="$libmp3 $libopus $libsamplerate -lm" \
|
||||
libvorbis=$out/native/libziran_vorbis.a
|
||||
test -n "$libopus" && test -n "$libsamplerate" && test -f "$libmp3" && test -f "$libvorbis"
|
||||
CC="$bin/$triple$api-clang" CFLAGS="-O2 -Wno-parentheses-equality" LDLIBS="$libmp3 $libvorbis $libopus $libsamplerate -lm" \
|
||||
"$ZIRAN" build --target=c --exe --target-os android --target-cpu "$cpu" --define ANDROID_BUILD --define "$arch" \
|
||||
--root src --module-path src --entry audio:main -o "$out/bin" src/audio.zi
|
||||
file "$out/bin/audio" | grep -q 'ELF'
|
||||
printf 'android %s: libopus, libsamplerate, libziran_mp3 and audio CLI built (API %s)\n' "$abi" "$api"
|
||||
printf 'android %s: libopus, libsamplerate, libziran_mp3, libziran_vorbis and audio CLI built (API %s)\n' "$abi" "$api"
|
||||
done
|
||||
|
||||
serial=${ANDROID_SERIAL:-}
|
||||
@@ -66,6 +71,7 @@ for name in short.opus voice.opus chirp.opus voice.wav chirp.wav; do
|
||||
adb -s "$serial" push "$fixtures/$name" "$remote/$name" >/dev/null
|
||||
done
|
||||
for name in $mp3s; do adb -s "$serial" push "tests/fixtures/mp3/$name" "$remote/$name" >/dev/null; done
|
||||
for name in $oggs; do adb -s "$serial" push "tests/fixtures/vorbis/${name#vorbis-}" "$remote/$name" >/dev/null; done
|
||||
# The same commands run on the device and with the Linux CLI.
|
||||
cat >"$host/commands" <<'EOF'
|
||||
inspect short.opus
|
||||
@@ -77,18 +83,20 @@ resample voice.wav voice-16k.wav --rate 16000
|
||||
resample chirp.wav chirp-44k.wav --rate 44100
|
||||
encode voice.wav voice-encoded.opus --bitrate 24000 --application voice --bandwidth wide --vbr constrained
|
||||
resample vbr.mp3 vbr-48k.wav --rate 48000
|
||||
resample vorbis-stereo.ogg vorbis-48k.wav --rate 48000
|
||||
EOF
|
||||
for name in $mp3s; do printf 'inspect %s\ndecode %s %s-decoded.wav\n' "$name" "$name" "${name%.*}" >>"$host/commands"; done
|
||||
for name in $mp3s $oggs; do printf 'inspect %s\ndecode %s %s-decoded.wav\n' "$name" "$name" "${name%.*}" >>"$host/commands"; done
|
||||
script="cd $remote && chmod 755 audio"
|
||||
while read -r line; do script="$script && ./audio $line"; done <"$host/commands"
|
||||
adb -s "$serial" shell "$script" >"$host/device.log" 2>&1 || { cat "$host/device.log" >&2; exit 1; }
|
||||
for name in short.wav voice-decoded.wav chirp-decoded.wav voice-16k.wav chirp-44k.wav voice-encoded.opus vbr-48k.wav; do
|
||||
for name in short.wav voice-decoded.wav chirp-decoded.wav voice-16k.wav chirp-44k.wav voice-encoded.opus vbr-48k.wav vorbis-48k.wav; do
|
||||
adb -s "$serial" pull "$remote/$name" "$host/$name" >/dev/null
|
||||
done
|
||||
for name in $mp3s; do adb -s "$serial" pull "$remote/${name%.*}-decoded.wav" "$host/${name%.*}-decoded.wav" >/dev/null; done
|
||||
for name in $mp3s $oggs; do adb -s "$serial" pull "$remote/${name%.*}-decoded.wav" "$host/${name%.*}-decoded.wav" >/dev/null; done
|
||||
adb -s "$serial" shell "rm -rf $remote" >/dev/null
|
||||
for name in short.opus voice.opus chirp.opus voice.wav chirp.wav; do cp "$fixtures/$name" "$host/linux/$name"; done
|
||||
for name in $mp3s; do cp "tests/fixtures/mp3/$name" "$host/linux/$name"; done
|
||||
for name in $oggs; do cp "tests/fixtures/vorbis/${name#vorbis-}" "$host/linux/$name"; done
|
||||
(cd "$host/linux" && while read -r line; do "$root/build/bin/audio" $line; done <../commands) >"$host/linux.log" 2>&1
|
||||
# shellcheck disable=SC2086
|
||||
python3 tests/android_compare.py "$host" "$abi" "$serial" $mp3s
|
||||
python3 tests/android_compare.py "$host" "$abi" "$serial" $mp3s $oggs
|
||||
@@ -25,7 +25,7 @@ linux_inspect = inspect_lines(host / 'linux.log')
|
||||
assert device_inspect == linux_inspect, (device_inspect, linux_inspect)
|
||||
|
||||
mp3_outputs = [Path(name).stem + '-decoded.wav' for name in mp3s]
|
||||
for name in ('short.wav', 'voice-decoded.wav', 'chirp-decoded.wav', 'voice-16k.wav', 'chirp-44k.wav', 'vbr-48k.wav', *mp3_outputs):
|
||||
for name in ('short.wav', 'voice-decoded.wav', 'chirp-decoded.wav', 'voice-16k.wav', 'chirp-44k.wav', 'vbr-48k.wav', 'vorbis-48k.wav', *mp3_outputs):
|
||||
(device_params, device), (linux_params, reference) = pcm(host / name), pcm(linux / name)
|
||||
assert device_params == linux_params, (name, device_params, linux_params)
|
||||
worst = max((abs(a - b) for a, b in zip(device, reference)), default=0)
|
||||
@@ -39,4 +39,4 @@ subprocess.run([str(Path('build/bin/audio').resolve()), 'decode', str(host / 'vo
|
||||
(_, _, source_frames), _ = pcm(linux / 'voice.wav')
|
||||
assert (rate, channels, frames) == (48000, 1, source_frames), (rate, channels, frames, source_frames)
|
||||
print(f'android {abi} encode: {(host / "voice-encoded.opus").stat().st_size} bytes, decoded on Linux to {frames} frames')
|
||||
print(f'android {abi} device {serial}: native Opus decode/encode, {len(mp3s)} MP3 decodes and best sinc resampling matched Linux')
|
||||
print(f'android {abi} device {serial}: native Opus decode/encode, {len(mp3s)} MP3 and Vorbis decodes and best sinc resampling matched Linux')
|
||||
+4
-3
@@ -2,8 +2,9 @@
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
ZIRAN=${ZIRAN:-ziran}
|
||||
# `make test` first builds libziran_mp3.a (dr_mp3) into build/native/linux.
|
||||
export LDLIBS="-L$(pwd)/build/native/linux -lziran_mp3 -lopus -lsamplerate -lm"
|
||||
# `make test` first builds libziran_mp3.a (dr_mp3) and libziran_vorbis.a
|
||||
# (stb_vorbis) into build/native/linux.
|
||||
export LDLIBS="-L$(pwd)/build/native/linux -lziran_mp3 -lziran_vorbis -lopus -lsamplerate -lm"
|
||||
mkdir -p build/tests
|
||||
python3 - <<'PYDOC'
|
||||
from pathlib import Path
|
||||
@@ -36,7 +37,7 @@ for form in source saved; do
|
||||
build/tests/go/program
|
||||
done
|
||||
# Target rejection, rather than silently fabricated codec/resampler output.
|
||||
for entry in Codec Sinc; do
|
||||
for entry in Codec Sinc Vorbis; do
|
||||
if "$ZIRAN" bundle --root tests --module-path src --entry "native_only:$entry" -o build/tests/native.zx tests/native_only.zi >build/tests/rejection.log 2>&1; then
|
||||
echo "native $entry unexpectedly bundled without its capability" >&2; exit 1
|
||||
fi
|
||||
|
||||
+4
-1
@@ -7,6 +7,7 @@
|
||||
#import "wav"
|
||||
#import "std/math"
|
||||
#import "mp3_contracts"
|
||||
#import "vorbis_contracts"
|
||||
|
||||
test_opus :: #system_library "opus";
|
||||
TestControl :: (state: *void, request: s32, arguments: ..any) -> s32 #foreign test_opus "opus_encoder_ctl";
|
||||
@@ -136,5 +137,7 @@ main :: () -> s32 {
|
||||
if stream.count != filtered.samples.count { print("stream length % expected %\n", stream.count, filtered.samples.count); return 26 }
|
||||
for i: 0..stream.count - 1 { if (cast(float64)stream[i] - cast(float64)filtered.samples[i]) > 0.000001 || (cast(float64)filtered.samples[i] - cast(float64)stream[i]) > 0.000001 { return 27 } }
|
||||
print("native audio contracts passed; % logical frames, alias mean square %\n", info.frames, energy / 14000.0)
|
||||
return Mp3Contracts()
|
||||
code := Mp3Contracts()
|
||||
if code != 0 { return code }
|
||||
return VorbisContracts()
|
||||
}
|
||||
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
# Ogg Vorbis test fixtures
|
||||
|
||||
Generated on 2026-11-16 with FFmpeg 7.1.5 (Debian 7.1.5-0+deb13u1) and its
|
||||
libvorbis encoder (Debian libvorbis 1.3.7). Each `NAME.wav` is FFmpeg's own
|
||||
decode of `NAME.ogg` (PCM16, its native `vorbis` decoder), the independent
|
||||
reference that `tests/vorbis_contracts.zi` compares sample values against.
|
||||
`long.ogg` has no reference: its seeks are checked against this package's
|
||||
own linear decode.
|
||||
|
||||
FFmpeg's Ogg demuxer counts the first packet's discarded half block, so its
|
||||
decode does not end at the final granule position: it runs a few dozen
|
||||
frames long (no end trim) or, for `comments.ogg`, 128 frames short. The
|
||||
contracts compare the frames both decodes hold. The exact length is the
|
||||
final granule position, which `ffprobe -show_entries stream=duration_ts`
|
||||
reports and which the system libvorbisfile 1.3.7 (`ov_pcm_total`, and the
|
||||
frame count `ov_read_float` returns) confirmed when these fixtures were
|
||||
made; its samples matched FFmpeg's within 0.5 PCM16 steps.
|
||||
|
||||
The 0.3 s source is a 440 Hz left / 660 Hz right tone plus seeded noise, as
|
||||
for the MP3 fixtures:
|
||||
|
||||
```sh
|
||||
SRC='sine=f=440:d=0.3:sample_rate=44100[a];sine=f=660:d=0.3:sample_rate=44100[b];anoisesrc=d=0.3:a=0.05:r=44100:seed=7[n];[a][b]amerge=inputs=2[s];[s][n]amix=inputs=2:normalize=0,volume=0.8'
|
||||
ff() { ffmpeg -hide_banner -loglevel error -y -bitexact "$@"; }
|
||||
ff -filter_complex "$SRC" -ac 2 -ar 44100 -c:a libvorbis -q:a 4 stereo.ogg
|
||||
ff -filter_complex "$SRC" -ac 1 -ar 44100 -c:a libvorbis -q:a 2 mono.ogg
|
||||
ff -filter_complex "$SRC" -ac 2 -ar 22050 -c:a libvorbis -q:a 3 rate22.ogg
|
||||
ff -filter_complex "$SRC" -ac 2 -ar 48000 -c:a libvorbis -q:a 5 rate48.ogg
|
||||
ff -filter_complex "$SRC" -ac 1 -ar 32000 -c:a libvorbis -q:a 1 -metadata title="Ziran fixture" \
|
||||
-metadata artist="Ziran audio" -metadata comment="Vorbis comments, ünïcödé" comments.ogg
|
||||
ff -f lavfi -i "sine=f=330:d=8:sample_rate=22050,volume=0.5" -f lavfi -i "anoisesrc=d=8:a=0.08:r=22050:seed=3" \
|
||||
-filter_complex amix=inputs=2:normalize=0 -ac 1 -ar 22050 -c:a libvorbis -q:a 0 long.ogg
|
||||
for f in stereo mono rate22 rate48 comments; do ff -i "$f.ogg" -map_metadata -1 -c:a pcm_s16le "$f.wav"; done
|
||||
```
|
||||
|
||||
| File | Stream | Granule frames | FFmpeg frames |
|
||||
| --- | --- | --- | --- |
|
||||
| `stereo.ogg` | 44.1 kHz stereo, `-q:a 4` | 13230 | 13312 |
|
||||
| `mono.ogg` | 44.1 kHz mono, `-q:a 2` | 13230 | 13312 |
|
||||
| `rate22.ogg` | 22.05 kHz stereo, `-q:a 3` | 6615 | 6656 |
|
||||
| `rate48.ogg` | 48 kHz stereo, `-q:a 5` | 14400 | 14464 |
|
||||
| `comments.ogg` | 32 kHz mono, `-q:a 1`; vendor `ffmpeg`, `encoder`, `title`, `artist` and a UTF-8 `DESCRIPTION` (FFmpeg's name for `comment`) | 9600 | 9472 |
|
||||
| `long.ogg` | 22.05 kHz mono, `-q:a 0`, 8 s | 176400 | — |
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
@@ -1,6 +1,7 @@
|
||||
#import "types"
|
||||
#import "opus"
|
||||
#import "resample"
|
||||
#import "vorbis"
|
||||
#program_export
|
||||
Codec :: () -> s32 {
|
||||
encoder: Encoder
|
||||
@@ -15,3 +16,11 @@ Sinc :: () -> s32 {
|
||||
SincClose(*state)
|
||||
return code
|
||||
}
|
||||
#program_export
|
||||
Vorbis :: () -> s32 {
|
||||
decoder: VorbisDecoder
|
||||
input: [4]u8
|
||||
code := VorbisDecoderOpen(*decoder, input[:], 1)
|
||||
VorbisDecoderClose(*decoder)
|
||||
return code
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
#import "wav"
|
||||
#import "mpeg_audio"
|
||||
#import "mpeg_fixture"
|
||||
#import "ogg_vorbis"
|
||||
#import "vorbis_fixture"
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
bytes: Vec(u8)
|
||||
@@ -46,6 +48,17 @@ main :: () -> s32 {
|
||||
short: Vec(u8)
|
||||
if !Mp3Synthetic(*short, 4, 5, false, true, false) { return 16 }
|
||||
if Mp3Inspect(VecSlice(short, 0, short.count), *mp3) != Malformed { return 17 }
|
||||
// Ogg Vorbis inspection is portable too: headers, comments, block sizes
|
||||
// from the setup header's mode table and granule checks.
|
||||
modes: [5]u8 = .[1, 0, 0, 1, 1]
|
||||
vorbis: Vec(u8)
|
||||
if !VorbisSynthetic(*vorbis, 1, 22050, modes[:], 0, 300) { return 18 }
|
||||
vorbis_info: VorbisInfo
|
||||
comments: VorbisComments
|
||||
if VorbisInspectComments(VecSlice(vorbis, 0, vorbis.count), *vorbis_info, *comments) != OK || vorbis_info.frames != VorbisSyntheticFrames(modes[:]) - 300 || vorbis_info.modes != 2 || vorbis_info.rate != 22050 || vorbis_info.end_trim != 300 { return 19 }
|
||||
if VorbisCommentValue(*comments, "title") != "synthetic" || VorbisVendor(*comments) != "ziran" || VorbisCommentCount(*comments) != 1 { return 20 }
|
||||
vorbis[vorbis.count - 1] ^= 1
|
||||
if VorbisInspect(VecSlice(vorbis, 0, vorbis.count), *vorbis_info) != Malformed || vorbis_info.frames != 0 { return 21 }
|
||||
print("portable audio contracts passed\n")
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
// Native Ogg Vorbis contracts over tests/fixtures/vorbis (see its README for
|
||||
// the FFmpeg commands that made them): decode against FFmpeg's reference PCM,
|
||||
// exact durations from the final granule position, streaming = whole-file
|
||||
// output, exact seeks, comments, the Opus path left to Opus, and errors
|
||||
// (never crashes) for truncated, corrupted, garbage, chained, synthetic and
|
||||
// non-Vorbis input. Run from the package root.
|
||||
#import "types"
|
||||
#import "std/vec"
|
||||
#import "std/file"
|
||||
#import "std/math"
|
||||
#import "std/byte_text_linux"
|
||||
#import "wav"
|
||||
#import "ogg"
|
||||
#import "pipeline"
|
||||
#import "ogg_vorbis"
|
||||
#import "vorbis"
|
||||
#import "vorbis_resample"
|
||||
#import "vorbis_fixture"
|
||||
|
||||
#scope_file
|
||||
// Largest decoder difference against FFmpeg's PCM16 reference, in PCM16
|
||||
// steps, and the largest RMS difference. The reference itself is rounded to
|
||||
// 16 bits (0.5 steps); measured: at most 0.501 steps, RMS 0.29.
|
||||
ToleranceSteps :: 1.0
|
||||
ToleranceRms :: 0.35
|
||||
Fail :: (code: s32, name: string) -> s32 { print("vorbis contract % failed: %\n", code, name); return code }
|
||||
// Fixture paths are built in caller-owned bytes, so sanitizer runs see no
|
||||
// retained strings.
|
||||
PathInto :: (path: *Vec(u8), name: string, extension: string) {
|
||||
parts: [4]string = .["tests/fixtures/vorbis/", name, ".", extension]
|
||||
for part: parts { for i: cast(s64)0..part.count - 1 { unused VecPush(<<path, part[i]) } }
|
||||
}
|
||||
Load :: (name: string, extension: string, bytes: *Vec(u8)) -> bool {
|
||||
path: Vec(u8)
|
||||
PathInto(*path, name, extension)
|
||||
return ReadFileInto(TextFromBytes(VecSlice(path, 0, path.count)), bytes)
|
||||
}
|
||||
Copy :: (from: []u8, to: *Vec(u8)) -> bool {
|
||||
for byte: from { if !VecPush(<<to, byte) { return false } }
|
||||
return true
|
||||
}
|
||||
Same :: (a: []float32, b: []float32) -> bool {
|
||||
if a.count != b.count { return false }
|
||||
for i: cast(s64)0..a.count - 1 { if a[i] != b[i] { return false } }
|
||||
return true
|
||||
}
|
||||
// Reads the rest of the stream in irregular chunks into OUTPUT.
|
||||
Stream :: (decoder: *VorbisDecoder, output: *Vec(float32)) -> s32 {
|
||||
sizes: [6]s64 = .[997, 1, 1024, 4093, 7, 128]
|
||||
scratch: [8186]float32
|
||||
channels := cast(s64)decoder.info.channels
|
||||
turn: s64
|
||||
while true {
|
||||
frames: s64
|
||||
code := VorbisDecoderRead(decoder, scratch[0:sizes[turn % 6] * channels], *frames)
|
||||
if code != OK { return code }
|
||||
if frames == 0 { return OK }
|
||||
for i: cast(s64)0..frames * channels - 1 { if !VecPush(<<output, scratch[i]) { return AllocationFailed } }
|
||||
turn += 1
|
||||
}
|
||||
return OK
|
||||
}
|
||||
Random :: (state: *u64) -> u8 {
|
||||
<<state = <<state * 6364136223846793005 + 1442695040888963407
|
||||
return cast(u8)(<<state >> 56)
|
||||
}
|
||||
// Page bodies [start, end) after the first SKIP pages, and a CRC refresh, so
|
||||
// corrupted payloads pass the container checks and reach stb_vorbis.
|
||||
Bodies :: (bytes: []u8, skip: s64, ranges: *Vec(s64)) {
|
||||
at: s64; page: s64
|
||||
while bytes.count - at >= 27 {
|
||||
segments := cast(s64)bytes[at + 26]
|
||||
size: s64
|
||||
for i: cast(s64)0..segments - 1 { size += bytes[at + 27 + i] }
|
||||
if page >= skip && size > 0 { unused VecPush(<<ranges, at + 27 + segments); unused VecPush(<<ranges, at + 27 + segments + size) }
|
||||
at += 27 + segments + size; page += 1
|
||||
}
|
||||
}
|
||||
Recrc :: (bytes: []u8) {
|
||||
at: s64
|
||||
while bytes.count - at >= 27 {
|
||||
segments := cast(s64)bytes[at + 26]
|
||||
size: s64
|
||||
for i: cast(s64)0..segments - 1 { size += bytes[at + 27 + i] }
|
||||
end := at + 27 + segments + size
|
||||
PutLittle(bytes, at + 22, 4, OggCRC(bytes[at:end]))
|
||||
at = end
|
||||
}
|
||||
}
|
||||
Fixtures :: () -> s32 {
|
||||
names: [5]string = .["stereo", "mono", "rate22", "rate48", "comments"]
|
||||
rates: [5]s32 = .[44100, 44100, 22050, 48000, 32000]
|
||||
channels: [5]s32 = .[2, 1, 2, 2, 1]
|
||||
// The final granule positions; ffprobe's duration_ts and libvorbisfile's
|
||||
// ov_pcm_total report the same.
|
||||
lengths: [5]s64 = .[13230, 13230, 6615, 14400, 9600]
|
||||
for index: 0..4 {
|
||||
name := names[index]
|
||||
bytes: Vec(u8)
|
||||
reference_bytes: Vec(u8)
|
||||
if !Load(name, "ogg", *bytes) || !Load(name, "wav", *reference_bytes) { return Fail(100, name) }
|
||||
input := VecSlice(bytes, 0, bytes.count)
|
||||
reference: PCM
|
||||
if WavDecode(VecSlice(reference_bytes, 0, reference_bytes.count), MaxFrames, *reference) != OK { return Fail(101, name) }
|
||||
if !VorbisProbe(input) { return Fail(102, name) }
|
||||
info: VorbisInfo
|
||||
if VorbisInspect(input, *info) != OK { return Fail(103, name) }
|
||||
if info.rate != rates[index] || info.channels != channels[index] || info.frames != lengths[index] || reference.rate != info.rate || reference.channels != info.channels { print("% frames % rate %\n", name, info.frames, info.rate); return Fail(104, name) }
|
||||
if info.packets < 2 || info.modes < 1 || info.short_block < 64 || info.long_block < info.short_block || info.end_trim < 0 || info.end_trim >= info.long_block || info.nominal_bitrate <= 0 { return Fail(105, name) }
|
||||
// FFmpeg's Ogg demuxer counts the discarded first packet, so its
|
||||
// decode ends up to one long block away from the granule length.
|
||||
reference_frames := reference.samples.count / reference.channels
|
||||
if reference_frames - info.frames > info.long_block || info.frames - reference_frames > info.long_block { return Fail(106, name) }
|
||||
// Whole-file float decode against the reference within tolerance,
|
||||
// over the frames both decodes hold.
|
||||
decoded: PCM
|
||||
if VorbisDecode(input, info.frames - 1, *decoded) != LimitExceeded || decoded.samples.count != 0 { return Fail(107, name) }
|
||||
if VorbisDecode(input, MaxFrames, *decoded) != OK || decoded.rate != info.rate || decoded.channels != info.channels || decoded.samples.count != info.frames * info.channels { return Fail(108, name) }
|
||||
shared := ifx reference_frames < info.frames then reference_frames else info.frames
|
||||
worst: float64; squares: float64
|
||||
for i: cast(s64)0..shared * info.channels - 1 {
|
||||
difference := (cast(float64)decoded.samples[i] - cast(float64)reference.samples[i]) * 32768.0
|
||||
if difference < 0.0 { difference = -difference }
|
||||
if difference > worst { worst = difference }
|
||||
squares += difference * difference
|
||||
}
|
||||
mean_square := squares / cast(float64)(shared * info.channels)
|
||||
if worst > ToleranceSteps || mean_square > ToleranceRms * ToleranceRms { print("% worst % mean square %\n", name, worst, mean_square); return Fail(109, name) }
|
||||
print("vorbis %: % frames at % Hz x%, % packets, end trim %, max difference % PCM16 steps, mean square % against FFmpeg over % frames\n", name, info.frames, info.rate, info.channels, info.packets, info.end_trim, worst, mean_square, shared)
|
||||
// Streaming in irregular chunks matches the whole-file samples, and
|
||||
// so does a rewind followed by a second pass.
|
||||
decoder: VorbisDecoder
|
||||
if VorbisDecoderOpen(*decoder, input, MaxFrames) != OK { return Fail(110, name) }
|
||||
streamed: Vec(float32)
|
||||
if Stream(*decoder, *streamed) != OK || !Same(VecSlice(streamed, 0, streamed.count), VecSlice(decoded.samples, 0, decoded.samples.count)) { VorbisDecoderClose(*decoder); return Fail(111, name) }
|
||||
if VorbisDecoderRewind(*decoder) != OK { VorbisDecoderClose(*decoder); return Fail(112, name) }
|
||||
again: Vec(float32)
|
||||
if Stream(*decoder, *again) != OK || !Same(VecSlice(again, 0, again.count), VecSlice(streamed, 0, streamed.count)) { VorbisDecoderClose(*decoder); return Fail(113, name) }
|
||||
// Interleaved s16 is the float output through the PCM16 boundary.
|
||||
if VorbisDecoderRewind(*decoder) != OK { VorbisDecoderClose(*decoder); return Fail(114, name) }
|
||||
shorts: [666]s16
|
||||
at: s64
|
||||
while true {
|
||||
frames: s64
|
||||
if VorbisDecoderReadS16(*decoder, shorts[0:333 * cast(s64)info.channels], *frames) != OK { VorbisDecoderClose(*decoder); return Fail(115, name) }
|
||||
if frames == 0 { break }
|
||||
for i: cast(s64)0..frames * info.channels - 1 {
|
||||
if shorts[i] != Pcm16(cast(float64)decoded.samples[at + i]) { VorbisDecoderClose(*decoder); return Fail(116, name) }
|
||||
}
|
||||
at += frames * info.channels
|
||||
}
|
||||
VorbisDecoderClose(*decoder); VorbisDecoderClose(*decoder)
|
||||
if at != decoded.samples.count { return Fail(117, name) }
|
||||
whole: Vec(s16)
|
||||
whole_info: VorbisInfo
|
||||
if VorbisDecodeS16(input, MaxFrames, *whole, *whole_info) != OK || whole.count != at || whole_info.frames != info.frames { return Fail(118, name) }
|
||||
// Any truncation, even of one byte, is an error before decoding.
|
||||
cuts: [6]s64 = .[1, 2, 57, bytes.count / 2 + 3, bytes.count - 4, bytes.count - 1]
|
||||
for cut: cuts {
|
||||
code := VorbisDecode(VecSlice(bytes, 0, bytes.count - cut), MaxFrames, *decoded)
|
||||
if code != Malformed { print("% cut % returned %\n", name, cut, code); return Fail(119, name) }
|
||||
}
|
||||
}
|
||||
return OK
|
||||
}
|
||||
// Comments: the comment header is copied verbatim (FFmpeg writes its
|
||||
// `comment` metadata as DESCRIPTION), field names match without
|
||||
// regard to ASCII case, and the decoder holds the same copy while open.
|
||||
Comments :: () -> s32 {
|
||||
bytes: Vec(u8)
|
||||
if !Load("comments", "ogg", *bytes) { return Fail(150, "comments") }
|
||||
input := VecSlice(bytes, 0, bytes.count)
|
||||
info: VorbisInfo
|
||||
comments: VorbisComments
|
||||
if VorbisInspectComments(input, *info, *comments) != OK || info.comments != VorbisCommentCount(*comments) || info.comments < 3 { return Fail(151, "comments") }
|
||||
if VorbisVendor(*comments).count == 0 || VorbisComment(*comments, -1) != "" || VorbisComment(*comments, info.comments) != "" { return Fail(152, "vendor") }
|
||||
if VorbisCommentValue(*comments, "TITLE") != "Ziran fixture" || VorbisCommentValue(*comments, "artist") != "Ziran audio" { return Fail(153, "fields") }
|
||||
if VorbisCommentValue(*comments, "Description") != "Vorbis comments, ünïcödé" || VorbisCommentValue(*comments, "missing") != "" || VorbisCommentValue(*comments, "TITL") != "" { return Fail(154, "fields") }
|
||||
decoder: VorbisDecoder
|
||||
if VorbisDecoderOpen(*decoder, input, MaxFrames) != OK { return Fail(155, "decoder") }
|
||||
same := VorbisVendor(*decoder.comments) == VorbisVendor(*comments) && VorbisCommentCount(*decoder.comments) == info.comments && VorbisCommentValue(*decoder.comments, "title") == "Ziran fixture"
|
||||
VorbisDecoderClose(*decoder)
|
||||
if !same || VorbisCommentCount(*decoder.comments) != 0 { return Fail(156, "decoder") }
|
||||
VorbisCommentsFree(*comments)
|
||||
if VorbisCommentCount(*comments) != 0 { return Fail(157, "free") }
|
||||
return OK
|
||||
}
|
||||
// Exact seeks: after a seek the decoder returns the very samples a linear
|
||||
// decode has at that frame, forward and backward, on an 8-second stream and
|
||||
// on a short one, including the end-trimmed tail.
|
||||
Seeks :: (name: string, expected_frames: s64) -> s32 {
|
||||
bytes: Vec(u8)
|
||||
if !Load(name, "ogg", *bytes) { return Fail(200, name) }
|
||||
input := VecSlice(bytes, 0, bytes.count)
|
||||
linear: PCM
|
||||
if VorbisDecode(input, MaxFrames, *linear) != OK { return Fail(201, name) }
|
||||
channels := cast(s64)linear.channels
|
||||
frames := linear.samples.count / channels
|
||||
if frames != expected_frames { print("% decoded % frames\n", name, frames); return Fail(202, name) }
|
||||
decoder: VorbisDecoder
|
||||
if VorbisDecoderOpen(*decoder, input, MaxFrames) != OK { return Fail(203, name) }
|
||||
defer { VorbisDecoderClose(*decoder) }
|
||||
if decoder.info.frames != frames { return Fail(204, name) }
|
||||
targets: [20]s64 = .[frames / 2, 1, 127, 128, 129, 255, 256, 1023, 1024, 1025, 12345, frames - 1000, frames - 1, 17, 0, frames / 3, frames, frames - 50, 4095, frames / 2 + 1]
|
||||
scratch: [1024]float32
|
||||
for target: targets {
|
||||
if target < 0 || target > frames { continue }
|
||||
if VorbisDecoderSeek(*decoder, target) != OK || decoder.position != target { print("% seek % failed\n", name, target); return Fail(205, name) }
|
||||
got: s64
|
||||
if VorbisDecoderRead(*decoder, scratch[0:512 * channels], *got) != OK { return Fail(206, name) }
|
||||
wanted := frames - target
|
||||
if wanted > 512 { wanted = 512 }
|
||||
if got != wanted { return Fail(207, name) }
|
||||
for i: cast(s64)0..got * channels - 1 {
|
||||
if scratch[i] != linear.samples[target * channels + i] { print("% seek % differs at sample %\n", name, target, i); return Fail(208, name) }
|
||||
}
|
||||
}
|
||||
if VorbisDecoderSeek(*decoder, frames + 1) != Invalid || VorbisDecoderSeek(*decoder, -1) != Invalid { return Fail(209, name) }
|
||||
// Reading on from a seek to the middle reaches the end exactly.
|
||||
if VorbisDecoderSeek(*decoder, frames / 2) != OK { return Fail(210, name) }
|
||||
rest: Vec(float32)
|
||||
if Stream(*decoder, *rest) != OK || !Same(VecSlice(rest, 0, rest.count), VecSlice(linear.samples, frames / 2 * channels, linear.samples.count)) { return Fail(211, name) }
|
||||
return OK
|
||||
}
|
||||
// Synthetic streams: block-size arithmetic, end trim and timeline checks.
|
||||
Synthetic :: () -> s32 {
|
||||
modes: [9]u8 = .[0, 0, 1, 1, 0, 1, 0, 0, 1]
|
||||
stream: Vec(u8)
|
||||
if !VorbisSynthetic(*stream, 2, 44100, modes[:], 0, 100) { return Fail(250, "synthetic") }
|
||||
info: VorbisInfo
|
||||
total := VorbisSyntheticFrames(modes[:])
|
||||
if VorbisInspect(VecSlice(stream, 0, stream.count), *info) != OK || info.frames != total - 100 || info.end_trim != 100 || info.modes != 2 || info.packets != 9 || info.long_block != VorbisSyntheticLong { return Fail(251, "synthetic") }
|
||||
// The setup header is filler, so stb_vorbis must refuse it cleanly.
|
||||
pcm: PCM
|
||||
if VorbisDecode(VecSlice(stream, 0, stream.count), MaxFrames, *pcm) != Malformed { return Fail(252, "synthetic decode") }
|
||||
// A timeline offset, more than two channels, an unsupported rate, a final
|
||||
// granule past the decodable frames and a header-only stream.
|
||||
offset: Vec(u8)
|
||||
if !VorbisSynthetic(*offset, 1, 44100, modes[:], 4410, 0) || VorbisInspect(VecSlice(offset, 0, offset.count), *info) != Unsupported { return Fail(253, "offset") }
|
||||
surround: Vec(u8)
|
||||
if !VorbisSynthetic(*surround, 6, 44100, modes[:], 0, 0) || VorbisInspect(VecSlice(surround, 0, surround.count), *info) != Unsupported { return Fail(254, "channels") }
|
||||
slow: Vec(u8)
|
||||
if !VorbisSynthetic(*slow, 1, 4000, modes[:], 0, 0) || VorbisInspect(VecSlice(slow, 0, slow.count), *info) != Unsupported { return Fail(255, "rate") }
|
||||
long: Vec(u8)
|
||||
if !VorbisSynthetic(*long, 1, 44100, modes[:], 0, -64) || VorbisInspect(VecSlice(long, 0, long.count), *info) != Malformed { return Fail(256, "granule") }
|
||||
single: [1]u8 = .[0]
|
||||
empty: Vec(u8)
|
||||
if !VorbisSynthetic(*empty, 1, 44100, single[:], 0, 0) || VorbisInspect(VecSlice(empty, 0, empty.count), *info) != Malformed { return Fail(257, "no audio") }
|
||||
return OK
|
||||
}
|
||||
Errors :: () -> s32 {
|
||||
decoder: VorbisDecoder
|
||||
scratch: [4]float32
|
||||
frames: s64
|
||||
if VorbisDecoderRead(*decoder, scratch[:], *frames) != Invalid || VorbisDecoderSeek(*decoder, 0) != Invalid { return Fail(300, "closed decoder") }
|
||||
VorbisDecoderClose(*decoder)
|
||||
// Garbage, silence and text are not Ogg Vorbis.
|
||||
state: u64 = 54321
|
||||
sizes: [8]s64 = .[0, 1, 3, 4, 10, 417, 4096, 65536]
|
||||
for size: sizes {
|
||||
noise: Vec(u8)
|
||||
for i: cast(s64)0..size - 1 { if !VecPush(noise, Random(*state)) { return Fail(301, "noise") } }
|
||||
pcm: PCM
|
||||
if VorbisDecode(VecSlice(noise, 0, noise.count), MaxFrames, *pcm) != Malformed { return Fail(302, "noise") }
|
||||
zeros: Vec(u8)
|
||||
if !VecResize(zeros, size) { return Fail(303, "zeros") }
|
||||
if VorbisDecode(VecSlice(zeros, 0, zeros.count), MaxFrames, *pcm) != Malformed { return Fail(304, "zeros") }
|
||||
}
|
||||
info: VorbisInfo
|
||||
text := "OggS is not enough to make this an Ogg Vorbis stream."
|
||||
prose: Vec(u8)
|
||||
for i: 0..text.count - 1 { if !VecPush(prose, text[i]) { return Fail(305, "text") } }
|
||||
if VorbisProbe(VecSlice(prose, 0, prose.count)) || VorbisInspect(VecSlice(prose, 0, prose.count), *info) != Malformed { return Fail(306, "text") }
|
||||
wav: Vec(u8)
|
||||
if !Load("mono", "wav", *wav) || VorbisInspect(VecSlice(wav, 0, wav.count), *info) != Malformed { return Fail(307, "wav") }
|
||||
// An Ogg Opus stream is not Vorbis and still inspects as Opus, which is
|
||||
// how the CLI and the Windows check pick the Opus decoder for it.
|
||||
tone: PCM
|
||||
tone.rate = 48000; tone.channels = 1
|
||||
if !VecResize(tone.samples, 4800) { return Fail(308, "opus") }
|
||||
for i: 0..4799 { tone.samples[i] = cast(float32)(0.3 * Sin(cast(float64)i * 2.0 * 3.14159265358979323846 * 440.0 / 48000.0)) }
|
||||
opus_bytes: Vec(u8)
|
||||
opus_info: Info
|
||||
if Encode(*tone, DefaultOptions(), *opus_bytes) != OK || VorbisProbe(VecSlice(opus_bytes, 0, opus_bytes.count)) { return Fail(309, "opus") }
|
||||
if VorbisInspect(VecSlice(opus_bytes, 0, opus_bytes.count), *info) != Malformed || Inspect(VecSlice(opus_bytes, 0, opus_bytes.count), *opus_info) != OK || opus_info.frames != 4800 { return Fail(310, "opus") }
|
||||
// Chained streams (one stream after another) are rejected as
|
||||
// unsupported, as is a stream followed by trailing bytes as malformed.
|
||||
first: Vec(u8)
|
||||
second: Vec(u8)
|
||||
if !Load("stereo", "ogg", *first) || !Load("mono", "ogg", *second) { return Fail(311, "chained") }
|
||||
chained: Vec(u8)
|
||||
if !Copy(VecSlice(first, 0, first.count), *chained) || !Copy(VecSlice(second, 0, second.count), *chained) { return Fail(312, "chained") }
|
||||
pcm: PCM
|
||||
if VorbisInspect(VecSlice(chained, 0, chained.count), *info) != Unsupported || VorbisDecode(VecSlice(chained, 0, chained.count), MaxFrames, *pcm) != Unsupported { return Fail(313, "chained") }
|
||||
trailing: Vec(u8)
|
||||
if !Copy(VecSlice(first, 0, first.count), *trailing) || !Copy(VecSlice(prose, 0, prose.count), *trailing) { return Fail(314, "trailing") }
|
||||
if VorbisInspect(VecSlice(trailing, 0, trailing.count), *info) != Malformed { return Fail(315, "trailing") }
|
||||
// A flipped byte without a CRC refresh fails the container check.
|
||||
flipped: Vec(u8)
|
||||
if !Copy(VecSlice(first, 0, first.count), *flipped) { return Fail(316, "crc") }
|
||||
flipped[flipped.count / 2] ^= 1
|
||||
if VorbisInspect(VecSlice(flipped, 0, flipped.count), *info) != Malformed { return Fail(317, "crc") }
|
||||
// Corrupted payload bytes behind refreshed CRCs reach stb_vorbis: in the
|
||||
// setup header (codebooks) and in the audio packets. Every decode must
|
||||
// return a status without crashing, and an OK decode keeps the declared
|
||||
// length.
|
||||
names: [3]string = .["stereo", "rate48", "comments"]
|
||||
trials: s64; decoded_ok: s64
|
||||
for name: names {
|
||||
bytes: Vec(u8)
|
||||
if !Load(name, "ogg", *bytes) || VorbisInspect(VecSlice(bytes, 0, bytes.count), *info) != OK { return Fail(318, name) }
|
||||
skips: [2]s64 = .[1, 2]
|
||||
for skip: skips {
|
||||
ranges: Vec(s64)
|
||||
Bodies(VecSlice(bytes, 0, bytes.count), skip, *ranges)
|
||||
if ranges.count < 2 { return Fail(319, name) }
|
||||
for trial: cast(s64)0..99 {
|
||||
corrupt: Vec(u8)
|
||||
if !Copy(VecSlice(bytes, 0, bytes.count), *corrupt) { return Fail(320, name) }
|
||||
for flip: cast(s64)0..3 {
|
||||
range := ((trial * 7919 + flip * 104729) % (ranges.count / 2)) * 2
|
||||
start := ranges[range]; width := ranges[range + 1] - start
|
||||
corrupt[start + (trial * 31 + flip * 977) % width] ^= Random(*state) | 1
|
||||
}
|
||||
Recrc(VecSlice(corrupt, 0, corrupt.count))
|
||||
output: PCM
|
||||
corrupt_info: VorbisInfo
|
||||
code := VorbisDecode(VecSlice(corrupt, 0, corrupt.count), MaxFrames, *output)
|
||||
if code == OK {
|
||||
decoded_ok += 1
|
||||
if VorbisInspect(VecSlice(corrupt, 0, corrupt.count), *corrupt_info) != OK || output.samples.count != corrupt_info.frames * corrupt_info.channels { return Fail(321, name) }
|
||||
shorts: Vec(s16)
|
||||
if VorbisDecodeS16(VecSlice(corrupt, 0, corrupt.count), MaxFrames, *shorts, *corrupt_info) != OK || shorts.count != output.samples.count { return Fail(323, name) }
|
||||
} else if code != Malformed && code != Unsupported && code != LimitExceeded { print("% corrupt returned %\n", name, code); return Fail(322, name) }
|
||||
trials += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
print("vorbis corruption: % decodes of corrupted payloads returned a status (% decoded to the declared length)\n", trials, decoded_ok)
|
||||
return OK
|
||||
}
|
||||
Files :: () -> s32 {
|
||||
decoder: VorbisDecoder
|
||||
if VorbisDecoderOpenFile(*decoder, "tests/fixtures/vorbis/missing.ogg", MaxFrames) != IOFailure || decoder.handle != null { return Fail(400, "missing file") }
|
||||
path: Vec(u8)
|
||||
PathInto(*path, "stereo", "ogg")
|
||||
stereo_path := TextFromBytes(VecSlice(path, 0, path.count))
|
||||
if VorbisDecoderOpenFile(*decoder, stereo_path, MaxFrames) != OK { return Fail(401, "stereo file") }
|
||||
if VorbisDecoderOpenFile(*decoder, stereo_path, MaxFrames) != Invalid { VorbisDecoderClose(*decoder); return Fail(402, "reopen") }
|
||||
streamed: Vec(float32)
|
||||
code := Stream(*decoder, *streamed)
|
||||
VorbisDecoderClose(*decoder)
|
||||
bytes: Vec(u8)
|
||||
pcm: PCM
|
||||
if code != OK || !Load("stereo", "ogg", *bytes) || VorbisDecode(VecSlice(bytes, 0, bytes.count), MaxFrames, *pcm) != OK { return Fail(403, "stereo file") }
|
||||
if !Same(VecSlice(streamed, 0, streamed.count), VecSlice(pcm.samples, 0, pcm.samples.count)) { return Fail(404, "stereo file") }
|
||||
// Resampling through audio/resample's sinc, and the same-rate path.
|
||||
resampled: PCM
|
||||
if VorbisDecodeResampled(VecSlice(bytes, 0, bytes.count), MaxFrames, 48000, *resampled) != OK || resampled.rate != 48000 || resampled.channels != 2 { return Fail(405, "resample") }
|
||||
frames := resampled.samples.count / 2
|
||||
if frames < 14399 || frames > 14401 { return Fail(406, "resample") }
|
||||
same: PCM
|
||||
if VorbisDecodeResampled(VecSlice(bytes, 0, bytes.count), MaxFrames, 44100, *same) != OK || !Same(VecSlice(same.samples, 0, same.samples.count), VecSlice(pcm.samples, 0, pcm.samples.count)) { return Fail(407, "resample") }
|
||||
if VorbisDecodeResampled(VecSlice(bytes, 0, bytes.count), MaxFrames, 7999, *same) != Invalid { return Fail(408, "resample") }
|
||||
return OK
|
||||
}
|
||||
|
||||
#scope_export
|
||||
VorbisContracts :: () -> s32 {
|
||||
code := Fixtures()
|
||||
if code == OK { code = Comments() }
|
||||
if code == OK { code = Seeks("long", 176400) }
|
||||
if code == OK { code = Seeks("stereo", 13230) }
|
||||
if code == OK { code = Seeks("rate22", 6615) }
|
||||
if code == OK { code = Synthetic() }
|
||||
if code == OK { code = Errors() }
|
||||
if code == OK { code = Files() }
|
||||
if code == OK { print("native Vorbis contracts passed: 5 fixtures within % PCM16 steps (RMS %), exact granule lengths and seeks, comments, malformed input rejected\n", ToleranceSteps, ToleranceRms) }
|
||||
return code
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Synthetic Ogg Vorbis streams for portable inspection tests: real
|
||||
// identification and comment headers, a setup header holding filler bits and
|
||||
// a two-mode table (mode 0 short blocks, mode 1 long), and one-byte audio
|
||||
// packets that name a mode, one packet per page. No decoder accepts the
|
||||
// setup header; the streams exercise audio/ogg_vorbis's container, header,
|
||||
// block-size and granule checks.
|
||||
#import "types"
|
||||
#import "std/vec"
|
||||
#import "ogg"
|
||||
|
||||
#scope_file
|
||||
Bits :: struct { bytes: Vec(u8); count: s64; }
|
||||
Put :: (bits: *Bits, value: s64, width: s64) -> bool {
|
||||
for i: cast(s64)0..width - 1 {
|
||||
if bits.count % 8 == 0 && !VecPush(bits.bytes, 0) { return false }
|
||||
if ((value >> i) & 1) != 0 { bits.bytes[bits.count / 8] |= cast(u8)(1 << (bits.count % 8)) }
|
||||
bits.count += 1
|
||||
}
|
||||
return true
|
||||
}
|
||||
PutText :: (bits: *Bits, text: string) -> bool {
|
||||
for i: 0..text.count - 1 { if !Put(bits, cast(s64)text[i], 8) { return false } }
|
||||
return true
|
||||
}
|
||||
|
||||
#scope_export
|
||||
// Short and long block sizes of the synthetic streams.
|
||||
VorbisSyntheticShort :: 256
|
||||
VorbisSyntheticLong :: 2048
|
||||
// Frames returned by packet I of MODES (0 short, 1 long): none for the
|
||||
// first, then half of each neighbouring block.
|
||||
VorbisSyntheticFrames :: (modes: []u8) -> s64 {
|
||||
total: s64
|
||||
for i: cast(s64)1..modes.count - 1 {
|
||||
previous := ifx modes[i - 1] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
|
||||
current := ifx modes[i] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
|
||||
total += (previous + current) / 4
|
||||
}
|
||||
return total
|
||||
}
|
||||
// Appends a stream with CHANNELS at RATE whose audio packets use MODES. Page
|
||||
// granules count from START; the last one trims TRIM frames.
|
||||
VorbisSynthetic :: (output: *Vec(u8), channels: s32, rate: s32, modes: []u8, start: s64, trim: s64) -> bool {
|
||||
identification: [30]u8
|
||||
identification[0] = 1
|
||||
text := "vorbis"
|
||||
for i: 0..5 { identification[1 + i] = text[i] }
|
||||
identification[11] = cast(u8)channels
|
||||
PutLittle(identification[:], 12, 4, cast(u64)rate)
|
||||
PutLittle(identification[:], 20, 4, 96000)
|
||||
identification[28] = cast(u8)(8 | (11 << 4)); identification[29] = 1
|
||||
if AppendPage(output, identification[:], 2, 0, 9, 0) != OK { return false }
|
||||
comment: Bits
|
||||
if !Put(*comment, 3, 8) || !PutText(*comment, "vorbis") || !Put(*comment, 5, 32) || !PutText(*comment, "ziran") ||
|
||||
!Put(*comment, 1, 32) || !Put(*comment, 15, 32) || !PutText(*comment, "TITLE=synthetic") || !Put(*comment, 1, 8) { return false }
|
||||
if AppendPage(output, VecSlice(comment.bytes, 0, comment.bytes.count), 0, 0, 9, 1) != OK { return false }
|
||||
// Filler stands for the codebooks, floors, residues and mappings.
|
||||
setup: Bits
|
||||
if !Put(*setup, 5, 8) || !PutText(*setup, "vorbis") || !Put(*setup, 65535, 24) || !Put(*setup, 1, 6) { return false }
|
||||
for mode: 0..1 { if !Put(*setup, mode, 1) || !Put(*setup, 0, 16) || !Put(*setup, 0, 16) || !Put(*setup, 0, 8) { return false } }
|
||||
if !Put(*setup, 1, 1) { return false }
|
||||
if AppendPage(output, VecSlice(setup.bytes, 0, setup.bytes.count), 0, 0, 9, 2) != OK { return false }
|
||||
total: s64
|
||||
for i: cast(s64)0..modes.count - 1 {
|
||||
if i > 0 {
|
||||
previous := ifx modes[i - 1] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
|
||||
current := ifx modes[i] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
|
||||
total += (previous + current) / 4
|
||||
}
|
||||
last := i == modes.count - 1
|
||||
packet: [1]u8 = .[cast(u8)((cast(s32)modes[i] << 1) | (ifx modes[i] == 1 then 12 else 0))]
|
||||
granule := start + total - (ifx last then trim else 0)
|
||||
if AppendPage(output, packet[:], ifx last then cast(u8)4 else cast(u8)0, granule, 9, cast(u32)(3 + i)) != OK { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
+19
-11
@@ -1,7 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Windows x86_64 MinGW build of the pinned libopus/libsamplerate/dr_libs
|
||||
# Windows x86_64 MinGW build of the pinned libopus/libsamplerate/dr_libs/stb
|
||||
# sources and two codec programs, run under Wine and compared with the Linux
|
||||
# CLI on the `make test` Opus fixtures and the committed MP3 fixtures.
|
||||
# CLI on the `make test` Opus fixtures and the committed MP3 and Vorbis
|
||||
# fixtures.
|
||||
# Invoke through build-queue (`make windows-test`).
|
||||
# WINDOWS_CC names the MinGW compiler (default x86_64-w64-mingw32-gcc).
|
||||
set -eu
|
||||
@@ -17,7 +18,9 @@ fixtures=build/tests/fixtures
|
||||
decoded="short voice chirp external-1 external-2 full narrow vbr-off encoded-2"
|
||||
rejected="bad-crc truncated chained trailing bad-preskip"
|
||||
mp3s="cbr.mp3 vbr.mp3 mono.mp3 mpeg2.mp3 mpeg25.mp3 noxing.mp3 id3.mp3 layer2.mp2 long.mp3"
|
||||
mp3_names=$(for file in $mp3s; do printf '%s ' "${file%.*}"; done)
|
||||
# Vorbis copies are prefixed: mono and long also name MP3 fixtures.
|
||||
oggs="vorbis-stereo.ogg vorbis-mono.ogg vorbis-rate22.ogg vorbis-rate48.ogg vorbis-comments.ogg vorbis-long.ogg"
|
||||
mp3_names=$(for file in $mp3s $oggs; do printf '%s ' "${file%.*}"; done)
|
||||
for name in $decoded $rejected; do
|
||||
test -f "$fixtures/$name.opus" || { echo "missing $fixtures/$name.opus; run make test first" >&2; exit 1; }
|
||||
done
|
||||
@@ -33,12 +36,13 @@ samplerate=$("$ZIRAN" pkg path libsamplerate --offline)
|
||||
"$CMAKE" -S native -B "$out/native" -DCMAKE_SYSTEM_NAME=Windows -DCMAKE_SYSTEM_PROCESSOR=AMD64 \
|
||||
-DCMAKE_C_COMPILER="$(command -v "$windows_cc")" -DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY \
|
||||
-DCMAKE_BUILD_TYPE=Release -DOPUS_DIR="$opus" -DSAMPLERATE_DIR="$samplerate" \
|
||||
-DDR_LIBS_DIR="$("$ZIRAN" pkg path dr_libs --offline)" >"$out/cmake.log" 2>&1 &&
|
||||
-DDR_LIBS_DIR="$("$ZIRAN" pkg path dr_libs --offline)" -DSTB_DIR="$("$ZIRAN" pkg path stb --offline)" >"$out/cmake.log" 2>&1 &&
|
||||
"$CMAKE" --build "$out/native" --parallel 2 >>"$out/cmake.log" 2>&1 || { tail -n 40 "$out/cmake.log" >&2; exit 1; }
|
||||
libopus=$out/native/libopus/libopus.a
|
||||
libsamplerate=$out/native/libsamplerate/src/libsamplerate.a
|
||||
libmp3=$out/native/libziran_mp3.a
|
||||
test -f "$libopus" && test -f "$libsamplerate" && test -f "$libmp3"
|
||||
libvorbis=$out/native/libziran_vorbis.a
|
||||
test -f "$libopus" && test -f "$libsamplerate" && test -f "$libmp3" && test -f "$libvorbis"
|
||||
|
||||
# Nix splits mcfgthread's static runtime from its GCC wrapper; follow only
|
||||
# this compiler's declared inputs. Distribution MinGW needs no extra path.
|
||||
@@ -60,7 +64,7 @@ test -f "$ziran_root/include/zir_vec.h" || { echo "no Ziran C headers under $zir
|
||||
# libopus keeps its default stack protector and _FORTIFY_SOURCE, which on
|
||||
# MinGW resolve from GCC's static libssp.
|
||||
for program in decode encode; do
|
||||
libs="$libopus $libmp3"
|
||||
libs="$libopus $libmp3 $libvorbis"
|
||||
test "$program" = decode || libs="$libopus $libsamplerate"
|
||||
rm -rf "$out/$program-c"
|
||||
"$ZIRAN" build --target=c --no-main --define _WIN32 --define __x86_64__ --root tests \
|
||||
@@ -73,19 +77,22 @@ for program in decode encode; do
|
||||
echo "windows_$program.exe imports a non-system DLL" >&2; exit 1
|
||||
fi
|
||||
done
|
||||
printf 'windows: libopus, libsamplerate, libziran_mp3 and codec programs built with %s\n' "$("$windows_cc" -dumpversion)"
|
||||
printf 'windows: libopus, libsamplerate, libziran_mp3, libziran_vorbis and codec programs built with %s\n' "$("$windows_cc" -dumpversion)"
|
||||
|
||||
cd "$out/run"
|
||||
for name in $decoded $rejected; do cp "$root/$fixtures/$name.opus" .; done
|
||||
cp "$root/$fixtures/voice.wav" .
|
||||
for file in $mp3s; do cp "$root/tests/fixtures/mp3/$file" .; done
|
||||
for file in $oggs; do cp "$root/tests/fixtures/vorbis/${file#vorbis-}" "$file"; done
|
||||
head -c 4000 cbr.mp3 >cbr-truncated.mp3
|
||||
head -c 6000 vorbis-stereo.ogg >vorbis-truncated.ogg
|
||||
mkdir -p linux
|
||||
{
|
||||
for name in $decoded; do echo "inspect $name.opus"; echo "decode $name.opus $name-decoded.wav"; done
|
||||
for name in $rejected; do echo "reject $name.opus"; done
|
||||
for file in $mp3s; do echo "inspect $file"; echo "decode $file ${file%.*}-decoded.wav"; done
|
||||
for file in $mp3s $oggs; do echo "inspect $file"; echo "decode $file ${file%.*}-decoded.wav"; done
|
||||
echo "reject cbr-truncated.mp3"
|
||||
echo "reject vorbis-truncated.ogg"
|
||||
} >decode.commands
|
||||
# Linux reference: the CLI on the same inputs (reject = CLI decode status).
|
||||
rm -f linux/*
|
||||
@@ -93,10 +100,11 @@ rm -f linux/*
|
||||
"$root/build/bin/audio" inspect "../$name.opus"
|
||||
"$root/build/bin/audio" decode "../$name.opus" "$name-decoded.wav" >/dev/null
|
||||
done && for name in $rejected; do "$root/build/bin/audio" decode "../$name.opus" rejected.wav || :; done &&
|
||||
for file in $mp3s; do
|
||||
for file in $mp3s $oggs; do
|
||||
"$root/build/bin/audio" inspect "../$file"
|
||||
"$root/build/bin/audio" decode "../$file" "${file%.*}-decoded.wav" >/dev/null
|
||||
done && { "$root/build/bin/audio" decode ../cbr-truncated.mp3 rejected.wav || :; }
|
||||
done && { "$root/build/bin/audio" decode ../cbr-truncated.mp3 rejected.wav || :; } &&
|
||||
{ "$root/build/bin/audio" decode ../vorbis-truncated.ogg rejected.wav || :; }
|
||||
"$root/build/bin/audio" encode ../voice.wav voice.opus --bitrate 24000 --application voice --bandwidth wide --vbr constrained >/dev/null) >linux/linux.log
|
||||
rm -f ./*-decoded.wav windows-voice.opus
|
||||
# Wine state stays private to this output; package lookups above keep the
|
||||
@@ -135,4 +143,4 @@ xvfb-run -a -n 400 -s '-screen 0 640x480x24' env -u TMPDIR HOME="$root/$out/home
|
||||
' sh "$wine"
|
||||
cd "$root"
|
||||
# shellcheck disable=SC2086
|
||||
python3 tests/windows_compare.py "$out/run" build/bin/audio $decoded $mp3_names -- $rejected cbr-truncated
|
||||
python3 tests/windows_compare.py "$out/run" build/bin/audio $decoded $mp3_names -- $rejected cbr-truncated vorbis-truncated
|
||||
@@ -24,11 +24,14 @@ def worst(a, b):
|
||||
|
||||
windows_log = [line.strip() for line in (run / 'windows.log').read_text().splitlines() if line.strip()]
|
||||
linux_log = [line.strip() for line in (linux / 'linux.log').read_text().splitlines() if line.strip()]
|
||||
inspect_windows = [line for line in windows_log if line.startswith(('Opus:', 'MP3:'))]
|
||||
inspect_linux = [line for line in linux_log if line.startswith(('Opus:', 'MP3:'))]
|
||||
assert len(inspect_linux) == len(decoded) and inspect_windows == inspect_linux, (inspect_windows, inspect_linux)
|
||||
errors_windows = [line for line in windows_log if not line.startswith(('Opus:', 'MP3:', 'decoded and rewound', 'wrote'))]
|
||||
errors_linux = [line for line in linux_log if not line.startswith(('Opus:', 'MP3:'))]
|
||||
# One summary line per inspected file; Vorbis adds vendor and comment lines.
|
||||
INSPECT = ('Opus:', 'MP3:', 'Vorbis')
|
||||
inspect_windows = [line for line in windows_log if line.startswith(INSPECT)]
|
||||
inspect_linux = [line for line in linux_log if line.startswith(INSPECT)]
|
||||
summaries = [line for line in inspect_linux if line.startswith(('Opus:', 'MP3:', 'Vorbis:'))]
|
||||
assert len(summaries) == len(decoded) and inspect_windows == inspect_linux, (inspect_windows, inspect_linux)
|
||||
errors_windows = [line for line in windows_log if not line.startswith(INSPECT + ('decoded and rewound', 'wrote'))]
|
||||
errors_linux = [line for line in linux_log if not line.startswith(INSPECT)]
|
||||
assert len(errors_linux) == len(rejected) and errors_windows == errors_linux, (errors_windows, errors_linux)
|
||||
print(f'windows inspect: {len(decoded)} fixtures matched Linux; {len(rejected)} malformed fixtures rejected as on Linux')
|
||||
|
||||
@@ -58,4 +61,4 @@ print(f'windows encode voice.wav: {windows_opus.stat().st_size} bytes (Linux {li
|
||||
status = (run / 'resample.log').read_text().strip()
|
||||
assert status == 'unsupported audio capability', status
|
||||
print('windows resample: SincOpen returns Unsupported before libsamplerate (documented boundary)')
|
||||
print(f'windows x86_64 under Wine: native Opus and MP3 decode/rewind and Opus encode matched Linux ({exact}/{len(decoded)} decodes bit-exact)')
|
||||
print(f'windows x86_64 under Wine: native Opus, MP3 and Vorbis decode/rewind and Opus encode matched Linux ({exact}/{len(decoded)} decodes bit-exact)')
|
||||
+73
-6
@@ -1,15 +1,17 @@
|
||||
// Decoder-only Windows check, linked with libopus and libziran_mp3 like
|
||||
// Kryon's playback: `inspect IN`, `decode IN OUT.wav` and `reject IN` mirror
|
||||
// the Linux CLI, choosing Ogg Opus or MP3 from the content as it does.
|
||||
// Decode streams through DecoderOpen/DecoderRead (Mp3DecoderOpen/Read) in
|
||||
// irregular chunks, then rewinds and requires the second pass to be
|
||||
// identical before writing WAV.
|
||||
// Decoder-only Windows check, linked with libopus, libziran_mp3 and
|
||||
// libziran_vorbis like Kryon's playback: `inspect IN`, `decode IN OUT.wav`
|
||||
// and `reject IN` mirror the Linux CLI, choosing Ogg Vorbis, Ogg Opus or MP3
|
||||
// from the content as it does. Decode streams through DecoderOpen/DecoderRead
|
||||
// (Mp3DecoderOpen/Read, VorbisDecoderOpen/Read) in irregular chunks, then
|
||||
// rewinds and requires the second pass to be identical before writing WAV.
|
||||
#import "types"
|
||||
#import "opus"
|
||||
#import "ogg"
|
||||
#import "wav"
|
||||
#import "mpeg_audio"
|
||||
#import "mp3"
|
||||
#import "ogg_vorbis"
|
||||
#import "vorbis"
|
||||
#import "std/vec"
|
||||
#import "std/file"
|
||||
#import "std/byte_text_linux"
|
||||
@@ -76,6 +78,70 @@ Mp3Command :: (command: string, input: []u8, argc: s32, argv: **u8) -> s32 {
|
||||
print("decoded and rewound % frames\n", at)
|
||||
return 0
|
||||
}
|
||||
// The Vorbis half of main, as for MP3 over audio/vorbis.
|
||||
VorbisCommand :: (command: string, input: []u8, argc: s32, argv: **u8) -> s32 {
|
||||
if command == "inspect" {
|
||||
info: VorbisInfo
|
||||
comments: VorbisComments
|
||||
code := VorbisInspectComments(input, *info, *comments)
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
VorbisPrintInfo(*info)
|
||||
VorbisPrintComments(*comments)
|
||||
return 0
|
||||
}
|
||||
decoder: VorbisDecoder
|
||||
code := VorbisDecoderOpen(*decoder, input, MaxFrames)
|
||||
if command == "reject" {
|
||||
VorbisDecoderClose(*decoder)
|
||||
print("%\n", ErrorText(code))
|
||||
if code == OK { return 1 }
|
||||
return 0
|
||||
}
|
||||
if command != "decode" || argc != 4 { VorbisDecoderClose(*decoder); return Invalid }
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
defer { VorbisDecoderClose(*decoder) }
|
||||
channels := cast(s64)decoder.info.channels
|
||||
pcm: PCM
|
||||
pcm.rate = decoder.info.rate; pcm.channels = decoder.info.channels
|
||||
if decoder.info.frames > MaxFrames || !VecResize(pcm.samples, decoder.info.frames * channels) { return LimitExceeded }
|
||||
scratch: [1994]float32
|
||||
at: s64
|
||||
while true {
|
||||
frames: s64
|
||||
code = VorbisDecoderRead(*decoder, scratch[0:997 * channels], *frames)
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
if frames == 0 { break }
|
||||
for i: cast(s64)0..frames * channels - 1 { pcm.samples[at * channels + i] = scratch[i] }
|
||||
at += frames
|
||||
}
|
||||
// A seek to the middle, then a rewind, reproduce the first pass exactly.
|
||||
middle := at / 2
|
||||
if VorbisDecoderSeek(*decoder, middle) != OK { print("seek failed\n"); return NativeFailure }
|
||||
frames: s64
|
||||
code = VorbisDecoderRead(*decoder, scratch[0:997 * channels], *frames)
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
for i: cast(s64)0..frames * channels - 1 {
|
||||
if scratch[i] != pcm.samples[middle * channels + i] { print("seek differs at frame %\n", middle); return Malformed }
|
||||
}
|
||||
if VorbisDecoderRewind(*decoder) != OK { print("rewind failed\n"); return NativeFailure }
|
||||
again: s64
|
||||
while true {
|
||||
code = VorbisDecoderRead(*decoder, scratch[0:channels], *frames)
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
if frames == 0 { break }
|
||||
for i: cast(s64)0..channels - 1 {
|
||||
if scratch[i] != pcm.samples[again * channels + i] { print("rewind differs at frame %\n", again); return Malformed }
|
||||
}
|
||||
again += 1
|
||||
}
|
||||
if again != at { print("rewind decoded % of % frames\n", again, at); return Malformed }
|
||||
output: Vec(u8)
|
||||
code = WavEncode(*pcm, *output)
|
||||
if code != OK { print("%\n", ErrorText(code)); return code }
|
||||
if !WriteEntireFile(TextFromCString(argv[3]), TextFromBytes(VecSlice(output, 0, output.count))) { print("input/output failed\n"); return IOFailure }
|
||||
print("decoded and rewound % frames\n", at)
|
||||
return 0
|
||||
}
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
if argc < 3 { print("windows_decode inspect|decode|reject INPUT [OUTPUT.wav]\n"); return Invalid }
|
||||
@@ -83,6 +149,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
|
||||
bytes: Vec(u8)
|
||||
if !ReadFileInto(TextFromCString(argv[2]), *bytes) { print("input/output failed\n"); return IOFailure }
|
||||
input := VecSlice(bytes, 0, bytes.count)
|
||||
if VorbisProbe(input) { return VorbisCommand(command, input, argc, argv) }
|
||||
if !Magic(input, 0, "OggS") { return Mp3Command(command, input, argc, argv) }
|
||||
if command == "inspect" {
|
||||
info: Info
|
||||
|
||||
+11
-2
@@ -27,11 +27,20 @@
|
||||
"ref": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
|
||||
"source": true,
|
||||
"url": "https://github.com/xiph/opus.git"
|
||||
},
|
||||
{
|
||||
"commit": "9600522de53973336fa033a289858a4354cbb04c",
|
||||
"dependencies": {},
|
||||
"id": "pe4a63e2d6e0424e7",
|
||||
"name": "stb",
|
||||
"ref": "9600522de53973336fa033a289858a4354cbb04c",
|
||||
"source": true,
|
||||
"url": "https://github.com/nothings/stb.git"
|
||||
}
|
||||
],
|
||||
"root": {
|
||||
"dependencies": {"dr_libs": "pb7c2dd1c09da0c1c", "libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e"},
|
||||
"dependency_refs": {"dr_libs": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c", "libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
|
||||
"dependencies": {"dr_libs": "pb7c2dd1c09da0c1c", "libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e", "stb": "pe4a63e2d6e0424e7"},
|
||||
"dependency_refs": {"dr_libs": "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c", "libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7", "stb": "9600522de53973336fa033a289858a4354cbb04c"},
|
||||
"name": "audio"
|
||||
},
|
||||
"toolchain": {
|
||||
|
||||
+11
-2
@@ -2,7 +2,7 @@
|
||||
name = "audio"
|
||||
module_roots = ["src"]
|
||||
entry = "src/audio.zi"
|
||||
links = ["ziran_mp3", "opus", "samplerate", "m"]
|
||||
links = ["ziran_mp3", "ziran_vorbis", "opus", "samplerate", "m"]
|
||||
|
||||
[toolchain]
|
||||
git = "https://github.com/ziranlang/ziran.git"
|
||||
@@ -18,9 +18,13 @@ resample = "src/resample.zi"
|
||||
mpeg_audio = "src/mpeg_audio.zi"
|
||||
mp3 = "src/mp3.zi"
|
||||
mp3_resample = "src/mp3_resample.zi"
|
||||
ogg_vorbis = "src/ogg_vorbis.zi"
|
||||
vorbis = "src/vorbis.zi"
|
||||
vorbis_resample = "src/vorbis_resample.zi"
|
||||
|
||||
# Pinned native sources for platform builds; see native/. dr_libs supplies
|
||||
# dr_mp3 (public domain or MIT-0), compiled into libziran_mp3.a.
|
||||
# dr_mp3 (public domain or MIT-0), compiled into libziran_mp3.a; stb supplies
|
||||
# stb_vorbis (public domain or MIT), compiled into libziran_vorbis.a.
|
||||
[dependencies.libopus]
|
||||
git = "https://github.com/xiph/opus.git"
|
||||
ref = "ddbe48383984d56acd9e1ab6a090c54ca6b735a6"
|
||||
@@ -35,3 +39,8 @@ source = true
|
||||
git = "https://github.com/mackron/dr_libs.git"
|
||||
ref = "f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c"
|
||||
source = true
|
||||
|
||||
[dependencies.stb]
|
||||
git = "https://github.com/nothings/stb.git"
|
||||
ref = "9600522de53973336fa033a289858a4354cbb04c"
|
||||
source = true
|
||||
Reference in new issue
Block a user