import { Stage } from './stage.js'; import { createFilm, buildDance, MOVE_SOURCES, BEAT_PASS, COLD, STYLES, CARDS } from './film.js'; import { Choreo, Warp, HEAD_LIMITS } from './robot.js'; import { sfxEnvelope } from './sfx.js'; import { FILM_SFX, CARD_SFX } from './variants.js'; import { clamp } from './kit.js'; import { Timeline, ShotsLane, TakesLane, WaveLane, SfxLane, RangeLane, timecode, clock as mmss } from './timeline.js'; import { QUERY } from './query.js'; import { MUSIC_OFFSET, PUBLIC_URL, LOCAL, FRAMES_URL, STILLS_URL, BEAT_GRID_URL, BAR_ONE, STORE, CUTS_DIR, FILM_CUT, NO_CUT, PLATFORMS, LENGTHS, PRESS_KIT, SOURCE, coverOf, videoOf, shareFiles, thumbOf, chaptersOf, sfxEvents, sfxSound } from './player/config.js'; import { createTransport } from './player/transport.js'; import { createCutAudio } from './player/cut-audio.js'; import { validateCutDoc, makeCut, closesOnCard, filmAt, programAt, mapSpans, mapCues, mapTimes, mapRegions, cutSfx, segmentAt, joinText, FPS } from './player/cut.js'; import { createJoinMenu } from './player/join-menu.js'; import { createUrlState, readResume } from './player/url-state.js'; import { bindKeys, typing, onControl } from './player/keymap.js'; import { createOsd } from './player/osd.js'; import { createFullscreen } from './player/fullscreen.js'; import { createRobotLink } from './player/robot-link.js'; import { createSplitter } from './player/splitter.js'; import { createSkim } from './player/skim.js'; import { createShare, copy } from './player/share.js'; import { createTakesAdapter, PREROLL } from './player/takes-adapter.js'; import { createReview } from './player/review.js'; import { createSpeed, rateLabel } from './player/speed.js'; import { createStrip, barBeat, STRIP_H } from './player/strip.js'; import { createFitControls } from './player/fit-controls.js'; import { blockHistoryNav } from './player/no-history-nav.js'; import { blockZoom } from './player/no-zoom.js'; import { createRange } from './player/range.js'; import { createSwitcher } from './player/switcher.js'; import { createViews } from './player/views.js'; import { createScenesGrid } from './player/scenes-grid.js'; import { createFirstPlay } from './player/first-play.js'; import { FORMAT, FORMATS, OW, OH } from './formats.js'; import { createReframe, safeOverlay, loadLayouts } from './reframe.js'; const RENDER = new URLSearchParams(location.search).has('render'); const root = document.getElementById('stage'); if (RENDER) document.body.classList.add('render'); const loader = document.querySelector('.ld-overlay'); if (RENDER) loader.remove(); else blockZoom(); // Player state carried over a reload of the same URL (uiState below): the // exact time, speed, loop, mode, the editor view's zoom / scroll, the takes // lane's scroll; after a take switch (reloadWith) also playing, a still. const RESUME = RENDER ? null : readResume(); // Until the film is ready: that time's frame from the frames sprite, where // the stage will be, so the switch doesn't flash black. // The frame is the one of the take being loaded, when it has a strip. if (RESUME?.still) { const { still, rect } = RESUME; const ph = document.createElement('div'); ph.className = 'ld-still'; Object.assign(ph.style, { left: `${rect.left}px`, top: `${rect.top}px`, width: `${rect.width}px`, height: `${rect.height}px`, ...still }); loader.classList.add('ld-resume'); loader.prepend(ph); } let ldDone = 0; let ldTotal = 0; const task = () => { ldTotal++; return () => { const k = ++ldDone / ldTotal; loader.setAttribute('aria-valuenow', String(Math.round(k * 100))); loader.querySelector('.ld-arc').style.strokeDasharray = `${0.12 + 0.76 * k} 1`; }; }; const step = p => { const done = RENDER ? () => {} : task(); return p.then(v => (done(), v)); }; const musicReady = RENDER ? null : step(canPlayThrough(document.getElementById('music'))); makeGrain(document.getElementById('grain')); const st = new Stage(document.getElementById('gl')); const fonts = ['400 100px Anton', '500 100px "DM Sans Variable"', '700 100px "DM Sans Variable"', 'italic 500 100px "DM Sans Variable"', '400 20px "JetBrains Mono"', '700 20px "JetBrains Mono"']; const json = url => fetch(url).then(r => r.json()); const peaksReady = RENDER ? null : step(json('data/waveform.json').catch(() => null)); // ?cut=: the player plays that cut (data/cuts/, src/player/cut.js), // FILM_CUT without one, the continuous edit with ?cut=none. Renders take // cuts from scripts/render.mjs --cut, not the page: there the cut only says // whether the page builds its cut-only scenes, and none plays without it. const CUT_PARAM = QUERY.get('cut'); const CUT_NAME = CUT_PARAM === NO_CUT ? null : (CUT_PARAM ?? (RENDER ? null : FILM_CUT)); const cutDoc = CUT_NAME && /^[\w-]+$/.test(CUT_NAME) ? json(`${CUTS_DIR}${CUT_NAME}.json`).catch(() => null) : null; // A beat (s), for the cuts' audio transitions. const beatPeriod = RENDER ? null : json(BEAT_GRID_URL).then(g => g.period, () => null); const warmedUp = RENDER ? () => {} : task(); // ?warp=0 (BEAT_PASS off): the dance on its old global shift, no beat warp, // the box's recorded move. const [audio, sourceBeats, tracks, beat] = await Promise.all([ step(json('data/audio.json')), step(json('data/moves-beats.json')), Promise.all(Object.entries(MOVE_SOURCES).map(async ([k, url]) => [k, new Choreo(await step(json(url)))])).then(Object.fromEntries), BEAT_PASS ? step(Promise.all([json('data/choreo-warp.json'), json('data/beat-grid.json')])).then(([w, g]) => ({ warp: new Warp(w), grid: g.beats })) : null, step(st.load('assets/reachy_mini_viz.glb', 'data/choreo.json')), step(Promise.all(fonts.map(f => document.fonts.load(f, 'REACHY mini 0123'))).then(() => document.fonts.ready)), step(STYLES.then(loadLayouts)), ]); st.choreo = buildDance(st.choreo, tracks, audio.beats, { em: sourceBeats.eminem, mm: sourceBeats.manyme }, beat); st.tracks = tracks; const params = new URLSearchParams(QUERY); // Player: the heaviest setups (scenes declaring lazy) wait for their scene, // so the first frame comes sooner. Rendering builds everything up front. const CUT_DOC = await cutDoc; const film = createFilm({ stage: st, root, audio, lazy: !RENDER, card: closesOnCard(CUT_DOC, CARDS) }); // Chapter titles / timecode overlay: off unless asked for (?hud). film.setHud(params.has('hud')); // ?format=v: the frame laid out for 9:16 after each scene's frame (src/formats.js). const reframe = createReframe({ st, root }); const sceneAt = t => film.scenes.find(s => t - COLD >= s.a && t - COLD < s.b) ?? film.scenes.at(-1); // Scenes drawn once (a lazy one is set up by then). const drawn = new Set(); const draw = t => { film.frame(t); reframe.frame(sceneAt(t), t - COLD); st.render(); drawn.add(sceneAt(t).id); }; // The player's clock, links and times are program time: the film's, or the // cut's (0 on its first frame). filmOf / programOf map between them. const PERIOD = await beatPeriod; const CUT = RENDER ? null : loadCut(CUT_DOC); const START = 0; const PROGRAM_END = CUT ? CUT.duration : film.duration; // The sound effects that can play: the film's, and a cut's cut-only scenes'. const SFX = CUT?.segments.some(s => s.card) ? [...FILM_SFX, ...CARD_SFX] : FILM_SFX; const filmOf = p => (CUT ? filmAt(CUT, p) : p); const programOf = (t, near) => (CUT ? programAt(CUT, t, near) : t); function loadCut(doc) { if (!doc) return CUT_NAME && console.warn(`?cut=${CUT_NAME}: no such cut in ${CUTS_DIR}`), null; const errs = validateCutDoc(doc, CUT_NAME); if (errs.length) return console.warn(`${CUTS_DIR}${CUT_NAME}.json: ${errs.join('; ')}`), null; try { return makeCut(doc, { duration: film.duration, cold: COLD, scenes: film.scenes, cards: CARDS, period: PERIOD }); } catch (e) { return console.warn(`${CUTS_DIR}${CUT_NAME}.json: ${e.message}`), null; } } // Where scene s first plays (a cut: its first segment showing it; null: // the cut skips it). Its held edges (cut.js HOLD) and a sliver under a // frame long show nothing of it. const sceneStart = s => { if (!CUT) return s.a + COLD; const g = CUT.segments.find(g => Math.min(g.pic[1], s.b + COLD) - Math.max(g.pic[0], s.a + COLD) >= 1 / FPS); return g ? (s.a + COLD <= g.pic[0] ? g.at : g.at + (s.a + COLD - g.in)) : null; }; // Start: ?t= / #t= (seconds), else #scene= (a scene id), else the top. const timeIn = (t, scene) => { const s = t === null && film.scenes.find(x => x.id === scene); return clamp(s ? sceneStart(s) ?? START : START + Number(t ?? 0), START, PROGRAM_END); }; // A reload of the same URL: the exact time it left (the hash has 0.1 s). const T0 = typeof RESUME?.t === 'number' ? clamp(RESUME.t, START, PROGRAM_END) : timeIn(params.get('t'), params.get('scene')); // Compile every shader variant so the first frame of each look doesn't // stall. Rendering: all up front. Player: the first frame first, the other // looks one per frame while paused (warmUp), all at once before playing. const warmQueue = film.scenes.map(s => Math.max(0, s.a + COLD + 0.5)); const warmUp = (all = false) => { for (let n = all ? warmQueue.length : 1; n > 0 && warmQueue.length; n--) draw(warmQueue.shift()); }; if (RENDER) { warmUp(true); draw(0); } else { // Yield a frame first so the loader can paint its progress. await new Promise(requestAnimationFrame); draw(filmOf(T0)); } warmedUp(); // frame/stage are exposed for scripts/probe-motion.mjs (no rendering needed). window.__film = { duration: film.duration, seek: draw, frame: film.frame, stage: st, scenes: film.scenes, cards: CARDS, cold: COLD, headLimits: HEAD_LIMITS }; window.__ready = true; if (!RENDER) { await musicReady; await startPlayer(await peaksReady); loader.classList.add('ld-out'); setTimeout(() => loader.remove(), 350); } // Resolves once the music can play through. iOS Safari ignores preload and // never fires canplaythrough before a user gesture, hence the timeout. function canPlayThrough(el) { return new Promise(resolve => { if (el.readyState >= 3) return resolve(); el.addEventListener('canplaythrough', resolve, { once: true }); el.addEventListener('error', resolve, { once: true }); setTimeout(resolve, 10_000); }); } // The player: wiring of src/player/* and the timeline around the film. function startPlayer(peaks) { const music = document.getElementById('music'); const btn = document.getElementById('play'); const controls = document.getElementById('controls'); const topbar = document.getElementById('topbar'); const time = document.getElementById('time'); const chapterEl = document.getElementById('chapter'); const tlBtn = document.getElementById('tlmode'); const robotLink = createRobotLink({ before: document.getElementById('fs') }); const fitBar = createFitControls({ bar: controls, timeline: () => document.getElementById(controls.classList.contains('tl-open') ? 'chapters' : 'timeline') }); const D = PROGRAM_END; // The picture at program time t (shown: that pair, for probes). let shown = { t: T0, film: filmOf(T0) }; const show = t => draw((shown = { t, film: filmOf(t) }).film); // A cut's chapters: the scenes' pieces it keeps, back to back (join: a // piece starting on a cut), its end card past the film's end included. const chapters = CUT ? mapSpans(CUT, chaptersOf(film.scenes, 0, Infinity), 0.01, { pic: true }) : chaptersOf(film.scenes, START, D); const chapterAt = t => chapters.find(c => t >= c.start && t < c.end) ?? chapters.at(-1); const transport = createTransport({ start: START, end: D, t: T0 }); const clock = transport.clock; window.__player = { clock, get cut() { return CUT && { name: CUT.name, duration: CUT.duration, segments: CUT.segments, joins: CUT.joins.map(({ at, out, in: inn, k, fx }) => ({ at, out, in: inn, k, fx })) }; }, filmOf, programOf, shown: () => shown, }; // Switching takes reloads the page (flags are read at module load): the // film time goes in the URL, the rest of the player state in RESUME. // key: the take switched to (its frames strip, null: the defaults). // preroll: film time to replay from, playing. const takes = createTakesAdapter({ params, scenes: film.scenes, offset: MUSIC_OFFSET, start: START, end: D, sceneAt: sceneStart, storageKey: STORE.takesFolded, reload: (...a) => reloadWith(...a) }); // Links keep the cut and the format (#cut=story&format=v, before the takes: // #t=12&cut=story&format=v&mc=v1). const cutEntries = q => [...(q.get('cut') ? [['cut', q.get('cut')]] : []), ...(FORMATS[q.get('format')]?.auto ? [['format', q.get('format')]] : [])]; // The page's views (src/player/views.js): the player, the scenes grid or // the Share tab (#view=scenes&t=12...), shown by showView below. const VIEWS = ['scenes', 'share']; const views = createViews({ ids: VIEWS, href: () => url.pageUrl(url.hashOf(params, { t: clock() })), onChange: v => showView(v) }); const url = createUrlState({ start: START, publicUrl: PUBLIC_URL, keys: ['view', ...VIEWS, 'platform', 'length', 'cut', 'format', ...takes.keys, 'in', 'out'], route: () => (views.current === 'share' ? shareView.route() : views.route()), entries: q => [...cutEntries(q), ...takes.entries(q), ...range.entries()] }); // What a reload restores besides the link: the UI (the in / out range, // takes, cut and format are in the hash; mode, splitter and fold in // localStorage too). const uiState = () => ({ speed: speed.speed, loop: range.loop, mode: tl.mode, view: tl.view(), blocks: takesLane.scrolls(), grid: scenesGrid.state(), share: shareView.state() }); url.kept(() => ({ ...uiState(), t: clock() })); const reloadWith = (q, focus, key = null, preroll = null) => { const t = preroll ?? clock(); const r = root.getBoundingClientRect(); const view = tl.view(); // Scrolled so the pre-roll and the take's start show. if (view && preroll !== null && !(preroll >= view.left && preroll + PREROLL + 1 <= view.right)) { view.left = Math.max(START, preroll - 1); view.sl = undefined; } url.reload(q, t, { ...uiState(), playing: preroll !== null || transport.playing, view, focus, rect: { left: r.left, top: r.top, width: r.width, height: r.height }, still: tl.frames.css(t, key) }); }; // The hash edited by hand (or on the Space's page): other takes or // another cut reload (on that link's time and a fitted view), a time or // scene seeks. url.onHashChange(q => { if (views.current === 'share') shareView.follow(); if (takes.differs(q) || (q.get('cut') ?? '') !== (params.get('cut') ?? '') || (FORMATS[q.get('format')] ?? FORMATS['16:9']) !== FORMAT) return url.reloadAsIs({ ...uiState(), view: null, blocks: {} }); range.fromQuery(q); // The playhead's own time (the hash has 0.1 s: back from the grid) stays put. const here = q.has('t') && Number(q.get('t')) === Math.round((clock() - START) * 10) / 10; if ((q.has('t') || q.has('scene')) && !here) seek(timeIn(q.get('t'), q.get('scene'))); }); // Resumed after a take switch without a gesture on this page: if the // browser blocks the sound, stay paused rather than play mute. // The Music lane's waveform (and a cut's sound): the song from // MUSIC_OFFSET, and the bits of it the credits replay as sound effects (at // their level and fades). const song = music.getAttribute('src'); const isSong = s => s.type === 'file' && s.src === song; const songRegions = [{ at: MUSIC_OFFSET }, ...SFX.filter(isSong).map(s => ({ at: s.t, from: s.from, len: s.until, gain: dt => (s.gain ?? 1) * sfxEnvelope(s, dt) }))]; const onPlayError = e => autoResume && e.name === 'NotAllowedError' && blocked(); // The whole film plays as a one-segment cut: the song on the Web Audio // clock, so it starts on its frame (the music element's play() stalls // ~0.2 s, a held first frame of YO). const heard = CUT ?? makeCut({ name: 'film', label: 'Full film', segments: [{ in: 0, out: 'end' }] }, { duration: film.duration, cold: COLD, scenes: film.scenes, period: PERIOD }); const sound = createCutAudio({ cut: heard, regions: songRegions, sfx: cutSfx(heard, SFX, isSong), src: song, transport, storageKey: STORE.volume, onPlayError }); const volIn = document.getElementById('volume'); sound.bindVolume(document.getElementById('mute'), volIn); window.__player.music = () => sound.element; window.__player.sfxBuffered = () => sound.sfxBuffered; if (CUT) window.__player.offline = sound.offline; // Shown over the film when the browser blocks the sound of a resumed // playback (a take switch reloads without a gesture on the new page). const hint = document.createElement('button'); hint.className = 'play-hint mono'; hint.type = 'button'; hint.innerHTML = ' Playthe browser blocked autoplay'; hint.onclick = () => speed.play(); const blocked = () => { pause(); const r = root.getBoundingClientRect(); Object.assign(hint.style, { left: `${r.left + r.width / 2}px`, top: `${r.top + r.height / 2}px` }); document.body.append(hint); hint.focus({ preventScroll: true }); }; // Over the film until it plays on this page (src/player/first-play.js). const firstPlay = createFirstPlay({ root, play: () => speed.play() }); window.__player.firstPlay = () => firstPlay.shown; const play = () => { hint.remove(); firstPlay.played(); // Looping: from the range's start (its end, backwards) if outside it. if (range.loop) { range.at(clock()); const s = range.span; const t = clock(); if (t < s.in || t >= s.out) seek(transport.rate < 0 ? s.out : s.in); } transport.play(t => { if (warmQueue.length) { warmUp(true); show(t); } }); sound.onPlay(); btn.textContent = '❚❚'; }; const pause = () => { transport.pause(); sound.onPause(); btn.textContent = '▶'; speed.render(); }; let sought = false; const seek = t => { sought = true; return sound.onSeek(transport.seek(t)); }; // Editor view: the picture is what ships, the readouts (scene, take, music // time, bar.beat, frame, a rate but 1x, skimming) go in the strip under it. let editing = false; const strip = createStrip({ host: document.getElementById('viewport'), fields: [ ...(CUT ? [{ id: 'cut', label: 'Cut', ch: 10, drop: 1, title: `${CUT.label} (data/cuts/${CUT.name}.json): segment / segments` }] : []), { id: 'scene', label: 'Scene', ch: 18, drop: 1, title: 'Scene at the playhead (or where you skim)' }, { id: 'take', label: 'Take', title: 'Take this scene plays (flag=option)' }, { id: 'state', ch: 7, right: true }, ...(CUT ? [{ id: 'src', label: 'Film', ch: 6, drop: 2, right: true, title: 'Source film time in seconds (what the cut shows)' }] : []), { id: 'music', label: 'Music', ch: 6, drop: 2, right: true, title: 'Music time in seconds (film time - COLD), as the scenes are timed in src/scenes/index.js' }, { id: 'beat', label: 'Bar', ch: 5, drop: 3, right: true, title: 'Bar.beat on data/beat-grid.json' }, { id: 'frame', label: 'Frame', ch: 4, right: true, title: 'Frame number at 30 fps' }, ], }); let rateText = ''; const speed = createSpeed({ transport, play, pause, control: document.getElementById('speed'), root, initial: RESUME?.speed, badge: () => !editing, onChange: r => (rateText = r === 1 ? '' : rateLabel(r, transport.playing)), }); const toggle = () => (transport.playing ? pause() : speed.play()); btn.onclick = toggle; blockHistoryNav(); // Every shortcut (the help overlay lists `keys` / `label`); `say`: what // the on-screen display shows after it, for what the picture doesn't. const nav = e => !e.metaKey && !e.ctrlKey; const playSay = () => (transport.playing ? 'Play' : 'Pause'); // Space plays / pauses wherever the focus is (a timeline row, a button): // its keyup must not click that control too. let spaced = false; addEventListener('keyup', e => e.code === 'Space' && spaced && ((spaced = false), e.preventDefault()), true); bindKeys( [ { key: ['g', 'G'], keys: ['G'], label: 'Scenes grid', when: e => nav(e) && !e.altKey && !typing(e), run: e => !e.repeat && toggleView('scenes') }, { key: ['s', 'S'], keys: ['S'], label: 'Share: the social cuts and the press kit', when: e => nav(e) && !e.altKey && !typing(e), run: e => !e.repeat && toggleView('share') }, { key: 'Escape', keys: ['esc'], label: 'Back to the player', when: () => views.current, run: () => views.close() }, { code: 'Space', keys: ['space'], label: 'Play / pause', when: e => !typing(e), prevent: true, run: e => { spaced = true; if (!e.repeat) toggle(); }, say: e => !e.repeat && playSay(), }, // On a button or a link, Enter is that control's. { code: ['Enter', 'NumpadEnter'], keys: ['enter'], label: 'Play / pause', when: e => nav(e) && !e.altKey && !typing(e) && !onControl(e), prevent: true, run: e => !e.repeat && toggle(), say: e => !e.repeat && playSay() }, { code: 'ArrowRight', keys: ['→'], label: 'Forward 1 s (shift: 5 s)', run: e => seek(clock() + (e.shiftKey ? 5 : 1)) }, { code: 'ArrowLeft', keys: ['←'], label: 'Back 1 s (shift: 5 s)', run: e => seek(clock() - (e.shiftKey ? 5 : 1)) }, { code: ['ArrowUp', 'ArrowDown'], keys: ['↑', '↓'], label: 'Volume', prevent: true, run: e => sound.setVolume(Math.round((sound.level + (e.code === 'ArrowUp' ? 0.1 : -0.1)) * 10) / 10), say: () => `Volume ${Math.round(sound.level * 100)}%`, sayKeys: e => [e.code === 'ArrowUp' ? '↑' : '↓'], }, { code: 'KeyM', keys: ['M'], label: 'Add a review marker at the playhead', when: e => nav(e) && !e.shiftKey && !e.altKey && !typing(e), prevent: true, run: () => review.add() }, { code: 'KeyM', keys: ['shift', 'M'], label: 'Next open marker', when: e => nav(e) && e.shiftKey && !e.altKey, run: () => review.jump(1) }, { code: 'KeyM', keys: ['alt', 'M'], label: 'Previous open marker', when: e => nav(e) && e.altKey && !e.shiftKey, prevent: true, run: () => review.jump(-1) }, { key: 'u', keys: ['U'], label: 'Mute', run: () => sound.toggleMute(), say: () => (sound.muted ? 'Muted' : 'Sound on') }, { code: 'KeyI', keys: ['I'], label: 'In point at the playhead', when: e => nav(e) && !e.altKey && !typing(e), run: () => range.setIn(clock()), say: () => 'In point' }, { code: 'KeyO', keys: ['O'], label: 'Out point at the playhead', when: e => nav(e) && !e.altKey && !typing(e), run: () => range.setOut(clock()), say: () => 'Out point' }, { code: 'KeyX', keys: ['X'], label: 'In / out on the scene under the playhead', when: e => nav(e) && !e.altKey && !e.shiftKey && !typing(e), run: () => markScene(chapterAt(clock())), say: () => 'In / out on the scene' }, { code: 'KeyX', keys: ['alt', 'X'], label: 'Clear in / out', when: e => nav(e) && e.altKey && !typing(e), prevent: true, run: () => range.clear(), say: () => 'In / out cleared' }, { code: 'KeyL', keys: ['cmd / ctrl', 'L'], label: 'Loop the range (or the scene)', when: e => (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey, prevent: true, run: () => range.toggleLoop(), say: () => (range.loop ? 'Loop on' : 'Loop off'), sayKeys: e => [e.metaKey ? '⌘' : 'ctrl', 'L'], }, { code: 'KeyK', keys: ['K'], label: 'Pause (held: J / L at 0.25x)', when: e => nav(e) && !e.altKey && !typing(e), run: () => speed.hold(), say: e => !e.repeat && 'Pause' }, { code: 'KeyL', keys: ['L'], label: 'Play forward, again 2x, 4x (shift: 0.25x)', when: e => nav(e) && !e.altKey && !typing(e), run: e => !e.repeat && speed.shuttle(1, e.shiftKey) }, { code: 'KeyJ', keys: ['J'], label: 'Play backward, again 2x, 4x (shift: 0.25x)', when: e => nav(e) && !e.altKey && !typing(e), run: e => !e.repeat && speed.shuttle(-1, e.shiftKey) }, { key: '.', keys: ['.'], label: 'Next frame', run: () => seek(clock() + 1 / 30) }, { key: ',', keys: [','], label: 'Previous frame', run: () => seek(clock() - 1 / 30) }, { key: 'n', keys: ['N'], label: 'Next scene', run: () => seek((chapters.find(c => c.start > clock() + 0.01) ?? chapters.at(-1)).start) }, { key: 'p', keys: ['P'], label: 'Previous scene', run: () => seek((chapters.filter(c => c.start < clock() - 0.5).at(-1) ?? chapters[0]).start) }, { key: 't', keys: ['T'], label: 'Editor view', when: () => !narrow, run: e => { keycap(tlBtn, true); if (!e.repeat) switchMode(); }, }, { key: ['=', '+'], keys: ['+'], label: 'Zoom in', run: () => tl.zoomBy(1.5) }, { key: '-', keys: ['-'], label: 'Zoom out', run: () => tl.zoomBy(1 / 1.5) }, { key: '0', keys: ['0'], label: 'Whole film', run: () => tl.fit() }, { key: 'f', keys: ['F'], label: 'Fullscreen', when: nav, run: () => fullscreen.toggle() }, { key: 'Escape', keys: ['esc'], label: 'Stop skimming', when: () => skim.current, run: () => { tl.stopSkim(); skim.set(null); }, }, ], // The other views have their own keys (src/player/scenes-grid.js; the // Share tab's fields, scrolling): only G, S and Esc reach the table. { ignore: e => (views.current && !['g', 'G', 's', 'S', 'Escape'].includes(e.key)) || (e.target === volIn && e.code.startsWith('Arrow')), onSay: createOsd({ root }) }, ); // Fullscreen: the film letterboxed with the viewer bar over it (fading out // with the cursor). The editor view gives way to the viewer bar until it exits. let fsFromEditor = false; const fullscreen = createFullscreen({ button: document.getElementById('fs'), onChange: on => { if (on) { fsFromEditor = editing; if (editing) tl.setMode('light'); } else if (fsFromEditor) tl.setMode('expanded'); wake(); fit(); }, }); root.addEventListener('dblclick', fullscreen.toggle); // Editor view: the timeline is as tall as its lanes and the film, a program // monitor, fills the rest; the splitter sizes the takes lane, the monitor // keeping at least MONITOR_MIN of the window. Only the display size // changes: the stage still renders 1920x1080, scaled. const MONITOR_MIN = 0.25; const splitter = createSplitter({ el: document.getElementById('splitter'), storageKey: STORE.split, legacyKeys: STORE.splitLegacy }); // Fullscreen: the stage renders at the size it's shown (devicePixelRatio // included) up to FS_RATIO x 1920x1080, for sharpness at a bearable cost. const FS_RATIO = 1.5; const fit = () => { fitBar.run(); const vw = innerWidth; const over = document.body.classList.contains('fs') && !editing; const vh = innerHeight - (over ? 0 : controls.offsetHeight); // The top bar's band above the picture (fullscreen viewer: over it). const top = over ? 0 : topbar.offsetHeight; // Editor view: the strip glued under the picture, both centred. const sh = editing ? STRIP_H : 0; const k = Math.min(vw / OW, (vh - top - sh) / OH); const x = (vw - OW * k) / 2; const y = top + (vh - top - sh - OH * k) / 2; root.style.transform = `translate(${x}px, ${y}px) scale(${k})`; if (editing) strip.place(x, y + OH * k, OW * k); const ratio = over ? clamp(k * devicePixelRatio, 1, FS_RATIO) : 1; if (ratio !== st.renderer.getPixelRatio()) { st.renderer.setPixelRatio(ratio); st.renderer.setSize(OW, OH, false); } if (editing) splitter.show(vh / innerHeight); speed.render(); }; const refit = () => (editing ? takesLane.size() : fit()); addEventListener('resize', refit); // The editor view is a desktop tool; phones keep the viewer bar. const narrow = matchMedia('(max-width: 640px)').matches; let savedMode = 'light'; try { if (!narrow) savedMode = RESUME?.mode ?? localStorage.getItem(STORE.mode) ?? savedMode; } catch {} // The end card has no thumb (the film's frames never reach it). const clips = chapters.map(c => { const groups = takes.groupsOf(c.id); const card = !!CUT?.segments[c.seg]?.card; return { id: c.id, start: c.start, end: c.end, label: c.name, tag: c.tag, thumb: card ? null : thumbOf(c.id), takes: groups, alt: takes.isAlt(groups), badge: takes.badge(groups), join: c.join, seg: c.seg }; }); // The strip's take: flag=option of the scene's takes. const takeText = new Map(clips.map(c => [c.id, (c.takes ?? []).map(g => `${g.id}=${g.value ?? 'default'}`).join(' ')])); let resumeAfterDrag = false; const onScrub = (phase, t) => { if (phase === 'start') { resumeAfterDrag = transport.playing; if (transport.playing) pause(); seek(t); } else if (phase === 'move') seek(t); else if (resumeAfterDrag) play(); }; const timelineEl = document.getElementById('timeline'); const review = createReview({ clock, pause, seek, start: START, chapter: chapterAt, takes: takes.current, link: m => url.publicLink(url.hashOf(new URLSearchParams(m.takes), { t: m.t, digits: 3 })), host: timelineEl, storageKey: STORE.markers, toProgram: programOf, toFilm: filmOf, }); const loopBtn = document.getElementById('loop'); const range = createRange({ start: START, end: D, fps: 30, lane: new RangeLane(), q: params, loop: RESUME?.loop === true, chapterAt, onSpan: s => { const what = s.name ?? 'range'; loopBtn.title = `Loop: ${what} (cmd / ctrl + L)`; loopBtn.ariaLabel = `Loop: ${what}`; }, onChange: () => { loopBtn.setAttribute('aria-pressed', String(range.loop)); loopBtn.classList.toggle('ranged', Boolean(range.range)); url.sync(params, clock(), true); }, }); loopBtn.setAttribute('aria-pressed', String(range.loop)); loopBtn.classList.toggle('ranged', Boolean(range.range)); loopBtn.onclick = () => range.toggleLoop(); const markScene = c => range.mark(c.start, c.end); const loopScene = c => { markScene(c); if (!range.loop) range.setLoop(true); const t = clock(); if (t < c.start || t >= c.end) seek(c.start); }; const takesLane = new TakesLane(takes.lane({ height: splitter.px, scroll: RESUME?.blocks, cap: lane => lane + innerHeight * (1 - MONITOR_MIN) - controls.offsetHeight - topbar.offsetHeight, onResize: () => fit() })); splitter.attach(takesLane); // The beat grid the dance is warped to (data/beat-grid.json), bars from // BAR_ONE. A cut: each segment's beats, its waveform, sounds, as it plays. const filmBeats = (beat?.grid ?? audio.beats).map(b => b + MUSIC_OFFSET); const songBeats = CUT ? mapTimes(CUT, filmBeats) : filmBeats; const downbeats = CUT ? mapTimes(CUT, filmBeats.filter((_, i) => (i - BAR_ONE) % 4 === 0)) : songBeats.filter((_, i) => (i - BAR_ONE) % 4 === 0); const events = sfxEvents(SFX, song); // Each with its sound for the waveform; a cut's from its kept film second // (src), to its segment's end at most. const sfxLane = (CUT ? [...mapSpans(CUT, events.filter(e => e.label === 'song')), ...mapCues(CUT, events.filter(e => e.label !== 'song'))].sort((a, b) => a.start - b.start) : events).map(e => ({ ...e, sound: CUT ? sfxSound(e.cue, e.src - e.cue.t, CUT.segments[e.seg].end) : sfxSound(e.cue) })); // The waveform's peaks (film time, data/waveform.json) as the cut plays them. const ps = peaks?.perSecond; const lanePeaks = CUT && peaks ? { ...peaks, values: Array.from({ length: Math.ceil(D * ps) }, (_, i) => peaks.values[Math.floor(filmOf((i + 0.5) / ps) * ps)] ?? 0) } : peaks; // The version switcher (top bar): the whole film or a cut of // data/cuts/index.json. Switching reloads on the same film moment. const cutList = () => json(`${CUTS_DIR}index.json`) .then(names => Promise.all(names.map(n => json(`${CUTS_DIR}${n}.json`).then(doc => (validateCutDoc(doc, n).length ? null : makeCut(doc, { duration: film.duration, cold: COLD, scenes: film.scenes, cards: CARDS, period: PERIOD }))).catch(() => null)))) .then(list => list.filter(Boolean), () => []); const switchCut = next => { const q = new URLSearchParams(params); if (!next) q.set('cut', NO_CUT); else if (next.name === FILM_CUT) q.delete('cut'); else q.set('cut', next.name); const f = filmOf(clock()); const t = next ? programAt(next, f) ?? 0 : f; // In / out are the old cut's times, so is the view (the new one fits). range.clear(); url.reload(q, t, { ...uiState(), playing: transport.playing, view: null }); }; // The format switcher, next to the version's (src/formats.js): reloads on // the same moment; a vertical frame also has the platforms' safe zones. const safe = FORMAT.platforms ? safeOverlay(root) : null; const showSafe = on => { root.classList.toggle('show-safe', on); try { localStorage.setItem(STORE.safeZones, on ? '1' : ''); } catch {} }; try { if (safe && localStorage.getItem(STORE.safeZones)) showSafe(true); } catch {} const switchFormat = f => { const q = new URLSearchParams(params); if (f.auto) q.set('format', f.id); else q.delete('format'); url.reload(q, clock(), { ...uiState(), playing: transport.playing }); }; // A cut by its name (its label's the tooltip), FILM_CUT as "Full film"; // the continuous edit listed only while it plays (?cut=none). const versionItem = x => (x ? { id: x.name, label: x.name === FILM_CUT ? 'Full film' : x.name[0].toUpperCase() + x.name.slice(1), hint: mmss(x.duration), title: x.label } : { id: '', label: 'Continuous edit', hint: mmss(film.duration), title: 'Every scene on the song as it runs (?cut=none)' }); const versions = list => ({ label: 'Version', items: [...(CUT ? [] : [versionItem(null)]), ...list.map(versionItem)], current: CUT?.name ?? '', pick: id => switchCut(list.find(x => x.name === id) ?? null) }); const switcher = createSwitcher( document.getElementById('switch'), [ versions(CUT ? [CUT] : []), { label: 'Format', items: Object.values(FORMATS).map(f => ({ id: f.id, label: f.label, ratio: f.h > f.w ? 'tall' : 'wide', title: `${f.label} ${f.h > f.w ? 'vertical' : 'wide'}, ${f.w}x${f.h}` })), current: FORMAT.id, pick: id => switchFormat(FORMATS[id]) }, ], safe ? [{ label: 'Safe zones', title: 'Show where TikTok, Reels and Shorts draw their UI over the video', on: root.classList.contains('show-safe'), onChange: showSafe }] : [], ); const cuts = cutList(); const versionsIn = cuts.then(list => list.length && switcher.set(0, versions(list))); // A cut's joins (editor view): a click on one's mark picks its audio // transition (src/player/join-menu.js), heard at once, saved by the dev server. const joinMenu = CUT && createJoinMenu({ getCut: () => CUT, setCut: next => { CUT.joins = next.joins; sound.setCut(next); shotsLane.refreshJoins(); }, audition: (a, b) => { range.mark(a, b); if (!range.loop) range.setLoop(true); seek(Math.max(START, a)); if (!transport.playing) speed.play(); }, stamp: t => timecode(t - START), save: LOCAL && fetch('__cuts/join').then(r => r.ok, () => false), }); const joinOf = c => CUT.joins.find(j => j.k === c.seg); const shotsLane = new ShotsLane({ buttons: [...takes.resetButton(clips.some(c => c.alt))], menu: (c, anchor) => [{ header: `${c.tag ? `${c.tag} ` : ''}${c.label}` }, { label: 'Loop this scene', run: () => loopScene(c) }, { label: 'In / out on this scene', hint: 'X', title: 'X: on the scene under the playhead', run: () => markScene(c) }, ...takes.playingItems(c.id, anchor)], joins: CUT && { text: c => joinText(joinOf(c).fx), title: c => `Join ${c.seg}: ${joinText(joinOf(c).fx)} (click: the audio transition, audition)`, open: (c, el, e) => joinMenu.open(c.seg, el, e), }, }); const tl = new Timeline(timelineEl, { duration: D, start: START, fps: 30, t: clock(), clips, lanes: [shotsLane, new WaveLane({ peaks: lanePeaks, src: song, regions: CUT ? mapRegions(CUT, songRegions) : songRegions }), new SfxLane({ events: sfxLane, onResize: () => refit() }), takesLane, review.lane, range.lane], view: RESUME?.view, beats: songBeats, downbeats, mode: savedMode, onMode: mode => { editing = mode === 'expanded'; controls.classList.toggle('tl-open', editing); tlBtn.setAttribute('aria-pressed', String(editing)); try { localStorage.setItem(STORE.mode, mode); } catch {} strip.show(editing); fit(); }, onSkim: s => skim.set(s), onScrub, }); // The editor view's chapter bar, where the viewer's timeline sits in the row. const chaptersBar = new Timeline(document.getElementById('chapters'), { duration: D, start: START, fps: 30, t: clock(), clips: clips.map(({ takes, ...c }) => c), lanes: [new ShotsLane()], mode: 'light', onScrub }); tl.frames.filmOf = chaptersBar.frames.filmOf = filmOf; // Take actions (make default, archive) and their status (top bar, right): // the local preview server only. takes.enableEdit(takesLane, document.getElementById('devstatus')); // Review markers: the dev server's file (re-read now and then: it can be // edited on disk), else this browser's storage. review.store.load(); if (LOCAL) setInterval(() => review.store.remote && review.store.load(), 10_000); // Skimming (editor view, paused). The lazy scenes show from the frames // sprite until they're set up. const skim = createSkim({ root, frames: tl.frames, paused: () => !transport.playing, needsSetup: t => { const s = sceneAt(filmOf(t)); return !RENDER && !!s.lazy && !drawn.has(s.id); }, setup: t => { film.frame(filmOf(t)); drawn.add(sceneAt(filmOf(t)).id); }, }); // The Share tab (src/player/share.js): the posts and the press kit. const cutOf = new Map(); cuts.then(list => list.forEach(c => cutOf.set(c.name, c))); const shareView = createShare({ host: document.body, bar: document.getElementById('toolbar'), local: LOCAL, publicLink: url.publicLink, platforms: PLATFORMS, lengths: LENGTHS, platformKey: STORE.sharePlatform, // Its link changed (a section gone to, a pick): the address bar, no history entry. onRoute: () => url.sync(params, clock(), true), // The cuts' durations (cutOf) known. ready: cuts, coverOf, videoOf, durationOf: p => cutOf.get(p.cut ?? FILM_CUT)?.duration ?? (p.cut ? null : film.duration), kit: PRESS_KIT, stills: () => scenesGrid.stills(), openScenes: () => openView('scenes'), files: shareFiles, source: SOURCE, // A post's mini player starting: the film is quiet. pauseFilm: () => transport.playing && pause(), }); // Copy link (the top bar, every view): the film at the playhead. const linkBtn = document.getElementById('copylink'); const linkAt = linkBtn.querySelector('small'); const showLinkAt = t => { const at = mmss(t - START); if (linkAt.textContent === at && linkBtn.title) return; linkAt.textContent = at; const what = at === '0:00' ? 'from the top' : `at ${at}`; linkBtn.title = `Copy a link to the film ${what}`; linkBtn.setAttribute('aria-label', linkBtn.title); }; linkBtn.onclick = () => copy(url.publicLink(url.hashOf(params, { t: clock(), lead: false })), 'link'); showLinkAt(clock()); // The film's name and song title, centred on the page: the title goes, // then all of it, before it meets the tabs or the right side. const navRow = topbar.querySelector('.tb-nav'); const filmId = navRow.querySelector('.tb-id'); const [navStart, navEnd] = [navRow.querySelector('.tb-start'), navRow.querySelector('.tb-end')]; const placeId = () => { const mid = navRow.clientWidth / 2; const fits = () => { const half = filmId.offsetWidth / 2 + 24; return navStart.offsetLeft + navStart.offsetWidth <= mid - half && navEnd.offsetLeft >= mid + half; }; filmId.classList.remove('short', 'off'); if (!fits()) filmId.classList.add('short'); if (!fits()) filmId.classList.add('off'); }; const idFit = new ResizeObserver(placeId); for (const e of [navRow, navStart, navEnd]) idFit.observe(e); // The bar's height changes with the view (the player's tools row is taller): the film follows. new ResizeObserver(() => refit()).observe(topbar); // The bar grows / shrinks and the film rescales with it, instead of jumping. const EASE = 'cubic-bezier(0.2, 0.7, 0.2, 1)'; const switchMode = () => { const from = controls.offsetHeight; const calm = matchMedia('(prefers-reduced-motion: reduce)').matches; if (!calm) root.style.transition = `transform 220ms ${EASE}`; tl.toggleMode(); showTime(clock()); const to = controls.offsetHeight; if (calm) return; controls.style.overflow = 'hidden'; controls.animate([{ height: `${from}px` }, { height: `${to}px` }], { duration: 220, easing: EASE }).finished.finally(() => { controls.style.overflow = ''; root.style.transition = ''; // A resize meanwhile measured the bar mid-animation. refit(); }); }; tlBtn.onclick = switchMode; // A button's keycap (T, O) looks pressed while the key or the button is held. const keycap = (b, down) => b.classList.toggle('down', down); const capped = { KeyT: tlBtn }; for (const b of Object.values(capped)) b.addEventListener('pointerdown', () => keycap(b, true)); for (const ev of ['pointerup', 'pointercancel', 'blur']) addEventListener(ev, () => Object.values(capped).forEach(b => keycap(b, false))); addEventListener('keyup', e => capped[e.code] && keycap(capped[e.code], false)); // Film frames sprite, optional. Locally, a newer sheet from // `npm run dev -- --frames` is picked up without a reload. No sheet: 204 // from the dev server, `null` in a build without one. let framesVersion = 0; const loadFrames = () => fetch(FRAMES_URL, { cache: 'no-store' }) .then(r => (r.status === 200 ? r.json() : null)) .then(meta => { if (meta && meta.version !== framesVersion) { framesVersion = meta.version; tl.frames.load(meta); chaptersBar.frames.load(meta); } }) .catch(() => {}); loadFrames(); if (LOCAL) setInterval(loadFrames, 10_000); // The scenes grid (src/player/scenes-grid.js): every scene of the whole // film in its order, in film time, each format's still, whatever cut or // format plays. The player under it is paused and not drawn. const scenesGrid = createScenesGrid({ host: document.body, bar: document.getElementById('toolbar'), manifest: STILLS_URL, items: chaptersOf(film.scenes, 0, film.duration).map(c => ({ id: c.id, tag: c.tag, name: c.name, film: [c.start, c.end] })), formats: Object.values(FORMATS).map(f => ({ id: f.id, label: f.label, vertical: f.h > f.w })), playing: FORMAT.id, duration: film.duration, storageKey: STORE.gridFormats, titlesKey: STORE.gridTitles, frames: () => tl.frames.meta, current: () => chapterAt(clock()).id, stamp: mmss, onPick: (it, f) => pickScene(it, f), }); const viewBtns = [...document.querySelectorAll('#views button')]; for (const b of viewBtns) b.onclick = () => (b.dataset.view ? openView(b.dataset.view) : views.close()); // The views over the paused player (not drawn meanwhile). const panes = { scenes: scenesGrid, share: shareView }; // Playing when a view opened: it plays on when back. let resumeAfterView = false; const openView = v => { if (v === views.current) return; if (!views.current) { resumeAfterView = transport.playing; pause(); // The player's entry at this very moment, for Back. url.sync(params, clock(), true); } views.open(v); }; const toggleView = v => (views.current === v ? views.close() : openView(v)); function showView(v, { scroll } = {}) { firstPlay.show(!v); for (const b of viewBtns) b.setAttribute('aria-pressed', String((b.dataset.view || null) === v)); document.body.classList.toggle('view-open', !!v); document.getElementById('viewport').inert = controls.inert = !!v; const left = Object.entries(panes).find(([id, p]) => id !== v && p.open && p.has(document.activeElement))?.[0]; for (const [id, p] of Object.entries(panes)) if (id !== v) p.hide(); if (v) { if (transport.playing) { resumeAfterView = true; pause(); } hint.remove(); if (skim.current) { tl.stopSkim(); skim.set(null); } document.body.classList.remove('idle'); panes[v].show({ scroll }); return; } if (left) viewBtns.find(b => b.dataset.view === left)?.focus({ preventScroll: true }); showLinkAt(clock()); if (resumeAfterView) speed.play(); resumeAfterView = false; } // A still: its scene from the start in the full film (FILM_CUT; one it // skips, in the continuous edit), in the still's format, playing (a new // history entry: Back returns to the grid). Off it or in another format, // a reload there. const pickScene = (it, f) => { resumeAfterView = false; const format = FORMATS[f] ?? FORMAT; const inFilm = CUT?.name === FILM_CUT ? programAt(CUT, it.film[0]) : null; const whole = CUT && inFilm == null; if (whole || format !== FORMAT) { const q = new URLSearchParams(params); if (whole) q.set('cut', NO_CUT); if (format.auto) q.set('format', format.id); else q.delete('format'); // In / out and the view are the cut's times. if (whole) range.clear(); views.close({ push: true }); return url.reload(q, inFilm ?? it.film[0], { ...uiState(), playing: true, ...(whole ? { view: null } : {}) }); } seek(inFilm ?? it.film[0]); views.close({ push: true }); speed.play(); }; // Viewer bar: fades out (with the cursor) after a moment without the mouse // while playing (fullscreen: even paused, sooner), back on any move, key or // touch. let lastInput = performance.now(); const wake = () => (lastInput = performance.now()); for (const ev of ['pointermove', 'pointerdown', 'keydown', 'wheel']) addEventListener(ev, wake, { passive: true }); const updateIdle = () => { const fs = document.body.classList.contains('fs'); const idle = (transport.playing || fs) && !editing && performance.now() - lastInput > (fs ? 2000 : 2500) && !controls.matches(':hover') && !topbar.matches(':hover'); if (idle !== document.body.classList.contains('idle')) document.body.classList.toggle('idle', idle); }; const showTime = t => { const fmt = editing ? timecode : mmss; const txt = `${fmt(t - START)} / ${fmt(D - START)}`; if (time.textContent !== txt) time.textContent = txt; }; let grid = beat?.grid ?? null; if (!grid) json(BEAT_GRID_URL).then(g => (grid = g.beats), () => {}); // The strip at program time t: the playhead's, or where the pointer skims // (sk, the take row it skims when that isn't the one playing). Music and // bar: the film's (a cut's source). const showStrip = (t, sk) => { const c = chapterAt(t); const other = sk?.take && !sk.take.on; const f = filmOf(t); if (CUT) { strip.set('cut', `${CUT.name} ${segmentAt(CUT, t).k + 1}/${CUT.segments.length}`); strip.set('src', f.toFixed(2)); } strip.set('scene', `${c.tag ? `${c.tag} ` : ''}${c.name}`); strip.set('take', other ? `${sk.take.tag ?? sk.take.key ?? sk.take.name}${sk.stripless ? ' (no strip)' : ''}` : takeText.get(c.id) ?? ''); strip.mark('take', 'other', Boolean(other)); strip.set('state', sk ? 'SKIM' : rateText); const m = f - MUSIC_OFFSET; strip.set('music', (Math.abs(m) < 0.005 ? 0 : m).toFixed(2)); strip.set('beat', barBeat(grid, m, BAR_ONE)); strip.set('frame', String(Math.max(0, Math.floor((t - START) * 30 + 1e-6)))); }; const loop = () => { // A view covers the player (paused): nothing to draw. if (views.current) { url.sync(params, clock()); requestAnimationFrame(loop); return; } if (transport.playing && skim.current) skim.set(null); let t = sound.frame(clock()); // The scene a loop without a range plays: the playhead's, held while it loops. if (sought || !(transport.playing && range.loop)) range.at(t); const jumped = sought; sought = false; if (transport.playing && range.loop) { const s = range.span; const r = transport.rate; const over = r > 0 ? t - s.out : s.in - t; if (over >= 0) { // The frame's overshoot carries over (a seek past the edge doesn't). const from = r > 0 ? s.in : s.out; t = sound.wrap(transport.seek(from + Math.sign(r) * (over < 0.25 ? over : 0)), from); } else if (r > 0) sound.cue(s.in, (s.out - t) / r); } if (transport.playing && t >= D) pause(); // Backwards: stops on the first frame. if (transport.playing && t <= START && transport.rate < 0) { pause(); seek(START); t = START; // Where playing stopped, not a seek: the timeline stays put. sought = false; } if (!transport.playing && warmQueue.length) { warmUp(); if (!warmQueue.length && resumePlaying) { resumePlaying = false; play(); } } const sk = skim.current; show(sk && !sk.sprite ? sk.t : Math.min(t, D)); robotLink.frame(sk ? null : st.lead); tl.update(t, jumped); if (editing) { chaptersBar.update(t); showStrip(sk ? sk.t : Math.min(t, D), sk); } updateIdle(); showTime(t); showLinkAt(t); const name = chapterAt(t).name; if (chapterEl.textContent !== name) { chapterEl.textContent = name; fitBar.run(); } url.sync(params, t); requestAnimationFrame(loop); }; // After a take switch: playback resumes once every look is compiled, and // a take picked from the keyboard gets the focus back. let resumePlaying = Boolean(RESUME?.playing); let autoResume = resumePlaying; if (resumePlaying && !warmQueue.length) { resumePlaying = false; play(); } for (const ev of ['pointerdown', 'keydown']) addEventListener(ev, () => { autoResume = false; if (sound.context?.state === 'suspended') sound.context.resume(); }, { once: true, capture: true }); if (RESUME?.focus != null) takesLane.focus(RESUME.focus); // A link or a reload on a view: up before the loader goes, where it was. if (views.current) showView(views.current, { scroll: RESUME?.[views.current === 'scenes' ? 'grid' : views.current]?.scroll }); requestAnimationFrame(loop); // The loader stays up until the bars are complete (the cuts listed with // their durations, the fonts in), a slow or failing cut at most BARS_WAIT. const BARS_WAIT = 4000; // On Share, its post too (its Download with its size, its fit line, its caption). const ready = Promise.race([Promise.all([versionsIn, document.fonts.ready, views.current === 'share' ? shareView.ready() : null]), new Promise(r => setTimeout(r, BARS_WAIT))]); // The first-play hint fades in once the loader is gone (its 350 ms fade), not on a resumed playback. ready.then(() => setTimeout(() => firstPlay.show(!views.current && !RESUME?.playing && !transport.playing), 350)); return ready; } function makeGrain(elm) { const c = document.createElement('canvas'); c.width = c.height = 256; const g = c.getContext('2d'); const img = g.createImageData(256, 256); let s = 1234567; for (let i = 0; i < img.data.length; i += 4) { s = (s * 1103515245 + 12345) >>> 0; const v = s >>> 24; img.data[i] = img.data[i + 1] = img.data[i + 2] = v; img.data[i + 3] = 255; } g.putImageData(img, 0, 0); elm.style.backgroundImage = `url(${c.toDataURL()})`; }