File size: 44,690 Bytes
82efbf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
"""Side-by-side inspector/editor for one audio file plus two RTTM annotations.

Serves a localhost page with an audio player with interval-selection
playback, and two stacked panels of per-speaker timeline tracks (RTTM A
on top, RTTM B below) sharing one time axis. Speakers of A and B are
auto-matched by maximal overlap so matched speakers share a color and
vertical order, and a "diff" strip between the panels highlights every
region where the two annotations disagree (speech only in A, only in B,
or attributed to different speakers).

Both annotations are editable in place: move/resize segments, reassign
the speaker, split at the playhead, delete, create segments and speaker
lanes, with undo/redo. Each RTTM saves to "<original-stem>_new.rttm"
next to the original file.

Usage:
    python double_rttm_viewer.py audio.wav a.rttm b.rttm [--port 8766]
    open: http://127.0.0.1:8766

The RTTM files are parsed for SPEAKER lines:
    SPEAKER <file-id> <chan> <onset> <duration> <NA> <NA> <speaker> ...
For non-WAV audio the duration is taken from the browser's decoder,
with the last RTTM segment end as the initial estimate.
"""
import argparse
import io
import json
import mimetypes
import os
import re
import wave
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


def parse_rttm(path):
    """Return (segments, file_id, channel) from SPEAKER lines of an RTTM."""
    segments = []
    file_id, chan = None, None
    with open(path, encoding="utf-8") as f:
        for ln, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith((";", "#")):
                continue
            parts = line.split()
            if parts[0] != "SPEAKER":
                continue
            if len(parts) < 8:
                raise ValueError(f"{path}:{ln}: malformed SPEAKER line")
            start, dur = float(parts[3]), float(parts[4])
            segments.append({"start": start, "end": start + dur,
                             "speaker": parts[7]})
            file_id = file_id or parts[1]
            chan = chan or parts[2]
    if not segments:
        raise ValueError(f"{path}: no SPEAKER lines found")
    segments.sort(key=lambda s: s["start"])
    return segments, file_id, chan


def load_audio(path):
    """Return (bytes, content-type, duration-or-None)."""
    with open(path, "rb") as f:
        data = f.read()
    if data[:4] == b"RIFF":
        with wave.open(io.BytesIO(data)) as w:
            return data, "audio/x-wav", w.getnframes() / w.getframerate()
    ctype = mimetypes.guess_type(path)[0] or "audio/mpeg"
    return data, ctype, None  # let the browser report the duration


PAGE = """<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>双 RTTM 对比编辑器</title>
<style>
  :root { --bg:#14161a; --panel:#1e2128; --text:#e6e6e6; --dim:#9aa0aa;
          --accent:#4da3ff; --sel:rgba(255,210,80,.25); --selborder:#ffd250;
          --aonly:#ffb020; --bonly:#3fd0ff; --mismatch:#ff5470;
          --labelw:210px; }
  * { box-sizing:border-box; }
  body { margin:0; background:var(--bg); color:var(--text);
         font:14px/1.5 system-ui,"Segoe UI",sans-serif; }
  header { display:flex; align-items:center; gap:12px; flex-wrap:wrap;
           padding:8px 16px; background:var(--panel);
           border-bottom:1px solid #000; position:sticky; top:0; z-index:6; }
  header .title { font-weight:600; }
  header .dim { color:var(--dim); font-size:12px; }
  button, input[type=text], input[type=number] { background:#2a2e37;
      color:var(--text); border:1px solid #3a3f4a; border-radius:6px;
      padding:4px 10px; font-size:13px; cursor:pointer; }
  button:hover { border-color:var(--accent); }
  button:disabled { opacity:.4; cursor:default; }
  button.dirty { border-color:var(--selborder); color:var(--selborder); }
  input[type=text], input[type=number] { cursor:text;
      font-variant-numeric:tabular-nums; }
  input[type=text]:focus, input[type=number]:focus {
      border-color:var(--selborder); outline:none; }
  #controls { display:flex; align-items:center; gap:10px; flex-wrap:wrap;
              padding:6px 16px; }
  #audio { width:100%; }
  .selinfo { color:var(--dim); font-size:13px; }
  .selinfo b { color:var(--selborder); font-weight:600; }
  #zoomwrap { margin-left:auto; display:flex; align-items:center; gap:6px;
              color:var(--dim); font-size:12px; }
  #diffstats { font-size:13px; }
  #diffstats b { font-weight:600; }
  .sw { display:inline-block; width:9px; height:9px; border-radius:2px;
        margin:0 3px 0 10px; vertical-align:baseline; }
  #editbar { display:none; align-items:center; gap:8px; flex-wrap:wrap;
             margin:0 16px 6px; padding:6px 12px; background:#262b35;
             border:1px solid var(--selborder); border-radius:8px; }
  #editbar .tag { font-weight:600; color:var(--selborder); }
  #editbar input[type=text] { width:90px; }
  #editbar #ebspk { width:120px; }
  #tracks-outer { margin:0 16px 24px; border:1px solid #2a2e37;
                  border-radius:8px; overflow-x:auto; background:var(--panel); }
  #tracks { position:relative; min-width:100%; }
  #ruler { position:relative; height:26px; border-bottom:1px solid #2a2e37;
           cursor:crosshair; user-select:none; }
  .tick { position:absolute; top:0; height:100%; border-left:1px solid #333842;
          color:var(--dim); font-size:10px; padding:2px 0 0 3px; }
  .panel-sep { position:relative; height:28px; background:#171a20;
               border-bottom:1px solid #262a32; }
  .panel-sep .lane-label { font-size:12px; max-width:none; color:var(--dim);
                           pointer-events:auto; }
  .panel-sep b { color:var(--text); }
  .panel-sep button { padding:1px 8px; font-size:11px; }
  .lane { position:relative; height:34px; border-bottom:1px solid #262a32; }
  .lane-label { position:sticky; left:0; z-index:5; display:inline-flex;
      align-items:center; gap:6px; height:100%; padding:0 8px;
      width:var(--labelw); background:var(--panel);
      border-right:1px solid #2a2e37;
      font-size:12px; white-space:nowrap;
      overflow:hidden; text-overflow:ellipsis; pointer-events:none; }
  .panel-sep .lane-label { width:auto; min-width:var(--labelw); }
  .gutter-mask { position:sticky; left:0; z-index:5; display:inline-block;
      width:var(--labelw); height:100%; background:var(--panel);
      border-right:1px solid #2a2e37; }
  .lane-label .swatch { width:10px; height:10px; border-radius:2px; flex:none; }
  .lane-label button { pointer-events:auto; padding:0 6px; font-size:11px; }
  .seg { position:absolute; top:7px; height:20px; border-radius:3px;
         opacity:.85; cursor:grab; min-width:2px; }
  .seg:hover { opacity:1; outline:1px solid #fff; z-index:2; }
  .seg.selected { opacity:1; outline:2px solid #fff; z-index:3; }
  .difflane { position:relative; height:26px; background:#101216;
              border-bottom:1px solid #262a32; }
  .difflane .lane-label { font-size:11px; }
  .diffseg { position:absolute; top:6px; height:14px; border-radius:2px;
             opacity:.9; cursor:pointer; min-width:2px; }
  .diffseg:hover { opacity:1; outline:1px solid #fff; z-index:2; }
  #playhead { position:absolute; top:0; bottom:0; width:1px;
              background:#ff5555; z-index:4; pointer-events:none; }
  #selbox { position:absolute; top:0; bottom:0; background:var(--sel);
            border-left:1px solid var(--selborder);
            border-right:1px solid var(--selborder);
            z-index:1; pointer-events:none; display:none; }
  #hint { padding:0 16px 12px; color:var(--dim); font-size:12px; }
  #err { color:#ff7070; padding:8px 16px; display:none; }
  #savemsg { font-size:12px; color:#7ddf8f; }
</style>
</head>
<body>
<header>
  <span class="title">双 RTTM 对比编辑器</span>
  <span class="dim" id="fname"></span>
  <span class="dim" id="rowinfo"></span>
  <span style="margin-left:auto"></span>
  <button id="savea"></button>
  <button id="saveb"></button>
  <span id="savemsg"></span>
</header>
<div id="err"></div>
<div id="controls">
  <audio id="audio" controls preload="auto"></audio>
</div>
<div id="controls">
  <button id="playsel" disabled>▶ 播放选区</button>
  <label class="dim"><input type="checkbox" id="loop"> 循环</label>
  <button id="clearsel" disabled>清除选区</button>
  <span class="dim">选区</span>
  <input type="text" id="selstart" placeholder="起 (秒或分:秒)" style="width:110px">
  <span class="dim">→</span>
  <input type="text" id="selend" placeholder="止 (秒或分:秒)" style="width:110px">
  <button id="applysel">应用</button>
  <span class="selinfo" id="selinfo">拖动空白选择区间;单击色块选中编辑</span>
  <label class="dim" style="margin-left:auto"><input type="checkbox" id="follow" checked> 跟随播放</label>
  <span id="zoomwrap" style="margin-left:0">缩放
    <input type="range" id="zoom" min="0" max="100" value="0" style="width:140px">
    <span id="zoomval">1×</span>
  </span>
</div>
<div id="controls">
  <span id="diffstats" class="dim">…</span>
  <span class="dim" style="margin-left:auto">忽略短于</span>
  <input type="number" id="mindiff" value="0.25" min="0" step="0.05" style="width:70px">
  <span class="dim">s 的差异</span>
  <button id="remap" title="按当前标注重新计算 A↔B 说话人配对与配色">重算说话人配对</button>
</div>
<div id="editbar">
  <span class="tag" id="ebtitle"></span>
  <span class="dim">说话人</span><input type="text" id="ebspk" list="spklist">
  <datalist id="spklist"></datalist>
  <span class="dim">起</span><input type="text" id="ebstart">
  <span class="dim">止</span><input type="text" id="ebend">
  <span class="dim" id="ebdur"></span>
  <button id="ebapply">应用 (Enter)</button>
  <button id="ebplay">▶ 播放该段</button>
  <button id="ebsplit">✂ 在播放头拆分 (S)</button>
  <button id="ebdel">🗑 删除 (Del)</button>
  <button id="ebclose">取消 (Esc)</button>
</div>
<div id="tracks-outer"><div id="tracks">
  <div id="ruler"></div>
  <div id="lanes"></div>
  <div id="selbox"></div>
  <div id="playhead" style="left:0"></div>
</div></div>
<div id="hint">单击色块=选中编辑 · 双击色块=播放该段 · 拖动色块=移动 ·
拖动色块边缘=调整边界 · Alt+在泳道空白拖动=新建段 · 泳道"+段"=把选区加为该说话人的段 ·
空白拖动=选区 / 单击=定位 · Del=删除 S=拆分 Ctrl+Z/Ctrl+Shift+Z=撤销/重做 ·
空格=播放/暂停 ←/→=±5s Shift+←/→=±0.5s Esc=取消</div>
<script>
const $ = id => document.getElementById(id);
const audio = $('audio');
const PALETTE = ['#4da3ff','#ff9f43','#2ecc71','#e74c3c','#a55eea','#f1c40f',
                 '#1abc9c','#fd79a8','#74b9ff','#e17055','#81ecec','#b8e994',
                 '#ffbe76','#badc58','#7ed6df','#e056fd','#f8a5c2','#63cdda'];
const CATNAME = {aonly:'仅A有语音', bonly:'仅B有语音', mismatch:'说话人不一致'};
const CATCOLOR = {aonly:'var(--aonly)', bonly:'var(--bonly)',
                  mismatch:'var(--mismatch)'};
let meta = null, dur = 0, zoomFactor = 1;
let sel = null;              // {start, end} seconds
let dragging = null;         // select | create | move | resize-l | resize-r
let selected = null;         // {file:'a'|'b', id}
let mapping = null;          // {pairs, colorOf:Map, nextColor}
let diffRegions = [], diffStats = null;
let nextId = 1;
const undoStack = {a:[], b:[]}, redoStack = {a:[], b:[]};
const dirty = {a:false, b:false};

function fmt(t) {
  const h = Math.floor(t/3600), m = Math.floor(t%3600/60), s = t%60;
  return (h? h+':' : '') + String(m).padStart(2,'0') + ':' +
         s.toFixed(2).padStart(5,'0');
}
const LABEL_W = 210;  // keep in sync with --labelw
function pxPerSec() {
  const w = $('tracks-outer').clientWidth - LABEL_W - 2;
  return (w / dur) * zoomFactor;
}
// content x-position of time t (timeline starts right of the label gutter)
function tX(t) { return LABEL_W + t * pxPerSec(); }
function xToTime(clientX) {
  const r = $('tracks').getBoundingClientRect();
  return Math.min(dur, Math.max(0,
      (clientX - r.left - LABEL_W) / pxPerSec()));
}
const natCmp = (a, b) => a.localeCompare(b, undefined, {numeric:true});
function findSeg(file, id) {
  return meta.files[file].segments.find(s => s.id === id);
}

/* ---------- speaker mapping (A<->B) and colors ---------- */

function speakerList(file) {
  const f = meta.files[file];
  const spks = new Set(f.segments.map(s => s.speaker));
  f.extraSpeakers.forEach(s => spks.add(s));
  return [...spks];
}

// pair A/B speakers maximizing total overlap duration; exact bitmask DP
// over the smaller side (fallback: greedy when both sides are large)
function bestPairs(ov, nA, nB) {
  let flip = false;
  if (nB > nA) {  // make B (mask side) the smaller one
    flip = true;
    const t = [];
    for (let j = 0; j < nB; j++) { t.push(ov.map(row => row[j])); }
    ov = t; [nA, nB] = [nB, nA];
  }
  let pairs = [];
  if (nB > 14) {  // greedy fallback
    const all = [];
    for (let i = 0; i < nA; i++)
      for (let j = 0; j < nB; j++)
        if (ov[i][j] > 0) all.push([ov[i][j], i, j]);
    all.sort((x, y) => y[0] - x[0]);
    const ua = new Set(), ub = new Set();
    for (const [, i, j] of all) {
      if (ua.has(i) || ub.has(j)) continue;
      ua.add(i); ub.add(j); pairs.push([i, j]);
    }
  } else {
    const FULL = 1 << nB;
    let dp = new Float64Array(FULL).fill(-1); dp[0] = 0;
    const choice = [];
    for (let i = 0; i < nA; i++) {
      const ndp = new Float64Array(FULL).fill(-1);
      const ch = new Int8Array(FULL).fill(-2);
      for (let mask = 0; mask < FULL; mask++) {
        if (dp[mask] < 0) continue;
        if (dp[mask] > ndp[mask]) { ndp[mask] = dp[mask]; ch[mask] = -1; }
        for (let j = 0; j < nB; j++) {
          if (mask & (1 << j) || ov[i][j] <= 0) continue;
          const nm = mask | (1 << j), v = dp[mask] + ov[i][j];
          if (v > ndp[nm]) { ndp[nm] = v; ch[nm] = j; }
        }
      }
      dp = ndp; choice.push(ch);
    }
    let best = 0;
    for (let m = 0; m < FULL; m++) if (dp[m] > dp[best]) best = m;
    let mask = best;
    for (let i = nA - 1; i >= 0; i--) {
      const j = choice[i][mask];
      if (j >= 0) { pairs.push([i, j]); mask ^= 1 << j; }
    }
  }
  if (flip) pairs = pairs.map(([i, j]) => [j, i]);
  return pairs;
}

function computeMapping() {
  const A = speakerList('a').sort(natCmp), B = speakerList('b').sort(natCmp);
  const ov = A.map(() => B.map(() => 0));
  const bBySpk = new Map(B.map((s, j) => [s, j]));
  const aBySpk = new Map(A.map((s, i) => [s, i]));
  const bSegs = meta.files.b.segments;
  for (const sa of meta.files.a.segments) {
    const i = aBySpk.get(sa.speaker);
    for (const sb of bSegs) {
      const o = Math.min(sa.end, sb.end) - Math.max(sa.start, sb.start);
      if (o > 0) ov[i][bBySpk.get(sb.speaker)] += o;
    }
  }
  const idx = bestPairs(ov, A.length, B.length);
  idx.sort((p, q) => ov[q[0]][q[1]] - ov[p[0]][p[1]]);  // strongest first
  mapping = {pairs: idx.map(([i, j]) => ({a: A[i], b: B[j]})),
             colorOf: new Map(), nextColor: 0};
  mapping.pairs.forEach((p, k) => {
    mapping.colorOf.set('a|' + p.a, k);
    mapping.colorOf.set('b|' + p.b, k);
  });
  mapping.nextColor = mapping.pairs.length;
  for (const file of ['a', 'b'])
    for (const spk of speakerList(file).sort(natCmp)) {
      const key = file + '|' + spk;
      if (!mapping.colorOf.has(key))
        mapping.colorOf.set(key, mapping.nextColor++);
    }
}

function colorFor(file, spk) {
  const key = file + '|' + spk;
  if (!mapping.colorOf.has(key))
    mapping.colorOf.set(key, mapping.nextColor++);
  return PALETTE[mapping.colorOf.get(key) % PALETTE.length];
}
function pairedWith(file, spk) {
  for (const p of mapping.pairs)
    if (p[file] === spk) return p[file === 'a' ? 'b' : 'a'];
  return null;
}
function mappedId(file, spk) {
  const k = mapping.pairs.findIndex(p => p[file] === spk);
  return k >= 0 ? 'P' + k : file.toUpperCase() + '#' + spk;
}
function laneOrder(file) {
  const spks = new Set(speakerList(file));
  const paired = mapping.pairs.map(p => p[file]).filter(s => spks.has(s));
  const rest = [...spks].filter(s => !paired.includes(s)).sort(natCmp);
  return [...paired, ...rest];
}

/* ---------- diff computation ---------- */

function computeDiff() {
  const bounds = new Set();
  const evts = {a: [], b: []};
  for (const file of ['a', 'b'])
    for (const s of meta.files[file].segments) {
      bounds.add(s.start); bounds.add(s.end);
      evts[file].push([s.start, 1, s.speaker], [s.end, -1, s.speaker]);
    }
  const ts = [...bounds].sort((x, y) => x - y);
  for (const file of ['a', 'b'])
    evts[file].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
  const act = {a: new Map(), b: new Map()};
  const ptr = {a: 0, b: 0};
  const raw = [];
  for (let k = 0; k + 1 < ts.length; k++) {
    const t0 = ts[k], t1 = ts[k + 1];
    for (const file of ['a', 'b']) {
      const e = evts[file], m = act[file];
      while (ptr[file] < e.length && e[ptr[file]][0] <= t0 + 1e-9) {
        const [, d, spk] = e[ptr[file]++];
        m.set(spk, (m.get(spk) || 0) + d);
        if (m.get(spk) <= 0) m.delete(spk);
      }
    }
    const aSpk = [...act.a.keys()], bSpk = [...act.b.keys()];
    if (!aSpk.length && !bSpk.length) continue;
    const sa = aSpk.map(s => mappedId('a', s)).sort().join(',');
    const sb = bSpk.map(s => mappedId('b', s)).sort().join(',');
    const cat = sa === sb ? 'same' : !aSpk.length ? 'bonly'
              : !bSpk.length ? 'aonly' : 'mismatch';
    raw.push({t0, t1, cat, sa, sb,
              aSpk: aSpk.sort(natCmp), bSpk: bSpk.sort(natCmp)});
  }
  // merge contiguous regions with identical category and speaker sets
  const merged = [];
  for (const r of raw) {
    const last = merged[merged.length - 1];
    if (last && last.cat === r.cat && last.sa === r.sa && last.sb === r.sb &&
        Math.abs(last.t1 - r.t0) < 1e-6) last.t1 = r.t1;
    else merged.push({...r});
  }
  diffStats = {union: 0, same: 0, aonly: 0, bonly: 0, mismatch: 0};
  for (const r of merged) {
    const d = r.t1 - r.t0;
    diffStats.union += d;
    diffStats[r.cat] += d;
  }
  diffRegions = merged.filter(r => r.cat !== 'same');
  renderStats();
}

function renderStats() {
  const s = diffStats;
  const pct = s.union ? (100 * s.same / s.union).toFixed(1) : '100.0';
  $('diffstats').innerHTML =
    `一致 <b>${pct}%</b>(按语音时长)` +
    `<span class="sw" style="background:var(--aonly)"></span>仅A ${s.aonly.toFixed(1)}s` +
    `<span class="sw" style="background:var(--bonly)"></span>仅B ${s.bonly.toFixed(1)}s` +
    `<span class="sw" style="background:var(--mismatch)"></span>不一致 ${s.mismatch.toFixed(1)}s`;
}

/* ---------- rendering ---------- */

function render() {
  const pps = pxPerSec(), width = Math.ceil(LABEL_W + dur * pps);
  $('tracks').style.width = width + 'px';

  const ruler = $('ruler');
  ruler.innerHTML = '';
  const mask = document.createElement('div');
  mask.className = 'gutter-mask';
  ruler.appendChild(mask);
  const steps = [0.1,0.2,0.5,1,2,5,10,15,30,60,120,300,600,1200,1800,3600];
  const step = steps.find(s => s*pps >= 90) || 3600;
  for (let t = 0; t <= dur; t += step) {
    if (tX(t) + 60 > width) break;  // skip ticks whose text would overflow
    const d = document.createElement('div');
    d.className = 'tick';
    d.style.left = tX(t) + 'px';
    d.textContent = fmt(t);
    ruler.appendChild(d);
  }

  const lanes = $('lanes');
  lanes.innerHTML = '';
  buildPanel(lanes, 'a', pps);
  buildDiffLane(lanes, pps);
  buildPanel(lanes, 'b', pps);
  updateSaveBtns();
  updateInfo();
  drawSel();
  movePlayhead();
}

function buildPanel(parent, file, pps) {
  const f = meta.files[file];
  const sep = document.createElement('div');
  sep.className = 'panel-sep';
  const spkN = new Set(f.segments.map(s => s.speaker)).size;
  sep.innerHTML =
    `<span class="lane-label"><b>${file.toUpperCase()}</b>·${f.rttm_file}` +
    ` · ${f.segments.length} 段 · ${spkN} 人 ` +
    `<button data-addspk="${file}">+新说话人</button></span>`;
  parent.appendChild(sep);

  for (const spk of laneOrder(file)) {
    const lane = document.createElement('div');
    lane.className = 'lane';
    lane.dataset.file = file;
    lane.dataset.speaker = spk;
    const color = colorFor(file, spk);
    const segs = f.segments.filter(s => s.speaker === spk);
    const partner = pairedWith(file, spk);
    const label = document.createElement('span');
    label.className = 'lane-label';
    label.innerHTML =
      `<span class="swatch" style="background:${color}"></span>${spk} ` +
      `<span style="color:var(--dim)">(${segs.length}` +
      (partner !== null ? ` ⇄ ${file === 'a' ? 'B' : 'A'}:${partner}` : '') +
      `)</span> <button data-addseg title="把当前选区加为该说话人的段">+段</button>`;
    lane.appendChild(label);
    for (const s of segs) {
      const d = document.createElement('div');
      d.className = 'seg';
      d.dataset.file = file;
      d.dataset.segId = s.id;
      if (selected && selected.file === file && selected.id === s.id)
        d.classList.add('selected');
      d.style.left = tX(s.start) + 'px';
      d.style.width = Math.max(2, (s.end-s.start)*pps) + 'px';
      d.style.background = colorFor(file, spk);
      d.title = `${file.toUpperCase()}:${spk}\\n${fmt(s.start)} → ${fmt(s.end)}` +
                `  (${(s.end-s.start).toFixed(2)}s)`;
      lane.appendChild(d);
    }
    parent.appendChild(lane);
  }
}

function buildDiffLane(parent, pps) {
  const lane = document.createElement('div');
  lane.className = 'difflane';
  const minDiff = parseFloat($('mindiff').value) || 0;
  const shown = diffRegions.filter(r => r.t1 - r.t0 >= minDiff);
  lane.innerHTML = `<span class="lane-label">差异 ` +
    `<span style="color:var(--dim)">(${shown.length})</span></span>`;
  for (const r of shown) {
    const d = document.createElement('div');
    d.className = 'diffseg';
    d.dataset.t0 = r.t0;
    d.dataset.t1 = r.t1;
    d.style.left = tX(r.t0) + 'px';
    d.style.width = Math.max(2, (r.t1-r.t0)*pps) + 'px';
    d.style.background = CATCOLOR[r.cat];
    d.title = `${CATNAME[r.cat]}  ${fmt(r.t0)} → ${fmt(r.t1)}` +
              ` (${(r.t1-r.t0).toFixed(2)}s)\\n` +
              `A: ${r.aSpk.join(', ') || '-'}\\nB: ${r.bSpk.join(', ') || '-'}`;
    lane.appendChild(d);
  }
  parent.appendChild(lane);
}

function updateInfo() {
  $('rowinfo').textContent = `时长 ${fmt(dur)}`;
}
function updateSaveBtns() {
  for (const file of ['a', 'b']) {
    const b = $('save' + file);
    b.textContent = `保存${file.toUpperCase()} → ${meta.files[file].out_file}` +
                    (dirty[file] ? ' *' : '');
    b.classList.toggle('dirty', dirty[file]);
  }
}

/* ---------- selection & playback (interval) ---------- */

function setSel(a, b, keepInputs) {
  if (b < a) [a, b] = [b, a];
  sel = {start: a, end: b};
  $('playsel').disabled = $('clearsel').disabled = false;
  $('selinfo').innerHTML =
    `选区 <b>${fmt(a)}</b> → <b>${fmt(b)}</b> (${(b-a).toFixed(2)}s)`;
  if (!keepInputs) {
    $('selstart').value = a.toFixed(3);
    $('selend').value = b.toFixed(3);
  }
  drawSel();
}
function clearSel() {
  sel = null;
  $('playsel').disabled = $('clearsel').disabled = true;
  $('selstart').value = $('selend').value = '';
  $('selinfo').textContent = '拖动空白选择区间;单击色块选中编辑';
  drawSel();
}
function parseTime(str) {
  str = str.trim();
  if (!str) return null;
  const parts = str.split(':');
  if (parts.some(p => p.trim() === '' || isNaN(p))) return null;
  return parts.reduce((t, p) => t * 60 + parseFloat(p), 0);
}
function applyManualSel() {
  const a = parseTime($('selstart').value);
  const b = parseTime($('selend').value);
  if (a === null || b === null || a < 0 || b <= a || a >= dur) {
    $('selinfo').innerHTML = '<span style="color:#ff7070">无效区间:' +
      '支持 秒 或 分:秒 格式,需满足 0 ≤ 起 &lt; 止</span>';
    return;
  }
  setSel(a, Math.min(b, dur), true);
  playSel();
}
function drawSel() {
  const box = $('selbox');
  if (!sel) { box.style.display = 'none'; return; }
  box.style.display = 'block';
  box.style.left = tX(sel.start) + 'px';
  box.style.width = ((sel.end-sel.start)*pxPerSec()) + 'px';
}
function playSel() {
  if (!sel) return;
  audio.currentTime = sel.start;
  audio.play();
}
audio.addEventListener('timeupdate', () => {
  if (sel && !audio.paused && audio.currentTime >= sel.end) {
    if ($('loop').checked) audio.currentTime = sel.start;
    else audio.pause();
  }
});

function movePlayhead() {
  $('playhead').style.left = tX(audio.currentTime) + 'px';
}
let progScroll = false;
function followPlayhead(force) {
  if (!$('follow').checked || !dur) return;
  const outer = $('tracks-outer');
  if (outer.scrollWidth <= outer.clientWidth + 1) return;
  const x = tX(audio.currentTime);
  const lo = outer.scrollLeft + LABEL_W + 10;
  const hi = outer.scrollLeft + outer.clientWidth - 40;
  if (force || x < lo || x > hi) {
    progScroll = true;
    outer.scrollLeft = Math.max(0,
        x - LABEL_W - (outer.clientWidth - LABEL_W) * 0.15);
  }
}
$('tracks-outer').addEventListener('scroll', () => {
  if (progScroll) { progScroll = false; return; }
  if (!audio.paused) $('follow').checked = false;
});
$('follow').onchange = () => followPlayhead(true);
audio.addEventListener('seeked', () => followPlayhead(true));
(function raf() {
  movePlayhead();
  if (!audio.paused) followPlayhead();
  requestAnimationFrame(raf);
})();

/* ---------- editing ---------- */

function pushUndo(file) {
  const f = meta.files[file];
  undoStack[file].push(JSON.stringify(
      {segments: f.segments, extraSpeakers: [...f.extraSpeakers]}));
  if (undoStack[file].length > 200) undoStack[file].shift();
  redoStack[file].length = 0;
}
function restore(file, snap) {
  const f = meta.files[file];
  const o = JSON.parse(snap);
  f.segments = o.segments;
  f.extraSpeakers = new Set(o.extraSpeakers);
}
function snapshot(file) {
  const f = meta.files[file];
  return JSON.stringify(
      {segments: f.segments, extraSpeakers: [...f.extraSpeakers]});
}
function undo(file) {
  if (!undoStack[file].length) return;
  redoStack[file].push(snapshot(file));
  restore(file, undoStack[file].pop());
  afterEdit(file, true);
}
function redo(file) {
  if (!redoStack[file].length) return;
  undoStack[file].push(snapshot(file));
  restore(file, redoStack[file].pop());
  afterEdit(file, true);
}
// after any data mutation: mark dirty, recompute diff, redraw
function afterEdit(file, checkSelection) {
  dirty[file] = true;
  if (checkSelection && selected && selected.file === file &&
      !findSeg(file, selected.id)) deselectSeg();
  computeDiff();
  render();
  refreshEditbar();
}
function lastEditedFile() {
  return selected ? selected.file : null;
}

function selectSeg(file, id) {
  selected = {file, id};
  document.querySelectorAll('.seg.selected')
      .forEach(e => e.classList.remove('selected'));
  const el = document.querySelector(
      `.seg[data-file="${file}"][data-seg-id="${id}"]`);
  if (el) el.classList.add('selected');
  refreshEditbar();
}
function deselectSeg() {
  selected = null;
  document.querySelectorAll('.seg.selected')
      .forEach(e => e.classList.remove('selected'));
  refreshEditbar();
}
function refreshEditbar() {
  const bar = $('editbar');
  if (!selected) { bar.style.display = 'none'; return; }
  const s = findSeg(selected.file, selected.id);
  if (!s) { bar.style.display = 'none'; return; }
  bar.style.display = 'flex';
  $('ebtitle').textContent =
      `${selected.file.toUpperCase()} · ${s.speaker}`;
  $('ebspk').value = s.speaker;
  $('ebstart').value = s.start.toFixed(3);
  $('ebend').value = s.end.toFixed(3);
  $('ebdur').textContent = `(${(s.end - s.start).toFixed(2)}s)`;
  const dl = $('spklist');
  dl.innerHTML = '';
  for (const spk of laneOrder(selected.file)) {
    const o = document.createElement('option');
    o.value = spk;
    dl.appendChild(o);
  }
}
function applyEditbar() {
  if (!selected) return;
  const s = findSeg(selected.file, selected.id);
  const start = parseTime($('ebstart').value);
  const end = parseTime($('ebend').value);
  const spk = $('ebspk').value.trim();
  if (start === null || end === null || !spk ||
      start < 0 || end <= start || start >= dur) {
    $('ebdur').textContent = '(无效输入)';
    return;
  }
  pushUndo(selected.file);
  s.start = start; s.end = Math.min(end, dur); s.speaker = spk;
  afterEdit(selected.file);
}
function splitSelected() {
  if (!selected) return;
  const s = findSeg(selected.file, selected.id);
  const t = audio.currentTime;
  if (t <= s.start + 0.02 || t >= s.end - 0.02) {
    $('ebdur').textContent = '(播放头不在段内,无法拆分)';
    return;
  }
  pushUndo(selected.file);
  const right = {id: nextId++, start: t, end: s.end, speaker: s.speaker};
  s.end = t;
  meta.files[selected.file].segments.push(right);
  afterEdit(selected.file);
}
function deleteSelected() {
  if (!selected) return;
  const f = meta.files[selected.file];
  pushUndo(selected.file);
  f.segments = f.segments.filter(s => s.id !== selected.id);
  const file = selected.file;
  deselectSeg();
  afterEdit(file);
}
function addSegFromSel(file, spk) {
  if (!sel) {
    $('selinfo').innerHTML =
        '<span style="color:#ff7070">先拖动选择一个区间,再点 +段</span>';
    return;
  }
  pushUndo(file);
  const s = {id: nextId++, start: sel.start, end: sel.end, speaker: spk};
  meta.files[file].segments.push(s);
  afterEdit(file);
  selectSeg(file, s.id);
}
function addSpeaker(file) {
  const name = prompt('新说话人标签(仅用于本页;保存时无段的说话人不会写入 RTTM):');
  if (!name || !name.trim()) return;
  meta.files[file].extraSpeakers.add(name.trim());
  render();
}

/* ---------- mouse interactions on tracks ---------- */

const tracksEl = $('tracks');
tracksEl.addEventListener('mousedown', ev => {
  const segEl = ev.target.closest('.seg');
  if (segEl) {
    const file = segEl.dataset.file, id = +segEl.dataset.segId;
    const r = segEl.getBoundingClientRect();
    const x = ev.clientX - r.left;
    const edge = Math.min(6, r.width / 3);
    const mode = r.width >= 12 && x < edge ? 'resize-l'
               : r.width >= 12 && x > r.width - edge ? 'resize-r' : 'move';
    const s = findSeg(file, id);
    dragging = {mode, file, id, el: segEl, moved: false, pushed: false,
                grabOffset: xToTime(ev.clientX) - s.start};
    ev.preventDefault();
    return;
  }
  const diffEl = ev.target.closest('.diffseg');
  if (diffEl) {
    dragging = {mode: 'select', anchor: xToTime(ev.clientX), moved: false,
                diffEl};
    ev.preventDefault();
    return;
  }
  const lane = ev.target.closest('.lane');
  if (ev.altKey && lane) {
    dragging = {mode: 'create', file: lane.dataset.file,
                spk: lane.dataset.speaker, lane,
                anchor: xToTime(ev.clientX), t0: null, t1: null,
                el: null, moved: false};
    ev.preventDefault();
    return;
  }
  dragging = {mode: 'select', anchor: xToTime(ev.clientX), moved: false};
  ev.preventDefault();
});

window.addEventListener('mousemove', ev => {
  if (!dragging) return;
  const t = xToTime(ev.clientX);
  const pps = pxPerSec();
  if (dragging.mode === 'select') {
    if (Math.abs(t - dragging.anchor) * pps > 3) {
      dragging.moved = true;
      setSel(dragging.anchor, t);
    }
  } else if (dragging.mode === 'create') {
    if (Math.abs(t - dragging.anchor) * pps > 3) {
      dragging.moved = true;
      dragging.t0 = Math.min(dragging.anchor, t);
      dragging.t1 = Math.max(dragging.anchor, t);
      if (!dragging.el) {
        dragging.el = document.createElement('div');
        dragging.el.className = 'seg';
        dragging.el.style.background =
            colorFor(dragging.file, dragging.spk);
        dragging.el.style.opacity = '0.6';
        dragging.lane.appendChild(dragging.el);
      }
      dragging.el.style.left = tX(dragging.t0) + 'px';
      dragging.el.style.width = Math.max(2, (dragging.t1-dragging.t0)*pps) + 'px';
    }
  } else {  // move / resize
    const s = findSeg(dragging.file, dragging.id);
    if (!s) { dragging = null; return; }
    if (!dragging.pushed) { pushUndo(dragging.file); dragging.pushed = true; }
    dragging.moved = true;
    if (dragging.mode === 'move') {
      const len = s.end - s.start;
      const ns = Math.min(Math.max(t - dragging.grabOffset, 0), dur - len);
      s.start = ns; s.end = ns + len;
    } else if (dragging.mode === 'resize-l') {
      s.start = Math.min(Math.max(t, 0), s.end - 0.02);
    } else {
      s.end = Math.max(Math.min(t, dur), s.start + 0.02);
    }
    dragging.el.style.left = tX(s.start) + 'px';
    dragging.el.style.width = Math.max(2, (s.end-s.start)*pps) + 'px';
    if (selected && selected.file === dragging.file &&
        selected.id === dragging.id) {
      $('ebstart').value = s.start.toFixed(3);
      $('ebend').value = s.end.toFixed(3);
      $('ebdur').textContent = `(${(s.end - s.start).toFixed(2)}s)`;
    }
  }
});

window.addEventListener('mouseup', ev => {
  if (!dragging) return;
  const d = dragging;
  dragging = null;
  if (d.mode === 'select') {
    if (!d.moved) {
      if (d.diffEl) {  // click on a diff region: select it and play
        setSel(+d.diffEl.dataset.t0, +d.diffEl.dataset.t1);
        playSel();
      } else {
        audio.currentTime = xToTime(ev.clientX);
      }
    }
  } else if (d.mode === 'create') {
    if (d.el) d.el.remove();
    if (d.moved && d.t1 - d.t0 >= 0.05) {
      pushUndo(d.file);
      const s = {id: nextId++, start: d.t0, end: d.t1, speaker: d.spk};
      meta.files[d.file].segments.push(s);
      afterEdit(d.file);
      selectSeg(d.file, s.id);
    }
  } else {  // move / resize finished (or plain click on a segment)
    if (d.moved) {
      afterEdit(d.file);
      selectSeg(d.file, d.id);
    } else {
      selectSeg(d.file, d.id);
    }
  }
});

tracksEl.addEventListener('dblclick', ev => {
  const segEl = ev.target.closest('.seg');
  if (!segEl) return;
  const s = findSeg(segEl.dataset.file, +segEl.dataset.segId);
  if (s) { setSel(s.start, s.end); playSel(); }
});

// lane-label "+seg" / panel "+speaker" buttons (delegated)
$('lanes').addEventListener('click', ev => {
  const t = ev.target;
  if (t.dataset && 'addseg' in t.dataset) {
    const lane = t.closest('.lane');
    addSegFromSel(lane.dataset.file, lane.dataset.speaker);
  } else if (t.dataset && t.dataset.addspk) {
    addSpeaker(t.dataset.addspk);
  }
});

/* ---------- save ---------- */

async function save(which) {
  const f = meta.files[which];
  $('savemsg').textContent = '保存中…';
  try {
    const r = await fetch('/api/save', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({which, segments: f.segments.map(
          ({start, end, speaker}) => ({start, end, speaker}))}),
    });
    if (!r.ok) throw new Error(await r.text());
    const res = await r.json();
    dirty[which] = false;
    updateSaveBtns();
    $('savemsg').textContent = `已保存 ${res.n} 段 → ${res.path}`;
  } catch (e) {
    $('savemsg').textContent = '';
    $('err').textContent = '保存失败: ' + e;
    $('err').style.display = 'block';
  }
}
$('savea').onclick = () => save('a');
$('saveb').onclick = () => save('b');
window.addEventListener('beforeunload', ev => {
  if (dirty.a || dirty.b) { ev.preventDefault(); ev.returnValue = ''; }
});

/* ---------- top-level controls & keys ---------- */

$('zoom').oninput = () => {
  zoomFactor = Math.pow(2, $('zoom').value / 12.5);  // 1x .. 256x
  $('zoomval').textContent = zoomFactor < 10 ?
      zoomFactor.toFixed(1)+'×' : Math.round(zoomFactor)+'×';
  render();
};
$('playsel').onclick = playSel;
$('clearsel').onclick = clearSel;
$('applysel').onclick = applyManualSel;
$('mindiff').oninput = () => render();
$('remap').onclick = () => { computeMapping(); computeDiff(); render(); };
$('ebapply').onclick = applyEditbar;
$('ebplay').onclick = () => {
  if (!selected) return;
  const s = findSeg(selected.file, selected.id);
  if (s) { setSel(s.start, s.end); playSel(); }
};
$('ebsplit').onclick = splitSelected;
$('ebdel').onclick = deleteSelected;
$('ebclose').onclick = deselectSeg;
['selstart', 'selend'].forEach(id => $(id).addEventListener('keydown',
  ev => { if (ev.key === 'Enter') applyManualSel(); }));
['ebspk', 'ebstart', 'ebend'].forEach(id => $(id).addEventListener('keydown',
  ev => { if (ev.key === 'Enter') applyEditbar(); }));

document.addEventListener('keydown', ev => {
  const typing = ev.target.tagName === 'INPUT' &&
                 ev.target.type !== 'checkbox' &&
                 ev.target.type !== 'range';
  if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 'z') {
    ev.preventDefault();
    const f = lastEditedFile() ||
        (undoStack.a.length ? 'a' : undoStack.b.length ? 'b' : null);
    if (f) ev.shiftKey ? redo(f) : undo(f);
    return;
  }
  if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 'y') {
    ev.preventDefault();
    const f = lastEditedFile() ||
        (redoStack.a.length ? 'a' : redoStack.b.length ? 'b' : null);
    if (f) redo(f);
    return;
  }
  if (typing) return;
  const jump = ev.shiftKey ? 0.5 : 5;
  if (ev.key === 'ArrowLeft')
    audio.currentTime = Math.max(0, audio.currentTime - jump);
  else if (ev.key === 'ArrowRight')
    audio.currentTime = Math.min(dur, audio.currentTime + jump);
  else if (ev.key === 'Escape') selected ? deselectSeg() : clearSel();
  else if (ev.key === 'Delete' || ev.key === 'Backspace') deleteSelected();
  else if (ev.key.toLowerCase() === 's') splitSelected();
  else if (ev.key === ' ') { ev.preventDefault();
    audio.paused ? audio.play() : audio.pause(); }
});
window.addEventListener('resize', render);

// non-WAV audio: the server may only estimate the duration from the last
// segment end, so refine it once the browser has decoded the metadata
audio.addEventListener('loadedmetadata', () => {
  if (isFinite(audio.duration) && Math.abs(audio.duration - dur) > 0.05) {
    dur = audio.duration;
    render();
  }
});

async function load() {
  $('err').style.display = 'none';
  let m;
  try {
    const r = await fetch('/api/meta');
    if (!r.ok) throw new Error(await r.text());
    m = await r.json();
  } catch (e) {
    $('err').textContent = '加载失败: ' + e;
    $('err').style.display = 'block';
    return;
  }
  meta = {audio_file: m.audio_file, duration: m.duration,
          files: {a: m.a, b: m.b}};
  for (const file of ['a', 'b']) {
    const f = meta.files[file];
    f.extraSpeakers = new Set();
    f.segments.forEach(s => { s.id = nextId++; });
  }
  dur = meta.duration;
  clearSel();
  audio.src = '/api/audio';
  $('fname').textContent =
      `${m.audio_file} · A=${m.a.rttm_file} · B=${m.b.rttm_file}`;
  document.title = '双 RTTM 对比编辑器 – ' + m.audio_file;
  computeMapping();
  computeDiff();
  render();
}

load();
</script>
</body>
</html>
"""


class Handler(BaseHTTPRequestHandler):
    audio_bytes = b""
    ctype = "audio/x-wav"
    meta = {}
    files = {}  # {"a"/"b": {"fid", "chan", "out_path"}}

    def log_message(self, *args):
        pass

    def _send(self, code, body, ctype="application/json", extra=None):
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        for k, v in (extra or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        try:
            self._route()
        except BrokenPipeError:
            pass
        except Exception as e:  # surface errors to the page
            self._send(500, str(e).encode(), "text/plain; charset=utf-8")

    def do_POST(self):
        try:
            if self.path == "/api/save":
                length = int(self.headers.get("Content-Length", 0))
                payload = json.loads(self.rfile.read(length))
                self._save(payload)
            else:
                self._send(404, b"not found", "text/plain")
        except BrokenPipeError:
            pass
        except Exception as e:
            self._send(500, str(e).encode(), "text/plain; charset=utf-8")

    def _save(self, payload):
        which = payload.get("which")
        if which not in self.files:
            raise ValueError(f"unknown rttm key: {which!r}")
        info = self.files[which]
        segs = sorted(payload["segments"], key=lambda s: float(s["start"]))
        lines = []
        for s in segs:
            start, end = float(s["start"]), float(s["end"])
            spk = re.sub(r"\s+", "_", str(s["speaker"]).strip())
            if not spk:
                raise ValueError("empty speaker label")
            if end <= start or start < 0:
                raise ValueError(f"invalid segment [{start}, {end}]")
            lines.append(f"SPEAKER {info['fid']} {info['chan']} "
                         f"{start:.3f} {end - start:.3f} "
                         f"<NA> <NA> {spk} <NA> <NA>\n")
        with open(info["out_path"], "w", encoding="utf-8") as f:
            f.writelines(lines)
        self._send(200, json.dumps(
            {"path": info["out_path"], "n": len(lines)}).encode())

    def _route(self):
        if self.path in ("/", "/index.html"):
            self._send(200, PAGE.encode(), "text/html; charset=utf-8")
        elif self.path == "/api/meta":
            self._send(200, json.dumps(self.meta).encode())
        elif self.path == "/api/audio":
            self._serve_audio(self.audio_bytes, self.ctype)
        else:
            self._send(404, b"not found", "text/plain")

    def _serve_audio(self, data, ctype):
        """Serve audio bytes with Range support so the player can seek."""
        rng = self.headers.get("Range")
        total = len(data)
        if rng and (m := re.fullmatch(r"bytes=(\d*)-(\d*)", rng.strip())):
            start = int(m.group(1)) if m.group(1) else 0
            end = int(m.group(2)) if m.group(2) else total - 1
            end = min(end, total - 1)
            if start > end:
                self._send(416, b"", ctype,
                           {"Content-Range": f"bytes */{total}"})
                return
            chunk = data[start:end + 1]
            self._send(206, chunk, ctype, {
                "Content-Range": f"bytes {start}-{end}/{total}",
                "Accept-Ranges": "bytes"})
        else:
            self._send(200, data, ctype, {"Accept-Ranges": "bytes"})


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("audio", help="path to the audio file (wav/mp3/...)")
    ap.add_argument("rttm_a", help="path to the first RTTM file (panel A)")
    ap.add_argument("rttm_b", help="path to the second RTTM file (panel B)")
    ap.add_argument("--port", type=int, default=8766)
    ap.add_argument("--host", default="127.0.0.1")
    args = ap.parse_args()

    data, ctype, duration = load_audio(args.audio)
    file_meta, files = {}, {}
    for key, path in (("a", args.rttm_a), ("b", args.rttm_b)):
        segments, fid, chan = parse_rttm(path)
        out_path = os.path.splitext(path)[0] + "_new.rttm"
        files[key] = {"fid": fid or os.path.splitext(
                          os.path.basename(args.audio))[0],
                      "chan": chan or "1", "out_path": out_path}
        file_meta[key] = {"rttm_file": os.path.basename(path),
                          "out_file": os.path.basename(out_path),
                          "segments": segments}
    if duration is None:  # refined client-side once the browser decodes it
        duration = max(s["end"] for k in file_meta
                       for s in file_meta[k]["segments"])

    Handler.audio_bytes = data
    Handler.ctype = ctype
    Handler.files = files
    Handler.meta = {
        "audio_file": os.path.basename(args.audio),
        "duration": duration,
        "a": file_meta["a"],
        "b": file_meta["b"],
    }
    srv = ThreadingHTTPServer((args.host, args.port), Handler)
    print(f"Serving {args.audio}\n  A: {args.rttm_a} "
          f"({len(file_meta['a']['segments'])} segments)\n  B: {args.rttm_b} "
          f"({len(file_meta['b']['segments'])} segments)\n"
          f"at http://{args.host}:{args.port}\n"
          f"Edits save to {files['a']['out_path']} / {files['b']['out_path']}")
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()