File size: 29,902 Bytes
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b533a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc36801
 
82b533a
bc36801
82b533a
bc36801
 
 
82b533a
 
bc36801
 
 
 
82b533a
 
bc36801
 
82b533a
 
 
 
 
 
 
 
 
 
bc36801
82b533a
 
 
 
 
 
 
 
 
 
bc36801
 
 
 
82b533a
bc36801
 
 
 
82b533a
bc36801
 
 
 
 
 
 
 
 
 
 
 
82b533a
 
 
 
 
 
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b533a
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b533a
 
 
 
 
 
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b533a
 
 
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b533a
 
 
 
 
 
 
 
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b533a
 
 
bc36801
 
 
 
 
 
 
82b533a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc36801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
/**
 * Streaming ASR Demo - JavaScript Implementation with Web Workers
 *
 * Architecture:
 * - Main thread: Audio capture, VAD, UI updates
 * - Encoder Worker: Preprocessor + Encoder ONNX inference
 * - Decoder Worker: Adapter + Decoder ONNX inference
 */

// =============================================================================
// Constants
// =============================================================================

const SAMPLE_RATE = 16000;
const VAD_CHUNK_SAMPLES = 160;  // 10ms - optimal for TenVAD
const ASR_CHUNK_SAMPLES = 320;  // 20ms - Moonshine frame size
const ENCODER_BATCH_SAMPLES = 5120;  // 320ms - batch size for encoder

const PRE_BUFFER_CHUNKS = 15;  // ~300ms at 20ms chunks
const POST_BUFFER_CHUNKS = 3;  // ~60ms at 20ms chunks

const MODEL_CONFIGS = {
    sleeker: {
        dim: 336,
        dec_dim: 288,
        depth: 6,
        encoder_depth: 6,
        n_past: 16,
        n_future: 4,
        nheads: 8,
        head_dim: 36,
        vocab_size: 32768
    },
    spindlier: {
        dim: 620,
        dec_dim: 512,
        depth: 10,
        encoder_depth: 10,
        n_past: 16,
        n_future: 4,
        nheads: 8,
        head_dim: 64,
        vocab_size: 32768
    }
};

// =============================================================================
// TenVAD - WebAssembly-based Voice Activity Detection
// =============================================================================

class TenVAD {
    constructor(hopSize = 160, threshold = 0.5) {
        this.hopSize = hopSize;
        this.threshold = threshold;
        this.module = null;
        this.vadHandle = null;
        this.audioPtr = null;
        this.probPtr = null;
        this.flagPtr = null;
        this.ready = false;
    }

    async init(wasmUrl = './ten_vad.js') {
        const wasmBinaryUrl = wasmUrl.replace('.js', '.wasm');

        // Dynamic import of the ES module
        const vadModule = await import(wasmUrl);
        const createTenVadModule = vadModule.default;

        this.module = await createTenVadModule({
            locateFile: (path) => {
                if (path.endsWith('.wasm')) {
                    return wasmBinaryUrl;
                }
                return path;
            }
        });

        // Create VAD instance
        const vadHandlePtr = this.module._malloc(4);
        const result = this.module._ten_vad_create(vadHandlePtr, this.hopSize, this.threshold);

        if (result !== 0) {
            this.module._free(vadHandlePtr);
            throw new Error(`Failed to create TenVAD instance: ${result}`);
        }

        this.vadHandle = this.module.HEAP32[vadHandlePtr / 4];
        this.module._free(vadHandlePtr);

        // Allocate buffers
        this.audioPtr = this.module._malloc(this.hopSize * 2);
        this.probPtr = this.module._malloc(4);
        this.flagPtr = this.module._malloc(4);

        this.ready = true;
    }

    process(audioChunkFloat32) {
        if (!this.ready) return -1;

        const int16Data = new Int16Array(this.hopSize);
        for (let i = 0; i < this.hopSize && i < audioChunkFloat32.length; i++) {
            int16Data[i] = Math.max(-32768, Math.min(32767, Math.round(audioChunkFloat32[i] * 32767)));
        }

        this.module.HEAP16.set(int16Data, this.audioPtr / 2);
        this.module._ten_vad_process(this.vadHandle, this.audioPtr, this.hopSize, this.probPtr, this.flagPtr);

        return this.module.HEAPF32[this.probPtr / 4];
    }

    destroy() {
        if (!this.ready || !this.module) return;

        this.ready = false;  // Prevent further use

        try {
            if (this.audioPtr) {
                this.module._free(this.audioPtr);
                this.audioPtr = null;
            }
            if (this.probPtr) {
                this.module._free(this.probPtr);
                this.probPtr = null;
            }
            if (this.flagPtr) {
                this.module._free(this.flagPtr);
                this.flagPtr = null;
            }
            // Skip _ten_vad_destroy as it causes memory access errors
            // The WASM memory will be cleaned up when the module is garbage collected
            this.vadHandle = null;
        } catch (e) {
            console.warn('TenVAD cleanup error:', e);
        }

        this.module = null;
    }
}

// Fallback simple energy-based VAD
class SimpleVAD {
    constructor(sampleRate = 16000, frameSize = 160) {
        this.frameSize = frameSize;
        this.energyHistory = [];
        this.historySize = 50;
        this.noiseFloor = 0.001;
        this.ready = true;
    }

    async init() {}

    process(audioChunk) {
        let energy = 0;
        for (let i = 0; i < audioChunk.length; i++) {
            energy += audioChunk[i] * audioChunk[i];
        }
        energy = Math.sqrt(energy / audioChunk.length);

        this.energyHistory.push(energy);
        if (this.energyHistory.length > this.historySize) {
            this.energyHistory.shift();
        }

        if (this.energyHistory.length > 10) {
            const sorted = [...this.energyHistory].sort((a, b) => a - b);
            this.noiseFloor = sorted[Math.floor(sorted.length * 0.1)] || 0.001;
        }

        const snr = energy / (this.noiseFloor + 1e-10);
        return 1 / (1 + Math.exp(-2 * (snr - 3)));
    }

    destroy() {}
}

// =============================================================================
// Pipelined Streaming ASR with Web Workers
// =============================================================================

class PipelinedStreamingASR {
    constructor(config) {
        this.modelName = config.modelName || 'sleeker';
        this.onnxUrl = config.onnxUrl || './models';
        this.onsetThreshold = config.onsetThreshold || 0.5;
        this.offsetThreshold = config.offsetThreshold || 0.3;
        this.emaAlpha = config.emaAlpha || 0.3;

        this.cfg = MODEL_CONFIGS[this.modelName];

        // Workers
        this.encoderWorker = null;
        this.decoderWorker = null;
        this.encoderReady = false;
        this.decoderReady = false;

        // VAD (runs on main thread for low latency)
        this.vad = null;

        // Audio capture
        this.audioContext = null;
        this.sourceNode = null;
        this.workletNode = null;

        // State
        this.running = false;
        this.state = 'idle';
        this.currentSegmentId = 0;
        this.emaProb = 0;
        this.onsetCounter = 0;
        this.offsetCounter = 0;

        // Buffers
        this.vadBuffer = [];
        this.asrBuffer = [];
        this.preBuffer = [];
        this.postBufferRemaining = 0;
        this.encoderBatchBuffer = [];  // Accumulate 320ms before sending to encoder

        // Display state
        this.vadHistory = [];
        this.vadUpdateCounter = 0;
        this.vadUpdateInterval = 5;  // Update display every 5 VAD chunks (50ms)

        // Callbacks
        this.onVadUpdate = null;
        this.onTranscript = null;
        this.onLiveCaption = null;
        this.onStatusUpdate = null;
        this.onQueueUpdate = null;
    }

    async loadModels(progressCallback, detailedProgressCallback) {
        // Track overall progress
        const totalModels = 7;  // VAD, Preprocessor, Encoder, Tokenizer, Adapter, Decoder Init, Decoder Step
        let completedModels = 0;
        let currentModel = '';
        let currentProgress = { loaded: 0, total: 0 };

        const updateProgress = () => {
            const overallPercent = (completedModels / totalModels) * 100;
            detailedProgressCallback?.({
                completedModels,
                totalModels,
                overallPercent,
                currentModel,
                currentProgress
            });
        };

        // Initialize VAD
        try {
            currentModel = 'VAD';
            progressCallback?.('Loading TenVAD...');
            updateProgress();
            this.vad = new TenVAD(VAD_CHUNK_SAMPLES, 0.5);
            await this.vad.init('./ten_vad.js');
            console.log('Using TenVAD');
            completedModels++;
            updateProgress();
        } catch (e) {
            console.warn('TenVAD failed, using SimpleVAD:', e.message);
            this.vad = new SimpleVAD(SAMPLE_RATE, VAD_CHUNK_SAMPLES);
            await this.vad.init();
            completedModels++;
            updateProgress();
        }

        // Initialize Encoder Worker with progress tracking
        progressCallback?.('Loading encoder models...');
        await this.initEncoderWorker((model, progress) => {
            currentModel = model;
            currentProgress = progress;
            updateProgress();
        }, () => {
            completedModels++;
            updateProgress();
        });

        // Initialize Decoder Worker with progress tracking
        progressCallback?.('Loading decoder models...');
        await this.initDecoderWorker((model, progress) => {
            currentModel = model;
            currentProgress = progress;
            updateProgress();
        }, () => {
            completedModels++;
            updateProgress();
        });

        progressCallback?.('Ready!');
    }

    initEncoderWorker(onProgress, onModelDone) {
        return new Promise((resolve, reject) => {
            this.encoderWorker = new Worker('./encoder_worker.js');

            this.encoderWorker.onmessage = (e) => {
                const { type } = e.data;

                switch (type) {
                    case 'ready':
                        this.encoderReady = true;
                        resolve();
                        break;
                    case 'error':
                        reject(new Error(e.data.message));
                        break;
                    case 'status':
                        // Progress update from worker
                        break;
                    case 'progress':
                        onProgress?.(e.data.model, { loaded: e.data.loaded, total: e.data.total });
                        break;
                    case 'model_done':
                        onModelDone?.(e.data.model);
                        break;
                    case 'segment_start':
                        this.decoderWorker?.postMessage({ type: 'segment_start', data: { segmentId: e.data.segmentId } });
                        break;
                    case 'segment_end':
                        this.decoderWorker?.postMessage({ type: 'segment_end', data: { segmentId: e.data.segmentId } });
                        break;
                    case 'features':
                        // Forward features to decoder worker
                        this.decoderWorker?.postMessage({
                            type: 'features',
                            data: {
                                segmentId: e.data.segmentId,
                                features: e.data.features,
                                dims: e.data.dims
                            }
                        }, [e.data.features.buffer]);
                        break;
                }
            };

            this.encoderWorker.postMessage({
                type: 'init',
                data: {
                    cfg: this.cfg,
                    onnxUrl: this.onnxUrl,
                    modelName: this.modelName
                }
            });
        });
    }

    initDecoderWorker(onProgress, onModelDone) {
        return new Promise((resolve, reject) => {
            this.decoderWorker = new Worker('./decoder_worker.js');

            this.decoderWorker.onmessage = (e) => {
                const { type } = e.data;

                switch (type) {
                    case 'ready':
                        this.decoderReady = true;
                        resolve();
                        break;
                    case 'error':
                        reject(new Error(e.data.message));
                        break;
                    case 'status':
                        break;
                    case 'progress':
                        onProgress?.(e.data.model, { loaded: e.data.loaded, total: e.data.total });
                        break;
                    case 'model_done':
                        onModelDone?.(e.data.model);
                        break;
                    case 'transcript':
                        this.onTranscript?.(e.data.text, e.data.segmentId);
                        break;
                    case 'live_caption':
                        this.onLiveCaption?.(e.data.text);
                        break;
                }
            };

            this.decoderWorker.postMessage({
                type: 'init',
                data: {
                    cfg: this.cfg,
                    onnxUrl: this.onnxUrl,
                    modelName: this.modelName
                }
            });
        });
    }

    async start() {
        if (this.running) return;

        const stream = await navigator.mediaDevices.getUserMedia({
            audio: {
                sampleRate: SAMPLE_RATE,
                channelCount: 1,
                echoCancellation: false,
                noiseSuppression: false,
                autoGainControl: false
            }
        });

        this.audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });

        // Check actual sample rate
        console.log(`Requested sample rate: ${SAMPLE_RATE}, Actual: ${this.audioContext.sampleRate}`);
        this.sourceNode = this.audioContext.createMediaStreamSource(stream);

        // Use AudioWorklet for better performance
        try {
            await this.audioContext.audioWorklet.addModule('./audio_processor.js');
            this.workletNode = new AudioWorkletNode(this.audioContext, 'audio-processor');

            this.workletNode.port.onmessage = (e) => {
                if (this.running) {
                    this.processAudioChunk(e.data.audio);
                }
            };

            this.sourceNode.connect(this.workletNode);
            this.workletNode.connect(this.audioContext.destination);
        } catch (e) {
            // Fallback to ScriptProcessor
            console.warn('AudioWorklet not available, using ScriptProcessor');
            const bufferSize = 2048;
            this.scriptNode = this.audioContext.createScriptProcessor(bufferSize, 1, 1);

            this.scriptNode.onaudioprocess = (e) => {
                if (this.running) {
                    const inputData = e.inputBuffer.getChannelData(0);
                    this.processAudioChunk(new Float32Array(inputData));
                }
            };

            this.sourceNode.connect(this.scriptNode);
            this.scriptNode.connect(this.audioContext.destination);
        }

        this.running = true;
        this.state = 'idle';
        this.onsetCounter = 0;
        this.offsetCounter = 0;
        this.emaProb = 0;

        this.onStatusUpdate?.('listening', 'Listening...');
    }

    stop() {
        this.running = false;

        if (this.workletNode) {
            this.workletNode.disconnect();
            this.workletNode = null;
        }
        if (this.scriptNode) {
            this.scriptNode.disconnect();
            this.scriptNode = null;
        }
        if (this.sourceNode) {
            this.sourceNode.disconnect();
            this.sourceNode = null;
        }
        if (this.audioContext) {
            this.audioContext.close();
            this.audioContext = null;
        }
        if (this.vad) {
            this.vad.destroy();
        }
        if (this.encoderWorker) {
            this.encoderWorker.terminate();
            this.encoderWorker = null;
        }
        if (this.decoderWorker) {
            this.decoderWorker.terminate();
            this.decoderWorker = null;
        }

        this.onStatusUpdate?.('idle', 'Stopped');
    }

    processAudioChunk(audioData) {
        // Accumulate for VAD (10ms chunks)
        this.vadBuffer.push(...audioData);

        // Accumulate for ASR (20ms chunks)
        this.asrBuffer.push(...audioData);

        // Process VAD chunks
        while (this.vadBuffer.length >= VAD_CHUNK_SAMPLES) {
            const vadChunk = new Float32Array(this.vadBuffer.splice(0, VAD_CHUNK_SAMPLES));
            const prob = this.vad.process(vadChunk);

            if (prob >= 0) {
                this.emaProb = this.emaAlpha * prob + (1 - this.emaAlpha) * this.emaProb;

                // Throttle display updates (every 50ms instead of 10ms)
                this.vadUpdateCounter++;
                if (this.vadUpdateCounter >= this.vadUpdateInterval) {
                    this.vadUpdateCounter = 0;
                    this.vadHistory.push(this.emaProb);
                    if (this.vadHistory.length > 100) this.vadHistory.shift();
                    this.onVadUpdate?.(this.emaProb, this.vadHistory);
                }

                this.updateSegmentState();
            }
        }

        // Extract complete ASR chunks
        while (this.asrBuffer.length >= ASR_CHUNK_SAMPLES) {
            const chunkData = this.asrBuffer.splice(0, ASR_CHUNK_SAMPLES);
            const chunk = new Float32Array(chunkData);

            if (this.state === 'speech') {
                this.sendAudioToEncoder(chunk);
            } else {
                this.preBuffer.push(chunk);
                if (this.preBuffer.length > PRE_BUFFER_CHUNKS) {
                    this.preBuffer.shift();
                }

                if (this.postBufferRemaining > 0) {
                    this.sendAudioToEncoder(chunk);
                    this.postBufferRemaining--;

                    if (this.postBufferRemaining === 0) {
                        this.finalizeSegmentEnd();
                    }
                }
            }
        }
    }

    sendAudioToEncoder(chunk, flush = false) {
        if (!this.encoderWorker || !this.encoderReady) return;

        // Accumulate chunks into batch buffer
        this.encoderBatchBuffer.push(...chunk);

        // Send when we have 320ms worth of audio, or on flush
        if (this.encoderBatchBuffer.length >= ENCODER_BATCH_SAMPLES || flush) {
            if (this.encoderBatchBuffer.length > 0) {
                const batch = new Float32Array(this.encoderBatchBuffer);
                this.encoderBatchBuffer = [];

                this.encoderWorker.postMessage({
                    type: 'audio',
                    data: {
                        audio: batch,
                        segmentId: this.currentSegmentId
                    }
                }, [batch.buffer]);
            }
        }
    }

    updateSegmentState() {
        if (this.state === 'idle') {
            if (this.emaProb >= this.onsetThreshold) {
                this.onsetCounter++;
                if (this.onsetCounter >= 2) {
                    this.startSegment();
                }
            } else {
                this.onsetCounter = 0;
            }
        } else if (this.state === 'speech') {
            if (this.emaProb < this.offsetThreshold) {
                this.offsetCounter++;
                if (this.offsetCounter >= 3) {
                    this.endSegment();
                }
            } else {
                this.offsetCounter = 0;
            }
        }
    }

    startSegment() {
        this.currentSegmentId++;
        this.state = 'speech';
        this.onsetCounter = 0;
        this.offsetCounter = 0;
        this.encoderBatchBuffer = [];  // Reset batch buffer for new segment

        // Tell encoder to start new segment
        this.encoderWorker?.postMessage({
            type: 'segment_start',
            data: { segmentId: this.currentSegmentId }
        });

        // Drain pre-buffer
        while (this.preBuffer.length > 0) {
            const chunk = this.preBuffer.shift();
            this.sendAudioToEncoder(chunk);
        }

        this.onStatusUpdate?.('recording', 'Recording...');
    }

    endSegment() {
        this.state = 'idle';
        this.offsetCounter = 0;
        this.postBufferRemaining = POST_BUFFER_CHUNKS;

        if (this.postBufferRemaining === 0) {
            this.finalizeSegmentEnd();
        }

        this.onStatusUpdate?.('listening', 'Listening...');
    }

    finalizeSegmentEnd() {
        // Process remaining complete chunks
        while (this.asrBuffer.length >= ASR_CHUNK_SAMPLES) {
            const chunkData = this.asrBuffer.splice(0, ASR_CHUNK_SAMPLES);
            const chunk = new Float32Array(chunkData);
            this.sendAudioToEncoder(chunk);
        }

        // Pad and send partial chunk
        if (this.asrBuffer.length > 0) {
            const padded = new Float32Array(ASR_CHUNK_SAMPLES);
            padded.set(this.asrBuffer);
            this.sendAudioToEncoder(padded);
        }
        this.asrBuffer = [];

        // Flush any remaining audio in the batch buffer
        this.sendAudioToEncoder(new Float32Array(0), true);

        // Signal segment end
        this.encoderWorker?.postMessage({
            type: 'segment_end',
            data: { segmentId: this.currentSegmentId }
        });
    }
}

// =============================================================================
// UI Controller
// =============================================================================

class ASRDemoUI {
    constructor() {
        this.asr = null;
        this.vadCanvas = null;
        this.vadCtx = null;

        this.initElements();
        this.initCanvas();
        this.bindEvents();
    }

    initElements() {
        this.loadingOverlay = document.getElementById('loadingOverlay');
        this.loadingText = document.getElementById('loadingText');
        this.loadingProgressFill = document.getElementById('loadingProgressFill');
        this.loadingProgressText = document.getElementById('loadingProgressText');
        this.loadingDetails = document.getElementById('loadingDetails');
        this.errorMessage = document.getElementById('errorMessage');
        this.statusDot = document.getElementById('statusDot');
        this.statusText = document.getElementById('statusText');
        this.startBtn = document.getElementById('startBtn');
        this.stopBtn = document.getElementById('stopBtn');
        this.vadBarFill = document.getElementById('vadBarFill');
        this.vadValue = document.getElementById('vadValue');
        this.audioQueueSize = document.getElementById('audioQueueSize');
        this.featuresQueueSize = document.getElementById('featuresQueueSize');
        this.droppedChunksEl = document.getElementById('droppedChunks');
        this.transcriptsList = document.getElementById('transcriptsList');
        this.liveCaption = document.getElementById('liveCaption');
        this.liveCaptionText = document.getElementById('liveCaptionText');
        this.modelSelect = document.getElementById('modelSelect');
        this.onnxUrl = document.getElementById('onnxUrl');
        this.onsetThreshold = document.getElementById('onsetThreshold');
        this.offsetThreshold = document.getElementById('offsetThreshold');
    }

    initCanvas() {
        this.vadCanvas = document.getElementById('vadCanvas');
        this.vadCtx = this.vadCanvas.getContext('2d');

        const rect = this.vadCanvas.getBoundingClientRect();
        this.vadCanvas.width = rect.width * window.devicePixelRatio;
        this.vadCanvas.height = rect.height * window.devicePixelRatio;
        this.vadCtx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }

    bindEvents() {
        this.startBtn.addEventListener('click', () => this.handleStart());
        this.stopBtn.addEventListener('click', () => this.handleStop());
    }

    async handleStart() {
        try {
            this.showLoading('Initializing...');

            const config = {
                modelName: this.modelSelect.value,
                onnxUrl: this.onnxUrl.value || './models',
                onsetThreshold: parseFloat(this.onsetThreshold.value),
                offsetThreshold: parseFloat(this.offsetThreshold.value)
            };

            this.asr = new PipelinedStreamingASR(config);

            this.asr.onVadUpdate = (prob, history) => this.updateVadDisplay(prob, history);
            this.asr.onTranscript = (text, segmentId) => this.addTranscript(text, segmentId);
            this.asr.onLiveCaption = (text) => this.updateLiveCaption(text);
            this.asr.onStatusUpdate = (status, text) => this.updateStatus(status, text);

            await this.asr.loadModels(
                (text) => {
                    this.loadingText.textContent = text;
                },
                (progress) => {
                    this.updateLoadingProgress(progress);
                }
            );

            await this.asr.start();

            this.hideLoading();
            this.startBtn.disabled = true;
            this.stopBtn.disabled = false;
            this.disableConfig(true);

        } catch (error) {
            console.error('Start error:', error);
            this.hideLoading();
            this.showError(`Failed to start: ${error.message}`);
        }
    }

    handleStop() {
        if (this.asr) {
            this.asr.stop();
            this.asr = null;
        }

        this.startBtn.disabled = false;
        this.stopBtn.disabled = true;
        this.disableConfig(false);
        this.updateStatus('idle', 'Ready');
    }

    updateVadDisplay(prob, history) {
        this.vadBarFill.style.width = `${prob * 100}%`;
        this.vadValue.textContent = `${Math.round(prob * 100)}%`;

        const ctx = this.vadCtx;
        const rect = this.vadCanvas.getBoundingClientRect();
        const width = rect.width;
        const height = rect.height;

        ctx.fillStyle = '#0f0f23';
        ctx.fillRect(0, 0, width, height);

        if (history.length < 2) return;

        const onsetY = height * (1 - parseFloat(this.onsetThreshold.value));
        const offsetY = height * (1 - parseFloat(this.offsetThreshold.value));

        ctx.strokeStyle = '#ff444466';
        ctx.beginPath();
        ctx.moveTo(0, onsetY);
        ctx.lineTo(width, onsetY);
        ctx.stroke();

        ctx.strokeStyle = '#00ff8866';
        ctx.beginPath();
        ctx.moveTo(0, offsetY);
        ctx.lineTo(width, offsetY);
        ctx.stroke();

        ctx.strokeStyle = '#00d4ff';
        ctx.lineWidth = 2;
        ctx.beginPath();

        for (let i = 0; i < history.length; i++) {
            const x = (i / (history.length - 1)) * width;
            const y = height * (1 - history[i]);
            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        ctx.stroke();
    }

    addTranscript(text, segmentId) {
        if (!text || !text.trim()) return;

        const item = document.createElement('div');
        item.className = 'transcript-item';
        item.innerHTML = `
            <span class="transcript-duration">#${segmentId}</span>
            <span class="transcript-text">${this.escapeHtml(text)}</span>
        `;
        this.transcriptsList.appendChild(item);
        this.transcriptsList.scrollTop = this.transcriptsList.scrollHeight;
    }

    updateLiveCaption(text) {
        if (text) {
            this.liveCaptionText.textContent = text;
            this.liveCaptionText.classList.remove('placeholder');
            this.liveCaption.classList.add('active');
        } else {
            this.liveCaptionText.textContent = 'Waiting for speech...';
            this.liveCaptionText.classList.add('placeholder');
            this.liveCaption.classList.remove('active');
        }
    }

    updateStatus(status, text) {
        this.statusDot.className = 'status-dot ' + status;
        this.statusText.textContent = text;
    }

    showLoading(text) {
        this.loadingText.textContent = text;
        this.loadingProgressFill.style.width = '0%';
        this.loadingProgressText.textContent = '0 / 7 models';
        this.loadingDetails.textContent = '';
        this.loadingOverlay.classList.remove('hidden');
    }

    hideLoading() {
        this.loadingOverlay.classList.add('hidden');
    }

    updateLoadingProgress(progress) {
        const { completedModels, totalModels, currentModel, currentProgress } = progress;

        // Update overall progress bar
        const overallPercent = (completedModels / totalModels) * 100;
        this.loadingProgressFill.style.width = `${overallPercent}%`;
        this.loadingProgressText.textContent = `${completedModels} / ${totalModels} models`;

        // Update details with current model and byte progress
        if (currentModel && currentProgress.total > 0) {
            const loadedMB = (currentProgress.loaded / (1024 * 1024)).toFixed(1);
            const totalMB = (currentProgress.total / (1024 * 1024)).toFixed(1);
            const percent = Math.round((currentProgress.loaded / currentProgress.total) * 100);
            this.loadingDetails.textContent = `${currentModel}: ${loadedMB} / ${totalMB} MB (${percent}%)`;
        } else if (currentModel) {
            this.loadingDetails.textContent = `Loading ${currentModel}...`;
        }
    }

    showError(message) {
        this.errorMessage.textContent = message;
        this.errorMessage.classList.add('visible');
    }

    disableConfig(disabled) {
        this.modelSelect.disabled = disabled;
        this.onnxUrl.disabled = disabled;
        this.onsetThreshold.disabled = disabled;
        this.offsetThreshold.disabled = disabled;
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    window.asrDemo = new ASRDemoUI();
});