@raucheacho/phono-web 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/assets/goul-audio.wasm +0 -0
- package/assets/goul-ptt-worklets.js +256 -0
- package/dist/announcements.d.ts +23 -0
- package/dist/audio.d.ts +79 -0
- package/dist/client.d.ts +265 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1204 -0
- package/dist/phone.d.ts +110 -0
- package/dist/react.d.ts +13 -0
- package/dist/react.js +18 -0
- package/dist/realtime.d.ts +39 -0
- package/dist/talkie.d.ts +85 -0
- package/dist/tones.d.ts +14 -0
- package/dist/types.d.ts +284 -0
- package/dist/types.js +0 -0
- package/package.json +53 -4
- package/src/announcements.ts +57 -0
- package/src/audio.ts +313 -0
- package/src/client.ts +433 -0
- package/src/index.ts +13 -0
- package/src/phone.ts +340 -0
- package/src/react.ts +34 -0
- package/src/realtime.ts +174 -0
- package/src/talkie.ts +342 -0
- package/src/tones.ts +58 -0
- package/src/types.ts +339 -0
package/src/audio.ts
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* L'audio d'un appel Phono, dans le navigateur.
|
|
3
|
+
*
|
|
4
|
+
* Le même fil que les téléphones et le SDK Go : des trames goul-audio (Opus,
|
|
5
|
+
* 20 ms) sur un sujet Konet en mode multiplex. Capture, encodage, tampon et
|
|
6
|
+
* lecture vivent dans les worklets de `goul-ptt-worklets.js`, sur le fil
|
|
7
|
+
* audio. Ce fichier n'orchestre que le reste — le micro, le sujet, et l'état
|
|
8
|
+
* qu'une interface affiche.
|
|
9
|
+
*
|
|
10
|
+
* Deux façons de parler :
|
|
11
|
+
* - « ptt » : appuyer pour parler (barre d'espace), comme dans Goul. Chaque
|
|
12
|
+
* pression est un nouveau flux ; celui d'en face jette le retard du
|
|
13
|
+
* précédent.
|
|
14
|
+
* - « open » : micro ouvert, comme un téléphone.
|
|
15
|
+
*
|
|
16
|
+
* Contrairement au push-to-talk de Goul, il n'y a pas de floor : en multiplex,
|
|
17
|
+
* les deux côtés peuvent parler en même temps. L'écho est l'affaire de
|
|
18
|
+
* l'annulation d'écho du navigateur (`echoCancellation: true`).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { KonetClient } from "@raucheacho/konet-js";
|
|
22
|
+
|
|
23
|
+
import type { AudioAssets } from "./client";
|
|
24
|
+
import type { AudioCredentials } from "./types";
|
|
25
|
+
|
|
26
|
+
const AUDIO_EVENT = "a";
|
|
27
|
+
const TARGET_MS = 120;
|
|
28
|
+
const MAX_MS = 400;
|
|
29
|
+
const JOIN_TIMEOUT_MS = 8_000;
|
|
30
|
+
/** Au-delà de ce silence, l'autre ne parle plus. */
|
|
31
|
+
const SPEAKING_HOLD_MS = 300;
|
|
32
|
+
/** En dessous, une trame est du silence (DTX). */
|
|
33
|
+
const VOICE_MIN_BYTES = 16;
|
|
34
|
+
|
|
35
|
+
export type TalkMode = "ptt" | "open";
|
|
36
|
+
|
|
37
|
+
export interface CallAudioSnapshot {
|
|
38
|
+
state: "idle" | "connecting" | "connected" | "denied" | "error";
|
|
39
|
+
mode: TalkMode;
|
|
40
|
+
/** Le micro part en ce moment. */
|
|
41
|
+
talking: boolean;
|
|
42
|
+
/** Micro coupé, en mode ouvert. */
|
|
43
|
+
muted: boolean;
|
|
44
|
+
/** L'autre parle (des trames arrivent). */
|
|
45
|
+
remoteSpeaking: boolean;
|
|
46
|
+
micReady: boolean;
|
|
47
|
+
error: string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type Listener = (s: CallAudioSnapshot) => void;
|
|
51
|
+
|
|
52
|
+
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
|
|
53
|
+
return Promise.race([
|
|
54
|
+
promise,
|
|
55
|
+
new Promise<T>((_, reject) => setTimeout(() => reject(new Error(message)), ms)),
|
|
56
|
+
]);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class CallAudio {
|
|
60
|
+
private listeners = new Set<Listener>();
|
|
61
|
+
private snapshot: CallAudioSnapshot;
|
|
62
|
+
|
|
63
|
+
private client: KonetClient | null = null;
|
|
64
|
+
private channel: ReturnType<KonetClient["channel"]> | null = null;
|
|
65
|
+
private context: AudioContext | null = null;
|
|
66
|
+
private micStream: MediaStream | null = null;
|
|
67
|
+
private capture: AudioWorkletNode | null = null;
|
|
68
|
+
private playback: AudioWorkletNode | null = null;
|
|
69
|
+
private wasmBytes: ArrayBuffer | null = null;
|
|
70
|
+
private speakingTimer: ReturnType<typeof setTimeout> | null = null;
|
|
71
|
+
private stopped = false;
|
|
72
|
+
|
|
73
|
+
constructor(
|
|
74
|
+
private readonly creds: AudioCredentials,
|
|
75
|
+
mode: TalkMode = "open",
|
|
76
|
+
private readonly assets: AudioAssets = {}
|
|
77
|
+
) {
|
|
78
|
+
this.snapshot = {
|
|
79
|
+
state: "idle",
|
|
80
|
+
mode,
|
|
81
|
+
talking: false,
|
|
82
|
+
muted: false,
|
|
83
|
+
remoteSpeaking: false,
|
|
84
|
+
micReady: false,
|
|
85
|
+
error: null,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
subscribe(listener: Listener): () => void {
|
|
90
|
+
this.listeners.add(listener);
|
|
91
|
+
listener(this.snapshot);
|
|
92
|
+
return () => this.listeners.delete(listener);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
get state() {
|
|
96
|
+
return this.snapshot;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Rejoint l'audio et commence à écouter. Doit être appelé depuis un geste
|
|
101
|
+
* (le clic qui décroche ou qui appelle) : c'est ce qui autorise le
|
|
102
|
+
* navigateur à démarrer le son et à demander le micro.
|
|
103
|
+
*/
|
|
104
|
+
async start(): Promise<void> {
|
|
105
|
+
if (this.stopped) return;
|
|
106
|
+
this.emit({ state: "connecting", error: null });
|
|
107
|
+
|
|
108
|
+
try {
|
|
109
|
+
await this.buildPlayback();
|
|
110
|
+
|
|
111
|
+
const client = new KonetClient(this.creds.url, { token: this.creds.token }).connect();
|
|
112
|
+
this.client = client;
|
|
113
|
+
const channel = client.channel(this.creds.topic, { binaryMode: "multiplex" });
|
|
114
|
+
this.channel = channel;
|
|
115
|
+
|
|
116
|
+
channel.on(this.creds.event || AUDIO_EVENT, (data) => {
|
|
117
|
+
const frame = data as Uint8Array;
|
|
118
|
+
this.playback?.port.postMessage({ type: "frame", frame });
|
|
119
|
+
// 6 octets d'en-tête, puis l'Opus. Un silence en DTX tient en un ou
|
|
120
|
+
// deux octets ; la parole en fait des dizaines.
|
|
121
|
+
if (frame.length > VOICE_MIN_BYTES) this.markRemoteSpeaking();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
await withTimeout(
|
|
125
|
+
channel.subscribe(),
|
|
126
|
+
JOIN_TIMEOUT_MS,
|
|
127
|
+
"L'appel n'a pas répondu. Vérifiez que le temps réel est joignable."
|
|
128
|
+
);
|
|
129
|
+
await this.context?.resume();
|
|
130
|
+
|
|
131
|
+
// Le micro maintenant : le geste qui a lancé l'appel autorise la demande.
|
|
132
|
+
await this.ensureCapture();
|
|
133
|
+
this.emit({ state: "connected" });
|
|
134
|
+
if (this.snapshot.mode === "open") this.startTalking();
|
|
135
|
+
} catch (error) {
|
|
136
|
+
this.emit({
|
|
137
|
+
state: this.isPermissionDenied(error) ? "denied" : "error",
|
|
138
|
+
error: this.describe(error),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Appuyer pour parler : début. */
|
|
144
|
+
press(): void {
|
|
145
|
+
if (this.snapshot.mode !== "ptt" || this.snapshot.state !== "connected") return;
|
|
146
|
+
this.startTalking();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Appuyer pour parler : fin. */
|
|
150
|
+
release(): void {
|
|
151
|
+
if (this.snapshot.mode !== "ptt") return;
|
|
152
|
+
this.stopTalking();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
setMode(mode: TalkMode): void {
|
|
156
|
+
this.stopTalking();
|
|
157
|
+
this.emit({ mode, muted: false });
|
|
158
|
+
if (mode === "open" && this.snapshot.state === "connected") this.startTalking();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Couper le micro, en mode ouvert. */
|
|
162
|
+
setMuted(muted: boolean): void {
|
|
163
|
+
if (this.snapshot.mode !== "open") return;
|
|
164
|
+
this.emit({ muted });
|
|
165
|
+
if (muted) this.stopTalking();
|
|
166
|
+
else this.startTalking();
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
stop(): void {
|
|
170
|
+
this.stopped = true;
|
|
171
|
+
if (this.speakingTimer) clearTimeout(this.speakingTimer);
|
|
172
|
+
this.capture?.port.postMessage({ type: "stop" });
|
|
173
|
+
this.playback?.port.postMessage({ type: "close" });
|
|
174
|
+
this.capture?.disconnect();
|
|
175
|
+
this.playback?.disconnect();
|
|
176
|
+
this.micStream?.getTracks().forEach((t) => t.stop());
|
|
177
|
+
void this.context?.close();
|
|
178
|
+
this.client?.disconnect();
|
|
179
|
+
this.client = null;
|
|
180
|
+
this.channel = null;
|
|
181
|
+
this.context = null;
|
|
182
|
+
this.micStream = null;
|
|
183
|
+
this.capture = null;
|
|
184
|
+
this.playback = null;
|
|
185
|
+
this.listeners.clear();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private startTalking(): void {
|
|
189
|
+
if (!this.capture || this.snapshot.talking) return;
|
|
190
|
+
// Un identifiant de flux par prise de parole : le tampon d'en face repart
|
|
191
|
+
// de zéro au lieu d'hériter du retard de la précédente.
|
|
192
|
+
const streamId = (Math.random() * 0xffffffff) >>> 0;
|
|
193
|
+
this.capture.port.postMessage({ type: "start", streamId, bitrate: 24_000 });
|
|
194
|
+
this.emit({ talking: true });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private stopTalking(): void {
|
|
198
|
+
if (!this.snapshot.talking) return;
|
|
199
|
+
this.capture?.port.postMessage({ type: "stop" });
|
|
200
|
+
this.emit({ talking: false });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private markRemoteSpeaking(): void {
|
|
204
|
+
if (!this.snapshot.remoteSpeaking) this.emit({ remoteSpeaking: true });
|
|
205
|
+
if (this.speakingTimer) clearTimeout(this.speakingTimer);
|
|
206
|
+
// Pas de « end » au tampon ici : en micro ouvert, les trames de silence
|
|
207
|
+
// continuent d'arriver dans le même flux, et le couper ferait rejouer le
|
|
208
|
+
// tampon de zéro à chaque pause.
|
|
209
|
+
this.speakingTimer = setTimeout(() => this.emit({ remoteSpeaking: false }), SPEAKING_HOLD_MS);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Tout ce qu'il faut pour entendre. Aucune permission. */
|
|
213
|
+
private async buildPlayback(): Promise<void> {
|
|
214
|
+
// Le navigateur ne donne le son temps réel (AudioWorklet) et le micro qu'à
|
|
215
|
+
// une page sécurisée : https://, ou localhost. Ailleurs (http://192.168…),
|
|
216
|
+
// ils n'existent tout simplement pas — on le dit, plutôt que de planter.
|
|
217
|
+
if (typeof window !== "undefined" && !window.isSecureContext) {
|
|
218
|
+
throw new Error(
|
|
219
|
+
"Le navigateur n'autorise l'audio que sur une page sécurisée : ouvrez cette page en https:// ou sur localhost."
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
const context = new AudioContext({ sampleRate: 48_000 });
|
|
223
|
+
if (!context.audioWorklet) {
|
|
224
|
+
void context.close();
|
|
225
|
+
throw new Error("Ce navigateur ne permet pas l'audio temps réel (AudioWorklet).");
|
|
226
|
+
}
|
|
227
|
+
this.context = context;
|
|
228
|
+
await context.audioWorklet.addModule(this.assets.workletUrl ?? "/goul-ptt-worklets.js");
|
|
229
|
+
|
|
230
|
+
// Les octets et non un module compilé : un WebAssembly.Module ne passe
|
|
231
|
+
// pas la frontière d'un worklet (voir Goul). Chaque worklet compile le sien.
|
|
232
|
+
const res = await fetch(this.assets.wasmUrl ?? "/goul-audio.wasm");
|
|
233
|
+
if (!res.ok) throw new Error("goul-audio.wasm introuvable : voir « Le cœur audio » dans le README de @raucheacho/phono-web.");
|
|
234
|
+
const bytes = await res.arrayBuffer();
|
|
235
|
+
this.wasmBytes = bytes;
|
|
236
|
+
|
|
237
|
+
const playback = new AudioWorkletNode(context, "goul-playback", {
|
|
238
|
+
numberOfInputs: 0,
|
|
239
|
+
numberOfOutputs: 1,
|
|
240
|
+
outputChannelCount: [1],
|
|
241
|
+
});
|
|
242
|
+
await this.initWorklet(playback, bytes.slice(0));
|
|
243
|
+
playback.connect(context.destination);
|
|
244
|
+
playback.port.postMessage({ type: "open", targetMs: TARGET_MS, maxMs: MAX_MS });
|
|
245
|
+
this.playback = playback;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Tout ce qu'il faut pour parler. Le seul endroit où le micro est demandé. */
|
|
249
|
+
private async ensureCapture(): Promise<void> {
|
|
250
|
+
const context = this.context;
|
|
251
|
+
const bytes = this.wasmBytes;
|
|
252
|
+
if (this.capture || !context || !bytes) return;
|
|
253
|
+
|
|
254
|
+
this.micStream = await navigator.mediaDevices.getUserMedia({
|
|
255
|
+
audio: {
|
|
256
|
+
echoCancellation: true,
|
|
257
|
+
noiseSuppression: true,
|
|
258
|
+
autoGainControl: true,
|
|
259
|
+
channelCount: 1,
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
const capture = new AudioWorkletNode(context, "goul-capture", {
|
|
264
|
+
numberOfInputs: 1,
|
|
265
|
+
numberOfOutputs: 0,
|
|
266
|
+
channelCount: 1,
|
|
267
|
+
});
|
|
268
|
+
await this.initWorklet(capture, bytes.slice(0));
|
|
269
|
+
capture.port.onmessage = ({ data }) => {
|
|
270
|
+
if (data.type === "frame") {
|
|
271
|
+
try {
|
|
272
|
+
this.channel?.sendBinary(this.creds.event || AUDIO_EVENT, data.frame as Uint8Array);
|
|
273
|
+
} catch {
|
|
274
|
+
/* pas encore rejoint, ou socket tombée : ces 20 ms sont perdues */
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
context.createMediaStreamSource(this.micStream).connect(capture);
|
|
279
|
+
this.capture = capture;
|
|
280
|
+
this.emit({ micReady: true });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private initWorklet(node: AudioWorkletNode, bytes: ArrayBuffer): Promise<void> {
|
|
284
|
+
return new Promise((resolve, reject) => {
|
|
285
|
+
const timer = setTimeout(() => reject(new Error("Le cœur audio n'a pas démarré.")), 5_000);
|
|
286
|
+
node.port.onmessage = ({ data }) => {
|
|
287
|
+
if (data.type === "ready") {
|
|
288
|
+
clearTimeout(timer);
|
|
289
|
+
resolve();
|
|
290
|
+
} else if (data.type === "error") {
|
|
291
|
+
clearTimeout(timer);
|
|
292
|
+
reject(new Error(data.message ?? "Le cœur audio a refusé de démarrer."));
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
node.port.postMessage({ type: "init", bytes }, [bytes]);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private isPermissionDenied(error: unknown): boolean {
|
|
300
|
+
return error instanceof DOMException && error.name === "NotAllowedError";
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private describe(error: unknown): string {
|
|
304
|
+
if (this.isPermissionDenied(error)) return "Micro refusé par le navigateur.";
|
|
305
|
+
return error instanceof Error ? error.message : "Erreur inconnue.";
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private emit(patch: Partial<CallAudioSnapshot>): void {
|
|
309
|
+
if (this.stopped && patch.state === undefined) return;
|
|
310
|
+
this.snapshot = { ...this.snapshot, ...patch };
|
|
311
|
+
this.listeners.forEach((l) => l(this.snapshot));
|
|
312
|
+
}
|
|
313
|
+
}
|