|
| 1 | +// SPDX-FileCopyrightText: 2025 LiveKit, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | +import { Mutex } from '@livekit/mutex'; |
| 5 | +import { |
| 6 | + type AudioFrame, |
| 7 | + type ByteStreamWriter, |
| 8 | + type Room, |
| 9 | + RoomEvent, |
| 10 | + type RpcInvocationData, |
| 11 | + type TrackKind, |
| 12 | +} from '@livekit/rtc-node'; |
| 13 | +import { log } from '../../log.js'; |
| 14 | +import { |
| 15 | + Future, |
| 16 | + Task, |
| 17 | + shortuuid, |
| 18 | + waitForParticipant, |
| 19 | + waitForTrackPublication, |
| 20 | +} from '../../utils.js'; |
| 21 | +import { AudioOutput, type PlaybackFinishedEvent } from '../io.js'; |
| 22 | + |
| 23 | +const RPC_CLEAR_BUFFER = 'lk.clear_buffer'; |
| 24 | +const RPC_PLAYBACK_FINISHED = 'lk.playback_finished'; |
| 25 | +const AUDIO_STREAM_TOPIC = 'lk.audio_stream'; |
| 26 | + |
| 27 | +export interface DataStreamAudioOutputOptions { |
| 28 | + room: Room; |
| 29 | + destinationIdentity: string; |
| 30 | + sampleRate?: number; |
| 31 | + waitRemoteTrack?: TrackKind; |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * AudioOutput implementation that streams audio to a remote avatar worker using LiveKit DataStream. |
| 36 | + */ |
| 37 | +export class DataStreamAudioOutput extends AudioOutput { |
| 38 | + static _playbackFinishedRpcRegistered: boolean = false; |
| 39 | + static _playbackFinishedHandlers: Record<string, (data: RpcInvocationData) => string> = {}; |
| 40 | + |
| 41 | + private room: Room; |
| 42 | + private destinationIdentity: string; |
| 43 | + private roomConnectedFuture: Future<void>; |
| 44 | + private waitRemoteTrack?: TrackKind; |
| 45 | + private streamWriter?: ByteStreamWriter; |
| 46 | + private pushedDuration: number = 0; |
| 47 | + private started: boolean = false; |
| 48 | + private lock = new Mutex(); |
| 49 | + private startTask?: Task<void>; |
| 50 | + |
| 51 | + #logger = log(); |
| 52 | + |
| 53 | + constructor(opts: DataStreamAudioOutputOptions) { |
| 54 | + super(opts.sampleRate, undefined); |
| 55 | + |
| 56 | + const { room, destinationIdentity, sampleRate, waitRemoteTrack } = opts; |
| 57 | + this.room = room; |
| 58 | + this.destinationIdentity = destinationIdentity; |
| 59 | + this.sampleRate = sampleRate; |
| 60 | + this.waitRemoteTrack = waitRemoteTrack; |
| 61 | + |
| 62 | + const onRoomConnected = async () => { |
| 63 | + if (this.startTask) return; |
| 64 | + |
| 65 | + await this.roomConnectedFuture.await; |
| 66 | + |
| 67 | + // register the rpc method right after the room is connected |
| 68 | + DataStreamAudioOutput.registerPlaybackFinishedRpc({ |
| 69 | + room, |
| 70 | + callerIdentity: this.destinationIdentity, |
| 71 | + handler: (data) => this.handlePlaybackFinished(data), |
| 72 | + }); |
| 73 | + |
| 74 | + this.startTask = Task.from(({ signal }) => this._start(signal)); |
| 75 | + }; |
| 76 | + |
| 77 | + this.roomConnectedFuture = new Future<void>(); |
| 78 | + |
| 79 | + this.room.on(RoomEvent.ConnectionStateChanged, (_) => { |
| 80 | + if (room.isConnected && !this.roomConnectedFuture.done) { |
| 81 | + this.roomConnectedFuture.resolve(undefined); |
| 82 | + } |
| 83 | + }); |
| 84 | + |
| 85 | + if (this.room.isConnected) { |
| 86 | + this.roomConnectedFuture.resolve(undefined); |
| 87 | + } |
| 88 | + |
| 89 | + onRoomConnected(); |
| 90 | + } |
| 91 | + |
| 92 | + private async _start(_abortSignal: AbortSignal) { |
| 93 | + const unlock = await this.lock.lock(); |
| 94 | + |
| 95 | + try { |
| 96 | + if (this.started) return; |
| 97 | + |
| 98 | + await this.roomConnectedFuture.await; |
| 99 | + |
| 100 | + this.#logger.debug( |
| 101 | + { |
| 102 | + identity: this.destinationIdentity, |
| 103 | + }, |
| 104 | + 'waiting for the remote participant', |
| 105 | + ); |
| 106 | + |
| 107 | + await waitForParticipant({ |
| 108 | + room: this.room, |
| 109 | + identity: this.destinationIdentity, |
| 110 | + }); |
| 111 | + |
| 112 | + if (this.waitRemoteTrack) { |
| 113 | + this.#logger.debug( |
| 114 | + { |
| 115 | + identity: this.destinationIdentity, |
| 116 | + kind: this.waitRemoteTrack, |
| 117 | + }, |
| 118 | + 'waiting for the remote track', |
| 119 | + ); |
| 120 | + |
| 121 | + await waitForTrackPublication({ |
| 122 | + room: this.room, |
| 123 | + identity: this.destinationIdentity, |
| 124 | + kind: this.waitRemoteTrack, |
| 125 | + }); |
| 126 | + } |
| 127 | + |
| 128 | + this.#logger.debug( |
| 129 | + { |
| 130 | + identity: this.destinationIdentity, |
| 131 | + }, |
| 132 | + 'remote participant ready', |
| 133 | + ); |
| 134 | + |
| 135 | + this.started = true; |
| 136 | + } finally { |
| 137 | + unlock(); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + async captureFrame(frame: AudioFrame): Promise<void> { |
| 142 | + if (!this.startTask) { |
| 143 | + this.startTask = Task.from(({ signal }) => this._start(signal)); |
| 144 | + } |
| 145 | + |
| 146 | + await this.startTask.result; |
| 147 | + await super.captureFrame(frame); |
| 148 | + |
| 149 | + if (!this.streamWriter) { |
| 150 | + this.streamWriter = await this.room.localParticipant!.streamBytes({ |
| 151 | + name: shortuuid('AUDIO_'), |
| 152 | + topic: AUDIO_STREAM_TOPIC, |
| 153 | + destinationIdentities: [this.destinationIdentity], |
| 154 | + attributes: { |
| 155 | + sample_rate: frame.sampleRate.toString(), |
| 156 | + num_channels: frame.channels.toString(), |
| 157 | + }, |
| 158 | + }); |
| 159 | + this.pushedDuration = 0; |
| 160 | + } |
| 161 | + |
| 162 | + // frame.data is a Int16Array, write accepts a Uint8Array |
| 163 | + await this.streamWriter.write(new Uint8Array(frame.data.buffer)); |
| 164 | + this.pushedDuration += frame.samplesPerChannel / frame.sampleRate; |
| 165 | + } |
| 166 | + |
| 167 | + flush(): void { |
| 168 | + super.flush(); |
| 169 | + |
| 170 | + if (this.streamWriter === undefined || !this.started) { |
| 171 | + return; |
| 172 | + } |
| 173 | + |
| 174 | + this.streamWriter.close().finally(() => { |
| 175 | + this.streamWriter = undefined; |
| 176 | + }); |
| 177 | + } |
| 178 | + |
| 179 | + clearBuffer(): void { |
| 180 | + if (!this.started) return; |
| 181 | + |
| 182 | + this.room.localParticipant!.performRpc({ |
| 183 | + destinationIdentity: this.destinationIdentity, |
| 184 | + method: RPC_CLEAR_BUFFER, |
| 185 | + payload: '', |
| 186 | + }); |
| 187 | + } |
| 188 | + |
| 189 | + private handlePlaybackFinished(data: RpcInvocationData): string { |
| 190 | + if (data.callerIdentity !== this.destinationIdentity) { |
| 191 | + this.#logger.warn( |
| 192 | + { |
| 193 | + callerIdentity: data.callerIdentity, |
| 194 | + destinationIdentity: this.destinationIdentity, |
| 195 | + }, |
| 196 | + 'playback finished event received from unexpected participant', |
| 197 | + ); |
| 198 | + return 'reject'; |
| 199 | + } |
| 200 | + |
| 201 | + this.#logger.info( |
| 202 | + { |
| 203 | + callerIdentity: data.callerIdentity, |
| 204 | + }, |
| 205 | + 'playback finished event received', |
| 206 | + ); |
| 207 | + |
| 208 | + const playbackFinishedEvent = JSON.parse(data.payload) as PlaybackFinishedEvent; |
| 209 | + this.onPlaybackFinished(playbackFinishedEvent); |
| 210 | + return 'ok'; |
| 211 | + } |
| 212 | + |
| 213 | + static registerPlaybackFinishedRpc({ |
| 214 | + room, |
| 215 | + callerIdentity, |
| 216 | + handler, |
| 217 | + }: { |
| 218 | + room: Room; |
| 219 | + callerIdentity: string; |
| 220 | + handler: (data: RpcInvocationData) => string; |
| 221 | + }) { |
| 222 | + DataStreamAudioOutput._playbackFinishedHandlers[callerIdentity] = handler; |
| 223 | + |
| 224 | + if (DataStreamAudioOutput._playbackFinishedRpcRegistered) { |
| 225 | + return; |
| 226 | + } |
| 227 | + |
| 228 | + const rpcHandler = async (data: RpcInvocationData): Promise<string> => { |
| 229 | + const handler = DataStreamAudioOutput._playbackFinishedHandlers[data.callerIdentity]; |
| 230 | + if (!handler) { |
| 231 | + log().warn( |
| 232 | + { |
| 233 | + callerIdentity: data.callerIdentity, |
| 234 | + expectedIdentities: Object.keys(DataStreamAudioOutput._playbackFinishedHandlers), |
| 235 | + }, |
| 236 | + 'playback finished event received from unexpected participant', |
| 237 | + ); |
| 238 | + |
| 239 | + return 'reject'; |
| 240 | + } |
| 241 | + return handler(data); |
| 242 | + }; |
| 243 | + |
| 244 | + room.localParticipant?.registerRpcMethod(RPC_PLAYBACK_FINISHED, rpcHandler); |
| 245 | + DataStreamAudioOutput._playbackFinishedRpcRegistered = true; |
| 246 | + } |
| 247 | +} |
0 commit comments