fix(protocol): produce valid MP3 records
Use the dedicated audio conversion path for record output so mono QQ voice records produce valid MP3 data. Add release-target smoke coverage and preserve conversion and cleanup failures for diagnostics. Fixes #239
This commit is contained in:
6 files changed
+182
-26
No files matched your search
@@ -127,6 +127,9 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
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.
|
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||||
- name: Build project
|
- name: Build project
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -45,6 +45,9 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
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.
|
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||||
- name: Build project
|
- name: Build project
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -91,6 +91,7 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
|
"test:native-audio": "vitest run tests/highway/audio-transcode-native.test.ts",
|
||||||
"bench": "vitest bench --run",
|
"bench": "vitest bench --run",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -21,12 +21,20 @@ interface FFmpegNativeAddon {
|
|||||||
getDuration(filePath: string): Promise<number>;
|
getDuration(filePath: string): Promise<number>;
|
||||||
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
|
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
|
||||||
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
|
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 cachedAddon: FFmpegNativeAddon | null = null;
|
||||||
let cachedLoadError: string | null = null;
|
let cachedLoadError: string | null = null;
|
||||||
|
|
||||||
|
function errorMessage(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
function addonFileName(): string {
|
function addonFileName(): string {
|
||||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||||
}
|
}
|
||||||
@@ -79,7 +87,7 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
|
|||||||
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
|
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
|
||||||
return cachedAddon;
|
return cachedAddon;
|
||||||
} catch (error) {
|
} 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);
|
throw new Error(cachedLoadError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -155,8 +163,8 @@ export function defaultPttTempDir(): string {
|
|||||||
|
|
||||||
// ── audio transcode (get_record out_format, #165) ──
|
// ── audio transcode (get_record out_format, #165) ──
|
||||||
// The addon is a custom ffmpeg build that bundles a SILK decoder, so it can
|
// 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
|
// transcode a QQ voice (SILK/AMR) into a normal container in one
|
||||||
// call — mirroring NapCat's FFmpegService.convertAudioFmt.
|
// decodeAudioToFmt call — mirroring NapCat's FFmpegService.convertAudioFmt.
|
||||||
|
|
||||||
/** Output formats accepted by `out_format` (mirrors NapCat's allowlist). */
|
/** 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;
|
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. */
|
/** Minimal addon surface the transcode needs — lets tests inject a fake. */
|
||||||
type AudioConvertAddon = Pick<FFmpegNativeAddon, 'convertFile'>;
|
type AudioConvertAddon = Pick<FFmpegNativeAddon, 'decodeAudioToFmt'>;
|
||||||
|
|
||||||
/** Default ceiling on the transcoded output read into memory for base64. SILK→
|
/** 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
|
* 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 id = crypto.randomBytes(8).toString('hex');
|
||||||
const inPath = path.join(dir, `${id}.in`);
|
const inPath = path.join(dir, `${id}.in`);
|
||||||
const outPath = path.join(dir, `${id}.${format}`);
|
const outPath = path.join(dir, `${id}.${format}`);
|
||||||
|
let outcome: PromiseSettledResult<{ base64: string; size: number }>;
|
||||||
try {
|
try {
|
||||||
await fs.promises.writeFile(inPath, bytes);
|
await fs.promises.writeFile(inPath, bytes);
|
||||||
const res = await addon.convertFile(inPath, outPath, format);
|
await addon.decodeAudioToFmt(inPath, outPath, format);
|
||||||
if (!res?.success || !fs.existsSync(outPath)) throw new Error('audio conversion failed');
|
if (!fs.existsSync(outPath)) throw new Error('audio conversion failed: no output file');
|
||||||
// Bound the output before reading it into memory (decompressing direction).
|
// Bound the output before reading it into memory (decompressing direction).
|
||||||
const stat = await fs.promises.stat(outPath);
|
const stat = await fs.promises.stat(outPath);
|
||||||
if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
|
if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
|
||||||
const out = await fs.promises.readFile(outPath);
|
const out = await fs.promises.readFile(outPath);
|
||||||
return { base64: out.toString('base64'), size: out.length };
|
outcome = { status: 'fulfilled', value: { base64: out.toString('base64'), size: out.length } };
|
||||||
} finally {
|
} catch (reason) {
|
||||||
// Await cleanup so no temp file lingers past the call (the bytes are
|
outcome = { status: 'rejected', reason };
|
||||||
// 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 }),
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `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;
|
||||||
}
|
}
|
||||||
@@ -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<void>;
|
||||||
|
decodeAudioToFmt(
|
||||||
|
inputFile: string,
|
||||||
|
outputFile: string,
|
||||||
|
format: string,
|
||||||
|
): Promise<{ result: boolean; sampleRate: number; channels: number; format: string }>;
|
||||||
|
getDuration(filePath: string): Promise<number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string, unknown> };
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,21 +1,22 @@
|
|||||||
import { afterAll, describe, expect, it } from 'vitest';
|
import { afterAll, describe, expect, it, vi } from 'vitest';
|
||||||
import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs';
|
import { mkdtempSync, promises as fsPromises, readdirSync, rmSync, writeFileSync } from 'fs';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { AUDIO_OUT_FORMATS, convertAudioBytes, isAudioOutFormat } from '@snowluma/protocol/highway/ffmpeg-addon';
|
import { AUDIO_OUT_FORMATS, convertAudioBytes, isAudioOutFormat } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||||
|
|
||||||
// convertAudioBytes is the pure (#165) transcode seam: write input → addon
|
// convertAudioBytes is the pure (#165) transcode seam: write input → the
|
||||||
// convertFile → read output as base64 → always clean up temp files. The native
|
// addon's dedicated audio transcoder → read output as base64 → always clean up
|
||||||
// addon is file-based and can't run in CI, so a fake addon stands in.
|
// 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-'));
|
const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'sl-audio-test-'));
|
||||||
afterAll(() => rmSync(tmpDir, { recursive: true, force: true }));
|
afterAll(() => rmSync(tmpDir, { recursive: true, force: true }));
|
||||||
|
|
||||||
/** Fake addon: writes deterministic bytes to the output path and reports ok. */
|
/** Fake addon: writes deterministic bytes to the output path and reports ok. */
|
||||||
const fakeOk = {
|
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
|
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 () => {
|
it('rejects an unsupported format before touching the addon', async () => {
|
||||||
let called = false;
|
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/);
|
await expect(convertAudioBytes(new Uint8Array([1]), 'opus', { addon: spy, tmpDir })).rejects.toThrow(/unsupported out_format/);
|
||||||
expect(called).toBe(false);
|
expect(called).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws and cleans up when the addon reports failure', async () => {
|
it('propagates a native conversion rejection and cleans up', async () => {
|
||||||
const fakeFail = { convertFile: async () => ({ success: false }) };
|
const fakeFail = {
|
||||||
await expect(convertAudioBytes(new Uint8Array([9]), 'mp3', { addon: fakeFail, tmpDir })).rejects.toThrow(/conversion failed/);
|
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
|
// no leftover temp files for this run
|
||||||
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.mp3') || n.endsWith('.in'));
|
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.mp3') || n.endsWith('.in'));
|
||||||
expect(leftover).toEqual([]);
|
expect(leftover).toEqual([]);
|
||||||
@@ -64,4 +72,29 @@ describe('convertAudioBytes', () => {
|
|||||||
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.flac') || n.endsWith('.in'));
|
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.flac') || n.endsWith('.in'));
|
||||||
expect(leftover).toEqual([]);
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user