fix(protocol): attach voice waveforms on outgoing records
Private-chat clients only draw the progress track from message metadata. Compute amplitudes when uploading a record so PC and phone show the bar.
This commit is contained in:
6 files changed
+344
-1
No files matched your search
@@ -488,6 +488,15 @@ describe('pipeline — finalizeMediaMsgInfo', () => {
|
||||
expect(decoded.extBizInfo.pic.textSummary).toBe('[image]');
|
||||
});
|
||||
|
||||
it('preserves a server ptt waveform on the outgoing MsgInfo', () => {
|
||||
const waveform = new Uint8Array([8, 4, 18, 4, 10, 20, 30, 40]);
|
||||
const out = finalizeMediaMsgInfo({
|
||||
msgInfo: { msgInfoBody: [], extBizInfo: { ptt: { waveform } } },
|
||||
});
|
||||
const decoded: any = protobuf_decode<EncodableMediaMsgInfo>(out);
|
||||
expect(decoded.extBizInfo.ptt.waveform).toEqual(waveform);
|
||||
});
|
||||
|
||||
it('without defaultPic, leaves pic untouched when server omits it', () => {
|
||||
const out = finalizeMediaMsgInfo({
|
||||
msgInfo: { msgInfoBody: [], extBizInfo: {} },
|
||||
|
||||
@@ -56,6 +56,14 @@ describe('ptt-upload', () => {
|
||||
const c2cFlags = (args.extBizInfo as any).ptt.bytesGeneralFlags;
|
||||
expect(c2cFlags.length).toBe(14);
|
||||
expect(c2cFlags[0]).toBe(0x9a);
|
||||
expect((args.extBizInfo as any).ptt.waveform).toBeUndefined();
|
||||
});
|
||||
|
||||
it('fingerprint path does not invent a waveform', async () => {
|
||||
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
|
||||
expect((args.extBizInfo as any).ptt.waveform).toBeUndefined();
|
||||
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('fingerprint payload: zero bytes, fastOnlyError ready, voiceFormat defaults to 1', async () => {
|
||||
|
||||
@@ -407,6 +407,12 @@ export interface VideoExtBizInfo {
|
||||
bytesPbReserve?: pb<3, bytes>;
|
||||
}
|
||||
|
||||
/** Encoded payload of `PttExtBizInfo.waveform`. Count must equal amplitudes. */
|
||||
export interface PttWaveform {
|
||||
size?: pb<1, uint_32>;
|
||||
amplitudes?: pb<2, bytes>;
|
||||
}
|
||||
|
||||
export interface PttExtBizInfo {
|
||||
srcUin?: pb<1, uint_64>;
|
||||
pttScene?: pb<2, uint_32>;
|
||||
|
||||
@@ -5,13 +5,19 @@ import path from 'path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MessageElement } from '../events';
|
||||
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
|
||||
import { defaultPttTempDir, encodeSilk, getFFmpegAddon } from './ffmpeg-addon';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
hexToBytes,
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import {
|
||||
amplitudesFromPcmS16le,
|
||||
encodePttWaveform,
|
||||
mergePttWaveform,
|
||||
pcmS16leFromWav,
|
||||
} from './ptt-waveform';
|
||||
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
@@ -42,6 +48,8 @@ interface PttPayload {
|
||||
fastOnly: boolean;
|
||||
/** Cleanup hooks for any temp silk files staged during loadPtt. */
|
||||
cleanups: Array<() => void>;
|
||||
/** Encoded `PttWaveform` for private-chat progress / peaks. Omitted on fingerprint. */
|
||||
waveform?: Uint8Array;
|
||||
}
|
||||
|
||||
function pttPayloadFromFingerprint(element: MessageElement): PttPayload {
|
||||
@@ -110,6 +118,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
||||
|
||||
const hashes = computeHashes(silkBytes);
|
||||
const waveform = await tryPttWaveform(silk.path, tempDir, cleanups);
|
||||
return {
|
||||
bytes: silkBytes,
|
||||
md5: hashes.md5,
|
||||
@@ -122,6 +131,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
voiceFormat: 1,
|
||||
fastOnly: false,
|
||||
cleanups: [...cleanups],
|
||||
waveform,
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
@@ -129,6 +139,25 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
}
|
||||
}
|
||||
|
||||
async function tryPttWaveform(
|
||||
silkPath: string,
|
||||
tempDir: string,
|
||||
cleanups: Array<() => void>,
|
||||
): Promise<Uint8Array | undefined> {
|
||||
const wavPath = path.join(tempDir, `snowluma-ptt-wave-${crypto.randomUUID()}.wav`);
|
||||
cleanups.push(() => { try { fs.unlinkSync(wavPath); } catch { /* ignore */ } });
|
||||
try {
|
||||
const decoded = await getFFmpegAddon().decodeAudioToFmt(silkPath, wavPath, 'wav');
|
||||
if (!decoded.result || !fs.existsSync(wavPath)) return undefined;
|
||||
const wav = new Uint8Array(fs.readFileSync(wavPath));
|
||||
const { pcm, channels } = pcmS16leFromWav(wav);
|
||||
return encodePttWaveform(amplitudesFromPcmS16le(pcm, { channels }));
|
||||
} catch (err) {
|
||||
moduleLog.debug('ptt waveform skipped: %s', err instanceof Error ? err.message : String(err));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
|
||||
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
||||
@@ -195,12 +224,14 @@ export async function uploadPttMsgInfo(
|
||||
bytesGeneralFlags: isGroup
|
||||
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
|
||||
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
|
||||
...(ptt.waveform ? { waveform: ptt.waveform } : {}),
|
||||
},
|
||||
},
|
||||
uploads,
|
||||
label: 'ptt',
|
||||
});
|
||||
|
||||
mergePttWaveform(upload, ptt.waveform);
|
||||
return finalizeMediaMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { PttWaveform } from '@snowluma/proto-defs/element';
|
||||
import type { NTV2UploadRespBody } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
/** Official receive-side default bar count (`ParsePttWave` fallback). */
|
||||
export const PTT_WAVEFORM_BINS = 30;
|
||||
/** Official default amplitude floor when a bin (or the whole clip) is silent. */
|
||||
export const PTT_WAVEFORM_SILENCE = 25;
|
||||
|
||||
function u16le(bytes: Uint8Array, offset: number): number {
|
||||
return bytes[offset]! | (bytes[offset + 1]! << 8);
|
||||
}
|
||||
|
||||
function u32le(bytes: Uint8Array, offset: number): number {
|
||||
return bytes[offset]!
|
||||
| (bytes[offset + 1]! << 8)
|
||||
| (bytes[offset + 2]! << 16)
|
||||
| (bytes[offset + 3]! << 24);
|
||||
}
|
||||
|
||||
function fourcc(bytes: Uint8Array, offset: number): string {
|
||||
return String.fromCharCode(
|
||||
bytes[offset]!,
|
||||
bytes[offset + 1]!,
|
||||
bytes[offset + 2]!,
|
||||
bytes[offset + 3]!,
|
||||
);
|
||||
}
|
||||
|
||||
function s16le(bytes: Uint8Array, offset: number): number {
|
||||
const raw = u16le(bytes, offset);
|
||||
return raw >= 0x8000 ? raw - 0x10000 : raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull s16le PCM out of a WAV produced by `decodeAudioToFmt(..., 'wav')`.
|
||||
* Rejects non-PCM / non-16-bit so a botched transcode cannot invent bars.
|
||||
*/
|
||||
export function pcmS16leFromWav(wav: Uint8Array): {
|
||||
pcm: Uint8Array;
|
||||
channels: number;
|
||||
sampleRate: number;
|
||||
} {
|
||||
if (wav.length < 12) throw new Error('wav is truncated');
|
||||
if (fourcc(wav, 0) !== 'RIFF' || fourcc(wav, 8) !== 'WAVE') {
|
||||
throw new Error('wav is not a RIFF/WAVE file');
|
||||
}
|
||||
|
||||
let offset = 12;
|
||||
let channels = 0;
|
||||
let sampleRate = 0;
|
||||
let bitsPerSample = 0;
|
||||
let audioFormat = 0;
|
||||
let data: Uint8Array | undefined;
|
||||
|
||||
while (offset + 8 <= wav.length) {
|
||||
const id = fourcc(wav, offset);
|
||||
const size = u32le(wav, offset + 4);
|
||||
const start = offset + 8;
|
||||
if (start + size > wav.length) throw new Error('wav chunk is truncated');
|
||||
if (id === 'fmt ') {
|
||||
if (size < 16) throw new Error('wav fmt chunk is short');
|
||||
audioFormat = u16le(wav, start);
|
||||
channels = u16le(wav, start + 2);
|
||||
sampleRate = u32le(wav, start + 4);
|
||||
bitsPerSample = u16le(wav, start + 14);
|
||||
} else if (id === 'data') {
|
||||
data = wav.subarray(start, start + size);
|
||||
}
|
||||
offset = start + size + (size & 1);
|
||||
}
|
||||
|
||||
if (!data) throw new Error('wav has no data chunk');
|
||||
if (audioFormat !== 1) throw new Error(`wav format ${audioFormat} is not PCM`);
|
||||
if (channels < 1) throw new Error('wav channel count is invalid');
|
||||
if (bitsPerSample !== 16) throw new Error(`wav bits ${bitsPerSample} is not s16`);
|
||||
return { pcm: data, channels, sampleRate };
|
||||
}
|
||||
|
||||
function silentWaveform(bins: number): Uint8Array {
|
||||
return new Uint8Array(bins).fill(PTT_WAVEFORM_SILENCE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Peak each window of interleaved s16le frames into official-length bars.
|
||||
* Quiet windows stay 0 (valleys). A fully silent clip uses the official floor
|
||||
* so private-chat clients still draw a progress track.
|
||||
*/
|
||||
export function amplitudesFromPcmS16le(
|
||||
pcm: Uint8Array,
|
||||
options: { channels?: number; bins?: number } = {},
|
||||
): Uint8Array {
|
||||
const channels = options.channels ?? 1;
|
||||
const bins = options.bins ?? PTT_WAVEFORM_BINS;
|
||||
if (channels < 1 || bins < 1) throw new Error('waveform channels/bins must be >= 1');
|
||||
|
||||
const frameSize = channels * 2;
|
||||
const frames = Math.floor(pcm.length / frameSize);
|
||||
if (frames === 0) return silentWaveform(bins);
|
||||
|
||||
const out = new Uint8Array(bins);
|
||||
let any = false;
|
||||
for (let bin = 0; bin < bins; bin += 1) {
|
||||
const start = Math.floor((bin * frames) / bins);
|
||||
let end = Math.floor(((bin + 1) * frames) / bins);
|
||||
if (end <= start) end = start + 1;
|
||||
let peak = 0;
|
||||
for (let frame = start; frame < end && frame < frames; frame += 1) {
|
||||
const base = frame * frameSize;
|
||||
for (let channel = 0; channel < channels; channel += 1) {
|
||||
const sample = Math.abs(s16le(pcm, base + channel * 2));
|
||||
if (sample > peak) peak = sample;
|
||||
}
|
||||
}
|
||||
const amplitude = Math.min(255, Math.round((peak * 255) / 32767));
|
||||
if (amplitude > 0) any = true;
|
||||
out[bin] = amplitude;
|
||||
}
|
||||
return any ? out : silentWaveform(bins);
|
||||
}
|
||||
|
||||
/** Encode amplitudes as the blob `ParsePttWave` accepts (count == bytes). */
|
||||
export function encodePttWaveform(amplitudes: Uint8Array): Uint8Array {
|
||||
if (amplitudes.length === 0) throw new Error('ptt waveform amplitudes are empty');
|
||||
return protobuf_encode<PttWaveform>({
|
||||
size: amplitudes.length,
|
||||
amplitudes,
|
||||
});
|
||||
}
|
||||
|
||||
export function decodePttWaveform(bytes: Uint8Array): { size: number; amplitudes: Uint8Array } {
|
||||
const decoded = protobuf_decode<PttWaveform>(bytes);
|
||||
const amplitudes = decoded.amplitudes ?? new Uint8Array(0);
|
||||
const size = decoded.size ?? 0;
|
||||
if (size !== amplitudes.length) {
|
||||
throw new Error(`ptt waveform count ${size} != amplitudes ${amplitudes.length}`);
|
||||
}
|
||||
return { size, amplitudes };
|
||||
}
|
||||
|
||||
/** Stamp computed waveform onto the upload response so finalize cannot drop it. */
|
||||
export function mergePttWaveform(
|
||||
upload: NTV2UploadRespBody,
|
||||
waveform: Uint8Array | undefined,
|
||||
): void {
|
||||
if (!waveform || waveform.length === 0 || !upload.msgInfo) return;
|
||||
const ext = upload.msgInfo.extBizInfo ?? {};
|
||||
upload.msgInfo.extBizInfo = {
|
||||
...ext,
|
||||
ptt: { ...ext.ptt, waveform },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { EncodableMediaMsgInfo } from '@snowluma/proto-defs/highway';
|
||||
import { finalizeMediaMsgInfo } from '@snowluma/protocol/highway/pipeline';
|
||||
import {
|
||||
PTT_WAVEFORM_BINS,
|
||||
PTT_WAVEFORM_SILENCE,
|
||||
amplitudesFromPcmS16le,
|
||||
decodePttWaveform,
|
||||
encodePttWaveform,
|
||||
mergePttWaveform,
|
||||
pcmS16leFromWav,
|
||||
} from '@snowluma/protocol/highway/ptt-waveform';
|
||||
|
||||
function le16(value: number): number[] {
|
||||
return [value & 0xff, (value >> 8) & 0xff];
|
||||
}
|
||||
|
||||
function le32(value: number): number[] {
|
||||
return [value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff];
|
||||
}
|
||||
|
||||
function ascii(text: string): number[] {
|
||||
return [...text].map((ch) => ch.charCodeAt(0));
|
||||
}
|
||||
|
||||
function s16leBytes(samples: number[]): Uint8Array {
|
||||
const out = new Uint8Array(samples.length * 2);
|
||||
for (let i = 0; i < samples.length; i += 1) {
|
||||
const v = samples[i]! < 0 ? samples[i]! + 0x10000 : samples[i]!;
|
||||
out[i * 2] = v & 0xff;
|
||||
out[i * 2 + 1] = (v >> 8) & 0xff;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Minimal PCM WAV: 16-bit, little-endian, one data chunk. */
|
||||
function wavBytes(samples: number[], channels = 1, sampleRate = 24_000): Uint8Array {
|
||||
const pcm = s16leBytes(samples);
|
||||
const fmtSize = 16;
|
||||
const dataSize = pcm.length;
|
||||
const riffSize = 4 + (8 + fmtSize) + (8 + dataSize);
|
||||
const out = new Uint8Array(12 + 8 + fmtSize + 8 + dataSize);
|
||||
let off = 0;
|
||||
const put = (bytes: number[]) => {
|
||||
out.set(bytes, off);
|
||||
off += bytes.length;
|
||||
};
|
||||
put(ascii('RIFF'));
|
||||
put(le32(riffSize));
|
||||
put(ascii('WAVE'));
|
||||
put(ascii('fmt '));
|
||||
put(le32(fmtSize));
|
||||
put(le16(1));
|
||||
put(le16(channels));
|
||||
put(le32(sampleRate));
|
||||
put(le32(sampleRate * channels * 2));
|
||||
put(le16(channels * 2));
|
||||
put(le16(16));
|
||||
put(ascii('data'));
|
||||
put(le32(dataSize));
|
||||
out.set(pcm, off);
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('pcmS16leFromWav', () => {
|
||||
it('reads s16le PCM and channel count from a plain WAV', () => {
|
||||
const wav = wavBytes([0, 32767, -32768], 1, 16_000);
|
||||
const parsed = pcmS16leFromWav(wav);
|
||||
expect(parsed.channels).toBe(1);
|
||||
expect(parsed.sampleRate).toBe(16_000);
|
||||
expect(parsed.pcm).toEqual(s16leBytes([0, 32767, -32768]));
|
||||
});
|
||||
|
||||
it('rejects a non-PCM WAV', () => {
|
||||
const wav = wavBytes([1, 2, 3]);
|
||||
wav[20] = 7;
|
||||
expect(() => pcmS16leFromWav(wav)).toThrow(/not PCM/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('amplitudesFromPcmS16le', () => {
|
||||
it('uses the official 30 bars and scales a full-scale peak to 255', () => {
|
||||
const loud = new Array(30).fill(0);
|
||||
loud[0] = 32767;
|
||||
const amps = amplitudesFromPcmS16le(s16leBytes(loud));
|
||||
expect(amps.length).toBe(PTT_WAVEFORM_BINS);
|
||||
expect(amps[0]).toBe(255);
|
||||
});
|
||||
|
||||
it('keeps quiet windows at 0 so the bar has valleys', () => {
|
||||
const samples = new Array(60).fill(0);
|
||||
samples[0] = 32767;
|
||||
const amps = amplitudesFromPcmS16le(s16leBytes(samples), { bins: 2 });
|
||||
expect([...amps]).toEqual([255, 0]);
|
||||
});
|
||||
|
||||
it('uses the official silence floor when the clip is empty', () => {
|
||||
const amps = amplitudesFromPcmS16le(new Uint8Array(0), { bins: 4 });
|
||||
expect([...amps]).toEqual(new Array(4).fill(PTT_WAVEFORM_SILENCE));
|
||||
});
|
||||
|
||||
it('peaks stereo frames from either channel', () => {
|
||||
const pcm = s16leBytes([0, 32767, 0, 0]);
|
||||
const amps = amplitudesFromPcmS16le(pcm, { channels: 2, bins: 1 });
|
||||
expect(amps[0]).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodePttWaveform / decodePttWaveform', () => {
|
||||
it('roundtrips with matching count and amplitudes', () => {
|
||||
const amplitudes = new Uint8Array([25, 40, 80, 10]);
|
||||
const encoded = encodePttWaveform(amplitudes);
|
||||
expect(decodePttWaveform(encoded)).toEqual({ size: 4, amplitudes });
|
||||
});
|
||||
|
||||
it('rejects an empty amplitude list', () => {
|
||||
expect(() => encodePttWaveform(new Uint8Array(0))).toThrow(/empty/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergePttWaveform', () => {
|
||||
it('writes waveform onto msgInfo so finalize keeps it', () => {
|
||||
const waveform = encodePttWaveform(new Uint8Array(PTT_WAVEFORM_BINS).fill(40));
|
||||
const upload = { msgInfo: { msgInfoBody: [], extBizInfo: { ptt: { bytesReserve: new Uint8Array([1]) } } } };
|
||||
mergePttWaveform(upload, waveform);
|
||||
const decoded: any = protobuf_decode<EncodableMediaMsgInfo>(finalizeMediaMsgInfo(upload));
|
||||
expect(decoded.extBizInfo.ptt.waveform).toEqual(waveform);
|
||||
expect(decoded.extBizInfo.ptt.bytesReserve).toEqual(new Uint8Array([1]));
|
||||
});
|
||||
|
||||
it('no-ops when waveform is missing', () => {
|
||||
const upload = { msgInfo: { msgInfoBody: [], extBizInfo: {} } };
|
||||
mergePttWaveform(upload, undefined);
|
||||
expect(upload.msgInfo.extBizInfo).toEqual({});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user