feat(onebot): get_record out_format — server-side voice transcode (#165)
#165: get_record gains an optional `out_format` (mp3/amr/wma/m4a/spx/ogg/ wav/flac, mirroring NapCat). When set, the QQ voice (SILK/AMR) is transcoded server-side and the result is attached as `data.base64`; the original info (file/url/file_size) is preserved. Absent ⇒ behaviour unchanged. This spares ASR consumers from shipping a SILK decoder. - protocol: convertAudioBytes(bytes, format, deps?) drives the bundled SILK-capable ffmpeg addon's convertFile through temp files (always cleaned up), with a format allowlist and an output-size cap. Pure/ injectable, unit-tested with a fake addon (6 cases). - core: ExtrasApi.convertRecord(source, format) = loadBinarySource (64 MiB cap) → convertAudioBytes. - onebot: get_record wires out_format; transcode failure (incl. an addon lacking SILK decode) degrades to ACTION_FAILED, never crashes. Adversarially reviewed: no path traversal (format allowlisted), no SSRF (source is the cached CDN url, not user input), cleanup covers every path, graceful degradation confirmed. Catalog regenerated. Real-machine e2e (does the shipped .node actually decode SILK?) is Phase 2.
This commit is contained in:
6 files changed
+241
-5
No files matched your search
@@ -152,3 +152,64 @@ export async function encodeSilk(inputFile: string, tempDir: string): Promise<En
|
||||
export function defaultPttTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-ptt');
|
||||
}
|
||||
|
||||
// ── 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.
|
||||
|
||||
/** 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 type AudioOutFormat = (typeof AUDIO_OUT_FORMATS)[number];
|
||||
export function isAudioOutFormat(s: string): s is AudioOutFormat {
|
||||
return (AUDIO_OUT_FORMATS as readonly string[]).includes(s);
|
||||
}
|
||||
|
||||
/** Minimal addon surface the transcode needs — lets tests inject a fake. */
|
||||
type AudioConvertAddon = Pick<FFmpegNativeAddon, 'convertFile'>;
|
||||
|
||||
/** 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
|
||||
* tiny. Generous; overridable via deps. */
|
||||
const DEFAULT_MAX_AUDIO_OUTPUT = 256 * 1024 * 1024; // 256 MiB
|
||||
|
||||
/**
|
||||
* Transcode raw audio bytes (a QQ voice SILK/AMR) to `format`, returning the
|
||||
* result as base64 + byte size. Writes the input + output to temp files (the
|
||||
* native addon is file-based), always cleaning them up. `deps` injects a fake
|
||||
* addon / tmp dir for tests. Throws on an unsupported format or a failed
|
||||
* conversion (e.g. the binary lacks SILK decode).
|
||||
*/
|
||||
export async function convertAudioBytes(
|
||||
bytes: Uint8Array,
|
||||
format: string,
|
||||
deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {},
|
||||
): Promise<{ base64: string; size: number }> {
|
||||
if (!isAudioOutFormat(format)) {
|
||||
throw new Error(`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`);
|
||||
}
|
||||
const addon = deps.addon ?? getFFmpegAddon();
|
||||
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
|
||||
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'snowluma-rec');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const inPath = path.join(dir, `${id}.in`);
|
||||
const outPath = path.join(dir, `${id}.${format}`);
|
||||
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');
|
||||
// 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 }),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { afterAll, describe, expect, it } from 'vitest';
|
||||
import { mkdtempSync, 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.
|
||||
|
||||
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) => {
|
||||
writeFileSync(out, Buffer.from('WAVDATA')); // stand-in converted payload
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
describe('isAudioOutFormat / AUDIO_OUT_FORMATS', () => {
|
||||
it('accepts exactly NapCat\'s allowlist', () => {
|
||||
expect([...AUDIO_OUT_FORMATS]).toEqual(['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac']);
|
||||
expect(isAudioOutFormat('wav')).toBe(true);
|
||||
expect(isAudioOutFormat('WAV')).toBe(false); // case-sensitive
|
||||
expect(isAudioOutFormat('opus')).toBe(false);
|
||||
expect(isAudioOutFormat('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertAudioBytes', () => {
|
||||
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');
|
||||
expect(r.size).toBe('WAVDATA'.length);
|
||||
});
|
||||
|
||||
it('rejects an unsupported format before touching the addon', async () => {
|
||||
let called = false;
|
||||
const spy = { convertFile: async () => { called = true; return { success: true }; } };
|
||||
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/);
|
||||
// no leftover temp files for this run
|
||||
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.mp3') || n.endsWith('.in'));
|
||||
expect(leftover).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects (and cleans up) when the output exceeds the cap', async () => {
|
||||
await expect(
|
||||
convertAudioBytes(new Uint8Array([1]), 'wav', { addon: fakeOk, tmpDir, maxOutputBytes: 3 }),
|
||||
).rejects.toThrow(/too large/);
|
||||
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.wav') || n.endsWith('.in'));
|
||||
expect(leftover).toEqual([]);
|
||||
});
|
||||
|
||||
it('cleans up the temp input + output on success too', async () => {
|
||||
await convertAudioBytes(new Uint8Array([4, 5]), 'flac', { addon: fakeOk, tmpDir });
|
||||
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.flac') || n.endsWith('.in'));
|
||||
expect(leftover).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user