File size: 41,280 Bytes
48b1aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use strict";
// LeanScene in the browser. Mirrors leanscene.frame_probs and leanscene.label_frames:
// every frame is decoded (WebCodecs), resized to 100x100, and run through the CNN in batches;
// the temporal head then labels each frame same / cut / fade, and the frozen rule
// (cut >= 0.7, fade >= 0.8, fade runs closed over gaps of <= 8 frames) turns that into transitions.
const $ = id => document.getElementById(id);
const SIZE = 100, HW = SIZE * SIZE, BATCH = 64, TILES = 8;  // TILES: frames are resized into an atlas of 8x8 tiles
const HEAD_CHUNK = 512, HEAD_MARGIN = 64;  // the head sees 32 frames each way; 64 keeps chunked output identical
const STRIP = 20, THUMB_W = 320;
const HIST = 64;  // colour histogram bins
let featS, headS, META, EP, busy = false, result = null;

// yield to the event loop without setTimeout's 4 ms minimum
const tick = () => (self.scheduler && scheduler.yield) ? scheduler.yield() : new Promise(r => { const c = new MessageChannel(); c.port1.onmessage = () => r(); c.port2.postMessage(0); });
const b64 = s => Uint8Array.from(atob(s), c => c.charCodeAt(0));
const fmtTime = t => { const m = Math.floor(t / 60), s = t - m * 60; return m + ":" + (s < 10 ? "0" : "") + s.toFixed(2); };
const css = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();

async function loadModel() {
  const st = $("status");
  try {
    if (!window.LEANSCENE) throw new Error("model.js is missing. Create it with: python demo/export_onnx.py");
    if (!window.ort || !window.MP4Box) throw new Error("Could not load onnxruntime-web / mp4box from cdn.jsdelivr.net (needs an internet connection).");
    if (!window.VideoDecoder) throw new Error("This browser has no WebCodecs video decoder. Use a current Chrome, Edge or Safari.");
    META = LEANSCENE.meta;
    ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;
    const t = performance.now();
    const want = new URLSearchParams(location.search).get("ep") || (navigator.gpu ? "webgpu" : "wasm");
    try { featS = await ort.InferenceSession.create(b64(LEANSCENE.features), { executionProviders: [want] }); EP = want; }
    catch (e) { console.warn("falling back to WebAssembly:", e); featS = await ort.InferenceSession.create(b64(LEANSCENE.features), { executionProviders: ["wasm"] }); EP = "wasm"; }
    headS = await ort.InferenceSession.create(b64(LEANSCENE.head), { executionProviders: [EP] });
    await featS.run({ x: new ort.Tensor("float32", new Float32Array(3 * HW), [1, 3, SIZE, SIZE]) });  // warm-up
    st.textContent = `Model ready: ${META.checkpoint}, ${((LEANSCENE.features.length + LEANSCENE.head.length) * 0.75 / 1e6).toFixed(1)} MB, loaded in ${Math.round(performance.now() - t)} ms. ` +
      (EP === "webgpu" ? "Runs on your GPU (WebGPU)." : `Runs on your CPU (WebAssembly, ${ort.env.wasm.numThreads} thread${ort.env.wasm.numThreads > 1 ? "s" : ""}).`);
    $("drop").classList.remove("busy");
    const src = new URLSearchParams(location.search).get("src");  // ?src=clip.mp4 processes a file served next to the page
    if (src) { const r = await fetch(src); if (!r.ok) throw new Error("Could not fetch " + src); run(new File([await r.blob()], src.split("/").pop())); }
  } catch (e) { st.textContent = e.message || String(e); st.className = "err"; }
}

// --- decoding: every frame of the first video track, in presentation order ---------------
function codecDescription(mp4, track) {
  for (const entry of mp4.getTrackById(track.id).mdia.minf.stbl.stsd.entries) {
    const box = entry.avcC || entry.hvcC || entry.vpcC || entry.av1C;
    if (box) { const ds = new DataStream(undefined, 0, DataStream.BIG_ENDIAN); box.write(ds); return new Uint8Array(ds.buffer, 8); }
  }
}

function decodeVideo(file, { onTrack, onFrame, shouldPause, index }) {  // index: filled as it goes with where each frame's bytes are, for thumbnails
  return new Promise((resolve, reject) => {
    const mp4 = MP4Box.createFile();
    let decoder = null, n = 0, failed = false, lastKey = 0;
    const waiting = [];  // [time, sample] of the samples handed to the decoder whose frame has not come out yet
    const place = () => {  // frames come out in presentation order, so this one is the waiting sample with the smallest time
      let m = 0; for (let i = 1; i < waiting.length; i++) if (waiting[i][0] < waiting[m][0]) m = i;
      if (!waiting.length) return;
      const s = waiting[m][1]; waiting[m] = waiting[waiting.length - 1]; waiting.pop();
      index.sampleOf.push(s); index.frameOf[s] = n;
    };
    const fail = e => { if (failed) return; failed = true; try { if (decoder && decoder.state !== "closed") decoder.close(); } catch (_) {} reject(e instanceof Error ? e : new Error(String(e))); };
    mp4.onError = e => fail(new Error("Could not read this file as MP4/MOV (" + e + ")."));
    mp4.onReady = info => {
      const t = info.videoTracks[0];
      if (!t) return fail(new Error("No video track found in this file."));
      decoder = new VideoDecoder({
        output: f => { try { if (!failed) { if (index) place(); onFrame(f, n++); } } catch (e) { fail(e); } finally { f.close(); } },
        error: e => fail(new Error(`This browser could not decode the video (codec ${t.codec}): ${e.message}`)),
      });
      const config = { codec: t.codec, codedWidth: t.video.width, codedHeight: t.video.height, description: codecDescription(mp4, t) };
      if (index) index.config = config;
      try { decoder.configure(config); }
      catch (e) { return fail(new Error(`Unsupported video codec ${t.codec}: ${e.message}`)); }
      if (onTrack) onTrack(t);
      mp4.setExtractionOptions(t.id, null, { nbSamples: 100 });
      mp4.start();
    };
    mp4.onSamples = (id, _user, samples) => {
      if (failed) return;
      if (index) for (const s of samples) {
        const i = index.off.length; if (s.is_sync) lastKey = i;
        index.off.push(s.offset); index.size.push(s.size); index.keyBefore.push(lastKey); waiting.push([s.cts, i]);
      }
      for (const s of samples)
        decoder.decode(new EncodedVideoChunk({ type: s.is_sync ? "key" : "delta", timestamp: 1e6 * s.cts / s.timescale, duration: 1e6 * s.duration / s.timescale, data: s.data }));
      mp4.releaseUsedSamples(id, samples[samples.length - 1].number);
    };
    (async () => {
      try {
        const CHUNK = 1 << 20;
        for (let off = 0; off < file.size && !failed; off += CHUNK) {
          const buf = await file.slice(off, off + CHUNK).arrayBuffer();
          buf.fileStart = off;
          mp4.appendBuffer(buf);
          while (!failed && ((decoder && decoder.decodeQueueSize > 40) || shouldPause())) await new Promise(r => setTimeout(r, 4));
        }
        if (failed) return;
        mp4.flush();
        if (!decoder) return fail(new Error("This does not look like an MP4/MOV video. WebM, MKV and AVI are not supported by this demo."));
        await decoder.flush();
        decoder.close();
        resolve(n);
      } catch (e) { fail(e); }
    })();
  });
}

// --- model -------------------------------------------------------------------------------
// Turning a batch's pixels into the model's input takes the page about as long as resizing the
// frames does (measured), so a worker does it while the page goes on with the next frames.
// This function is turned into text to start the worker: it can use nothing from outside itself.
function pixelWorker(SIZE, HIST, TILES) {
  const HW = SIZE * SIZE, AW = TILES * SIZE;
  // BIN maps a byte to its colour histogram bin exactly as float32 (v/255)*(4-0.001) truncates
  const BIN = Uint8Array.from({ length: 256 }, (_, v) => Math.floor(Math.fround(Math.fround(v / 255) * Math.fround(3.999))));
  self.onmessage = ev => {  // atlas pixels -> one (n,3,SIZE,SIZE) tensor, planar BGR in [0,1] as the model was trained
    const { run, n, d } = ev.data, t = performance.now(), x = new Float32Array(n * 3 * HW), hist = new Float32Array(n * HIST);
    for (let k = 0; k < n; k++) {
      const ox = (k % TILES) * SIZE, oy = Math.floor(k / TILES) * SIZE, o = k * 3 * HW, ho = k * HIST;
      for (let y = 0, p = 0; y < SIZE; y++) {
        let q = ((oy + y) * AW + ox) * 4;
        for (let c = 0; c < SIZE; c++, p++, q += 4) {
          const r = d[q], g = d[q + 1], b = d[q + 2];
          x[o + p] = b / 255; x[o + HW + p] = g / 255; x[o + 2 * HW + p] = r / 255;
          hist[ho + (BIN[b] * 4 + BIN[g]) * 4 + BIN[r]] += 1 / HW;  // joint 4x4x4 colour histogram (models.color_hist)
        }
      }
    }
    postMessage({ run, n, x, hist, ms: performance.now() - t }, [x.buffer, hist.buffer]);
  };
}
let pixels = null, runs = 0;
async function detect(file, progress) {
  const D = META.dim;
  const live = $("live").getContext("2d");
  // Frames are drawn (resized) into an 8x8 atlas of 100x100 tiles and read back once per batch.
  // willReadFrequently keeps the atlas in CPU memory: reading pixels back from a GPU canvas was the
  // slowest step of the page (415 vs 1,300 frames/s for decode + resize + readback of 720p, measured).
  const atlasC = document.createElement("canvas"); atlasC.width = atlasC.height = TILES * SIZE;
  const atlas = atlasC.getContext("2d", { willReadFrequently: true });
  atlas.imageSmoothingEnabled = true; atlas.imageSmoothingQuality = "low";  // bilinear, closest to cv2.resize
  let feats = new Float32Array(D * 4096), nFeat = 0, total = 0, track = null, fill = 0;
  const times = [], prof = { model: 0, resize: 0, pixels: 0, head: 0 };  // milliseconds in the CNN, in resize + pixel readback, in the worker that builds the input, in the temporal head
  const queue = []; let pumping = null;
  const pump = () => pumping || (pumping = (async () => {
    while (queue.length) {
      const { x, n, hist } = queue.shift();
      const tm = performance.now();
      const out = await featS.run({ x: new ort.Tensor("float32", x, [n, 3, SIZE, SIZE]) });
      prof.model += performance.now() - tm;
      if ((nFeat + n) * D > feats.length) { const g = new Float32Array(feats.length * 2); g.set(feats); feats = g; }
      if (out.y.dims[1] !== D - HIST) throw new Error("model.js does not match this page. Re-run demo/export_onnx.py and reload without cache.");
      const y = out.y.data, E = D - HIST;  // model output: 128 CNN features, then the layout descriptor
      for (let k = 0; k < n; k++) {      // feature row = CNN features, colour histogram, layout descriptor
        const o = (nFeat + k) * D;
        feats.set(y.subarray(k * E, k * E + 128), o);
        feats.set(hist.subarray(k * HIST, (k + 1) * HIST), o + 128);
        feats.set(y.subarray(k * E + 128, (k + 1) * E), o + 128 + HIST);
      }
      nFeat += n;
      await head(false);
      progress(nFeat, total);
      await tick();  // let decoded frames and the page breathe
    }
    pumping = null;
  })());
  if (!pixels) pixels = new Worker(URL.createObjectURL(new Blob([`(${pixelWorker})(${SIZE},${HIST},${TILES})`], { type: "text/javascript" })));
  const run = ++runs; let away = 0, workerError = null;  // away: batches the worker has not sent back yet
  pixels.onmessage = ev => {
    const m = ev.data; if (m.run !== run) return;
    away--; prof.pixels += m.ms; queue.push(m); pump();
  };
  pixels.onerror = ev => { workerError = new Error("The page's pixel worker stopped: " + (ev.message || "unknown error")); };
  const push = () => {  // the atlas's pixels go to the worker, which sends back the model's input
    if (!fill) return;
    const tr = performance.now(), n = fill, d = atlas.getImageData(0, 0, TILES * SIZE, Math.ceil(n / TILES) * SIZE).data;
    away++; pixels.postMessage({ run, n, d }, [d.buffer]);
    prof.resize += performance.now() - tr;
    fill = 0;
  };

  const index = { config: null, off: [], size: [], keyBefore: [], sampleOf: [], frameOf: [] };

  // Shots are handed on while the video is still being read: `stream.shots` grows as the head
  // confirms each shot's end, a "leanscene:shots" event says when it grew, and `done` when the
  // last one is in. clip.js uses this to pick up each shot's picture without a second decode.
  const stream = window.LEANSCENE_STREAM = { shots: [], done: false, failed: false, thumbs: null };
  const shotsGrew = () => document.dispatchEvent(new CustomEvent("leanscene:shots"));
  // About once per second of video, a small copy of the frame is drawn into a ring of tiles on
  // one canvas. It stays on the graphics card: nothing is read back here. When a shot ends, the
  // tile nearest its middle, if it is still in the ring, is handed on with the shot as a bitmap.
  // Measured on 20 minutes of 1080p (28,906 frames): this adds about 0.3 s to 17.5 s of
  // detection. Holding every 8th frame added 1.5 s, and holding ImageBitmaps of the frames 2.5 s.
  const RING_COLS = 8, slotOf = new Map(), frameIn = [];  // frame -> its tile, and tile -> its frame
  let every = 0, ringX = null, ringW = 0, ringH = 0, ringSize = 0, ringN = 0, holdOK = true;
  const hold = (f, i) => {
    try {
      if (!ringX) {
        ringW = THUMB_W; ringH = Math.round(THUMB_W * f.displayHeight / f.displayWidth);
        const rows = Math.max(1, Math.min(16, Math.floor(4096 / ringH))), c = document.createElement("canvas");
        c.width = RING_COLS * ringW; c.height = rows * ringH; ringSize = RING_COLS * rows; ringX = c.getContext("2d", { alpha: false });
      }
      const slot = ringN++ % ringSize;
      if (frameIn[slot] !== undefined) slotOf.delete(frameIn[slot]);
      ringX.drawImage(f, (slot % RING_COLS) * ringW, Math.floor(slot / RING_COLS) * ringH, ringW, ringH);
      frameIn[slot] = i; slotOf.set(i, slot);
    } catch (_) { holdOK = false; }
  };
  const heldNear = (start, end, mid) => {  // the held frame inside the shot that is nearest its middle, or -1
    if (!ringX) return -1;
    const near = Math.round(mid / every) * every;
    for (const f of [near, near < mid ? near + every : near - every]) if (f >= start && f <= end && slotOf.has(f)) return f;
    return -1;
  };
  let shotStart = 0, scan = 0;  // first frame of the shot still open; first frame the rule has not settled
  const addShot = (start, end) => {
    const mid = (start + end) >> 1, f = heldNear(start, end, mid), s = { start, end, mid, rep: mid, held: null, heldFrame: f };
    if (f >= 0) try {
      const slot = slotOf.get(f);
      s.held = createImageBitmap(ringX.canvas, (slot % RING_COLS) * ringW, Math.floor(slot / RING_COLS) * ringH, ringW, ringH);
      s.held.catch(() => {});
    } catch (_) { s.held = null; }
    stream.shots.push(s);
  };
  const emit = final => {  // the rule over the frames not settled yet; a run is settled once no later frame can extend it
    const base = scan, n = headDone - base, before = stream.shots.length;
    for (const t of transitions(probs.subarray(base * 3, headDone * 3), n)) {
      if (!final && t.end + META.close + 2 > n) break;
      if (base + t.before >= shotStart) addShot(shotStart, base + t.before);
      shotStart = base + t.after; scan = base + t.end + 1;
    }
    if (final) { if (shotStart <= headDone - 1) addShot(shotStart, headDone - 1); stream.done = true; }
    if (final || stream.shots.length > before) shotsGrew();
  };
  // The temporal head, a chunk of frames at a time as their features arrive (same output as one pass).
  let probs = new Float32Array(3 * 4096), headDone = 0;
  async function head(final) {
    while (headDone < nFeat && (final || nFeat - headDone >= HEAD_CHUNK + HEAD_MARGIN)) {
      const th = performance.now(), a = headDone, lo = Math.max(0, a - HEAD_MARGIN), hi = Math.min(nFeat, a + HEAD_CHUNK + HEAD_MARGIN), keep = Math.min(HEAD_CHUNK, nFeat - a);
      // slice (a copy): the worker takes ownership of the buffer it is sent
      const out = await headS.run({ x: new ort.Tensor("float32", feats.slice(lo * D, hi * D), [1, hi - lo, D]) });
      if ((a + keep) * 3 > probs.length) { const g = new Float32Array(Math.max(probs.length * 2, (a + keep) * 3)); g.set(probs); probs = g; }
      probs.set(out.y.data.subarray((a - lo) * 3, (a - lo + keep) * 3), a * 3);
      headDone += keep; prof.head += performance.now() - th;
      emit(final && headDone >= nFeat);
    }
  }

  try {
    await decodeVideo(file, {
      index,
      onTrack: t => {
        track = t; total = t.nb_samples; stream.thumbs = thumbnailer(file, index);
        every = Math.max(8, Math.round(t.nb_samples / (t.duration / t.timescale)) || 24);  // frames in a second of this video
      },
      shouldPause: () => queue.length + away > 2,
      onFrame: (f, i) => {
        const tr = performance.now();
        times.push(f.timestamp / 1e6);
        if (holdOK && i % every === 0 && window.clipHoldFrames && clipHoldFrames()) hold(f, i);
        atlas.drawImage(f, (fill % TILES) * SIZE, Math.floor(fill / TILES) * SIZE, SIZE, SIZE);
        if (fill === 0) live.drawImage(f, 0, 0, SIZE, SIZE);  // small preview of where we are
        prof.resize += performance.now() - tr;
        if (++fill === BATCH) push();
      },
    });
    push();
    while (away || pumping) { if (workerError) throw workerError; if (pumping) await pumping; else await new Promise(r => setTimeout(r, 1)); }
    const n = nFeat;
    if (!n) throw new Error("No frames could be decoded from this video.");
    await head(true);
    return { n, times, probs: probs.slice(0, n * 3), track, prof, thumbs: stream.thumbs };
  } catch (e) {
    stream.failed = true; if (stream.thumbs) stream.thumbs.close(); shotsGrew();
    throw e;
  } finally {
    if (ringX) ringX.canvas.width = ringX.canvas.height = 0;  // gives the ring's memory back
  }
}

// the decision rule (leanscene.label_frames): returns runs of transition frames
function transitions(probs, n) {
  const lab = new Uint8Array(n);
  for (let i = 0; i < n; i++) lab[i] = probs[i * 3 + 1] >= META.cut ? 1 : probs[i * 3 + 2] >= META.fade ? 2 : 0;
  const fades = []; for (let i = 0; i < n; i++) if (lab[i] === 2) fades.push(i);
  const closed = lab.slice();
  for (let k = 1; k < fades.length; k++) { const a = fades[k - 1], b = fades[k]; if (b - a > 1 && b - a <= META.close + 1) closed.fill(2, a, b); }
  const out = [];
  for (let i = 0; i < n; i++) {
    if (!closed[i]) continue;
    let e = i, gradual = false, peak = 0;
    while (e + 1 < n && closed[e + 1]) e++;
    for (let j = i; j <= e; j++) { if (closed[j] === 2) gradual = true; peak = Math.max(peak, probs[j * 3 + 1], probs[j * 3 + 2]); }
    // a cut is labelled on the first frame of the new shot; a gradual run covers the blended frames
    out.push({ start: i, end: e, type: gradual ? "gradual" : "cut", peak, before: Math.max(0, i - 1), after: gradual ? Math.min(n - 1, e + 1) : e });
    i = e;
  }
  return out;
}

// second decode pass: exact thumbnails of the frames we want to show
// --- thumbnails, decoded on demand ---------------------------------------------------------
// Nothing is decoded twice up front. When a picture scrolls into view, the frames from the
// keyframe before it up to it are read from the file and decoded, which takes a fraction of a
// second. `index` is what the first pass records about every frame's bytes (see decodeVideo);
// it is still growing while the video is read, and any frame that has come out can be asked for.
const BLANK = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";  // transparent pixel: no broken-image icon while a picture loads
function thumbnailer(file, index) {
  const order = index.sampleOf, frameOf = index.frameOf, keyBefore = index.keyBefore;  // frame (display order) -> sample (decode order), and back; sample -> its keyframe
  const cache = new Map(), pending = new Map();  // frame -> promise of an image URL; keyframe sample -> Map(frame -> resolve)
  const c = document.createElement("canvas"), ctx = c.getContext("2d");
  let decoder = null, current = null, working = false, closed = false;
  const open = () => {
    decoder = new VideoDecoder({
      output: f => {
        try {
          const done = current && current.get(f.timestamp);  // chunks are stamped with their frame number
          if (done) {
            if (!c.width || c.dataset.sized !== "1") { c.width = THUMB_W; c.height = Math.round(THUMB_W * f.displayHeight / f.displayWidth); c.dataset.sized = "1"; }
            ctx.drawImage(f, 0, 0, c.width, c.height);
            current.delete(f.timestamp); done(c.toDataURL("image/jpeg", 0.8));
          }
        } finally { f.close(); }
      },
      error: e => { console.warn("thumbnail decoder:", e); decoder = null; },
    });
    decoder.configure(index.config);
  };
  async function work() {
    if (working) return;
    working = true;
    while (pending.size && !closed) {
      const k = [...pending.keys()].pop(), group = pending.get(k);  // newest request first: what is on screen now
      pending.delete(k); current = group;
      try {
        if (!decoder || decoder.state !== "configured") open();
        let last = k, lo = Infinity, hi = 0;
        for (const f of group.keys()) last = Math.max(last, order[f]);
        for (let s = k; s <= last; s++) { lo = Math.min(lo, index.off[s]); hi = Math.max(hi, index.off[s] + index.size[s]); }
        const buf = new Uint8Array(await file.slice(lo, hi).arrayBuffer());
        for (let s = k; s <= last && decoder; s++)
          decoder.decode(new EncodedVideoChunk({ type: s === k ? "key" : "delta", timestamp: frameOf[s] ?? 1e12 + s /* its frame has not come out of the first pass yet: never asked for */, data: buf.subarray(index.off[s] - lo, index.off[s] - lo + index.size[s]) }));
        if (decoder) await decoder.flush();
      } catch (e) { console.warn("thumbnail:", e); decoder = null; }
      for (const done of group.values()) done("");  // frames the decoder did not produce stay blank
      current = null;
    }
    working = false;
  }
  const get = frame => {
    if (!cache.has(frame)) cache.set(frame, new Promise(done => {
      const k = keyBefore[order[frame]];
      let group = pending.get(k);
      if (group) pending.delete(k); else group = new Map();
      group.set(frame, done); pending.set(k, group);  // re-inserted last, so it is served first
      work();
    }));
    return cache.get(frame);
  };
  const seen = new IntersectionObserver(entries => {
    for (const e of entries) if (e.isIntersecting) {
      seen.unobserve(e.target);
      get(+e.target.dataset.frame).then(url => { if (closed) return; e.target.classList.remove("loading"); if (url) e.target.src = url; });
    }
  }, { rootMargin: "300px" });
  return {
    get,
    lazy(img, frame) { img.dataset.frame = frame; img.src = BLANK; img.classList.add("loading"); seen.observe(img); return img; },  // load when it nears the screen
    close() { closed = true; seen.disconnect(); pending.clear(); try { if (decoder && decoder.state !== "closed") decoder.close(); } catch (_) {} },
  };
}

// --- page --------------------------------------------------------------------------------
async function run(file) {
  if (busy || !featS) return;
  busy = true; if (result) result.thumbs.close(); result = null;
  $("error").hidden = true; $("results").hidden = true; $("progress").hidden = false; $("drop").classList.add("busy");
  $("pbar").value = 0; $("ptext").textContent = "Reading " + file.name + "…";
  try {
    const t0 = performance.now();
    const r = await detect(file, (done, total) => {
      const dt = (performance.now() - t0) / 1000;
      $("pbar").value = total ? done / total : 0;
      $("ptext").textContent = `Detecting: ${done.toLocaleString()} / ${total.toLocaleString()} frames · ${Math.round(done / dt)} frames/s`;
    });
    const seconds = (performance.now() - t0) / 1000;
    const trans = transitions(r.probs, r.n);
    const stripIdx = Array.from({ length: Math.min(STRIP, r.n) }, (_, k) => Math.min(r.n - 1, Math.floor((k + 0.5) * r.n / Math.min(STRIP, r.n))));
    const thumbs = r.thumbs;  // pictures are decoded when they scroll into view
    const fps = r.n > 1 ? (r.n - 1) / (r.times[r.n - 1] - r.times[0]) : 0;
    result = { file: file.name, frames: r.n, fps, seconds, model: META.checkpoint, prof: r.prof, rule: { cut: META.cut, fade: META.fade, close: META.close },
      transitions: trans.map(t => ({ ...t, time: r.times[t.after] - r.times[0] })), probs: r.probs, times: r.times, thumbs, stripIdx };
    window.LEANSCENE_RESULT = result;
    show(file);
  } catch (e) {
    console.error(e);
    $("error").textContent = e.message || String(e); $("error").hidden = false;
  } finally {
    busy = false; $("progress").hidden = true; $("drop").classList.remove("busy");
  }
}

// Player time of frame i. The player's clock does not always start at the first video frame:
// when the file has no edit list and its video starts after its audio (common with B-frames),
// the first frame sits a couple of frames in. show() measures that as result.base.
const base = () => result.base ?? result.times[0];
const timeOf = i => result.times[i] - base();
function seek(t, play) { const v = $("player"); v.currentTime = Math.max(0, t); if (play) v.play().catch(() => {}); }

function show(file) {
  const R = result, v = $("player");
  if (v.src) URL.revokeObjectURL(v.src);
  v.src = URL.createObjectURL(file);
  if (v.requestVideoFrameCallback) v.requestVideoFrameCallback((now, m) => {  // the first frame shown tells us where the player's clock puts frame 0
    const b = R.times[0] - m.mediaTime;
    if (result === R && v.currentTime < 0.01 && Math.abs(b) < 10) R.base = b;
  });
  const cuts = R.transitions.filter(t => t.type === "cut").length, grads = R.transitions.length - cuts;
  const dur = R.frames / (R.fps || 1);
  const stat = (b, label) => `<div><b>${b}</b>${label}</div>`;
  $("summary").innerHTML = stat(R.transitions.length + 1, "shots") + stat(cuts, "cuts") + stat(grads, "fades / gradual") +
    stat(R.frames.toLocaleString(), `frames at ${R.fps.toFixed(2)} fps`) + stat(Math.round(R.frames / R.seconds).toLocaleString(), "frames/s, decoding included") +
    stat((dur / R.seconds).toFixed(1) + "×", "faster than real time");
  $("strip").replaceChildren(...R.stripIdx.map(i => { const im = new Image(); im.alt = "frame " + i; return R.thumbs.lazy(im, i); }));
  $("cardsTitle").textContent = R.transitions.length ? `${R.transitions.length} transitions` : "No transitions found";
  activeCard = -1;
  showPage(0);
  $("results").hidden = false;
  drawOverview();
  setView(0, R.frames);
  document.dispatchEvent(new CustomEvent("leanscene:result"));  // clip.js listens for this
}

// --- timeline: an overview of the whole video, and a strip below it that zooms and pans ----
let view = { a: 0, b: 1 };  // the frames the strip shows, as fractional frame numbers [a, b)
let dragging = false, ovDown = false, lastTouch = 0, drawQueued = false;
const TOP = 14, RULER = 16;
const span = () => view.b - view.a;
const tlW = () => $("timeline").clientWidth || 1;
const minSpan = () => Math.min(result.frames, Math.max(10, tlW() / 10));  // closest zoom: 10 px per frame
const timeAt = f => timeOf(Math.max(0, Math.min(result.frames - 1, Math.floor(f))));
function frameAtTime(t) {  // fractional frame shown at player time t
  const T = result.times, t0 = base(); let lo = 0, hi = T.length - 1;
  while (lo < hi) { const m = (lo + hi + 1) >> 1; if (T[m] - t0 <= t) lo = m; else hi = m - 1; }
  const next = lo + 1 < T.length ? T[lo + 1] - T[lo] : 0;
  return lo + (next > 0 ? Math.max(0, Math.min(1, (t - (T[lo] - t0)) / next)) : 0);
}
function setView(a, b) {
  if (!result) return;
  const n = result.frames, s = Math.max(minSpan(), Math.min(n, b - a));
  a = Math.max(0, Math.min(n - s, a));
  view = { a, b: a + s };
  const box = $("ovbox"); box.style.left = 100 * a / n + "%"; box.style.width = 100 * s / n + "%";
  $("zoominfo").textContent = s >= n ? "" : `${clock(timeAt(a))} – ${clock(timeAt(a + s))}`;
  $("zfit").disabled = $("zout").disabled = s >= n; $("zin").disabled = s <= minSpan();
  if (!drawQueued) { drawQueued = true; requestAnimationFrame(() => { drawQueued = false; drawTimeline(); }); }
}
function zoomAt(frame, factor) {  // keeps `frame` under the same pixel
  const s = span(), ns = Math.max(minSpan(), Math.min(result.frames, s * factor)), a = frame - (frame - view.a) * ns / s;
  setView(a, a + ns);
}
function clock(t, decimals = 0) {
  const h = Math.floor(t / 3600), m = Math.floor(t % 3600 / 60), s = t - h * 3600 - m * 60;
  const ss = (s < 10 ? "0" : "") + s.toFixed(decimals);
  return h ? `${h}:${m < 10 ? "0" : ""}${m}:${ss}` : `${m}:${ss}`;
}

function plot(g, W, y0, h, a, b) {  // cut and fade probability of frames a..b across W pixels
  const R = result, px = W / (b - a), i0 = Math.max(0, Math.floor(a)), i1 = Math.min(R.frames, Math.ceil(b));
  const layers = [[2, css("--fade"), 0.75], [1, css("--cut"), 1]];
  if (px >= 1) {  // zoomed in: one bar per frame
    const gap = px >= 4 ? 1 : 0;
    for (const [k, color, alpha] of layers) {
      g.fillStyle = color; g.globalAlpha = alpha;
      for (let i = i0; i < i1; i++) { const p = R.probs[i * 3 + k]; if (p > 0.02) g.fillRect((i - a) * px, y0 + h * (1 - p), px - gap, h * p); }
    }
  } else {  // zoomed out: each pixel column shows the highest probability of the frames under it
    const col = new Float32Array(W * 3);
    for (let i = i0; i < i1; i++) {
      const x = Math.max(0, Math.min(W - 1, Math.floor((i - a) * px))) * 3;
      if (R.probs[i * 3 + 1] > col[x + 1]) col[x + 1] = R.probs[i * 3 + 1];
      if (R.probs[i * 3 + 2] > col[x + 2]) col[x + 2] = R.probs[i * 3 + 2];
    }
    for (const [k, color, alpha] of layers) {
      g.fillStyle = color; g.globalAlpha = alpha;
      for (let x = 0; x < W; x++) { const p = col[x * 3 + k]; if (p > 0.02) g.fillRect(x, y0 + h * (1 - p), 1, h * p); }
    }
  }
  g.globalAlpha = 1;
}

function canvas2d(id) {
  const c = $(id), dpr = window.devicePixelRatio || 1, W = c.clientWidth, H = c.clientHeight;
  c.width = W * dpr; c.height = H * dpr;
  const g = c.getContext("2d"); g.scale(dpr, dpr); g.clearRect(0, 0, W, H);
  return { g, W, H };
}

function drawOverview() {
  if (!result) return;
  const { g, W, H } = canvas2d("overview");
  plot(g, W, 2, H - 4, 0, result.frames);
}

function drawTimeline() {
  if (!result) return;
  const R = result, { g, W, H } = canvas2d("timeline"), { a, b } = view, px = W / (b - a);
  const h = H - TOP - RULER - 2, cutC = css("--cut"), fadeC = css("--fade");
  g.strokeStyle = css("--line"); g.setLineDash([3, 4]); g.lineWidth = 1;
  for (const th of new Set([R.rule.cut, R.rule.fade])) { const y = TOP + h * (1 - th) + 0.5; g.beginPath(); g.moveTo(0, y); g.lineTo(W, y); g.stroke(); }
  g.setLineDash([]);
  plot(g, W, TOP, h, a, b);
  for (const t of R.transitions) {  // markers above the plot
    if (t.end + 1 < a || t.start > b) continue;
    const x = ((t.start + t.end + 1) / 2 - a) * px;
    g.fillStyle = t.type === "cut" ? cutC : fadeC;
    if (t.type !== "cut" && px >= 1) g.fillRect((t.start - a) * px, 4, (t.end + 1 - t.start) * px, 3);  // how long a gradual transition lasts
    g.beginPath(); g.moveTo(x - 4, 2); g.lineTo(x + 4, 2); g.lineTo(x, 10); g.fill();
  }
  // time ruler: the smallest round step that keeps labels about 90 px apart
  const t0 = timeAt(a), t1 = timeAt(b), secs = Math.max(1e-6, t1 - t0);
  const step = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600].find(s => s / secs * W >= 90) || 3600;
  g.fillStyle = css("--mute"); g.font = "10px -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
  for (let k = Math.ceil(t0 / step); k * step <= t1; k++) {
    const x = (frameAtTime(k * step) - a) * px;
    g.fillRect(x, H - RULER, 1, 4); g.fillText(clock(k * step, step < 1 ? 1 : 0), x + 3, H - 4);
  }
}

const tl = $("tlwrap"), ov = $("ovwrap");
const xFrac = ev => { const r = tl.getBoundingClientRect(); return (ev.clientX - r.left) / r.width; };
function frameAtX(ev) { return Math.max(0, Math.min(result.frames - 1, Math.floor(view.a + xFrac(ev) * span()))); }
tl.addEventListener("wheel", ev => {  // pinch or Ctrl/Cmd + scroll zooms; sideways scroll (or Shift + scroll) pans
  if (!result) return;
  const unit = ev.deltaMode === 1 ? 16 : 1;
  if (ev.ctrlKey || ev.metaKey) zoomAt(view.a + xFrac(ev) * span(), Math.exp(ev.deltaY * unit * 0.01));
  else if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) { const d = ev.deltaX * unit * span() / tlW(); setView(view.a + d, view.b + d); }
  else return;  // plain vertical scroll still scrolls the page
  ev.preventDefault(); lastTouch = performance.now();
}, { passive: false });
let pinch = null;  // Safari reports trackpad pinches as gesture events
tl.addEventListener("gesturestart", ev => { if (!result) return; ev.preventDefault(); pinch = { s: span(), f: view.a + xFrac(ev) * span() }; });
tl.addEventListener("gesturechange", ev => { if (!pinch) return; ev.preventDefault(); zoomAt(pinch.f, pinch.s / ev.scale / span()); lastTouch = performance.now(); });
tl.addEventListener("gestureend", () => { pinch = null; });
let down = null;  // a press that has not moved is a click (jump there); one that moves drags the view
tl.addEventListener("pointerdown", ev => { if (result && !ev.button) down = { x: ev.clientX, a: view.a, id: ev.pointerId }; });
tl.addEventListener("pointermove", ev => {
  if (!result) return;
  if (down) {
    const dx = ev.clientX - down.x;
    if (!dragging && Math.abs(dx) > 4 && span() < result.frames) { dragging = true; try { tl.setPointerCapture(down.id); } catch (_) {} tl.classList.add("drag"); $("tip").hidden = true; }
    if (dragging) { const a = down.a - dx * span() / tlW(); setView(a, a + span()); lastTouch = performance.now(); return; }
  }
  const i = frameAtX(ev), tip = $("tip"), r = tl.getBoundingClientRect();
  tip.hidden = false; tip.style.left = Math.max(60, Math.min(r.width - 60, ev.clientX - r.left)) + "px";
  tip.textContent = `${fmtTime(timeOf(i))} · frame ${i}`;
});
const release = ev => {
  if (!down) return;
  if (!dragging && ev.type === "pointerup") seek(timeOf(frameAtX(ev)), false);
  down = null; dragging = false; tl.classList.remove("drag");
};
tl.addEventListener("pointerup", release);
tl.addEventListener("pointercancel", release);
tl.addEventListener("pointerleave", () => { $("tip").hidden = true; });
// overview: press or drag to move the zoomed view there
const ovGo = ev => { const r = ov.getBoundingClientRect(), f = (ev.clientX - r.left) / r.width * result.frames, s = span(); setView(f - s / 2, f + s / 2); lastTouch = performance.now(); };
ov.addEventListener("pointerdown", ev => { if (!result || ev.button) return; ovDown = true; ovGo(ev); try { ov.setPointerCapture(ev.pointerId); } catch (_) {} });
ov.addEventListener("pointermove", ev => { if (ovDown) ovGo(ev); });
ov.addEventListener("pointerup", () => { ovDown = false; });
ov.addEventListener("pointercancel", () => { ovDown = false; });
const zoomButton = factor => () => {
  if (!result) return;
  const f = frameAtTime($("player").currentTime);
  zoomAt(f >= view.a && f <= view.b ? f : (view.a + view.b) / 2, factor);  // around the playhead when it is in view
};
$("zin").onclick = zoomButton(0.5);
$("zout").onclick = zoomButton(2);
$("zfit").onclick = () => { if (result) setView(0, result.frames); };
// previous / next transition: the buttons, and the left and right arrow keys
// The cards are paged: a film has many hundreds of transitions.
const PER_PAGE = 48;  // a multiple of 12, so rows are full at 4, 3, 2 and 1 columns
let activeCard = -1, cardPage = 0;
function card(t, k) {
  const R = result, b = document.createElement("button"); b.className = "card";
  const where = t.type === "cut" ? `frame ${t.after}` : `frames ${t.start}–${t.end}`;
  b.innerHTML = `<div class="pair"><img alt="frame ${t.before}"><img alt="frame ${t.after}"></div>` +
    `<div class="cap"><span><span class="tag ${t.type}">${t.type}</span> · ${fmtTime(t.time)}</span><span class="mute">${where} · p ${t.peak.toFixed(2)}</span></div>`;
  const [before, after] = b.querySelectorAll("img"); R.thumbs.lazy(before, t.before); R.thumbs.lazy(after, t.after);
  b.onclick = () => { markCard(k); seek(timeOf(t.start) + 0.001, true); /* +1 ms: an exact frame time can round to the frame before */ $("player").scrollIntoView({ behavior: "smooth", block: "nearest" }); };
  return b;
}
function showPage(p, scroll) {
  const T = result.transitions, n = T.length, pages = Math.max(1, Math.ceil(n / PER_PAGE));
  cardPage = Math.max(0, Math.min(pages - 1, p));
  const a = cardPage * PER_PAGE, b = Math.min(n, a + PER_PAGE);
  $("cards").replaceChildren(...T.slice(a, b).map((t, i) => card(t, a + i)));
  if (activeCard >= a && activeCard < b) $("cards").children[activeCard - a].classList.add("on");
  for (const el of document.querySelectorAll(".pager")) {
    el.hidden = pages < 2;
    el.querySelector(".pinfo").textContent = `${(a + 1).toLocaleString()}–${b.toLocaleString()} of ${n.toLocaleString()}`;
    el.querySelector(".pprev").disabled = cardPage === 0; el.querySelector(".pnext").disabled = cardPage === pages - 1;
  }
  if (scroll) $("cardsTitle").scrollIntoView({ behavior: "smooth", block: "start" });
}
function markCard(k) {  // highlights transition k, turning to its page when it is on another one
  const page = Math.floor(k / PER_PAGE);
  if (k >= 0 && page !== cardPage) { activeCard = k; showPage(page); return; }
  const cards = $("cards").children, a = cardPage * PER_PAGE;
  if (cards[activeCard - a]) cards[activeCard - a].classList.remove("on");
  activeCard = k; if (cards[k - a]) cards[k - a].classList.add("on");
}
document.addEventListener("click", ev => {
  const btn = ev.target.closest && ev.target.closest(".pager button");
  if (btn && result) showPage(cardPage + (btn.classList.contains("pnext") ? 1 : -1), !!btn.closest(".bottom"));
});
function step(dir) {
  if (!result) return;
  const T = result.transitions, v = $("player"), f = Math.floor(frameAtTime(v.currentTime) + 1e-3);
  const back = v.paused ? 0 : (result.fps || 30) * 0.5;  // while playing, "previous" within half a second of a transition goes one further back
  let k = -1;
  if (dir > 0) k = T.findIndex(t => t.start > f);
  else for (let i = T.length - 1; i >= 0; i--) if (T[i].start < f - back) { k = i; break; }
  if (k < 0) {  // nothing earlier: "previous" goes to the first frame of the video
    if (dir < 0 && f > 0) { seek(timeOf(0), false); markCard(-1); }
    return;
  }
  seek(timeOf(T[k].start) + 0.001, false);  // keeps playing if it was playing
  markCard(k);
}
$("tprev").onclick = () => step(-1);
$("tnext").onclick = () => step(1);
// Capture phase, and stopped there: a focused player handles the arrow keys itself (it seeks by
// a few seconds) before a bubbling listener runs, which made one press skip several transitions.
window.addEventListener("keydown", ev => {
  if (!result || ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || (ev.key !== "ArrowLeft" && ev.key !== "ArrowRight")) return;
  if (ev.target.closest && ev.target.closest("input, textarea, select")) return;
  ev.preventDefault(); ev.stopImmediatePropagation();
  step(ev.key === "ArrowRight" ? 1 : -1);
}, true);
(function playhead() {
  if (result) {
    const v = $("player"), n = result.frames, f = frameAtTime(v.currentTime), s = span();
    // while playing, turn the page when the playhead leaves the view (unless the view was just moved by hand)
    if (!v.paused && s < n && !dragging && !ovDown && performance.now() - lastTouch > 1500 && (f < view.a || f > view.a + s * 0.95)) setView(f - s * 0.05, f + s * 0.95);
    const p = (f - view.a) / span(), ph = $("playhead");
    ph.hidden = p < 0 || p > 1; ph.style.left = 100 * p + "%";
    $("ovhead").style.left = 100 * f / n + "%";
  }
  requestAnimationFrame(playhead);
})();
$("player").addEventListener("seeked", () => {  // a jump from a card or the player's own bar: bring it into view
  if (!result) return;
  const f = frameAtTime($("player").currentTime), s = span();
  if (f < view.a || f > view.b) setView(f - s / 2, f + s / 2);
});
window.addEventListener("resize", () => { drawOverview(); setView(view.a, view.b); });
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => { drawOverview(); drawTimeline(); });

$("download").onclick = () => {
  const R = result, body = { file: R.file, model: R.model, rule: R.rule, frames: R.frames, fps: R.fps,
    transitions: R.transitions.map(t => ({ type: t.type, start_frame: t.start, end_frame: t.end, time_s: +t.time.toFixed(3), peak_probability: +t.peak.toFixed(4) })) };
  const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([JSON.stringify(body, null, 1)], { type: "application/json" }));
  a.download = R.file.replace(/\.[^.]+$/, "") + ".transitions.json"; a.click(); URL.revokeObjectURL(a.href);
};

const drop = $("drop");
$("file").addEventListener("change", ev => { if (ev.target.files[0]) run(ev.target.files[0]); ev.target.value = ""; });
window.addEventListener("dragover", ev => { ev.preventDefault(); drop.classList.add("over"); });
window.addEventListener("dragleave", ev => { if (!ev.relatedTarget) drop.classList.remove("over"); });
window.addEventListener("drop", ev => { ev.preventDefault(); drop.classList.remove("over"); const f = ev.dataTransfer.files[0]; if (f) run(f); });