neuroniun 0.2.0 → 0.7.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.
@@ -0,0 +1,366 @@
1
+ // O AGENTE FALA na sala do N-Call (spec docs/specs/1-abertas/20261121-ncall-agentes.md §4-§5, F2).
2
+ // Regra pura, sem LiveKit: quem usa (ncall.js) injeta `chamar` (flows abertos com o token da bash),
3
+ // `publica` (dado da sala no topico neuroniun.sala) e `toca` (voz como trilha; devolve {parar()} e a
4
+ // promessa `fim`). Assim os testes rodam com servidor e sala falsos.
5
+ //
6
+ // - CHAMADO pelo nome/apelido/@apelido -> rea_pensar(chamado) -> texto no topico (fala_agente) + voz.
7
+ // - ALGO UTIL (de vez em quando, nunca a cada fala) -> rea_pensar(util); se a IA disser `mao`, levanta a
8
+ // mao (protocolo do hn_ncall: {"t":"mao","alvo":<identidade>}) e so fala quando recebe a vez ou e chamado.
9
+ // - DUVIDA -> uma pergunta por vez: outra so depois que alguem falar de novo.
10
+ // - INTERRUPCAO: outra pessoa comecou a falar enquanto a voz toca -> para a voz NA HORA.
11
+ // - AGENTE <-> AGENTE: fala_agente de outro agente que chama este -> rea_rodada (conta no servidor) e
12
+ // rea_pensar(rodada); esgotou -> rea_pensar(resumo) uma vez e para de responder naquele pedido.
13
+ // - TETO da reuniao (servidor diz teto_reuniao ou sair) -> avisa e pede para sair.
14
+ // - A SOS (dono, 03/12/2026; spec 20261203-agente-ligar-resposta-rapida §5): na sala so o agente e UMA pessoa ->
15
+ // toda fala e para o agente, sem precisar do nome; ele espera ~1,5 s sem voz humana (nunca fala por cima) e
16
+ // responde. EM GRUPO (2+ pessoas) -> nunca fala sem a vez: "algo util" que viria como fala vira MAO levantada;
17
+ // ser chamado pelo nome = receber a vez.
18
+ // - NA HORA: chamado (ou a sos) -> {"t":"pensando","alvo":<identidade>,"on":true} no topico antes de ir ao
19
+ // servidor (o app mostra "pensando…" no ladrilho); on:false quando termina.
20
+ import { foiChamado } from './ncall_regra.js';
21
+
22
+ export const TOPICO_DA_SALA = 'neuroniun.sala';
23
+ export const TAMANHO_MAXIMO = 2048;
24
+
25
+ const TEXTOS = {
26
+ pt: {
27
+ teto: 'Cheguei ao limite de créditos desta reunião. Vou sair agora; a ata fica com quem me convidou.',
28
+ tchau: 'Obrigado. Estou saindo da reunião; a ata fica com quem me convidou.',
29
+ },
30
+ en: {
31
+ teto: 'I reached the credit limit for this meeting. I am leaving now; the minutes go to whoever invited me.',
32
+ tchau: 'Thank you. I am leaving the meeting; the minutes go to whoever invited me.',
33
+ },
34
+ es: {
35
+ teto: 'Llegué al límite de créditos de esta reunión. Salgo ahora; el acta queda con quien me invitó.',
36
+ tchau: 'Gracias. Salgo de la reunión; el acta queda con quien me invitó.',
37
+ },
38
+ };
39
+
40
+ export function textoDoAgente(chave, idioma) {
41
+ const t = TEXTOS[idioma] || TEXTOS.pt;
42
+ return t[chave] || TEXTOS.pt[chave] || '';
43
+ }
44
+
45
+ /** Mensagem do topico em bytes; null se passaria do tamanho que o app le (2048). */
46
+ export function codifica(msg) {
47
+ const b = new TextEncoder().encode(JSON.stringify({ v: 1, ...msg }));
48
+ return b.length > TAMANHO_MAXIMO ? null : b;
49
+ }
50
+
51
+ /** Le os bytes de outra ponta; tolerante (lixo = null). */
52
+ export function decodifica(bytes) {
53
+ if (!bytes || bytes.length === 0 || bytes.length > TAMANHO_MAXIMO) return null;
54
+ try {
55
+ const m = JSON.parse(new TextDecoder().decode(bytes));
56
+ return m && typeof m === 'object' && !Array.isArray(m) ? m : null;
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+
62
+ /** Corta o texto para caber no topico (o app le ate 2048 bytes). */
63
+ export function cabeNoTopico(texto, max = 400) {
64
+ let t = String(texto || '').replace(/​/g, '').replace(/\s+/g, ' ').trim();
65
+ if (t.length > max) t = t.slice(0, max);
66
+ while (new TextEncoder().encode(t).length > 1500) t = t.slice(0, -10);
67
+ return t;
68
+ }
69
+
70
+ async function espera(chamar, flow, token, id, { tentativas = 20, intervaloMs = 1500, dorme } = {}) {
71
+ const dormir = dorme || ((ms) => new Promise((r) => setTimeout(r, ms)));
72
+ for (let i = 0; i < tentativas; i++) {
73
+ const r = await chamar(flow, [token, id]);
74
+ if (r?.ok === false) return r;
75
+ if (r?.ok === true && r.estado !== 'na_fila') return r;
76
+ if (i < tentativas - 1) await dormir(intervaloMs);
77
+ }
78
+ return { ok: false, codigo: 'tempo_esgotado' };
79
+ }
80
+
81
+ export class FalaDoAgente {
82
+ constructor(opcoes) {
83
+ const {
84
+ chamar,
85
+ publica,
86
+ toca,
87
+ tokenBash,
88
+ sala,
89
+ agente,
90
+ apelido,
91
+ nome = '',
92
+ identidade,
93
+ idioma = 'pt',
94
+ comVoz = true,
95
+ utilACadaMs = 45000,
96
+ utilMinFalas = 3,
97
+ agora = () => Date.now(),
98
+ aoSair = () => {},
99
+ log = () => {},
100
+ esperaOpts = {},
101
+ // Quantas PESSOAS (nao agentes) estao na sala agora; null = nao sei (comporta-se como em grupo).
102
+ pessoasNaSala = null,
103
+ silencioASosMs = 1500,
104
+ esperaASosMaxMs = 20000,
105
+ dormeMs = (ms) => new Promise((r) => setTimeout(r, ms)),
106
+ } = opcoes;
107
+ Object.assign(this, { chamar, publica, toca, tokenBash, sala, agente, apelido, identidade, idioma, comVoz });
108
+ this.nomes = [apelido, nome].filter(Boolean);
109
+ this.utilACadaMs = utilACadaMs;
110
+ this.utilMinFalas = utilMinFalas;
111
+ this.agora = agora;
112
+ this.aoSair = aoSair;
113
+ this.log = log;
114
+ this.esperaOpts = esperaOpts;
115
+ this.pessoasNaSala = pessoasNaSala;
116
+ this.silencioASosMs = silencioASosMs;
117
+ this.esperaASosMaxMs = esperaASosMaxMs;
118
+ this.dormeMs = dormeMs;
119
+ this.ultimaVozHumana = 0;
120
+ this.aguardandoSilencio = false;
121
+ this.tocando = null; // {parar(), fim}
122
+ this.maoLevantada = null; // {texto, id}
123
+ this.perguntaAberta = false;
124
+ this.falasDesdeUtil = 0;
125
+ this.ultimoUtil = agora();
126
+ this.ocupado = false;
127
+ this.encerrado = false;
128
+ this.esgotados = new Set();
129
+ this.interrupcoes = 0;
130
+ }
131
+
132
+ /** A sala tem so uma pessoa (e este agente). Sem a contagem, nao e a sos. */
133
+ aSos() {
134
+ if (typeof this.pessoasNaSala !== 'function') return false;
135
+ try {
136
+ return Number(this.pessoasNaSala()) === 1;
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+
142
+ /** O cliente avisa a cada quadro com voz humana (acima do limiar): o "a sos" espera o silencio. */
143
+ vozHumana() {
144
+ this.ultimaVozHumana = this.agora();
145
+ }
146
+
147
+ /** Uma fala HUMANA transcrita (rea_ouvir/rea_estado). */
148
+ async ouviu(fala) {
149
+ if (this.encerrado) return;
150
+ this.perguntaAberta = false;
151
+ this.falasDesdeUtil += 1;
152
+ if (foiChamado(fala.texto, this.nomes)) {
153
+ // Com a mao levantada, ser chamado e receber a vez: fala o que tinha.
154
+ if (this.maoLevantada) return this.recebeuAVez();
155
+ if (this.aSos()) return this.respondeASos();
156
+ return this.pensa('chamado');
157
+ }
158
+ // A sos, toda fala e para o agente (o padrao da voz: espera o silencio, nao interrompe, responde).
159
+ if (this.aSos()) return this.respondeASos();
160
+ const passou = this.agora() - this.ultimoUtil >= this.utilACadaMs;
161
+ if (passou && this.falasDesdeUtil >= this.utilMinFalas && !this.maoLevantada) {
162
+ this.ultimoUtil = this.agora();
163
+ this.falasDesdeUtil = 0;
164
+ return this.pensa('util');
165
+ }
166
+ }
167
+
168
+ /** Mensagem do topico neuroniun.sala (de outra ponta). */
169
+ async recebeuDado(m, remetente) {
170
+ if (this.encerrado || !m) return;
171
+ if (m.t === 'vez' && this.souEu(m.alvo)) return this.recebeuAVez();
172
+ if (m.t === 'fala_agente' && !this.souEu(m.alvo) && foiChamado(m.texto, this.nomes)) {
173
+ return this.respondeAgente(m, remetente);
174
+ }
175
+ }
176
+
177
+ /** A identidade da sala pode voltar em minusculas do nucleo (`a_ag_…`). */
178
+ souEu(alvo) {
179
+ return String(alvo || '').toLowerCase() === String(this.identidade || '').toLowerCase();
180
+ }
181
+
182
+ /** Alguem (pessoa) comecou a falar: a voz do agente para na hora. */
183
+ alguemFalando() {
184
+ if (!this.tocando) return false;
185
+ try {
186
+ this.tocando.parar();
187
+ } catch (e) {
188
+ this.log('parar_voz', e);
189
+ }
190
+ this.tocando = null;
191
+ this.interrupcoes += 1;
192
+ this.log('interrompido', { n: this.interrupcoes });
193
+ return true;
194
+ }
195
+
196
+ /** A SOS: espera ~1,5 s sem voz humana e responde; uma espera por vez (a fala seguinte entra no mesmo turno). */
197
+ async respondeASos() {
198
+ if (this.aguardandoSilencio || this.ocupado) return null;
199
+ this.aguardandoSilencio = true;
200
+ try {
201
+ const ini = this.agora();
202
+ while (!this.encerrado && this.agora() - this.ultimaVozHumana < this.silencioASosMs) {
203
+ if (this.agora() - ini >= this.esperaASosMaxMs) break;
204
+ await this.dormeMs(Math.max(50, this.silencioASosMs - (this.agora() - this.ultimaVozHumana)));
205
+ }
206
+ } finally {
207
+ this.aguardandoSilencio = false;
208
+ }
209
+ if (this.encerrado) return null;
210
+ return this.pensa('chamado');
211
+ }
212
+
213
+ async recebeuAVez() {
214
+ const m = this.maoLevantada;
215
+ if (!m) return;
216
+ this.maoLevantada = null;
217
+ this.publica({ t: 'mao', alvo: this.identidade, on: false });
218
+ await this.fala({ acao: 'falar', texto: m.texto, assunto: m.assunto, id: m.id });
219
+ }
220
+
221
+ async respondeAgente(m, remetente) {
222
+ const pedido = String(m.pedido || `${String(remetente || m.alvo || 'x')}`).replace(/[^A-Za-z0-9_]/g, '_').slice(0, 60) || 'x';
223
+ if (this.esgotados.has(pedido)) return;
224
+ const r = await this.chamar('rea_rodada', [this.tokenBash, this.sala, pedido]);
225
+ if (r?.ok !== true) {
226
+ this.log('rea_rodada', r);
227
+ return;
228
+ }
229
+ if (r.esgotou === true) {
230
+ this.esgotados.add(pedido);
231
+ return this.pensa('resumo', pedido);
232
+ }
233
+ return this.pensa('rodada', pedido);
234
+ }
235
+
236
+ async pensa(gatilho, pedido = '') {
237
+ if (this.encerrado) return null;
238
+ // Uma ideia por vez: enquanto pensa, outro gatilho espera a proxima fala.
239
+ if (this.ocupado) return null;
240
+ if (gatilho === 'util' && this.perguntaAberta) return null;
241
+ this.ocupado = true;
242
+ const naHora = gatilho === 'chamado';
243
+ if (naHora) this.publica({ t: 'pensando', alvo: this.identidade, on: true, nome: this.apelido });
244
+ try {
245
+ const r = await this.chamar('rea_pensar', [this.tokenBash, this.sala, this.agente, gatilho]);
246
+ if (r?.ok !== true) {
247
+ this.log('rea_pensar', r);
248
+ if (r?.codigo === 'teto_reuniao') await this.sai('teto');
249
+ return r;
250
+ }
251
+ const res = await espera(this.chamar, 'rea_fala_estado', this.tokenBash, r.id, this.esperaOpts);
252
+ if (res?.ok !== true) {
253
+ this.log('rea_fala_estado', { codigo: res?.codigo });
254
+ return res;
255
+ }
256
+ const ideia = { ...res, id: r.id, pedido };
257
+ if (res.acao === 'sair') {
258
+ await this.sai('teto');
259
+ return ideia;
260
+ }
261
+ // EM GRUPO o agente nunca toma a palavra sozinho: o que viria como fala espontanea vira mao levantada.
262
+ const semAVez = gatilho === 'util' && !this.aSos() && (res.acao === 'falar' || res.acao === 'perguntar');
263
+ if (res.acao === 'mao' || semAVez) {
264
+ this.maoLevantada = { texto: res.texto, assunto: res.assunto, id: r.id };
265
+ this.publica({ t: 'mao', alvo: this.identidade, on: true, em: this.agora(), nome: this.apelido });
266
+ } else if (res.acao === 'falar' || res.acao === 'perguntar') {
267
+ if (res.acao === 'perguntar' && this.perguntaAberta) return ideia;
268
+ await this.fala(ideia);
269
+ if (res.acao === 'perguntar') this.perguntaAberta = true;
270
+ }
271
+ if (res.sair === 'sim') await this.sai('teto');
272
+ return ideia;
273
+ } finally {
274
+ this.ocupado = false;
275
+ // Encerrado, a despedida (fala_agente acao sair) ja limpa o "pensando…" no app.
276
+ if (naHora && !this.encerrado) this.publica({ t: 'pensando', alvo: this.identidade, on: false });
277
+ }
278
+ }
279
+
280
+ /** Texto no topico SEMPRE; voz quando a sala tem o audio do agente. */
281
+ async fala(ideia) {
282
+ const texto = cabeNoTopico(ideia.texto);
283
+ if (!texto) return;
284
+ this.publica({
285
+ t: 'fala_agente',
286
+ alvo: this.identidade,
287
+ nome: this.apelido,
288
+ acao: ideia.acao,
289
+ texto,
290
+ assunto: cabeNoTopico(ideia.assunto, 80),
291
+ ...(ideia.pedido ? { pedido: ideia.pedido } : {}),
292
+ });
293
+ if (!this.comVoz || !ideia.id || !this.toca) return;
294
+ const v = await this.chamar('rea_voz', [this.tokenBash, this.sala, this.agente, ideia.id]);
295
+ if (v?.ok !== true) {
296
+ this.log('rea_voz', v);
297
+ return;
298
+ }
299
+ const a = await espera(this.chamar, 'rea_fala_estado', this.tokenBash, v.id, this.esperaOpts);
300
+ if (a?.ok !== true || !a.audio_base64) {
301
+ this.log('voz', { codigo: a?.codigo });
302
+ return;
303
+ }
304
+ if (String(a.format || 'wav') !== 'wav') {
305
+ this.log('voz', { codigo: 'formato_sem_suporte', format: a.format });
306
+ return;
307
+ }
308
+ const tocando = this.toca(a.audio_base64);
309
+ this.tocando = tocando;
310
+ try {
311
+ await tocando?.fim;
312
+ } finally {
313
+ if (this.tocando === tocando) this.tocando = null;
314
+ }
315
+ }
316
+
317
+ async sai(motivo) {
318
+ if (this.encerrado) return;
319
+ this.encerrado = true;
320
+ this.alguemFalando();
321
+ if (this.maoLevantada) this.publica({ t: 'mao', alvo: this.identidade, on: false });
322
+ this.maoLevantada = null;
323
+ this.publica({
324
+ t: 'fala_agente',
325
+ alvo: this.identidade,
326
+ nome: this.apelido,
327
+ acao: 'sair',
328
+ texto: textoDoAgente(motivo === 'teto' ? 'teto' : 'tchau', this.idioma),
329
+ });
330
+ this.aoSair(motivo);
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Le um WAV PCM 16 bits (o que o ia_tts devolve com format wav) em base64.
336
+ * Devolve {taxa, canais, amostras: Int16Array} ou null se nao for PCM16.
337
+ * Tolerante ao tamanho 0xFFFFFFFF de streaming (usa o que tiver no buffer).
338
+ */
339
+ export function lerWav(b64) {
340
+ let buf;
341
+ try {
342
+ buf = Buffer.from(String(b64 || ''), 'base64');
343
+ } catch {
344
+ return null;
345
+ }
346
+ if (buf.length < 44 || buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') return null;
347
+ let p = 12;
348
+ let fmt = null;
349
+ while (p + 8 <= buf.length) {
350
+ const id = buf.toString('ascii', p, p + 4);
351
+ let tam = buf.readUInt32LE(p + 4);
352
+ const ini = p + 8;
353
+ if (id === 'fmt ') {
354
+ fmt = { formato: buf.readUInt16LE(ini), canais: buf.readUInt16LE(ini + 2), taxa: buf.readUInt32LE(ini + 4), bits: buf.readUInt16LE(ini + 14) };
355
+ } else if (id === 'data') {
356
+ if (!fmt || fmt.formato !== 1 || fmt.bits !== 16 || fmt.canais < 1) return null;
357
+ if (tam > buf.length - ini || tam === 0xffffffff) tam = buf.length - ini;
358
+ tam -= tam % (2 * fmt.canais);
359
+ const copia = Buffer.from(buf.subarray(ini, ini + tam));
360
+ const amostras = new Int16Array(copia.buffer, copia.byteOffset, tam / 2);
361
+ return { taxa: fmt.taxa, canais: fmt.canais, amostras };
362
+ }
363
+ p = ini + tam + (tam % 2);
364
+ }
365
+ return null;
366
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Regras puras do cliente N-Call: detecção de chamada ao agente e limite de rodadas.
3
+ * Sem dependências externas.
4
+ */
5
+
6
+ /**
7
+ * Remove acentos e passa para minúsculas (NFD + remove \p{Diacritic}).
8
+ */
9
+ export function normaliza(s) {
10
+ if (!s) return '';
11
+ return s.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
12
+ }
13
+
14
+ /**
15
+ * true se a fala chama o agente: nome ou apelido como palavra inteira, ou "@apelido",
16
+ * sem diferenciar maiúsculas nem acentos ("Ána" chama "Ana"; "Banana" NÃO chama "Ana").
17
+ */
18
+ export function foiChamado(texto, nomes) {
19
+ if (!texto || !nomes || nomes.length === 0) return false;
20
+ const textoNorm = normaliza(texto);
21
+
22
+ for (const nome of nomes) {
23
+ const nomeNorm = normaliza(nome);
24
+ if (!nomeNorm) continue;
25
+
26
+ // verificar "@nome" (com @ antes)
27
+ const padraoComArroba = new RegExp(`@${escapeRegex(nomeNorm)}\\b`, 'i');
28
+ if (padraoComArroba.test(textoNorm)) return true;
29
+
30
+ // verificar como palavra inteira (com limites de palavra)
31
+ const padraoPalavra = new RegExp(`\\b${escapeRegex(nomeNorm)}\\b`, 'i');
32
+ if (padraoPalavra.test(textoNorm)) return true;
33
+ }
34
+
35
+ return false;
36
+ }
37
+
38
+ /**
39
+ * Escapa caracteres especiais de regex.
40
+ */
41
+ function escapeRegex(s) {
42
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
43
+ }
44
+
45
+ /**
46
+ * Contador de rodadas agente↔agente por pedido: true enquanto houver rodada; registra a rodada usada.
47
+ */
48
+ export class LimiteDeRodadas {
49
+ constructor(max = 6) {
50
+ this.max = max;
51
+ this.usadas = new Map();
52
+ }
53
+
54
+ /**
55
+ * Devolve true se ainda podia (e conta), false se esgotou.
56
+ */
57
+ usa(pedidoId) {
58
+ const usadas = this.usadas.get(pedidoId) || 0;
59
+ if (usadas >= this.max) return false;
60
+ this.usadas.set(pedidoId, usadas + 1);
61
+ return true;
62
+ }
63
+
64
+ /**
65
+ * Número de rodadas restantes.
66
+ */
67
+ restam(pedidoId) {
68
+ const usadas = this.usadas.get(pedidoId) || 0;
69
+ return Math.max(0, this.max - usadas);
70
+ }
71
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Segmentador de fala por participante (VAD por energia) para áudio PCM 16 bits mono.
3
+ * Estado separado POR falante em um Map. Sem dependências externas.
4
+ */
5
+
6
+ /**
7
+ * RMS em dBFS de um quadro Int16Array.
8
+ * 20*log10(rms/32768); quadro vazio ou silêncio absoluto => -Infinity.
9
+ */
10
+ export function energiaDb(quadro) {
11
+ if (!quadro || quadro.length === 0) return -Infinity;
12
+ let soma = 0;
13
+ for (let i = 0; i < quadro.length; i++) {
14
+ const v = quadro[i];
15
+ soma += v * v;
16
+ }
17
+ const rms = Math.sqrt(soma / quadro.length);
18
+ if (rms === 0) return -Infinity;
19
+ return 20 * Math.log10(rms / 32768);
20
+ }
21
+
22
+ /**
23
+ * Monta um WAV PCM 16 bits mono com cabeçalho RIFF de 44 bytes e devolve base64.
24
+ */
25
+ export function wavBase64(pcm, taxa) {
26
+ const n = pcm.length;
27
+ const bytesDados = n * 2;
28
+ const total = 44 + bytesDados;
29
+ const buf = new ArrayBuffer(total);
30
+ const dv = new DataView(buf);
31
+
32
+ // RIFF chunk
33
+ dv.setUint8(0, 0x52); // R
34
+ dv.setUint8(1, 0x49); // I
35
+ dv.setUint8(2, 0x46); // F
36
+ dv.setUint8(3, 0x46); // F
37
+ dv.setUint32(4, total - 8, true); // tamanho do arquivo - 8
38
+ // WAVE
39
+ dv.setUint8(8, 0x57); // W
40
+ dv.setUint8(9, 0x41); // A
41
+ dv.setUint8(10, 0x56); // V
42
+ dv.setUint8(11, 0x45); // E
43
+ // fmt chunk
44
+ dv.setUint8(12, 0x66); // f
45
+ dv.setUint8(13, 0x6d); // m
46
+ dv.setUint8(14, 0x74); // t
47
+ dv.setUint8(15, 0x20); // espaço
48
+ dv.setUint32(16, 16, true); // tamanho do fmt
49
+ dv.setUint16(20, 1, true); // PCM
50
+ dv.setUint16(22, 1, true); // canais = 1
51
+ dv.setUint32(24, taxa, true); // taxa de amostragem
52
+ dv.setUint32(28, taxa * 2, true); // byte rate = taxa * canais * bits/8
53
+ dv.setUint16(32, 2, true); // block align = canais * bits/8
54
+ dv.setUint16(34, 16, true); // bits por amostra
55
+ // data chunk
56
+ dv.setUint8(36, 0x64); // d
57
+ dv.setUint8(37, 0x61); // a
58
+ dv.setUint8(38, 0x74); // t
59
+ dv.setUint8(39, 0x61); // a
60
+ dv.setUint32(40, bytesDados, true); // tamanho dos dados
61
+
62
+ // amostras
63
+ for (let i = 0; i < n; i++) {
64
+ dv.setInt16(44 + i * 2, pcm[i], true);
65
+ }
66
+
67
+ // base64
68
+ const bytes = new Uint8Array(buf);
69
+ let bin = '';
70
+ for (let i = 0; i < bytes.length; i++) {
71
+ bin += String.fromCharCode(bytes[i]);
72
+ }
73
+ return btoa(bin);
74
+ }
75
+
76
+ /**
77
+ * Segmentador de fala por participante.
78
+ */
79
+ export class SegmentadorDeFala {
80
+ constructor({
81
+ taxa = 16000,
82
+ limiarDb = -45,
83
+ minFalaMs = 400,
84
+ silencioFimMs = 700,
85
+ maxSegmentoMs = 15000,
86
+ } = {}) {
87
+ this.taxa = taxa;
88
+ this.limiarDb = limiarDb;
89
+ this.minFalaMs = minFalaMs;
90
+ this.silencioFimMs = silencioFimMs;
91
+ this.maxSegmentoMs = maxSegmentoMs;
92
+ // estado por falante
93
+ this.estado = new Map();
94
+ }
95
+
96
+ /**
97
+ * Recebe um quadro (Int16Array) de UM participante.
98
+ * Devolve [] ou uma lista de segmentos prontos:
99
+ * { falante, inicioMs, fimMs, pcm: Int16Array }
100
+ */
101
+ empurra(falante, quadro) {
102
+ if (!quadro || quadro.length === 0) return [];
103
+
104
+ let st = this.estado.get(falante);
105
+ if (!st) {
106
+ st = {
107
+ tempoMs: 0,
108
+ aberto: false,
109
+ inicioMs: 0,
110
+ quadros: [],
111
+ silencioAcumMs: 0,
112
+ duracaoTotalMs: 0,
113
+ vozMs: 0,
114
+ };
115
+ this.estado.set(falante, st);
116
+ }
117
+
118
+ const duracaoQuadroMs = (quadro.length / this.taxa) * 1000;
119
+ const energia = energiaDb(quadro);
120
+ const ehVoz = energia >= this.limiarDb;
121
+
122
+ const prontos = [];
123
+
124
+ if (ehVoz) {
125
+ if (!st.aberto) {
126
+ // abre segmento
127
+ st.aberto = true;
128
+ st.inicioMs = st.tempoMs;
129
+ st.quadros = [];
130
+ st.silencioAcumMs = 0;
131
+ st.duracaoTotalMs = 0;
132
+ st.vozMs = 0;
133
+ }
134
+ // adiciona o quadro de voz
135
+ st.quadros.push(quadro);
136
+ st.silencioAcumMs = 0;
137
+ st.duracaoTotalMs += duracaoQuadroMs;
138
+ st.vozMs += duracaoQuadroMs;
139
+
140
+ // verifica maxSegmentoMs
141
+ if (st.duracaoTotalMs >= this.maxSegmentoMs) {
142
+ // fecha o segmento atual
143
+ if (st.vozMs >= this.minFalaMs) {
144
+ const pcm = this._concat(st.quadros);
145
+ const fimMs = st.tempoMs + duracaoQuadroMs;
146
+ prontos.push({
147
+ falante,
148
+ inicioMs: st.inicioMs,
149
+ fimMs: fimMs,
150
+ pcm,
151
+ });
152
+ }
153
+ // abre outro se o quadro seguinte for voz (mas aqui já processamos este quadro)
154
+ // o próximo quadro será processado na próxima chamada; se for voz, abre novo
155
+ st.aberto = false;
156
+ st.quadros = [];
157
+ st.silencioAcumMs = 0;
158
+ st.duracaoTotalMs = 0;
159
+ st.vozMs = 0;
160
+ }
161
+ } else {
162
+ // silêncio
163
+ if (st.aberto) {
164
+ // adiciona o quadro de silêncio interno
165
+ st.quadros.push(quadro);
166
+ st.silencioAcumMs += duracaoQuadroMs;
167
+ st.duracaoTotalMs += duracaoQuadroMs;
168
+
169
+ if (st.silencioAcumMs >= this.silencioFimMs) {
170
+ // fecha o segmento (sem incluir o silêncio final que causou o fechamento)
171
+ // remover os quadros de silêncio do final
172
+ if (st.vozMs >= this.minFalaMs) {
173
+ const pcm = this._removeSilencioFinal(st.quadros);
174
+ if (pcm.length > 0) {
175
+ const fimMs = st.tempoMs + duracaoQuadroMs - st.silencioAcumMs;
176
+ // fimMs relativo ao início do segmento
177
+ const fimRelativo = st.inicioMs + (st.duracaoTotalMs - st.silencioAcumMs);
178
+ prontos.push({
179
+ falante,
180
+ inicioMs: st.inicioMs,
181
+ fimMs: fimRelativo,
182
+ pcm,
183
+ });
184
+ }
185
+ }
186
+ st.aberto = false;
187
+ st.quadros = [];
188
+ st.silencioAcumMs = 0;
189
+ st.duracaoTotalMs = 0;
190
+ st.vozMs = 0;
191
+ }
192
+ }
193
+ // se não estava aberto, nada a fazer
194
+ }
195
+
196
+ // avança o tempo do falante
197
+ st.tempoMs += duracaoQuadroMs;
198
+
199
+ return prontos;
200
+ }
201
+
202
+ /**
203
+ * Fecha o que estiver aberto (fim da reunião). Devolve a lista de segmentos prontos.
204
+ */
205
+ fecha() {
206
+ const prontos = [];
207
+ for (const [falante, st] of this.estado.entries()) {
208
+ if (st.aberto && st.quadros.length > 0) {
209
+ if (st.vozMs >= this.minFalaMs) {
210
+ const pcm = this._removeSilencioFinal(st.quadros);
211
+ if (pcm.length > 0) {
212
+ const fimRelativo = st.inicioMs + (st.duracaoTotalMs - st.silencioAcumMs);
213
+ prontos.push({
214
+ falante,
215
+ inicioMs: st.inicioMs,
216
+ fimMs: fimRelativo,
217
+ pcm,
218
+ });
219
+ }
220
+ }
221
+ }
222
+ }
223
+ this.estado.clear();
224
+ return prontos;
225
+ }
226
+
227
+ /**
228
+ * Concatena uma lista de Int16Array em um único Int16Array.
229
+ */
230
+ _concat(quadros) {
231
+ let total = 0;
232
+ for (const q of quadros) total += q.length;
233
+ const out = new Int16Array(total);
234
+ let pos = 0;
235
+ for (const q of quadros) {
236
+ out.set(q, pos);
237
+ pos += q.length;
238
+ }
239
+ return out;
240
+ }
241
+
242
+ /**
243
+ * Remove os quadros de silêncio do final da lista (os que estão após a última voz).
244
+ */
245
+ _removeSilencioFinal(quadros) {
246
+ // encontrar o último índice que é voz
247
+ let ultimoVoz = -1;
248
+ for (let i = 0; i < quadros.length; i++) {
249
+ const e = energiaDb(quadros[i]);
250
+ if (e >= this.limiarDb) {
251
+ ultimoVoz = i;
252
+ }
253
+ }
254
+ if (ultimoVoz === -1) return new Int16Array(0);
255
+ const recortados = quadros.slice(0, ultimoVoz + 1);
256
+ return this._concat(recortados);
257
+ }
258
+ }