diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index 557a088a..64b0ade6 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -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); + } } diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index b9bb2c6a..24438b6c 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -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 diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 001b98c7..b462ff50 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -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 diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index f6c86d84..95e8b114 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -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)}`); + } }, }), diff --git a/packages/protocol/src/highway/ffmpeg-addon.ts b/packages/protocol/src/highway/ffmpeg-addon.ts index c4b69ce5..52de8d3a 100644 --- a/packages/protocol/src/highway/ffmpeg-addon.ts +++ b/packages/protocol/src/highway/ffmpeg-addon.ts @@ -152,3 +152,64 @@ export async function encodeSilk(inputFile: string, tempDir: string): Promise; + +/** 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 }), + ]); + } +} diff --git a/packages/protocol/tests/highway/audio-transcode.test.ts b/packages/protocol/tests/highway/audio-transcode.test.ts new file mode 100644 index 00000000..0fd975e6 --- /dev/null +++ b/packages/protocol/tests/highway/audio-transcode.test.ts @@ -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([]); + }); +});