Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
689 lines (586 loc) · 20.7 KB
/
Copy pathapp.js
File metadata and controls
689 lines (586 loc) · 20.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
'use strict';
/* ------------------------------------------------------------------ *
* Frame Extractor — navegação frame a frame em vídeos locais e
* exportação do frame selecionado como JPG no tamanho original.
* ------------------------------------------------------------------ */
const $ = (id) => document.getElementById(id);
const video = $('video');
const thumbVideo = $('thumbVideo');
const capture = $('capture');
const tlCanvas = $('timeline');
const tlCtx = tlCanvas.getContext('2d');
const ui = {
openBtn: $('openBtn'), fileInput: $('fileInput'), fileName: $('fileName'),
dropzone: $('dropzone'), stage: $('stage'), status: $('status'),
infoRes: $('infoRes'), infoFps: $('infoFps'), infoFrames: $('infoFrames'), infoTime: $('infoTime'),
frameInput: $('frameInput'), frameTotal: $('frameTotal'),
first: $('firstBtn'), prev10: $('prev10Btn'), prev: $('prevBtn'),
next: $('nextBtn'), next10: $('next10Btn'), last: $('lastBtn'),
fpsInput: $('fpsInput'), quality: $('quality'), qVal: $('qVal'), saveBtn: $('saveBtn'),
};
const state = {
file: null,
url: null,
duration: 0,
fps: 30,
frameCount: 1,
frame: 0, // 0-based internamente; exibido como frame+1
ready: false,
viewStart: 0, // primeiro frame visível na timeline (float)
viewFrames: 1, // quantos frames cabem na janela visível (float)
};
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
/* ------------------------------------------------------------------ *
* Carregamento do arquivo
* ------------------------------------------------------------------ */
ui.openBtn.addEventListener('click', () => ui.fileInput.click());
ui.fileInput.addEventListener('change', () => {
if (ui.fileInput.files[0]) loadFile(ui.fileInput.files[0]);
});
for (const evt of ['dragenter', 'dragover']) {
document.addEventListener(evt, (e) => {
e.preventDefault();
ui.dropzone.classList.add('over');
});
}
for (const evt of ['dragleave', 'drop']) {
document.addEventListener(evt, (e) => {
e.preventDefault();
if (evt === 'dragleave' && e.relatedTarget) return;
ui.dropzone.classList.remove('over');
});
}
document.addEventListener('drop', (e) => {
const f = e.dataTransfer && e.dataTransfer.files[0];
if (f) loadFile(f);
});
async function loadFile(file) {
if (!file.type.startsWith('video/') && !/\.(mp4|m4v|mov|webm|mkv)$/i.test(file.name)) {
setStatus('Arquivo não parece ser um vídeo.');
return;
}
if (state.url) URL.revokeObjectURL(state.url);
thumbs.reset();
state.file = file;
state.url = URL.createObjectURL(file);
state.ready = false;
ui.fileName.textContent = file.name;
setStatus('Carregando vídeo…');
video.src = state.url;
thumbVideo.src = state.url;
try {
await once(video, 'loadedmetadata');
} catch {
setStatus('Não foi possível carregar este vídeo (codec não suportado pelo navegador).');
return;
}
state.duration = video.duration;
if (!isFinite(state.duration) || state.duration <= 0) {
setStatus('Duração do vídeo desconhecida — arquivo possivelmente corrompido.');
return;
}
ui.dropzone.classList.add('hidden');
ui.stage.classList.remove('hidden');
setStatus('Detectando taxa de quadros…');
const detected = await detectFps(video);
setFps(detected || 30);
if (!detected) {
setStatus('FPS não detectado automaticamente — ajuste o campo FPS se necessário.');
} else {
setStatus('');
}
state.ready = true;
state.viewStart = 0;
state.viewFrames = state.frameCount;
resizeTimeline();
await gotoFrame(0);
}
function once(el, type) {
return new Promise((resolve, reject) => {
const ok = (e) => { cleanup(); resolve(e); };
const err = (e) => { cleanup(); reject(e); };
const cleanup = () => {
el.removeEventListener(type, ok);
el.removeEventListener('error', err);
};
el.addEventListener(type, ok, { once: true });
el.addEventListener('error', err, { once: true });
});
}
/* ------------------------------------------------------------------ *
* Detecção de FPS
* Reproduz um trecho curto e mede o intervalo entre os mediaTime
* reportados por requestVideoFrameCallback.
* ------------------------------------------------------------------ */
const COMMON_FPS = [
24000 / 1001, 24, 25, 30000 / 1001, 30, 48, 50,
60000 / 1001, 60, 90, 100, 120000 / 1001, 120,
];
function detectFps(v) {
if (typeof v.requestVideoFrameCallback !== 'function') return Promise.resolve(null);
return new Promise((resolve) => {
const deltas = [];
let last = null;
let done = false;
const finish = () => {
if (done) return;
done = true;
v.pause();
v.currentTime = 0;
if (deltas.length < 5) return resolve(null);
deltas.sort((a, b) => a - b);
const median = deltas[Math.floor(deltas.length / 2)];
if (!(median > 0)) return resolve(null);
resolve(snapFps(1 / median));
};
const cb = (_now, meta) => {
if (done) return;
if (last !== null && meta.mediaTime > last) deltas.push(meta.mediaTime - last);
last = meta.mediaTime;
if (deltas.length >= 24) return finish();
v.requestVideoFrameCallback(cb);
};
v.muted = true;
v.currentTime = 0;
v.requestVideoFrameCallback(cb);
const p = v.play();
if (p && p.catch) p.catch(() => finish());
setTimeout(finish, 2500);
});
}
function snapFps(raw) {
let best = raw, bestErr = Infinity;
for (const cand of COMMON_FPS) {
const err = Math.abs(cand - raw) / cand;
if (err < bestErr) { bestErr = err; best = cand; }
}
return bestErr <= 0.02 ? best : Math.round(raw * 1000) / 1000;
}
function setFps(fps) {
state.fps = clamp(fps, 1, 480);
state.frameCount = Math.max(1, Math.round(state.duration * state.fps));
ui.fpsInput.value = Math.round(state.fps * 1000) / 1000;
ui.frameInput.max = state.frameCount;
ui.frameTotal.textContent = '/ ' + state.frameCount;
state.viewFrames = clamp(state.viewFrames || state.frameCount, MIN_VIEW, state.frameCount);
updateInfo();
}
ui.fpsInput.addEventListener('change', async () => {
const v = parseFloat(ui.fpsInput.value);
if (!isFinite(v) || v <= 0) { ui.fpsInput.value = state.fps; return; }
const t = frameToTime(state.frame);
setFps(v);
thumbs.reset();
state.viewStart = 0;
state.viewFrames = state.frameCount;
await gotoFrame(Math.round(t * state.fps));
});
/* ------------------------------------------------------------------ *
* Conversão frame <-> tempo e navegação
* ------------------------------------------------------------------ */
function frameToTime(f) {
const t = (f + 0.5) / state.fps;
return clamp(t, 0, Math.max(0, state.duration - 1e-4));
}
let seekPending = null;
let seeking = false;
let seekResolvers = [];
function pumpSeek() {
if (seekPending === null) { seeking = false; return; }
const f = seekPending;
seekPending = null;
seeking = true;
video.currentTime = frameToTime(f);
}
video.addEventListener('seeked', () => {
if (seekPending !== null) { pumpSeek(); return; }
seeking = false;
updateInfo();
const rs = seekResolvers;
seekResolvers = [];
rs.forEach((r) => r());
});
function seekToFrame(f) {
return new Promise((resolve) => {
let done = false;
const finish = () => { if (!done) { done = true; resolve(); } };
seekResolvers.push(finish);
// rede de seguranca: alguns navegadores nao emitem 'seeked' para
// uma busca redundante — nunca deixamos a promessa pendurada.
setTimeout(finish, 2000);
seekPending = f;
if (!seeking) pumpSeek();
});
}
function atFrame(f) {
return Math.abs(video.currentTime - frameToTime(f)) <= 1 / state.fps;
}
async function gotoFrame(f) {
if (!state.file) return;
state.frame = clamp(Math.round(f), 0, state.frameCount - 1);
ui.frameInput.value = state.frame + 1;
ensureVisible();
updateInfo();
drawTimeline();
if (!seeking && seekPending === null &&
Math.abs(video.currentTime - frameToTime(state.frame)) < 1e-6) return;
await seekToFrame(state.frame);
drawTimeline();
}
const step = (d) => gotoFrame(state.frame + d);
ui.first.addEventListener('click', () => gotoFrame(0));
ui.prev10.addEventListener('click', () => step(-10));
ui.prev.addEventListener('click', () => step(-1));
ui.next.addEventListener('click', () => step(1));
ui.next10.addEventListener('click', () => step(10));
ui.last.addEventListener('click', () => gotoFrame(state.frameCount - 1));
ui.frameInput.addEventListener('change', () => {
const v = parseInt(ui.frameInput.value, 10);
if (isFinite(v)) gotoFrame(v - 1);
else ui.frameInput.value = state.frame + 1;
});
document.addEventListener('keydown', (e) => {
if (!state.ready) return;
const tag = document.activeElement && document.activeElement.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') return;
switch (e.key) {
case 'ArrowLeft': step(e.shiftKey ? -10 : -1); break;
case 'ArrowRight': step(e.shiftKey ? 10 : 1); break;
case 'Home': gotoFrame(0); break;
case 'End': gotoFrame(state.frameCount - 1); break;
default: return;
}
e.preventDefault();
});
function updateInfo() {
ui.infoRes.textContent = video.videoWidth ? `${video.videoWidth}×${video.videoHeight}` : '—';
ui.infoFps.textContent = `${Math.round(state.fps * 1000) / 1000} fps`;
ui.infoFrames.textContent = `frame ${state.frame + 1} de ${state.frameCount}`;
ui.infoTime.textContent = `${fmtTime(video.currentTime)} / ${fmtTime(state.duration)}`;
}
function fmtTime(t) {
if (!isFinite(t)) return '--:--';
const h = Math.floor(t / 3600);
const m = Math.floor((t % 3600) / 60);
const s = Math.floor(t % 60);
const ms = Math.floor((t % 1) * 1000);
const pad = (n, w = 2) => String(n).padStart(w, '0');
return (h ? pad(h) + ':' : '') + pad(m) + ':' + pad(s) + '.' + pad(ms, 3);
}
function setStatus(msg, ok = false) {
ui.status.textContent = msg;
ui.status.classList.toggle('ok', !!ok);
}
/* ------------------------------------------------------------------ *
* Timeline
* ------------------------------------------------------------------ */
const MIN_VIEW = 6; // zoom máximo: 6 frames na tela
const STRIP_H = 62; // altura da faixa de miniaturas
const RULER_H = 42; // altura da régua
let tlW = 0, tlH = 0;
function resizeTimeline() {
const dpr = window.devicePixelRatio || 1;
const rect = tlCanvas.getBoundingClientRect();
tlW = Math.max(1, Math.round(rect.width));
tlH = Math.max(1, Math.round(rect.height));
tlCanvas.width = Math.round(tlW * dpr);
tlCanvas.height = Math.round(tlH * dpr);
tlCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
drawTimeline();
}
window.addEventListener('resize', resizeTimeline);
const pxPerFrame = () => tlW / state.viewFrames;
const frameToX = (f) => (f - state.viewStart) * pxPerFrame();
const xToFrame = (x) => state.viewStart + x / pxPerFrame();
function clampView() {
state.viewFrames = clamp(state.viewFrames, Math.min(MIN_VIEW, state.frameCount), state.frameCount);
state.viewStart = clamp(state.viewStart, 0, Math.max(0, state.frameCount - state.viewFrames));
}
function ensureVisible() {
clampView();
const margin = state.viewFrames * 0.1;
if (state.frame < state.viewStart + margin) {
state.viewStart = state.frame - margin;
} else if (state.frame > state.viewStart + state.viewFrames - margin) {
state.viewStart = state.frame - state.viewFrames + margin;
}
clampView();
}
function drawTimeline() {
if (!tlW) return;
const c = tlCtx;
clampView();
c.clearRect(0, 0, tlW, tlH);
c.fillStyle = '#1c2027';
c.fillRect(0, 0, tlW, tlH);
drawStrip(c);
drawRuler(c);
drawPlayhead(c);
}
function drawStrip(c) {
const ar = video.videoWidth ? video.videoWidth / video.videoHeight : 16 / 9;
const thumbH = STRIP_H - 8;
const thumbW = Math.max(24, Math.round(thumbH * ar));
const slots = Math.max(1, Math.floor(tlW / thumbW));
const slotW = tlW / slots;
const wanted = [];
c.save();
c.beginPath();
c.rect(0, 0, tlW, STRIP_H);
c.clip();
for (let i = 0; i < slots; i++) {
const x = i * slotW;
const f = clamp(Math.round(xToFrame(x + slotW / 2)), 0, state.frameCount - 1);
const img = thumbs.get(f);
c.fillStyle = '#12151b';
c.fillRect(x + 1, 4, slotW - 2, thumbH);
if (img) {
// preenche o slot mantendo a proporção (cover)
const sc = Math.max((slotW - 2) / img.width, thumbH / img.height);
const w = img.width * sc, h = img.height * sc;
c.drawImage(img, x + 1 + (slotW - 2 - w) / 2, 4 + (thumbH - h) / 2, w, h);
} else {
wanted.push(f);
}
c.strokeStyle = '#272d38';
c.lineWidth = 1;
c.strokeRect(x + 1.5, 4.5, slotW - 3, thumbH - 1);
}
c.restore();
thumbs.request(wanted);
}
function niceStep(minFrames) {
const steps = [1, 2, 5, 10, 15, 20, 25, 30, 50, 60, 100, 150, 250, 300, 500, 600, 1000,
1500, 2500, 3000, 5000, 10000, 25000, 50000, 100000];
for (const s of steps) if (s >= minFrames) return s;
return steps[steps.length - 1];
}
function drawRuler(c) {
const top = STRIP_H;
c.fillStyle = '#171a21';
c.fillRect(0, top, tlW, RULER_H);
c.strokeStyle = '#333a47';
c.beginPath();
c.moveTo(0, top + 0.5);
c.lineTo(tlW, top + 0.5);
c.stroke();
const ppf = pxPerFrame();
// quando bem ampliado, desenha a célula de cada frame
if (ppf >= 4) {
const f0 = Math.floor(state.viewStart);
const f1 = Math.ceil(state.viewStart + state.viewFrames);
for (let f = f0; f <= f1; f++) {
if (f < 0 || f >= state.frameCount) continue;
const x = frameToX(f);
c.fillStyle = f === state.frame ? '#2f4a6d' : (f % 2 ? '#1b1f27' : '#1e222b');
c.fillRect(x, top + 1, ppf, RULER_H - 14);
}
}
const stepF = niceStep(Math.ceil(64 / ppf));
c.font = '11px ui-monospace, SFMono-Regular, Menlo, monospace';
c.textAlign = 'center';
c.textBaseline = 'bottom';
const start = Math.max(0, Math.floor(state.viewStart / stepF) * stepF);
const end = Math.min(state.frameCount - 1, state.viewStart + state.viewFrames);
for (let f = start; f <= end; f += stepF) {
const x = frameToX(f) + (ppf >= 4 ? ppf / 2 : 0);
if (x < -40 || x > tlW + 40) continue;
c.strokeStyle = '#414a5b';
c.beginPath();
c.moveTo(Math.round(x) + 0.5, top + RULER_H - 13);
c.lineTo(Math.round(x) + 0.5, top + RULER_H - 6);
c.stroke();
c.fillStyle = '#8b94a5';
c.fillText(String(f + 1), x, tlH - 4);
}
}
function drawPlayhead(c) {
const ppf = pxPerFrame();
const x = frameToX(state.frame) + (ppf >= 4 ? ppf / 2 : 0);
c.strokeStyle = '#4c9aff';
c.lineWidth = 2;
c.beginPath();
c.moveTo(x, 0);
c.lineTo(x, STRIP_H + RULER_H - 14);
c.stroke();
// etiqueta com o número do frame
const label = String(state.frame + 1);
c.font = 'bold 11px ui-monospace, SFMono-Regular, Menlo, monospace';
const w = c.measureText(label).width + 12;
const lx = clamp(x - w / 2, 2, tlW - w - 2);
c.fillStyle = '#4c9aff';
c.fillRect(lx, 4, w, 16);
c.fillStyle = '#0d1117';
c.textAlign = 'center';
c.textBaseline = 'middle';
c.fillText(label, lx + w / 2, 12.5);
}
/* --- interação: arrastar para navegar, roda do mouse para zoom --- */
let dragging = false;
tlCanvas.addEventListener('pointerdown', (e) => {
if (!state.ready) return;
dragging = true;
tlCanvas.setPointerCapture(e.pointerId);
scrubTo(e);
});
tlCanvas.addEventListener('pointermove', (e) => {
if (dragging) scrubTo(e);
});
for (const evt of ['pointerup', 'pointercancel']) {
tlCanvas.addEventListener(evt, (e) => {
dragging = false;
try { tlCanvas.releasePointerCapture(e.pointerId); } catch {}
});
}
function scrubTo(e) {
const rect = tlCanvas.getBoundingClientRect();
const x = e.clientX - rect.left;
gotoFrame(xToFrame(x));
}
tlCanvas.addEventListener('wheel', (e) => {
if (!state.ready) return;
e.preventDefault();
const rect = tlCanvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const anchor = xToFrame(x);
const factor = e.deltaY > 0 ? 1.25 : 0.8;
state.viewFrames = clamp(state.viewFrames * factor,
Math.min(MIN_VIEW, state.frameCount), state.frameCount);
state.viewStart = anchor - (x / tlW) * state.viewFrames;
clampView();
drawTimeline();
}, { passive: false });
/* ------------------------------------------------------------------ *
* Miniaturas (vídeo secundário, uma busca por vez)
* ------------------------------------------------------------------ */
const thumbs = {
cache: new Map(),
queue: [],
busy: false,
gen: 0,
MAX: 400,
reset() {
this.cache.clear();
this.queue.length = 0;
this.gen++;
},
get(f) {
return this.cache.get(f) || null;
},
request(frames) {
if (!frames.length) return;
// a fila só guarda o que está visível agora
this.queue = frames.filter((f) => !this.cache.has(f));
if (!this.busy) this.run();
},
async run() {
this.busy = true;
const gen = this.gen;
while (this.queue.length) {
if (gen !== this.gen) break;
const f = this.queue.shift();
if (this.cache.has(f)) continue;
try {
const img = await this.grab(f);
if (gen !== this.gen) break;
this.cache.set(f, img);
if (this.cache.size > this.MAX) {
this.cache.delete(this.cache.keys().next().value);
}
drawTimeline();
} catch {
break;
}
}
this.busy = false;
},
grab(f) {
return new Promise((resolve, reject) => {
if (!thumbVideo.videoWidth && thumbVideo.readyState < 1) {
thumbVideo.addEventListener('loadedmetadata', () => this.grab(f).then(resolve, reject), { once: true });
return;
}
const timer = setTimeout(() => { cleanup(); reject(new Error('timeout')); }, 5000);
const onSeeked = () => {
clearTimeout(timer);
cleanup();
const h = 54;
const w = Math.max(2, Math.round(h * (thumbVideo.videoWidth / thumbVideo.videoHeight)));
const cv = document.createElement('canvas');
cv.width = w; cv.height = h;
cv.getContext('2d').drawImage(thumbVideo, 0, 0, w, h);
resolve(cv);
};
const onError = () => { clearTimeout(timer); cleanup(); reject(new Error('thumb')); };
const cleanup = () => {
thumbVideo.removeEventListener('seeked', onSeeked);
thumbVideo.removeEventListener('error', onError);
};
thumbVideo.addEventListener('seeked', onSeeked, { once: true });
thumbVideo.addEventListener('error', onError, { once: true });
thumbVideo.currentTime = frameToTime(f);
});
},
};
/* ------------------------------------------------------------------ *
* Exportação JPG
* ------------------------------------------------------------------ */
ui.quality.addEventListener('input', () => { ui.qVal.textContent = ui.quality.value; });
ui.saveBtn.addEventListener('click', async () => {
if (!state.ready) return;
ui.saveBtn.disabled = true;
setStatus('Gerando JPG…');
try {
await saveJpg();
} catch (err) {
const hint = err.name === 'SecurityError'
? ' — abra a página por um servidor local (ex.: python3 -m http.server) em vez de file://'
: '';
setStatus('Falha ao salvar: ' + err.message + hint);
} finally {
ui.saveBtn.disabled = false;
}
});
async function saveJpg() {
// garante que a busca terminou e que o frame correto já foi apresentado
for (let i = 0; i < 3; i++) {
if (!seeking && seekPending === null && atFrame(state.frame)) break;
await seekToFrame(state.frame);
}
await framePainted();
const w = video.videoWidth, h = video.videoHeight;
if (!w || !h) throw new Error('dimensões do vídeo indisponíveis');
capture.width = w;
capture.height = h;
const ctx = capture.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
const quality = parseInt(ui.quality.value, 10) / 100;
const blob = await new Promise((res, rej) => {
capture.toBlob((b) => (b ? res(b) : rej(new Error('toBlob falhou'))), 'image/jpeg', quality);
});
const base = state.file.name.replace(/\.[^.]+$/, '');
const pad = String(state.frameCount).length;
const name = `${base}_frame_${String(state.frame + 1).padStart(pad, '0')}.jpg`;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 4000);
setStatus(`Salvo: ${name} — ${w}×${h} · ${(blob.size / 1024).toFixed(0)} KB`, true);
}
function framePainted() {
if (typeof video.requestVideoFrameCallback !== 'function') {
return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
}
return new Promise((resolve) => {
let done = false;
const finish = () => { if (!done) { done = true; resolve(); } };
video.requestVideoFrameCallback(finish);
setTimeout(finish, 300);
});
}
/* ------------------------------------------------------------------ */
resizeTimeline();