Files
faq_chatbot_frontend/src/app/services/voice-stream/voice-stream.service.ts
T
PeymanHonarjoo f6ce43453a feat(voice): implement real-time voice-to-voice streaming engine
Introduce a complete low-level audio processing and streaming pipeline
for live voice conversations.

- Implement `VoiceAudioEngine` using `AudioWorklet` for low-latency
  PCM16 capture and playback.
- Add `pcm-capture` and `pcm-playback` worklets for high-performance
  audio processing outside the main thread.
- Implement `VoiceStreamService` to manage the voice-to-voice state
  machine (LISTENING, PROCESSING, SPEAKING, INTERRUPTED).
- Add `VoiceApiService` for managing conversation and session lifecycle
  via REST and WebSocket.
- Create `VoiceStreamPanelComponent` to display real-time transcripts,
  status indicators, and the animated voice orb.
- Integrate voice streaming into the `AiChatInputComponent` with
  support for seamless UI transitions between text and voice modes.
2026-10-08 12:52:29 +03:30

631 lines
22 KiB
TypeScript

import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
import { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service';
import { VoiceApiError, VoiceApiService } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
import {
VOICE_STREAM_CONFIG,
VoiceConnection,
VoiceMessage,
VoiceServerEvent,
VoiceSessionEnd,
VoiceStreamState,
} from './voice-stream.types';
export type VoiceStartFailure =
| 'cancelled'
| 'unsupported'
| 'mic'
| 'engine'
| 'auth'
| 'unavailable'
| 'api'
| 'connect';
export type VoiceStartResult =
| { ok: true }
| { ok: false; reason: VoiceStartFailure; message: string };
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
type ErrorEvent = Extract<VoiceServerEvent, { type: 'error' }>;
const MESSAGES = {
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).',
micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
engine: 'راه‌اندازی پردازشگر صوتی ناموفق بود. صفحه را دوباره بارگذاری کنید.',
auth: 'نشست شما منقضی شده است. دوباره وارد شوید.',
voiceDisabled: 'گفتگوی صوتی برای این سامانه فعال نیست.',
rateLimited: 'تعداد درخواست‌ها زیاد است. کمی بعد دوباره تلاش کنید.',
unavailable: 'سرویس موقتاً در دسترس نیست. کمی بعد دوباره تلاش کنید.',
sessionUnusable: 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.',
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
conversationTitle: 'گفتگوی صوتی',
} as const;
/** How long INTERRUPTED stays visible before returning to LISTENING. */
const INTERRUPTED_FLASH_MS = 150;
/** How long a retryable server error stays on screen. */
const ERROR_BANNER_MS = 6000;
/**
* One live voice call against the MVP API (mvp_ui_api_catalog.md §6):
*
* mic ─▶ engine ─▶ PCM16 16 kHz frames ─▶ WSS ─▶ server
* server ─▶ session_ready / transcript / sources / turn_interrupted / error (JSON)
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
*
* Start: mic permission → GET /me (CSRF) → GET /configuration (voice enabled?)
* → POST /conversations → POST /voice/sessions → WSS stream_path → `session_ready`.
* End: close the socket, stop audio, POST /voice/sessions/{id}/close.
*
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes playback.
* (The contract has no client→server interrupt message.)
*/
@Injectable({ providedIn: 'root' })
export class VoiceStreamService {
private readonly ngZone = inject(NgZone);
private readonly engine = inject(VoiceAudioEngine);
private readonly api = inject(VoiceApiService);
private readonly config = inject(VOICE_STREAM_CONFIG);
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
readonly state = signal<VoiceStreamState>('IDLE');
readonly connection = signal<VoiceConnection>('disconnected');
readonly messages = signal<VoiceMessage[]>([]);
readonly muted = signal(false);
/** Non-fatal, retryable server error to show as a banner (e.g. SEARCH_TIMEOUT). */
readonly streamError = signal<string | null>(null);
/** true from the moment start() is called until the call is over. */
readonly isOpen = computed(() => this.connection() !== 'disconnected');
readonly isSupported = this.engine.isSupported && typeof WebSocket !== 'undefined';
/** Emits once for every call that reached `connected` (normal end or failure). */
readonly sessionEnded$ = new Subject<VoiceSessionEnd>();
private transport: VoiceTransport | null = null;
private remote: { sessionId: string; conversationId: string; csrf: string } | null = null;
private session = 0;
private streaming = false;
private turnEnded = false;
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null;
private errorTimer: ReturnType<typeof setTimeout> | null = null;
private readyWaiter: {
resolve: () => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout>;
} | null = null;
private lastConversationId: string | null = null;
// ---- public API -----------------------------------------------------------
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
if (this.isOpen()) return this.failure('cancelled', '');
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
const session = ++this.session;
const stale = (): boolean => session !== this.session;
this.messages.set([]);
this.muted.set(false);
this.clearError();
this.resetTurnFlags();
this.lastConversationId = null;
this.state.set('IDLE');
this.connection.set('connecting');
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
try {
await this.engine.start({
onFrame: (pcm) => this.onMicFrame(pcm),
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()),
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
});
} catch (err) {
return this.abortStart(session, this.mapEngineError(err));
}
if (stale()) {
// Cancelled while the permission prompt / worklets were loading: release what was just opened.
if (!this.isOpen()) this.engine.stop();
return this.failure('cancelled', '');
}
// 2) REST: identity/CSRF → capabilities → conversation → voice session
let streamPath: string;
try {
const me = await this.api.me();
if (stale()) return this.failure('cancelled', '');
const configuration = await this.api.configuration();
if (stale()) return this.failure('cancelled', '');
if (!configuration.capabilities.voice) {
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
}
const conversation = await this.api.createConversation(me.csrf_token, MESSAGES.conversationTitle);
if (stale()) return this.failure('cancelled', '');
const voiceSession = await this.api.createVoiceSession(me.csrf_token, conversation.id);
const remote = {
sessionId: voiceSession.session_id,
conversationId: conversation.id,
csrf: me.csrf_token,
};
if (stale()) {
this.closeRemote(remote); // cancelled after the server already reserved the session
return this.failure('cancelled', '');
}
this.remote = remote;
this.lastConversationId = conversation.id;
streamPath = voiceSession.stream_path;
} catch (err) {
if (stale()) return this.failure('cancelled', '');
return this.abortStart(session, this.mapApiError(err));
}
// 3) WebSocket (created outside the zone so socket events don't trigger change detection)
const transport = this.createTransport(this.api.streamUrl(streamPath));
this.transport = transport;
try {
await this.ngZone.runOutsideAngular(() =>
transport.connect({
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session),
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
}),
);
} catch {
if (stale()) return this.failure('cancelled', '');
return this.abortStart(session, { reason: 'connect', message: MESSAGES.connect });
}
if (stale()) return this.failure('cancelled', '');
// 4) wait for `session_ready` (the server pushes it; the client sends no handshake)
try {
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('ready-timeout')),
this.config.connectTimeoutMs,
);
this.readyWaiter = { resolve, reject, timer };
});
} catch (err) {
if (stale()) return this.failure('cancelled', '');
const badFormat = err instanceof Error && err.message === 'format';
return this.abortStart(session, {
reason: 'connect',
message: badFormat ? MESSAGES.badFormat : MESSAGES.connect,
});
}
if (stale()) return this.failure('cancelled', '');
this.connection.set('connected');
this.state.set('LISTENING');
this.streaming = true;
return { ok: true };
}
/** User ends the call. Safe to call at any time. */
end(): void {
if (!this.isOpen()) return;
this.finishSession();
}
toggleMute(): void {
const next = !this.muted();
this.muted.set(next);
this.engine.setMuted(next); // frames keep flowing (silent), so the server never sees a gap
}
/** Level (0..1) the orb should follow: assistant audio while speaking, otherwise the mic. */
orbLevel(): number {
if (this.state() === 'SPEAKING') return this.engine.outputLevel();
return this.muted() ? 0 : this.engine.inputLevel();
}
dismissError(): void {
this.clearError();
}
/** Component teardown: release everything without emitting events. */
dispose(): void {
this.rejectReady();
this.teardown();
}
// ---- audio from the microphone (outside the zone) --------------------------
private onMicFrame(pcm: ArrayBuffer): void {
if (this.streaming) this.transport?.sendAudio(pcm);
}
// ---- audio from the server (outside the zone) ------------------------------
private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return;
this.engine.enqueuePlayback(chunk);
this.clearSettleTimer();
if (this.state() !== 'SPEAKING') {
this.ngZone.run(() => {
if (this.interruptTimer) {
clearTimeout(this.interruptTimer);
this.interruptTimer = null;
}
this.state.set('SPEAKING');
});
}
}
// ---- JSON events from the server -------------------------------------------
private onServerEvent(event: VoiceServerEvent, session: number): void {
if (session !== this.session) return;
switch (event.type) {
case 'session_ready': {
const { input_audio: input, output_audio: output } = event;
const compatible =
input.encoding === 'pcm_s16le' &&
output.encoding === 'pcm_s16le' &&
input.channels === 1 &&
output.channels === 1 &&
input.sample_rate === this.config.inputSampleRate &&
output.sample_rate === this.config.outputSampleRate;
if (compatible) this.resolveReady();
else this.rejectReady(new Error('format'));
break;
}
case 'transcript':
this.onTranscript(event);
break;
case 'sources':
this.upsertSources(event);
break;
case 'turn_interrupted':
this.onTurnInterrupted(event.turn_ref);
break;
case 'error':
this.onServerError(event, session);
break;
}
}
private onTranscript(event: TranscriptEvent): void {
this.upsertTranscript(event);
if (event.status === 'interrupted') {
this.onTurnInterrupted(event.turn_ref);
return;
}
if (event.role === 'user') {
// The user finished their sentence; the assistant is working on it.
if (event.status === 'completed' && this.state() === 'LISTENING') {
this.state.set('PROCESSING');
}
return;
}
if (event.status === 'completed') {
// All text for this turn is out. Play what is buffered, then return to LISTENING.
this.turnEnded = true;
this.engine.flushPlayback();
}
}
/** Server-side barge-in: the user spoke over the assistant. */
private onTurnInterrupted(turnRef: string): void {
this.engine.clearPlayback(); // empty the playback queue immediately
this.turnEnded = false;
this.clearSettleTimer();
this.markInterrupted(turnRef);
const state = this.state();
if (state === 'SPEAKING' || state === 'PROCESSING') {
this.state.set('INTERRUPTED');
if (this.interruptTimer) clearTimeout(this.interruptTimer);
this.interruptTimer = setTimeout(() => {
this.interruptTimer = null;
if (this.state() === 'INTERRUPTED') this.state.set('LISTENING');
}, INTERRUPTED_FLASH_MS);
}
}
private onServerError(event: ErrorEvent, session: number): void {
const { message, retryable, code } = event.error;
console.warn('VoiceStreamService: server error', code, event.error.request_id);
if (!retryable) {
this.failSession(message || MESSAGES.server, session);
return;
}
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
this.engine.clearPlayback();
this.turnEnded = false;
this.clearSettleTimer();
this.finalizeAssistant();
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
this.showError(message || MESSAGES.server);
}
// ---- end of an assistant turn ----------------------------------------------
private onPlaybackIdle(): void {
const state = this.state();
if (state !== 'SPEAKING' && state !== 'PROCESSING') return;
if (this.turnEnded) {
this.finishTurn();
} else if (state === 'SPEAKING') {
// The buffer drained but no `completed` transcript arrived (yet). If no more audio comes, the turn is over.
this.clearSettleTimer();
this.settleTimer = setTimeout(() => {
this.settleTimer = null;
if (this.state() === 'SPEAKING') this.finishTurn();
}, this.config.settleMs);
}
}
private finishTurn(): void {
this.turnEnded = false;
this.clearSettleTimer();
this.finalizeAssistant();
this.state.set('LISTENING');
}
// ---- transcript ------------------------------------------------------------
private upsertTranscript(event: TranscriptEvent): void {
const id = `${event.turn_ref}:${event.role}`;
const final = event.status !== 'partial';
const interrupted = event.status === 'interrupted';
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
if (index === -1) {
if (!event.text.trim()) return list;
return [
...list,
{
id,
turnRef: event.turn_ref,
role: event.role,
text: event.text,
final,
interrupted: interrupted || undefined,
},
];
}
const current = list[index];
if (current.interrupted && !interrupted) return list; // late partial for a cut-off message
const copy = [...list];
copy[index] = {
...current,
text: this.mergeTranscriptText(current.text, event),
final: current.final || final,
interrupted: current.interrupted || interrupted || undefined,
};
return copy;
});
}
/**
* The catalog does not say whether a `partial` carries the full text so far or only the new fragment,
* so both are handled:
* - `completed` with text → the final full text replaces whatever was accumulated
* - text that starts with what we already have → cumulative, replace
* - anything else → a fragment, append as-is (fragments carry their own spacing)
* If the backend turns out to use only one style, this is the single place to simplify.
*/
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
const next = event.text;
if (!next) return previous;
if (!previous || event.status === 'completed') return next;
if (next.startsWith(previous)) return next;
return previous + next;
}
private upsertSources(event: SourcesEvent): void {
const id = `${event.turn_ref}:assistant`;
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
const current: VoiceMessage =
index === -1
? { id, turnRef: event.turn_ref, role: 'assistant', text: '', final: false }
: list[index];
const sources = [...(current.sources ?? [])];
for (const source of event.sources) {
if (!sources.some((s) => s.source_ref === source.source_ref && s.chunk_id === source.chunk_id)) {
sources.push(source);
}
}
const next = { ...current, sources };
if (index === -1) return [...list, next];
const copy = [...list];
copy[index] = next;
return copy;
});
}
private markInterrupted(turnRef: string): void {
const id = `${turnRef}:assistant`;
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
if (index === -1 || list[index].interrupted) return list;
const copy = [...list];
copy[index] = { ...copy[index], final: true, interrupted: true };
return copy;
});
}
private finalizeAssistant(): void {
this.messages.update((list) =>
list.some((m) => m.role === 'assistant' && !m.final)
? list.map((m) => (m.role === 'assistant' && !m.final ? { ...m, final: true } : m))
: list,
);
}
private finalizeAll(): void {
this.messages.update((list) =>
list.some((m) => !m.final) ? list.map((m) => (m.final ? m : { ...m, final: true })) : list,
);
}
// ---- lifecycle -------------------------------------------------------------
private failSession(message: string, session: number): void {
if (session !== this.session || !this.isOpen()) return;
this.finishSession(message);
}
private finishSession(error?: string): void {
const wasConnected = this.connection() === 'connected';
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
this.rejectReady();
this.finalizeAll();
const messages = this.messages();
this.teardown();
if (wasConnected) this.sessionEnded$.next({ conversationId, messages, error });
}
private abortStart(
session: number,
failure: { reason: VoiceStartFailure; message: string },
): VoiceStartResult {
if (session === this.session) this.teardown();
return this.failure(failure.reason, failure.message);
}
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
private teardown(): void {
this.session++;
this.streaming = false;
this.resetTurnFlags();
this.clearSettleTimer();
this.clearError();
if (this.interruptTimer) {
clearTimeout(this.interruptTimer);
this.interruptTimer = null;
}
const transport = this.transport;
this.transport = null;
transport?.close();
this.engine.stop();
// V04: tell the server the session is over (best effort).
const remote = this.remote;
this.remote = null;
if (remote) this.closeRemote(remote);
this.connection.set('disconnected');
this.state.set('IDLE');
this.muted.set(false);
}
private closeRemote(remote: { sessionId: string; csrf: string }): void {
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
/* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */
});
}
private resetTurnFlags(): void {
this.turnEnded = false;
}
private clearSettleTimer(): void {
if (this.settleTimer) {
clearTimeout(this.settleTimer);
this.settleTimer = null;
}
}
private showError(message: string): void {
this.clearError();
this.streamError.set(message);
this.errorTimer = setTimeout(() => this.clearError(), ERROR_BANNER_MS);
}
private clearError(): void {
if (this.errorTimer) {
clearTimeout(this.errorTimer);
this.errorTimer = null;
}
if (this.streamError() !== null) this.streamError.set(null);
}
private resolveReady(): void {
const waiter = this.readyWaiter;
this.readyWaiter = null;
if (!waiter) return;
clearTimeout(waiter.timer);
waiter.resolve();
}
private rejectReady(error: Error = new Error('cancelled')): void {
const waiter = this.readyWaiter;
this.readyWaiter = null;
if (!waiter) return;
clearTimeout(waiter.timer);
waiter.reject(error);
}
// ---- error mapping ---------------------------------------------------------
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (err instanceof MicrophoneError) {
if (err.code === 'unsupported') return { reason: 'unsupported', message: MESSAGES.unsupported };
return {
reason: 'mic',
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
};
}
if (err instanceof VoiceEngineError && err.code === 'unsupported') {
return { reason: 'unsupported', message: MESSAGES.unsupported };
}
return { reason: 'engine', message: MESSAGES.engine };
}
/** Maps the catalog's error codes (§7) to a user-facing Persian message. */
private mapApiError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (!(err instanceof VoiceApiError)) return { reason: 'api', message: MESSAGES.api };
switch (err.code) {
case 'AUTH_REQUIRED':
return { reason: 'auth', message: MESSAGES.auth };
case 'RATE_LIMITED':
return { reason: 'api', message: MESSAGES.rateLimited };
case 'DEPENDENCY_UNAVAILABLE':
return { reason: 'unavailable', message: MESSAGES.unavailable };
case 'LIVE_SESSION_UNUSABLE':
return { reason: 'api', message: MESSAGES.sessionUnusable };
case 'NETWORK':
return { reason: 'connect', message: MESSAGES.connect };
default:
return { reason: 'api', message: MESSAGES.api };
}
}
private failure(reason: VoiceStartFailure, message: string): VoiceStartResult {
return { ok: false, reason, message };
}
}