-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
825 lines (676 loc) · 28 KB
/
Copy pathscript.js
File metadata and controls
825 lines (676 loc) · 28 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
import { openSb3, costumeUrl } from './webapp/js/sb3-toolkit.js';
import { SpriteProject, SpriteVisemeRecord } from './webapp/js/sprite-project.js';
// ====== CONFIG: adjust if your files live elsewhere ======
const WORKER_PATH = '/webapp/js/recognizer.local.js';
// const WORKER_PATH = './webapp/js/recognizer.js';
const MODEL_BASE = '/en-us/en-us/';
const DICT_PATH = '/en-us/cmudict-en-us.dict';
const LM_PATH = '/en-us/en-us.lm.bin';
const USE_SENDUMP = true; // set false if your model has mixture_weights instead
const LEAD_MS = 80; // tweak 40..80
// ====== UI helpers ======
const $ = s => document.querySelector(s);
const $status = $('#status'), $transcript = $('#transcript'), $csv = $('#csv');
const $tbl = $('#tbl'), $file = $('#file'), $process = $('#process'), $download = $('#download');
const log = (s, cls) => { const el = document.createElement('div'); el.textContent = s; if (cls) el.className = cls; $status.appendChild(el); $status.scrollTop = $status.scrollHeight; };
/**
* @exports @typedef {{processing: boolean}} StateDef
* @type {StateDef}
*/
const state = { processing: false };
const MOUTH_SRC = {
"Rest": 'img/Rest.svg', "AI": 'img/AI.svg', "E": 'img/E.svg', "O": 'img/O.svg', "U": 'img/U.svg',
"FV": 'img/FV.svg', "L": 'img/L.svg', "M": 'img/M.svg', "Th": 'img/Th.svg', "ChJSh": 'img/ChJSh.svg'
};
// Color per viseme (tweak freely)
const COLOURS = ['#7aa2ff', '#a0ff7a', '#ffd37a', '#ff9f7a',
'#7affd6', '#e07aff', '#ff7ab0', '#7aff8c', '#ff7a7a'];
let VCOL = {
Rest: '#2c3140', AI: '#7aa2ff', E: '#a0ff7a', O: '#ffd37a', U: '#ff9f7a',
FV: '#7affd6', L: '#e07aff', M: '#ff7ab0', Th: '#7aff8c', ChJSh: '#ff7a7a'
};
/** @type SpriteVisemeRecord */
let lastRecord = null;
const buildVisemesFromPhones = buildVisemesFromPhones2
// Build visemes directly from phone hypseg
function buildVisemesFromPhones1(hypseg, minHoldMs = 80, gapToRestMs = 120) {
console.log('hypseg', hypseg, lastRecord);
const restViseme = lastRecord.restViseme;
const out = [];
const push = (t, v) => {
const ts = Math.max(0, Math.round(t));
const last = out[out.length - 1];
if (!last || last.v !== v || last.t !== ts) out.push({ t: ts, v });
};
let prevEnd = 0;
for (const s of hypseg) {
const word = (s.word || '').toLowerCase();
const t0 = s.start * 10, t1 = s.end * 10; // frames→ms
// many builds emit <sil> phones; treat them as gaps
if (!word || /^<.*>$/.test(word)) {
if (t0 - prevEnd >= gapToRestMs) push(prevEnd, restViseme);
prevEnd = Math.max(prevEnd, t1);
continue;
}
const v = lastRecord.phonesToViseme[s.word]?.viseme; // { phone: normPhone(phone), viseme: label, token, note: '' };;
if (!v) {
if (t0 - prevEnd >= gapToRestMs) push(prevEnd, restViseme);
prevEnd = Math.max(prevEnd, t1);
continue; // skip unknown phones
}
// normal phone
if (t0 - prevEnd >= gapToRestMs) push(prevEnd, restViseme);
const last = out[out.length - 1];
if (!last || (last.v !== v && (last.v === restViseme || t0 - last.t >= minHoldMs))) {
push(t0, v);
}
prevEnd = Math.max(prevEnd, t1);
}
if (!out.length || out[0].t > 0) out.unshift({ t: 0, v: restViseme });
// collapse tiny flips but keep REST boundaries
const collapsed = [];
for (const e of out) {
const last = collapsed[collapsed.length - 1];
if (!last) { collapsed.push(e); continue; }
if (e.v === last.v) continue;
if (e.v !== restViseme && last.v !== restViseme && (e.t - last.t) < minHoldMs) continue;
collapsed.push(e);
}
return collapsed;
}
const VOWELS = new Set(['AA', 'AE', 'AH', 'AO', 'AW', 'AY', 'EH', 'ER', 'EY', 'IH', 'IY', 'OW', 'OY', 'UH', 'UW']);
const normPhone = p => (p || '').replace(/[<>+]/g, '').toUpperCase();
function buildVisemesFromPhones2(hypseg, {
minHoldVowel = 50,
minHoldCons = 80,
gapToRestMs = 120
} = {}) {
const restViseme = lastRecord.restViseme;
const out = [];
const push = (t, v) => {
const ts = Math.max(0, Math.round(t));
const last = out[out.length - 1];
if (!last || last.v !== v) out.push({ t: ts, v });
};
let prevEnd = 0;
for (const s of hypseg) {
const p = normPhone(s.word);
const t0 = s.start * 10, t1 = s.end * 10;
// treat explicit silence/noise as gaps – use duration up to silence end
if (/^(SIL|NSN|SPN)$/.test(normPhone(s.word))) {
const t0 = s.start * 10, t1 = s.end * 10;
const silFromLastPhone = t1 - prevEnd; // <-- key change
if (silFromLastPhone >= gapToRestMs) {
const last = out[out.length - 1];
if (!last || last.v !== restViseme) push(prevEnd, restViseme); // close right when speech ends
}
prevEnd = Math.max(prevEnd, t1);
continue;
}
const v = lastRecord.phonesToViseme[p]?.viseme;
if (!v) { // unknown -> gap
if (t0 - prevEnd >= gapToRestMs) push(prevEnd, restViseme);
prevEnd = Math.max(prevEnd, t1);
continue;
}
const minHold = VOWELS.has(p) ? minHoldVowel : minHoldCons;
if (t0 - prevEnd >= gapToRestMs) push(prevEnd, restViseme);
const last = out[out.length - 1];
if (!last) { push(t0, v); prevEnd = Math.max(prevEnd, t1); continue; }
if (last.v === v) { prevEnd = Math.max(prevEnd, t1); continue; }
if (last.v === restViseme || (t0 - last.t) >= minHold) {
// normal change at phone onset
push(t0, v);
} else {
// mid-phone handoff after minHold expires, if it still lands inside this phone
const handoffAt = last.t + minHold;
if (handoffAt < t1 - 1) push(handoffAt, v);
// else: swallow extremely short segment
}
prevEnd = Math.max(prevEnd, t1);
}
// after the loop
if (out.length && out[out.length - 1].v !== restViseme) {
push(prevEnd, restViseme);
}
if (!out.length || out[0].t > 0) out.unshift({ t: 0, v: restViseme });
// keep your collapse if you like; consider dropping micro-RESTs <40ms between non-rests
return out;
}
// ====== Audio decode → Int16 16k mono ======
async function decodeToMono16k(file) {
const MAX_DURATION_MS = 300000; // 5 minutes in milliseconds
const MAX_SAMPLES = Math.floor((MAX_DURATION_MS / 1000) * 16000); // 16kHz sample rate
const arrayBuf = await file.arrayBuffer();
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const src = await ctx.decodeAudioData(arrayBuf);
const offline = new OfflineAudioContext(1, Math.ceil(src.duration * 16000), 16000);
const bs = offline.createBufferSource();
bs.buffer = src;
bs.connect(offline.destination);
bs.start();
const out = await offline.startRendering();
const data = out.getChannelData(0);
if (data.length > MAX_SAMPLES) {
const originalSec = data.length / 16000;
const maxSec = MAX_DURATION_MS / 1000;
const min = Math.floor(originalSec / 60);
const sec = Math.round(originalSec % 60).toString().padStart(2, '0');
const maxMin = Math.floor(maxSec / 60);
const maxRemSec = Math.round(maxSec % 60).toString().padStart(2, '0');
log(`audio too long (truncated from ${min}m${sec}s to ${maxMin}m${maxRemSec}s)`, 'err');
}
// Truncate to the first 5 minutes if necessary
const truncatedData = data.length > MAX_SAMPLES ? data.subarray(0, MAX_SAMPLES) : data;
const pcm16 = new Int16Array(truncatedData.length);
for (let i = 0; i < truncatedData.length; i++) {
const s = Math.max(-1, Math.min(1, truncatedData[i]));
pcm16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
}
return pcm16;
}
// ====== Worker wiring ======
let worker; let canProcess = false; let pendingChunks = []; let filesToLoad = 0; let filesLoaded = 0; let initialized = false;
function startWorker() {
worker = new Worker(WORKER_PATH);
let isListening = false;
let listeningResolvers = [];
let processedResolve = null;
setMouth(lastRecord?.restViseme || 'REST');
function waitForListening() {
if (isListening) return Promise.resolve();
return new Promise(res => listeningResolvers.push(res));
}
function sendChunkAwait(chunk) {
return new Promise(res => {
processedResolve = res;
// SEND AS PLAIN ARRAY (some builds dislike typed arrays)
worker.postMessage({ command: 'process', data: Array.from(chunk) });
});
}
worker.onmessage = (e) => {
const m = e.data || {};
if (m.status === 'error') {
const detail = (typeof m.error === 'object') ? JSON.stringify(m.error) : (m.error || m.data || JSON.stringify(m));
log('Worker error: ' + detail, 'err');
return;
}
if (m.ready) {
log('Worker ready ✔', 'ok');
const preLoadFiles = [
['en-us/en-us/feat.params', 'en-us/en-us/feat.params'],
['en-us/en-us/mdef', 'en-us/en-us/mdef'],
['en-us/en-us/means', 'en-us/en-us/means'],
['en-us/en-us/variances', 'en-us/en-us/variances'],
['en-us/en-us/transition_matrices', 'en-us/en-us/transition_matrices'],
['en-us/en-us/sendump', 'en-us/en-us/sendump'], // or mixture_weights
// ['cmudict-en-us.dict', 'en-us/cmudict-en-us.dict'],
// ['en-us.lm.bin', 'en-us/en-us.lm.bin'],
['en-us/en-us-phone.lm.bin', 'en-us/en-us-phone.lm.bin']
];
filesToLoad = preLoadFiles.length;
worker.postMessage({
command: 'load',
data: preLoadFiles,
});
return;
}
if (m.status === 'load complete') {
worker.postMessage({
command: 'initialize',
data: [
['-samprate', '16000'],
// explicit acoustic model files
['-mdef', 'en-us/en-us/mdef'],
['-mean', 'en-us/en-us/means'],
['-var', 'en-us/en-us/variances'],
['-tmat', 'en-us/en-us/transition_matrices'],
['-sendump', 'en-us/en-us/sendump'], // or ['-mixw','en-us/en-us/mixture_weights']
['-featparams', 'en-us/en-us/feat.params'],
// *** PHONEME MODE ***
['-allphone', 'en-us/en-us-phone.lm.bin'],
['-backtrace', '1'], // essential: enable phone segmentation
['-fwdtree', 'no'],
['-fwdflat', 'no'],
// Optional – keep silences so you see gaps (tweak to taste)
['-remove_silence', 'no'],
['-dither', 'yes'],
['-bestpath', '1'],
['-cmn', 'live'], // per-utterance CMN; reset between runs
['-cmninit', '40,3,-1'], // re-seed CMN so run #1 isn’t “cold”
['-varnorm', 'yes'],
['-agc', 'none'],
['-pl_window', '5'], // back to default, more stable
// no file logging
['-logfn', '/dev/null']
]
});
log('Initialized recognizer');
return;
}
if (m.status === 'listening') {
isListening = true;
for (const r of listeningResolvers) r();
listeningResolvers = [];
log('Listening…');
return;
}
if (m.status === 'proc-recv') {
// optional: uncomment to see inflight chunks
// log(`recv #${m.seq} (${m.len} samples)`);
return;
}
if (m.status === 'processed') {
// optional: uncomment to see acks
// log(`ack #${m.seq}`);
if (processedResolve) { processedResolve(); processedResolve = null; }
return;
}
if (m.status === 'stopped' || m.hypseg) {
if (m.hyp) $transcript.textContent = m.hyp;
if (m.hypseg) {
const minHold = parseInt($('#minHold').value || '80', 10);
const vowelW = parseFloat($('#vowelW').value || '1.4');
const visemes = buildVisemesFromPhones(m.hypseg, /*minHoldMs*/ parseInt($('#minHold').value || '80', 10),
/*gapToRestMs*/ 120);
$tbl.innerHTML = visemes.map(e => `<tr><td>${e.t}</td><td>${e.v}</td></tr>`).join('');
const lines = ['time_ms,viseme', ...visemes.map(e => `${e.t},${e.v}`)];
$csv.value = lines.join("\n");
// After you compute `visemes` and fill the table/CSV:
lastVisemes = visemes.slice(); // keep a copy
drawTimeline(lastVisemes, lastDurationMs);
// Reset readout + playhead to start
$curV.textContent = lastRecord?.restViseme || 'REST';
drawPlayhead(0, lastDurationMs);
setMouth(lastRecord?.restViseme || 'REST');
$play.textContent = '▶ Play';
$download.disabled = false;
proj.writeVismeDataToSprite(lastRecord, visemes, state);
log('Done ✔', 'ok');
}
return;
}
if (m.status === 'loaded') {
filesLoaded++;
log(`Loaded ${m.file} (${filesLoaded}/${filesToLoad})`);
if (filesLoaded === filesToLoad) {
log('All model files loaded ✔', 'ok');
canProcess = true;
}
return;
}
if (m.status) log(m.status);
};
// Resample PCM16 waveform for drawing: min/max per column (chunk)
// This version ensures each chunk covers an equal number of samples,
// and always finds the true min/max in each chunk.
function resampleWaveformForDrawing(pcm16) {
if (!pcm16 || !pcm16.length) return;
const W = $wave.width;
const chunkSize = Math.ceil(pcm16.length / W);
// Precompute min/max for each column
const minArr = new Float32Array(W);
const maxArr = new Float32Array(W);
for (let col = 0; col < W; col++) {
let min = 1, max = -1;
const start = col * chunkSize;
const end = Math.min(start + chunkSize, pcm16.length);
for (let i = start; i < end; i++) {
const v = pcm16[i] / 32768;
if (v < min) min = v;
if (v > max) max = v;
}
minArr[col] = min;
maxArr[col] = max;
}
// Optionally, you can store minArr/maxArr for later use
// or return them if needed
lastMinArr = minArr; lastMaxArr = maxArr;
}
$process.addEventListener('click', () => {
if (!$file.files.length) return;
const file = $file.files[0];
processAudio(file);
});
/**
*
* @param {Blob|File} file
* @param {SpriteVisemeRecord} record
* @returns
*/
async function processAudio(file, record) {
if (!file) {
setLastRecord();
drawWaveform();
drawTimeline();
return;
}
console.log(record);
setLastRecord(record);
$process.disabled = true; $download.disabled = true;
$csv.value = ''; $tbl.innerHTML = ''; $status.textContent = '';
state.processing = true;
try {
log('Decoding & resampling to 16k mono…');
const pcm16 = await decodeToMono16k(file);
log(`Samples: ${pcm16.length.toLocaleString()} (16kHz)`);
lastPCM16 = pcm16;
lastDurationMs = Math.round((pcm16.length / 16000) * 1000);
resampleWaveformForDrawing(pcm16);
// Waveform baseline
drawWaveform(lastPCM16, lastDurationMs);
// Set up the audio element for playback/sync
if (urlObject) URL.revokeObjectURL(urlObject);
urlObject = URL.createObjectURL(file);
$player.src = urlObject;
$player.onended = () => { stopAnim(); $play.textContent = '▶ Play'; };
$play.disabled = false;
// Create the waiter BEFORE start to avoid races
const listeningP = waitForListening();
worker.postMessage({ command: 'start', warmupMs: 500 }); // once-per-worker warm-up
await listeningP;
log('Streaming to worker, Please wait…');
const CHUNK = 16384; // 1s chunks 16k
for (let i = 0; i < pcm16.length; i += CHUNK) {
processProgress = i / pcm16.length;
drawWaveform(lastPCM16, lastDurationMs);
const slice = pcm16.subarray(i, i + CHUNK);
await sendChunkAwait(slice); // waits for 'processed'
}
processProgress = 1;
worker.postMessage({ command: 'stop' });
} catch (err) {
console.error(err);
log('Error: ' + (err?.message || err), 'err');
} finally {
$process.disabled = false;
state.processing = false;
}
}
proj.setProcessAudio(processAudio);
/**
*
* @param {SpriteVisemeRecord} record
*/
function setLastRecord(record) {
lastRecord = record; // Keep track of the record we are processing!
VCOL = {}; // reset
const costumeNames = Object.keys(record.costumeToPhones);
let i = 0;
for (const cname of costumeNames) {
if (cname === record.restViseme) {
VCOL[cname] = '#2c3140'; // dark grey for REST
} else {
VCOL[cname] = COLOURS[i++ % (COLOURS.length)];
}
}
}
}
// $file.addEventListener('change', () => { $process.disabled = !worker || !$file.files?.length; });
let isListening = false;
let listeningResolvers = [];
let processedResolve = null;
let processProgress = 0; // processingProgress (0..1)
// called once in your script:
function waitForListening() {
if (isListening) return Promise.resolve();
return new Promise(res => listeningResolvers.push(res));
}
function sendChunkAwait(chunk) {
return new Promise(res => {
processedResolve = res;
worker.postMessage({ command: 'process', data: chunk });
});
}
// === Visualiser state ===
const $wave = document.getElementById('wave');
const $timeline = document.getElementById('timeline');
const $play = document.getElementById('playPause');
const $player = document.getElementById('player');
const $curV = document.getElementById('currentViseme');
let lastPCM16 = null; // filled when you decode
let lastVisemes = []; // filled when we build visemes
let lastDurationMs = 0; // total audio duration in ms
let lastMinArr = null, lastMaxArr = null; // resampled waveform data
let urlObject = null;
// Draw a simple RMS waveform from Int16
function drawWaveform(pcm16, durationMs) {
const ctx = $wave.getContext('2d');
const W = $wave.width, H = $wave.height;
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = '#0f1117';
ctx.fillRect(0, 0, W, H);
if (!lastMaxArr || !pcm16 || !pcm16.length) return;
// Downsample to columns
const cols = W;
const step = Math.max(1, Math.floor(pcm16.length / cols));
let processedX = processProgress * cols;
ctx.strokeStyle = '#7a7a7a';
ctx.beginPath();
// Precompute min/max for each column in a single pass
const minArr = lastMinArr;
const maxArr = lastMaxArr;
for (let x = 0; x < cols; x++) {
const min = minArr[x];
const max = maxArr[x];
const mid = H / 2;
if (x > processedX) {
processedX = 999;
ctx.stroke();
ctx.strokeStyle = '#3a4154';
ctx.beginPath();
}
ctx.moveTo(x, mid + min * mid);
ctx.lineTo(x, mid + max * mid);
}
ctx.stroke();
// axis baseline
ctx.strokeStyle = '#242938';
ctx.beginPath();
ctx.moveTo(0, H / 2); ctx.lineTo(W, H / 2);
ctx.stroke();
}
// Draw viseme timeline blocks across the width
function drawTimeline(visemes, durationMs) {
const ctx = $timeline.getContext('2d');
const W = $timeline.width, H = $timeline.height;
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = '#0f1117';
ctx.fillRect(0, 0, W, H);
if (!visemes || !visemes.length || durationMs <= 0) return;
// Convert viseme events (t,v) into spans [t..next.t or end]
for (let i = 0; i < visemes.length; i++) {
const t0 = visemes[i].t;
const t1 = (i < visemes.length - 1) ? visemes[i + 1].t : durationMs;
const v = visemes[i].v;
const x = Math.floor((t0 / durationMs) * W);
const w = Math.max(1, Math.floor(((t1 - t0) / durationMs) * W));
ctx.fillStyle = VCOL[v] || '#505a72';
ctx.fillRect(x, 0, w, H);
}
}
// Draw the moving playhead on both canvases
function drawPlayhead(ms, durationMs) {
const PW = Math.max(1, Math.floor(1)); // playhead width
const wx = Math.floor((ms / durationMs) * $wave.width);
const tx = Math.floor((ms / durationMs) * $timeline.width);
const wctx = $wave.getContext('2d');
const tctx = $timeline.getContext('2d');
// redraw base then overlay line for crispness:
drawWaveform(lastPCM16, lastDurationMs);
drawTimeline(lastVisemes, lastDurationMs);
wctx.fillStyle = '#ffd54a';
wctx.fillRect(wx, 0, PW, $wave.height);
tctx.fillStyle = '#ffd54a';
tctx.fillRect(tx, 0, PW, $timeline.height);
// in your animation loop:
const v = visemeAt(lastVisemes, ms);
$curV.textContent = v;
setMouth(v);
}
// Find current viseme for time ms
function visemeAt(visemes, ms) {
if (!visemes || !visemes.length) return lastRecord?.restViseme || 'REST';
// binary search would be better; linear is fine for small lists:
let cur = lastRecord?.restViseme || 'REST';
for (let i = 0; i < visemes.length; i++) {
if (visemes[i].t <= ms) cur = visemes[i].v; else break;
}
return cur;
}
// const $mouthImg = document.getElementById('mouthImg');
/** @type {HTMLCanvasElement} */
const $mouthCanvas = document.getElementById('mouthCanvas');
// $mouthImg.style.display = 'none'; // hide until loaded
const $projectSprites = document.getElementById('project-sprites');
$projectSprites.style.display = 'none'; // hide until loaded
const $spriteCostumes = document.getElementById('sprite-costumes');
$spriteCostumes.style.display = 'none'; // hide until loaded
const $spriteSounds = document.getElementById('sprite-sounds');
$spriteSounds.style.display = 'none'; // hide until loaded
function setMouth(v) {
if (lastRecord) {
lastRecord.drawCostume($mouthCanvas, v);
}
}
// Animation loop tied to <audio> time
let rafId = 0;
let lastDraw = 0;
function loop() {
const now = performance.now();
if (now - lastDraw > 33) {
const ms = $player.currentTime * 1000;
drawPlayhead(ms, lastDurationMs);
lastDraw = now;
}
rafId = requestAnimationFrame(loop);
}
function attachSeek(canvas) {
let isSeeking = false;
function seek(ev) {
if (!lastDurationMs || !$player.src) return;
const rect = canvas.getBoundingClientRect();
const x = (ev.touches ? ev.touches[0].clientX : ev.clientX) - rect.left;
const frac = Math.max(0, Math.min(1, x / rect.width));
$player.currentTime = (frac * lastDurationMs) / 1000;
drawPlayhead(frac * lastDurationMs, lastDurationMs);
}
function startSeek(ev) { isSeeking = true; seek(ev); ev.preventDefault?.(); }
function moveSeek(ev) { if (isSeeking) { seek(ev); ev.preventDefault?.(); } }
function endSeek() { isSeeking = false; }
canvas.addEventListener('mousedown', startSeek);
canvas.addEventListener('mousemove', moveSeek);
window.addEventListener('mouseup', endSeek);
canvas.addEventListener('touchstart', startSeek, { passive: false });
canvas.addEventListener('touchmove', moveSeek, { passive: false });
window.addEventListener('touchend', endSeek);
canvas.addEventListener('click', seek);
}
attachSeek($wave);
attachSeek($timeline);
// Wire play/pause (create URL from the uploaded file so we play the same audio)
$play.addEventListener('click', () => {
if (!$player.src) return; // nothing loaded yet
if ($player.paused) {
$player.play();
$play.textContent = '⏸ Pause';
stopAnim();
rafId = requestAnimationFrame(loop);
} else {
$player.pause();
$play.textContent = '▶ Play';
stopAnim();
drawPlayhead($player.currentTime * 1000, lastDurationMs); // freeze playhead
}
});
function stopAnim() {
cancelAnimationFrame(rafId);
rafId = 0;
setMouth(lastRecord?.restViseme || 'REST');
}
const proj = new SpriteProject();
const container = document.getElementById('project-sprites');
const tbodySprite = document.getElementById('spr-tbl');
const tbodyCost = document.getElementById('cost-tbl');
const tbodySound = document.getElementById('sound-tbl');
document.getElementById('btnSave').addEventListener('click', async () => {
if (!proj) return;
try {
let ok = await proj.save('test.sb3');
showButtonFeedback(document.getElementById('btnSave'), '✔ Saved');
} catch (e) {
showButtonFeedback(document.getElementById('btnSave'), '✖ Failed', true);
}
});
document.getElementById('btnLoad').addEventListener('click', async () => {
/* const result = await openSb3(); // this will try Access API first, else fall back to its own hidden <input>
if (result.method === 'cancelled') return;
console.log('Loaded', result.name);
console.log('Summary:', summarize());
*/
// 1) Load a project
const res = await openSb3();
if (res.method === 'cancelled') return;
// todo: loop through targets and clear down any viseme list data for sounds that no longer exist
drawTimeline();
drawWaveform();
stopAnim();
$play.disabled = true;
$process.disabled = true;
lastRecord = null;
$spriteSounds.style.display = 'none';
// analyze + render
await proj.analyze({
minHitsPerCostume: 1,
minMappedPerSprite: 4,
soundPriorityWeight: 0.25
});
$projectSprites.style.display = 'block';
// 2) Render the sprite list
proj.renderSpriteTable(tbodySprite, container, state, {
/**
* @param {SpriteVisemeRecord} rec
*/
onSelect: (rec) => {
// Light feedback — you get the FULL record here:
console.log('Selected:', rec.name, 'mapped:', rec.totalMapped, rec);
$spriteCostumes.style.display = 'block'; // show when a sprite is selected
$spriteSounds.style.display = 'block';
proj.renderCostumeTable(rec, tbodyCost);
proj.renderSoundTable(rec, tbodySound, state);
// rec.selectedSound
rec.drawCostume($mouthCanvas, rec.restViseme);
},
/**
* @param {SpriteVisemeRecord} rec
*/
onChoose: (rec) => {
// Start your processing flow
console.log('Chosen for processing:', rec.name);
// e.g., open a right panel with its mapped costumes, apply phone→label mapping, etc.
}
});
});
function showButtonFeedback(btn, msg, isError = false) {
let span = btn.querySelector('.save-feedback');
if (!span) {
span = document.createElement('span');
span.className = 'save-feedback';
btn.appendChild(span);
}
span.textContent = msg;
span.style.color = isError ? '#d00' : '#8f8';
setTimeout(() => {
span.style.padding = '0 8px !important';
span.style.width = 'inherit';
span.style.opacity = '1';
// fade out after 2s
setTimeout(() => {
span.style.opacity = '0';
span.style.width = '0';
span.style.padding = '0';
span.style.color = '#888'
}, 3000);
}, 0);
}
startWorker();