Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

test: verify rendered loop controls and document frame playback

Soohong Kimb2781a06f789
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d0fac8..d63f5fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased
+- Upgraded sound generation and game-pack audio integration to version 2: removed file-level crossfades and boundary tapers in favor of complete normalized exports with integer frame `playback` coordinates, removed legacy loop seconds and taper metadata, and bundled standalone runtime helper `sprite-gen-audio-v2.mjs` for Web Audio loop preparation.
+
- Added `sprite-gen sound` CLI and game-pack audio integration for ElevenLabs SFX/BGM generation, featuring SQLite request deduplication, cosine loop crossfading, multi-pass FFmpeg loudnorm/alimiter normalization, dual Opus/AAC encoding, and Web Audio loop boundary metadata.
- Added `--cycle once` nonloop motion support with automatic selection for `death`, `fall`, `land`, `cast`, `hurt_hold`, and `transform`, rejection on cyclic states, no seam gate or wrap correction, and a terminal stability gate searching the whole clip for the first stable terminal window ($K = \max(4, \lceil\text{fps} \times 0.2\rceil)$) after action departure (ending at window end, discarding later recovery or shaking), with conservative candidate end pose geometric screening (alpha >= 8 body boxes; height <= 80% of initial for `death`/`fall`, changed geometry for other states) and retained cut edge contact validation (ignoring discarded tail).
diff --git a/docs/game-pack.md b/docs/game-pack.md
index 9fd28fd..b6a6f69 100644
--- a/docs/game-pack.md
+++ b/docs/game-pack.md
@@ -13,7 +13,7 @@ sprite-gen game-pack --request game.json --out-dir game-assets
* `--request <path>`: Path to the request JSON file. Paths within the request resolve relative to the request file directory.
* `--out-dir <path>`: Target output directory. Must be a new directory path.
* `--page-size <int>`: Maximum page dimension in pixels. Defaults to `4096`. Lower bound is `1`; cannot exceed `4096`.
-* `--max-bytes <int>`: Total encoded byte budget for all output files (PNG, WebP, JSON, OGG, and M4A combined). Defaults to `50000000` (50 MB). Lower bound is `1`; configurable downward only.
+* `--max-bytes <int>`: Total encoded byte budget for all output files (PNG, WebP, JSON, JS modules, OGG, and M4A combined). Defaults to `50000000` (50 MB). Lower bound is `1`; configurable downward only.
Invalid arguments, missing files, frame dimension overflows, or budget violations exit with a non-zero status.
@@ -92,7 +92,7 @@ Source policies and row anchors are preserved by the asset adapter. Optional ent
* Every frame receives 1-pixel edge extrusion on each side (+2 pixels to width and height). Maximum frame dimension plus 2 pixels must fit within `--page-size`.
* Trimming and rotation are disabled (`trimmed: false`, `rotated: false`).
* Each page has PNG and lossless WebP copies (preserving exact RGB and alpha).
-* Total byte size across all PNG, WebP, JSON, OGG, and M4A outputs must not exceed `--max-bytes`.
+* Total byte size across all PNG, WebP, JSON, JS modules, OGG, and M4A outputs must not exceed `--max-bytes`.
* Layout packing bins assets and frames using stable keys.
## Output manifest
@@ -168,13 +168,70 @@ Game packs support optional bundled audio declared in pack recipes via `request.
```json
{
"audio": [
- { "id": "hit", "source": "../hit/sound.json" }
+ { "id": "music", "source": "../music/sound.json" }
]
}
```
### Integration Rules
-- **Packaging and Manifest**: Pack assembly copies format files flat into the output directory as `audio-<id>.ogg` (Opus, 160 kbps) and `audio-<id>.m4a` (AAC, 192 kbps). The pack manifest preserves audio properties and format file metadata under `manifest.audio[id]`. Refer to [`sound.md`](sound.md) for generation options and full manifest metadata schemas.
-- **Event Linkage**: String matching between audio `event` identifiers and animation `events[].name` provides runtime linkage for consumer engines to match strings. The pack does not enforce that every audio event has an associated animation (such as UI sounds or background music), and does not promise automatic runtime code.
-- **Pack Limits**: Bundled audio file sizes count against the global 50,000,000-byte pack limit. Audio-free pack builds remain byte-for-byte unchanged.
-- **Runtime Playback**: Web Audio uses `loopStart` (`0`) and `loopEnd` (`processed PCM duration`) metadata to exclude padding. HTML audio (such as `<audio loop>`) is not guaranteed gapless.
+- **Packaging and Manifest**: Pack assembly copies format files flat into the output directory as `audio-<id>.ogg` (Opus, 160 kbps) and `audio-<id>.m4a` (AAC, 192 kbps). Output `manifest.audio[id]` contains:
+ - `event`: Safe string event identifier matching animation event names.
+ - `audio_kind`: `"sfx"` or `"bgm"`.
+ - `loop`: Boolean looping flag.
+ - `duration_seconds`: Final prepared playback duration `(end_frame - start_frame - overlap_frames) / sample_rate`.
+ - `target_lufs`: Target integrated loudness.
+ - `playback`: Integer coordinate object (`version`, `sample_rate`, `start_frame`, `end_frame`, `overlap_frames`) preserved exactly from source `sound.json`.
+ - `files`: Format dictionary for `ogg` and `m4a` containing relative paths (`audio-<id>.ogg`, `audio-<id>.m4a`), `sha256`, decoded `duration_seconds`, `lufs`, and `true_peak_dbfs` (`encode_passes` and `pcm_peak_limit_dbtp` exist only in `sound.json` and are stripped on load).
+ - `player`: Runtime helper descriptor:
+ ```json
+ {
+ "path": "sprite-gen-audio-v2.mjs",
+ "sha256": "<actual file hash>",
+ "export": "prepareAudioBuffer"
+ }
+ ```
+ The `player.sha256` value is the SHA-256 digest computed from the exact shipped bytes of the bundled module.
+- **Runtime Helper**: Pack generation emits a single copy of `sprite-gen-audio-v2.mjs` into the pack root. The helper is self-contained with no external imports or dependencies. The canonical buffer preparation logic resides strictly in this helper; consumers must not duplicate blending logic.
+- **Event Linkage**: String matching between audio `event` identifiers and animation `events[].name` provides runtime linkage for consumer engines. The pack does not require an animation for every audio asset (such as background music or UI sound effects) and emits no runtime game glue code.
+- **Pack Limits**: All output files (PNG, WebP, JSON, JS modules, OGG, and M4A) count toward `--max-bytes` (default 50,000,000 bytes). Packs containing no audio remain byte-for-byte unchanged.
+- **Web Audio Playback Contract**: Conforms to [W3C Web Audio decodeAudioData](https://www.w3.org/TR/webaudio-1.0/#dom-baseaudiocontext-decodeaudiodata) and [W3C Web Audio looping](https://www.w3.org/TR/webaudio-1.0/#looping).
+ - Never play raw exported loop files with only `source.loop = true`; raw files are encoded audio containing complete pre-overlap sources and codec padding. HTML `<audio loop>` cannot guarantee gapless playback.
+ - Decode once via `AudioContext.decodeAudioData`, prepare once via `prepareAudioBuffer` or `createAudioSource`, and reuse prepared buffers.
+ - The runtime helper configures `loopStart = 0` and `loopEnd = prepared.duration` on the prepared `AudioBufferSourceNode`.
+
+### Web Audio Playback Example
+
+```javascript
+// Playback must be initiated by a user gesture
+button.addEventListener('click', async () => {
+ const audioContext = new AudioContext();
+ await audioContext.resume();
+
+ // Load pack manifest
+ const packURL = new URL('game-pack.json', import.meta.url);
+ const packResponse = await fetch(packURL);
+ const pack = await packResponse.json();
+
+ // Inspect audio asset and import bundled runtime helper
+ const audio = pack.audio.music;
+ const helperURL = new URL(audio.player.path, packURL).href;
+ const { createAudioSource } = await import(helperURL);
+
+ // Caller selects supported format (e.g. m4a or ogg)
+ const formatKey = 'm4a';
+ const audioFile = audio.files[formatKey];
+ const audioFileURL = new URL(audioFile.path, packURL);
+
+ // Fetch and decode full source encoded audio file
+ const fileResponse = await fetch(audioFileURL);
+ const arrayBuffer = await fileResponse.arrayBuffer();
+ const decoded = await audioContext.decodeAudioData(arrayBuffer);
+
+ // Create configured, unstarted AudioBufferSourceNode
+ const sourceNode = createAudioSource(audioContext, decoded, audio);
+ sourceNode.connect(audioContext.destination);
+
+ // Start playback
+ sourceNode.start();
+});
+```
diff --git a/docs/sound.md b/docs/sound.md
index e70cf55..434f043 100644
--- a/docs/sound.md
+++ b/docs/sound.md
@@ -35,50 +35,99 @@ Raw paid audio is stored in SQLite keyed by provider parameter digest. Tuning `-
## Audio DSP, Looping, and Quality Gates
-1. **Cosine Looping**: Blends tail and head with complementary cosine crossfade, subtracting overlap from provider length (default `min(0.25, requested_duration/8)`, under half source duration; 20s BGM yields ~19.75s). Cosine tail/head overlap is followed by a 5ms cosine taper to zero at both outer boundaries to suppress codec priming discontinuities; duration is not shortened further.
-2. **Normalization**: Two-pass [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm) targets -2 dBTP with repeating loop context. At most three per-format encode/measure passes correct codec reconstruction overshoot using measured gain and a tighter oversampled [FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter) (192kHz, auto-gain off, latency compensated); all passes are offline and never trigger provider retries.
-3. **Quality Gates**: Output formats must decode to target +/-1 LU and true peak <=-1 dBTP. Silence or unmeasurable audio fails. Numeric checks do not judge musical beat alignment.
-4. **Export Formats**: Outputs 48kHz stereo Opus in OGG (`sound.ogg`, `libopus`, 160 kbps) and AAC in M4A (`sound.m4a`, `aac`, 192 kbps).
-5. **Playback**: Web Audio uses `loopStart` (`0`) and `loopEnd` (`processed PCM duration`) on decoded `AudioBuffer` to exclude padding; HTML audio (such as `<audio loop>`) is not guaranteed gapless.
-
-## Manifest Schema and Pack Integration
-
-Outputs `sound.json` (v1, `kind="sprite-gen-sound"`): `event`, `audio_kind`, `loop`, `duration_seconds`, `target_lufs`, `codec_taper_seconds` (0.005 for loops, 0 for nonloops), `loop_start_seconds` (0), `loop_end_seconds` (processed PCM duration), and `files` (`ogg` and `m4a` entries with `path`, decoded `duration_seconds`, `lufs`, `true_peak_dbfs` [true peak dBTP], `sha256`, `encode_passes`, `pcm_peak_limit_dbtp`).
-
-Game pack recipes reference audio via `request.audio = [{"id": "hit", "source": "../hit/sound.json"}]`:
-- Files copy flat as `audio-<id>.ogg` and `audio-<id>.m4a`; `manifest.audio[id]` preserves properties and metadata.
-- Consumers match `event` strings against animation `events[].name` (packs require no animation for UI/music and generate no runtime code).
-- Audio sizes count toward the 50,000,000-byte pack limit; audio-free packages remain unchanged.
+1. **Export and Normalization**: Provider audio decodes to 48kHz stereo PCM. Normalization uses two-pass [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm) targeting -2 dBTP with repeating loop context. Up to three per-format offline encode/measure passes correct codec reconstruction overshoot using measured gain and tighter oversampled [FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter) (192kHz, auto-gain off, latency compensated) without triggering provider retries.
+2. **Export Formats**: Outputs complete normalized audio in 48kHz stereo Opus in OGG (`sound.ogg`, `libopus`, 160 kbps) and AAC in M4A (`sound.m4a`, `aac`, 192 kbps). Export files remove all pre-encode crossfades, loop splices, and 5ms boundary zero-tapers; the complete normalized source is preserved intact in encoded audio.
+3. **Quality Gates**: Output formats must decode to the integrated loudness target within +/-1 LU and true peak <= -1 dBTP. Silence or unmeasurable audio fails. Numeric checks do not judge musical beat alignment.
+4. **Looping and Playback Quality**: Crossfading is deferred to runtime preparation. Because playback overlap blending can alter loudness, applications must validate prepared and rendered audio output. No claim is made that all signals are perceptually seamless or beat aligned.
+5. **Boundary Continuity Verification**: Quality checks evaluate the wrap delta by subtracting original adjacent samples across the prepared loop splice. Artificial control discontinuities must fail; there is no absolute near-zero endpoint sample criterion. Tests verify numeric waveforms rather than subjective listening.
+
+## Manifest Schema and Coordinates
+
+Outputs `sound.json` (version 2, `kind="sprite-gen-sound"`, `recipe.processing_version=2`). Existing output directories generated with prior recipe versions are rejected; specify a new `--out-dir`. Unchanged provider cache entries are reused offline without API keys or network requests. Provider APIs, caching, and retry behaviors remain unchanged.
+
+### Manifest Properties
+
+- `event`: Safe string identifier (1..128 characters).
+- `audio_kind`: `"sfx"` or `"bgm"`.
+- `loop`: Boolean looping flag.
+- `duration_seconds`: Final playback duration in seconds, derived as `(end_frame - start_frame - overlap_frames) / sample_rate` (for example, `(144000 - 12000) / 48000 = 2.75` s).
+- `target_lufs`: Target integrated loudness in LUFS (`-36..-9`).
+- `playback`: Integer coordinate object governing client-side preparation:
+ ```json
+ {
+ "version": 2,
+ "sample_rate": 48000,
+ "start_frame": 0,
+ "end_frame": 144000,
+ "overlap_frames": 12000
+ }
+ ```
+ - Coordinates refer to the complete exported pre-overlap PCM source at `sample_rate` (48000 Hz, independent of provider container sample rate) over the half-open interval `[start_frame, end_frame)`.
+ - Let `N = end_frame - start_frame` and `M = overlap_frames`.
+ - For non-looping audio (`loop: false`), `M = 0`.
+ - For looping audio (`loop: true`), `2 <= M < N / 2`.
+ - Manifest `duration_seconds` is `(N - M) / sample_rate`.
+ - The CLI `--crossfade` parameter (seconds) is converted to integer frame count `M`, defaulting to `min(0.25, requested_duration / 8)`.
+- `files`: Format dictionary for `ogg` and `m4a` containing `path`, decoded `duration_seconds` (full decoded file duration, which may include codec priming/tail padding), `lufs`, `true_peak_dbfs`, `sha256`, `encode_passes`, and `pcm_peak_limit_dbtp`.
+- **Removed Fields**: `codec_taper_seconds`, `loop_start_seconds`, `loop_end_seconds`, and `crossfade_seconds` are removed from output manifest metadata (the recipe still accepts `--crossfade` in seconds).
+
+## Client Playback Helper: sprite-gen-audio-v2.mjs
+
+Loop blending and buffer trimming are executed in the browser via the standalone ES module `sprite-gen-audio-v2.mjs` (owned by the engine under `sprite_gen/audio`, bundled in wheels and emitted into game packs). The helper has no external imports or dependencies. The canonical algorithm resides solely in this module and must not be duplicated into consumer application code.
+
+### Export Signatures
+
+- `prepareAudioBuffer(decoded, playback) => AudioBuffer`:
+ - Maps playback coordinates to decoded sample rate `r` (`decoded.sampleRate`):
+ - `first = Math.round(start_frame * r / sample_rate)`
+ - `N' = Math.round(N * r / sample_rate)`
+ - `L' = Math.round((N - M) * r / sample_rate)`
+ - `M' = N' - L'`
+ - `last = first + N'`
+ - Rounding uses standard JavaScript `Math.round` (positive ties round upward toward `+Infinity`). Coordinates are not clamped to `decoded.length`; truncated inputs throw an error.
+ - Constructs output of length `L'` by slicing `source[first + M' : last - M']` and blending tail `M'` with head `M'` using complementary cosine weights `0.5 - 0.5 * Math.cos(Math.PI * i / (M' - 1))`.
+ - For non-looping audio (`M = 0`), trims the buffer to `[first : last]` with length `L' = N'`.
+ - The input `AudioBuffer` is not modified.
+ - Employs an internal `WeakMap` cache per module instance. Calling with the same input buffer and playback metadata returns the previously prepared buffer. Passing an already prepared buffer with identical metadata returns itself; passing altered metadata on an already prepared buffer throws. Applications should import the same module URL once, retain prepared buffers, and avoid copying prepared PCM back into raw inputs.
+- `createAudioSource(context, decoded, audio) => AudioBufferSourceNode`:
+ - Calls `prepareAudioBuffer(decoded, audio.playback)`.
+ - Instantiates an unstarted `AudioBufferSourceNode`. Sets `source.buffer = prepared`, `source.loop = audio.loop`, `source.loopStart = 0`, and `source.loopEnd = prepared.duration`.
+ - The decoded buffer sample rate should match the audio context rate. Decode once, prepare once, and reuse the prepared buffer for repeated playback nodes.
+ - Never play raw exported loop files with only `loop = true` or HTML `<audio loop>`; raw files are encoded audio containing full pre-overlap sources and codec padding.
## Examples
```bash
-sprite-gen sound --kind sfx --prompt "laser" --duration 0.8 --event laser:shot --out-dir ./dist/laser
-sprite-gen sound --kind bgm --prompt "synth cave" --duration 20.0 --event cave:bgm --out-dir ./dist/cave
+sprite-gen sound --kind sfx --prompt "laser shot" --duration 0.8 --event laser:shot --out-dir ./dist/laser
+sprite-gen sound --kind bgm --prompt "synth cave" --duration 20.0 --event cave:bgm --crossfade 0.25 --out-dir ./dist/cave
```
-### Manifest Audio Fragment (Partial)
+### Manifest Audio Fragment (`sound.json`, Partial)
+
```json
{
- "audio": {
- "hit": {
- "event": "hit",
- "audio_kind": "sfx",
- "loop": false,
- "duration_seconds": 1.25,
- "target_lufs": -18.0,
- "loop_start_seconds": 0.0,
- "loop_end_seconds": 1.25,
- "files": {
- "ogg": { "path": "audio-hit.ogg" },
- "m4a": { "path": "audio-hit.m4a" }
- }
- }
+ "kind": "sprite-gen-sound",
+ "version": 2,
+ "event": "cave:bgm",
+ "audio_kind": "bgm",
+ "loop": true,
+ "duration_seconds": 19.75,
+ "target_lufs": -20.0,
+ "playback": {
+ "version": 2,
+ "sample_rate": 48000,
+ "start_frame": 0,
+ "end_frame": 960000,
+ "overlap_frames": 12000
+ },
+ "files": {
+ "ogg": { "path": "sound.ogg" },
+ "m4a": { "path": "sound.m4a" }
}
}
```
-## References (Checked 2026-10-13)
+## References
- [ElevenLabs SFX](https://elevenlabs.io/docs/api-reference/text-to-sound-effects/convert)
- [ElevenLabs Music](https://elevenlabs.io/docs/api-reference/music/compose)
- [ElevenLabs 429 Errors](https://elevenlabs.io/docs/help-center/technical/api-error-code-429)
@@ -87,3 +136,5 @@ sprite-gen sound --kind bgm --prompt "synth cave" --duration 20.0 --event cave:b
- [ElevenLabs Subscription](https://elevenlabs.io/docs/api-reference/user/subscription/get)
- [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm)
- [FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter)
+- [W3C Web Audio decodeAudioData](https://www.w3.org/TR/webaudio-1.0/#dom-baseaudiocontext-decodeaudiodata)
+- [W3C Web Audio looping](https://www.w3.org/TR/webaudio-1.0/#looping)
diff --git a/sprite_gen/audio/manifest.py b/sprite_gen/audio/manifest.py
index d850796..a3aef5f 100644
--- a/sprite_gen/audio/manifest.py
+++ b/sprite_gen/audio/manifest.py
@@ -32,7 +32,7 @@ def load(path, max_bytes):
raise ValueError('invalid audio kind or loop flag')
frames = playback.validate(value.get('playback'), value['loop'])
duration = playback.duration(frames)
- if value.get('duration_seconds') != duration:
+ if _number(value.get('duration_seconds'), 'duration', 0, 601) != duration:
raise ValueError('audio duration must be derived from playback frames')
result = {'event': event_name(value.get('event')), 'audio_kind': value['audio_kind'], 'loop': value['loop'],
'duration_seconds': duration, 'target_lufs': _number(value.get('target_lufs'), 'target LUFS', -36, -9),
@@ -56,7 +56,7 @@ def load(path, max_bytes):
if hashlib.sha256(data).hexdigest() != file.get('sha256'):
raise ValueError('audio file digest does not match its manifest')
record = {'path': name, 'sha256': file['sha256'],
- 'duration_seconds': _number(file.get('duration_seconds'), 'file duration', frames['end_frame']/frames['sample_rate']-2/frames['sample_rate'], 602),
+ 'duration_seconds': _number(file.get('duration_seconds'), 'file duration', frames['end_frame']/frames['sample_rate'], 602),
'lufs': _number(file.get('lufs'), 'LUFS', -70, 0),
'true_peak_dbfs': _number(file.get('true_peak_dbfs'), 'true peak', -100, -1)}
if abs(record['lufs'] - result['target_lufs']) > 1:
diff --git a/sprite_gen/audio/processing.py b/sprite_gen/audio/processing.py
index 7bf402e..478fe75 100644
--- a/sprite_gen/audio/processing.py
+++ b/sprite_gen/audio/processing.py
@@ -111,7 +111,7 @@ def export(source: Path, out_dir: Path, *, target_lufs, loop, crossfade):
for attempt in range(3):
_ffmpeg([*_pcm_args(), '-map_metadata', '-1', *codec, str(path)], encoded_samples.astype('<f4').tobytes())
decoded = decode(path)
- if len(decoded) < len(samples) - 2:
+ if len(decoded) < len(samples):
raise ValueError(f'{fmt} truncated the audio')
interval = decoded[:len(samples)] # AAC may retain a final partial codec frame.
measured = measure(np.tile(interval, (3, 1)) if loop else interval, target_lufs)
diff --git a/tests/audio/render_playback.mjs b/tests/audio/render_playback.mjs
index a014a97..510b0bb 100644
--- a/tests/audio/render_playback.mjs
+++ b/tests/audio/render_playback.mjs
@@ -24,11 +24,12 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) {
const check = (ok, message) => { if (!ok) throw new Error(message); };
// Non-zero origin and a frame count whose independent rounding differs.
const meta = { version: 2, sample_rate: 48000, start_frame: 13,
- end_frame: 144014, overlap_frames: 12001 };
+ end_frame: 144019, overlap_frames: 12010 };
const first = Math.round(meta.start_frame * rate / 48000);
const n = Math.round((meta.end_frame-meta.start_frame)*rate/48000);
const length = Math.round((meta.end_frame-meta.start_frame-meta.overlap_frames)*rate/48000);
const count = n-length;
+ if (rate===44100) check(n-Math.round(meta.overlap_frames*rate/48000)!==length, 'rounding counterexample missing');
const input = new AudioBuffer({ sampleRate: rate, length: first+n, numberOfChannels: 2 });
for (let c=0;c<2;c++) {
const x=input.getChannelData(c);
@@ -52,7 +53,7 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) {
check(Math.abs((control[0]-control.at(-1))-expected)>.12, 'broken negative control');
}
let rejected=false;
- try { prepareAudioBuffer(out, { ...meta, overlap_frames: 12002 }); } catch { rejected=true; }
+ try { prepareAudioBuffer(out, { ...meta, overlap_frames: 12011 }); } catch { rejected=true; }
check(rejected, 'changed metadata reused prepared audio');
const ctx=new OfflineAudioContext(2, length*3, rate);
const source=createAudioSource(ctx,input,{loop:true,playback:meta});
@@ -64,7 +65,30 @@ for (const [name, engine] of Object.entries({ chromium, webkit })) {
maxError=Math.max(maxError,Math.abs(rendered.getChannelData(c)[i]-out.getChannelData(c)[i%length]));
}
check(maxError<1e-7, 'rendered looping differs from prepared buffer');
- return { length, count, added_wrap_error:0, added_join_error:0, control_detected:true, render_error:maxError };
+ const corrupted = new AudioBuffer({ sampleRate:rate, length, numberOfChannels:2 });
+ for(let c=0;c<2;c++) {
+ corrupted.copyToChannel(out.getChannelData(c),c);
+ corrupted.getChannelData(c)[0]+=.125;
+ }
+ const controlContext=new OfflineAudioContext(2,length*3,rate);
+ const controlSource=controlContext.createBufferSource();
+ controlSource.buffer=corrupted; controlSource.loop=true;
+ controlSource.loopStart=0; controlSource.loopEnd=corrupted.duration;
+ controlSource.connect(controlContext.destination); controlSource.start();
+ const controlRender=await controlContext.startRendering();
+ let controlError=0, controls=0;
+ for(let c=0;c<2;c++) {
+ const x=input.getChannelData(c), r=controlRender.getChannelData(c);
+ const baseline=x[first+count]-x[first+count-1];
+ for(let lap=1;lap<3;lap++) {
+ const at=lap*length, error=Math.abs((r[at]-r[at-1])-baseline);
+ controlError=Math.max(controlError,error);
+ if(error>.12) controls++;
+ }
+ }
+ check(controls===4, 'rendered discontinuity control escaped detection');
+ return { length, count, added_wrap_error:0, added_join_error:0,
+ controls_detected:controls, control_added_wrap_error:controlError, render_error:maxError };
}, { code: `data:text/javascript;base64,${moduleBytes.toString('base64')}`, rate });
reports.push({ browser:name, browser_version:browser.version(), rate, synthetic });
for (const item of cases) {
diff --git a/tests/audio/test_sound.py b/tests/audio/test_sound.py
index 07b7935..ab83a35 100644
--- a/tests/audio/test_sound.py
+++ b/tests/audio/test_sound.py
@@ -129,6 +129,9 @@ def test_short_effect_and_loop_encoded_playback(tmp_path, monkeypatch, kind, dur
'end_frame': round(duration*48000), 'overlap_frames': 12000 if loop else 0}
assert result['duration_seconds'] == (meta['end_frame']-meta['overlap_frames'])/48000
assert 'loop_end_seconds' not in result and 'codec_taper_seconds' not in result
+ for file in result['files'].values():
+ assert file['duration_seconds'] >= duration
+ assert len(processing.decode(tmp_path/'out'/file['path'])) >= meta['end_frame']
def test_preflight_does_not_claim_and_cached_source_works_without_key(tmp_path, monkeypatch):