Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: preserve stereo soundtrack channels during offline production (#9397)

[._.]/ Adam Eivya11596e994c3
diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.md
index 69992479fd..4f0c32895d 100644
--- a/docs/CODE_ANIMATION_PACKAGES.md
+++ b/docs/CODE_ANIMATION_PACKAGES.md
@@ -205,7 +205,7 @@ of total synthesis work. Event durations must fit the film. Preview plays the
persisted WAV used by final muxing; a live Web Audio clock is never captured.
Portable `file` audio is normalized to this same grid (trimmed or padded, without
-looping). `POST /api/code-animation/projects/:id/sound-assets` accepts an explicit
+looping), preserving stereo channels. `POST /api/code-animation/projects/:id/sound-assets` accepts an explicit
`revisionId`, `source` (`upload` or `library`) and existing audio `filename`
basename. It copies validated asset bytes into a new immutable package candidate;
there are no host-path inputs. The portable package limits still apply (2 MiB
diff --git a/server/services/codeAnimation/projectFiles.js b/server/services/codeAnimation/projectFiles.js
index 3f2e73f28c..b4a27c15de 100644
--- a/server/services/codeAnimation/projectFiles.js
+++ b/server/services/codeAnimation/projectFiles.js
@@ -157,7 +157,7 @@ export async function readRunArtifact(projectId, runId, name, sha256) {
const handle = await open(join(dir, name), constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
try {
const info = await handle.stat();
- if (!info.isFile() || info.size > 44 + 180 * 48000 * 2) throw unsafe();
+ if (!info.isFile() || info.size > 44 + 180 * 48000 * 2 * 2) throw unsafe();
const bytes = await handle.readFile();
if (createHash('sha256').update(bytes).digest('hex') !== sha256) throw unsafe();
return bytes;
diff --git a/server/services/codeAnimation/sound.db.test.js b/server/services/codeAnimation/sound.db.test.js
index 58f06f5fdb..646696c8f5 100644
--- a/server/services/codeAnimation/sound.db.test.js
+++ b/server/services/codeAnimation/sound.db.test.js
@@ -23,6 +23,7 @@ import { errorMiddleware } from '../../lib/errorHandler.js';
import { request } from '../../lib/testHelper.js';
import { PATHS } from '../../lib/paths.js';
import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
+import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';
import { soundTimeline, synthesizeSoundtrack } from '../../lib/codeAnimationSound.js';
import { evaluateVerdict } from './evidence.js';
import { sampleFilm, renderViaMediaQueue } from './stageRender.js';
@@ -114,7 +115,10 @@ describe.skipIf(!ready)('Revision-bound sound public workflows', () => {
const wav = synthesizeSoundtrack(soundTimeline(revision.manifest));
for (const source of ['upload', 'library']) {
const root = source === 'upload' ? PATHS.uploads : PATHS.music;
- await mkdir(root, { recursive: true }); await writeFile(join(root, 'example.wav'), wav);
+ const left = new Float32Array(96000);
+ for (let i = 0; i < left.length; i++) left[i] = wav.readInt16LE(44 + i * 2) / 32768;
+ const antiPhase = pcmToWavBuffer([left, Float32Array.from(left, sample => -sample)], { sampleRate: 48000 });
+ await mkdir(root, { recursive: true }); await writeFile(join(root, 'example.wav'), antiPhase);
const response = await post(`/projects/${project.id}/sound-assets`, { revisionId: revision.id, source, filename: 'example.wav' });
expect(response.status).toBe(201);
const exported = (await get(`/projects/${project.id}/revisions/${response.body.revision.id}/package`)).body;
@@ -122,7 +126,8 @@ describe.skipIf(!ready)('Revision-bound sound public workflows', () => {
// Once staged, the original is irrelevant to offline production.
await writeFile(join(root, 'example.wav'), 'replaced');
const run = await terminal(project.id, () => post(`/projects/${project.id}/stage-runs`, {}));
- expect(run.data.soundtrack).toMatchObject({ kind: 'file', measured: { durationMs: 2000, frames: 96000 } });
+ expect(run.data.soundtrack).toMatchObject({ kind: 'file', measured: { durationMs: 2000, frames: 96000, channels: 2 } });
+ expect(run.data.soundtrack.measured.rms).toBeGreaterThan(0.01);
}
expect((await post(`/projects/${project.id}/sound-assets`, { revisionId: revision.id, source: 'upload', filename: '/private/example.wav' })).status).toBe(400);
});
diff --git a/server/services/codeAnimation/sound.js b/server/services/codeAnimation/sound.js
index 5e5d13cfda..361d22309d 100644
--- a/server/services/codeAnimation/sound.js
+++ b/server/services/codeAnimation/sound.js
@@ -19,15 +19,15 @@ const exec = promisify(execFile);
const fail = (message, code = 'CODE_ANIMATION_SOUND_UNVERIFIED') => new ServerError(message, { status: 409, code });
const DEMUXERS = { '.wav': 'wav', '.mp3': 'mp3', '.m4a': 'mov', '.ogg': 'ogg', '.flac': 'flac', '.aac': 'aac' };
-async function decode(path, timeline, signal, { demuxer, pad = false } = {}) {
+async function decode(path, timeline, signal, { demuxer, pad = false, channels = 1 } = {}) {
const bin = await findFfmpeg();
if (!bin) throw fail('ffmpeg is required to measure and produce a soundtrack');
signal.throwIfAborted();
const { stdout } = await exec(bin, ['-v', 'error', '-nostdin', '-protocol_whitelist', 'file,pipe',
...(demuxer ? ['-f', demuxer] : []), '-i', path, '-map', '0:a:0',
...(pad ? ['-af', 'apad'] : []), '-t', String(timeline.samples / timeline.sampleRate + (pad ? 0 : 0.1)),
- '-ar', String(timeline.sampleRate), '-ac', '1', '-f', 's16le', 'pipe:1'],
- { encoding: 'buffer', maxBuffer: (timeline.samples + timeline.sampleRate) * 2, timeout: 30000, signal });
+ '-ar', String(timeline.sampleRate), '-ac', String(channels), '-f', 's16le', 'pipe:1'],
+ { encoding: 'buffer', maxBuffer: (timeline.samples + timeline.sampleRate) * 2 * channels, timeout: 30000, signal });
signal.throwIfAborted();
return stdout;
}
@@ -51,7 +51,8 @@ export async function produceSoundtrack({ projectId, runId, revision, signal, re
throw fail('Authored sound has no supported offline timeline or staged audio file; the film was not declared silent.', 'CODE_ANIMATION_SOUND_UNSUPPORTED');
}
signal.throwIfAborted();
- await reserve(44 + timeline.samples * 2);
+ const channels = audio.kind === 'file' ? 2 : 1;
+ await reserve(44 + timeline.samples * 2 * channels);
let wav;
if (audio.kind === 'procedural') wav = synthesizeSoundtrack(timeline);
else {
@@ -59,10 +60,12 @@ export async function produceSoundtrack({ projectId, runId, revision, signal, re
if (!demuxer) throw fail('Unsupported staged audio format', 'CODE_ANIMATION_SOUND_UNSUPPORTED');
// Revision bytes have just been integrity checked and snapshotted; only a
// portable asset inside that copy is decoded, never a host path from a request.
- const pcm = await decode(join(PATHS.data, revision.staged, audio.path), timeline, signal, { demuxer, pad: true });
- if (pcm.length !== timeline.samples * 2) throw fail('Staged audio could not fill the film sample grid');
- const samples = new Float32Array(timeline.samples);
- for (let i = 0; i < samples.length; i += 1) samples[i] = pcm.readInt16LE(i * 2) / 32768;
+ const pcm = await decode(join(PATHS.data, revision.staged, audio.path), timeline, signal, { demuxer, pad: true, channels });
+ if (pcm.length !== timeline.samples * 2 * channels) throw fail('Staged audio could not fill the film sample grid');
+ const samples = Array.from({ length: channels }, () => new Float32Array(timeline.samples));
+ for (let i = 0; i < timeline.samples; i += 1) {
+ for (let channel = 0; channel < channels; channel += 1) samples[channel][i] = pcm.readInt16LE((i * channels + channel) * 2) / 32768;
+ }
wav = pcmToWavBuffer(samples, { sampleRate: CODE_ANIMATION_SAMPLE_RATE });
}
signal.throwIfAborted();
@@ -103,8 +106,9 @@ export async function muxSoundtrack({ projectId, revision, soundtrack, result, s
const duration = Number(stream?.duration);
const expected = timeline.samples / timeline.sampleRate;
if (!stream || !Number.isFinite(duration) || Math.abs(duration - expected) > 0.06) throw fail('Muxed audio stream duration did not match the film');
- const decoded = await decode(videoPath, timeline, signal);
- if (Math.abs(decoded.length / 2 / timeline.sampleRate - expected) > 0.06) throw fail('Decoded mux duration did not match the film');
+ const channels = soundtrack.measured.channels;
+ const decoded = await decode(videoPath, timeline, signal, { channels });
+ if (Math.abs(decoded.length / 2 / channels / timeline.sampleRate - expected) > 0.06) throw fail('Decoded mux duration did not match the film');
const events = measureSoundEvents(decoded, timeline);
const reference = measureSoundEvents(bytes.subarray(44), timeline);
if (events.some((event, index) => event.firstSample === null || Math.abs(event.firstSeconds - reference[index].firstSeconds) > 0.02)) {
@@ -119,7 +123,7 @@ export async function muxSoundtrack({ projectId, revision, soundtrack, result, s
signal.throwIfAborted();
const videoHash = videoDigest.digest('hex');
return { version: 1, videoHash, evidenceHash: soundHash(canonicalStringify({ packageHash: revision.packageHash, audioHash: artifact.sha256, videoHash, decodedHash: soundHash(decoded) })), revisionId: revision.id, packageHash: revision.packageHash, audioHash: soundHash(bytes),
- timelineHash: timeline.hash, stream, decodedSamples: decoded.length / 2, decodedDurationSeconds: decoded.length / 2 / timeline.sampleRate,
+ timelineHash: timeline.hash, stream, decodedSamples: decoded.length / 2 / channels, decodedChannels: channels, decodedDurationSeconds: decoded.length / 2 / channels / timeline.sampleRate,
decodedHash: soundHash(decoded), peak, events, verified: ['audio-stream', 'audio-duration', ...(events.length ? ['audio-event-placement'] : [])],
unverified: soundtrack.unverified };
}
diff --git a/server/services/codeAnimation/stages.realBrowser.db.test.js b/server/services/codeAnimation/stages.realBrowser.db.test.js
index 39c043e725..2337268d62 100644
--- a/server/services/codeAnimation/stages.realBrowser.db.test.js
+++ b/server/services/codeAnimation/stages.realBrowser.db.test.js
@@ -147,7 +147,11 @@ describe.skipIf(!dbReady || !chrome || !ffmpeg || !ffprobe)('Production stages w
for (const source of ['upload', 'library']) {
const root = source === 'upload' ? PATHS.uploads : PATHS.music;
await mkdir(root, { recursive: true });
- await writeFile(join(root, 'example.wav'), wav);
+ const { pcmToWavBuffer } = await import('../../lib/chiptuneRender.js');
+ const left = new Float32Array(96000);
+ for (let i = 0; i < left.length; i++) left[i] = wav.readInt16LE(44 + i * 2) / 32768;
+ const stereo = pcmToWavBuffer([left, Float32Array.from(left, sample => -sample)], { sampleRate: 48000 });
+ await writeFile(join(root, 'example.wav'), stereo);
const staged = await stageProductionSoundAsset(projectId, { revisionId: data.currentRevisionId, source, filename: 'example.wav' });
await writeFile(join(root, 'example.wav'), 'replaced');
const next = await startProductionStageRun(projectId, { revisionId: staged.revision.id }, {
@@ -156,6 +160,8 @@ describe.skipIf(!dbReady || !chrome || !ffmpeg || !ffprobe)('Production stages w
expect(await next.done).toBe('completed');
const saved = (await getProductionHistory(projectId, { limit: 1, offset: 0 })).items[0].data;
expect(saved.soundtrack.kind).toBe('file');
+ expect(saved.soundtrack.measured.channels).toBe(2);
+ expect(saved.output.audioEvidence.decodedChannels).toBe(2);
expect(saved.output.audioEvidence.peak).toBeGreaterThan(0.1);
expect(saved.output.audioEvidence.decodedDurationSeconds).toBeCloseTo(2, 1);
expect(saved.output.audioEvidence.packageHash).toBe(staged.revision.packageHash);