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
@@ -5,6 +5,8 @@ import {
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
@@ -157,4 +159,18 @@ export class ExtrasApi {
|
||||
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
|
||||
/**
|
||||
* Transcode a voice record (`get_record out_format`, #165). `source` is a
|
||||
* URL / local path / `base64://…` (the record's download URL in practice);
|
||||
* it is loaded then transcoded to `format` via the bundled SILK-capable
|
||||
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
|
||||
* failed conversion.
|
||||
*/
|
||||
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
|
||||
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
|
||||
// default so a tampered/oversized source can't be pulled in.
|
||||
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
|
||||
return convertAudioBytes(bytes, format);
|
||||
}
|
||||
}
|
||||
@@ -5235,7 +5235,7 @@
|
||||
{
|
||||
"name": "get_record",
|
||||
"aliases": [],
|
||||
"summary": "获取语音信息",
|
||||
"summary": "获取语音信息;传 out_format 则服务端转码并附带 base64",
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
@@ -5257,6 +5257,33 @@
|
||||
},
|
||||
"default": "",
|
||||
"role": "file_id"
|
||||
},
|
||||
{
|
||||
"name": "out_format",
|
||||
"type": "enum",
|
||||
"required": false,
|
||||
"values": [
|
||||
"mp3",
|
||||
"amr",
|
||||
"wma",
|
||||
"m4a",
|
||||
"spx",
|
||||
"ogg",
|
||||
"wav",
|
||||
"flac"
|
||||
],
|
||||
"schema": {
|
||||
"enum": [
|
||||
"mp3",
|
||||
"amr",
|
||||
"wma",
|
||||
"m4a",
|
||||
"spx",
|
||||
"ogg",
|
||||
"wav",
|
||||
"flac"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -5272,6 +5299,18 @@
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"x-role": "file_id"
|
||||
},
|
||||
"out_format": {
|
||||
"enum": [
|
||||
"mp3",
|
||||
"amr",
|
||||
"wma",
|
||||
"m4a",
|
||||
"spx",
|
||||
"ogg",
|
||||
"wav",
|
||||
"flac"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
|
||||
@@ -5238,7 +5238,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
{
|
||||
"name": "get_record",
|
||||
"aliases": [],
|
||||
"summary": "获取语音信息",
|
||||
"summary": "获取语音信息;传 out_format 则服务端转码并附带 base64",
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
@@ -5260,6 +5260,33 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"default": "",
|
||||
"role": "file_id"
|
||||
},
|
||||
{
|
||||
"name": "out_format",
|
||||
"type": "enum",
|
||||
"required": false,
|
||||
"values": [
|
||||
"mp3",
|
||||
"amr",
|
||||
"wma",
|
||||
"m4a",
|
||||
"spx",
|
||||
"ogg",
|
||||
"wav",
|
||||
"flac"
|
||||
],
|
||||
"schema": {
|
||||
"enum": [
|
||||
"mp3",
|
||||
"amr",
|
||||
"wma",
|
||||
"m4a",
|
||||
"spx",
|
||||
"ogg",
|
||||
"wav",
|
||||
"flac"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -5275,6 +5302,18 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"x-role": "file_id"
|
||||
},
|
||||
"out_format": {
|
||||
"enum": [
|
||||
"mp3",
|
||||
"amr",
|
||||
"wma",
|
||||
"m4a",
|
||||
"spx",
|
||||
"ogg",
|
||||
"wav",
|
||||
"flac"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
|
||||
@@ -545,18 +545,32 @@ export const actions = [
|
||||
|
||||
defineAction({
|
||||
name: 'get_record',
|
||||
summary: '获取语音信息',
|
||||
summary: '获取语音信息;传 out_format 则服务端转码并附带 base64',
|
||||
readOnly: true,
|
||||
params: {
|
||||
file: f.string().default('').role('record'),
|
||||
file_id: f.string().default('').role('file_id'),
|
||||
// Optional server-side transcode (#165): SILK/AMR → the requested
|
||||
// container, returned as `data.base64`. Absent ⇒ behaviour unchanged.
|
||||
out_format: f.enum('mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac').optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const file = p.file || p.file_id;
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
const info = await ctx.getRecordInfo(file);
|
||||
if (info) return okResponse(info);
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
|
||||
if (!info) return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
|
||||
if (!p.out_format) return okResponse(info);
|
||||
// Transcode from the record's download URL (fall back to file field).
|
||||
const source = String(info.url || info.file || '');
|
||||
if (!source) return failedResponse(RETCODE.ACTION_FAILED, 'record has no downloadable source');
|
||||
try {
|
||||
// Keep the original record info (file_size stays the source size, like
|
||||
// NapCat) and just attach the transcoded payload.
|
||||
const { base64 } = await ctx.bridge.apis.extras.convertRecord(source, p.out_format);
|
||||
return okResponse({ ...info, out_format: p.out_format, base64 });
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `语音转码失败:${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
|
||||
@@ -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