-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
2802 lines (2500 loc) · 95.7 KB
/
App.tsx
File metadata and controls
2802 lines (2500 loc) · 95.7 KB
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
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { Pause, Play } from 'lucide-react';
import { blobToAudioBuffer } from './services/audioProcessor';
import {
clearAudioRangesWithSilence,
deleteAudioRangeRipple,
extractAudioRangesPadded,
insertAudioAtFrame,
insertSilenceFramesAtFrame,
overwriteAudioAtFrame,
} from './services/audioEdit';
import {
clearFrameRanges,
createSilentFrames,
deleteFrameRangeRipple,
extractFrameRangesPadded,
insertFramesAtFrame,
overwriteFramesAtFrame,
} from './services/frameEdit';
import { exportTracksToZip } from './services/audioExporter';
import { getVadTuning, VadPreset, VadTuning } from './services/vad';
import {
analyzeAudioBufferWithSileroVadEngine,
getSileroVadError,
getSileroVadStatus,
subscribeSileroVadError,
subscribeSileroVadStatus,
} from './services/sileroVadEngine';
import type { SileroVadError, SileroVadStatus } from './services/sileroVadEngine';
import { exportSheetImagesToZip } from './services/sheetImageExporter';
import { computeVadAutoTuning } from './services/vadAutoTuner';
import {
applyOverrideRange,
applyOverrideRanges,
clearOverrideRanges,
createSpeechOverrides,
deleteOverrideRange,
extractOverrideRanges,
insertOverrideRange,
overwriteOverrideRange,
resizeSpeechOverrides,
} from './services/speechLabels';
import { TimesheetViewport } from './components/TimesheetViewport';
import { HelpSheet } from './components/HelpSheet';
import { TrackMuteMenu } from './components/TrackMuteMenu';
import { AppShell } from './components/AppShell';
import { EditPalette } from './components/EditPalette';
import { MoreSheet } from './components/MoreSheet';
import { TopBar } from './components/TopBar';
import { TransportDock } from './components/TransportDock';
import { useViewportHeight } from './hooks/useViewportHeight';
import { FrameData, InputTestState, RecordingState, Track } from './types';
import { ClipboardClip, EditTarget, SelectionRange, SelectionRanges } from './domain/editTypes';
import { DEFAULT_FPS, getFramesPerColumn, getFramesPerSheet } from './domain/timesheet';
import { formatTimecode, formatTimecodeOneBased } from './domain/timecode';
import { createI18n, getInitialLanguage, type Language } from './domain/i18n';
const FPS = DEFAULT_FPS;
const FRAMES_PER_COLUMN = getFramesPerColumn(FPS);
const SCRUB_PREVIEW_SEC = 0.08;
const SCRUB_FADE_SEC = 0.01;
const SCRUB_THROTTLE_MS = 50;
const SCRUB_STATE_RESET_MS = 200;
const MIC_SLEEP_MS = 5 * 60 * 1000;
const MIC_SLEEP_CHECK_MS = 15 * 1000;
const MIN_SHEET_ZOOM = 1;
const MAX_SHEET_ZOOM = 3;
const SHEET_ZOOM_STEP = 0.1;
const AUTO_VAD_BASE_THRESHOLD_SCALE = 1;
const AUTO_VAD_BASE_STABILITY = 0.4;
const MIN_AUTO_TUNE_FRAMES = 6;
// 末尾側に余白列を確保して、終了後の選択/貼り付けを行えるようにする
const VIRTUAL_TAIL_COLUMNS = 1;
const MIN_INPUT_GAIN_DB = -18;
const MAX_INPUT_GAIN_DB = 18;
const INPUT_TEST_DURATION_MS = 5200;
const INPUT_TEST_IGNORE_MS = 700;
const INPUT_TEST_MIN_SPEECH_RATIO = 0.12;
const INPUT_TEST_TARGET_PEAK_DB = -6;
const INPUT_TEST_MIN_RMS = 0.008;
const INPUT_TEST_UI_UPDATE_MS = 120;
const MOBILE_UI_MAX_WIDTH = 900;
const MOBILE_COMPACT_MAX_WIDTH = 760;
const MOBILE_TIGHT_MAX_WIDTH = 430;
const getViewportWidth = (): number => {
if (typeof window === 'undefined') return 0;
const visualWidth = window.visualViewport?.width;
if (typeof visualWidth === 'number' && visualWidth > 0) {
return visualWidth;
}
return window.innerWidth;
};
/** screen.width が viewport より大幅に小さい場合は物理画面幅を返す(Android 表示スケーリング対策) */
const getBreakpointWidth = (): number => {
const vpWidth = getViewportWidth();
if (typeof window === 'undefined') return vpWidth;
const screenWidth = window.screen?.width;
if (typeof screenWidth === 'number' && screenWidth > 0 && screenWidth < vpWidth * 0.8) {
return screenWidth;
}
return vpWidth;
};
const UI_SCALE_KEY = 'komasync-ui-scale';
const getAutoUiScale = (): number => {
if (typeof window === 'undefined') return 1;
const vp = getViewportWidth();
const sw = window.screen?.width;
if (typeof sw === 'number' && sw > 0 && vp > sw * 1.3) {
// Android 表示スケーリング: viewport が screen より大幅に広い
return Math.min(Math.round((vp / sw) * 0.85 * 20) / 20, 1.5);
}
// 通常のモバイル端末(iPhone 等): コントロールを小さめにしてタイムシート領域を広く取る
return 0.75;
};
const loadUiScale = (): number => {
try {
const stored = localStorage.getItem(UI_SCALE_KEY);
if (stored !== null) {
const v = parseFloat(stored);
if (Number.isFinite(v) && v >= 0.75 && v <= 1.5) return Math.round(v * 20) / 20;
}
} catch { /* ignore */ }
return getAutoUiScale();
};
const dbToGain = (db: number): number => Math.pow(10, db / 20);
const gainToDb = (gain: number): number => 20 * Math.log10(Math.max(gain, 1e-8));
// ブラウザ側の音声処理が原因で音切れするケースがあるため、可能なら無効化を要求する
const MIC_CONSTRAINTS: MediaStreamConstraints = {
audio: {
echoCancellation: { ideal: false },
noiseSuppression: { ideal: false },
autoGainControl: { ideal: false },
channelCount: { ideal: 1 },
},
};
const clampSheetZoom = (value: number): number => Math.min(MAX_SHEET_ZOOM, Math.max(MIN_SHEET_ZOOM, value));
const normalizeSheetZoom = (value: number): number => Math.round(clampSheetZoom(value) * 100) / 100;
const clampInputGainDb = (value: number): number => Math.min(MAX_INPUT_GAIN_DB, Math.max(MIN_INPUT_GAIN_DB, value));
const WAVEFORM_REFERENCE_QUANTILE = 0.98;
// Use a factory function to ensure fresh references on reset
const createInitialTracks = (): Track[] => [
{
id: '1',
name: 'Track 1',
color: 'blue',
audioBuffer: null,
frames: [],
waveformReferenceMax: 0,
speechOverrides: [],
isVisible: true,
isMuted: false,
},
{
id: '2',
name: 'Track 2',
color: 'red',
audioBuffer: null,
frames: [],
waveformReferenceMax: 0,
speechOverrides: [],
isVisible: true,
isMuted: false,
},
{
id: '3',
name: 'Track 3',
color: 'green',
audioBuffer: null,
frames: [],
waveformReferenceMax: 0,
speechOverrides: [],
isVisible: true,
isMuted: false,
},
];
type HistoryEntry =
| { kind: 'tracks'; tracks: Track[] }
| { kind: 'vadThreshold'; value: number };
const getSupportedMimeType = (): string | undefined => {
const types = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/mp4',
'audio/ogg;codecs=opus',
'audio/aac'
];
for (const type of types) {
if (typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(type)) {
return type;
}
}
return undefined;
};
type WindowWithWebkitAudioContext = Window & {
webkitAudioContext?: typeof AudioContext;
};
const getAudioContextClass = (): typeof AudioContext => {
const audioContextClass = window.AudioContext || (window as WindowWithWebkitAudioContext).webkitAudioContext;
if (!audioContextClass) {
throw new Error('AudioContext is not supported');
}
return audioContextClass;
};
const getErrorMessage = (error: unknown): string => {
if (error instanceof Error && error.message) return error.message;
if (typeof error === 'string') return error;
if (error && typeof error === 'object' && 'message' in error) {
const message = (error as { message?: unknown }).message;
if (typeof message === 'string') return message;
}
return '';
};
const getErrorName = (error: unknown): string => {
if (error instanceof Error && error.name) return error.name;
if (error && typeof error === 'object' && 'name' in error) {
const name = (error as { name?: unknown }).name;
if (typeof name === 'string') return name;
}
return '';
};
const normalizeSelectionRange = (range: SelectionRange): SelectionRange => {
const startFrame = Math.max(0, Math.floor(Math.min(range.startFrame, range.endFrame)));
const endFrame = Math.max(startFrame, Math.floor(Math.max(range.startFrame, range.endFrame)));
return { startFrame, endFrame };
};
const mergeSelectionRanges = (ranges: SelectionRanges): SelectionRanges => {
if (ranges.length === 0) return [];
const normalized = ranges
.map(normalizeSelectionRange)
.sort((a, b) => a.startFrame - b.startFrame || a.endFrame - b.endFrame);
const merged: SelectionRanges = [normalized[0]];
for (let i = 1; i < normalized.length; i += 1) {
const current = normalized[i];
const last = merged[merged.length - 1];
if (current.startFrame <= last.endFrame + 1) {
last.endFrame = Math.max(last.endFrame, current.endFrame);
continue;
}
merged.push({ ...current });
}
return merged;
};
const areSelectionRangesEqual = (a: SelectionRanges, b: SelectionRanges): boolean => {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i]?.startFrame !== b[i]?.startFrame) return false;
if (a[i]?.endFrame !== b[i]?.endFrame) return false;
}
return true;
};
export default function App() {
const [mobileInteractionMode, setMobileInteractionMode] = useState<'navigate' | 'select'>('navigate');
const [recordingState, setRecordingState] = useState<RecordingState>(RecordingState.IDLE);
const [language, setLanguage] = useState<Language>(() => getInitialLanguage());
const { t, list: tList } = useMemo(() => createI18n(language), [language]);
// Multi-track State
const [tracks, setTracks] = useState<Track[]>(createInitialTracks());
const [recordTrackId, setRecordTrackId] = useState<string>('1');
const [editTarget, setEditTarget] = useState<EditTarget>('1');
// History State for Undo/Redo
const [historyPast, setHistoryPast] = useState<HistoryEntry[]>([]);
const [historyFuture, setHistoryFuture] = useState<HistoryEntry[]>([]);
// Clipboard State
const [clipboardClip, setClipboardClip] = useState<ClipboardClip | null>(null);
const [muteMenu, setMuteMenu] = useState<{ x: number; y: number } | null>(null);
const [currentFrame, setCurrentFrame] = useState(0);
const [isScrubbing, setIsScrubbing] = useState(false);
const [vadPreset, setVadPreset] = useState<VadPreset>('quiet');
const [vadStability, setVadStability] = useState(AUTO_VAD_BASE_STABILITY);
const [vadThresholdScale, setVadThresholdScale] = useState(AUTO_VAD_BASE_THRESHOLD_SCALE);
const [isVadAuto, setIsVadAuto] = useState(true);
const [playWhileRecording, setPlayWhileRecording] = useState(true);
const [inputGainDb, setInputGainDb] = useState(0);
const [isLimiterEnabled, setIsLimiterEnabled] = useState(true);
const [inputTestState, setInputTestState] = useState<InputTestState>({
status: 'idle',
progress: 0,
message: '',
});
const [isMoreOpen, setIsMoreOpen] = useState(false);
const [isHelpOpen, setIsHelpOpen] = useState(false);
const [isMicReady, setIsMicReady] = useState(false);
const [isMicPreparing, setIsMicPreparing] = useState(false);
const [viewportFirstColumn, setViewportFirstColumn] = useState(0);
const [sheetZoom, setSheetZoom] = useState(1);
const [vadEngineStatus, setVadEngineStatus] = useState<SileroVadStatus>(() => getSileroVadStatus());
const [vadEngineError, setVadEngineError] = useState<SileroVadError>(() => getSileroVadError());
const [mobileViewportWidth, setMobileViewportWidth] = useState(() =>
getViewportWidth()
);
const [isCoarsePointer, setIsCoarsePointer] = useState(() =>
typeof window !== 'undefined' && typeof window.matchMedia === 'function'
? window.matchMedia('(pointer: coarse)').matches
: false
);
const [topBarWidth, setTopBarWidth] = useState(0);
const [uiScale, setUiScaleRaw] = useState(loadUiScale);
const showDebug = typeof window !== 'undefined' && new URLSearchParams(window.location.search).has('debug');
// Selection State
const [selection, setSelection] = useState<SelectionRanges>([]);
const [selectionMenu, setSelectionMenu] = useState<{ x: number; y: number } | null>(null);
const selectionRef = useRef<SelectionRanges>([]);
const selectionStateRef = useRef<SelectionRanges>([]);
const selectionPendingRef = useRef<SelectionRanges | undefined>(undefined);
const selectionScrubPendingRef = useRef<{ frame: number; trackId: string } | null>(null);
const selectionScrubLastRef = useRef<{ frame: number; trackId: string } | null>(null);
const selectionRafRef = useRef<number | null>(null);
const maxFramesRef = useRef(0);
const virtualMaxFramesRef = useRef(0);
const [virtualMaxFrames, setVirtualMaxFrames] = useState(0);
const audioContextRef = useRef<AudioContext | null>(null);
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const gainNodeRef = useRef<GainNode | null>(null);
const limiterNodeRef = useRef<DynamicsCompressorNode | null>(null);
const recordingGraphCleanupRef = useRef<(() => void) | null>(null);
const audioChunksRef = useRef<Blob[]>([]);
const recordingStartFrameRef = useRef<number>(0);
const recordingStartTimeRef = useRef<number>(0);
const micStreamRef = useRef<MediaStream | null>(null);
const micPreparePromiseRef = useRef<Promise<MediaStream> | null>(null);
const pendingRecordStartRef = useRef(false);
const lastSingleTrackIdRef = useRef<string>('1');
const currentFrameRef = useRef(0);
const lastFrameRef = useRef(0);
const inputRmsRef = useRef(0);
const autoMicWarmupRef = useRef(false);
const lastActivityRef = useRef(Date.now());
const recordingStateRef = useRef(recordingState);
const isMicReadyRef = useRef(isMicReady);
const isMicPreparingRef = useRef(isMicPreparing);
const vadThresholdHistoryRef = useRef<{ startValue: number } | null>(null);
const vadThresholdCommitTimerRef = useRef<number | null>(null);
const inputTestAbortRef = useRef<AbortController | null>(null);
const vuAnalyserRef = useRef<AnalyserNode | null>(null);
const vuSourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
const vuAnimationFrameRef = useRef<number>(0);
// Store source nodes for each track for mixed playback
const sourceNodesRef = useRef<Map<string, { source: AudioBufferSourceNode; gain: GainNode }>>(new Map());
const scrubNodesRef = useRef<{ source: AudioBufferSourceNode; gain: GainNode }[]>([]);
const scrubLastTimeRef = useRef(0);
const scrubFramePendingRef = useRef<number | null>(null);
const scrubFrameLastRef = useRef<number | null>(null);
const scrubRafRef = useRef<number | null>(null);
const isScrubbingRef = useRef(false);
const scrubStateResetRef = useRef<number | null>(null);
const startTimeRef = useRef<number>(0);
const animationFrameRef = useRef<number>(0);
useViewportHeight();
useEffect(() => {
if (typeof window === 'undefined') return;
const updateViewportWidth = () => {
setMobileViewportWidth(getViewportWidth());
};
updateViewportWidth();
window.addEventListener('resize', updateViewportWidth);
window.visualViewport?.addEventListener('resize', updateViewportWidth);
if (typeof window.matchMedia !== 'function') {
return () => {
window.removeEventListener('resize', updateViewportWidth);
window.visualViewport?.removeEventListener('resize', updateViewportWidth);
};
}
const mediaQuery = window.matchMedia('(pointer: coarse)');
const updatePointer = () => setIsCoarsePointer(mediaQuery.matches);
updatePointer();
if (typeof mediaQuery.addEventListener === 'function') {
mediaQuery.addEventListener('change', updatePointer);
return () => {
window.removeEventListener('resize', updateViewportWidth);
window.visualViewport?.removeEventListener('resize', updateViewportWidth);
mediaQuery.removeEventListener('change', updatePointer);
};
}
mediaQuery.addListener(updatePointer);
return () => {
window.removeEventListener('resize', updateViewportWidth);
window.visualViewport?.removeEventListener('resize', updateViewportWidth);
mediaQuery.removeListener(updatePointer);
};
}, []);
const startScrubState = useCallback((autoResetMs?: number) => {
if (scrubStateResetRef.current !== null) {
window.clearTimeout(scrubStateResetRef.current);
scrubStateResetRef.current = null;
}
setIsScrubbing(true);
if (autoResetMs && autoResetMs > 0) {
scrubStateResetRef.current = window.setTimeout(() => {
scrubStateResetRef.current = null;
setIsScrubbing(false);
}, autoResetMs);
}
}, []);
const stopScrubState = useCallback(() => {
if (scrubStateResetRef.current !== null) {
window.clearTimeout(scrubStateResetRef.current);
scrubStateResetRef.current = null;
}
setIsScrubbing(false);
}, []);
useEffect(() => {
return () => {
if (scrubStateResetRef.current !== null) {
window.clearTimeout(scrubStateResetRef.current);
}
};
}, []);
useEffect(() => {
return () => {
if (scrubRafRef.current !== null) {
cancelAnimationFrame(scrubRafRef.current);
scrubRafRef.current = null;
}
};
}, []);
useEffect(() => {
if (selection.length === 0) {
setSelectionMenu(null);
}
}, [selection]);
useEffect(() => {
selectionRef.current = selection;
selectionStateRef.current = selection;
}, [selection]);
useEffect(() => {
return () => {
if (selectionRafRef.current !== null) {
cancelAnimationFrame(selectionRafRef.current);
selectionRafRef.current = null;
}
};
}, []);
useEffect(() => {
return () => {
inputTestAbortRef.current?.abort();
};
}, []);
// Stats (Calculate total max duration across all tracks)
const maxFrames = Math.max(0, ...tracks.map(t => t.frames.length));
useEffect(() => {
maxFramesRef.current = maxFrames;
const baseFrame = Math.max(0, Math.floor(currentFrameRef.current));
const columnIndex = Math.floor(baseFrame / FRAMES_PER_COLUMN);
const required = Math.max(
maxFrames,
(columnIndex + 1 + VIRTUAL_TAIL_COLUMNS) * FRAMES_PER_COLUMN
);
if (required !== virtualMaxFramesRef.current) {
virtualMaxFramesRef.current = required;
setVirtualMaxFrames(required);
}
}, [maxFrames]);
useEffect(() => {
currentFrameRef.current = currentFrame;
}, [currentFrame]);
const commitCurrentFrame = useCallback(
(nextFrame: number) => {
const clampedFrame = Math.max(0, Math.floor(nextFrame));
currentFrameRef.current = clampedFrame;
setCurrentFrame(clampedFrame);
},
[]
);
const commitSelectionState = useCallback((ranges: SelectionRanges) => {
const normalized = mergeSelectionRanges(ranges);
const prev = selectionStateRef.current;
selectionStateRef.current = normalized;
selectionRef.current = normalized;
if (areSelectionRangesEqual(prev, normalized)) return;
setSelection(normalized);
}, []);
const clearSelectionImmediate = useCallback(() => {
if (selectionRafRef.current !== null) {
cancelAnimationFrame(selectionRafRef.current);
selectionRafRef.current = null;
}
selectionPendingRef.current = undefined;
selectionScrubPendingRef.current = null;
selectionScrubLastRef.current = null;
commitSelectionState([]);
setSelectionMenu(null);
}, [commitSelectionState]);
useEffect(() => {
recordingStateRef.current = recordingState;
}, [recordingState]);
useEffect(() => {
if (typeof window === 'undefined') return;
const handleLanguageChange = () => {
setLanguage(getInitialLanguage());
};
window.addEventListener('languagechange', handleLanguageChange);
return () => window.removeEventListener('languagechange', handleLanguageChange);
}, []);
useEffect(() => {
const node = gainNodeRef.current;
const ctx = audioContextRef.current;
if (!node || !ctx) return;
const nextGain = dbToGain(clampInputGainDb(inputGainDb));
node.gain.setTargetAtTime(nextGain, ctx.currentTime, 0.01);
}, [inputGainDb]);
useEffect(() => {
isMicReadyRef.current = isMicReady;
}, [isMicReady]);
useEffect(() => {
isMicPreparingRef.current = isMicPreparing;
}, [isMicPreparing]);
useEffect(() => {
return subscribeSileroVadStatus((status) => {
setVadEngineStatus(status);
});
}, []);
useEffect(() => {
return subscribeSileroVadError((error) => {
setVadEngineError(error);
});
}, []);
const applyVadAutoTuningFromFrames = useCallback((_framesList: FrameData[][]) => {
// Auto-tuning は無効化: Silero v6 公式推奨パラメータをそのまま使う。
// thresholdScale / stability を録音ごとに書き換えると判定がブレるため、
// 固定値(thresholdScale=1, stability=0.4)で運用する。
}, []);
const getFrameCountFromBuffer = useCallback((audioBuffer: AudioBuffer | null): number => {
if (!audioBuffer) return 0;
return Math.round((audioBuffer.length * FPS) / audioBuffer.sampleRate);
}, []);
const createSpeechOverridesForBuffer = useCallback(
(audioBuffer: AudioBuffer | null): number[] => createSpeechOverrides(getFrameCountFromBuffer(audioBuffer)),
[getFrameCountFromBuffer]
);
const getWaveformReferenceMax = useCallback((frames: FrameData[]): number => {
// 編集後に残った区間だけで波形が急に肥大化しないよう、録音全体の代表値を保持する。
const volumes = frames
.map((frame) => frame.volume ?? 0)
.filter((volume) => volume > 0)
.sort((a, b) => a - b);
if (volumes.length === 0) return 0;
const index = Math.min(volumes.length - 1, Math.floor((volumes.length - 1) * WAVEFORM_REFERENCE_QUANTILE));
return volumes[index] ?? volumes[volumes.length - 1] ?? 0;
}, []);
const analyzeVadFrames = useCallback(
async (trackId: string, audioBuffer: AudioBuffer, tuning: VadTuning): Promise<FrameData[]> => {
const { frames, debug } = await analyzeAudioBufferWithSileroVadEngine(audioBuffer, FPS, tuning);
if (import.meta.env.DEV) {
const total = frames.length;
let speechCount = 0;
let maxVolume = 0;
let maxSpeechRun = 0;
let currentRun = 0;
frames.forEach((frame) => {
if (frame.volume > maxVolume) maxVolume = frame.volume;
if (frame.isSpeech) {
speechCount += 1;
currentRun += 1;
if (currentRun > maxSpeechRun) maxSpeechRun = currentRun;
} else {
currentRun = 0;
}
});
const ratio = total > 0 ? speechCount / total : 0;
const status = getSileroVadStatus();
console.info(
`[VAD] track=${trackId} total=${total} speech=${speechCount} ratio=${ratio.toFixed(3)} maxVol=${maxVolume.toFixed(5)} maxRun=${maxSpeechRun} status=${status}`
);
if (typeof window !== 'undefined') {
const debugTarget = window as Window & {
__vadDebug?: Record<
string,
{
frames: FrameData[];
summary: {
total: number;
speechCount: number;
ratio: number;
maxVolume: number;
maxSpeechRun: number;
status: string;
};
workerDebug?: unknown;
}
>;
};
if (!debugTarget.__vadDebug) debugTarget.__vadDebug = {};
debugTarget.__vadDebug[trackId] = {
frames,
summary: {
total,
speechCount,
ratio,
maxVolume,
maxSpeechRun,
status,
},
workerDebug: debug,
};
}
}
return frames;
},
[]
);
// --- History Management ---
const HISTORY_LIMIT = 30;
const pushHistoryEntry = useCallback((entry: HistoryEntry) => {
setHistoryPast(prev => [...prev.slice(-(HISTORY_LIMIT - 1)), entry]);
setHistoryFuture([]); // Clear future on new action
}, []);
const clearVadThresholdCommitTimer = () => {
if (vadThresholdCommitTimerRef.current !== null) {
window.clearTimeout(vadThresholdCommitTimerRef.current);
vadThresholdCommitTimerRef.current = null;
}
};
const commitVadThresholdHistory = useCallback(() => {
clearVadThresholdCommitTimer();
const snapshot = vadThresholdHistoryRef.current;
if (!snapshot) return;
vadThresholdHistoryRef.current = null;
if (snapshot.startValue !== vadThresholdScale) {
pushHistoryEntry({ kind: 'vadThreshold', value: snapshot.startValue });
}
}, [pushHistoryEntry, vadThresholdScale]);
const scheduleVadThresholdCommit = useCallback(() => {
clearVadThresholdCommitTimer();
vadThresholdCommitTimerRef.current = window.setTimeout(() => {
commitVadThresholdHistory();
}, 300);
}, [commitVadThresholdHistory]);
useEffect(() => {
return () => {
clearVadThresholdCommitTimer();
};
}, []);
const handleVadThresholdScaleChange = useCallback((nextScale: number) => {
if (isVadAuto) return;
if (!vadThresholdHistoryRef.current) {
vadThresholdHistoryRef.current = { startValue: vadThresholdScale };
}
setVadThresholdScale(nextScale);
scheduleVadThresholdCommit();
}, [isVadAuto, scheduleVadThresholdCommit, vadThresholdScale]);
const handleVadStabilityChange = useCallback((nextValue: number) => {
if (isVadAuto) return;
setVadStability(nextValue);
}, [isVadAuto]);
const handleToggleVadAuto = useCallback((nextValue: boolean) => {
setIsVadAuto(nextValue);
if (nextValue) {
clearVadThresholdCommitTimer();
vadThresholdHistoryRef.current = null;
setVadThresholdScale(AUTO_VAD_BASE_THRESHOLD_SCALE);
setVadStability(AUTO_VAD_BASE_STABILITY);
}
}, []);
const saveToHistory = useCallback(() => {
commitVadThresholdHistory();
pushHistoryEntry({ kind: 'tracks', tracks });
}, [commitVadThresholdHistory, pushHistoryEntry, tracks]);
const handleUndo = useCallback(() => {
if (historyPast.length === 0) return;
const previous = historyPast[historyPast.length - 1];
const newPast = historyPast.slice(0, -1);
const futureEntry: HistoryEntry =
previous.kind === 'tracks'
? { kind: 'tracks', tracks }
: { kind: 'vadThreshold', value: vadThresholdScale };
setHistoryFuture(prev => [futureEntry, ...prev]);
if (previous.kind === 'tracks') {
setTracks(previous.tracks);
// Reset selection to avoid ghost selections
clearSelectionImmediate();
} else {
setVadThresholdScale(previous.value);
}
setHistoryPast(newPast);
}, [
clearSelectionImmediate,
historyPast,
tracks,
vadThresholdScale,
]);
const handleRedo = useCallback(() => {
if (historyFuture.length === 0) return;
const next = historyFuture[0];
const newFuture = historyFuture.slice(1);
const pastEntry: HistoryEntry =
next.kind === 'tracks'
? { kind: 'tracks', tracks }
: { kind: 'vadThreshold', value: vadThresholdScale };
setHistoryPast(prev => [...prev, pastEntry]);
if (next.kind === 'tracks') {
setTracks(next.tracks);
clearSelectionImmediate();
} else {
setVadThresholdScale(next.value);
}
setHistoryFuture(newFuture);
}, [
clearSelectionImmediate,
historyFuture,
tracks,
vadThresholdScale,
]);
const handleResetProject = () => {
if (window.confirm(t('app.confirmReset'))) {
// Stop playback/recording first
stopAllSources();
stopScrubSources();
stopVuMeter();
stopMicStream();
cancelAnimationFrame(animationFrameRef.current);
// Reset all states
setTracks(createInitialTracks());
setHistoryPast([]);
setHistoryFuture([]);
setRecordTrackId('1');
setEditTarget('1');
lastSingleTrackIdRef.current = '1';
commitCurrentFrame(0);
clearSelectionImmediate();
setClipboardClip(null);
setRecordingState(RecordingState.IDLE);
recordingStartFrameRef.current = 0;
recordingStartTimeRef.current = 0;
isScrubbingRef.current = false;
stopScrubState();
}
};
const handleExportAudio = async () => {
try {
await exportTracksToZip(tracks);
} catch (error: unknown) {
const message = getErrorMessage(error) || t('app.exportAudioFailed');
alert(message);
console.error(error);
}
};
const handleExportSheetImagesCurrent = async () => {
try {
const sheetIndex = Math.max(0, Math.floor(viewportFirstColumn / 2));
await exportSheetImagesToZip(tracks, FPS, { type: 'sheet', sheetIndex });
} catch (error: unknown) {
const message = getErrorMessage(error) || t('app.exportSheetFailed');
alert(message);
console.error(error);
}
};
const handleExportSheetImagesAll = async () => {
try {
await exportSheetImagesToZip(tracks, FPS, { type: 'all' });
} catch (error: unknown) {
const message = getErrorMessage(error) || t('app.exportSheetFailed');
alert(message);
console.error(error);
}
};
const handleBackgroundClick = () => {
clearSelectionImmediate();
};
const handleOpenMuteMenu = useCallback((point: { x: number; y: number }) => {
setMuteMenu(point);
}, []);
const handleCloseMuteMenu = useCallback(() => {
setMuteMenu(null);
}, []);
const updateTrack = (trackId: string, updates: Partial<Track>) => {
setTracks(prev => prev.map(t => t.id === trackId ? { ...t, ...updates } : t));
};
const toggleTrackMute = (trackId: string) => {
const currentMuted = tracks.find((track) => track.id === trackId)?.isMuted ?? false;
const nextMuted = !currentMuted;
if (recordingState === RecordingState.PLAYING || recordingState === RecordingState.RECORDING) {
const node = sourceNodesRef.current.get(trackId);
if (node) {
const ctxTime = audioContextRef.current?.currentTime ?? 0;
node.gain.gain.setValueAtTime(nextMuted ? 0 : 1, ctxTime);
}
}
setTracks((prev) =>
prev.map((track) => (track.id === trackId ? { ...track, isMuted: !track.isMuted } : track))
);
};
const stopAllSources = useCallback(() => {
sourceNodesRef.current.forEach(({ source, gain }) => {
try { source.stop(); } catch {}
try { source.disconnect(); } catch {}
try { gain.disconnect(); } catch {}
});
sourceNodesRef.current.clear();
}, []);
const stopPlaybackLoop = useCallback(() => {
stopAllSources();
cancelAnimationFrame(animationFrameRef.current);
}, [stopAllSources]);
const handlePause = useCallback(() => {
stopPlaybackLoop();
setRecordingState(RecordingState.PAUSED);
}, [stopPlaybackLoop]);
const stopScrubSources = useCallback(() => {
scrubNodesRef.current.forEach(({ source, gain }) => {
try {
source.stop();
} catch {
// no-op
}
try {
source.disconnect();
} catch {
// no-op
}
try {
gain.disconnect();
} catch {
// no-op
}
});
scrubNodesRef.current = [];
}, []);
const playScrubPreview = useCallback((frame: number, trackId?: string) => {
const now = performance.now();
if (now - scrubLastTimeRef.current < SCRUB_THROTTLE_MS) return;
scrubLastTimeRef.current = now;
const audibleTracks = trackId
? tracks.filter((track) => track.id === trackId && track.audioBuffer && !track.isMuted)
: tracks.filter((track) => track.audioBuffer && !track.isMuted);
if (audibleTracks.length === 0) {
stopScrubSources();
return;
}
if (!audioContextRef.current || audioContextRef.current.state === 'closed') {
const AudioContextClass = getAudioContextClass();
audioContextRef.current = new AudioContextClass();
}
const ctx = audioContextRef.current;
if (ctx.state === 'suspended') {
void ctx.resume();
}
stopScrubSources();
const offset = frame / FPS;
const nowTime = ctx.currentTime;
audibleTracks.forEach((track) => {
const buffer = track.audioBuffer;
if (!buffer) return;
if (offset >= buffer.duration) return;
const duration = Math.min(SCRUB_PREVIEW_SEC, buffer.duration - offset);
if (duration <= 0) return;
const source = ctx.createBufferSource();
source.buffer = buffer;
const gain = ctx.createGain();
const fade = Math.min(SCRUB_FADE_SEC, duration / 2);
const hold = Math.max(0, duration - fade);
gain.gain.setValueAtTime(0, nowTime);
gain.gain.linearRampToValueAtTime(1, nowTime + fade);
gain.gain.setValueAtTime(1, nowTime + hold);
gain.gain.linearRampToValueAtTime(0, nowTime + duration);
source.connect(gain);
gain.connect(ctx.destination);
source.start(0, offset, duration);
scrubNodesRef.current.push({ source, gain });
});
}, [stopScrubSources, tracks]);
const commitScrubFrame = useCallback(
(frame: number) => {
if (scrubFrameLastRef.current === frame) return;
scrubFrameLastRef.current = frame;
commitCurrentFrame(frame);
playScrubPreview(frame);
},
[commitCurrentFrame, playScrubPreview]
);
const flushScrubFrame = useCallback(
(forceFrame?: number | null) => {
if (scrubRafRef.current !== null) {
cancelAnimationFrame(scrubRafRef.current);
scrubRafRef.current = null;
}
const frame = forceFrame ?? scrubFramePendingRef.current;
scrubFramePendingRef.current = null;
if (frame === null || frame === undefined) return;
commitScrubFrame(frame);
},
[commitScrubFrame]
);
const scheduleScrubFrame = useCallback(
(frame: number) => {
if (scrubFrameLastRef.current === frame) return;
scrubFramePendingRef.current = frame;
if (scrubRafRef.current !== null) return;
scrubRafRef.current = requestAnimationFrame(() => {
scrubRafRef.current = null;
const pending = scrubFramePendingRef.current;
scrubFramePendingRef.current = null;