diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index fa31301b..c022f7f1 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -127,6 +127,9 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile + - name: Verify bundled record MP3 transcode + run: pnpm --filter @snowluma/protocol test:native-audio + # Always builds the WebUI flavor — no separate "core-only" artifact. - name: Build project env: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d31e3e3b..f18332b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,6 +45,9 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile + - name: Verify bundled record MP3 transcode + run: pnpm --filter @snowluma/protocol test:native-audio + # Always builds the WebUI flavor — no separate "core-only" artifact. - name: Build project env: diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 56bd9ad6..43bd4902 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -91,6 +91,7 @@ }, "scripts": { "test": "vitest run", + "test:native-audio": "vitest run tests/highway/audio-transcode-native.test.ts", "bench": "vitest bench --run", "typecheck": "tsc --noEmit" }, diff --git a/packages/protocol/src/highway/ffmpeg-addon.ts b/packages/protocol/src/highway/ffmpeg-addon.ts index 52de8d3a..0edf14a2 100644 --- a/packages/protocol/src/highway/ffmpeg-addon.ts +++ b/packages/protocol/src/highway/ffmpeg-addon.ts @@ -21,12 +21,20 @@ interface FFmpegNativeAddon { getDuration(filePath: string): Promise; convertToNTSilkTct(inputPath: string, outputPath: string): Promise; decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>; - decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>; + decodeAudioToFmt( + filePath: string, + outputPath: string, + format: string, + ): Promise<{ result: boolean; channels: number; sampleRate: number; format: string }>; } let cachedAddon: FFmpegNativeAddon | null = null; let cachedLoadError: string | null = null; +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + function addonFileName(): string { return `ffmpegAddon.${process.platform}.${process.arch}.node`; } @@ -79,7 +87,7 @@ export function getFFmpegAddon(): FFmpegNativeAddon { cachedAddon = mod.exports as unknown as FFmpegNativeAddon; return cachedAddon; } catch (error) { - cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`; + cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${errorMessage(error)}`; throw new Error(cachedLoadError); } } @@ -155,8 +163,8 @@ export function defaultPttTempDir(): string { // ── audio transcode (get_record out_format, #165) ── // The addon is a custom ffmpeg build that bundles a SILK decoder, so it can -// transcode a QQ voice (SILK/AMR) into a normal container in one convertFile -// call — mirroring NapCat's FFmpegService.convertAudioFmt. +// transcode a QQ voice (SILK/AMR) into a normal container in one +// decodeAudioToFmt call — mirroring NapCat's FFmpegService.convertAudioFmt. /** Output formats accepted by `out_format` (mirrors NapCat's allowlist). */ export const AUDIO_OUT_FORMATS = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'] as const; @@ -166,7 +174,7 @@ export function isAudioOutFormat(s: string): s is AudioOutFormat { } /** Minimal addon surface the transcode needs — lets tests inject a fake. */ -type AudioConvertAddon = Pick; +type AudioConvertAddon = Pick; /** Default ceiling on the transcoded output read into memory for base64. SILK→ * WAV/FLAC is a decompressing direction, so cap it even though real voices are @@ -195,21 +203,40 @@ export async function convertAudioBytes( const id = crypto.randomBytes(8).toString('hex'); const inPath = path.join(dir, `${id}.in`); const outPath = path.join(dir, `${id}.${format}`); + let outcome: PromiseSettledResult<{ base64: string; size: number }>; try { await fs.promises.writeFile(inPath, bytes); - const res = await addon.convertFile(inPath, outPath, format); - if (!res?.success || !fs.existsSync(outPath)) throw new Error('audio conversion failed'); + await addon.decodeAudioToFmt(inPath, outPath, format); + if (!fs.existsSync(outPath)) throw new Error('audio conversion failed: no output file'); // Bound the output before reading it into memory (decompressing direction). const stat = await fs.promises.stat(outPath); if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`); const out = await fs.promises.readFile(outPath); - return { base64: out.toString('base64'), size: out.length }; - } finally { - // Await cleanup so no temp file lingers past the call (the bytes are - // already in memory by now). allSettled → a missing file never throws. - await Promise.allSettled([ - fs.promises.rm(inPath, { force: true }), - fs.promises.rm(outPath, { force: true }), - ]); + outcome = { status: 'fulfilled', value: { base64: out.toString('base64'), size: out.length } }; + } catch (reason) { + outcome = { status: 'rejected', reason }; } + + // `force` makes missing files harmless. Any remaining rejection is a real + // permission/I/O failure and must stay observable instead of leaking voice + // data silently. Preserve the conversion error too when both phases fail. + const cleanupResults = await Promise.allSettled([ + fs.promises.rm(inPath, { force: true }), + fs.promises.rm(outPath, { force: true }), + ]); + const cleanupErrors = cleanupResults + .filter((result): result is PromiseRejectedResult => result.status === 'rejected') + .map((result) => result.reason); + if (cleanupErrors.length > 0) { + const cleanupMessage = cleanupErrors.map(errorMessage).join('; '); + if (outcome.status === 'rejected') { + throw new AggregateError( + [outcome.reason, ...cleanupErrors], + `audio conversion failed: ${errorMessage(outcome.reason)}; temporary audio file cleanup failed: ${cleanupMessage}`, + ); + } + throw new AggregateError(cleanupErrors, `temporary audio file cleanup failed: ${cleanupMessage}`); + } + if (outcome.status === 'rejected') throw outcome.reason; + return outcome.value; } diff --git a/packages/protocol/tests/highway/audio-transcode-native.test.ts b/packages/protocol/tests/highway/audio-transcode-native.test.ts new file mode 100644 index 00000000..345e44a8 --- /dev/null +++ b/packages/protocol/tests/highway/audio-transcode-native.test.ts @@ -0,0 +1,89 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'; +import os from 'os'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon'; + +interface NativeAudioAddon { + convertToNTSilkTct(inputFile: string, outputFile: string): Promise; + decodeAudioToFmt( + inputFile: string, + outputFile: string, + format: string, + ): Promise<{ result: boolean; sampleRate: number; channels: number; format: string }>; + getDuration(filePath: string): Promise; +} + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +function makeMonoWav(sampleRate = 24_000, durationSeconds = 1): Buffer { + const samples = sampleRate * durationSeconds; + const bytes = Buffer.alloc(44 + samples * 2); + bytes.write('RIFF', 0); + bytes.writeUInt32LE(36 + samples * 2, 4); + bytes.write('WAVE', 8); + bytes.write('fmt ', 12); + bytes.writeUInt32LE(16, 16); + bytes.writeUInt16LE(1, 20); + bytes.writeUInt16LE(1, 22); + bytes.writeUInt32LE(sampleRate, 24); + bytes.writeUInt32LE(sampleRate * 2, 28); + bytes.writeUInt16LE(2, 32); + bytes.writeUInt16LE(16, 34); + bytes.write('data', 36); + bytes.writeUInt32LE(samples * 2, 40); + for (let i = 0; i < samples; i += 1) { + bytes.writeInt16LE(Math.round(Math.sin(2 * Math.PI * 440 * i / sampleRate) * 12_000), 44 + i * 2); + } + return bytes; +} + +function loadBundledAddon(): NativeAudioAddon { + const addonPath = path.resolve( + __dirname, + `../../../runtime/native/ffmpeg/ffmpegAddon.${process.platform}.${process.arch}.node`, + ); + const mod = { exports: {} as Record }; + process.dlopen(mod, addonPath); + return mod.exports as unknown as NativeAudioAddon; +} + +function hasMp3Signature(bytes: Buffer): boolean { + const hasId3Tag = bytes.length >= 3 && bytes.subarray(0, 3).toString('ascii') === 'ID3'; + const hasFrameSync = bytes.length >= 2 && bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0; + return hasId3Tag || hasFrameSync; +} + +const isReleaseTarget = (process.platform === 'win32' && process.arch === 'x64') + || (process.platform === 'linux' && (process.arch === 'x64' || process.arch === 'arm64')); +const describeBundledAddon = isReleaseTarget + ? describe + : describe.skip; + +describeBundledAddon('bundled ffmpeg addon', () => { + let tmpDir: string; + beforeAll(() => { + tmpDir = mkdtempSync(path.join(os.tmpdir(), 'sl-native-audio-test-')); + }); + afterAll(() => rmSync(tmpDir, { recursive: true, force: true })); + + it('converts a mono QQ-style SILK record to a decodable MP3 through the public transcode seam', async () => { + const addon = loadBundledAddon(); + const wavPath = path.join(tmpDir, 'mono-input.wav'); + const silkPath = path.join(tmpDir, 'mono-input.ntsilk'); + writeFileSync(wavPath, makeMonoWav()); + await addon.convertToNTSilkTct(wavPath, silkPath); + + const result = await convertAudioBytes(readFileSync(silkPath), 'mp3', { addon, tmpDir }); + const mp3 = Buffer.from(result.base64, 'base64'); + const outputPath = path.join(tmpDir, 'mono-output.mp3'); + writeFileSync(outputPath, mp3); + + expect(result.size).toBe(mp3.length); + expect(hasMp3Signature(mp3)).toBe(true); + const duration = await addon.getDuration(outputPath); + expect(duration).toBeGreaterThan(0.9); + expect(duration).toBeLessThan(1.2); + }); +}); diff --git a/packages/protocol/tests/highway/audio-transcode.test.ts b/packages/protocol/tests/highway/audio-transcode.test.ts index 0fd975e6..072ca04e 100644 --- a/packages/protocol/tests/highway/audio-transcode.test.ts +++ b/packages/protocol/tests/highway/audio-transcode.test.ts @@ -1,21 +1,22 @@ -import { afterAll, describe, expect, it } from 'vitest'; -import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs'; +import { afterAll, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, promises as fsPromises, readdirSync, rmSync, writeFileSync } from 'fs'; import os from 'os'; import path from 'path'; import { AUDIO_OUT_FORMATS, convertAudioBytes, isAudioOutFormat } from '@snowluma/protocol/highway/ffmpeg-addon'; -// convertAudioBytes is the pure (#165) transcode seam: write input → addon -// convertFile → read output as base64 → always clean up temp files. The native -// addon is file-based and can't run in CI, so a fake addon stands in. +// convertAudioBytes is the pure (#165) transcode seam: write input → the +// addon's dedicated audio transcoder → read output as base64 → always clean up +// temp files. Unit tests inject a fake; audio-transcode-native.test.ts covers +// each bundled release-platform addon in the build matrices. const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'sl-audio-test-')); afterAll(() => rmSync(tmpDir, { recursive: true, force: true })); /** Fake addon: writes deterministic bytes to the output path and reports ok. */ const fakeOk = { - convertFile: async (_in: string, out: string, _fmt: string) => { + decodeAudioToFmt: async (_in: string, out: string, format: string) => { writeFileSync(out, Buffer.from('WAVDATA')); // stand-in converted payload - return { success: true }; + return { result: true, sampleRate: 24_000, channels: 1, format }; }, }; @@ -38,14 +39,21 @@ describe('convertAudioBytes', () => { it('rejects an unsupported format before touching the addon', async () => { let called = false; - const spy = { convertFile: async () => { called = true; return { success: true }; } }; + const spy = { + decodeAudioToFmt: async (_in: string, _out: string, format: string) => { + called = true; + return { result: true, sampleRate: 24_000, channels: 1, format }; + }, + }; await expect(convertAudioBytes(new Uint8Array([1]), 'opus', { addon: spy, tmpDir })).rejects.toThrow(/unsupported out_format/); expect(called).toBe(false); }); - it('throws and cleans up when the addon reports failure', async () => { - const fakeFail = { convertFile: async () => ({ success: false }) }; - await expect(convertAudioBytes(new Uint8Array([9]), 'mp3', { addon: fakeFail, tmpDir })).rejects.toThrow(/conversion failed/); + it('propagates a native conversion rejection and cleans up', async () => { + const fakeFail = { + decodeAudioToFmt: async () => { throw new Error('native conversion failed'); }, + }; + await expect(convertAudioBytes(new Uint8Array([9]), 'mp3', { addon: fakeFail, tmpDir })).rejects.toThrow(/native conversion failed/); // no leftover temp files for this run const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.mp3') || n.endsWith('.in')); expect(leftover).toEqual([]); @@ -64,4 +72,29 @@ describe('convertAudioBytes', () => { const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.flac') || n.endsWith('.in')); expect(leftover).toEqual([]); }); + + it('surfaces temporary-file cleanup failures', async () => { + const rmSpy = vi.spyOn(fsPromises, 'rm').mockRejectedValue(new Error('cleanup denied')); + try { + await expect( + convertAudioBytes(new Uint8Array([6]), 'wav', { addon: fakeOk, tmpDir }), + ).rejects.toThrow(/temporary audio file cleanup failed/); + } finally { + rmSpy.mockRestore(); + } + }); + + it('reports both the conversion and cleanup causes when both fail', async () => { + const nativeFailure = { + decodeAudioToFmt: async () => { throw new Error('native conversion failed'); }, + }; + const rmSpy = vi.spyOn(fsPromises, 'rm').mockRejectedValue(new Error('cleanup denied')); + try { + await expect( + convertAudioBytes(new Uint8Array([7]), 'mp3', { addon: nativeFailure, tmpDir }), + ).rejects.toThrow(/native conversion failed.*cleanup denied/); + } finally { + rmSpy.mockRestore(); + } + }); });