From cfc481445b87b102d7587946e018b42eb22a1bde Mon Sep 17 00:00:00 2001 From: paul Date: Thu, 26 Nov 2026 20:52:20 +0000 Subject: [PATCH 1/2] Add contrib.xmp: a tracker-module player for std.audio contrib.xmp plays MOD, S3M, XM, IT, MED and the other formats libxmp reads, through std.audio. It is full libxmp (the player, every loader, ProWizard and the depackers), and std.audio stays the only audio output. API (contrib/xmp/module.ae): load(data, length) / load_file(path) -> ptr!, free; title, format, channels, patterns, orders, instruments, samples, duration_ms; start(p, rate), render(p, frames) -> string! (interleaved signed 16-bit stereo), render_all, seek_ms, set_order, position_ms, order, row, looping, ended; and through std.audio, sound(p, rate) (render_all into audio.load_pcm) and stream_open(p, rate, frames) + pump(p, src) (blocks pushed into an audio.stream_open ring). Each player owns its libxmp context and buffers; nothing runs on a thread of its own. libxmp's source is handled as contrib.sqlite's amalgamation is: contrib/xmp/libxmp.lock pins libxmp 4.7.4's GitHub release tarball by URL and SHA-256 (the checksum libxmp publishes for the release); scripts/fetch-libxmp.sh downloads it, refuses a mismatch, and extracts include/, src/ (no src/lite) and the licence into the gitignored contrib/xmp/libxmp/, with sources.txt taken from Makefile.vc's object lists. No configure or CMake. - make contrib (tests/scripts/contrib_build.sh) compiles those sources into build/contrib/libxmp.a beside libaether_xmp.a, cached by release, compiler and flags, and falls back to the system libxmp when the source cannot be fetched (LIBXMP_SYSTEM=1 forces it). - ae build --target compiles libxmp for the target (ae_vendored_xmp in tools/ae_cross.c, one cache slot per object), unless a CROSSBUILD_SYSROOT stages the archives; a binary release with no archives compiles it for the host the same way (tools/ae.c). - Release staging fetches the source and ships it, with libxmp's COPYING and contrib/xmp/NOTICE, plus the two archives; the install trim keeps the source; CI fetches it and runs the spec (valgrind on Linux, Windows) and the cross build. Tests: contrib/xmp/test_xmp.ae writes a ProTracker MOD and a Fast Tracker II XM byte by byte and asserts on the rendered PCM (sound, silence, exact length, seek and loop positions, refusals), with the std.audio half on the headless engine; tests/integration/libxmp_fetch (the fetch script, offline) and tests/integration/xmp_vendored_cross (zig). Co-Authored-By: Claude Opus 5.5 --- .github/scripts/contrib_check.sh | 7 + .github/scripts/trim_contrib_sources.sh | 3 + .github/workflows/ci.yml | 60 ++- .github/workflows/release.yml | 6 +- .gitignore | 3 + Makefile | 11 +- contrib/xmp/NOTICE | 44 ++ contrib/xmp/README.md | 186 +++++++ contrib/xmp/aether_xmp.c | 363 ++++++++++++++ contrib/xmp/libxmp.lock | 30 ++ contrib/xmp/module.ae | 262 ++++++++++ contrib/xmp/test_xmp.ae | 460 ++++++++++++++++++ docs/bootstrap-from-source.md | 3 + docs/stdlib-vs-contrib.md | 1 + .../20261126T205022Z-added-contrib-xmp.md | 16 + scripts/fetch-libxmp.sh | 131 +++++ scripts/stage-release.sh | 30 +- .../test_install_contrib_resolves.sh | 2 + .../test_install_host_bridges.sh | 2 + .../libxmp_fetch/test_libxmp_fetch.sh | 126 +++++ .../test_release_contrib_c_modules.sh | 33 +- .../test_release_cross_contrib_archives.sh | 11 +- .../test_trim_contrib_sources.sh | 12 + .../NEEDS_EXTERNAL_TOOLCHAIN | 4 + .../test_xmp_vendored_cross.sh | 113 +++++ tests/scripts/contrib_build.sh | 148 +++++- tools/ae.c | 98 +++- tools/ae_cross.c | 284 ++++++++++- tools/ae_internal.h | 12 + 29 files changed, 2421 insertions(+), 40 deletions(-) create mode 100644 contrib/xmp/NOTICE create mode 100644 contrib/xmp/README.md create mode 100644 contrib/xmp/aether_xmp.c create mode 100644 contrib/xmp/libxmp.lock create mode 100644 contrib/xmp/module.ae create mode 100644 contrib/xmp/test_xmp.ae create mode 100644 new_changelogs/20261126T205022Z-added-contrib-xmp.md create mode 100755 scripts/fetch-libxmp.sh create mode 100644 tests/integration/libxmp_fetch/test_libxmp_fetch.sh create mode 100644 tests/integration/xmp_vendored_cross/NEEDS_EXTERNAL_TOOLCHAIN create mode 100644 tests/integration/xmp_vendored_cross/test_xmp_vendored_cross.sh diff --git a/.github/scripts/contrib_check.sh b/.github/scripts/contrib_check.sh index 9edc09b8f..6c7c07f86 100755 --- a/.github/scripts/contrib_check.sh +++ b/.github/scripts/contrib_check.sh @@ -108,6 +108,13 @@ TESTS=( # pkg-config column: neither path needs one, and the veneer step above # SKIPs the entry when neither is available. "sqlite/roundtrip|$SQL/test_sqlite.ae||run|" + # xmp: the tracker-module player, built like sqlite: through the module's + # @link and the archives `make contrib` builds -- libxmp from the pinned + # source when it can be fetched, the system libxmp otherwise; the veneer + # step above SKIPs the entry when neither is there. Its modules are written + # by the test, and its std.audio half runs on the headless engine, so it + # needs no sound card. Leak-clean. + "xmp/player|contrib/xmp/test_xmp.ae||leak|" # templating/native: co-located spec (replaces the four # tests/integration/native_templating_* dirs). Pure Aether — no system # library, so no pkg-config column and nothing to skip on. diff --git a/.github/scripts/trim_contrib_sources.sh b/.github/scripts/trim_contrib_sources.sh index 97f7a1e59..338505f7e 100755 --- a/.github/scripts/trim_contrib_sources.sh +++ b/.github/scripts/trim_contrib_sources.sh @@ -9,6 +9,7 @@ # as contrib.d3d12 and contrib.metal do with theirs (#2208); # - contrib/sqlite/aether_sqlite.c and the fetched SQLite amalgamation, # which `ae build --target` compiles for the target (#1372); +# - contrib/xmp/aether_xmp.c and the fetched libxmp source, likewise; # - the fetched QuickJS amalgamation, which contrib/quickjs/aether_quickjs.c # (kept by its @source) #includes rather than naming with @source; # - with --keep-host-bridges, contrib/host//aether_host_.c, @@ -71,6 +72,8 @@ find "$dir" -type f \( -name '*.c' -o -name '*.m' \) | while IFS= read -r f; do # foreign target, so they ship as source. case "$f" in */contrib/sqlite/aether_sqlite.c|*/contrib/sqlite/amalgamation/*.c) continue ;; + # The same for contrib.xmp: its veneer and the fetched libxmp source. + */contrib/xmp/aether_xmp.c|*/contrib/xmp/libxmp/*) continue ;; # aether_quickjs.c #includes the QuickJS amalgamation, so no @source # names it; without this it was deleted and an installed # contrib.quickjs could not build. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f1ed7118..25438c818 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -585,7 +585,7 @@ jobs: # simply never used. Split restore/save as for the miniaudio object. # ============================================================ ci-sqlite-cross: - name: contrib.sqlite / self-contained cross builds + name: contrib.sqlite + contrib.xmp / self-contained cross builds runs-on: ubuntu-26.04 timeout-minutes: 30 @@ -605,15 +605,16 @@ jobs: path: | .zig .ci-cache/ae-cross - key: sqlite-xobj-${{ hashFiles('scripts/get-zig.sh', 'tools/ae_zig_pin.h', 'contrib/sqlite/amalgamation.lock') }}-${{ hashFiles('tools/ae_cross.c') }} + key: sqlite-xobj-${{ hashFiles('scripts/get-zig.sh', 'tools/ae_zig_pin.h', 'contrib/sqlite/amalgamation.lock', 'contrib/xmp/libxmp.lock') }}-${{ hashFiles('tools/ae_cross.c') }} restore-keys: | - sqlite-xobj-${{ hashFiles('scripts/get-zig.sh', 'tools/ae_zig_pin.h', 'contrib/sqlite/amalgamation.lock') }}- + sqlite-xobj-${{ hashFiles('scripts/get-zig.sh', 'tools/ae_zig_pin.h', 'contrib/sqlite/amalgamation.lock', 'contrib/xmp/libxmp.lock') }}- - - name: Provision zig and the SQLite amalgamation + - name: Provision zig, the SQLite amalgamation and the libxmp source run: | ZIG="$(./scripts/get-zig.sh "$GITHUB_WORKSPACE/.zig")" echo "$(dirname "$ZIG")" >> "$GITHUB_PATH" sh scripts/fetch-sqlite-amalgamation.sh + sh scripts/fetch-libxmp.sh - name: Build the toolchain run: make -j"$(nproc)" compiler ae stdlib @@ -628,6 +629,17 @@ jobs: # aarch64 must actually have run, not been skipped for want of qemu. echo "$out" | grep -q 'aarch64-linux-musl: built, ran the spec' + # contrib.xmp the same way: libxmp's sources compiled per target, cached + # in the same directory, and the module's spec run on both targets. + - name: Cross-build and run contrib.xmp + env: + AETHER_CACHE_DIR: ${{ github.workspace }}/.ci-cache/ae-cross + run: | + out="$(sh tests/integration/xmp_vendored_cross/test_xmp_vendored_cross.sh)" + echo "$out" + echo "$out" | grep -q '\[PASS\]' + echo "$out" | grep -q 'aarch64-linux-musl: built, ran the spec' + # A macOS dylib cross-linked on Linux: its install name and minimum are # read from the Mach-O load commands. A Mac host rewrites the id after the # link, so only a non-Mac host catches a cross link that left it unset. @@ -648,7 +660,7 @@ jobs: path: | .zig .ci-cache/ae-cross - key: sqlite-xobj-${{ hashFiles('scripts/get-zig.sh', 'tools/ae_zig_pin.h', 'contrib/sqlite/amalgamation.lock') }}-${{ hashFiles('tools/ae_cross.c') }} + key: sqlite-xobj-${{ hashFiles('scripts/get-zig.sh', 'tools/ae_zig_pin.h', 'contrib/sqlite/amalgamation.lock', 'contrib/xmp/libxmp.lock') }}-${{ hashFiles('tools/ae_cross.c') }} ci-freebsd-native: name: FreeBSD / native build + unit tests @@ -784,6 +796,18 @@ jobs: - name: Fetch the pinned SQLite amalgamation run: sh scripts/fetch-sqlite-amalgamation.sh + # contrib.xmp compiles the pinned libxmp source into build/contrib/ + # libxmp.a the same way, fetched explicitly for the same reason. + - name: Fetch the pinned libxmp source + run: sh scripts/fetch-libxmp.sh + + - name: Restore libxmp archive cache + id: libxmp_obj_cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .ci-cache/libxmp + key: libxmp-obj-ubuntu-22.04-${{ hashFiles('contrib/xmp/libxmp.lock', 'tests/scripts/contrib_build.sh') }} + # The amalgamation's object costs most of a minute to compile; cache it the # way the miniaudio object is cached. contrib_build.sh names each object by # a hash of its source, compiler and flags, so a restored directory can @@ -817,6 +841,15 @@ jobs: path: .ci-cache/sqlite key: sqlite-obj-ubuntu-22.04-${{ hashFiles('contrib/sqlite/amalgamation.lock', 'tests/scripts/contrib_build.sh') }} + - name: Save libxmp archive cache (merge to main, on miss only) + if: >- + github.event_name == 'push' && github.ref == 'refs/heads/main' + && steps.libxmp_obj_cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .ci-cache/libxmp + key: libxmp-obj-ubuntu-22.04-${{ hashFiles('contrib/xmp/libxmp.lock', 'tests/scripts/contrib_build.sh') }} + # A driver is installed above, so contrib/vulkan skipping here would mean # the GPU path silently stopped being covered. Fail instead. - name: Assert the Vulkan test actually ran @@ -1320,6 +1353,14 @@ jobs: path: .ci-cache/sqlite key: sqlite-obj-windows-${{ hashFiles('contrib/sqlite/amalgamation.lock', 'tests/scripts/contrib_build.sh') }} + # And contrib.xmp's libxmp archive, built from its pinned source. + - name: Restore libxmp archive cache + id: libxmp_obj_cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .ci-cache/libxmp + key: libxmp-obj-windows-${{ hashFiles('contrib/xmp/libxmp.lock', 'tests/scripts/contrib_build.sh') }} + - name: Build and run the contrib series # contrib_check.sh probes for each entry's libraries with pkg-config and # skips the entries whose dependency is absent, so this reports what this @@ -1369,6 +1410,15 @@ jobs: path: .ci-cache/sqlite key: sqlite-obj-windows-${{ hashFiles('contrib/sqlite/amalgamation.lock', 'tests/scripts/contrib_build.sh') }} + - name: Save libxmp archive cache (merge to main, on miss only) + if: >- + github.event_name == 'push' && github.ref == 'refs/heads/main' + && steps.libxmp_obj_cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .ci-cache/libxmp + key: libxmp-obj-windows-${{ hashFiles('contrib/xmp/libxmp.lock', 'tests/scripts/contrib_build.sh') }} + # lavapipe is installed above, so a Vulkan entry that skipped would be # coverage silently lost. The same assertion as the Linux leg's. - name: Assert the Vulkan tests actually ran diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9564f9f8e..b8382edbe 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -910,14 +910,16 @@ jobs: TARGET=freebsd-x86_64 # The cross-built aetherc cannot run here, so no module artifacts: # the FreeBSD archive's imports parse the sources. contrib.sqlite's - # archives (lib/contrib/libaether_sqlite.a, libsqlite3.a) are built + # archives (lib/contrib/libaether_sqlite.a, libsqlite3.a) and + # contrib.xmp's (libaether_xmp.a, libxmp.a) are built # for FreeBSD with the same zig and sysroot, as the Linux and macOS # legs build theirs natively: without them `-laether_sqlite` failed # against a FreeBSD release (sae on ghostbsd, 2026-11-11). PATH="$(dirname "${{ steps.prov.outputs.zig }}"):$PATH" \ AETHER_SYSROOT="${{ steps.prov.outputs.sysroot }}" \ sh scripts/stage-release.sh build/.alien/freebsd-x86_64 release --contrib-target x86_64-freebsd.15.0 - ls -l release/lib/contrib/libaether_sqlite.a release/lib/contrib/libsqlite3.a + ls -l release/lib/contrib/libaether_sqlite.a release/lib/contrib/libsqlite3.a \ + release/lib/contrib/libaether_xmp.a release/lib/contrib/libxmp.a # Note the cross-build in the archive so downstream users know it was # not run through the test suite on FreeBSD. echo "Cross-built for FreeBSD with zig cc; not run through the test suite on FreeBSD." \ diff --git a/.gitignore b/.gitignore index a67c4a87f..904fea168 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,6 @@ compiler/aether_frontend_id.h # Fetched by scripts/fetch-quickjs-amalgamation.sh; pinned in # contrib/quickjs/amalgamation.lock, never committed. /contrib/quickjs/amalgamation/ +# Fetched by scripts/fetch-libxmp.sh; pinned in contrib/xmp/libxmp.lock, +# never committed. +/contrib/xmp/libxmp/ diff --git a/Makefile b/Makefile index 6a60696aa..055caae0c 100644 --- a/Makefile +++ b/Makefile @@ -1904,6 +1904,10 @@ test-release-archive: compiler ae stdlib check-archive-exports test -f "$$verdir/share/aether/tools/ae-fetch/main.ae" || (echo " FAIL: the package fetcher's source is missing (#1362)"; exit 1) && \ test -f "$$verdir/share/aether/contrib/sqlite/amalgamation/sqlite3.c" || (echo " FAIL: the SQLite amalgamation is missing (#1372)"; exit 1) && \ test -f "$$verdir/share/aether/contrib/quickjs/amalgamation/quickjs-amalgam.c" || (echo " FAIL: the QuickJS amalgamation is missing"; exit 1) && \ + test -f "$$verdir/share/aether/contrib/xmp/libxmp/sources.txt" || (echo " FAIL: the libxmp source is missing"; exit 1) && \ + test -f "$$verdir/share/aether/contrib/xmp/libxmp/src/player.c" || (echo " FAIL: libxmp's sources were trimmed from the archive"; exit 1) && \ + test -f "$$verdir/share/aether/contrib/xmp/libxmp/COPYING" || (echo " FAIL: libxmp's licence is missing"; exit 1) && \ + test -f "$$verdir/share/aether/contrib/xmp/NOTICE" || (echo " FAIL: contrib/xmp/NOTICE is missing"; exit 1) && \ test -s "$$verdir/share/aether/MANIFEST" || (echo " FAIL: share/aether/MANIFEST missing; ae cannot build from source without it"; exit 1) && \ shipped_specs=$$(find "$$verdir/share/aether" -type f -name 'test_*.ae' | head -5) && \ { test -z "$$shipped_specs" || (echo " FAIL: co-located specs shipped in the archive (#1584):"; echo "$$shipped_specs" | sed 's/^/ /'; exit 1); } && \ @@ -2985,6 +2989,7 @@ install: $(VERSION_HEADER) release-build ae stdlib # Modules covered (v1): # - sqlite (-lsqlite3) # - avcodec (FFmpeg's decode libraries) +# - xmp (libxmp: the pinned source, else -lxmp) # - host/stunt (the test double; dlopens libstunt) # - host/aether (fork+exec sandboxed child via LD_PRELOAD; # libc + in-tree sandbox runtime only) @@ -3482,7 +3487,11 @@ check-extern-widths: compiler ae stdlib @./$(EXTERN_WIDTHS_CHECKER) --root tests/extern_widths/fixture --expect 13 tests/extern_widths/fixture \ > $(BUILD_DIR)/extern_widths/self_test.log 2>&1 || \ { cat $(BUILD_DIR)/extern_widths/self_test.log; exit 1; } - @./$(EXTERN_WIDTHS_CHECKER) --exclude tests/extern_widths/fixture $(EXTERN_WIDTHS_DIRS) + @# contrib/xmp/libxmp is libxmp's fetched release source, which no + @# extern binds (contrib/xmp/aether_xmp.c does). Read as text it seems to + @# define stb_vorbis_* twice, but its vorbis.h renames those to + @# libxmp_vorbis_*, and its tempfile.h its mkstemp to libxmp_mkstemp. + @./$(EXTERN_WIDTHS_CHECKER) --exclude tests/extern_widths/fixture --exclude contrib/xmp/libxmp $(EXTERN_WIDTHS_DIRS) # ----------------------------------------------------------------- # Raw calls (#3107): a std module binds C through `*_raw` externs and diff --git a/contrib/xmp/NOTICE b/contrib/xmp/NOTICE new file mode 100644 index 000000000..69538b7c1 --- /dev/null +++ b/contrib/xmp/NOTICE @@ -0,0 +1,44 @@ +contrib.xmp and libxmp +====================== + +contrib.xmp plays tracker modules through libxmp, the Extended Module +Player library: + + https://github.com/libxmp/libxmp + +The libxmp release pinned in libxmp.lock is not committed here. +scripts/fetch-libxmp.sh downloads it, checks its SHA-256, and extracts it +into libxmp/ unchanged, together with its licence (libxmp/COPYING); release +archives ship that directory as it was extracted. libxmp is distributed +under the MIT License, reproduced below. + +Extended Module Player +Copyright (C) 1996-2026 Claudio Matsuoka and Hipolito Carraro Jr + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Components inside libxmp +------------------------ + +Some of libxmp's source files come from other projects and carry their own +copyright and licence notices in the files themselves, which ship unchanged: +among them the LHA decoder (lhasa: ISC licence), miniz's inflate and zip +reader (MIT), stb_vorbis (public domain or MIT), the xz decoder (public +domain), the bzip2 decoder (0BSD), MD5 (public domain), and BSD-licensed +fnmatch and mkstemp. Those notices, in libxmp/src/, are part of this notice. diff --git a/contrib/xmp/README.md b/contrib/xmp/README.md new file mode 100644 index 000000000..4a7e0110a --- /dev/null +++ b/contrib/xmp/README.md @@ -0,0 +1,186 @@ +# contrib.xmp: a tracker-module player for std.audio + +Plays tracker modules (MOD, S3M, XM, IT, MED and the rest of the formats +[libxmp](https://github.com/libxmp/libxmp) reads) through `std.audio`. It is +full libxmp: the player, every loader, ProWizard and the depackers, not +libxmp-lite. A player renders interleaved signed 16-bit stereo PCM, and +std.audio plays it, either the whole module at once or block by block into +a stream source. contrib.xmp has no audio output of its own: std.audio +(miniaudio) is the only backend. + +It lives in `contrib/` because it is not something every program expects of +a standard library, and libxmp is a sizeable C library fetched against a +pinned checksum. See [docs/stdlib-vs-contrib.md](../../docs/stdlib-vs-contrib.md). + +## Playing a module + +```aether +import std.audio +import std.fs +import contrib.xmp + +main() { + data, n, rerr = fs.read_binary("song.xm") + if rerr != "" { println(rerr); return } + p, err = xmp.load(data, n) + if err != "" { println(err); return } + defer xmp.free(p) + println("${xmp.title(p)} (${xmp.format(p)}), ${xmp.duration_ms(p)} ms") + + if !audio.open() { return } + // A ring of half a second; pump keeps it full. + src, serr = xmp.stream_open(p, 48000, 24000) + if serr != "" { println(serr); return } + _ = audio.play(src) + while !xmp.ended(p) { + _, _ = xmp.pump(p, src) + sleep(100) + } + // ... let the ring drain, then + audio.unload(src) + audio.close() +} +``` + +For a short module, or one played many times, render it once instead: +`src, err = xmp.sound(p, 48000)` gives a std.audio source of the whole song +(via `audio.load_pcm`) that plays, seeks and loops like any other source. + +## API + +All errors follow contrib.sqlite and std.audio: a fallible call returns +`(value, "")` or `(null / "" / -1, reason)`, and the reason is a static +string beginning `xmp:` (or `audio:` from std.audio). + +### Loading and freeing + +| Call | Returns | | +|---|---|---| +| `xmp.load(data, length)` | `ptr!` | A module from its bytes (as `fs.read_binary` gives them). The bytes are copied, and never read past the string's own length. | +| `xmp.load_file(path)` | `ptr!` | A module from a file; libxmp unpacks a packed one (zip, gzip, xz, LHA, PowerPacker, ...) itself. | +| `xmp.free(p)` | | Release the player and its module. `null` is a no-op. | + +Bytes that are no module, an empty input, a truncated module or a missing +file are refused with a reason and no player. + +### Module info + +`xmp.title(p)`, `xmp.format(p)` (strings, owned copies), `xmp.channels(p)`, +`xmp.patterns(p)`, `xmp.orders(p)` (the length of the order list), +`xmp.instruments(p)`, `xmp.samples(p)` and `xmp.duration_ms(p)` (libxmp's +scan of the main sequence, once through). All are valid from `load` on. + +### Playing + +| Call | Returns | | +|---|---|---| +| `xmp.start(p, sample_rate)` | `string` | Start, or restart, from the top at 4000 to 768000 Hz. `""` or the reason. | +| `xmp.render(p, frames)` | `string!` | The next `frames` frames, `frames * xmp.FRAME_BYTES` bytes (FRAME_BYTES is 4). Fewer at the end of a module that is not looping, `""` once it has ended. Up to 4,194,304 frames a call. | +| `xmp.render_all(p)` | `string!` | From where the player stands to the end, once, looping held off for the call. Refused past 30 minutes. | +| `xmp.seek_ms(p, ms)` | `string` | Move to `ms` into the module, to the libxmp frame (a tick). | +| `xmp.set_order(p, order)` | `string` | Move to the start of entry `order` of the order list. | +| `xmp.position_ms(p)` | `int` | Where the next rendered frame falls, in ms. | +| `xmp.order(p)`, `xmp.row(p)` | `int` | The order-list entry and pattern row now playing. | +| `xmp.looping(p, on)`, `xmp.is_looping(p)` | | Wrap at the end (on) or stop there (off, the default). | +| `xmp.ended(p)` | `bool` | A module that is not looping has played to its end. | + +The PCM is std.audio's `FORMAT_S16`: signed 16-bit, two channels +interleaved, in the machine's byte order (little-endian on every target). + +### Through std.audio + +| Call | Returns | | +|---|---|---| +| `xmp.sound(p, sample_rate)` | `ptr!` | `start`, `render_all`, then `audio.load_pcm`: a std.audio source of the whole module. Release it with `audio.unload`. | +| `xmp.stream_open(p, sample_rate, capacity_frames)` | `ptr!` | `start`, then `audio.stream_open` with a ring of `capacity_frames`, filled once by `pump`. Release it with `audio.unload`. | +| `xmp.pump(p, src)` | `int!` | Render as much as the ring has room for and push it. The frames pushed: 0 when the ring is full or the module has ended. | + +## Threading + +A player belongs to one thread at a time, and every call does its work on +the calling thread, there and then. Nothing in contrib.xmp starts a thread +or needs a callback. With a stream source, std.audio's mixer thread drains +the ring on its own while the thread that owns the player calls `pump` +often enough to keep it from running dry: a ring of `capacity_frames` lasts +`capacity_frames / sample_rate` seconds, so pump at least twice in that +time. `audio.stream_underruns(src)` counts any silence the mixer had to +substitute. Each player has its own libxmp context; there is no state +shared between players, so two players on two threads are independent. + +## Build + +`import contrib.xmp` is all a program needs. The module's `@link` +(`-laether_xmp -lxmp -lm`) puts the libraries on the link line. + +### Where libxmp comes from + +libxmp is compiled from its release source, pinned by version, URL and +SHA-256 in [`libxmp.lock`](libxmp.lock) (libxmp **4.7.4**, the release +tarball from libxmp's GitHub releases; its SHA-256 is the one libxmp +publishes in the release notes). It is not committed: +[`scripts/fetch-libxmp.sh`](../../scripts/fetch-libxmp.sh) downloads it, +refuses it unless the checksum matches, and extracts `include/`, `src/` +(without `src/lite`), `COPYING` and `README` into `contrib/xmp/libxmp/` +(gitignored), with `sources.txt`: the C files libxmp's own `Makefile.vc` +compiles for the full library (its `OBJS`, `PROWIZ_OBJS` and +`DEPACKER_OBJS`). libxmp's `configure` and CMake are not used. Release +archives ship the extracted directory, so an installed toolchain never +fetches anything. + +- **Native (`make contrib`).** The veneer builds into + `build/contrib/libaether_xmp.a`, and libxmp's sources into + `build/contrib/libxmp.a` beside it, which `-lxmp` resolves to ahead of any + system library: the program carries libxmp and needs none where it runs. + `make install-contrib` installs both. The archive is cached in + `.ci-cache/libxmp/` (`LIBXMP_OBJ_CACHE_DIR`), keyed by the release, the + compiler and the flags. +- **Cross (`ae build --target=`).** The veneer and libxmp are + compiled for the target with zig cc, each of libxmp's objects cached per + target in the ae cache (`~/.aether/cache`, or `AETHER_CACHE_DIR`). The + first build for a target prints `Compiling libxmp for `. A + `CROSSBUILD_SYSROOT` staging `libaether_xmp.a` and `libxmp.a` still takes + precedence. +- **No archives (a binary release, or a tree without `make contrib`).** + `ae build` compiles the veneer and the libxmp source shipped in + `share/aether/contrib/xmp/` with the host compiler, caches the objects and + the archive, and links them in place of `-laether_xmp -lxmp`. +- **System library (fallback).** When the source cannot be fetched + (offline, no `curl`/`wget`) or `LIBXMP_SYSTEM=1` is set, `make contrib` + builds the veneer against the system `xmp.h` and `-lxmp` links the system + libxmp (`libxmp-dev` on Debian and Ubuntu, `libxmp` in Homebrew, MSYS2, + FreeBSD ports). Cross builds have no such fallback. + +The one compile flag, `LIBXMP_STATIC`, lives in the lock's `LIBXMP_CFLAGS` +and is part of every cache key. With no `HAVE_*` flags libxmp never starts +a helper program to unpack a module, which is the configuration +`Makefile.vc` builds. + +### Moving to a newer libxmp + +Change the four values in `libxmp.lock` (`LIBXMP_VERSION`, `LIBXMP_URL`, +`LIBXMP_SHA256`, `LIBXMP_CFLAGS`), checking the SHA-256 against the one in +libxmp's release notes, run `scripts/fetch-libxmp.sh`, run the tests below, +and update the version in this README. + +## Test + +```sh +ONLY="xmp/" bash .github/scripts/contrib_check.sh # the module spec, test_xmp.ae +sh tests/integration/libxmp_fetch/test_libxmp_fetch.sh # the fetch script, offline +sh tests/integration/xmp_vendored_cross/test_xmp_vendored_cross.sh # needs zig +``` + +The spec writes its own modules, byte by byte: a four-channel ProTracker MOD +and a two-channel Fast Tracker II XM, each one looped square-wave sample that +sounds for the first half of the song and is silenced for the second. It +asserts on the rendered PCM (sound where the note plays, silence where it +does not, the song's exact length, where seeking and looping land) and runs +its std.audio half on std.audio's headless engine, so it needs no sound +card. No third-party music is in the tree. + +## Licence + +libxmp is MIT-licensed, Copyright (C) 1996-2026 Claudio Matsuoka and +Hipolito Carraro Jr; some of its source files come from other projects under +their own notices. See [NOTICE](NOTICE), which release archives ship with +`libxmp/COPYING`. diff --git a/contrib/xmp/aether_xmp.c b/contrib/xmp/aether_xmp.c new file mode 100644 index 000000000..b8d9918a2 --- /dev/null +++ b/contrib/xmp/aether_xmp.c @@ -0,0 +1,363 @@ +/* contrib/xmp — a tracker-module player for std.audio, over libxmp. + * + * libxmp (https://github.com/libxmp/libxmp, MIT; see NOTICE) loads and + * renders MOD, S3M, XM, IT, MED and the other formats it reads. This file is + * the thin C side of contrib.xmp: one XmpPlayer per module, holding its own + * libxmp context, render buffer and error, so two players never share state + * and nothing here is a mutable global. + * + * Surface (module.ae wraps it; the raw names are not for callers): + * aether_xmp_new() -> XmpPlayer* (NULL out of memory) + * aether_xmp_free(p) -> void (NULL is a no-op) + * aether_xmp_load_memory(p, data, n) -> int (0, or -XMP_ERROR_*) + * aether_xmp_load_path(p, path) -> int + * aether_xmp_strerror(code) -> const char* (static text) + * aether_xmp_title / format(p) -> AetherString* (owned copies) + * aether_xmp_channels / patterns / orders / instruments / samples(p) -> int + * aether_xmp_duration_ms(p) -> int + * aether_xmp_start(p, rate) -> int (0, or -XMP_ERROR_*) + * aether_xmp_render(p, frames) -> int (bytes in the buffer, or -code) + * aether_xmp_render_all(p) -> int (the same, to the end) + * aether_xmp_buffer(p) -> void* (the bytes render left) + * aether_xmp_seek_ms(p, ms) / set_order(p, order) -> int + * aether_xmp_position_ms / order / row(p) -> int + * aether_xmp_set_looping(p, on) / is_looping / ended(p) -> int + * + * PCM is interleaved signed 16-bit stereo in the host's byte order (every + * target Aether builds for is little-endian: std.audio's FORMAT_S16). + * + * Threading: a player is used by one thread at a time. render() does all the + * work synchronously on the caller's thread; nothing here starts a thread or + * needs pumping. Feeding std.audio is the caller pushing rendered blocks into + * a stream source (module.ae's pump), whose ring the mixer thread drains. + */ + +#include +#include +#include + +#include + +#include "../../std/string/aether_string.h" + +#define XMP_BYTES_PER_FRAME 4 /* 16-bit stereo */ +/* render(): one call's ceiling, std.audio's own render limit. */ +#define XMP_MAX_BLOCK_FRAMES 4194304 +/* render_all(): a module that never ends (its scan found no end and looping + * is off, which libxmp should not allow, or a pathological one) stops here + * rather than filling memory: 30 minutes at the highest rate fits an int. */ +#define XMP_MAX_ALL_MS (30 * 60 * 1000) + +typedef struct XmpPlayer { + xmp_context ctx; + int loaded; /* a module is loaded */ + int playing; /* start() succeeded */ + int rate; /* sample rate start() was given */ + int looping; /* 1: wrap at the end; 0: stop there */ + int ended; /* not looping, and the end was reached */ + int loop_base; /* libxmp's loop_count when end detection was armed */ + /* The part of libxmp's last frame not yet handed out. */ + const unsigned char* left; + int left_bytes; + /* The block render() fills; grown as needed, freed with the player. */ + unsigned char* buf; + size_t buf_cap; +} XmpPlayer; + +void* aether_xmp_new(void) { + XmpPlayer* p = (XmpPlayer*)calloc(1, sizeof(XmpPlayer)); + if (!p) return NULL; + p->ctx = xmp_create_context(); + if (!p->ctx) { free(p); return NULL; } + return p; +} + +void aether_xmp_free(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return; + if (p->playing) xmp_end_player(p->ctx); + if (p->loaded) xmp_release_module(p->ctx); + xmp_free_context(p->ctx); + free(p->buf); + free(p); +} + +const char* aether_xmp_strerror(int code) { + switch (code < 0 ? -code : code) { + case 0: return ""; + case XMP_END: return "xmp: the module has ended"; + case XMP_ERROR_INTERNAL: return "xmp: internal error"; + case XMP_ERROR_FORMAT: return "xmp: not a module format libxmp recognises"; + case XMP_ERROR_LOAD: return "xmp: the module is damaged or truncated"; + case XMP_ERROR_DEPACK: return "xmp: the packed module could not be unpacked"; + case XMP_ERROR_SYSTEM: return "xmp: system error (cannot read the file, or out of memory)"; + case XMP_ERROR_INVALID: return "xmp: invalid argument"; + case XMP_ERROR_STATE: return "xmp: the player is not in a state for that (load, then start)"; + default: return "xmp: error"; + } +} + +static void xmp_unload(XmpPlayer* p) { + if (p->playing) { xmp_end_player(p->ctx); p->playing = 0; } + if (p->loaded) { xmp_release_module(p->ctx); p->loaded = 0; } + p->left = NULL; p->left_bytes = 0; p->ended = 0; +} + +/* `data` is declared `@aether string` (docs/c-interop.md, #3297): the + * counted string itself, so its own length bounds the read and a module's + * bytes are never mistaken for a string header. */ +int aether_xmp_load_memory(void* vp, const void* data, int length) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + const char* bytes = data ? aether_string_data(data) : NULL; + size_t have = data ? aether_string_length(data) : 0; + if (length > 0 && (size_t)length > have) length = (int)have; + if (!bytes || length <= 0) return -XMP_ERROR_FORMAT; /* nothing to recognise */ + xmp_unload(p); + int rc = xmp_load_module_from_memory(p->ctx, bytes, (long)length); + if (rc < 0) return rc; + p->loaded = 1; + return 0; +} + +/* `path` is a plain `string`: its characters. */ +int aether_xmp_load_path(void* vp, const char* path) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + if (!path || !path[0]) return -XMP_ERROR_INVALID; + xmp_unload(p); + int rc = xmp_load_module(p->ctx, path); + if (rc < 0) return rc; + p->loaded = 1; + return 0; +} + +static struct xmp_module* xmp_mod(XmpPlayer* p, struct xmp_module_info* mi) { + if (!p || !p->loaded) return NULL; + xmp_get_module_info(p->ctx, mi); + return mi->mod; +} + +void* aether_xmp_title(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return string_new(m ? m->name : ""); +} + +void* aether_xmp_format(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return string_new(m ? m->type : ""); +} + +int aether_xmp_channels(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return m ? m->chn : 0; +} + +int aether_xmp_patterns(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return m ? m->pat : 0; +} + +int aether_xmp_orders(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return m ? m->len : 0; +} + +int aether_xmp_instruments(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return m ? m->ins : 0; +} + +int aether_xmp_samples(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + return m ? m->smp : 0; +} + +/* The length of the module's first (main) sequence, as libxmp's scan + * measured it when the module loaded. */ +int aether_xmp_duration_ms(void* vp) { + struct xmp_module_info mi; + struct xmp_module* m = xmp_mod((XmpPlayer*)vp, &mi); + if (!m || mi.num_sequences < 1 || !mi.seq_data) return 0; + return mi.seq_data[0].duration; +} + +/* Arm end detection from where the player stands now: the end is the next + * time libxmp's loop counter moves. */ +static void xmp_arm_end(XmpPlayer* p) { + struct xmp_frame_info fi; + xmp_get_frame_info(p->ctx, &fi); + p->loop_base = fi.loop_count; + p->ended = 0; +} + +int aether_xmp_start(void* vp, int rate) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + if (!p->loaded) return -XMP_ERROR_STATE; + if (rate < XMP_MIN_SRATE || rate > XMP_MAX_SRATE) return -XMP_ERROR_INVALID; + if (p->playing) { xmp_end_player(p->ctx); p->playing = 0; } + int rc = xmp_start_player(p->ctx, rate, 0); /* 16-bit signed stereo */ + if (rc < 0) return rc; + p->playing = 1; + p->rate = rate; + p->left = NULL; p->left_bytes = 0; + xmp_arm_end(p); + return 0; +} + +static int xmp_reserve(XmpPlayer* p, size_t bytes) { + if (bytes <= p->buf_cap) return 1; + size_t cap = p->buf_cap ? p->buf_cap : 16384; + while (cap < bytes) cap *= 2; + unsigned char* nb = (unsigned char*)realloc(p->buf, cap); + if (!nb) return 0; + p->buf = nb; + p->buf_cap = cap; + return 1; +} + +/* Append up to `want` bytes of PCM to p->buf at `at`, playing libxmp frames + * as needed. Returns the bytes written; fewer than asked only at the end of + * a module that is not looping (p->ended is then set). */ +static int xmp_fill(XmpPlayer* p, size_t at, int want) { + int done = 0; + while (done < want) { + if (p->left_bytes == 0) { + if (p->ended) break; + if (xmp_play_frame(p->ctx) < 0) { p->ended = 1; break; } + struct xmp_frame_info fi; + xmp_get_frame_info(p->ctx, &fi); + /* A frame played after the loop counter moved is the module + * starting over: with looping off, the end came first. */ + if (!p->looping && fi.loop_count > p->loop_base) { p->ended = 1; break; } + p->left = (const unsigned char*)fi.buffer; + p->left_bytes = fi.buffer_size; + if (p->left_bytes <= 0) { p->left_bytes = 0; continue; } + } + int n = want - done; + if (n > p->left_bytes) n = p->left_bytes; + memcpy(p->buf + at + (size_t)done, p->left, (size_t)n); + p->left += n; + p->left_bytes -= n; + done += n; + } + return done; +} + +int aether_xmp_render(void* vp, int frames) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + if (!p->playing) return -XMP_ERROR_STATE; + if (frames < 0 || frames > XMP_MAX_BLOCK_FRAMES) return -XMP_ERROR_INVALID; + int want = frames * XMP_BYTES_PER_FRAME; + if (!xmp_reserve(p, (size_t)want + 1)) return -XMP_ERROR_SYSTEM; + return xmp_fill(p, 0, want); +} + +int aether_xmp_render_all(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + if (!p->playing) return -XMP_ERROR_STATE; + int was_looping = p->looping; + if (was_looping) { p->looping = 0; xmp_arm_end(p); } + long long cap = (long long)XMP_MAX_ALL_MS * p->rate / 1000 * XMP_BYTES_PER_FRAME; + if (cap > INT_MAX - 1) cap = INT_MAX - 1; + size_t total = 0; + int rc = 0; + const int chunk = 65536 * XMP_BYTES_PER_FRAME; + while (!p->ended) { + if ((long long)total + chunk > cap) { rc = -XMP_ERROR_INVALID; break; } + if (!xmp_reserve(p, total + (size_t)chunk + 1)) { rc = -XMP_ERROR_SYSTEM; break; } + total += (size_t)xmp_fill(p, total, chunk); + } + if (was_looping) { p->looping = 1; xmp_arm_end(p); } + return rc < 0 ? rc : (int)total; +} + +void* aether_xmp_buffer(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + return p ? p->buf : NULL; +} + +int aether_xmp_seek_ms(void* vp, int ms) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + if (!p->playing) return -XMP_ERROR_STATE; + if (ms < 0) ms = 0; + int rc = xmp_seek_time_frame(p->ctx, ms); + if (rc < 0) return rc; + p->left = NULL; p->left_bytes = 0; + xmp_arm_end(p); + return 0; +} + +int aether_xmp_set_order(void* vp, int order) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + if (!p->playing) return -XMP_ERROR_STATE; + if (order < 0 || order >= aether_xmp_orders(p)) return -XMP_ERROR_INVALID; + /* The new position, or -1 for order 0, which libxmp marks as a restart + * (the same value as -XMP_END, so it cannot be read as an error). */ + int rc = xmp_set_position(p->ctx, order); + if (rc < -1) return rc; + p->left = NULL; p->left_bytes = 0; + xmp_arm_end(p); + return 0; +} + +/* Where the next rendered frame is, in the module's time: libxmp's clock + * stands after the frame it last played, less what of that frame is still + * waiting to be handed out. */ +int aether_xmp_position_ms(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p || !p->playing) return 0; + struct xmp_frame_info fi; + xmp_get_frame_info(p->ctx, &fi); + long long t = fi.time; + if (p->rate > 0) t -= (long long)p->left_bytes / XMP_BYTES_PER_FRAME * 1000 / p->rate; + return t < 0 ? 0 : (int)t; +} + +int aether_xmp_order(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p || !p->playing) return 0; + struct xmp_frame_info fi; + xmp_get_frame_info(p->ctx, &fi); + return fi.pos; +} + +int aether_xmp_row(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p || !p->playing) return 0; + struct xmp_frame_info fi; + xmp_get_frame_info(p->ctx, &fi); + return fi.row; +} + +int aether_xmp_set_looping(void* vp, int on) { + XmpPlayer* p = (XmpPlayer*)vp; + if (!p) return -XMP_ERROR_INVALID; + p->looping = on ? 1 : 0; + /* Looping on after the end carries on from the top; looping off re-arms + * the end from here, but leaves a module that already ended ended. */ + if (p->playing && (on || !p->ended)) xmp_arm_end(p); + return 0; +} + +int aether_xmp_is_looping(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + return p ? p->looping : 0; +} + +int aether_xmp_ended(void* vp) { + XmpPlayer* p = (XmpPlayer*)vp; + return (p && p->ended) ? 1 : 0; +} diff --git a/contrib/xmp/libxmp.lock b/contrib/xmp/libxmp.lock new file mode 100644 index 000000000..a0e21180a --- /dev/null +++ b/contrib/xmp/libxmp.lock @@ -0,0 +1,30 @@ +# The libxmp source contrib.xmp compiles (full libxmp: the player, every +# loader, ProWizard and the depackers; not libxmp-lite). +# +# Not committed: scripts/fetch-libxmp.sh downloads LIBXMP_URL (libxmp's own +# GitHub release tarball), refuses it unless its SHA-256 is LIBXMP_SHA256, +# and extracts include/, src/ and the licence into contrib/xmp/libxmp/ +# (gitignored), with sources.txt: the C files libxmp's Makefile.vc compiles +# (OBJS, PROWIZ_OBJS and DEPACKER_OBJS), one per line. `make contrib`, CI and +# release packaging run it; release archives ship the extracted files, so an +# installed toolchain never needs the network. +# +# LIBXMP_SHA256 is the checksum libxmp publishes in the release notes for the +# tag (and GitHub records for the asset), so the pin can be audited against +# the upstream listing. +# +# LIBXMP_CFLAGS is the one flag set, used for the native archive +# (tests/scripts/contrib_build.sh) and the per-target cross archive (ae build +# --target). It is part of both cache keys, so changing it recompiles. +# LIBXMP_STATIC: a static library (no dllimport/dllexport on Windows). No +# HAVE_* flags: libxmp then never spawns a helper program (HAVE_POPEN and +# friends), never calls the process-wide umask (HAVE_UMASK), and uses its +# own mkstemp (O_EXCL, mode 0600; tempfile.h names it libxmp_mkstemp, so it +# never stands in for the C library's), the configuration Makefile.vc builds. +# +# To bump: change the four values, run the fetch script, and update the +# version in contrib/xmp/README.md. +LIBXMP_VERSION=4.7.4 +LIBXMP_URL=https://github.com/libxmp/libxmp/releases/download/libxmp-4.7.4/libxmp-4.7.4.tar.gz +LIBXMP_SHA256=a25583aa3b031c78ba0b4e83387fa596fb05742622e60f60d1540ee2af79b8d9 +LIBXMP_CFLAGS="-DLIBXMP_STATIC" diff --git a/contrib/xmp/module.ae b/contrib/xmp/module.ae new file mode 100644 index 000000000..89bf8725f --- /dev/null +++ b/contrib/xmp/module.ae @@ -0,0 +1,262 @@ +// contrib.xmp — a tracker-module player for std.audio, over libxmp. +// Import with: import contrib.xmp +// +// Plays MOD, S3M, XM, IT, MED and the rest of the formats libxmp reads +// (full libxmp: every loader, ProWizard and the depackers). A player renders +// interleaved signed 16-bit stereo PCM, which std.audio plays: either the +// whole module up front (`sound`, for std.audio's load_pcm) or block by +// block into a std.audio stream source (`stream_open` + `pump`). There is no +// audio output of its own; std.audio is the only backend. +// +// Loading: +// xmp.load(data, length) -> ptr! // module bytes (e.g. fs.read_binary) +// xmp.load_file(path) -> ptr! +// xmp.free(p) // null is a no-op +// +// Module info (valid from load on): +// xmp.title(p) / xmp.format(p) -> string // owned copies +// xmp.channels(p), patterns(p), orders(p), instruments(p), samples(p) -> int +// xmp.duration_ms(p) -> int // libxmp's scan of the main sequence +// +// Playing: +// xmp.start(p, sample_rate) -> string // "" or why not; restarts from the top +// xmp.render(p, frames) -> string! // frames * FRAME_BYTES bytes, fewer at the end +// xmp.render_all(p) -> string! // from here to the end, looping or not +// xmp.seek_ms(p, ms) / xmp.set_order(p, order) -> string +// xmp.position_ms(p), order(p), row(p) -> int +// xmp.looping(p, on), xmp.is_looping(p), xmp.ended(p) +// +// Through std.audio: +// xmp.sound(p, sample_rate) -> ptr! // a std.audio source of the whole module +// xmp.stream_open(p, sample_rate, frames) -> ptr! // a std.audio stream source +// xmp.pump(p, src) -> int! // render into its free space +// +// Errors follow contrib.sqlite and std.audio: a fallible call returns +// (value, "") or (null / "" / -1, reason), and the reason is a static string. +// +// Threading: a player belongs to one thread at a time and does all its work +// in the call that asks for it. Nothing here runs on a thread of its own. +// With a stream source the mixer thread drains the ring on its own, and the +// program calls `pump` often enough to keep it from running dry (a ring of +// `frames` lasts frames / sample_rate seconds; pump at least twice in that +// time). audio.stream_underruns on the source says if it ever did run dry. +// +// Build: the `@link` below carries the libraries. libxmp is the source +// pinned in libxmp.lock: `make contrib` fetches it and compiles it into +// build/contrib/libxmp.a beside the veneer, and `ae build --target=` +// compiles it for the target; when it cannot be fetched, `make contrib` +// builds against the system libxmp instead. Without `make contrib` (a binary +// release builds no contrib archives) `ae build` compiles the veneer and the +// libxmp source shipped beside this file itself. README.md has the details. + +import std.audio +import std.string + +// -laether_xmp is the veneer archive `make contrib` builds; -lxmp is the +// vendored static libxmp beside it (or the system library), before -lm, +// which its mixer needs. +@link("-laether_xmp -lxmp -lm") + +exports( + FRAME_BYTES, + load, load_file, free, + title, format, channels, patterns, orders, instruments, samples, duration_ms, + start, render, render_all, + seek_ms, set_order, position_ms, order, row, + looping, is_looping, ended, + sound, stream_open, pump +) + +// Bytes per rendered frame: two channels of signed 16-bit. +const FRAME_BYTES = 4 + +// ---- substrate externs (aether_xmp.c) ---- +extern aether_xmp_new() -> ptr +extern aether_xmp_free(p: ptr) +// `@aether`: the counted string, so its length bounds the read (#3297). +extern aether_xmp_load_memory(p: ptr, data: @aether string, length: int) -> int +extern aether_xmp_load_path(p: ptr, path: string) -> int +extern aether_xmp_strerror(code: int) -> string +extern aether_xmp_title(p: ptr) -> string @heap +extern aether_xmp_format(p: ptr) -> string @heap +extern aether_xmp_channels(p: ptr) -> int +extern aether_xmp_patterns(p: ptr) -> int +extern aether_xmp_orders(p: ptr) -> int +extern aether_xmp_instruments(p: ptr) -> int +extern aether_xmp_samples(p: ptr) -> int +extern aether_xmp_duration_ms(p: ptr) -> int +extern aether_xmp_start(p: ptr, rate: int) -> int +extern aether_xmp_render(p: ptr, frames: int) -> int +extern aether_xmp_render_all(p: ptr) -> int +// The bytes the last render left, whose length render returned: a `ptr`, so +// nothing reads it as a C string up to its first NUL. +extern aether_xmp_buffer(p: ptr) -> ptr +extern aether_xmp_seek_ms(p: ptr, ms: int) -> int +extern aether_xmp_set_order(p: ptr, order: int) -> int +extern aether_xmp_position_ms(p: ptr) -> int +extern aether_xmp_order(p: ptr) -> int +extern aether_xmp_row(p: ptr) -> int +extern aether_xmp_set_looping(p: ptr, on: int) -> int +extern aether_xmp_is_looping(p: ptr) -> int +extern aether_xmp_ended(p: ptr) -> int + +// Length-aware AetherString constructor, from std.string: the PCM holds NULs. +extern string_new_with_length(data: ptr, length: size_t) -> string @heap + +// ---- loading ---- + +// Load a module from `length` bytes of `data` (fs.read_binary's shape; the +// bytes are copied, so `data` need not outlive the player). Returns the +// player, or (null, reason) for bytes libxmp does not recognise as a module, +// a damaged one, or none at all. Release it with `free`. +load(data: string, length: int) -> ptr! { + p = aether_xmp_new() + if p == null { return null, "xmp: out of memory" } + rc = aether_xmp_load_memory(p, data, length) + if rc != 0 { + aether_xmp_free(p) + return null, aether_xmp_strerror(rc) + } + return p +} + +// Load a module from the file at `path`. libxmp unpacks a compressed one +// (zip, gzip, xz, lha, PowerPacker, ...) itself. +load_file(path: string) -> ptr! { + p = aether_xmp_new() + if p == null { return null, "xmp: out of memory" } + rc = aether_xmp_load_path(p, path) + if rc != 0 { + aether_xmp_free(p) + return null, aether_xmp_strerror(rc) + } + return p +} + +// Release the player and its module. After this the pointer is invalid. +free(p: ptr) { aether_xmp_free(p) } + +// ---- module info ---- + +// The module's title as stored in it ("" when it has none). +title(p: ptr) -> string { return aether_xmp_title(p) } +// The format libxmp identified, e.g. "Protracker M.K." or "Fast Tracker II". +format(p: ptr) -> string { return aether_xmp_format(p) } +channels(p: ptr) -> int { return aether_xmp_channels(p) } +patterns(p: ptr) -> int { return aether_xmp_patterns(p) } +// The length of the order list (the song's sequence of patterns). +orders(p: ptr) -> int { return aether_xmp_orders(p) } +instruments(p: ptr) -> int { return aether_xmp_instruments(p) } +samples(p: ptr) -> int { return aether_xmp_samples(p) } +// How long the module plays once through, in milliseconds. +duration_ms(p: ptr) -> int { return aether_xmp_duration_ms(p) } + +// ---- playing ---- + +// Start (or restart) the player at `sample_rate` Hz (4000 to 768000), from +// the top of the module. Returns "" or the reason. +start(p: ptr, sample_rate: int) -> string { + rc = aether_xmp_start(p, sample_rate) + if rc != 0 { return aether_xmp_strerror(rc) } + return "" +} + +// Render the next `frames` frames: frames * FRAME_BYTES bytes of interleaved +// signed 16-bit stereo, std.audio's FORMAT_S16. Fewer at the end of a module +// that is not looping, and "" once it has ended (`ended` says so). Returns +// ("", reason) before `start` or for a block over 4,194,304 frames. +render(p: ptr, frames: int) -> string! { + n = aether_xmp_render(p, frames) + if n < 0 { return "", aether_xmp_strerror(n) } + return string_new_with_length(aether_xmp_buffer(p), n) +} + +// Render from where the player stands to the end of the module, once, as +// one block: looping is held off for the call. Refused past 30 minutes. +render_all(p: ptr) -> string! { + n = aether_xmp_render_all(p) + if n < 0 { return "", aether_xmp_strerror(n) } + return string_new_with_length(aether_xmp_buffer(p), n) +} + +// Move playback to `ms` milliseconds into the module, to the frame. +seek_ms(p: ptr, ms: int) -> string { + rc = aether_xmp_seek_ms(p, ms) + if rc != 0 { return aether_xmp_strerror(rc) } + return "" +} + +// Move playback to the start of entry `order` in the order list. +set_order(p: ptr, order: int) -> string { + rc = aether_xmp_set_order(p, order) + if rc != 0 { return aether_xmp_strerror(rc) } + return "" +} + +// Where the next rendered frame falls in the module, in milliseconds. +position_ms(p: ptr) -> int { return aether_xmp_position_ms(p) } +// The order-list entry and the row of its pattern now playing. +order(p: ptr) -> int { return aether_xmp_order(p) } +row(p: ptr) -> int { return aether_xmp_row(p) } + +// Loop at the end (on) or stop there (off, the default). Turning it on +// after the end carries on from the top. +looping(p: ptr, on: bool) { + v = 0 + if on { v = 1 } + _ = aether_xmp_set_looping(p, v) +} +is_looping(p: ptr) -> bool { return aether_xmp_is_looping(p) == 1 } +// True once a module that is not looping has played to its end. +ended(p: ptr) -> bool { return aether_xmp_ended(p) == 1 } + +// ---- through std.audio ---- + +// Start the player at `sample_rate` and render the whole module into a +// std.audio source (audio.load_pcm), which plays, seeks and loops like any +// other. The player is left at the end; the source owns its own copy of the +// PCM. Release the source with audio.unload. +sound(p: ptr, sample_rate: int) -> ptr! { + err = start(p, sample_rate) + if err != "" { return null, err } + pcm, rerr = render_all(p) + if rerr != "" { return null, rerr } + n = string.length(pcm) + if n == 0 { return null, "xmp: the module renders no audio" } + src, aerr = audio.load_pcm(pcm, n, sample_rate, 2, audio.FORMAT_S16) + if aerr != "" { return null, aerr } + return src +} + +// Start the player at `sample_rate` and open a std.audio stream source for +// it holding `capacity_frames` frames, already filled by one `pump`. Play +// it with audio.play, keep it fed with `pump`, release it with +// audio.unload (before freeing the player or not: they are independent). +stream_open(p: ptr, sample_rate: int, capacity_frames: int) -> ptr! { + err = start(p, sample_rate) + if err != "" { return null, err } + src, serr = audio.stream_open(sample_rate, 2, audio.FORMAT_S16, capacity_frames) + if serr != "" { return null, serr } + _, perr = pump(p, src) + if perr != "" { + audio.unload(src) + return null, perr + } + return src +} + +// Render as much as `src` (from stream_open) has room for and push it in. +// Returns the frames pushed: 0 when the ring is full, or once the module has +// ended (`ended`), and (-1, reason) on an error. Call it from the thread +// that owns the player, as often as the module section above says. +pump(p: ptr, src: ptr) -> int! { + room = audio.stream_capacity(src) - audio.stream_queued(src) + if room <= 0 { return 0 } + pcm, err = render(p, room) + if err != "" { return -1, err } + n = string.length(pcm) + if n == 0 { return 0 } + pushed, perr = audio.stream_push(src, pcm, n) + if perr != "" { return -1, perr } + return pushed +} diff --git a/contrib/xmp/test_xmp.ae b/contrib/xmp/test_xmp.ae new file mode 100644 index 000000000..0b0c0c8d8 --- /dev/null +++ b/contrib/xmp/test_xmp.ae @@ -0,0 +1,460 @@ +// contrib.xmp tests. Every module played here is written by the test itself, +// byte by byte, from the format's own layout: a four-channel ProTracker MOD +// and a two-channel Fast Tracker II XM, each one looping square-wave sample +// playing for the first half of the song and silenced for the second. The +// assertions are on the rendered PCM: sound where a note plays, silence +// where none does, the length the song's speed and tempo give it, and where +// seeking and looping put playback. The std.audio half runs on std.audio's +// headless engine, so no sound card is involved. + +import std.audio +import std.bytes +import std.fs +import std.spec +import std.string +import contrib.xmp + +const RATE = 44100 +// Both songs: speed 6, 125 BPM, so a row is 6 ticks of 20 ms, and 16 rows +// (two 8-row patterns in the MOD, one 16-row pattern in the XM). +const SONG_MS = 1920 +// Where the note stops: the start of the second half. +const HALF_MS = 960 + +put_text(b: ptr, at: int, s: string) { + i = 0 + while i < string.length(s) { + bytes.set(b, at + i, string.char_at(s, i) & 255) + i = i + 1 + } +} + +// A ProTracker M.K. module: 31 sample slots (one used), two orders, two +// patterns of 64 rows by 4 channels. Sample 1 is a 64-byte square wave +// looped whole. Pattern 0 plays C-2 on channel 0 at row 0 and breaks to the +// next order at row 7; pattern 1 sets channel 0's volume to 0 at row 0 and +// breaks at row 7. So 16 rows of song: 8 sounding, 8 silent. +make_mod() -> (string, int) { + smp_len = 64 + total = 1084 + 2 * 1024 + smp_len + b = bytes.new(total) + i = 0 + while i < total { + bytes.set(b, i, 0) + i = i + 1 + } + put_text(b, 0, "aether xmp test") + // Sample 1's header at 20: name, then length in words, finetune, + // volume, loop start and loop length in words. + put_text(b, 20, "square") + bytes.set_be16(b, 42, smp_len / 2) + bytes.set(b, 44, 0) + bytes.set(b, 45, 64) + bytes.set_be16(b, 46, 0) + bytes.set_be16(b, 48, smp_len / 2) + // Slots 2..31: no sample, loop length 1 word (the "no loop" mark). + s = 1 + while s < 31 { + bytes.set_be16(b, 20 + s * 30 + 28, 1) + s = s + 1 + } + bytes.set(b, 950, 2) // song length: two orders + bytes.set(b, 951, 127) // restart byte + bytes.set(b, 952, 0) // order 0: pattern 0 + bytes.set(b, 953, 1) // order 1: pattern 1 + put_text(b, 1080, "M.K.") + // A cell is 4 bytes: sample high nibble | period high nibble, period + // low byte, sample low nibble << 4 | effect, effect parameter. Rows are + // 16 bytes (4 channels). + p0 = 1084 + bytes.set(b, p0 + 0, (428 >> 8) & 15) // C-2, period 428, sample 1 + bytes.set(b, p0 + 1, 428 & 255) + bytes.set(b, p0 + 2, (1 << 4) | 0) + bytes.set(b, p0 + 7 * 16 + 2, 13) // row 7: D00, pattern break + p1 = 1084 + 1024 + bytes.set(b, p1 + 2, 12) // row 0: C00, volume 0 + bytes.set(b, p1 + 7 * 16 + 2, 13) // row 7: D00 + // The square wave, signed 8-bit. + d = 1084 + 2 * 1024 + k = 0 + while k < smp_len { + v = 64 + if k >= smp_len / 2 { v = 256 - 64 } + bytes.set(b, d + k, v) + k = k + 1 + } + return bytes.finish(b, total), total +} + +// A Fast Tracker II module (version 0x0104): 2 channels, one 16-row +// pattern, one instrument with one 8-bit sample, the same looped square +// wave. Row 0 plays C-4 with instrument 1; row 8 is a key-off, which with +// the volume envelope off silences the note at once. +make_xm() -> (string, int) { + rows = 16 + chans = 2 + pat_data = rows * chans * 5 + smp_len = 64 + inst_size = 263 + total = 336 + 9 + pat_data + inst_size + 40 + smp_len + b = bytes.new(total) + i = 0 + while i < total { + bytes.set(b, i, 0) + i = i + 1 + } + put_text(b, 0, "Extended Module: ") + put_text(b, 17, "aether xm test") + bytes.set(b, 37, 26) + put_text(b, 38, "aether") + bytes.set_le16(b, 58, 260) // version 0x0104 + bytes.set_le32(b, 60, 276) // header size, from offset 60 + bytes.set_le16(b, 64, 1) // song length + bytes.set_le16(b, 66, 0) // restart position + bytes.set_le16(b, 68, chans) + bytes.set_le16(b, 70, 1) // patterns + bytes.set_le16(b, 72, 1) // instruments + bytes.set_le16(b, 74, 1) // linear frequency table + bytes.set_le16(b, 76, 6) // speed + bytes.set_le16(b, 78, 125) // BPM + // Order table at 80: order 0 is pattern 0 (already zero). + // Pattern 0 at 336, unpacked: 5 bytes per cell (note, instrument, + // volume column, effect, parameter). + p = 336 + bytes.set_le32(b, p, 9) + bytes.set(b, p + 4, 0) + bytes.set_le16(b, p + 5, rows) + bytes.set_le16(b, p + 7, pat_data) + cells = p + 9 + bytes.set(b, cells + 0, 49) // row 0, channel 0: C-4 + bytes.set(b, cells + 1, 1) // instrument 1 + bytes.set(b, cells + 8 * chans * 5, 97) // row 8, channel 0: key off + // Instrument 1: header size, name, type, sample count, then (for a + // sample-bearing instrument) the sample header size, keymap, envelopes + // (left off) and the rest of its 263 bytes. + ins = cells + pat_data + bytes.set_le32(b, ins, inst_size) + put_text(b, ins + 4, "square") + bytes.set_le16(b, ins + 27, 1) + bytes.set_le32(b, ins + 29, 40) + // Sample header: length, loop start, loop length (bytes), volume, + // finetune, type (1: forward loop), panning, relative note, reserved, + // name. + sh = ins + inst_size + bytes.set_le32(b, sh, smp_len) + bytes.set_le32(b, sh + 4, 0) + bytes.set_le32(b, sh + 8, smp_len) + bytes.set(b, sh + 12, 64) + bytes.set(b, sh + 14, 1) + bytes.set(b, sh + 15, 128) + put_text(b, sh + 18, "square") + // Sample data, delta-coded: +64 then a step down to -64 halfway. + d = sh + 40 + bytes.set(b, d, 64) + bytes.set(b, d + smp_len / 2, 128) // -128 as a byte: 64 -> -64 + return bytes.finish(b, total), total +} + +// The largest absolute sample over frames [from, to) of interleaved 16-bit +// stereo PCM, both channels. +peak(pcm: string, n: int, from: int, to: int) -> int { + frames = n / 4 + if to > frames { to = frames } + best = 0 + f = from + while f < to { + c = 0 + while c < 2 { + at = f * 4 + c * 2 + lo = string.char_at_n(pcm, n, at) & 255 + hi = string.char_at_n(pcm, n, at + 1) & 255 + v = lo | (hi << 8) + if v >= 32768 { v = 65536 - v } + if v > best { best = v } + c = c + 1 + } + f = f + 1 + } + return best +} + +ms_frames(ms: int) -> int { return ms * RATE / 1000 } + +// Renders from where the player stands to the end in blocks of `block` +// frames, the way a caller feeding a device does, and returns it all. +render_blocks(p: ptr, block: int) -> (string, int) { + cap = ms_frames(10000) * 4 + out = bytes.new(cap) + total = 0 + while true { + pcm, err = xmp.render(p, block) + if err != "" { return bytes.finish(out, 0), -1 } + n = string.length(pcm) + if n == 0 { break } + if total + n > cap { return bytes.finish(out, total), -2 } + _ = bytes.copy_from_string(out, total, pcm, n) + total = total + n + } + return bytes.finish(out, total), total +} + +main() { + fw = spec.init() + mod, mod_n = make_mod() + xm, xm_n = make_xm() + + spec.describe(fw, "xmp: loading and module info") { + spec.it(fw, "reads a ProTracker MOD from memory") callback { + p, err = xmp.load(mod, mod_n) + spec.assert_str_eq(err, "", "loads") + spec.assert_not_null(p, "a player") + spec.assert_str_eq(xmp.title(p), "aether xmp test", "title") + spec.assert_contains(xmp.format(p), "M.K.", "format names the M.K. signature") + spec.assert_eq(xmp.channels(p), 4, "channels") + spec.assert_eq(xmp.patterns(p), 2, "patterns") + spec.assert_eq(xmp.orders(p), 2, "orders") + spec.assert_eq(xmp.samples(p), 31, "sample slots") + spec.assert_eq(xmp.duration_ms(p), SONG_MS, "16 rows at speed 6, 125 BPM") + xmp.free(p) + } + spec.it(fw, "reads a Fast Tracker II XM from memory") callback { + p, err = xmp.load(xm, xm_n) + spec.assert_str_eq(err, "", "loads") + spec.assert_str_eq(xmp.title(p), "aether xm test", "title") + // libxmp names an XM's format after the tracker field. + spec.assert_str_eq(xmp.format(p), "aether XM 1.04", "format") + spec.assert_eq(xmp.channels(p), 2, "channels") + // The one pattern, plus the empty one libxmp's XM loader adds + // for orders that name a missing pattern. + spec.assert_eq(xmp.patterns(p), 2, "patterns") + spec.assert_eq(xmp.orders(p), 1, "orders") + spec.assert_eq(xmp.instruments(p), 1, "instruments") + spec.assert_eq(xmp.duration_ms(p), SONG_MS, "duration") + xmp.free(p) + } + spec.it(fw, "reads a module from a file") callback { + dir, derr = fs.make_temp_dir("", "xmp") + spec.assert_str_eq(derr, "", "temp dir") + path = "${dir}/song.mod" + spec.assert_str_eq(fs.write(path, mod), "", "written") + p, err = xmp.load_file(path) + spec.assert_str_eq(err, "", "loads from the path") + spec.assert_eq(xmp.channels(p), 4, "the same module") + xmp.free(p) + spec.assert_str_eq(fs.remove_tree(dir), "", "cleaned up") + } + } + + spec.describe(fw, "xmp: refusals") { + spec.it(fw, "refuses bytes that are not a module") callback { + junk = bytes.new(4096) + i = 0 + while i < 4096 { + bytes.set(junk, i, (i * 37 + 11) & 255) + i = i + 1 + } + data = bytes.finish(junk, 4096) + p, err = xmp.load(data, 4096) + spec.assert_null(p, "no player") + spec.assert_contains(err, "xmp:", "says why") + } + spec.it(fw, "refuses empty input") callback { + p, err = xmp.load("", 0) + spec.assert_null(p, "no player") + spec.assert_contains(err, "not a module format", "says why") + } + spec.it(fw, "refuses a truncated module") callback { + p, err = xmp.load(mod, 1084) + spec.assert_null(p, "no player") + spec.assert_err(err, "says why") + } + spec.it(fw, "reads no further than the bytes it was given") callback { + // A length past the end of the string is held to the string. + p, err = xmp.load(mod, mod_n * 4) + spec.assert_str_eq(err, "", "loads the module that is there") + spec.assert_eq(xmp.channels(p), 4, "the same module") + xmp.free(p) + } + spec.it(fw, "refuses a path that is not there") callback { + p, err = xmp.load_file("/nonexistent/aether/xmp/none.mod") + spec.assert_null(p, "no player") + spec.assert_err(err, "says why") + } + spec.it(fw, "refuses render and seek before start, and a bad rate") callback { + p, _ = xmp.load(mod, mod_n) + pcm, err = xmp.render(p, 100) + spec.assert_eq(string.length(pcm), 0, "no audio") + spec.assert_contains(err, "state", "render before start") + spec.assert_err(xmp.seek_ms(p, 10), "seek before start") + spec.assert_err(xmp.start(p, 100), "100 Hz refused") + spec.assert_str_eq(xmp.start(p, RATE), "", "then a real rate starts") + _, berr = xmp.render(p, 5000000) + spec.assert_err(berr, "a block past the limit is refused") + xmp.free(p) + } + spec.it(fw, "free accepts null") callback { + xmp.free(null) + } + } + + spec.describe(fw, "xmp: rendering") { + spec.it(fw, "renders the MOD: sound, then silence, then the end") callback { + p, _ = xmp.load(mod, mod_n) + spec.assert_str_eq(xmp.start(p, RATE), "", "starts") + pcm, n = render_blocks(p, 1024) + spec.assert_true(n > 0, "renders") + frames = n / 4 + // The song is 1920 ms; libxmp's frames are whole ticks, so the + // total is exact to the frame. + spec.assert_eq(frames, ms_frames(SONG_MS), "length is the song's") + spec.assert_true(peak(pcm, n, ms_frames(20), ms_frames(900)) > 1000, "the note sounds") + spec.assert_eq(peak(pcm, n, ms_frames(HALF_MS + 60), frames), 0, "volume 0 is silence") + spec.assert_true(xmp.ended(p), "ended") + again, err = xmp.render(p, 1024) + spec.assert_str_eq(err, "", "rendering past the end is not an error") + spec.assert_eq(string.length(again), 0, "but gives nothing") + xmp.free(p) + } + spec.it(fw, "renders the XM: sound until the key-off, then silence") callback { + p, _ = xmp.load(xm, xm_n) + spec.assert_str_eq(xmp.start(p, RATE), "", "starts") + pcm, n = render_blocks(p, 4410) + frames = n / 4 + spec.assert_eq(frames, ms_frames(SONG_MS), "length is the song's") + spec.assert_true(peak(pcm, n, ms_frames(20), ms_frames(900)) > 1000, "the note sounds") + spec.assert_eq(peak(pcm, n, ms_frames(HALF_MS + 60), frames), 0, "silent after the key-off") + xmp.free(p) + } + spec.it(fw, "render_all gives the same song in one block") callback { + p, _ = xmp.load(mod, mod_n) + _ = xmp.start(p, RATE) + xmp.looping(p, true) + pcm, err = xmp.render_all(p) + spec.assert_str_eq(err, "", "renders") + spec.assert_eq(string.length(pcm) / 4, ms_frames(SONG_MS), "once through, looping or not") + spec.assert_true(xmp.is_looping(p), "looping is left as it was") + xmp.free(p) + } + } + + spec.describe(fw, "xmp: position, seeking and looping") { + spec.it(fw, "position follows rendering") callback { + p, _ = xmp.load(mod, mod_n) + _ = xmp.start(p, RATE) + spec.assert_eq(xmp.position_ms(p), 0, "at the top") + _, _ = xmp.render(p, ms_frames(500)) + pos = xmp.position_ms(p) + spec.assert_true(pos >= 480 && pos <= 520, "about 500 ms in (got ${pos})") + spec.assert_eq(xmp.order(p), 0, "still in order 0") + xmp.free(p) + } + spec.it(fw, "seek_ms moves into the silent half, set_order back") callback { + p, _ = xmp.load(mod, mod_n) + _ = xmp.start(p, RATE) + // Stop mid-frame while the note sounds, so the seek has a part + // frame of it to throw away. + _, _ = xmp.render(p, ms_frames(100) + 7) + spec.assert_str_eq(xmp.seek_ms(p, 1200), "", "seeks") + pos = xmp.position_ms(p) + spec.assert_true(pos >= 1180 && pos <= 1220, "at 1200 ms (got ${pos})") + pcm, _ = xmp.render(p, ms_frames(300)) + spec.assert_eq(xmp.order(p), 1, "in order 1") + spec.assert_eq(peak(pcm, string.length(pcm), 0, ms_frames(300)), 0, "silent there") + spec.assert_str_eq(xmp.set_order(p, 0), "", "back to order 0") + back, _ = xmp.render(p, ms_frames(300)) + spec.assert_true(peak(back, string.length(back), ms_frames(20), ms_frames(300)) > 1000, "sounding again") + spec.assert_eq(xmp.order(p), 0, "in order 0") + xmp.free(p) + } + spec.it(fw, "seek_ms lands on the frame: the rest plays exactly the rest") callback { + p, _ = xmp.load(mod, mod_n) + _ = xmp.start(p, RATE) + _, _ = xmp.render(p, ms_frames(100) + 7) + // 1200 ms is a whole number of 20 ms ticks, so no rounding. + spec.assert_str_eq(xmp.seek_ms(p, 1200), "", "seeks") + _, n = render_blocks(p, 1000) + spec.assert_eq(n / 4, ms_frames(SONG_MS - 1200), "720 ms to the end, nothing from before the seek") + xmp.free(p) + } + spec.it(fw, "seeking after the end plays again") callback { + p, _ = xmp.load(mod, mod_n) + _ = xmp.start(p, RATE) + _, _ = render_blocks(p, 8192) + spec.assert_true(xmp.ended(p), "ended") + spec.assert_str_eq(xmp.seek_ms(p, 0), "", "seeks to the top") + spec.assert_false(xmp.ended(p), "no longer ended") + pcm, n = render_blocks(p, 8192) + spec.assert_eq(n / 4, ms_frames(SONG_MS), "the whole song again") + xmp.free(p) + } + spec.it(fw, "looping on wraps to the top instead of ending") callback { + p, _ = xmp.load(mod, mod_n) + _ = xmp.start(p, RATE) + xmp.looping(p, true) + pcm, err = xmp.render(p, ms_frames(SONG_MS + 800)) + spec.assert_str_eq(err, "", "renders") + n = string.length(pcm) + spec.assert_eq(n / 4, ms_frames(SONG_MS + 800), "every frame asked for") + spec.assert_false(xmp.ended(p), "not ended") + spec.assert_true(peak(pcm, n, ms_frames(SONG_MS + 20), ms_frames(SONG_MS + 800)) > 1000, + "the note sounds again after the wrap") + xmp.looping(p, false) + _, _ = render_blocks(p, 8192) + spec.assert_true(xmp.ended(p), "looping off: ends at the next end") + xmp.free(p) + } + } + + spec.describe(fw, "xmp: through std.audio") { + spec.it(fw, "sound() gives a std.audio source of the whole song") callback { + spec.assert_true(audio.open_headless(RATE, 2), "headless engine") + p, _ = xmp.load(mod, mod_n) + src, err = xmp.sound(p, RATE) + spec.assert_str_eq(err, "", "a source") + d = audio.duration_ms(src) + spec.assert_true(d >= SONG_MS - 1 && d <= SONG_MS + 1, "its duration is the song's (got ${d})") + _ = audio.play(src) + _ = audio.render(ms_frames(500)) + spec.assert_true(audio.rendered_peak(0) > 0.03, "plays the note") + _ = audio.seek_ms(src, 1300) + // The mixer reads a source a block ahead: one render to drain + // what it read before the seek, then the silent half. + _ = audio.render(2048) + _ = audio.render(ms_frames(300)) + spec.assert_true(audio.rendered_peak(0) < 0.0001, "and the silence") + audio.unload(src) + xmp.free(p) + audio.close() + } + spec.it(fw, "stream_open and pump feed a stream source block by block") callback { + spec.assert_true(audio.open_headless(RATE, 2), "headless engine") + p, _ = xmp.load(mod, mod_n) + src, err = xmp.stream_open(p, RATE, 8192) + spec.assert_str_eq(err, "", "a stream source") + spec.assert_eq(audio.stream_queued(src), 8192, "filled by stream_open") + pushed, perr = xmp.pump(p, src) + spec.assert_str_eq(perr, "", "pump") + spec.assert_eq(pushed, 0, "nothing to do while full") + _ = audio.play(src) + // Play the song through in 2048-frame steps, pumping after each. + loud = 0.0 + step = 0 + while step < 40 { + _ = audio.render(2048) + if step < 15 && audio.rendered_peak(0) > loud { loud = audio.rendered_peak(0) } + _, _ = xmp.pump(p, src) + step = step + 1 + } + spec.assert_true(loud > 0.03, "the note reached the mix") + spec.assert_true(xmp.ended(p), "the player reached the end") + n, _ = xmp.pump(p, src) + spec.assert_eq(n, 0, "pump after the end pushes nothing") + spec.assert_eq_long(audio.stream_underruns(src), 0 as long, "no underrun while the song played") + audio.unload(src) + xmp.free(p) + audio.close() + } + } + + return spec.run_summary(fw) +} diff --git a/docs/bootstrap-from-source.md b/docs/bootstrap-from-source.md index a7ff1993e..be41bf816 100644 --- a/docs/bootstrap-from-source.md +++ b/docs/bootstrap-from-source.md @@ -74,6 +74,7 @@ is absent**, a skip is normal, not an error): |---|---|---| | `sqlite` | nothing: fetches the pinned amalgamation (#1372); `libsqlite3-dev` only when offline | `scripts/fetch-sqlite-amalgamation.sh`, else `pkg-config sqlite3` / `` | | `avcodec` | FFmpeg's `libavcodec`/`libavformat`/`libavutil`/`libswscale`/`libswresample` dev | `pkg-config libavcodec …` | +| `xmp` | nothing: fetches the pinned libxmp release; `libxmp-dev` only when offline | `scripts/fetch-libxmp.sh`, else `pkg-config libxmp` / `` | | `host_stunt`, `host_aether` | nothing (libc and the in-tree runtime) | always built | The language bridges (Lua, Python, Tcl, Perl, Ruby, JS, Go, Java and more) @@ -220,6 +221,8 @@ looks like: ``` sqlite OK build/contrib/libaether_sqlite.a avcodec SKIP (dev library not found) + libxmp OK build/contrib/libxmp.a (libxmp 4.7.4, vendored) + xmp OK build/contrib/libaether_xmp.a host_aether OK build/contrib/libaether_host_aether.a host_stunt OK build/contrib/libaether_host_stunt.a ``` diff --git a/docs/stdlib-vs-contrib.md b/docs/stdlib-vs-contrib.md index 120244f97..92968c7cd 100644 --- a/docs/stdlib-vs-contrib.md +++ b/docs/stdlib-vs-contrib.md @@ -83,6 +83,7 @@ and `zlib` uses for libz. | Module | Reason for `contrib/` | |---|---| | `contrib/sqlite/` | DB driver, fails rubric Q1 (not universal) and Q3 (4 MiB amalgamation). | +| `contrib/xmp/` | A tracker-module player (MOD, S3M, XM, IT, MED, ...) for std.audio over libxmp: not universal (Q1), and libxmp is a 179-source C library fetched against a pinned checksum (Q3). | | `contrib/quickjs/` | An embedded JavaScript engine (quickjs-ng): not universal (Q1) and a 3 MB amalgamation (Q3). | | `contrib/tinyweb/` | Builder DSL for HTTP services, competes with `std.http.server`'s closure-config approach; opinionated shape that's better off evolving without the stability constraint. | | `contrib/templating/{native,liquid}/` | Escape-correct output emission, `native` (Aether-as-template-language) and `liquid` (Shopify Liquid port). Opinionated template surfaces; fail Q2. | diff --git a/new_changelogs/20261126T205022Z-added-contrib-xmp.md b/new_changelogs/20261126T205022Z-added-contrib-xmp.md new file mode 100644 index 000000000..9ec744cdd --- /dev/null +++ b/new_changelogs/20261126T205022Z-added-contrib-xmp.md @@ -0,0 +1,16 @@ +- **`contrib.xmp`: a tracker-module player for std.audio.** `import + contrib.xmp` loads MOD, S3M, XM, IT, MED and the other formats libxmp + reads (full libxmp: every loader, ProWizard and the depackers), from bytes + or a path, reports the title, format, channels, patterns, orders and + duration, and renders interleaved 16-bit stereo PCM with seeking, order + jumps and looping. `xmp.sound` renders a whole module into a std.audio + source (`load_pcm`); `xmp.stream_open` and `xmp.pump` feed a std.audio + stream source block by block. std.audio stays the only audio output. Each + player carries its own libxmp context, and nothing in the module runs on a + thread of its own. libxmp 4.7.4 is pinned by URL and SHA-256 in + `contrib/xmp/libxmp.lock` and fetched by `scripts/fetch-libxmp.sh`, never + committed; `make contrib` compiles it from the source list libxmp's + Makefile.vc builds into `build/contrib/libxmp.a`, `ae build --target` + compiles it for the target, a binary release ships the source (with + libxmp's MIT licence, and `contrib/xmp/NOTICE`) and the archives, and the + system libxmp is the fallback when the source cannot be fetched. diff --git a/scripts/fetch-libxmp.sh b/scripts/fetch-libxmp.sh new file mode 100755 index 000000000..bc46ffa0c --- /dev/null +++ b/scripts/fetch-libxmp.sh @@ -0,0 +1,131 @@ +#!/bin/sh +# Fetch the pinned libxmp source for contrib.xmp. +# +# scripts/fetch-libxmp.sh [dest-dir] +# +# Reads contrib/xmp/libxmp.lock (or $LIBXMP_LOCK), downloads LIBXMP_URL, +# refuses the archive unless its SHA-256 is LIBXMP_SHA256, and extracts +# libxmp's include/ and src/ (without src/lite, the libxmp-lite build) plus +# docs/COPYING and README into dest-dir (default contrib/xmp/libxmp). It +# writes dest-dir/sources.txt: the C files libxmp's own Makefile.vc compiles +# for the full library (OBJS, PROWIZ_OBJS, DEPACKER_OBJS), one path per line +# relative to dest-dir. Prints dest-dir on success. +# +# Idempotent: dest-dir/.sha256 records the archive the files came from, and a +# matching record with sources.txt present is a no-op with no network access. +# The record is written last, so an interrupted run is a miss, never a +# half-extracted hit. (Modelled on scripts/fetch-sqlite-amalgamation.sh.) +set -eu + +root="$(cd "$(dirname "$0")/.." && pwd)" +lock="${LIBXMP_LOCK:-$root/contrib/xmp/libxmp.lock}" +dest="${1:-$root/contrib/xmp/libxmp}" + +[ -f "$lock" ] || { echo "fetch-libxmp: no lock file at $lock" >&2; exit 1; } +LIBXMP_URL=""; LIBXMP_SHA256=""; LIBXMP_VERSION="" +# shellcheck disable=SC1090 +. "$lock" +[ -n "$LIBXMP_URL" ] && [ -n "$LIBXMP_SHA256" ] || { + echo "fetch-libxmp: $lock must set LIBXMP_URL and LIBXMP_SHA256" >&2; exit 1; } + +if [ -f "$dest/sources.txt" ] && [ -f "$dest/.sha256" ] && + [ "$(cat "$dest/.sha256")" = "$LIBXMP_SHA256" ]; then + printf '%s\n' "$dest" + exit 0 +fi + +sha256_of() { + if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1 + elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1 + elif [ "$(uname -s)" = OpenBSD ]; then sha256 -q "$1" # base, no sha256sum + else echo "fetch-libxmp: neither sha256sum nor shasum is installed" >&2; return 1 + fi +} + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +tgz="$work/libxmp.tar.gz" + +echo "fetch-libxmp: downloading libxmp $LIBXMP_VERSION from $LIBXMP_URL" >&2 +if command -v curl >/dev/null 2>&1; then + curl -fsSL "$LIBXMP_URL" -o "$tgz" || { echo "fetch-libxmp: download failed" >&2; exit 1; } +elif command -v wget >/dev/null 2>&1; then + wget -q -O "$tgz" "$LIBXMP_URL" || { echo "fetch-libxmp: download failed" >&2; exit 1; } +else + echo "fetch-libxmp: neither curl nor wget is installed" >&2; exit 1 +fi + +got="$(sha256_of "$tgz")" +if [ "$got" != "$LIBXMP_SHA256" ]; then + echo "fetch-libxmp: SHA-256 mismatch for $LIBXMP_URL" >&2 + echo " expected $LIBXMP_SHA256" >&2 + echo " got $got" >&2 + exit 1 +fi + +# The archive holds one top-level directory (libxmp-/). tar where it +# exists, python3's tarfile where it does not. +x="$work/x" +mkdir -p "$x" +if command -v tar >/dev/null 2>&1 && tar -xzf "$tgz" -C "$x" 2>/dev/null; then + : +elif command -v python3 >/dev/null 2>&1; then + rm -rf "$x"; mkdir -p "$x" + python3 -I - "$tgz" "$x" <<'PY' +import sys, tarfile +with tarfile.open(sys.argv[1], "r:gz") as t: + if hasattr(tarfile, "data_filter"): + t.extractall(sys.argv[2], filter="data") + else: + for m in t.getmembers(): + if m.name.startswith("/") or ".." in m.name.split("/"): + raise SystemExit("unsafe member " + m.name) + t.extractall(sys.argv[2]) +PY +else + echo "fetch-libxmp: need tar or python3 to extract the archive" >&2; exit 1 +fi +top="$(find "$x" -mindepth 1 -maxdepth 1 -type d | head -1)" +for f in include/xmp.h src/player.c Makefile.vc docs/COPYING README; do + [ -f "$top/$f" ] || { echo "fetch-libxmp: $f missing from the archive" >&2; exit 1; } +done + +# The full library's sources, exactly as Makefile.vc lists them (it uses +# CRLF line ends and backslashed paths): the three object lists, each ended +# by a blank line. +out="$work/out" +mkdir -p "$out" +awk '{ sub(/\r$/, "") } + /^(OBJS|PROWIZ_OBJS|DEPACKER_OBJS)[ \t]*=/ { on = 1; next } + on && /^[ \t]*$/ { on = 0 } + on && /\.obj/ { s = $1; gsub(/\\/, "/", s); sub(/\.obj$/, ".c", s); print s }' \ + "$top/Makefile.vc" > "$out/sources.txt" +n=0 +while IFS= read -r s; do + case "$s" in src/*.c) ;; *) echo "fetch-libxmp: unexpected source '$s' in Makefile.vc" >&2; exit 1 ;; esac + [ -f "$top/$s" ] || { echo "fetch-libxmp: Makefile.vc names $s, which the archive lacks" >&2; exit 1; } + n=$((n + 1)) +done < "$out/sources.txt" +[ "$n" -gt 100 ] || { echo "fetch-libxmp: only $n sources found in Makefile.vc" >&2; exit 1; } + +cp -R "$top/include" "$out/include" +cp -R "$top/src" "$out/src" +rm -rf "$out/src/lite" +cp "$top/docs/COPYING" "$out/COPYING" +cp "$top/README" "$out/README" + +# Replace an earlier fetch whole, so no file of another version survives; a +# directory this script did not make is never removed. +if [ -e "$dest" ]; then + if [ -f "$dest/sources.txt" ] || [ -z "$(ls -A "$dest" 2>/dev/null)" ]; then + rm -rf "$dest" + else + echo "fetch-libxmp: $dest exists and is not an earlier fetch; not replacing it" >&2 + exit 1 + fi +fi +mkdir -p "$(dirname "$dest")" +cp -R "$out" "$dest" +printf '%s' "$LIBXMP_SHA256" > "$dest/.sha256" +echo "fetch-libxmp: libxmp $LIBXMP_VERSION ready in $dest ($n sources)" >&2 +printf '%s\n' "$dest" diff --git a/scripts/stage-release.sh b/scripts/stage-release.sh index 471b04081..5f0ebe375 100755 --- a/scripts/stage-release.sh +++ b/scripts/stage-release.sh @@ -13,12 +13,13 @@ # --module-artifacts runs to precompile the installed std modules # (#1746); a cross-build, whose aetherc cannot run here, leaves it out and its # imports parse the sources. -# --contrib-archives builds contrib.sqlite's veneer and the vendored SQLite -# for the machine running this script and ships them as lib/contrib/ -# libaether_sqlite.a and libsqlite3.a (the dev layout's build/contrib, which +# --contrib-archives builds contrib.sqlite's veneer and the vendored SQLite, +# and contrib.xmp's veneer and the vendored libxmp, for the machine running +# this script and ships them as lib/contrib/libaether_sqlite.a, libsqlite3.a, +# libaether_xmp.a and libxmp.a (the dev layout's build/contrib, which # `ae build` and aeb's own link both put on -L). Only a NATIVE stage may pass # it: a cross-build's archives would be for the wrong machine. -# --contrib-target builds the same two archives for a cross-built +# --contrib-target builds the same four archives for a cross-built # release instead, with `zig cc -target ` (zig on PATH, and for a # FreeBSD triple the base sysroot in AETHER_SYSROOT, as the cross-build # itself takes them), -fPIC like the native ones, and checks each object is @@ -111,6 +112,10 @@ sh scripts/fetch-sqlite-amalgamation.sh >/dev/null # The same for contrib.quickjs: its pinned amalgamation ships, because # aether_quickjs.c compiles it into every program that imports the module. sh scripts/fetch-quickjs-amalgamation.sh >/dev/null +# And contrib.xmp's pinned libxmp source, which `ae build` (and +# `ae build --target`) compiles when no libaether_xmp.a is there; its +# licence (COPYING) ships beside it, with contrib/xmp/NOTICE. +sh scripts/fetch-libxmp.sh >/dev/null cp -r contrib "$out/share/aether/" c="$out/share/aether/contrib" find "$c" -type d \( -name tests -o -name benchmarks \) -prune -exec rm -rf {} + @@ -121,13 +126,16 @@ sh .github/scripts/trim_contrib_sources.sh "$c" --keep-host-bridges echo "$0: the SQLite amalgamation is missing from the staged contrib" >&2; exit 1; } [ -f "$c/quickjs/amalgamation/quickjs-amalgam.c" ] || { echo "$0: the QuickJS amalgamation is missing from the staged contrib" >&2; exit 1; } +[ -f "$c/xmp/libxmp/src/player.c" ] && [ -f "$c/xmp/libxmp/COPYING" ] || { + echo "$0: the libxmp source or its licence is missing from the staged contrib" >&2; exit 1; } # Compiled module artifacts (#1746), made by the aetherc this release ships. if [ -n "$modules_aetherc" ]; then sh scripts/build_module_artifacts.sh "$modules_aetherc" . "$out/lib/aether/modules" fi -# The contrib.sqlite archives (#1372). A program linked without `ae build` +# The contrib.sqlite and contrib.xmp archives (#1372). A program linked +# without `ae build` # (aeb's orchestrator link, an aether.toml link_flags list) names # `-laether_sqlite -lsqlite3` itself and reads no source, so a release that # ships only the source (above) fails it with "library 'aether_sqlite' not @@ -136,11 +144,12 @@ fi # (see the header). if [ -n "$contrib_archives" ]; then cdir="$(mktemp -d)" - if ! CONTRIB_TARGET="$contrib_target" MODULES=sqlite CONTRIB_OUT="$cdir" \ + if ! CONTRIB_TARGET="$contrib_target" MODULES=sqlite,xmp CONTRIB_OUT="$cdir" \ bash tests/scripts/contrib_build.sh >"$cdir/build.log" 2>&1 \ - || [ ! -f "$cdir/libaether_sqlite.a" ] || [ ! -f "$cdir/libsqlite3.a" ]; then + || [ ! -f "$cdir/libaether_sqlite.a" ] || [ ! -f "$cdir/libsqlite3.a" ] \ + || [ ! -f "$cdir/libaether_xmp.a" ] || [ ! -f "$cdir/libxmp.a" ]; then sed 's/^/ /' "$cdir/build.log" >&2 - echo "$0: could not build the contrib.sqlite archives${contrib_target:+ for $contrib_target} (the vendored libsqlite3.a is required)" >&2 + echo "$0: could not build the contrib.sqlite and contrib.xmp archives${contrib_target:+ for $contrib_target} (the vendored libsqlite3.a and libxmp.a are required)" >&2 rm -rf "$cdir"; exit 1 fi # A cross stage's archives must hold objects for the target: contrib_build @@ -155,7 +164,7 @@ if [ -n "$contrib_archives" ]; then aarch64-*) want="ELF 64-bit LSB relocatable, ARM aarch64" ;; *) want="ELF" ;; esac - for a in libaether_sqlite.a libsqlite3.a; do + for a in libaether_sqlite.a libsqlite3.a libaether_xmp.a libxmp.a; do xd="$cdir/x.$a" mkdir -p "$xd" (cd "$xd" && zig ar x "$cdir/$a") || { echo "$0: cannot unpack $a" >&2; rm -rf "$cdir"; exit 1; } @@ -169,7 +178,8 @@ if [ -n "$contrib_archives" ]; then done fi mkdir -p "$out/lib/contrib" - cp "$cdir/libaether_sqlite.a" "$cdir/libsqlite3.a" "$out/lib/contrib/" + cp "$cdir/libaether_sqlite.a" "$cdir/libsqlite3.a" \ + "$cdir/libaether_xmp.a" "$cdir/libxmp.a" "$out/lib/contrib/" rm -rf "$cdir" fi diff --git a/tests/integration/install_contrib_resolves/test_install_contrib_resolves.sh b/tests/integration/install_contrib_resolves/test_install_contrib_resolves.sh index 9bb5325d4..9c1ec5aa7 100755 --- a/tests/integration/install_contrib_resolves/test_install_contrib_resolves.sh +++ b/tests/integration/install_contrib_resolves/test_install_contrib_resolves.sh @@ -65,6 +65,8 @@ unexpected_c_files() { # contrib.sqlite's veneer and fetched amalgamation ship in both # layouts: `ae build --target` compiles them for the target (#1372). case "$f" in */contrib/sqlite/aether_sqlite.c|*/contrib/sqlite/amalgamation/*.c) continue ;; esac + # contrib.xmp's veneer and fetched libxmp source, for the same reason. + case "$f" in */contrib/xmp/aether_xmp.c|*/contrib/xmp/libxmp/*.c) continue ;; esac # aether_quickjs.c #includes the fetched QuickJS amalgamation, so no # @source names it; it ships with the module that needs it. case "$f" in */contrib/quickjs/amalgamation/*.c) continue ;; esac diff --git a/tests/integration/install_manifest/test_install_host_bridges.sh b/tests/integration/install_manifest/test_install_host_bridges.sh index 540113844..fefa52294 100755 --- a/tests/integration/install_manifest/test_install_host_bridges.sh +++ b/tests/integration/install_manifest/test_install_host_bridges.sh @@ -114,6 +114,8 @@ extra=$(echo "$shipped_c" | while IFS= read -r f; do # contrib.sqlite's veneer and fetched amalgamation, which # `ae build --target` compiles for the target (#1372). case "$f" in */contrib/sqlite/aether_sqlite.c|*/contrib/sqlite/amalgamation/*.c) continue ;; esac + # contrib.xmp's veneer and fetched libxmp source, for the same reason. + case "$f" in */contrib/xmp/aether_xmp.c|*/contrib/xmp/libxmp/*.c) continue ;; esac # aether_quickjs.c #includes the fetched QuickJS amalgamation (no @source). case "$f" in */contrib/quickjs/amalgamation/*.c) continue ;; esac echo "$sourced" | grep -qxF -- "$(physical "$f")" && continue diff --git a/tests/integration/libxmp_fetch/test_libxmp_fetch.sh b/tests/integration/libxmp_fetch/test_libxmp_fetch.sh new file mode 100644 index 000000000..018d1a2f5 --- /dev/null +++ b/tests/integration/libxmp_fetch/test_libxmp_fetch.sh @@ -0,0 +1,126 @@ +#!/bin/sh +# scripts/fetch-libxmp.sh fetches the pinned libxmp release and refuses +# anything else. +# +# Runs against a fixture tarball and lock (LIBXMP_LOCK, a file:// URL), so it +# needs no network and never touches contrib/xmp/libxmp. +# +# Asserts: +# - an archive whose SHA-256 is not the pinned one is refused, and nothing +# is extracted (no .sha256 record, no sources.txt) +# - the pinned archive extracts include/, src/ (without src/lite, the +# libxmp-lite build), COPYING and README, writes sources.txt as exactly +# Makefile.vc's three object lists (CRLF line ends, backslashed paths), +# records its hash, and prints the destination +# - a second run with a matching record is a no-op that does not download +# - an archive whose Makefile.vc names a source it lacks is refused +# - a destination that is not an earlier fetch is never replaced +set -e +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" +. "$ROOT/tests/lib/portable.sh" +FETCH="$ROOT/scripts/fetch-libxmp.sh" +NAME=libxmp_fetch + +command -v curl >/dev/null 2>&1 || { echo " [SKIP] $NAME: needs curl for file:// URLs"; exit 0; } +command -v python3 >/dev/null 2>&1 || { echo " [SKIP] $NAME: needs python3 to build the fixture"; exit 0; } + +T="$(mktemp -d)" +trap 'rm -rf "$T" || true' EXIT + +fail() { + echo " [FAIL] $NAME: $1" + [ -n "${2:-}" ] && printf '%s\n' "$2" | sed 's/^/ /' | head -10 + exit 1 +} + +# make_tgz OUT N -- a tarball shaped like libxmp's release: one top directory, +# a Makefile.vc listing N sources per object list beyond the files present +# when N > 40 (40 of each list are there; 3 lists, 120 sources). +make_tgz() { + python3 -I - "$1" "$2" <<'PY' +import io, sys, tarfile +out, listed = sys.argv[1], int(sys.argv[2]) +top = "libxmp-9.9.9/" +files = {"include/xmp.h": "/* fixture */\n", "docs/COPYING": "fixture licence\n", + "README": "fixture\n", "src/lite/lite-player.c": "/* lite */\n", + "src/loaders/README": "not a source\n"} +lists = {"OBJS": "src\\core%02d", "PROWIZ_OBJS": "src\\loaders\\prowizard\\pw%02d", + "DEPACKER_OBJS": "src\\depackers\\dp%02d"} +mk = ["CFLAGS = /O2\r\n", "\r\n"] +for var, pat in lists.items(): + mk.append(var + "\t= \\\r\n") + for i in range(listed): + name = pat % i + mk.append(" " + name + ".obj \\\r\n") + if i < 40: + files[name.replace("\\", "/") + ".c"] = "/* %s */\n" % name + mk.append("\r\n") +files["src/player.c"] = "/* player */\n" +mk.append("LITE_OBJS\t= \\\r\n src\\lite\\lite-player.obj \\\r\n\r\n") +files["Makefile.vc"] = "".join(mk) +with tarfile.open(out, "w:gz") as t: + for n, body in files.items(): + data = body.encode() + info = tarfile.TarInfo(top + n) + info.size = len(data) + t.addfile(info, io.BytesIO(data)) +PY +} +sha() { sha256_of "$1"; } +lock() { # lock URL SHA + printf 'LIBXMP_VERSION=9.9.9\nLIBXMP_URL=%s\nLIBXMP_SHA256=%s\nLIBXMP_CFLAGS="-DX"\n' "$1" "$2" > "$T/lock" +} +url() { # file:// URL that a native Windows curl also understands + p="$1" + command -v cygpath >/dev/null 2>&1 && p="/$(cygpath -m "$p")" + printf 'file://%s' "$p" +} +export LIBXMP_LOCK="$T/lock" + +make_tgz "$T/good.tar.gz" 40 +GOOD_SHA="$(sha "$T/good.tar.gz")" + +# --- 1. wrong checksum is refused --------------------------------------- +lock "$(url "$T/good.tar.gz")" "0000000000000000000000000000000000000000000000000000000000000000" +if OUT=$(sh "$FETCH" "$T/dest" 2>&1); then fail "a checksum mismatch was accepted" "$OUT"; fi +echo "$OUT" | grep -q "SHA-256 mismatch" || fail "the refusal did not say why" "$OUT" +[ -e "$T/dest/.sha256" ] && fail "a refused archive left a hash record" +[ -e "$T/dest/sources.txt" ] && fail "a refused archive was extracted" + +# --- 2. the pinned archive extracts the full library's sources ---------- +lock "$(url "$T/good.tar.gz")" "$GOOD_SHA" +OUT=$(sh "$FETCH" "$T/dest" 2>/dev/null) || fail "the pinned archive was refused" "$(sh "$FETCH" "$T/dest" 2>&1)" +[ "$OUT" = "$T/dest" ] || fail "stdout was not the destination" "$OUT" +for f in include/xmp.h src/player.c src/core00.c src/loaders/prowizard/pw39.c src/depackers/dp07.c COPYING README sources.txt; do + [ -f "$T/dest/$f" ] || fail "$f was not extracted" +done +[ -e "$T/dest/src/lite" ] && fail "src/lite (libxmp-lite) was extracted too" +n=$(grep -c . "$T/dest/sources.txt") +[ "$n" = 120 ] || fail "sources.txt has $n lines, not Makefile.vc's 120" +grep -q 'lite' "$T/dest/sources.txt" && fail "sources.txt names a libxmp-lite source" +grep -q "$(printf '\r')" "$T/dest/sources.txt" && fail "sources.txt kept Makefile.vc's CR line ends" +[ "$(sed -n 41p "$T/dest/sources.txt")" = "src/loaders/prowizard/pw00.c" ] || + fail "sources.txt does not hold Makefile.vc's paths, in order" "$(sed -n 39,42p "$T/dest/sources.txt")" +[ "$(cat "$T/dest/.sha256")" = "$GOOD_SHA" ] || fail "the hash record is wrong" + +# --- 3. a matching record does not download again ------------------------ +lock "$(url "$T/no-such.tar.gz")" "$GOOD_SHA" +OUT=$(sh "$FETCH" "$T/dest" 2>&1) || fail "an already-fetched pin tried to download" "$OUT" +echo "$OUT" | grep -q "downloading" && fail "an already-fetched pin downloaded" "$OUT" + +# --- 4. an archive missing a listed source is refused -------------------- +make_tgz "$T/short.tar.gz" 41 +lock "$(url "$T/short.tar.gz")" "$(sha "$T/short.tar.gz")" +if OUT=$(sh "$FETCH" "$T/dest2" 2>&1); then fail "an archive lacking a listed source was accepted" "$OUT"; fi +echo "$OUT" | grep -q "core40.c, which the archive lacks" || fail "the refusal did not name the source" "$OUT" +[ -e "$T/dest2/.sha256" ] && fail "an incomplete archive left a hash record" + +# --- 5. a directory that is not an earlier fetch is left alone ------------ +mkdir -p "$T/mine" +echo keep > "$T/mine/notes.txt" +lock "$(url "$T/good.tar.gz")" "$GOOD_SHA" +if OUT=$(sh "$FETCH" "$T/mine" 2>&1); then fail "a foreign directory was replaced" "$OUT"; fi +[ "$(cat "$T/mine/notes.txt")" = keep ] || fail "a foreign directory's file was touched" + +echo " [PASS] libxmp fetch: pinned, verified, Makefile.vc's source list, idempotent" diff --git a/tests/integration/release_contrib_c_modules/test_release_contrib_c_modules.sh b/tests/integration/release_contrib_c_modules/test_release_contrib_c_modules.sh index 0d644b25b..22ea431cd 100755 --- a/tests/integration/release_contrib_c_modules/test_release_contrib_c_modules.sh +++ b/tests/integration/release_contrib_c_modules/test_release_contrib_c_modules.sh @@ -14,7 +14,8 @@ # # The release tree is staged by scripts/stage-release.sh, the script every # release.yml leg packs, so this checks what ships. It fetches the SQLite and -# QuickJS amalgamations (a no-op when they are already in the tree); offline, +# QuickJS amalgamations and the libxmp source (a no-op when they are already +# in the tree); offline, # with neither there, the test skips. contrib.avcodec is checked where # FFmpeg's development libraries are installed, except on Windows (below). # sweep-timeout: 900 @@ -39,7 +40,7 @@ trap 'rm -rf "$TMP" || true' EXIT rel="$TMP/release" if ! sh "$ROOT/scripts/stage-release.sh" "$ROOT/build" "$rel" --contrib-archives > "$TMP/stage.log" 2>&1; then - if grep -q -E "fetch-(sqlite|quickjs)" "$TMP/stage.log"; then + if grep -q -E "fetch-(sqlite|quickjs|libxmp)" "$TMP/stage.log"; then echo " [SKIP] $NAME: the amalgamations could not be fetched (offline?)" exit 0 fi @@ -53,13 +54,14 @@ fi # is the runtime's Windows --emit=obj entry point). aeb's own link names # `-laether_sqlite -lsqlite3` and never compiles contrib source, so a release # without them failed `library 'aether_sqlite' not found` for sae and LisMusic. -for a in libaether_sqlite.a libsqlite3.a; do +for a in libaether_sqlite.a libsqlite3.a libaether_xmp.a libxmp.a; do [ -f "$rel/lib/contrib/$a" ] || { echo " [FAIL] $NAME: the staged release has no lib/contrib/$a" exit 1; } done others=$(find "$rel" \( -name 'libaether_*.a' ! -name libaether_main.a ! -name libaether_sqlite.a \ - -o -name 'libsqlite3.a' -path '*' ! -path "$rel/lib/contrib/*" \) ) + ! -name libaether_xmp.a \ + -o \( -name 'libsqlite3.a' -o -name 'libxmp.a' \) ! -path "$rel/lib/contrib/*" \) ) if [ -n "$others" ]; then echo " [FAIL] $NAME: unexpected contrib archives in the staged release:" echo "$others" | sed 's/^/ /' @@ -113,6 +115,27 @@ main() { }' "sqlite=42" mv "$TMP/amalgamation.away" "$rel/share/aether/contrib/sqlite/amalgamation" +# contrib.xmp the same two ways: compiled from the libxmp source the release +# ships, then with that source gone, from the shipped archives. Bytes that +# are no module go through every one of libxmp's loaders before the refusal. +XMP_PROG='import contrib.xmp +import std.string +main() { + junk = "" + i = 0 + while i < 64 { + junk = string.concat(junk, "not a tracker module, only text. ") + i = i + 1 + } + p, err = xmp.load(junk, string.length(junk)) + if p == null { println("xmp=${err}") } +}' +XMP_WANT="xmp=xmp: not a module format libxmp recognises" +check xmp "$XMP_PROG" "$XMP_WANT" +mv "$rel/share/aether/contrib/xmp/libxmp" "$TMP/libxmp.away" +check xmp_archives "$XMP_PROG" "$XMP_WANT" +mv "$TMP/libxmp.away" "$rel/share/aether/contrib/xmp/libxmp" + # Linked the way aeb links (no `ae build`): the emitted C, libaether.a and the # module's own @link flags, with only -L lib and -L lib/contrib. if [ "$EXE" != ".exe" ]; then @@ -173,5 +196,5 @@ main() { fi [ "$fails" -eq 0 ] || exit 1 -echo " [PASS] $NAME: contrib.sqlite, jq and i18n.collate build and run from a staged release" +echo " [PASS] $NAME: contrib.sqlite, xmp, jq and i18n.collate build and run from a staged release" exit 0 diff --git a/tests/integration/release_cross_contrib_archives/test_release_cross_contrib_archives.sh b/tests/integration/release_cross_contrib_archives/test_release_cross_contrib_archives.sh index 155fd420d..16a4cecf2 100644 --- a/tests/integration/release_cross_contrib_archives/test_release_cross_contrib_archives.sh +++ b/tests/integration/release_cross_contrib_archives/test_release_cross_contrib_archives.sh @@ -1,6 +1,7 @@ #!/bin/sh # The FreeBSD release ships contrib.sqlite's archives, as Linux's and macOS's -# do: lib/contrib/libaether_sqlite.a and libsqlite3.a, built for FreeBSD. +# do: lib/contrib/libaether_sqlite.a and libsqlite3.a, built for FreeBSD (and +# contrib.xmp's, libaether_xmp.a and libxmp.a, the same way). # # Until 2026-11 the FreeBSD leg staged its archive without them (a native # stage builds them for the machine it runs on, and the FreeBSD release is @@ -73,15 +74,15 @@ trap 'rm -rf "$TMP" || true' EXIT rel="$TMP/release" if ! sh "$ROOT/scripts/stage-release.sh" "$bin" "$rel" --contrib-target x86_64-freebsd.15.0 \ > "$TMP/stage.log" 2>&1; then - if grep -q "fetch-sqlite" "$TMP/stage.log"; then - echo " [SKIP] $NAME: the SQLite amalgamation could not be fetched (offline?)" + if grep -q -E "fetch-(sqlite|libxmp)" "$TMP/stage.log"; then + echo " [SKIP] $NAME: the SQLite amalgamation or libxmp could not be fetched (offline?)" exit 0 fi echo " [FAIL] $NAME: scripts/stage-release.sh --contrib-target failed" tail -12 "$TMP/stage.log" | sed 's/^/ /' exit 1 fi -for a in libaether_sqlite.a libsqlite3.a; do +for a in libaether_sqlite.a libsqlite3.a libaether_xmp.a libxmp.a; do [ -f "$rel/lib/contrib/$a" ] || { echo " [FAIL] $NAME: no lib/contrib/$a"; exit 1; } x="$TMP/x.$a" mkdir -p "$x" @@ -94,4 +95,4 @@ for a in libaether_sqlite.a libsqlite3.a; do esac done done -echo " [PASS] $NAME: the FreeBSD stage ships lib/contrib/libaether_sqlite.a and libsqlite3.a, for x86-64 FreeBSD" +echo " [PASS] $NAME: the FreeBSD stage ships lib/contrib/libaether_sqlite.a, libsqlite3.a, libaether_xmp.a and libxmp.a, for x86-64 FreeBSD" diff --git a/tests/integration/trim_contrib_sources/test_trim_contrib_sources.sh b/tests/integration/trim_contrib_sources/test_trim_contrib_sources.sh index 71ddcc073..eae124f7c 100644 --- a/tests/integration/trim_contrib_sources/test_trim_contrib_sources.sh +++ b/tests/integration/trim_contrib_sources/test_trim_contrib_sources.sh @@ -4,6 +4,7 @@ # every .c and .m goes, except a file a module.ae in the tree names with # @source (contrib.vulkan.vk names one a directory up), contrib.sqlite's # veneer and fetched amalgamation (`ae build --target` compiles them, #1372), +# contrib.xmp's veneer and fetched libxmp source (the same, for libxmp), # and, when asked, the contrib/host//aether_host_.c bridges. Run # on a tree built here, so it needs no install and no toolchain. set -eu @@ -34,6 +35,13 @@ make_tree() { : > "$1/sqlite/amalgamation/sqlite3.c" : > "$1/sqlite/amalgamation/sqlite3.h" : > "$1/sqlite/scratch.c" + # contrib.xmp: the veneer and the fetched libxmp source, nested. + mkdir -p "$1/xmp/libxmp/src/loaders" + printf '// links libaether_xmp.a\n' > "$1/xmp/module.ae" + : > "$1/xmp/aether_xmp.c" + : > "$1/xmp/libxmp/src/player.c" + : > "$1/xmp/libxmp/src/loaders/mod_load.c" + : > "$1/xmp/scratch.c" printf '// links libaether_tinyweb.a\n' > "$1/tinyweb/module.ae" : > "$1/tinyweb/ws_handshake.c" # A package whose C file is @source'd from a sibling .ae, not module.ae @@ -68,6 +76,9 @@ gone "$TMP/contrib/tinyweb/ws_handshake.c" "keep-host: an archived mod present "$TMP/contrib/sqlite/aether_sqlite.c" "keep-host: contrib.sqlite's veneer, for --target" present "$TMP/contrib/sqlite/amalgamation/sqlite3.c" "keep-host: the SQLite amalgamation, for --target" gone "$TMP/contrib/sqlite/scratch.c" "keep-host: only the veneer is kept in sqlite/" +present "$TMP/contrib/xmp/aether_xmp.c" "keep-host: contrib.xmp's veneer, for --target" +present "$TMP/contrib/xmp/libxmp/src/loaders/mod_load.c" "keep-host: the libxmp source, for --target" +gone "$TMP/contrib/xmp/scratch.c" "keep-host: only the veneer is kept in xmp/" # --- install-contrib: archives carry the bridges, so they go too ------------ make_tree "$TMP/contrib" @@ -78,6 +89,7 @@ gone "$TMP/contrib/host/stunt/aether_host_stunt.c" "no-flag: host bridge" gone "$TMP/contrib/tinyweb/ws_handshake.c" "no-flag: archived module's source" present "$TMP/contrib/sqlite/aether_sqlite.c" "no-flag: contrib.sqlite's veneer, for --target" present "$TMP/contrib/sqlite/amalgamation/sqlite3.c" "no-flag: the SQLite amalgamation, for --target" +present "$TMP/contrib/xmp/libxmp/src/player.c" "no-flag: the libxmp source, for --target" # --- the one contrib.vulkan.vk needs: "../aether_vulkan.c" alone ----------- make_tree "$TMP/contrib" diff --git a/tests/integration/xmp_vendored_cross/NEEDS_EXTERNAL_TOOLCHAIN b/tests/integration/xmp_vendored_cross/NEEDS_EXTERNAL_TOOLCHAIN new file mode 100644 index 000000000..9099ed3f6 --- /dev/null +++ b/tests/integration/xmp_vendored_cross/NEEDS_EXTERNAL_TOOLCHAIN @@ -0,0 +1,4 @@ +zig 0.16.0 (scripts/get-zig.sh) and the fetched libxmp source +(scripts/fetch-libxmp.sh). Each target compiles the runtime and, on a cold +cache, libxmp's 179 sources, so this runs in CI's ci-sqlite-cross job rather +than the default sweep. diff --git a/tests/integration/xmp_vendored_cross/test_xmp_vendored_cross.sh b/tests/integration/xmp_vendored_cross/test_xmp_vendored_cross.sh new file mode 100644 index 000000000..d10dc88ec --- /dev/null +++ b/tests/integration/xmp_vendored_cross/test_xmp_vendored_cross.sh @@ -0,0 +1,113 @@ +#!/bin/sh +# `ae build --target` links contrib.xmp with no libxmp on the target, +# compiling the pinned libxmp source once per target and reusing it. +# +# For each musl target (static, so it runs without a target sysroot): +# - contrib/xmp/test_xmp.ae, the module's full spec, cross-builds and passes +# when run (natively for the host's arch, under qemu-user for another +# arch when it is installed; otherwise the binary's arch is checked and +# running is skipped) +# - the binary is statically linked: nothing for a libxmp to satisfy +# - libxmp's objects sit in the ae cache under the target's name, and a +# second build reuses them ("Compiling libxmp" is printed on a miss only) +# +# Needs zig on PATH and the fetched libxmp source; skips without either. +# Uses $AETHER_CACHE_DIR when set (CI persists it), a fresh one otherwise. +set -e +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" +. "$ROOT/tests/lib/portable.sh" +AE="$ROOT/build/ae" +NAME=xmp_vendored_cross +[ -x "$AE" ] || { echo " [SKIP] $NAME: ae not built"; exit 0; } +command -v zig >/dev/null 2>&1 || { echo " [SKIP] $NAME: zig not on PATH (scripts/get-zig.sh)"; exit 0; } +[ -f "$ROOT/contrib/xmp/libxmp/sources.txt" ] || { + echo " [SKIP] $NAME: no libxmp source (scripts/fetch-libxmp.sh)"; exit 0; } + +T="$(mktemp -d)" +trap 'rm -rf "$T" || true' EXIT +if [ -z "${AETHER_CACHE_DIR:-}" ]; then + AETHER_CACHE_DIR="$T/cache" +fi +export AETHER_CACHE_DIR +mkdir -p "$AETHER_CACHE_DIR" + +TARGETS="${XMP_CROSS_TARGETS:-x86_64-linux-musl aarch64-linux-musl}" +HOST_ARCH="$(uname -m)" +[ "$HOST_ARCH" = arm64 ] && HOST_ARCH=aarch64 + +fail() { + echo " [FAIL] $NAME: $1" + [ -n "${2:-}" ] && printf '%s\n' "$2" | grep -vE '^[[:space:]]*$' | tail -12 | sed 's/^/ /' + exit 1 +} + +cat > "$T/info.ae" <<'AE' +import contrib.xmp + +main() { + p, err = xmp.load("", 0) + if p == null { println("refused: ${err}") } +} +AE +cp "$ROOT/contrib/xmp/test_xmp.ae" "$T/spec.ae" + +# A musl Linux binary runs natively only on Linux. +runner_for() { + [ "$(uname -s)" = Linux ] || return 1 + case "$1" in + "$HOST_ARCH") echo "" ; return 0 ;; + esac + for q in "qemu-$1-static" "qemu-$1"; do + if command -v "$q" >/dev/null 2>&1; then echo "$q"; return 0; fi + done + return 1 +} + +for target in $TARGETS; do + arch="${target%%-*}" + case "$arch" in + x86_64) want_file="x86-64" ;; + aarch64) want_file="aarch64" ;; + *) want_file="$arch" ;; + esac + + cold=1 + ls "$AETHER_CACHE_DIR" | grep -q "^libxmp[0-9]*-$target-.*\.o$" && cold=0 + FIRST=$(cd "$T" && "$AE" build --target="$target" info.ae -o "info-$target" 2>&1) || { + case "$FIRST" in + *"sub-compilation of musl libc.a failed"*) + echo " [SKIP] $NAME: zig cannot build musl libc.a on this host"; exit 0 ;; + esac + fail "info.ae did not build for $target" "$FIRST"; } + if [ "$cold" = 1 ]; then + case "$FIRST" in *"Compiling libxmp for $target"*) ;; + *) fail "a cold cache did not compile libxmp for $target" "$FIRST" ;; esac + fi + n=$(ls "$AETHER_CACHE_DIR" | grep -c "^libxmp[0-9]*-$target-.*\.o$" || true) + want_n=$(grep -c . "$ROOT/contrib/xmp/libxmp/sources.txt") + [ "$n" -ge "$want_n" ] || fail "$n of libxmp's $want_n objects are cached for $target" + + SPEC_OUT=$(cd "$T" && "$AE" build --target="$target" spec.ae -o "spec-$target" 2>&1) \ + || fail "the contrib.xmp spec did not build for $target" "$SPEC_OUT" + case "$SPEC_OUT" in *"Compiling libxmp"*) fail "a warm cache recompiled libxmp for $target" "$SPEC_OUT" ;; esac + + if command -v file >/dev/null 2>&1; then + desc="$(file_desc "$T/spec-$target")" + printf '%s' "$desc" | grep -q "$want_file" || fail "$target binary has the wrong arch" "$desc" + printf '%s' "$desc" | grep -q "statically linked" || fail "$target binary is not static" "$desc" + fi + + if run=$(runner_for "$arch"); then + GOT=$(cd "$T" && $run "./info-$target") || fail "$target probe did not run" "$GOT" + case "$GOT" in "refused: xmp: "*) ;; *) fail "$target probe printed '$GOT'" ;; esac + SPEC=$(cd "$T" && $run "./spec-$target" 2>&1) || fail "the contrib.xmp spec failed on $target" "$SPEC" + printf '%s' "$SPEC" | grep -q "passing" || fail "the spec reported no passes on $target" "$SPEC" + printf '%s' "$SPEC" | grep -qiE "failing|pending|skipped" && fail "the spec did not pass outright on $target" "$SPEC" + echo " $target: built, ran the spec${run:+ (under $run)}" + else + echo " $target: built (no qemu-$arch here, so not run)" + fi +done + +echo " [PASS] $NAME: self-contained libxmp for $TARGETS" diff --git a/tests/scripts/contrib_build.sh b/tests/scripts/contrib_build.sh index b74bedcf2..ae016d2ad 100755 --- a/tests/scripts/contrib_build.sh +++ b/tests/scripts/contrib_build.sh @@ -4,7 +4,7 @@ # Two modes: # # 1. Default (MODULES unset) — best-effort: probe every contrib module -# (sqlite, avcodec and the host bridges left here, stunt and aether). For each available dep, compile + archive. +# (sqlite, avcodec, xmp and the host bridges left here, stunt and aether). For each available dep, compile + archive. # Skip + tally any whose dev libs aren't installed. Same shape as # historical behaviour; convenient for dev boxes. # @@ -26,7 +26,8 @@ # Writes build/contrib/MANIFEST listing one line per built archive: # \t[\t] # The optional third column is the name to install it under, when that is not -# libaether_.a (the vendored SQLite, which stays libsqlite3.a). +# libaether_.a (the vendored SQLite and libxmp, which stay +# libsqlite3.a and libxmp.a). # `make install-contrib` reads this manifest to know what to ship. # # Called from `make contrib` (default mode) or @@ -227,6 +228,108 @@ build_vendored_sqlite() { return 0 } +# --- libxmp: the pinned source, or the system library ---------------------- +# contrib.xmp prefers the libxmp release pinned in contrib/xmp/libxmp.lock, +# compiled from the source list libxmp's Makefile.vc builds the full library +# from (scripts/fetch-libxmp.sh writes it as sources.txt) into +# build/contrib/libxmp.a beside the veneer. `-laether_xmp -lxmp` (the +# module's @link) then resolves -lxmp to that archive, as -lsqlite3 resolves +# to the vendored SQLite above, so the program needs no libxmp where it runs. +# +# Fetched on demand (checksum-verified, never committed). When it cannot be +# had the veneer builds against the system libxmp; LIBXMP_SYSTEM=1 forces +# that path. +LIBXMP_DIR="$ROOT/contrib/xmp/libxmp" +LIBXMP_VENDORED="" +LIBXMP_CFLAGS="" +xmp_requested() { + [ -z "${MODULES:-}" ] && return 0 + case ",$MODULES," in *,xmp,*) return 0 ;; esac + return 1 +} +if [ "${LIBXMP_SYSTEM:-}" != "1" ] && xmp_requested; then + if sh "$ROOT/scripts/fetch-libxmp.sh" "$LIBXMP_DIR" >/dev/null; then + LIBXMP_VENDORED=1 + # shellcheck disable=SC1090 + LIBXMP_CFLAGS="$(. "$ROOT/contrib/xmp/libxmp.lock"; printf '%s' "$LIBXMP_CFLAGS")" + else + echo " xmp: libxmp source unavailable -- falling back to the system library" >&2 + fi +fi + +# Compile every source in sources.txt and archive them as +# build/contrib/libxmp.a. The objects are cached as one archive in +# $LIBXMP_OBJ_CACHE_DIR, named for everything that changes it: the fetched +# release (its checksum), the source list, the compiler's identity, every +# flag and the target. Compiles run in parallel, one per processor. +LIBXMP_OBJ_CACHE_DIR="${LIBXMP_OBJ_CACHE_DIR:-$ROOT/.ci-cache/libxmp}" +build_vendored_libxmp() { + local AR="$1" + local flags="${BASE_CFLAGS[*]} -w $LIBXMP_CFLAGS -I$LIBXMP_DIR/include" + local key + key=$( { cat "$LIBXMP_DIR/.sha256" "$LIBXMP_DIR/sources.txt" + $CC --version 2>/dev/null | head -1 + printf '%s\n%s\n' "$flags" "$CONTRIB_TARGET"; } | sha256_text ) + local cached="$LIBXMP_OBJ_CACHE_DIR/libxmp-${key:0:16}.a" + if [ -f "$cached" ]; then + cp "$cached" "$STAGE/libxmp.a" + printf " %-18s cached archive %s\n" "libxmp" "${cached#"$ROOT"/}" + else + local nsrc; nsrc=$(wc -l < "$LIBXMP_DIR/sources.txt" | tr -d ' ') + printf " %-18s compiling %s sources (once per input set)\n" "libxmp" "$nsrc" + local od="$STAGE/libxmp.objs" + mkdir -p "$od" + local jobs + jobs=$(getconf _NPROCESSORS_ONLN 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 2) + # One compile per line of sources.txt, objects named by their index + # so two sources with one basename could not overwrite each other. + # Batches of $jobs background compiles: `wait -n` is not in the + # bash 3.2 macOS ships. + local i=0 src idx + while IFS= read -r src; do + [ -n "$src" ] || continue + i=$((i + 1)); idx=$(printf '%03d' "$i") + # shellcheck disable=SC2086 + ( $CC "${BASE_CFLAGS[@]}" -w $LIBXMP_CFLAGS -I"$LIBXMP_DIR/include" \ + -c "$LIBXMP_DIR/$src" -o "$od/x$idx.o" 2>"$od/x$idx.err" || + echo "$src" > "$od/x$idx.failed" ) & + [ $((i % jobs)) -eq 0 ] && wait + done < "$LIBXMP_DIR/sources.txt" + wait + cat "$od"/x*.failed > "$od/failed" 2>/dev/null || true + cat "$od"/x*.err > "$od/errors" 2>/dev/null || true + if [ -s "$od/failed" ] || [ "$(find "$od" -name 'x*.o' | wc -l | tr -d ' ')" != "$nsrc" ]; then + printf " %-18s FAIL (compile)\n" "libxmp" + sed 's/^/ /' "$od/failed" 2>/dev/null | head -5 + sed 's/^/ /' "$od/errors" 2>/dev/null | head -10 + return 2 + fi + # In a few batches, so no one command line grows past what a + # Windows shell will run. + local batch=() + local o + for o in "$od"/x*.o; do + batch+=("$o") + if [ "${#batch[@]}" -ge 40 ]; then + $AR rcs "$STAGE/libxmp.a" "${batch[@]}" || { printf " %-18s FAIL (archive)\n" "libxmp"; return 2; } + batch=() + fi + done + if [ "${#batch[@]}" -gt 0 ]; then + $AR rcs "$STAGE/libxmp.a" "${batch[@]}" || { printf " %-18s FAIL (archive)\n" "libxmp"; return 2; } + fi + rm -rf "$od" + mkdir -p "$LIBXMP_OBJ_CACHE_DIR" + cp "$STAGE/libxmp.a" "$cached.tmp.$$" && mv "$cached.tmp.$$" "$cached" + fi + publish libxmp.a + printf " %-18s OK build/contrib/libxmp.a (libxmp %s, vendored)\n" "libxmp" \ + "$(sed -n 's/^LIBXMP_VERSION=//p' "$ROOT/contrib/xmp/libxmp.lock")" + # Third column: installed as libxmp.a for the module's -lxmp. + echo -e "libxmp\tbuild/contrib/libxmp.a\tlibxmp.a" >> "$STAGE/MANIFEST" + return 0 +} + # probe_ echoes dev-include flags on stdout when the dep is # available. Returns 0 if available, 1 if not. @@ -261,6 +364,32 @@ probe_sqlite() { return 1 } +probe_xmp() { + # The vendored libxmp's header, so the veneer compiles against the libxmp + # it links (LIBXMP_STATIC: no dllimport on Windows), ahead of any system + # xmp.h. + if [ -n "$LIBXMP_VENDORED" ]; then + echo "-I$LIBXMP_DIR/include $LIBXMP_CFLAGS" + return 0 + fi + # Cross mode: libxmp is in no target's base; "present" iff it was staged + # into CROSSBUILD_SYSROOT (else SKIP/FAIL, as for sqlite3). + if [ -n "$CROSS_MODE" ]; then + cross_dep_present xmp.h xmp + return + fi + if pkg-config --exists libxmp 2>/dev/null; then + pkg-config --cflags-only-I libxmp + return 0 + fi + if printf '#include \nint main(){return 0;}\n' | \ + $CC -E -xc - >/dev/null 2>&1; then + echo "" + return 0 + fi + return 1 +} + probe_avcodec() { # FFmpeg's decode libraries. Video-only shim, but swscale does the RGBA # conversion and avutil carries the frame/image helpers, so all four are @@ -308,6 +437,9 @@ cross_class() { # -> echoes the class token # it, a libsqlite3 staged in CROSSBUILD_SYSROOT does. sqlite) if [ -n "$SQLITE_VENDORED" ]; then echo "vendored" else echo "tier3:sqlite3.h:sqlite3"; fi ;; + # The same for libxmp: its pinned source, else a staged libxmp. + xmp) if [ -n "$LIBXMP_VENDORED" ]; then echo "vendored" + else echo "tier3:xmp.h:xmp"; fi ;; # stunt's bridge has no dependency at all: it compiles like core. host_stunt) echo "tier1" ;; # The Aether host's fork+exec body is Linux/macOS only; not @@ -335,7 +467,10 @@ build_module() { incs="" ;; vendored) - incs="-I$SQLITE_AMAL_DIR" + case "$name" in + xmp) incs="-I$LIBXMP_DIR/include $LIBXMP_CFLAGS" ;; + *) incs="-I$SQLITE_AMAL_DIR" ;; + esac ;; tier3:*) local hdr="${class#tier3:}"; local lib="${hdr#*:}"; hdr="${hdr%%:*}" @@ -398,6 +533,9 @@ build_module() { if [ "$name" = "sqlite" ] && [ -n "$SQLITE_VENDORED" ]; then build_vendored_sqlite "$AR" || return 2 fi + if [ "$name" = "xmp" ] && [ -n "$LIBXMP_VENDORED" ]; then + build_vendored_libxmp "$AR" || return 2 + fi publish "libaether_$name.a" printf " %-18s OK build/contrib/libaether_%s.a\n" "$name" "$name" echo -e "$name\tbuild/contrib/libaether_$name.a" >> "$STAGE/MANIFEST" @@ -407,6 +545,9 @@ build_module() { if [ "$name" = "sqlite" ] && [ -z "$SQLITE_VENDORED" ]; then rm -f "$OUT/libsqlite3.a" fi + if [ "$name" = "xmp" ] && [ -z "$LIBXMP_VENDORED" ]; then + rm -f "$OUT/libxmp.a" + fi return 0 } @@ -419,6 +560,7 @@ build_module() { CATALOGUE=( "sqlite|sqlite contrib/sqlite/aether_sqlite.c AETHER_HAS_SQLITE probe_sqlite" "avcodec|avcodec contrib/avcodec/aether_avcodec.c AETHER_HAS_AVCODEC probe_avcodec" + "xmp|xmp contrib/xmp/aether_xmp.c AETHER_HAS_XMP probe_xmp" "aether|host_aether contrib/host/aether/aether_host_aether.c AETHER_HAS_AETHER_HOST probe_aether" "stunt|host_stunt contrib/host/stunt/aether_host_stunt.c AETHER_HAS_STUNT probe_stunt" ) diff --git a/tools/ae.c b/tools/ae.c index 6c78b567f..48b0ef4cb 100644 --- a/tools/ae.c +++ b/tools/ae.c @@ -5986,6 +5986,92 @@ static const char* vendored_sqlite_link(const char* cc, const char* ae_link, return rewritten; } +/* contrib.xmp on a toolchain with no libaether_xmp.a: the same as + * contrib.sqlite above. The module's @link asks for `-laether_xmp -lxmp`; + * a binary release ships contrib/xmp's veneer and the pinned libxmp source + * instead of the archives, so compile them (each object and the archive + * cached, ae_vendored_xmp) and link them in place of the two -l flags. A + * toolchain that has the archive keeps it, and so does one with no libxmp + * source to compile (the system-library route `make contrib` falls back to). + * + * Returns `ae_link` itself when nothing changes, else a string that lives + * until the next call; NULL when a compile failed (said). */ +static const char* vendored_xmp_link(const char* cc, const char* ae_link, + const char* user_cflags) { + static char* rewritten = NULL; + if (g_emit_obj || g_emit_csrc) return ae_link; /* no link */ + if (!link_list_has(ae_link, "-laether_xmp")) return ae_link; + if (tc.has_lib) { + char lib_dir[1024]; + snprintf(lib_dir, sizeof(lib_dir), "%s", tc.lib); + char* bs = strrchr(lib_dir, '\\'); + char* fs = strrchr(lib_dir, '/'); + char* slash = (!bs) ? fs : (!fs) ? bs : (bs > fs ? bs : fs); + if (slash) *slash = '\0'; + char a[1200]; + snprintf(a, sizeof(a), "%s/contrib/libaether_xmp.a", lib_dir); + if (path_exists(a)) return ae_link; + snprintf(a, sizeof(a), "%s/libaether_xmp.a", lib_dir); + if (path_exists(a)) return ae_link; + } + char list[1200]; + snprintf(list, sizeof(list), "%s/contrib/xmp/libxmp/sources.txt", tc.src_root); + if (!path_exists(list)) return ae_link; + +#ifdef _WIN32 + const char* pic = ""; +#else + const char* pic = " -fPIC"; +#endif + char* flags = ae_strdup_printf("-O2%s%s%s%s", pic, gcc_relation_flags(cc), + user_cflags[0] ? " " : "", user_cflags); + if (!flags) { + fprintf(stderr, "Error: out of memory building the contrib.xmp compile command.\n"); + return NULL; + } + /* The archiver that goes with the compiler: zig's own beside `zig cc`. */ + const char* ar = strncmp(cc, "zig cc", 6) == 0 ? "zig ar" : "ar"; + char objs[3400] = ""; + bool ok = ae_vendored_xmp(tc.src_root, "host", cc, ar, flags, NULL, + objs, sizeof(objs), NULL, NULL); + free(flags); + if (!ok) return NULL; + + /* The veneer and the archive take -laether_xmp's place; -lxmp goes. */ + size_t cap = strlen(ae_link) + strlen(objs) + 2; + char* out = malloc(cap); + if (!out) { + fprintf(stderr, "Error: out of memory building the link command.\n"); + return NULL; + } + size_t o = 0; + for (const char* p = ae_link; *p; ) { + while (*p == ' ') p++; + if (!*p) break; + const char* e = p; + while (*e && *e != ' ') e++; + size_t n = (size_t)(e - p); + const char* put = p; + size_t put_n = n; + if (n == 12 && strncmp(p, "-laether_xmp", 12) == 0) { + put = objs[0] == ' ' ? objs + 1 : objs; + put_n = strlen(put); + } else if (n == 5 && strncmp(p, "-lxmp", 5) == 0) { + put_n = 0; + } + if (put_n) { + if (o) out[o++] = ' '; + memcpy(out + o, put, put_n); + o += put_n; + } + p = e; + } + out[o] = '\0'; + free(rewritten); + rewritten = out; + return rewritten; +} + /* #2757: a source build (`ae build --trace`, or a toolchain with no * libaether.a) handed every runtime source to the one compiler command that * links the program, and the compiler took them one after another: about 90 @@ -6973,10 +7059,12 @@ void build_gcc_cmd(char* cmd, size_t size, /* See AETHER_WIN_SYSTEM_LIBS: one list, shared with `ae cflags --libs` * so the two cannot drift apart again. */ const char* win_link_libs = AETHER_WIN_SYSTEM_LIBS; - /* contrib.sqlite with no archive here: compile it (see - * vendored_sqlite_link). */ + /* contrib.sqlite and contrib.xmp with no archive here: compile them + * (see vendored_sqlite_link, vendored_xmp_link). */ ae_link = vendored_sqlite_link(s_gcc_cmd, ae_link, user_cflags); if (!ae_link) { free(opt); set_failing_cmd(cmd, size); return; } + ae_link = vendored_xmp_link(s_gcc_cmd, ae_link, user_cflags); + if (!ae_link) { free(opt); set_failing_cmd(cmd, size); return; } char lib_dir[1024]; if (tc.has_lib) { strncpy(lib_dir, tc.lib, sizeof(lib_dir) - 1); @@ -7103,10 +7191,12 @@ void build_gcc_cmd(char* cmd, size_t size, #ifdef __APPLE__ default_macos_deployment_target(); #endif - /* contrib.sqlite with no archive here: compile it (see - * vendored_sqlite_link). */ + /* contrib.sqlite and contrib.xmp with no archive here: compile them + * (see vendored_sqlite_link, vendored_xmp_link). */ ae_link = vendored_sqlite_link(cc, ae_link, user_cflags); if (!ae_link) { set_failing_cmd(cmd, size); return; } + ae_link = vendored_xmp_link(cc, ae_link, user_cflags); + if (!ae_link) { set_failing_cmd(cmd, size); return; } char* opt; /* the flags, with user cflags of any length (#2534) */ // --emit=lib adds -fPIC -shared so the output is loadable via dlopen. // --emit=both (exe + lib from one source) is not supported by this diff --git a/tools/ae_cross.c b/tools/ae_cross.c index 84f84b83d..01661a520 100644 --- a/tools/ae_cross.c +++ b/tools/ae_cross.c @@ -981,12 +981,13 @@ static int cross_link_wants(const char* link_hdr, const char* names) { * the right object; a miss compiles and publishes. The veneer is small and * is compiled per build like the runtime. */ -/* SQLITE_CFLAGS from the lock file, quotes stripped; "" when absent. A +/* The `key` (SQLITE_CFLAGS=, LIBXMP_CFLAGS=) line of a lock file, quotes + * stripped; "" when absent. A * string the caller frees, NULL when out of memory (after saying so). The * line is read whole (#2537): one past 1 KB was cut, its closing quote went * with the cut so the opening one stayed in the flags, and the flags past * the cut never reached the compile or the cache key. */ -static char* cross_sqlite_lock_cflags(const char* lock) { +static char* cross_lock_cflags(const char* lock, const char* key) { char* out = NULL; FILE* f = fopen(lock, "r"); if (f) { @@ -994,8 +995,9 @@ static char* cross_sqlite_lock_cflags(const char* lock) { size_t cap = 0; int got; while ((got = ae_read_line(f, &line, &cap)) > 0) { - if (strncmp(line, "SQLITE_CFLAGS=", 14) != 0) continue; - char* v = line + 14; + size_t kl = strlen(key); + if (strncmp(line, key, kl) != 0) continue; + char* v = line + kl; size_t n = strlen(v); while (n && (v[n-1] == '\n' || v[n-1] == '\r')) v[--n] = '\0'; if (n >= 2 && v[0] == '"' && v[n-1] == '"') { v[n-1] = '\0'; v++; } @@ -1112,7 +1114,7 @@ bool ae_vendored_sqlite(const char* base, const char* tag, return false; } - char* sqlite_cflags = cross_sqlite_lock_cflags(lock); + char* sqlite_cflags = cross_lock_cflags(lock, "SQLITE_CFLAGS="); if (!sqlite_cflags) return false; /* out of memory, said */ char cc_version[256]; cross_compiler_version(cc_cmd, cc_version, sizeof(cc_version)); @@ -1195,6 +1197,240 @@ bool ae_vendored_sqlite(const char* base, const char* tag, return ok; } +/* ---- contrib.xmp from the pinned libxmp source ----------------------------- + * + * The same arrangement for libxmp: a program importing contrib.xmp asks for + * `-laether_xmp -lxmp`, and when no archive covers the target the veneer and + * the libxmp release scripts/fetch-libxmp.sh put in contrib/xmp/libxmp/ are + * compiled here. libxmp is not one TU but the list libxmp's Makefile.vc + * builds the full library from (sources.txt), so each source is compiled to + * its own cache slot, `libxmpNNN--.o`, keyed on that source and on + * what keys the whole set: the release checksum and source list, the + * compiler command and version, the flags and the lock's LIBXMP_CFLAGS. The + * headers come from the same checksummed release as the sources. + * + * What is appended to `link_objs` is the veneer and one archive of those + * objects: in `objdir` when there is one (a cross build), else in the cache + * under the set's key. `obj_list`, when given, gets the objects themselves, + * for an --emit=staticlib archive (an archive inside an archive is not + * searched by a linker). */ +static void cross_hex_key(AeSha256* ctx, char key[17]) { + unsigned char digest[32]; + ae_sha256_final(ctx, digest); + for (int i = 0; i < 8; i++) snprintf(key + i * 2, 3, "%02x", digest[i]); +} + +/* Run `ar rcs ""` over `objs` (quoted paths, space-separated) in + * batches, so no single command line grows past what a Windows shell runs. */ +static bool cross_archive_batched(const char* ar_cmd, const char* archive, + char** objs, int nobjs, + char** cmd, size_t* cmd_cap) { + remove(archive); + for (int i = 0; i < nobjs; ) { + if (!cross_cmd_fmt(cmd, cmd_cap, "%s rcs \"%s\"", ar_cmd, archive)) return false; + for (int j = 0; j < 24 && i < nobjs; j++, i++) { + size_t used = strlen(*cmd); + if (!cross_buf_reserve(cmd, cmd_cap, used + strlen(objs[i]) + 4)) return false; + snprintf(*cmd + used, *cmd_cap - used, " \"%s\"", objs[i]); + } + if (run_cmd_show_warnings(*cmd) != 0) return false; + } + return true; +} + +bool ae_vendored_xmp(const char* base, const char* tag, + const char* cc_cmd, const char* ar_cmd, const char* flags, + const char* objdir, + char* link_objs, size_t link_sz, + char** obj_list, size_t* obj_cap) { + char dir[1200], list[1300], rec[1300], lock[1200], veneer[1200], str_h[1200], inc[1300]; + snprintf(dir, sizeof(dir), "%s/contrib/xmp/libxmp", base); + snprintf(list, sizeof(list), "%s/sources.txt", dir); + snprintf(rec, sizeof(rec), "%s/.sha256", dir); + snprintf(inc, sizeof(inc), "%s/include", dir); + snprintf(lock, sizeof(lock), "%s/contrib/xmp/libxmp.lock", base); + snprintf(veneer, sizeof(veneer), "%s/contrib/xmp/aether_xmp.c", base); + snprintf(str_h, sizeof(str_h), "%s/std/string/aether_string.h", base); + if (!path_exists(list) || !path_exists(veneer)) { + fprintf(stderr, + "Error: contrib.xmp needs libxmp built for %s, and neither source is here.\n" + " The pinned libxmp source is not in %s. In a source tree, fetch it with:\n" + " scripts/fetch-libxmp.sh\n" + " or build libaether_xmp.a + libxmp.a (`make contrib`; for a cross\n" + " target, stage them in a CROSSBUILD_SYSROOT, aether-crossbuild).\n", + tag, dir); + return false; + } + + /* The source list, one path per line, relative to `dir`. */ + char* srcs[512]; + int nsrc = 0; + { + FILE* f = fopen(list, "r"); + if (!f) { fprintf(stderr, "Error: cannot read %s\n", list); return false; } + char* line = NULL; + size_t cap = 0; + int got; + while ((got = ae_read_line(f, &line, &cap)) > 0) { + size_t n = strlen(line); + while (n && (line[n-1] == '\n' || line[n-1] == '\r' || line[n-1] == ' ')) line[--n] = '\0'; + if (!n) continue; + if (nsrc == (int)(sizeof(srcs) / sizeof(srcs[0]))) { got = -2; break; } + if (!(srcs[nsrc] = strdup(line))) { got = -1; break; } + nsrc++; + } + free(line); + fclose(f); + if (got < 0 || nsrc == 0) { + for (int i = 0; i < nsrc; i++) free(srcs[i]); + fprintf(stderr, "Error: %s is %s.\n", list, + got == -2 ? "longer than this toolchain expects" : + nsrc == 0 ? "empty" : "unreadable (out of memory)"); + return false; + } + } + + char* xmp_cflags = cross_lock_cflags(lock, "LIBXMP_CFLAGS="); + char cc_version[256]; + cross_compiler_version(cc_cmd, cc_version, sizeof(cc_version)); + + AeSha256 ctx; + char key[17]; + ae_sha256_init(&ctx); + cross_sha256_update_file(&ctx, rec); + cross_sha256_update_file(&ctx, list); + cross_sha256_update_str(&ctx, tag); + cross_sha256_update_str(&ctx, cc_cmd); + cross_sha256_update_str(&ctx, cc_version); + cross_sha256_update_str(&ctx, flags); + cross_sha256_update_str(&ctx, xmp_cflags ? xmp_cflags : ""); + cross_hex_key(&ctx, key); + + init_cache_dir(); + char* cmd = NULL; + char* prefix = NULL; + size_t cmd_cap = 0, prefix_cap = 0; + char* objs[512] = { 0 }; + bool ok = false; + char archive[1600], veneer_obj[1600]; + do { + if (!xmp_cflags) break; /* out of memory, said */ + /* The archive of the whole set, when the cache has it, is all a + * native build needs. */ + bool have_archive = false; + if (objdir) { + snprintf(archive, sizeof(archive), "%s/libxmp.a", objdir); + } else { + snprintf(archive, sizeof(archive), "%s/libxmp-%s-%s.a", s_cache_dir, tag, key); + if (path_exists(archive)) { cache_touch(archive); have_archive = true; } + } + bool need_objs = !have_archive || obj_list; + if (need_objs) { + if (!cross_cmd_fmt(&prefix, &prefix_cap, "%s %s -w %s -I\"%s\"", + cc_cmd, flags, xmp_cflags, inc)) { + fprintf(stderr, "Error: out of memory building the libxmp compile command.\n"); + break; + } + bool said = false, failed = false; + for (int i = 0; i < nsrc; i++) { + char src[1600], stem[32], okey[17]; + snprintf(src, sizeof(src), "%s/%s", dir, srcs[i]); + snprintf(stem, sizeof(stem), "libxmp%03d", i); + ae_sha256_init(&ctx); + cross_sha256_update_str(&ctx, key); + cross_sha256_update_str(&ctx, srcs[i]); + cross_sha256_update_file(&ctx, src); + cross_hex_key(&ctx, okey); + char slot[1400]; + snprintf(slot, sizeof(slot), "%s/%s-%s-%s.o", s_cache_dir, stem, tag, okey); + if (!said && !path_exists(slot)) { + fprintf(stderr, "Compiling libxmp for %s (%d sources, cached for later builds)...\n", + tag, nsrc); + said = true; + } + char obj[1600]; + if (!vendored_cached_obj(stem, tag, okey, prefix, src, &cmd, &cmd_cap, + obj, sizeof(obj)) || + !(objs[i] = strdup(obj))) { + fprintf(stderr, "Error: compiling libxmp's %s for %s failed.\n", srcs[i], tag); + failed = true; + break; + } + } + if (failed) break; + } + if (!have_archive) { + char tmp[1700]; + if (objdir) snprintf(tmp, sizeof(tmp), "%s", archive); + else snprintf(tmp, sizeof(tmp), "%s.tmp.%d", archive, (int)getpid()); + if (!cross_archive_batched(ar_cmd, tmp, objs, nsrc, &cmd, &cmd_cap)) { + fprintf(stderr, "Error: archiving libxmp for %s failed.\n", tag); + remove(tmp); + break; + } + if (!objdir) { + if (cache_publish(tmp, archive) == 0) cache_enforce_limit(archive, 0); + else snprintf(archive, sizeof(archive), "%s", tmp); + } + } + + /* The veneer, against the pinned headers. */ + if (!cross_cmd_fmt(&prefix, &prefix_cap, "%s %s %s -I\"%s\" %s", + cc_cmd, flags, xmp_cflags, inc, tc_include_flags())) { + fprintf(stderr, "Error: out of memory building the contrib.xmp compile command.\n"); + break; + } + bool vok; + if (objdir) { + snprintf(veneer_obj, sizeof(veneer_obj), "%s/aether_xmp.o", objdir); + vok = cross_cmd_fmt(&cmd, &cmd_cap, "%s -c \"%s\" -o \"%s\"", prefix, veneer, veneer_obj) + && run_cmd_show_warnings(cmd) == 0; + } else { + char vkey[17]; + ae_sha256_init(&ctx); + cross_sha256_update_str(&ctx, key); + cross_sha256_update_file(&ctx, veneer); + cross_sha256_update_file(&ctx, str_h); + cross_sha256_update_str(&ctx, prefix); + cross_hex_key(&ctx, vkey); + vok = vendored_cached_obj("aether_xmp", tag, vkey, prefix, veneer, &cmd, &cmd_cap, + veneer_obj, sizeof(veneer_obj)); + } + if (!vok) { + fprintf(stderr, "Error: compiling contrib.xmp for %s failed.\n", tag); + break; + } + size_t used = strlen(link_objs); + int w = snprintf(link_objs + used, link_sz - used, " \"%s\" \"%s\"", veneer_obj, archive); + if (w < 0 || (size_t)w >= link_sz - used) { + fprintf(stderr, "Error: the link line has no room for contrib.xmp.\n"); + break; + } + if (obj_list) { + bool grown = true; + size_t pos = *obj_list ? strlen(*obj_list) : 0; + for (int i = 0; i < nsrc && grown; i++) { + grown = cross_buf_reserve(obj_list, obj_cap, pos + strlen(objs[i]) + 4); + if (grown) pos += (size_t)snprintf(*obj_list + pos, *obj_cap - pos, " \"%s\"", objs[i]); + } + if (grown) { + grown = cross_buf_reserve(obj_list, obj_cap, pos + strlen(veneer_obj) + 4); + if (grown) snprintf(*obj_list + pos, *obj_cap - pos, " \"%s\"", veneer_obj); + } + if (!grown) { + fprintf(stderr, "Error: out of memory listing contrib.xmp's objects.\n"); + break; + } + } + ok = true; + } while (0); + for (int i = 0; i < nsrc; i++) { free(srcs[i]); free(objs[i]); } + free(cmd); + free(prefix); + free(xmp_cflags); + return ok; +} + int run_cross_build(const char* c_file, const char* out_file, bool optimize, const char* extra, const char* ztriple, bool emit_lib, @@ -1509,6 +1745,9 @@ int run_cross_build(const char* c_file, const char* out_file, * sqlite3_* references resolved by the lib that follows. */ { "aether_sqlite", "-laether_sqlite -lsqlite3", "aether_sqlite sqlite3", "" }, + /* contrib.xmp: the veneer, then libxmp. */ + { "aether_xmp", "-laether_xmp -lxmp", + "aether_xmp xmp", "" }, }; for (size_t i = 0; i < sizeof(t2) / sizeof(t2[0]); i++) { snprintf(probe, sizeof(probe), "%s/lib/lib%s.a", xsr, t2[i].probe); @@ -1548,6 +1787,14 @@ int run_cross_build(const char* c_file, const char* out_file, vendored_sqlite = cross_link_wants(link_hdr, "-laether_sqlite") != 0; free(link_hdr); } + /* contrib.xmp likewise, from the pinned libxmp source (ae_vendored_xmp). */ + bool vendored_xmp = false; + if (!strstr(crossbuild_libs, "libaether_xmp.a")) { + char* link_hdr = NULL; + if (cross_read_aether_link_raw(c_file, &link_hdr) < 0) return 1; + vendored_xmp = cross_link_wants(link_hdr, "-laether_xmp") != 0; + free(link_hdr); + } /* std.regex needs no sysroot (#1389): when nothing above staged a real * libpcre2-8 (no CROSSBUILD_SYSROOT, or one without pcre2), compile the * vendored engine instead. AETHER_VENDOR_PCRE2 turns @@ -1685,6 +1932,33 @@ int run_cross_build(const char* c_file, const char* out_file, snprintf(objlist + obj_pos, objlist_cap - obj_pos, "%s", sqlite_objs); obj_pos += strlen(sqlite_objs); } + /* 2a'. contrib.xmp from the pinned libxmp source: the veneer and + * an archive of libxmp join the link; an --emit=staticlib + * archive takes libxmp's objects themselves. */ + if (vendored_xmp) { + char xmp_flags[4096]; + snprintf(xmp_flags, sizeof(xmp_flags), "%s%s %s %s", + sysroot_flag, lib_pic, opt, user_cflags); + char xmp_objs[3400] = ""; + char* xmp_list = NULL; + size_t xmp_list_cap = 0; + bool xok = ae_vendored_xmp(base, ztriple, cc_cmd, ar_cmd, xmp_flags, objdir, + xmp_objs, sizeof(xmp_objs), + emit_staticlib ? &xmp_list : NULL, + emit_staticlib ? &xmp_list_cap : NULL); + if (!xok) { free(xmp_list); break; } + size_t cl = strlen(crossbuild_libs); + snprintf(crossbuild_libs + cl, sizeof(crossbuild_libs) - cl, "%s", xmp_objs); + const char* add = emit_staticlib && xmp_list ? xmp_list : ""; + if (!cross_buf_reserve(&objlist, &objlist_cap, obj_pos + strlen(add) + 1)) { + free(xmp_list); + fprintf(stderr, "Error: out of memory building the cross-compile object list.\n"); + break; + } + snprintf(objlist + obj_pos, objlist_cap - obj_pos, "%s", add); + obj_pos += strlen(add); + free(xmp_list); + } /* Clear any stale output so the FreeBSD "output exists == linked" * success signal below can't be fooled by a prior build's binary. */ diff --git a/tools/ae_internal.h b/tools/ae_internal.h index 501cdcb40..a4f20ad0a 100644 --- a/tools/ae_internal.h +++ b/tools/ae_internal.h @@ -389,6 +389,18 @@ bool ae_vendored_sqlite(const char* base, const char* tag, const char* objdir, char* link_objs, size_t link_sz); +/* contrib.xmp from the pinned libxmp source the toolchain ships: compile + * each of libxmp's sources (cached one slot apiece) and the veneer with + * `cc_cmd` for `tag`, archive libxmp with `ar_cmd` (in `objdir`, or cached + * when it is NULL), and append the veneer and the archive, quoted, to + * `link_objs`; with `obj_list`, append the objects themselves there too. + * False, having said why, on failure. */ +bool ae_vendored_xmp(const char* base, const char* tag, + const char* cc_cmd, const char* ar_cmd, const char* flags, + const char* objdir, + char* link_objs, size_t link_sz, + char** obj_list, size_t* obj_cap); + int run_cross_build(const char* c_file, const char* out_file, bool optimize, const char* extra_files, const char* ztriple, bool emit_lib, bool emit_staticlib); From 8ed403b1babef6aa372d4436fad191913d626893 Mon Sep 17 00:00:00 2001 From: paul Date: Thu, 26 Nov 2026 21:45:01 +0000 Subject: [PATCH 2/2] std.string: to_float parses to 64 bits, correctly rounded; to_f32 added Aether's `float` is 64-bit (C double), but string.to_float parsed with strtof and widened the 32-bit result, so it returned about seven significant digits dressed as a double: a, _ = string.to_float("0.1") println(string.string_from_double(a)) // 0.10000000149011612 c, _ = string.to_float("16777217") println(string.string_from_double(c)) // 16777216 to_float now parses with strtod, correctly rounded to binary64, with the syntax to_double accepted (hex constants, inf/nan spellings, the same errors). string_to_float_raw writes a double; string_get_float parses at 64 bits rather than widening a float. to_double is kept, as a call to to_float, so the two always agree; the externs string_try_double and string_get_double are kept the same way, as string_try_float and string_get_float under their old names. Each carries a TODO: delete it once nothing in the aether-lang-dev org's repos or in friends-and-family repos uses it. Not a breaking change. Every caller in this tree moves to to_float (benchmarks, contrib jq and liquid, std cbor, decimal and jsonpath, the tests and the docs), so the in-tree count of to_double callers is zero. decimal.to_double is a decimal-to-float conversion, not a parse, and keeps its name. string_to_double_raw, which nothing outside std.string used, is removed. string.to_f32(s) -> (f32, string) is the 32-bit parse: strtof, rounded once straight to binary32, returning a real f32 (C float), with past the f32 range an overflow error; externs string_to_f32_raw, string_try_f32, string_get_f32. No caller in the tree wanted 32-bit rounding; to_f32 keeps the locale-pinned strtof path (aether_c_strtof, with its msvcrt handling) reachable and tested. Tests whose expectations encoded the 32-bit parse now call to_f32: test_string_parse_hex_float and test_string_parse_float_halfway (their float-bits checks, e.g. 0x1.000001p0 -> 1.0 and the float-tie inputs), test_string_parse_inf_nan, test_string_embedded_nul, test_string_to_number_widths and tests/syntax/test_string_parse_tuple; their to_double checks become to_float checks. No golden file changed. New tests/regression/test_string_to_float_64_bit.ae, failing before the fix: to_float("0.1") equals the literal 0.1 with bits 3fb999999999999a, "16777217" reads back as 16777217, 17-significant-digit values (pi, DBL_MAX, DBL_MIN, ...) round-trip through string_from_double to the same bits, "1e39" is in range; to_f32 rounds like strtof ("0.1" -> 3fb99999a0000000 widened, "16777217" -> 16777216, "1e39" overflows); to_double equals to_float bit for bit and still rejects trailing garbage. The LSP completion list gains to_f32 and marks to_double slated for deletion; docs/api and the stdlib index regenerated; changelog fragment under changed. Co-Authored-By: Claude Opus 5.5 --- benchmarks/core/run.ae | 4 +- .../cross-language/lib/benchstats/module.ae | 8 +- contrib/jq/eval.ae | 2 +- contrib/jq/lexer.ae | 2 +- contrib/templating/liquid/module.ae | 4 +- docs/api/index.html | 7 +- docs/api/string.html | 35 +++++++-- docs/locale-independent-float-text.md | 4 +- docs/stdlib-reference.md | 11 +-- lsp/aether_lsp.c | 3 +- ...0261126T210258Z-changed-to-float-64-bit.md | 17 +++++ runtime/aether_locale_num.h | 2 +- std/cbor/module.ae | 2 +- std/decimal/module.ae | 2 +- std/jsonpath/parser.ae | 2 +- std/string/aether_string.c | 58 +++++++------- std/string/aether_string.h | 11 ++- std/string/module.ae | 52 +++++++++---- tests/regression/test_string_double_locale.ae | 14 ++-- .../test_string_double_roundtrip.ae | 2 +- tests/regression/test_string_edge_cases.ae | 4 +- tests/regression/test_string_embedded_nul.ae | 12 +-- .../test_string_from_double_reclaimed.ae | 2 +- .../test_string_from_number_widths.ae | 8 +- .../test_string_parse_float_halfway.ae | 28 +++---- .../regression/test_string_parse_hex_float.ae | 26 +++---- tests/regression/test_string_parse_inf_nan.ae | 33 ++++---- .../regression/test_string_to_float_64_bit.ae | 76 +++++++++++++++++++ .../test_string_to_number_widths.ae | 28 +++---- tests/syntax/test_string_parse_tuple.ae | 20 ++--- 30 files changed, 316 insertions(+), 163 deletions(-) create mode 100644 new_changelogs/20261126T210258Z-changed-to-float-64-bit.md create mode 100644 tests/regression/test_string_to_float_64_bit.ae diff --git a/benchmarks/core/run.ae b/benchmarks/core/run.ae index 6c81ad90d..1d76d4d3d 100644 --- a/benchmarks/core/run.ae +++ b/benchmarks/core/run.ae @@ -121,7 +121,7 @@ record_rows(t: ptr, best: ptr, out: string) { if string.starts_with(line, "row ") != 0 { parts = string.split(line, " ") if string.array_size(parts) == 4 { - v, err = string.to_double(string.array_get(parts, 2)) + v, err = string.to_float(string.array_get(parts, 2)) if err == "" { record(t, best, string.array_get(parts, 1), string.array_get(parts, 3), v) } @@ -144,7 +144,7 @@ record_phases(t: ptr, best: ptr, out: string, prefix: string) { if string.starts_with(line, "phase ") != 0 { parts = string.split(line, " ") if string.array_size(parts) >= 3 { - v, err = string.to_double(string.array_get(parts, 2)) + v, err = string.to_float(string.array_get(parts, 2)) if err == "" { record(t, best, "${prefix}${string.array_get(parts, 1)}", "ms", v) } diff --git a/benchmarks/cross-language/lib/benchstats/module.ae b/benchmarks/cross-language/lib/benchstats/module.ae index 64c857dbd..3fff8580d 100644 --- a/benchmarks/cross-language/lib/benchstats/module.ae +++ b/benchmarks/cross-language/lib/benchstats/module.ae @@ -145,7 +145,7 @@ number_after(output: string, label: string) -> float { rest = string.trim(string.substring(line, at + string.length(label), string.length(line))) words = string.split(rest, " ") if string.array_size(words) > 0 { - v, err = string.to_double(string.array_get(words, 0)) + v, err = string.to_float(string.array_get(words, 0)) if err == "" { result = v } @@ -229,11 +229,11 @@ parse_cpu_seconds(output: string, is_mac: int) -> float { w = string.array_get(words, k) if string.length(w) > 0 { if w == "user" { - u, e1 = string.to_double(prev) + u, e1 = string.to_float(prev) if e1 == "" { user = u } } if w == "sys" { - s, e2 = string.to_double(prev) + s, e2 = string.to_float(prev) if e2 == "" { sys = s } } prev = w @@ -272,7 +272,7 @@ parse_peak_mb(output: string, is_mac: int) -> float { if string.contains(line, "maximum resident set size") == 1 { words = string.split(string.trim(line), " ") if string.array_size(words) > 0 { - b, err = string.to_double(string.array_get(words, 0)) + b, err = string.to_float(string.array_get(words, 0)) if err == "" { result = b / 1048576.0 } diff --git a/contrib/jq/eval.ae b/contrib/jq/eval.ae index 2a4dc7a7e..e498145da 100644 --- a/contrib/jq/eval.ae +++ b/contrib/jq/eval.ae @@ -3365,7 +3365,7 @@ _parse_number(s: string) -> (float, string) { if ed == 0 { return 0.0, "bad exponent" } } if i != n { return 0.0, "trailing characters" } - d, err = string.to_double(s) + d, err = string.to_float(s) if err != "" { return 0.0, err } return d, "" } diff --git a/contrib/jq/lexer.ae b/contrib/jq/lexer.ae index 36bf8188a..fa44e1fbe 100644 --- a/contrib/jq/lexer.ae +++ b/contrib/jq/lexer.ae @@ -356,7 +356,7 @@ _lex_number(lx: *Lexer) { } } text = string.substring_n(_src(lx), lx.len, start, lx.pos) - d, err = string.to_double(text) + d, err = string.to_float(text) if err != "" { // Out of double range: 1e1000 overflows to infinity (which prints as // the largest double, as in jq), 1e-1000 underflows to zero. diff --git a/contrib/templating/liquid/module.ae b/contrib/templating/liquid/module.ae index d71050645..e4353c118 100644 --- a/contrib/templating/liquid/module.ae +++ b/contrib/templating/liquid/module.ae @@ -1509,7 +1509,7 @@ shortest_digits(mag: float) -> (string, int) { } } cand = string.concat(string.concat(string.concat("0.", head), "e"), string.from_int(hd)) - back, _berr = string.to_double(cand) + back, _berr = string.to_float(cand) if back == mag { // Drop trailing zeros; they carry no digits. hn = string_length(head) @@ -1571,7 +1571,7 @@ ruby_float_text(v: float) -> string { // A decimal result, printed through Float as Liquid prints it. ddecimal_out(neg: int, m: string, scale: int) -> string { - d, derr = string.to_double(dtext(neg, m, scale)) + d, derr = string.to_float(dtext(neg, m, scale)) if derr != "" { // Beyond a double's range: Ruby's to_f gives Infinity for a value // too large and zero for one too small, each with its sign. diff --git a/docs/api/index.html b/docs/api/index.html index 2f639e9b0..5e998e750 100644 --- a/docs/api/index.html +++ b/docs/api/index.html @@ -484,7 +484,7 @@

stream

string

std.string - String Module Import with: import std.string Building strings incrementally? Do NOT loop `d = "${d}${piece}"` / `string.concat(d, piece)` — each iteration re-copies the whole prefix, so the loop is O(n²) in total bytes (issue #1346).

- 101 exports + 104 exports

supervise

@@ -2818,13 +2818,15 @@

Search Results

  • to_int_rawstring
  • to_long_rawstring
  • to_float_rawstring
  • -
  • to_double_rawstring
  • +
  • to_f32_rawstring
  • try_intstring
  • get_intstring
  • try_longstring
  • get_longstring
  • try_floatstring
  • get_floatstring
  • +
  • try_f32string
  • +
  • get_f32string
  • try_doublestring
  • get_doublestring
  • to_int_radix_rawstring
  • @@ -2833,6 +2835,7 @@

    Search Results

  • to_intstring
  • to_longstring
  • to_floatstring
  • +
  • to_f32string
  • to_doublestring
  • to_int_radixstring
  • strip_prefixstring
  • diff --git a/docs/api/string.html b/docs/api/string.html index 77cbfe5a5..5d08358b3 100644 --- a/docs/api/string.html +++ b/docs/api/string.html @@ -84,13 +84,15 @@

    Exports

  • to_int_raw
  • to_long_raw
  • to_float_raw
  • -
  • to_double_raw
  • +
  • to_f32_raw
  • try_int
  • get_int
  • try_long
  • get_long
  • try_float
  • get_float
  • +
  • try_f32
  • +
  • get_f32
  • try_double
  • get_double
  • to_int_radix_raw
  • @@ -99,6 +101,7 @@

    Exports

  • to_int
  • to_long
  • to_float
  • +
  • to_f32
  • to_double
  • to_int_radix
  • strip_prefix
  • @@ -594,10 +597,11 @@

    to_long_raw extern

    to_float_raw extern

    to_float_raw(str, out_value) -> int

    str: string, out_value: ptr

    +

    out_value: a `float` (8-byte double) slot for to_float_raw, an `f32` (4-byte float) slot for to_f32_raw.

    -
    -

    to_double_raw extern

    -
    to_double_raw(str, out_value) -> int
    +
    +

    to_f32_raw extern

    +
    to_f32_raw(str, out_value) -> int

    str: string, out_value: ptr

    @@ -631,10 +635,21 @@

    get_float extern

    get_float(s) -> float

    s: string

    +
    +

    try_f32 extern

    +
    try_f32(s) -> int
    +

    s: string

    +
    +
    +

    get_f32 extern

    +
    get_f32(s) -> f32
    +

    s: string

    +

    try_double extern

    try_double(s) -> int

    s: string

    +

    TODO: delete string_try_double and string_get_double once nothing in the aether-lang-dev org's repos or in friends-and-family repos uses them; they are string_try_float and string_get_float under their old names.

    get_double extern

    @@ -673,13 +688,19 @@

    to_long fn

    to_float fn

    to_float(s) -> (float, string)

    s: string

    -

    Parse a string to a float. Returns (value, "") on success, (0.0, error) on invalid input. "inf", "infinity", "nan" and hexadecimal constants parse on every platform, as for to_double; a hex constant is rounded straight to float.

    +

    Parse a string to a float (64-bit, C double), correctly rounded to the nearest binary64 value. Returns (value, "") on success, (0.0, error) on invalid input. Leading whitespace, a sign and trailing whitespace are accepted; trailing garbage, an embedded NUL and overflow are errors. "inf", "infinity" and "nan" (any case, optionally signed) parse identically on every platform, so the "Infinity", "-Infinity" and "NaN" that from_double emits read back, and so do C99 hexadecimal constants such as "0x1.8p3", correctly rounded too. from_double's text reads back to the same bits. For a 32-bit value use to_f32.

    +
    +
    +

    to_f32 fn

    +
    to_f32(s) -> (f32, string)
    +

    s: string

    +

    Parse a string to an f32 (32-bit, C float), rounded once, straight to the nearest binary32 value as strtof does (not through a double, which can round twice). Same syntax and errors as to_float; a value past the f32 range is an overflow error. Returns (value, "") or (0.0, error).

    to_double fn

    -
    to_double(s) -> (float, string)
    +
    to_double(s)

    s: string

    -

    Parse a string to a double. Returns (value, "") on success, (0.0, error) on invalid input. "inf", "infinity" and "nan" (any case, optionally signed) parse identically on every platform, so the "Infinity", "-Infinity" and "NaN" that from_double emits read back, and so do C99 hexadecimal constants such as "0x1.8p3" (correctly rounded).

    +

    TODO: delete to_double once nothing in the aether-lang-dev org's repos or in friends-and-family repos calls it; use to_float, which it now is. Parse a string to a float: the same correctly rounded 64-bit parse as to_float, which it calls, so the two always agree.

    to_int_radix fn

    diff --git a/docs/locale-independent-float-text.md b/docs/locale-independent-float-text.md index afecf7806..b4bb76b72 100644 --- a/docs/locale-independent-float-text.md +++ b/docs/locale-independent-float-text.md @@ -39,7 +39,7 @@ Aether has two entirely separate needs, and PR #1429 accidentally straddled them | | **Machine text** | **Human text** | |---|---|---| -| Users | `string.from_double`, `string.to_double`, JSON, config files, wire protocols, `${}` interpolation | `std.number` (Phase 4 of #863) | +| Users | `string.from_double`, `string.to_float`, JSON, config files, wire protocols, `${}` interpolation | `std.number` (Phase 4 of #863) | | Correct decimal point | **always `.`** | whatever the locale says | | Correct grouping | **never** | locale-defined | | Depends on `LC_NUMERIC` | **must not** | must, via explicit locale argument | @@ -173,7 +173,7 @@ nothing worth preserving. Concretely this means: `#else` so it cannot be mistaken for the fallback we rejected. - **No opt-in flag, no legacy mode.** The old post-hoc block at `aether_string.c:847-860` is deleted outright, not gated. -- **Behaviour changes are allowed to be visible.** `string.to_double("3.14")` starts succeeding +- **Behaviour changes are allowed to be visible.** `string.to_float("3.14")` (then `to_double`) starts succeeding under `de_DE.UTF-8` where it used to fail; JSON output changes separator in those locales. Both are the fix, not a regression. Document them in the CHANGELOG as fixes, not as breaking changes. - Free rein to change the internal C signatures (`runtime/aether_runtime_types.c:98`'s `atof` → diff --git a/docs/stdlib-reference.md b/docs/stdlib-reference.md index eb1650494..d59e71ddc 100644 --- a/docs/stdlib-reference.md +++ b/docs/stdlib-reference.md @@ -85,7 +85,7 @@ header comment is the authoritative description. | `std.strarr` | Growable string array whose backing is a `string[]`, for sorting runtime-built lists. | 15 | [guide](../std/strarr/README.md) · [source](../std/strarr/module.ae) | | `std.strbuilder` | Amortised-O(1) string building. | 18 | [guide](../std/strbuilder/README.md) · [source](../std/strbuilder/module.ae) | | `std.stream` | Credit-windowed streams between actors: memory stays bounded however fast the producer is. | 11 | [guide](../std/stream/README.md) · [source](../std/stream/module.ae) | -| `std.string` | Managed strings: construction, search, slicing, case, split and join. | 101 | [full section](#strings-stdstring) | +| `std.string` | Managed strings: construction, search, slicing, case, split and join. | 104 | [full section](#strings-stdstring) | | `std.supervise` | Supervisors that restart dead actors in place, by strategy and within a restart budget. | 9 | [guide](../std/supervise/README.md) · [source](../std/supervise/module.ae) | | `std.sync` | Atomic 64-bit integer cell (load, store, add, sub, compare-and-swap) for refcounts and lock-free reclamation. | 7 | [guide](../std/sync/README.md) · [source](../std/sync/module.ae) | | `std.tar` | Streaming tar archives: a ustar writer, a ustar, pax and GNU reader. | 24 | [full section](#posix-ustar-archives-stdtar) | @@ -940,12 +940,13 @@ For a `split_once`-style operation (find the first `sep` in `s`, return the halv - `string.from_int_radix(value, radix)` → `string` - Inverse of `to_int_radix`. Render `value` in base `radix` (`[2, 36]`); empty string on invalid radix; `'-'` prefix for negatives. Pair with `pad_start` for fixed-width hex bytes. - `string.pad_start(s, total_width, pad_char)` → `string` - Prepend `pad_char` (single-byte char code, e.g. `48` for `'0'`, `32` for `' '`) until `s` reaches `total_width`. Returns a fresh copy if `s` is already long enough (no truncation). - `string.pad_end(s, total_width, pad_char)` → `string` - Append-side variant of `pad_start`. Useful for columnar text output. -- `string.to_float(s)` → `(float, string)` - Parse float -- `string.to_double(s)` → `(float, string)` - Parse double +- `string.to_float(s)` → `(float, string)` - Parse a 64-bit float (C double), correctly rounded +- `string.to_f32(s)` → `(f32, string)` - Parse a 32-bit float (C float), rounded once as `strtof` does; past the f32 range is an overflow error +- `string.to_double(s)` → `(float, string)` - The same parse as `to_float`, kept for now and slated for deletion; use `to_float` -Each returns `(value, "")` on success or `(0, "invalid ...")` on parse failure. Except for `to_int_radix` (above), they handle leading whitespace, sign, trailing whitespace; reject trailing non-whitespace. `to_float` and `to_double` also read `inf`, `infinity` and `nan` in any case and with a sign, on every platform, so `from_double`'s `Infinity`, `-Infinity` and `NaN` round-trip, and C99 hexadecimal constants such as `0x1.8p3`, correctly rounded to the result type. +Each returns `(value, "")` on success or `(0, "invalid ...")` on parse failure. Except for `to_int_radix` (above), they handle leading whitespace, sign, trailing whitespace; reject trailing non-whitespace. `to_float` and `to_f32` also read `inf`, `infinity` and `nan` in any case and with a sign, on every platform, so `from_double`'s `Infinity`, `-Infinity` and `NaN` round-trip, and C99 hexadecimal constants such as `0x1.8p3`, correctly rounded to the result type. -Raw out-parameter externs are preserved as `string_to_int_raw`, `string_to_long_raw`, `string_to_float_raw`, `string_to_double_raw` for callers who need to distinguish zero from parse failure without a tuple destructure. +Raw out-parameter externs are preserved as `string_to_int_raw`, `string_to_long_raw`, `string_to_float_raw` (a `float` slot) and `string_to_f32_raw` (an `f32` slot) for callers who need to distinguish zero from parse failure without a tuple destructure. **Memory:** - `string.retain(str)` - Increment reference count diff --git a/lsp/aether_lsp.c b/lsp/aether_lsp.c index ae07f7a02..011af7c48 100644 --- a/lsp/aether_lsp.c +++ b/lsp/aether_lsp.c @@ -368,7 +368,8 @@ void lsp_handle_completion(LSPServer* server, const char* id, const char* uri, i "{\"label\":\"string.to_int\",\"kind\":3,\"detail\":\"-> (int, error)\"}," "{\"label\":\"string.to_long\",\"kind\":3,\"detail\":\"-> (long, error)\"}," "{\"label\":\"string.to_float\",\"kind\":3,\"detail\":\"-> (float, error)\"}," - "{\"label\":\"string.to_double\",\"kind\":3,\"detail\":\"-> (double, error)\"}," + "{\"label\":\"string.to_f32\",\"kind\":3,\"detail\":\"-> (f32, error)\"}," + "{\"label\":\"string.to_double\",\"kind\":3,\"detail\":\"-> (float, error) (same as to_float; slated for deletion)\"}," /* ---- std.collections (list / map / string_list) ---- */ "{\"label\":\"list_new\",\"kind\":3,\"detail\":\"-> ptr (ArrayList)\"}," diff --git a/new_changelogs/20261126T210258Z-changed-to-float-64-bit.md b/new_changelogs/20261126T210258Z-changed-to-float-64-bit.md new file mode 100644 index 000000000..607945bb4 --- /dev/null +++ b/new_changelogs/20261126T210258Z-changed-to-float-64-bit.md @@ -0,0 +1,17 @@ +- **`string.to_float` parses to 64 bits, correctly rounded; `to_double` + stays for now as the same function, slated for deletion.** Aether's `float` + is 64-bit (C `double`), but `to_float` parsed with `strtof` and widened the + 32-bit result, so it returned about seven significant digits dressed as a + double: `to_float("0.1")` gave 0.10000000149011612 and + `to_float("16777217")` gave 16777216. It now parses with `strtod`, + correctly rounded to binary64, with the syntax `to_double` accepted + (hexadecimal constants, `inf`/`nan` spellings, the same errors), and + `from_double`'s text reads back to the same bits; `string_to_float_raw` now + writes a `double`. `to_double` (and the externs `string_try_double` / + `string_get_double`) now call the same parse; they are kept until nothing + in the aether-lang-dev org's repos or in friends-and-family repos uses + them, then deleted, so move callers to `to_float`. The extern + `string_to_double_raw` is removed. The new + `string.to_f32(s) -> (f32, string)` is the 32-bit parse: `strtof`, rounded + once, returning a real `f32`, with the f32 range's overflow an error + (externs `string_to_f32_raw`, `string_try_f32`, `string_get_f32`). diff --git a/runtime/aether_locale_num.h b/runtime/aether_locale_num.h index e5b045531..a087ec05d 100644 --- a/runtime/aether_locale_num.h +++ b/runtime/aether_locale_num.h @@ -14,7 +14,7 @@ // program starts in the "C" locale, so a standalone Aether binary is safe by // default — but an Aether library embedded in a host that has called // setlocale(LC_ALL, "") (GTK, PHP, countless C/C++ apps) inherits that host's -// locale, and then string.to_double("3.14") FAILS to parse under any +// locale, and then string.to_float("3.14") FAILS to parse under any // comma-decimal locale. Fixing that by calling setlocale ourselves is not an // option: it is process-global, it is not ours to change as a library, and // Aether runs its own threads (actors, scheduler, worker pool, HTTP accept diff --git a/std/cbor/module.ae b/std/cbor/module.ae index 5d7dfac07..42c4ca3c3 100644 --- a/std/cbor/module.ae +++ b/std/cbor/module.ae @@ -2091,7 +2091,7 @@ fn digits_plus_one(digits: string) -> string { // are `bits`. fn reads_back(digits: string, point: int, bits: long) -> bool { text = string.concat("0.", string.concat(digits, string.concat("e", string.from_int(point)))) - v, err = string.to_double(text) + v, err = string.to_float(text) return err == "" && mem.bits_of_float(v) == bits } diff --git a/std/decimal/module.ae b/std/decimal/module.ae index 83df1bbbd..892834079 100644 --- a/std/decimal/module.ae +++ b/std/decimal/module.ae @@ -816,7 +816,7 @@ to_string_fixed_bank(d: @keep ptr, places: int) -> string { // The nearest binary float. Lossy by nature; for display use to_string. to_double(d: @keep ptr) -> float { s = to_string(d) - v, _err = string.to_double(s) + v, _err = string.to_float(s) return v } diff --git a/std/jsonpath/parser.ae b/std/jsonpath/parser.ae index 5477292c1..7b4791f3a 100644 --- a/std/jsonpath/parser.ae +++ b/std/jsonpath/parser.ae @@ -1311,7 +1311,7 @@ _parse_number(p: *Parser) -> ptr { if is_float == 1 { l = model.new_literal(model.L_FLOAT) - (l as *Literal).fval = string.get_double(num_str) + (l as *Literal).fval = string.get_float(num_str) return l } diff --git a/std/string/aether_string.c b/std/string/aether_string.c index 20fb8d2a4..e0d9f361d 100644 --- a/std/string/aether_string.c +++ b/std/string/aether_string.c @@ -1576,7 +1576,7 @@ AetherString* string_from_float(double value) { } // Deterministic double-to-decimal text conversion paired with -// string_to_double_raw. Seventeen significant decimal digits are sufficient +// string_to_float_raw. Seventeen significant decimal digits are sufficient // to recover every finite IEEE-754 binary64 value exactly. This is deliberately // round-trip-safe rather than shortest-round-trip formatting. AetherString* string_from_double(double value) { @@ -1598,7 +1598,7 @@ AetherString* string_from_double(double value) { } } - // This is MACHINE text — it round-trips through string_to_double, goes + // This is MACHINE text — it round-trips through string_to_float, goes // into JSON, config files and onto sockets — so the decimal separator must // be '.' whatever locale the process is in. aether_c_snprintf_double pins // the conversion to the C locale rather than reformatting afterwards. @@ -1824,17 +1824,21 @@ int string_to_long_raw(const void* str, long long* out_value) { return 1; } -int string_to_float_raw(const void* str, float* out_value) { +// Aether's `float` is 64-bit (C double), so to_float parses with strtod, +// correctly rounded to binary64. (It once parsed with strtof and widened the +// 32-bit result: to_float("0.1") read back as 0.10000000149011612.) +int string_to_float_raw(const void* str, double* out_value) { const char* data = str_data(str); if (!str || !data[0] || !out_value) return 0; char* endptr; errno = 0; - // Locale-pinned: strtof obeys LC_NUMERIC, which would reject "3.14" - // outright under a comma-decimal locale. See aether_locale_num.h. - float val = aether_c_strtof(data, &endptr); + // Locale-pinned — the inverse of string_from_double. Without this, a host + // that has called setlocale(LC_ALL, "") to a comma-decimal locale makes + // this function reject "3.14" as unparseable. See aether_locale_num.h. + double val = aether_c_strtod(data, &endptr); - if (endptr == data || (errno == ERANGE && (val == HUGE_VALF || val == -HUGE_VALF))) { + if (endptr == data || (errno == ERANGE && (val == HUGE_VAL || val == -HUGE_VAL))) { return 0; } @@ -1844,18 +1848,20 @@ int string_to_float_raw(const void* str, float* out_value) { return 1; } -int string_to_double_raw(const void* str, double* out_value) { +// The 32-bit parse behind string.to_f32: strtof, rounded once, straight to +// binary32 (rounding through double first would land on a float tie and +// round again). +int string_to_f32_raw(const void* str, float* out_value) { const char* data = str_data(str); if (!str || !data[0] || !out_value) return 0; char* endptr; errno = 0; - // Locale-pinned — the inverse of string_from_double. Without this, a host - // that has called setlocale(LC_ALL, "") to a comma-decimal locale makes - // this function reject "3.14" as unparseable. See aether_locale_num.h. - double val = aether_c_strtod(data, &endptr); + // Locale-pinned: strtof obeys LC_NUMERIC, which would reject "3.14" + // outright under a comma-decimal locale. See aether_locale_num.h. + float val = aether_c_strtof(data, &endptr); - if (endptr == data || (errno == ERANGE && (val == HUGE_VAL || val == -HUGE_VAL))) { + if (endptr == data || (errno == ERANGE && (val == HUGE_VALF || val == -HUGE_VALF))) { return 0; } @@ -1895,23 +1901,23 @@ long long string_get_int_radix(const void* s, int radix) { long long v = 0; string_to_int_radix_raw(s, radix, &v); return v; } int string_try_float(const void* s) { - float v; return string_to_float_raw(s, &v); -} -// Returns double, not float: Aether's `float` type is 64-bit (it lowers -// to C `double`), so the extern `string_get_float -> float` expects a -// 64-bit return. Returning a 32-bit C `float` here left Aether reading -// the result register as a double → garbage (e.g. to_float("2.5") came -// back 5.3e-315). We still parse at float precision (to_float's contract; -// use to_double for full precision), then widen for the ABI. + double v; return string_to_float_raw(s, &v); +} +// Aether's `float` lowers to C `double`: parsed and returned at 64 bits. double string_get_float(const void* s) { - float v = 0.0f; string_to_float_raw(s, &v); return (double)v; + double v = 0.0; string_to_float_raw(s, &v); return v; } -int string_try_double(const void* s) { - double v; return string_to_double_raw(s, &v); +int string_try_f32(const void* s) { + float v; return string_to_f32_raw(s, &v); } -double string_get_double(const void* s) { - double v = 0.0; string_to_double_raw(s, &v); return v; +// Aether's `f32` lowers to C `float`. +float string_get_f32(const void* s) { + float v = 0.0f; string_to_f32_raw(s, &v); return v; } +// TODO: delete once nothing in the aether-lang-dev org's repos or in +// friends-and-family repos uses them. The old names of the 64-bit parse. +int string_try_double(const void* s) { return string_try_float(s); } +double string_get_double(const void* s) { return string_get_float(s); } // Printf-style string formatting AetherString* string_format(const char* fmt, ...) { diff --git a/std/string/aether_string.h b/std/string/aether_string.h index 830db4eff..b573a544b 100644 --- a/std/string/aether_string.h +++ b/std/string/aether_string.h @@ -295,7 +295,7 @@ AetherString* string_from_long(long long value); // — see the .c-side comment for the full diagnosis. AetherString* string_from_float(double value); // Lossless, deterministic double-to-decimal text conversion pairing with -// `string.to_double`. Round-trips every finite IEEE-754 binary64 value, +// `string.to_float`. Round-trips every finite IEEE-754 binary64 value, // and normalizes special values. AetherString* string_from_double(double value); @@ -319,8 +319,8 @@ AetherString* string_pad_end(const void* s, int total_width, int pad_char); // (`string.to_int`, etc.) which return `(value, error)` tuples. int string_to_int_raw(const void* str, int* out_value); int string_to_long_raw(const void* str, long long* out_value); // 64-bit slot (Windows `long` is 32-bit) -int string_to_float_raw(const void* str, float* out_value); -int string_to_double_raw(const void* str, double* out_value); +int string_to_float_raw(const void* str, double* out_value); // 64-bit: Aether `float` is C double +int string_to_f32_raw(const void* str, float* out_value); // 32-bit: Aether `f32` is C float // Base-N parse, radix in 2..36. Out-slot is `long long*` for LLP64 // safety, matching string_to_long_raw. Accepts exactly an optional '-', @@ -339,6 +339,11 @@ int string_try_long(const void* s); long long string_get_long(const void* s); // 64-bit on every platform int string_try_float(const void* s); double string_get_float(const void* s); // 64-bit: Aether `float` lowers to C double +int string_try_f32(const void* s); +float string_get_f32(const void* s); // 32-bit: Aether `f32` lowers to C float +// TODO: delete once nothing in the aether-lang-dev org's repos or in +// friends-and-family repos uses them: string_try_float / string_get_float +// under their old names, for std.string's to_double. int string_try_double(const void* s); double string_get_double(const void* s); // Base-N split-return — same shape as try_long/get_long, with a radix diff --git a/std/string/module.ae b/std/string/module.ae index 8f5d22685..02b4d11f2 100644 --- a/std/string/module.ae +++ b/std/string/module.ae @@ -34,11 +34,12 @@ exports( string_to_cstr, string_from_int, string_from_long, string_from_float, string_from_double, string_from_int_radix, string_pad_start, string_pad_end, - string_to_int_raw, string_to_long_raw, string_to_float_raw, string_to_double_raw, + string_to_int_raw, string_to_long_raw, string_to_float_raw, string_to_f32_raw, string_try_int, string_get_int, string_try_long, string_get_long, - string_try_float, string_get_float, string_try_double, string_get_double, + string_try_float, string_get_float, string_try_f32, string_get_f32, + string_try_double, string_get_double, string_to_int_radix_raw, string_try_int_radix, string_get_int_radix, - to_int, to_long, to_float, to_double, to_int_radix, + to_int, to_long, to_float, to_f32, to_double, to_int_radix, strip_prefix, copy, string_format_list, format, string_glob_match_raw, glob_match, glob_match_pathname, @@ -373,8 +374,10 @@ extern string_pad_end(s: string, total_width: int, pad_char: int) -> string @hea // Parsing — raw externs (escape hatch) extern string_to_int_raw(str: string, out_value: ptr) -> int extern string_to_long_raw(str: string, out_value: ptr) -> int +// out_value: a `float` (8-byte double) slot for to_float_raw, an `f32` +// (4-byte float) slot for to_f32_raw. extern string_to_float_raw(str: string, out_value: ptr) -> int -extern string_to_double_raw(str: string, out_value: ptr) -> int +extern string_to_f32_raw(str: string, out_value: ptr) -> int extern string_to_int_radix_raw(str: string, radix: int, out_value: ptr) -> int // Parsing — split-return helpers for the Go-style wrappers. @@ -384,6 +387,11 @@ extern string_try_long(s: string) -> int extern string_get_long(s: string) -> long extern string_try_float(s: string) -> int extern string_get_float(s: string) -> float +extern string_try_f32(s: string) -> int +extern string_get_f32(s: string) -> f32 +// TODO: delete string_try_double and string_get_double once nothing in the +// aether-lang-dev org's repos or in friends-and-family repos uses them; they +// are string_try_float and string_get_float under their old names. extern string_try_double(s: string) -> int extern string_get_double(s: string) -> float // Base-N parse split-return. The value slot is `long` (int64) because @@ -416,10 +424,15 @@ to_long(s: string) -> long! { return string_get_long(s), "" } -// Parse a string to a float. Returns (value, "") on success, -// (0.0, error) on invalid input. "inf", "infinity", "nan" and -// hexadecimal constants parse on every platform, as for to_double; a hex -// constant is rounded straight to float. +// Parse a string to a float (64-bit, C double), correctly rounded to the +// nearest binary64 value. Returns (value, "") on success, (0.0, error) on +// invalid input. Leading whitespace, a sign and trailing whitespace are +// accepted; trailing garbage, an embedded NUL and overflow are errors. +// "inf", "infinity" and "nan" (any case, optionally signed) parse +// identically on every platform, so the "Infinity", "-Infinity" and "NaN" +// that from_double emits read back, and so do C99 hexadecimal constants such +// as "0x1.8p3", correctly rounded too. from_double's text reads back to the +// same bits. For a 32-bit value use to_f32. to_float(s: string) -> { ok = string_try_float(s) if ok == 0 { @@ -428,17 +441,24 @@ to_float(s: string) -> { return string_get_float(s), "" } -// Parse a string to a double. Returns (value, "") on success, -// (0.0, error) on invalid input. "inf", "infinity" and "nan" (any case, -// optionally signed) parse identically on every platform, so the -// "Infinity", "-Infinity" and "NaN" that from_double emits read back, and -// so do C99 hexadecimal constants such as "0x1.8p3" (correctly rounded). +// TODO: delete to_double once nothing in the aether-lang-dev org's repos or +// in friends-and-family repos calls it; use to_float, which it now is. +// Parse a string to a float: the same correctly rounded 64-bit parse as +// to_float, which it calls, so the two always agree. to_double(s: string) -> { - ok = string_try_double(s) + return to_float(s) +} + +// Parse a string to an f32 (32-bit, C float), rounded once, straight to the +// nearest binary32 value as strtof does (not through a double, which can +// round twice). Same syntax and errors as to_float; a value past the f32 +// range is an overflow error. Returns (value, "") or (0.0, error). +to_f32(s: string) -> (f32, string) { + ok = string_try_f32(s) if ok == 0 { - return 0.0, "invalid double" + return 0.0 as f32, "invalid f32" } - return string_get_double(s), "" + return string_get_f32(s), "" } // Base-N parse: like `to_long` but accepts a radix in [2, 36]. diff --git a/tests/regression/test_string_double_locale.ae b/tests/regression/test_string_double_locale.ae index 9fb2df9bb..17db0c656 100644 --- a/tests/regression/test_string_double_locale.ae +++ b/tests/regression/test_string_double_locale.ae @@ -14,7 +14,7 @@ // called setlocale) does to us for real. // // The bug this pins: under a comma-decimal locale, bare strtod("3.14") stops -// at the '.', so string.to_double REJECTED valid input and every fractional +// at the '.', so string.to_float REJECTED valid input and every fractional // number in a JSON document failed to parse. // // SKIPs visibly when no comma-decimal locale is installed. To run it for real @@ -105,11 +105,11 @@ check_interp_ld(value: longdouble, expected: string, label: string) -> int { // wrong magnitude — bare strtod under a comma locale stops at the '.' and // yields 3.0 for "3.14", which an error check alone would miss. check_parse_as(text: string, expected: string, label: string) -> int { - value, err = string.to_double(text) + value, err = string.to_float(text) ok = 1 if err != "" { ok = 0 - println(" FAIL ${label}: to_double(\"${text}\") errored: ${err}") + println(" FAIL ${label}: to_float(\"${text}\") errored: ${err}") } string.free(err) @@ -265,13 +265,13 @@ main() { // Parse side — this is the half that was entirely unprotected and which // FAILED outright before the fix. - fails = fails + check_parse("3.1400000000000001", "to_double(3.14...)") - fails = fails + check_parse("0.5", "to_double(0.5)") - fails = fails + check_parse("-2.5", "to_double(-2.5)") + fails = fails + check_parse("3.1400000000000001", "to_float(3.14...)") + fails = fails + check_parse("0.5", "to_float(0.5)") + fails = fails + check_parse("-2.5", "to_float(-2.5)") // Exponent form parses to the same value but re-emits as plain digits // under %.17g, so compare against the canonical spelling rather than the // input. - fails = fails + check_parse_as("1.5e10", "15000000000", "to_double(1.5e10)") + fails = fails + check_parse_as("1.5e10", "15000000000", "to_float(1.5e10)") // JSON in both directions (RFC 8259 conformance). fails = fails + check_json_roundtrip() diff --git a/tests/regression/test_string_double_roundtrip.ae b/tests/regression/test_string_double_roundtrip.ae index 9a763854b..3e907f696 100644 --- a/tests/regression/test_string_double_roundtrip.ae +++ b/tests/regression/test_string_double_roundtrip.ae @@ -4,7 +4,7 @@ import std.string check_roundtrip(bits: long) -> int { value = mem.float_from_bits(bits) text = string.from_double(value) - parsed, err = string.to_double(text) + parsed, err = string.to_float(text) parsed_bits = mem.bits_of_float(parsed) ok = 1 diff --git a/tests/regression/test_string_edge_cases.ae b/tests/regression/test_string_edge_cases.ae index 066015090..18e404803 100644 --- a/tests/regression/test_string_edge_cases.ae +++ b/tests/regression/test_string_edge_cases.ae @@ -170,8 +170,8 @@ main() { print(" FAIL\n"); exit(1) } - print("\nTest 15: to_double on scientific notation\n") - v, e15 = string.to_double("1.5e3") + print("\nTest 15: to_float on scientific notation\n") + v, e15 = string.to_float("1.5e3") if e15 != "" { print(" FAIL: should accept 1.5e3\n"); exit(1) } diff --git a/tests/regression/test_string_embedded_nul.ae b/tests/regression/test_string_embedded_nul.ae index 458fed752..707902cfb 100644 --- a/tests/regression/test_string_embedded_nul.ae +++ b/tests/regression/test_string_embedded_nul.ae @@ -133,17 +133,17 @@ test_numbers() -> int { f = f + check(ie != "", "to_int read 1299") _l, le = string.to_long(bad) f = f + check(le != "", "to_long read 1299") - _fl, fe = string.to_float(with_nul("1.5", "7")) - f = f + check(fe != "", "to_float read 1.57") - _d, de = string.to_double(with_nul("1.5", "7")) - f = f + check(de != "", "to_double read 1.57") + _fl, fe = string.to_f32(with_nul("1.5", "7")) + f = f + check(fe != "", "to_f32 read 1.57") + _d, de = string.to_float(with_nul("1.5", "7")) + f = f + check(de != "", "to_float read 1.57") _t, te = string.to_int(with_nul("12", "")) f = f + check(te != "", "to_int read 12") // Plain text, and trailing whitespace, still parse. ok_i, oe = string.to_int(string.concat("1", "2 ")) f = f + check(oe == "" && ok_i == 12, "to_int(\"12 \")") - ok_d, ode = string.to_double(string.concat("2", ".5")) - f = f + check(ode == "" && ok_d == 2.5, "to_double(\"2.5\")") + ok_d, ode = string.to_float(string.concat("2", ".5")) + f = f + check(ode == "" && ok_d == 2.5, "to_float(\"2.5\")") return f } diff --git a/tests/regression/test_string_from_double_reclaimed.ae b/tests/regression/test_string_from_double_reclaimed.ae index 2121a1538..639f0c82e 100644 --- a/tests/regression/test_string_from_double_reclaimed.ae +++ b/tests/regression/test_string_from_double_reclaimed.ae @@ -10,7 +10,7 @@ extern exit(code: int) round_trips(x: float) -> int { text = string.from_double(x) - v, err = string.to_double(text) + v, err = string.to_float(text) if err != "" { return 0 } if v != x { return 0 } return 1 diff --git a/tests/regression/test_string_from_number_widths.ae b/tests/regression/test_string_from_number_widths.ae index 79bf963d2..a72718c29 100644 --- a/tests/regression/test_string_from_number_widths.ae +++ b/tests/regression/test_string_from_number_widths.ae @@ -90,7 +90,7 @@ main() { } println(" PASS: from_float 1.0 / 3.14 / 0.0001 / 0.0 / -2.5") - // ---- Round-trip: from_float -> to_double should be ~identity -- + // ---- Round-trip: from_float -> to_float should be ~identity -- // // The strongest cross-check: emit then parse a high-precision // double and verify it's within tolerance. Pre-fix this would @@ -102,14 +102,14 @@ main() { // round-trip tolerance is "within %g's truncation noise" rather // than "byte-exact." If we ever switch to %.17g, tighten this. s = string.from_float(3.14159265358979) - v, err = string.to_double(s) - if eq(err, "") != 1 { fail("to_double on round-trip: err=${err}") } + v, err = string.to_float(s) + if eq(err, "") != 1 { fail("to_float on round-trip: err=${err}") } diff = v - 3.14159265358979 if diff < 0.0 { diff = 0.0 - diff } if diff > 0.0001 { fail("round-trip drift: 3.14159265358979 -> '${s}' -> ${v} (diff=${diff})") } - println(" PASS: from_float -> to_double round-trips 3.14159265358979 within %g precision") + println(" PASS: from_float -> to_float round-trips 3.14159265358979 within %g precision") // ---- Round-trip: from_long -> to_long for 2^40 --------------- // diff --git a/tests/regression/test_string_parse_float_halfway.ae b/tests/regression/test_string_parse_float_halfway.ae index ab6b56156..ca76e719a 100644 --- a/tests/regression/test_string_parse_float_halfway.ae +++ b/tests/regression/test_string_parse_float_halfway.ae @@ -1,4 +1,4 @@ -// Regression (#3818): string.to_float and string.to_double read decimal text +// Regression (#3818): string.to_f32 and string.to_float read decimal text // as a correctly rounded strtof and strtod in the C locale do, whatever the // ambient locale and whatever C runtime the program is built against. // @@ -11,7 +11,7 @@ // then goes to even: "1.00000005960464477540" is above 1 + 2^-24 and must // give 1 + 2^-23, not 1; the text just under FLT_MAX + ulp/2 must give // FLT_MAX, not an overflow; the text just above 2^-150 must give the least -// subnormal, not 0. string.to_double is checked at its own ties: msvcrt.dll's +// subnormal, not 0. string.to_float is checked at its own ties: msvcrt.dll's // _strtod_l does not round them correctly. The expected bits are UCRT // strtof's and strtod's. // @@ -53,42 +53,42 @@ select_comma_locale() -> string { return "" } -// to_float's result, widened to double (exact), must have exactly the bits +// to_f32's result, widened to double (exact), must have exactly the bits // `want`. flt(s: string, want: long, where: string) -> int { - v, err = string.to_float(s) + v, err = string.to_f32(s) if err != "" || mem.bits_of_float(v) != want { got = string.from_int_radix(mem.bits_of_float(v), 16) - println(" FAIL [${where}] to_float(\"${s}\"): bits ${got} err='${err}'") + println(" FAIL [${where}] to_f32(\"${s}\"): bits ${got} err='${err}'") return 1 } return 0 } -// to_double's result must have exactly the bits `want`. +// to_float's result must have exactly the bits `want`. dbl(s: string, want: long, where: string) -> int { - v, err = string.to_double(s) + v, err = string.to_float(s) if err != "" || mem.bits_of_float(v) != want { got = string.from_int_radix(mem.bits_of_float(v), 16) - println(" FAIL [${where}] to_double(\"${s}\"): bits ${got} err='${err}'") + println(" FAIL [${where}] to_float(\"${s}\"): bits ${got} err='${err}'") return 1 } return 0 } dbl_err(s: string, where: string) -> int { - v, err = string.to_double(s) + v, err = string.to_float(s) if err == "" { - println(" FAIL [${where}] to_double(\"${s}\") should error, got ${v}") + println(" FAIL [${where}] to_float(\"${s}\") should error, got ${v}") return 1 } return 0 } flt_err(s: string, where: string) -> int { - v, err = string.to_float(s) + v, err = string.to_f32(s) if err == "" { - println(" FAIL [${where}] to_float(\"${s}\") should error, got ${v}") + println(" FAIL [${where}] to_f32(\"${s}\") should error, got ${v}") return 1 } return 0 @@ -134,7 +134,7 @@ checks(where: string) -> int { fails = fails + flt_err(".", where) fails = fails + flt_err("-", where) - // to_double the same way. msvcrt.dll's _strtod_l does not round these + // to_float the same way. msvcrt.dll's _strtod_l does not round these // correctly: 2^53 + 1 is the tie between 2^53 and 2^53 + 2, 1 + 2^-53 // the tie between 1 and 1 + 2^-52, 2^-1075 the tie between 0 and the // least subnormal; just above each, the upper one. @@ -152,7 +152,7 @@ checks(where: string) -> int { } main() { - println("=== to_float / to_double: decimal text next to a tie, C and comma locales ===") + println("=== to_f32 / to_float: decimal text next to a tie, C and comma locales ===") fails = checks("C") loc = select_comma_locale() diff --git a/tests/regression/test_string_parse_hex_float.ae b/tests/regression/test_string_parse_hex_float.ae index 6a6a9acd2..50b90d6f8 100644 --- a/tests/regression/test_string_parse_hex_float.ae +++ b/tests/regression/test_string_parse_hex_float.ae @@ -1,7 +1,7 @@ -// Regression (#2508): string.to_double and string.to_float read C99 +// Regression (#2508): string.to_float and string.to_f32 read C99 // hexadecimal floating constants ("0x1.8p3") the same on every platform, // correctly rounded to the result type. glibc and UCRT parse them, but on -// Windows with msvcrt (MINGW64) to_double("0x1p3") failed: _strtod_l read the +// Windows with msvcrt (MINGW64) to_float("0x1p3") failed: _strtod_l read the // "0" and stopped, leaving "x1p3" as trailing garbage. import std.mem import std.string @@ -10,46 +10,46 @@ extern exit(code: int) // The double's bits must be exactly `want`. dbl(s: string, want: long) -> int { - v, err = string.to_double(s) + v, err = string.to_float(s) if err != "" || mem.bits_of_float(v) != want { got = string.from_int_radix(mem.bits_of_float(v), 16) - println(" FAIL to_double(\"${s}\"): bits ${got} err='${err}'") + println(" FAIL to_float(\"${s}\"): bits ${got} err='${err}'") return 1 } return 0 } -// to_float's result, widened to double, must have exactly the bits `want`. +// to_f32's result, widened to double, must have exactly the bits `want`. flt(s: string, want: long) -> int { - v, err = string.to_float(s) + v, err = string.to_f32(s) if err != "" || mem.bits_of_float(v) != want { got = string.from_int_radix(mem.bits_of_float(v), 16) - println(" FAIL to_float(\"${s}\"): bits ${got} err='${err}'") + println(" FAIL to_f32(\"${s}\"): bits ${got} err='${err}'") return 1 } return 0 } dbl_err(s: string) -> int { - v, err = string.to_double(s) + v, err = string.to_float(s) if err == "" { - println(" FAIL to_double(\"${s}\") should error, got ${v}") + println(" FAIL to_float(\"${s}\") should error, got ${v}") return 1 } return 0 } flt_err(s: string) -> int { - v, err = string.to_float(s) + v, err = string.to_f32(s) if err == "" { - println(" FAIL to_float(\"${s}\") should error, got ${v}") + println(" FAIL to_f32(\"${s}\") should error, got ${v}") return 1 } return 0 } main() { - println("=== to_double / to_float: hexadecimal floating constants ===") + println("=== to_float / to_f32: hexadecimal floating constants ===") fails = 0 // The forms: either case, sign, optional point and exponent. @@ -103,7 +103,7 @@ main() { fails = fails + dbl_err("0x1q") fails = fails + dbl_err("0x 1") - // to_float rounds the exact value to float directly. 1 + 2^-24 + 2^-60 + // to_f32 rounds the exact value to float directly. 1 + 2^-24 + 2^-60 // is just above a float tie: through double it would first become the // tie 1 + 2^-24 and then round to even, 1.0. fails = fails + flt("0x1p3", 0x4020000000000000) diff --git a/tests/regression/test_string_parse_inf_nan.ae b/tests/regression/test_string_parse_inf_nan.ae index 61320a749..bbd35f35b 100644 --- a/tests/regression/test_string_parse_inf_nan.ae +++ b/tests/regression/test_string_parse_inf_nan.ae @@ -1,8 +1,9 @@ -// Regression (#2472): string.to_double and string.to_float read the C99 +// Regression (#2472): string.to_float and string.to_f32 read the C99 // "inf" / "infinity" / "nan" spellings, in any case and with a sign, on // every platform. string.from_double writes "Infinity", "-Infinity" and // "NaN", and on Windows (msvcrt's _strtod_l) none of them read back: -// to_double(from_double(1.0 / 0.0)) failed with "invalid double". +// to_double(from_double(1.0 / 0.0)), now to_float, failed with "invalid +// double". import std.mem import std.string @@ -31,14 +32,14 @@ matches(v: float, want: int) -> int { accept(s: string, want: int) -> int { fails = 0 - d, derr = string.to_double(s) + d, derr = string.to_float(s) if derr != "" || matches(d, want) != 1 { - println(" FAIL to_double(\"${s}\"): ${d} err='${derr}'") + println(" FAIL to_float(\"${s}\"): ${d} err='${derr}'") fails = fails + 1 } - f, ferr = string.to_float(s) + f, ferr = string.to_f32(s) if ferr != "" || matches(f, want) != 1 { - println(" FAIL to_float(\"${s}\"): ${f} err='${ferr}'") + println(" FAIL to_f32(\"${s}\"): ${f} err='${ferr}'") fails = fails + 1 } return fails @@ -46,14 +47,14 @@ accept(s: string, want: int) -> int { reject(s: string) -> int { fails = 0 - _d, derr = string.to_double(s) + _d, derr = string.to_float(s) if derr == "" { - println(" FAIL to_double(\"${s}\") should error") + println(" FAIL to_float(\"${s}\") should error") fails = fails + 1 } - _f, ferr = string.to_float(s) + _f, ferr = string.to_f32(s) if ferr == "" { - println(" FAIL to_float(\"${s}\") should error") + println(" FAIL to_f32(\"${s}\") should error") fails = fails + 1 } return fails @@ -61,7 +62,7 @@ reject(s: string) -> int { roundtrip(bits: long, want: int) -> int { text = string.from_double(mem.float_from_bits(bits)) - v, err = string.to_double(text) + v, err = string.to_float(text) if err != "" || matches(v, want) != 1 { println(" FAIL round-trip of \"${text}\": ${v} err='${err}'") return 1 @@ -70,7 +71,7 @@ roundtrip(bits: long, want: int) -> int { } main() { - println("=== to_double / to_float: inf and nan spellings ===") + println("=== to_float / to_f32: inf and nan spellings ===") fails = 0 // from_double's own output reads back. @@ -117,10 +118,10 @@ main() { fails = fails + reject("i nf") // Ordinary numbers are untouched. - one, oerr = string.to_double("1.5") - if oerr != "" || one != 1.5 { println(" FAIL to_double(\"1.5\")"); fails = fails + 1 } - big, berr = string.to_double("1e999") - if berr == "" { println(" FAIL to_double(\"1e999\") overflow accepted as ${big}"); fails = fails + 1 } + one, oerr = string.to_float("1.5") + if oerr != "" || one != 1.5 { println(" FAIL to_float(\"1.5\")"); fails = fails + 1 } + big, berr = string.to_float("1e999") + if berr == "" { println(" FAIL to_float(\"1e999\") overflow accepted as ${big}"); fails = fails + 1 } if fails > 0 { println("FAIL: ${fails} checks failed") diff --git a/tests/regression/test_string_to_float_64_bit.ae b/tests/regression/test_string_to_float_64_bit.ae new file mode 100644 index 000000000..0536da4ef --- /dev/null +++ b/tests/regression/test_string_to_float_64_bit.ae @@ -0,0 +1,76 @@ +// Regression: string.to_float parses to Aether's `float`, which is 64-bit +// (C double), correctly rounded. It used to parse with strtof and widen the +// 32-bit result, so to_float("0.1") gave 0.10000000149011612 and +// to_float("16777217") gave 16777216: about seven significant digits dressed +// as a double. string.to_f32 is the 32-bit parse, rounded once, as strtof. +import std.mem +import std.string + +extern exit(code: int) + +check(ok: int, what: string) -> int { + if ok == 0 { + println(" FAIL ${what}") + return 1 + } + return 0 +} + +main() { + println("=== to_float is a 64-bit parse; to_f32 the 32-bit one ===") + fails = 0 + + a, ea = string.to_float("0.1") + fails = fails + check(ea == "" && a == 0.1, "to_float(\"0.1\") == 0.1, got ${string.from_double(a)}") + fails = fails + check(mem.bits_of_float(a) == 0x3fb999999999999a, "to_float(\"0.1\") bits") + + b, eb = string.to_float("16777217") + fails = fails + check(eb == "" && b == 16777217.0, "to_float(\"16777217\"), got ${string.from_double(b)}") + + // 17 significant digits: the text from_double writes reads back to the + // same bits, for values that need all of them. + texts = ["0.10000000000000001", "3.1415926535897931", "1.7976931348623157e+308", + "2.2250738585072014e-308", "9007199254740993", "0.30000000000000004"] + for t in texts { + v, ev = string.to_float(t) + back = string.from_double(v) + w, ew = string.to_float(back) + fails = fails + check(ev == "" && ew == "" && mem.bits_of_float(v) == mem.bits_of_float(w), + "round-trip ${t} -> ${back}") + } + // 2^53 + 1 is not a double; it rounds to even, 2^53. + n, en = string.to_float("9007199254740993") + fails = fails + check(en == "" && n == 9007199254740992.0, "to_float(2^53 + 1) rounds to even") + pi, ep = string.to_float("3.1415926535897931") + fails = fails + check(ep == "" && mem.bits_of_float(pi) == 0x400921fb54442d18, "to_float(pi) bits") + + // to_f32 rounds like strtof: once, straight to binary32. + f, ef = string.to_f32("0.1") + fails = fails + check(ef == "" && mem.bits_of_float(f as float) == 0x3fb99999a0000000, "to_f32(\"0.1\") bits") + fails = fails + check(f == 0.1 as f32, "to_f32(\"0.1\") == 0.1 as f32") + g, eg = string.to_f32("16777217") + fails = fails + check(eg == "" && (g as float) == 16777216.0, "to_f32(\"16777217\") rounds to 16777216") + h, eh = string.to_f32("1e39") + fails = fails + check(eh != "", "to_f32(\"1e39\") overflows binary32, got ${h as float}") + k, ek = string.to_float("1e39") + fails = fails + check(ek == "" && k == 1e39, "to_float(\"1e39\") is in range") + _x, ex = string.to_f32("abc") + fails = fails + check(ex != "", "to_f32(\"abc\") errors") + + // to_double stays for now, slated for deletion: the same parse as to_float. + same = ["0.1", "16777217", "3.1415926535897931", "0x1.8p3", "-Infinity", "1e39", " 2.5 "] + for t in same { + d, ed = string.to_double(t) + v, ev = string.to_float(t) + fails = fails + check(ed == "" && ev == "" && mem.bits_of_float(d) == mem.bits_of_float(v), + "to_double(\"${t}\") == to_float") + } + _d, edbad = string.to_double("1.5x") + fails = fails + check(edbad != "", "to_double(\"1.5x\") errors") + + if fails > 0 { + println("FAIL: ${fails} checks failed") + exit(1) + } + println("All PASS") +} diff --git a/tests/regression/test_string_to_number_widths.ae b/tests/regression/test_string_to_number_widths.ae index 052836fb1..1390d3c61 100644 --- a/tests/regression/test_string_to_number_widths.ae +++ b/tests/regression/test_string_to_number_widths.ae @@ -8,10 +8,12 @@ // 2. to_float returned garbage (e.g. 5.3e-315 for "2.5") — the C // string_get_float returned a 32-bit `float` while Aether's `float` // is 64-bit (lowers to C double), so the result register was read -// as a double. Fixed by returning `(double)v` from string_get_float. +// as a double. Fixed by returning a double from string_get_float +// (which now parses at 64 bits too); to_f32 is the 32-bit parse and +// returns a real C float, Aether's `f32`. // -// to_int and to_double were already correct; covered here so the whole -// family is pinned. +// to_int and the 64-bit parse were already correct; covered here so the +// whole family is pinned. import std.string @@ -42,17 +44,17 @@ main() { if i1 != 1000000 { fail("to_int wrong: ${i1}") } println(" PASS: to_int") - // to_float: must not read a 32-bit float as a 64-bit double. - f1, fe = string.to_float("2.5") - if fe != "" { fail("to_float err: ${fe}") } - if f1 != 2.5 { fail("to_float garbage for 2.5: ${f1}") } - println(" PASS: to_float") + // to_f32: must not read a 32-bit float as a 64-bit double. + f1, fe = string.to_f32("2.5") + if fe != "" { fail("to_f32 err: ${fe}") } + if f1 != 2.5 { fail("to_f32 garbage for 2.5: ${f1}") } + println(" PASS: to_f32") - // to_double: full-precision path. - d1, de = string.to_double("2.5") - if de != "" { fail("to_double err: ${de}") } - if d1 != 2.5 { fail("to_double wrong: ${d1}") } - println(" PASS: to_double") + // to_float: full-precision path. + d1, de = string.to_float("2.5") + if de != "" { fail("to_float err: ${de}") } + if d1 != 2.5 { fail("to_float wrong: ${d1}") } + println(" PASS: to_float") // Error paths still report invalid input. _, be = string.to_long("not-a-number") diff --git a/tests/syntax/test_string_parse_tuple.ae b/tests/syntax/test_string_parse_tuple.ae index 9cecf925c..52281c31a 100644 --- a/tests/syntax/test_string_parse_tuple.ae +++ b/tests/syntax/test_string_parse_tuple.ae @@ -1,4 +1,4 @@ -// Test: string.to_int/to_long/to_float/to_double Go-style wrappers. +// Test: string.to_int/to_long/to_f32/to_float Go-style wrappers. // Replaces the out-parameter pattern (`string_to_int(s, &out)`) with // native tuple destructuring. @@ -41,24 +41,24 @@ main() { exit(1) } - // to_float success - f, ferr = string.to_float("3.14") + // to_f32 success + f, ferr = string.to_f32("3.14") if ferr != "" { - println("FAIL: to_float(3.14) errored: ${ferr}") + println("FAIL: to_f32(3.14) errored: ${ferr}") exit(1) } - // to_float failure - _, ferr2 = string.to_float("not a number") + // to_f32 failure + _, ferr2 = string.to_f32("not a number") if ferr2 == "" { - println("FAIL: to_float should error on bad input") + println("FAIL: to_f32 should error on bad input") exit(1) } - // to_double success - d, derr = string.to_double("2.71828") + // to_float success + d, derr = string.to_float("2.71828") if derr != "" { - println("FAIL: to_double errored: ${derr}") + println("FAIL: to_float errored: ${derr}") exit(1) }