|
| 1 | +// SPDX-FileCopyrightText: 2026 LiveKit, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | +import { AudioFrame } from '@livekit/rtc-node'; |
| 5 | +import { describe, expect, it } from 'vitest'; |
| 6 | +import { adoptLocalAudioFrame } from './_frame_identity.js'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Stands in for the `AudioFrame` of a second copy of `@livekit/rtc-node`: identical shape, same |
| 10 | + * constructor name, unrelated identity. That is exactly what the CJS build produces when the |
| 11 | + * Cloud backend pulls it in through `createRequire`. |
| 12 | + */ |
| 13 | +class ForeignAudioFrame { |
| 14 | + constructor( |
| 15 | + readonly data: Int16Array, |
| 16 | + readonly sampleRate: number, |
| 17 | + readonly channels: number, |
| 18 | + readonly samplesPerChannel: number, |
| 19 | + private readonly _userdata: Record<string, unknown> = {}, |
| 20 | + ) {} |
| 21 | + |
| 22 | + get userdata(): Record<string, unknown> { |
| 23 | + return this._userdata; |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +describe('adoptLocalAudioFrame', () => { |
| 28 | + it('adopts a frame built by another copy of rtc-node', () => { |
| 29 | + const samples = new Int16Array([1, -2, 3, -4]); |
| 30 | + const foreign = new ForeignAudioFrame(samples, 16000, 1, 4, { source: 'krisp' }); |
| 31 | + |
| 32 | + // The premise of the bug: this lookalike fails the identity check every consumer relies on. |
| 33 | + expect(foreign instanceof AudioFrame).toBe(false); |
| 34 | + |
| 35 | + const adopted = adoptLocalAudioFrame(foreign as unknown as AudioFrame); |
| 36 | + |
| 37 | + expect(adopted instanceof AudioFrame).toBe(true); |
| 38 | + expect(adopted.sampleRate).toBe(16000); |
| 39 | + expect(adopted.channels).toBe(1); |
| 40 | + expect(adopted.samplesPerChannel).toBe(4); |
| 41 | + expect(adopted.userdata).toEqual({ source: 'krisp' }); |
| 42 | + // Adopting must not copy the audio: this runs on every frame of every session. |
| 43 | + expect(adopted.data).toBe(samples); |
| 44 | + }); |
| 45 | + |
| 46 | + it('returns a local frame untouched', () => { |
| 47 | + const local = new AudioFrame(new Int16Array([5, 6]), 48000, 1, 2); |
| 48 | + |
| 49 | + expect(adoptLocalAudioFrame(local)).toBe(local); |
| 50 | + }); |
| 51 | +}); |
0 commit comments