diff --git a/packages/protocol/src/highway/ffmpeg-addon.ts b/packages/protocol/src/highway/ffmpeg-addon.ts index 0edf14a2..249df52e 100644 --- a/packages/protocol/src/highway/ffmpeg-addon.ts +++ b/packages/protocol/src/highway/ffmpeg-addon.ts @@ -4,7 +4,10 @@ import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; +import { createLogger } from '@snowluma/common/logger'; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const log = createLogger('Highway.Audio'); export interface FFmpegVideoInfo { width: number; @@ -180,6 +183,25 @@ type AudioConvertAddon = Pick; * WAV/FLAC is a decompressing direction, so cap it even though real voices are * tiny. Generous; overridable via deps. */ const DEFAULT_MAX_AUDIO_OUTPUT = 256 * 1024 * 1024; // 256 MiB +const SILK_V3_SIGNATURE = Buffer.from('#!SILK_V3', 'ascii'); + +/** + * QQ AI voices use the same SILK payload as ordinary QQ voices but may carry + * a 0x03 container marker. The bundled decoder accepts the ordinary 0x02 + * marker, so normalize this exact, observed container variant at the shared + * transcode boundary. Copy before rewriting to preserve caller-owned bytes. + */ +function normalizeQqAiSilkContainer(bytes: Uint8Array): Uint8Array { + if (bytes.length < SILK_V3_SIGNATURE.length + 1 || bytes[0] !== 0x03) return bytes; + for (let index = 0; index < SILK_V3_SIGNATURE.length; index += 1) { + if (bytes[index + 1] !== SILK_V3_SIGNATURE[index]) return bytes; + } + + const normalized = Uint8Array.from(bytes); + normalized[0] = 0x02; + log.debug('normalized QQ AI SILK container for audio transcoding'); + return normalized; +} /** * Transcode raw audio bytes (a QQ voice SILK/AMR) to `format`, returning the @@ -205,7 +227,7 @@ export async function convertAudioBytes( const outPath = path.join(dir, `${id}.${format}`); let outcome: PromiseSettledResult<{ base64: string; size: number }>; try { - await fs.promises.writeFile(inPath, bytes); + await fs.promises.writeFile(inPath, normalizeQqAiSilkContainer(bytes)); 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). diff --git a/packages/protocol/tests/highway/audio-transcode.test.ts b/packages/protocol/tests/highway/audio-transcode.test.ts index 92e67e74..ddedb889 100644 --- a/packages/protocol/tests/highway/audio-transcode.test.ts +++ b/packages/protocol/tests/highway/audio-transcode.test.ts @@ -1,5 +1,12 @@ import { afterAll, describe, expect, it, vi } from 'vitest'; -import { mkdtempSync, promises as fsPromises, readdirSync, rmSync, writeFileSync } from 'fs'; +import { + mkdtempSync, + promises as fsPromises, + readFileSync, + 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'; @@ -31,6 +38,31 @@ describe('isAudioOutFormat / AUDIO_OUT_FORMATS', () => { }); describe('convertAudioBytes', () => { + it('accepts the QQ AI SILK container without mutating the caller bytes', async () => { + const input = Buffer.concat([ + Buffer.from([0x03]), + Buffer.from('#!SILK_V3', 'ascii'), + Buffer.from([0x04, 0x00, 0x11, 0x22, 0x33, 0x44]), + ]); + const originalInput = Buffer.from(input); + let stagedInput: Buffer | null = null; + const addon = { + decodeAudioToFmt: async (inputPath: string, outputPath: string, format: string) => { + stagedInput = readFileSync(inputPath); + writeFileSync(outputPath, Buffer.from('MP3DATA')); + return { result: true, sampleRate: 24_000, channels: 1, format }; + }, + }; + + await convertAudioBytes(input, 'mp3', { addon, tmpDir }); + + expect(stagedInput?.subarray(0, 10)).toEqual( + Buffer.concat([Buffer.from([0x02]), Buffer.from('#!SILK_V3', 'ascii')]), + ); + expect(stagedInput?.subarray(10)).toEqual(input.subarray(10)); + expect(input).toEqual(originalInput); + }); + it('transcodes and returns base64 + size of the addon output', async () => { const r = await convertAudioBytes(new Uint8Array([1, 2, 3]), 'wav', { addon: fakeOk, tmpDir }); expect(Buffer.from(r.base64, 'base64').toString()).toBe('WAVDATA'); diff --git a/packages/protocol/tests/native/audio-transcode.test.ts b/packages/protocol/tests/native/audio-transcode.test.ts index d0cf2f5e..bac664de 100644 --- a/packages/protocol/tests/native/audio-transcode.test.ts +++ b/packages/protocol/tests/native/audio-transcode.test.ts @@ -86,4 +86,28 @@ describeBundledAddon('bundled native ffmpeg addon', () => { expect(duration).toBeGreaterThan(0.9); expect(duration).toBeLessThan(1.2); }); + + it('converts the QQ AI SILK container variant through the public transcode seam', async () => { + const addon = loadBundledAddon(); + const wavPath = path.join(tmpDir, 'ai-input.wav'); + const silkPath = path.join(tmpDir, 'ai-input.ntsilk'); + writeFileSync(wavPath, makeMonoWav()); + await addon.convertToNTSilkTct(wavPath, silkPath); + + const aiSilk = readFileSync(silkPath); + expect(aiSilk.subarray(0, 10)).toEqual( + Buffer.concat([Buffer.from([0x02]), Buffer.from('#!SILK_V3', 'ascii')]), + ); + aiSilk[0] = 0x03; + + const result = await convertAudioBytes(aiSilk, 'mp3', { addon, tmpDir }); + const mp3 = Buffer.from(result.base64, 'base64'); + const outputPath = path.join(tmpDir, 'ai-output.mp3'); + writeFileSync(outputPath, mp3); + + expect(hasMp3Signature(mp3)).toBe(true); + const duration = await addon.getDuration(outputPath); + expect(duration).toBeGreaterThan(0.9); + expect(duration).toBeLessThan(1.2); + }); });