File size: 43,714 Bytes
8aa91b2
 
 
 
 
2a4f3d6
 
 
 
 
 
8aa91b2
e403f98
8aa91b2
 
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
 
 
 
 
 
e403f98
 
 
 
 
8aa91b2
 
 
 
 
 
e403f98
 
 
 
8aa91b2
 
e403f98
 
 
8aa91b2
e403f98
8aa91b2
 
e403f98
 
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
e403f98
 
 
8aa91b2
e403f98
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
 
 
e403f98
8aa91b2
 
e403f98
8aa91b2
 
e403f98
 
 
8aa91b2
e403f98
 
 
8aa91b2
2a4f3d6
e403f98
 
 
2a4f3d6
e403f98
8aa91b2
 
e403f98
8aa91b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e403f98
 
 
 
 
 
 
 
 
 
 
8aa91b2
e403f98
 
 
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
 
e403f98
 
 
 
 
 
 
8aa91b2
e403f98
 
8aa91b2
e403f98
8aa91b2
e403f98
 
 
 
 
8aa91b2
e403f98
8aa91b2
 
 
e403f98
 
2a4f3d6
8aa91b2
 
 
 
 
 
 
 
 
2a4f3d6
8aa91b2
 
2a4f3d6
8aa91b2
 
e403f98
 
8aa91b2
2a4f3d6
8aa91b2
 
2a4f3d6
e403f98
 
8aa91b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
 
e403f98
 
 
 
 
2a4f3d6
e403f98
2a4f3d6
e403f98
 
 
8aa91b2
 
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
 
 
e403f98
 
8aa91b2
 
 
 
 
 
e403f98
8aa91b2
e403f98
8aa91b2
 
e403f98
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
 
 
 
 
 
 
 
 
8aa91b2
2a4f3d6
8aa91b2
2a4f3d6
8aa91b2
 
e403f98
 
 
8aa91b2
e403f98
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
e403f98
 
8aa91b2
e403f98
 
 
8aa91b2
 
 
 
 
e403f98
8aa91b2
 
e403f98
 
 
 
 
 
 
8aa91b2
2a4f3d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
e403f98
 
 
 
2a4f3d6
 
e403f98
 
 
 
 
 
2a4f3d6
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
 
 
 
 
 
 
 
 
 
 
 
e403f98
 
 
 
2a4f3d6
 
e403f98
 
 
 
 
 
 
 
 
2a4f3d6
 
414c74d
 
 
 
 
 
2a4f3d6
e403f98
2a4f3d6
414c74d
 
 
 
 
 
 
 
2a4f3d6
 
 
 
 
 
 
 
 
 
 
 
e403f98
 
2a4f3d6
e403f98
 
 
 
2a4f3d6
 
 
 
 
 
 
 
 
e403f98
 
2a4f3d6
 
 
 
 
 
 
 
 
e403f98
 
 
 
 
 
 
 
2a4f3d6
 
 
 
 
 
 
 
 
e403f98
2a4f3d6
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
 
e403f98
2a4f3d6
 
 
 
e403f98
 
2a4f3d6
e403f98
 
 
 
 
 
 
 
 
 
2a4f3d6
 
e403f98
 
 
 
 
 
 
2a4f3d6
 
 
 
e403f98
 
 
 
 
 
 
2a4f3d6
e403f98
 
 
2a4f3d6
e403f98
2a4f3d6
 
 
 
 
 
e403f98
 
 
 
 
 
 
 
 
 
 
2a4f3d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e403f98
 
2a4f3d6
e403f98
2a4f3d6
e403f98
2a4f3d6
8aa91b2
 
 
 
 
 
 
 
 
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4f3d6
 
e403f98
2a4f3d6
8aa91b2
e403f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa91b2
 
 
 
2a4f3d6
e403f98
8aa91b2
2a4f3d6
8aa91b2
2a4f3d6
414c74d
2a4f3d6
 
 
 
 
8aa91b2
 
 
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>tiny-voca Studio — TTS in your browser</title>
<meta name="description" content="A 4.5M-parameter text-to-speech model running entirely in your browser: WebGPU, with a WASM fallback. Nothing you type leaves your device." />
<meta property="og:type" content="website" />
<meta property="og:title" content="tiny-voca Studio" />
<meta property="og:description" content="A 4.5M-parameter text-to-speech model running entirely in your browser: WebGPU, with a WASM fallback. Nothing you type leaves your device." />
<meta name="twitter:card" content="summary" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource-variable/inter@5/index.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/jetbrains-mono@5/index.css" />
<style>
  :root {
    --bg: #0a0c0f;
    --panel: #14181d;
    --panel-hi: #1a1f26;
    --line: #262c34;
    --line-hi: #323a44;
    --ink: #e8ecf1;
    --muted: #9aa3af;
    --dim: #5d6673;
    --amber: #ffb454;
    --green: #35d07f;
    --red: #ff5d5d;
    --teal: #7dd8c3;
    --mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
  }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  [hidden] { display: none !important; }
  body {
    font-family: "Inter Variable", "Inter", ui-sans-serif, system-ui, sans-serif;
    background:
      radial-gradient(1200px 480px at 50% -12%, rgba(255, 180, 84, 0.07), transparent 60%),
      var(--bg);
    color: var(--ink);
    min-height: 100vh;
    padding-bottom: 42px; /* status strip */
    -webkit-font-smoothing: antialiased;
  }

  /* ------- top bar ------- */
  .topbar {
    position: relative; z-index: 10;
    display: flex; align-items: center; gap: 14px; padding: 9px 20px;
    background: rgba(10, 12, 15, 0.85);
    backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
    border-bottom: 1px solid var(--line);
  }
  .brand { display: flex; align-items: center; gap: 9px; font-weight: 650; font-size: 0.95rem; white-space: nowrap; }
  .brand .mark { width: 26px; height: 26px; border-radius: 7px; display: block; flex-shrink: 0; }
  .brand .brand-sub { color: var(--muted); font-weight: 500; padding-left: 12px; margin-left: 4px; border-left: 1px solid var(--line-hi); }
  .mode-tabs { display: flex; gap: 2px; background: #0d1013; border: 1px solid var(--line); border-radius: 8px; padding: 3px; margin-left: 10px; }
  .mode-tabs button {
    border: none; border-radius: 6px; padding: 6px 16px; font: 600 0.8rem/1 inherit; font-family: inherit;
    background: transparent; color: var(--muted); cursor: pointer; transition: all 0.15s;
  }
  .mode-tabs button:hover { color: var(--ink); }
  .mode-tabs button.active { background: var(--panel-hi); color: var(--ink); box-shadow: inset 0 0 0 1px var(--line-hi); }
  .spacer { flex: 1; }
  .toplink { color: var(--muted); text-decoration: none; font-size: 0.8rem; font-weight: 550; white-space: nowrap; transition: color 0.15s; }
  .toplink:hover { color: var(--ink); }
  .toplink.cta { color: var(--amber); border: 1px solid rgba(255, 180, 84, 0.4); border-radius: 8px; padding: 6px 14px; transition: background 0.15s; }
  .toplink.cta:hover { background: rgba(255, 180, 84, 0.10); }

  main { position: relative; z-index: 1; display: flex; flex-direction: column; align-items: center; padding: 22px 16px 10px; }

  /* ------- rack ------- */
  .rack { width: min(1020px, calc(100vw - 24px)); display: flex; flex-direction: column; gap: 12px; }
  .panel {
    background: linear-gradient(180deg, var(--panel-hi), var(--panel));
    border: 1px solid var(--line); border-radius: 12px;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.03), 0 12px 32px rgba(0,0,0,0.45);
    position: relative;
  }
  .panel-head {
    display: flex; align-items: center; gap: 10px;
    padding: 9px 14px; border-bottom: 1px solid var(--line);
    font-size: 0.66rem; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: var(--dim);
  }
  .panel-head .right { margin-left: auto; display: flex; align-items: center; gap: 10px; }
  .panel-body { padding: 14px; }

  /* LEDs + readouts */
  .led { width: 8px; height: 8px; border-radius: 50%; background: #2a2f36; flex-shrink: 0; transition: background 0.2s, box-shadow 0.2s; }
  .led.on.green { background: var(--green); box-shadow: 0 0 7px rgba(53, 208, 127, 0.8); }
  .led.on.amber { background: var(--amber); box-shadow: 0 0 7px rgba(255, 180, 84, 0.8); }
  .led.on.red { background: var(--red); box-shadow: 0 0 7px rgba(255, 93, 93, 0.8); }
  .readout {
    font-family: var(--mono); font-size: 0.72rem; color: var(--amber);
    background: #05070a; border: 1px solid var(--line); border-radius: 6px;
    padding: 3px 9px; text-shadow: 0 0 8px rgba(255, 180, 84, 0.35);
    white-space: nowrap; font-variant-numeric: tabular-nums;
  }
  .readout.teal { color: var(--teal); text-shadow: 0 0 8px rgba(125, 216, 195, 0.3); }
  .readout.dim { color: var(--muted); text-shadow: none; }

  /* ------- loading ------- */
  .loading-track { height: 5px; border-radius: 999px; background: #0d1013; border: 1px solid var(--line); overflow: hidden; }
  .loading-fill { height: 100%; width: 0%; background: linear-gradient(90deg, var(--teal), var(--amber)); transition: width 0.25s; }
  .loading-text { margin-top: 7px; font-family: var(--mono); font-size: 0.7rem; color: var(--muted); display: flex; justify-content: space-between; gap: 10px; }

  /* ------- desk layout ------- */
  .desk { display: grid; grid-template-columns: 1.5fr 1fr; gap: 12px; }
  @media (max-width: 860px) { .desk { grid-template-columns: 1fr; } }

  textarea {
    font-family: inherit; font-size: 0.98rem; line-height: 1.6; color: var(--ink);
    background: #0d1014; border: 1px solid var(--line); border-radius: 8px; outline: none;
    width: 100%; padding: 13px 15px; resize: vertical;
  }
  textarea:focus { border-color: var(--line-hi); box-shadow: 0 0 0 3px rgba(255, 180, 84, 0.08); }
  textarea::placeholder { color: var(--dim); }

  .presets { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
  .preset {
    border: 1px solid var(--line); background: #0d1013; color: var(--muted);
    border-radius: 6px; padding: 6px 11px; cursor: pointer;
    font: 550 0.74rem/1.25 inherit; font-family: inherit; transition: all 0.14s;
    max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  .preset:hover { color: var(--ink); border-color: var(--line-hi); background: var(--panel-hi); }
  .preset b { color: var(--teal); font-weight: 700; margin-right: 5px; font-family: var(--mono); font-size: 0.68rem; }

  /* ------- channel strips: voices ------- */
  .voices { display: flex; gap: 8px; }
  .voice-ch {
    flex: 1; border: 1px solid var(--line); border-radius: 9px; cursor: pointer;
    background: #0d1013; color: var(--ink); font-family: inherit;
    padding: 10px 12px; display: flex; align-items: center; gap: 10px; text-align: left; transition: all 0.14s;
  }
  .voice-ch:hover { border-color: var(--line-hi); }
  .voice-ch.active { border-color: rgba(255, 180, 84, 0.55); background: rgba(255, 180, 84, 0.07); box-shadow: 0 0 0 3px rgba(255, 180, 84, 0.07); }
  .voice-ch .vname { font-weight: 700; font-size: 0.86rem; }
  .voice-ch .vdesc { font-size: 0.68rem; color: var(--muted); margin-top: 2px; }

  /* ------- faders ------- */
  .faders { display: flex; justify-content: space-around; gap: 8px; margin-top: 16px; }
  .fader { display: flex; flex-direction: column; align-items: center; gap: 8px; }
  .fader .f-label { font-size: 0.62rem; font-weight: 700; letter-spacing: 0.13em; text-transform: uppercase; color: var(--dim); }
  .fader .f-track {
    height: 132px; width: 46px; display: flex; align-items: center; justify-content: center;
    background:
      repeating-linear-gradient(180deg, transparent 0 12px, rgba(255,255,255,0.05) 12px 13px),
      #0d1013;
    border: 1px solid var(--line); border-radius: 8px; position: relative;
  }
  .fader .f-detent { position: absolute; left: 4px; right: 4px; height: 1px; background: rgba(255, 180, 84, 0.45); pointer-events: none; }
  .fader input[type="range"] {
    appearance: none; -webkit-appearance: none;
    width: 118px; height: 30px; background: transparent; cursor: ns-resize;
    transform: rotate(-90deg);
  }
  .fader input[type="range"]::-webkit-slider-runnable-track { height: 4px; background: #2c333d; border-radius: 2px; }
  .fader input[type="range"]::-webkit-slider-thumb {
    appearance: none; -webkit-appearance: none; width: 14px; height: 26px; margin-top: -11px;
    border-radius: 4px; border: 1px solid #3a424d;
    background: linear-gradient(180deg, #39414c, #21262e);
    box-shadow: 0 2px 6px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.12);
    cursor: grab;
  }
  .fader input[type="range"]::-moz-range-track { height: 4px; background: #2c333d; border-radius: 2px; }
  .fader input[type="range"]::-moz-range-thumb {
    width: 14px; height: 26px; border-radius: 4px; border: 1px solid #3a424d;
    background: linear-gradient(180deg, #39414c, #21262e);
    box-shadow: 0 2px 6px rgba(0,0,0,0.6); cursor: grab;
  }
  .fader .readout { min-width: 62px; text-align: center; }
  .f-hint { font-size: 0.62rem; color: var(--dim); text-align: center; margin-top: 6px; }

  /* ------- transport ------- */
  .transport { display: flex; gap: 8px; margin-top: 16px; }
  .t-btn {
    border: 1px solid var(--line-hi); border-radius: 9px; font-family: inherit; cursor: pointer;
    background: linear-gradient(180deg, #262c35, #181d23); color: var(--ink);
    padding: 13px 10px; font-size: 0.86rem; font-weight: 700; transition: all 0.13s;
    box-shadow: 0 3px 10px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.06);
  }
  .t-btn:hover:not(:disabled) { border-color: #49525e; transform: translateY(-1px); }
  .t-btn:disabled { opacity: 0.45; cursor: wait; }
  .t-btn.speak { flex: 2; background: linear-gradient(180deg, #ffc06e, #e89a3c); color: #2a1503; border-color: #d18a2e; }
  .t-btn.speak:hover:not(:disabled) { box-shadow: 0 6px 18px rgba(255, 170, 60, 0.25); }
  .t-btn.ab { flex: 1; }
  .t-btn.ab.armed { border-color: rgba(125, 216, 195, 0.6); color: var(--teal); box-shadow: 0 0 0 3px rgba(125, 216, 195, 0.08); }

  /* ------- master ------- */
  .master-row { display: flex; align-items: center; gap: 14px; padding: 12px 14px; border-bottom: 1px solid var(--line); }
  .m-btn {
    width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--line-hi); flex-shrink: 0;
    background: linear-gradient(180deg, #262c35, #181d23); color: var(--ink); font-size: 0.95rem; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 3px 10px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.06); transition: all 0.13s;
  }
  .m-btn:hover:not(:disabled) { border-color: #49525e; transform: scale(1.04); }
  .m-btn:disabled { opacity: 0.4; cursor: default; }
  #vu { flex: 1; height: 16px; min-width: 0; background: #0d1013; border: 1px solid var(--line); border-radius: 5px; }
  .master-time { font-family: var(--mono); font-size: 0.78rem; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }

  /* ------- take lanes ------- */
  .lanes { display: flex; flex-direction: column; }
  .lane { border-bottom: 1px solid var(--line); padding: 10px 14px 12px; }
  .lane:last-child { border-bottom: none; }
  .lane-head { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
  .lane-voice {
    font-family: var(--mono); font-size: 0.68rem; font-weight: 700; letter-spacing: 0.08em;
    border-radius: 5px; padding: 3px 8px;
  }
  .lane-voice.f2 { color: var(--amber); background: rgba(255, 180, 84, 0.12); border: 1px solid rgba(255, 180, 84, 0.35); }
  .lane-voice.m2 { color: var(--teal); background: rgba(125, 216, 195, 0.10); border: 1px solid rgba(125, 216, 195, 0.35); }
  .lane-state { font-size: 0.74rem; color: var(--muted); }
  .lane-state.rec { color: var(--red); }
  .lane-state.rec::before { content: "● "; animation: blink 1.1s steps(2) infinite; }
  @keyframes blink { 50% { opacity: 0.25; } }
  .lane-dl {
    margin-left: auto; color: var(--muted); font-size: 0.72rem; font-weight: 650; text-decoration: none;
    border: 1px solid var(--line-hi); border-radius: 6px; padding: 4px 10px; transition: all 0.14s;
  }
  .lane-dl:hover { color: var(--ink); background: var(--panel-hi); }
  .lane-wave { width: 100%; height: 52px; display: block; cursor: pointer; background: #0d1013; border: 1px solid var(--line); border-radius: 7px; }
  .lane-phonemes {
    margin-top: 7px; font-family: var(--mono); font-size: 0.68rem; line-height: 1.6; color: var(--dim);
    max-height: 3.3em; overflow-y: auto; word-break: break-word;
  }
  .lane-phonemes:empty { display: none; }
  .lanes-empty { padding: 22px 14px; text-align: center; color: var(--dim); font-size: 0.8rem; }

  /* ------- takes (history) ------- */
  .takes { display: flex; gap: 6px; flex-wrap: wrap; }
  .take-chip {
    border: 1px solid var(--line); background: #0d1013; color: var(--muted);
    border-radius: 6px; padding: 6px 11px; font: 600 0.72rem/1 inherit; font-family: var(--mono);
    cursor: pointer; transition: all 0.14s;
  }
  .take-chip:hover { color: var(--ink); border-color: var(--line-hi); }

  .foot { margin: 22px 0 4px; font-size: 0.72rem; color: var(--dim); text-align: center; position: relative; z-index: 1; line-height: 1.7; }
  .foot a { color: var(--muted); }

  /* workflow view */
  #workflow-view { position: fixed; inset: 45px 0 34px 0; z-index: 5; background: var(--bg); }
  #workflow-view iframe { width: 100%; height: 100%; border: none; }

  /* status strip */
  .statusbar {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 20;
    display: flex; align-items: center; gap: 10px; padding: 7px 16px;
    background: rgba(10, 12, 15, 0.92); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
    border-top: 1px solid var(--line); font-size: 0.76rem; color: var(--muted);
  }
  #status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .statusbar.busy .pulse { background: var(--amber); box-shadow: 0 0 7px rgba(255, 180, 84, 0.8); animation: pulse 1s ease-in-out infinite; }
  .pulse { width: 8px; height: 8px; border-radius: 50%; background: var(--green); box-shadow: 0 0 7px rgba(53, 208, 127, 0.7); flex-shrink: 0; }
  @keyframes pulse { 50% { opacity: 0.35; } }
  #ep-badge {
    font-family: var(--mono); font-size: 0.66rem; font-weight: 700; letter-spacing: 0.06em;
    border: 1px solid rgba(125, 216, 195, 0.45); color: var(--teal);
    border-radius: 5px; padding: 3px 8px; white-space: nowrap;
  }
  #perf { font-family: var(--mono); font-size: 0.7rem; font-variant-numeric: tabular-nums; white-space: nowrap; }

  @media (max-width: 640px) {
    .brand .brand-sub, .toplink:not(.cta), #perf { display: none; }
  }
</style>
</head>
<body>

<header class="topbar">
  <div class="brand">
    <svg class="mark" viewBox="0 0 26 26" aria-hidden="true">
      <rect width="26" height="26" rx="7" fill="#ffb454"/>
      <path d="M8 9v8M12 6v14M16 10v6M20 12v2" stroke="#2a1503" stroke-width="2.4" stroke-linecap="round"/>
    </svg>
    tiny-voca
    <span class="brand-sub">Studio</span>
  </div>
  <nav class="mode-tabs">
    <button id="mode-studio" class="active">Studio</button>
    <button id="mode-workflow">Workflow</button>
  </nav>
  <div class="spacer"></div>
  <a class="toplink" href="https://huggingface.co/n4ze3m/tiny-voca" target="_blank" rel="noopener">Model card ↗</a>
  <a class="toplink" href="https://github.com/n4ze3m/tiny-voca" target="_blank" rel="noopener">GitHub ↗</a>
  <a class="toplink cta" href="/workflow/?ui=canvas" target="_blank" rel="noopener">Open canvas ↗</a>
</header>

<main id="studio-view">
  <div class="rack">

    <!-- console header -->
    <section class="panel">
      <div class="panel-head">
        <span class="led on amber" id="power-led"></span>tiny-voca · session console
        <div class="right">
          <span class="readout dim">4.5M params</span>
          <span class="readout dim">24 kHz · mono · 16-bit</span>
          <span class="readout teal" id="ep-readout" hidden>—</span>
        </div>
      </div>
      <div class="panel-body" id="loading">
        <div class="loading-track"><div class="loading-fill" id="loading-fill"></div></div>
        <div class="loading-text"><span id="loading-stage">Starting…</span><span>first visit ≈ 40 MB, then cached in this browser</span></div>
      </div>
    </section>

    <div class="desk">
      <!-- program -->
      <section class="panel">
        <div class="panel-head">Program<div class="right"><span class="readout dim"><span id="chars">0</span> / 5000</span></div></div>
        <div class="panel-body">
          <textarea id="text" rows="6" maxlength="5000" placeholder="Type the script — English only. Numbers, dates, money and abbreviations are read aloud like a person would…"></textarea>
          <div class="presets" id="presets"></div>
        </div>
      </section>

      <!-- control -->
      <section class="panel">
        <div class="panel-head">Voices &amp; prosody</div>
        <div class="panel-body">
          <div class="voices">
            <button class="voice-ch active" data-voice="F2">
              <span class="led on amber"></span>
              <span><span class="vname">F2 · female</span><div class="vdesc">bright, youthful</div></span>
            </button>
            <button class="voice-ch" data-voice="M2">
              <span class="led"></span>
              <span><span class="vname">M2 · male</span><div class="vdesc">steady, warm</div></span>
            </button>
          </div>

          <div class="faders">
            <div class="fader">
              <span class="f-label">Speed</span>
              <div class="f-track"><span class="f-detent" id="detent-speed"></span><input type="range" id="speed" min="0.5" max="2" step="0.05" value="1" /></div>
              <span class="readout" id="speed-out">1.00×</span>
            </div>
            <div class="fader">
              <span class="f-label">Pitch</span>
              <div class="f-track"><span class="f-detent" id="detent-pitch"></span><input type="range" id="pitch" min="-0.348" max="0.348" step="0.029" value="0" /></div>
              <span class="readout" id="pitch-out">0.0 st</span>
            </div>
            <div class="fader">
              <span class="f-label">Range</span>
              <div class="f-track"><span class="f-detent" id="detent-range"></span><input type="range" id="range" min="0.5" max="1.5" step="0.05" value="1" /></div>
              <span class="readout" id="range-out">1.00</span>
            </div>
          </div>
          <p class="f-hint">double-click a fader to reset · pitch in semitones</p>

          <div class="transport">
            <button class="t-btn speak" id="run-btn" disabled>Loading…</button>
            <button class="t-btn ab" id="ab-btn" disabled title="Speak the same text with F2 and M2">A/B</button>
          </div>
        </div>
      </section>
    </div>

    <!-- master -->
    <section class="panel">
      <div class="master-row">
        <button class="m-btn" id="play-btn" title="Play / pause" disabled>▶</button>
        <canvas id="vu"></canvas>
        <span class="master-time" id="master-time">00:00.0</span>
        <span class="readout dim" id="master-voice">no take loaded</span>
      </div>
      <div class="lanes" id="lanes">
        <div class="lanes-empty" id="lanes-empty">No takes yet — write a program and press SPEAK. Speech streams in sentence by sentence.</div>
      </div>
    </section>

    <!-- takes -->
    <section class="panel" id="takes-panel" hidden>
      <div class="panel-head">Takes this session</div>
      <div class="panel-body"><div class="takes" id="takes"></div></div>
    </section>

  </div>

  <footer class="foot">
    Unofficial studio · Model by <a href="https://huggingface.co/n4ze3m" target="_blank" rel="noopener">n4ze3m</a> ·
    <a href="https://huggingface.co/n4ze3m/tiny-voca" target="_blank" rel="noopener">Apache-2.0</a> · trained on
    <a href="https://huggingface.co/datasets/n4ze3m/tiny-voca" target="_blank" rel="noopener">synthetic speech</a> — disclose synthetic audio to listeners.<br />
    The model, phonemizer and your text stay in this tab; the Workflow tab speaks on the Space's CPU instead.
  </footer>
</main>

<section id="workflow-view" hidden>
  <iframe id="workflow-frame" title="tiny-voca workflow canvas"></iframe>
</section>

<footer class="statusbar" id="statusbar">
  <div class="pulse"></div>
  <span id="status">Loading…</span>
  <div class="spacer"></div>
  <span id="perf"></span>
  <span id="ep-badge" hidden></span>
</footer>

<audio id="player" hidden></audio>

<script type="module">
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js"; // server fallback only

  const $ = (id) => document.getElementById(id);
  const SAMPLE_RATE = 24000;
  const SEMITONE = 0.058; // model card: 0.058 of log-F0 shift is about one semitone
  const state = { voice: "F2", ready: false, ep: null, server: false, app: null, ab: false };

  const EXAMPLES = [
    ["Hello! This is tiny voca, a small text to speech model that runs on a phone or in a browser.", "F2"],
    ["The meeting moved to 3:30 pm on March 14th, so we have about 45 minutes left.", "M2"],
    ["Did you really think I would forget your birthday?", "F2"],
    ["She had never seen the sea before, and for a long while she stood at the edge of the water without saying a word.", "M2"],
    ["Dr. Patel paid $12.99 for 3 tickets on 3/14 — that's 40% off the usual price.", "F2"],
  ];

  function setStatus(text, busy = false) {
    $("status").textContent = text;
    $("statusbar").classList.toggle("busy", busy);
  }

  // ---------- mode tabs ----------
  let frameLoaded = false;
  function setMode(mode) {
    $("mode-studio").classList.toggle("active", mode === "studio");
    $("mode-workflow").classList.toggle("active", mode === "workflow");
    $("studio-view").style.display = mode === "workflow" ? "none" : "";
    $("workflow-view").hidden = mode !== "workflow";
    if (mode === "workflow" && !frameLoaded) {
      $("workflow-frame").src = "/workflow/?ui=canvas";
      frameLoaded = true;
    }
  }
  $("mode-studio").onclick = () => setMode("studio");
  $("mode-workflow").onclick = () => setMode("workflow");

  // ---------- controls ----------
  $("text").addEventListener("input", () => { $("chars").textContent = $("text").value.length; });

  function setVoice(voice) {
    state.voice = voice;
    document.querySelectorAll(".voice-ch").forEach((ch) => {
      const active = ch.dataset.voice === voice;
      ch.classList.toggle("active", active);
      ch.querySelector(".led").className = active ? "led on amber" : "led";
    });
  }
  document.querySelectorAll(".voice-ch").forEach((ch) => { ch.onclick = () => setVoice(ch.dataset.voice); });

  const DEFAULTS = { speed: 1, pitch: 0, range: 1 };
  function readouts() {
    $("speed-out").textContent = `${(+$("speed").value).toFixed(2)}×`;
    const st = +$("pitch").value / SEMITONE;
    $("pitch-out").textContent = `${st > 0 ? "+" : ""}${st.toFixed(1)} st`;
    $("range-out").textContent = (+$("range").value).toFixed(2);
  }
  for (const id of ["speed", "pitch", "range"]) {
    $(id).addEventListener("input", readouts);
    $(id).addEventListener("dblclick", () => { $(id).value = DEFAULTS[id]; readouts(); });
  }
  // detent markers: fraction of the range that is the default
  function placeDetent(id, min, max, value) {
    $(`detent-${id}`).style.top = `${(1 - (value - min) / (max - min)) * 100}%`;
  }
  placeDetent("speed", 0.5, 2, 1);
  placeDetent("pitch", -0.348, 0.348, 0);
  placeDetent("range", 0.5, 1.5, 1);
  readouts();

  $("ab-btn").onclick = () => {
    state.ab = !state.ab;
    $("ab-btn").classList.toggle("armed", state.ab);
    setStatus(state.ab ? "A/B armed — SPEAK records F2 and M2 back to back." : "A/B off.");
  };

  for (const [text, voice] of EXAMPLES) {
    const chip = document.createElement("button");
    chip.className = "preset";
    chip.innerHTML = `<b>${voice}</b>${text}`;
    chip.title = `${text} · voice: ${voice}`;
    chip.onclick = () => {
      $("text").value = text;
      $("chars").textContent = text.length;
      setVoice(voice);
      $("text").focus();
      setStatus(`Preset loaded — ${voice} will read it. Press SPEAK.`);
    };
    $("presets").appendChild(chip);
  }

  // ---------- shared player + analyser (VU on replay) ----------
  const player = $("player");
  let replayCtx = null, analyser = null;
  const analyserBuf = new Uint8Array(256);
  function ensureAnalyser() {
    if (analyser) return;
    replayCtx = new (window.AudioContext || window.webkitAudioContext)();
    const src = replayCtx.createMediaElementSource(player);
    analyser = replayCtx.createAnalyser();
    analyser.fftSize = 512;
    src.connect(analyser);
    analyser.connect(replayCtx.destination);
  }

  // ---------- VU meter ----------
  const vu = $("vu");
  const vuCtx2d = vu.getContext("2d");
  let vuLevel = 0, vuTarget = 0, vuPeak = 0, vuPeakT = 0;

  function drawVu() {
    const dpr = window.devicePixelRatio || 1;
    const w = vu.clientWidth, h = vu.clientHeight;
    if (w && (vu.width !== Math.round(w * dpr))) { vu.width = Math.round(w * dpr); vu.height = Math.round(h * dpr); }
    if (!w) return;
    vuCtx2d.setTransform(dpr, 0, 0, dpr, 0, 0);
    vuCtx2d.clearRect(0, 0, w, h);
    const segs = 48;
    const gap = 2;
    const sw = (w - gap * (segs - 1)) / segs;
    const lit = Math.round(vuLevel * segs);
    const peakSeg = Math.round(vuPeak * segs) - 1;
    for (let i = 0; i < segs; i++) {
      const f = i / segs;
      const color = f < 0.62 ? "#35d07f" : f < 0.85 ? "#ffb454" : "#ff5d5d";
      vuCtx2d.fillStyle = i < lit ? color : "rgba(255,255,255,0.07)";
      vuCtx2d.fillRect(i * (sw + gap), 2, sw, h - 4);
      if (i === peakSeg && vuPeak > 0.02) {
        vuCtx2d.fillStyle = color;
        vuCtx2d.fillRect(i * (sw + gap), 2, sw, 2.5);
      }
    }
  }

  function vuLoop(t) {
    // live chunks push vuTarget; replay reads the analyser; silence decays
    if (!live && analyser && !player.paused && !player.ended) {
      analyser.getByteTimeDomainData(analyserBuf);
      let peak = 0;
      for (let i = 0; i < analyserBuf.length; i++) {
        const v = Math.abs(analyserBuf[i] - 128) / 128;
        if (v > peak) peak = v;
      }
      vuTarget = peak;
    } else if (!live) {
      vuTarget = 0;
    } else {
      vuTarget *= 0.985; // between sentences, let the meter breathe
    }
    vuLevel = vuTarget > vuLevel ? vuLevel + (vuTarget - vuLevel) * 0.5 : vuLevel * 0.90;
    if (vuLevel > vuPeak) { vuPeak = vuLevel; vuPeakT = t; }
    if (t - vuPeakT > 900) vuPeak *= 0.97;
    drawVu();
    requestAnimationFrame(vuLoop);
  }
  requestAnimationFrame(vuLoop);

  // ---------- waveform helpers ----------
  function peaksOf(samples, bars) {
    const peaks = new Float32Array(bars);
    const step = Math.max(1, Math.floor(samples.length / bars));
    for (let i = 0; i < bars; i++) {
      let peak = 0;
      const start = i * step;
      for (let j = start; j < Math.min(start + step, samples.length); j += 4) {
        const v = Math.abs(samples[j]);
        if (v > peak) peak = v;
      }
      peaks[i] = peak;
    }
    return Array.from(peaks);
  }

  function drawLaneWave(lane, frac = -1) {
    const canvas = lane.waveEl;
    const ctx = canvas.getContext("2d");
    const dpr = window.devicePixelRatio || 1;
    const w = canvas.clientWidth, h = canvas.clientHeight;
    if (!w) return;
    if (canvas.width !== Math.round(w * dpr)) { canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr); }
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, w, h);
    // time ruler (1 s ticks) once duration is known
    if (lane.duration) {
      ctx.fillStyle = "rgba(255,255,255,0.10)";
      const pxPerSec = w / lane.duration;
      for (let s = 1; s < lane.duration; s++) ctx.fillRect(Math.round(s * pxPerSec), h - 7, 1, 7);
    }
    const bars = Math.max(1, lane.peaks.length);
    const gap = 1.5;
    const bw = Math.max(1.2, (w - gap * (bars - 1)) / bars);
    const color = lane.voice === "F2" ? "255,180,84" : "125,216,195";
    for (let i = 0; i < bars; i++) {
      const p = Math.max(0.05, lane.peaks[i] ?? 0.05);
      const bh = Math.max(2, p * (h - 14));
      const x = i * (bw + gap);
      const played = frac >= 0 && i / bars <= frac;
      ctx.fillStyle = played ? `rgba(${color},1)` : `rgba(${color},0.38)`;
      ctx.fillRect(x, (h - 8 - bh) / 2, bw, bh);
    }
  }

  function fmtTime(s) {
    if (!isFinite(s)) s = 0;
    return `${String(Math.floor(s / 60)).padStart(2, "0")}:${(s % 60).toFixed(1).padStart(4, "0")}`;
  }

  function concatChunks(chunks) {
    const total = chunks.reduce((n, c) => n + c.length, 0);
    const out = new Float32Array(total);
    let off = 0;
    for (const c of chunks) { out.set(c, off); off += c.length; }
    return out;
  }

  function wavUrl(samples) {
    const buffer = new ArrayBuffer(44 + samples.length * 2);
    const view = new DataView(buffer);
    const writeStr = (off, s) => { for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i)); };
    writeStr(0, "RIFF"); view.setUint32(4, 36 + samples.length * 2, true); writeStr(8, "WAVE");
    writeStr(12, "fmt "); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
    view.setUint32(24, SAMPLE_RATE, true); view.setUint32(28, SAMPLE_RATE * 2, true);
    view.setUint16(32, 2, true); view.setUint16(34, 16, true);
    writeStr(36, "data"); view.setUint32(40, samples.length * 2, true);
    for (let i = 0; i < samples.length; i++) {
      const s = Math.max(-1, Math.min(1, samples[i]));
      view.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);
    }
    return URL.createObjectURL(new Blob([buffer], { type: "audio/wav" }));
  }

  // ---------- take lanes ----------
  const lanes = []; // newest first
  let currentLane = null;
  let live = null;  // {ctx, next, t0, sources, chunks, samples, lane}

  function laneEl(lane) {
    const el = document.createElement("div");
    el.className = "lane";
    el.innerHTML = `
      <div class="lane-head">
        <span class="lane-voice ${lane.voice.toLowerCase()}">${lane.voice}</span>
        <span class="lane-state rec">recording…</span>
        <a class="lane-dl" hidden download="tiny-voca-${lane.voice.toLowerCase()}.wav">↓ wav</a>
      </div>
      <canvas class="lane-wave"></canvas>
      <div class="lane-phonemes"></div>`;
    lane.el = el;
    lane.waveEl = el.querySelector(".lane-wave");
    lane.stateEl = el.querySelector(".lane-state");
    lane.dlEl = el.querySelector(".lane-dl");
    lane.phonEl = el.querySelector(".lane-phonemes");
    lane.waveEl.addEventListener("click", (e) => {
      if (!lane.url) return;
      if (currentLane !== lane) return loadLane(lane, true);
      if (!player.duration) return;
      const box = lane.waveEl.getBoundingClientRect();
      player.currentTime = Math.min(0.999, Math.max(0, (e.clientX - box.left) / box.width)) * player.duration;
    });
    $("lanes-empty").hidden = true;
    $("lanes").prepend(el);
    requestAnimationFrame(() => drawLaneWave(lane));
    return el;
  }

  function newLane(voice) {
    const lane = { voice, url: null, duration: 0, peaks: [], phonemes: "", meta: "" };
    laneEl(lane);
    lanes.unshift(lane);
    return lane;
  }

  function loadLane(lane, autoplay = false) {
    if (!lane.url) return;
    if (currentLane && currentLane !== lane) drawLaneWave(currentLane, 0);
    currentLane = lane;
    player.src = lane.url;
    $("play-btn").disabled = false;
    $("master-voice").textContent = lane.meta;
    drawLaneWave(lane, 0);
    if (autoplay) { ensureAnalyser(); player.play().catch(() => {}); }
  }

  player.addEventListener("timeupdate", () => {
    if (!currentLane) return;
    drawLaneWave(currentLane, player.duration ? player.currentTime / player.duration : 0);
    $("master-time").textContent = `${fmtTime(player.currentTime)} / ${fmtTime(player.duration)}`;
  });
  player.addEventListener("play", () => { $("play-btn").textContent = "⏸"; });
  player.addEventListener("pause", () => { $("play-btn").textContent = "▶"; });
  player.addEventListener("ended", () => { $("play-btn").textContent = "▶"; if (currentLane) drawLaneWave(currentLane, 0); });

  $("play-btn").onclick = () => {
    if (live) { // a take is streaming: pause the whole live context
      if (live.ctx.state === "running") { live.ctx.suspend(); $("play-btn").textContent = "▶"; }
      else { live.ctx.resume(); $("play-btn").textContent = "⏸"; }
      return;
    }
    if (!currentLane || !player.src) return;
    ensureAnalyser();
    player.paused ? player.play().catch(() => {}) : player.pause();
  };

  function pushTakeChip(lane) {
    $("takes-panel").hidden = false;
    const chip = document.createElement("button");
    chip.className = "take-chip";
    chip.textContent = `${lane.voice} · ${lane.duration.toFixed(1)}s`;
    chip.title = lane.text.slice(0, 140);
    chip.onclick = () => loadLane(lane, true);
    $("takes").prepend(chip);
    while ($("takes").children.length > 12) $("takes").lastChild.remove();
  }

  // ---------- live (streaming) playback ----------
  function stopLive() {
    if (live) { live.ctx.close().catch(() => {}); live = null; }
  }

  function scheduleChunk(samples) {
    const buf = live.ctx.createBuffer(1, samples.length, SAMPLE_RATE);
    buf.getChannelData(0).set(samples);
    const src = live.ctx.createBufferSource();
    src.buffer = buf;
    src.connect(live.ctx.destination);
    const start = Math.max(live.ctx.currentTime + 0.06, live.next);
    src.start(start);
    live.next = start + buf.duration;
    live.sources.push(src);
    // feed the VU from the chunk's own peak
    let peak = 0;
    for (let i = 0; i < samples.length; i += 16) peak = Math.max(peak, Math.abs(samples[i]));
    vuTarget = Math.max(vuTarget, peak);
  }

  function liveTick() {
    if (!live) return;
    const lane = live.lane;
    const played = live.ctx.currentTime - live.t0;
    const total = Math.max(0.01, live.next - live.t0);
    if (lane.duration) drawLaneWave(lane, Math.min(1, played / Math.max(total, lane.duration)));
    $("master-time").textContent = fmtTime(Math.max(0, played));
    if (played < total + 0.3) requestAnimationFrame(liveTick);
  }

  // ---------- in-browser engine (Web Worker) ----------
  let engine = null;
  try {
    engine = window.Worker ? new Worker("/engine.js") : null;
  } catch (err) {
    engine = null;
  }
  let speakId = 0;
  let take = null; // {id, queue, text}

  // A hard worker failure (script fetch, CDN import, crash) never reaches
  // onmessage — fall back to the server instead of hanging on "Loading…".
  if (engine) engine.onerror = (event) => {
    console.warn("engine worker crashed:", event.message);
    if (!state.server) activateServerFallback(event.message || "worker error");
  };

  if (engine) engine.onmessage = (event) => {
    const msg = event.data;
    if (msg.type === "status") {
      $("loading-stage").textContent = msg.message;
      if (typeof msg.progress === "number") $("loading-fill").style.width = `${Math.round(msg.progress * 100)}%`;
      setStatus(msg.message, true);
      return;
    }
    if (msg.type === "ready") {
      state.ready = true;
      state.ep = msg.ep;
      $("loading").hidden = true;
      $("run-btn").disabled = false;
      $("ab-btn").disabled = false;
      $("run-btn").textContent = "● SPEAK";
      $("ep-badge").hidden = false;
      $("ep-readout").hidden = false;
      const label = msg.ep === "webgpu" ? "WebGPU · on your device" : "WASM · on your device";
      $("ep-badge").textContent = label;
      $("ep-readout").textContent = msg.ep === "webgpu" ? "engine: webgpu" : "engine: wasm";
      setStatus(`Ready — the model runs ${msg.ep === "webgpu" ? "on your GPU (WebGPU)" : "in your browser (WASM)"}.`);
      return;
    }
    if (msg.type === "error") {
      if (msg.where === "load") {
        console.warn("in-browser engine failed, using the server:", msg.message);
        activateServerFallback(msg.message);
      } else {
        setStatus(msg.message);
        transportFree();
        if (live) { live.lane.stateEl.textContent = "failed"; live.lane.stateEl.classList.remove("rec"); }
        stopLive();
      }
      return;
    }
    if (!take || msg.id !== take.id) return; // a stale take
    if (msg.type === "sentence") {
      scheduleChunk(msg.audio);
      live.chunks.push(msg.audio);
      live.samples += msg.audio.length;
      const lane = live.lane;
      lane.peaks = peaksOf(concatChunks(live.chunks), 140);
      lane.phonemes += (lane.phonemes ? "\n" : "") + msg.phonemes;
      lane.phonEl.textContent = lane.phonemes;
      lane.phonEl.scrollTop = lane.phonEl.scrollHeight;
      lane.stateEl.textContent = `sentence ${msg.index + 1} / ${msg.total}`;
      drawLaneWave(lane);
      setStatus(`Recording ${lane.voice}… sentence ${msg.index + 1} of ${msg.total}`, true);
      return;
    }
    if (msg.type === "done") {
      finalizeTake(msg);
      return;
    }
  };

  function finalizeTake(msg) {
    const lane = live.lane;
    const url = wavUrl(msg.audio);
    lane.url = url;
    lane.duration = msg.audio.length / SAMPLE_RATE;
    lane.peaks = peaksOf(msg.audio, 140);
    lane.meta = `${lane.voice} · ${lane.duration.toFixed(1)}s · ${msg.utterances} utt`;
    lane.dlEl.href = url;
    lane.dlEl.hidden = false;
    lane.stateEl.textContent = `${lane.duration.toFixed(1)}s · ${msg.utterances} utterance${msg.utterances === 1 ? "" : "s"}`;
    lane.stateEl.classList.remove("rec");
    drawLaneWave(lane);
    pushTakeChip(lane);
    $("perf").textContent = `${lane.duration.toFixed(1)}s in ${msg.seconds.toFixed(2)}s (${(lane.duration / Math.max(msg.seconds, 0.01)).toFixed(0)}× rt)`;

    // swap to the file-backed player when the live stream has drained
    const ctx = live.ctx;
    const remaining = Math.max(0, live.next - ctx.currentTime);
    const doneLane = lane;
    setTimeout(() => {
      if (!live || live.ctx !== ctx) return;
      stopLive();
      $("play-btn").textContent = "▶";
      loadLane(doneLane, false);
      $("master-time").textContent = `00:00.0 / ${fmtTime(doneLane.duration)}`;
    }, remaining * 1000 + 150);

    // A/B: the second voice is queued behind the first
    if (take.queue.length) {
      const nextVoice = take.queue.shift();
      setStatus(`${lane.voice} done — now recording ${nextVoice}…`, true);
      startTake(nextVoice, take.text, take.queue);
    } else {
      transportFree();
      setStatus("Done");
    }
  }

  function transportFree() {
    $("run-btn").disabled = false;
    $("ab-btn").disabled = false;
    $("play-btn").disabled = !currentLane && !live;
  }

  async function startTake(voice, text, queue) {
    stopLive();
    player.removeAttribute("src");
    const ctx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: SAMPLE_RATE });
    await ctx.resume();
    const lane = newLane(voice);
    lane.text = text;
    live = { ctx, next: ctx.currentTime + 0.08, t0: ctx.currentTime + 0.08, sources: [], chunks: [], samples: 0, lane };
    take = { id: take ? take.id : ++speakId, queue, text };
    if (!take.id) take.id = ++speakId;
    currentLane = null;
    $("play-btn").disabled = false;
    $("play-btn").textContent = "⏸";
    $("master-voice").textContent = `${voice} · recording…`;
    setStatus(`Phonemizing for ${voice}…`, true);
    requestAnimationFrame(liveTick);
    engine.postMessage({
      type: "speak", id: take.id, text, voice,
      speed: +$("speed").value,
      pitchShift: +$("pitch").value,
      pitchRange: +$("range").value,
    });
  }

  function generate() {
    const text = $("text").value.trim();
    if (!text) { setStatus("Write a program first."); $("text").focus(); return; }
    if (state.server) return generateOnServer(text);
    $("run-btn").disabled = true;
    $("ab-btn").disabled = true;
    take = null;
    const queue = state.ab ? ["M2"] : [];
    startTake(state.ab ? "F2" : state.voice, text, queue);
  }

  $("run-btn").onclick = generate;
  $("text").addEventListener("keydown", (e) => {
    if ((e.metaKey || e.ctrlKey) && e.key === "Enter" && !$("run-btn").disabled) generate();
  });

  // ---------- server fallback (only if the in-browser engine can't load) ----------
  async function getApp() {
    if (!state.app) state.app = await client(location.origin, { events: ["data", "status"] });
    return state.app;
  }

  function activateServerFallback(reason) {
    state.server = true;
    state.ready = true;
    state.ep = "server";
    $("loading").hidden = true;
    $("run-btn").disabled = false;
    $("ab-btn").disabled = false;
    $("run-btn").textContent = "● SPEAK";
    $("ep-badge").hidden = false;
    $("ep-readout").hidden = false;
    $("ep-badge").textContent = "server CPU";
    $("ep-readout").textContent = "engine: server";
    setStatus("In-browser engine unavailable here — using the Space's CPU instead.");
  }

  function unwrap(result) {
    let data = result?.data;
    if (data && !Array.isArray(data) && Array.isArray(data.data)) data = data.data;
    if (Array.isArray(data)) data = data[0];
    return data ?? {};
  }

  async function serverSpeak(text, voice) {
    const app = await getApp();
    let result = null;
    for await (const msg of app.submit("/speak", {
      text, voice,
      speed: +$("speed").value, pitch_shift: +$("pitch").value, pitch_range: +$("range").value,
    })) {
      if (msg.type === "status") {
        if (msg.stage === "error") throw new Error(msg.message || "Generation failed.");
        continue;
      }
      if (msg.type === "data" || msg.type === "generating") result = msg;
    }
    const item = unwrap(result);
    if (!item.audio_url) throw new Error("No audio came back.");
    return item;
  }

  async function generateOnServer(text) {
    $("run-btn").disabled = true;
    $("ab-btn").disabled = true;
    stopLive();
    try {
      const voices = state.ab ? ["F2", "M2"] : [state.voice];
      for (const voice of voices) {
        setStatus(`Synthesizing ${voice} on the server…`, true);
        const lane = newLane(voice);
        lane.text = text;
        const item = await serverSpeak(text, voice);
        lane.url = item.audio_url;
        lane.duration = item.duration;
        lane.peaks = [0.5];
        lane.meta = `${voice} · ${item.duration}s · ${item.utterances} utt`;
        lane.dlEl.href = item.audio_url;
        lane.dlEl.hidden = false;
        lane.stateEl.textContent = `${item.duration}s · server`;
        lane.stateEl.classList.remove("rec");
        drawLaneWave(lane);
        pushTakeChip(lane);
        loadLane(lane, true);
        $("perf").textContent = `${item.duration}s in ${item.seconds}s`;
      }
      setStatus("Done");
    } catch (err) {
      setStatus(String(err?.message || err));
    } finally {
      transportFree();
    }
  }

  // ---------- boot ----------
  if (!engine) {
    activateServerFallback("Web Workers unavailable");
  } else {
    engine.postMessage({ type: "load" });
    setStatus("Loading the model into your browser…", true);
  }
</script>
</body>
</html>