oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// talk-store.mjs — the whole talk, in memory (spec §6, "Getting
2// ready"; S17). Shared by the presenter window and the slide window.
3//
4// GET /p/{session}/talk (presenting_talk.go) is every slide of the full
5// talk, rendered at press 0, with the pictures it shows (a clip's poster
6// among them, and its video fetched beside them) and, for whoever
7// may drive, its notes. A slide is ready once its families are on (the
8// font gate's prepareSection) and its pictures are decoded, so a press
9// that lands on it needs no network. Until it is ready the window keeps
10// what it shows (has, ready).
11//
12// The talk lives in memory only. A newer version of the deck (refresh)
13// is loaded beside the one in use, quietly, and taken when the window
14// says so (adopt), which it does at its next change of slide.
15//
16// view is the version in moves.mjs's shape, so talkOrder, advance and
17// settleNear answer for the talk as the window holds it: each slide's
18// talk ('full' or in the talk; parked slides never reach a reader) and
19// one box per press, which is all presses() needs to count them.
20
21// How many slides get ready at once.
22const AT_ONCE = 4
23
24/** A slide's presses as boxes presses() counts: n boxes on steps 1 to n. */
25function pressBoxes (n) {
26 const out = []
27 for (let k = 1; k <= n; k++) out.push({ id: 'press' + k, type: 'image', step: k })
28 return out
29}
30
31function version (payload, etag) {
32 const slides = Array.isArray(payload.slides) ? payload.slides : []
33 return {
34 deckSeq: Number(payload.deckSeq) || 0,
35 arrive: payload.arrive || 'appear',
36 etag,
37 slides,
38 byID: new Map(slides.map(s => [s.id, s])),
39 view: { slides: slides.map(s => ({ id: s.id, talk: s.full ? 'full' : '', blocks: pressBoxes(Number(s.presses) || 0) })) },
40 ready: new Set(),
41 failed: new Set(),
42 waiters: new Map(),
43 // The deck's uploaded fonts as the font manifest carries them
44 // (presenting_talk.go): learned before a slide is made ready.
45 uploaded: payload.uploaded || null,
46 // The scenes its slides show (scene_pages.go), as the frame layer
47 // runs them: each bundle's address, name, words and data.
48 scenes: payload.scenes && typeof payload.scenes === 'object' ? payload.scenes : {}
49 }
50}
51
52// The pictures decoded, held so the browser keeps them for the talk.
53const held = []
54// The scene bundles already fetched.
55const fetched = new Set()
56
57// Clips' videos are warmed into the browser's HTTP cache (assets.go
58// answers them private, immutable, for a year), one at a time, each
59// body read and dropped as it streams, never held. Warming stops once
60// 300 MiB have come: what is not warm loads when its slide plays it.
61const WARM_LIMIT = 300 * 1024 * 1024
62const warmed = new Set()
63let warmedBytes = 0
64let warming = Promise.resolve()
65
66function warmClip (fetchImpl, src) {
67 if (typeof src !== 'string' || warmed.has(src)) return
68 warmed.add(src)
69 warming = warming.then(async () => {
70 if (warmedBytes >= WARM_LIMIT) return
71 const r = await fetchImpl(src, { credentials: 'same-origin' })
72 const reader = r && r.ok && r.body && r.body.getReader ? r.body.getReader() : null
73 if (!reader) return
74 // One that would go past the limit is not begun, and ends warming.
75 if (warmedBytes + (Number(r.headers && r.headers.get('Content-Length')) || 0) > WARM_LIMIT) {
76 warmedBytes = WARM_LIMIT
77 return reader.cancel()
78 }
79 for (;;) {
80 const { done, value } = await reader.read()
81 if (done) return
82 warmedBytes += value.byteLength
83 if (warmedBytes >= WARM_LIMIT) return reader.cancel()
84 }
85 }).catch(() => { warmed.delete(src) })
86}
87
88/** A picture fetched and decoded, so drawing it later waits for nothing. */
89export function decodePicture (url) {
90 const img = new Image()
91 img.decoding = 'async'
92 img.src = url
93 held.push(img)
94 return img.decode()
95}
96
97export async function loadTalk ({
98 href,
99 fonts = () => globalThis.slidesFonts,
100 onProgress = () => {},
101 from = 0,
102 fetchImpl = (...args) => globalThis.fetch(...args),
103 picture = decodePicture
104}) {
105 const fontsOf = typeof fonts === 'function' ? fonts : () => fonts
106
107 async function fetchTalk (etag) {
108 const headers = { Accept: 'application/json' }
109 if (etag) headers['If-None-Match'] = etag
110 const r = await fetchImpl(href, { credentials: 'same-origin', cache: 'no-store', headers })
111 if (r.status === 304) return null
112 if (!r.ok) throw new Error('talk: ' + r.status)
113 return version(await r.json(), r.headers.get('ETag'))
114 }
115
116 // prepare makes one slide ready: its families on, its pictures
117 // decoded. A slide that fails is tried again by retry().
118 async function prepare (v, s) {
119 try {
120 const f = fontsOf()
121 // A font the deck took on after this window opened is learned from
122 // the version, so the slide waits for it (final review, I6).
123 if (f && typeof f.learnUploaded === 'function' && v.uploaded) f.learnUploaded(v.uploaded)
124 await Promise.all([
125 f && f.prepareSection ? f.prepareSection(s.html) : null,
126 ...(Array.isArray(s.assets) ? s.assets : []).map(picture)
127 ])
128 v.ready.add(s.id)
129 v.failed.delete(s.id)
130 const waiting = v.waiters.get(s.id) || []
131 v.waiters.delete(s.id)
132 for (const resolve of waiting) resolve(true)
133 } catch {
134 v.failed.add(s.id)
135 }
136 }
137
138 // prepareAll gets every slide of v ready, a few at a time, starting
139 // at index start (the slide on screen), saying how far it has got.
140 async function prepareAll (v, start, report) {
141 // Each scene's bundle into the cache, so its frame needs no network;
142 // each clip's video warmed (warmClip), which no slide waits for: a
143 // clip not yet here shows its poster, and its press still counts.
144 for (const sc of Object.values(v.scenes)) {
145 if (sc && typeof sc.src === 'string' && !fetched.has(sc.src)) {
146 fetched.add(sc.src)
147 Promise.resolve().then(() => fetchImpl(sc.src, { credentials: 'same-origin' })).catch(() => fetched.delete(sc.src))
148 }
149 }
150 const n = v.slides.length
151 const order = []
152 for (let i = 0; i < n; i++) order.push(v.slides[(start + i) % n])
153 // From the slide on screen on.
154 for (const s of order) for (const src of (Array.isArray(s.clips) ? s.clips : [])) warmClip(fetchImpl, src)
155 const say = finished => report && onProgress({ done: v.ready.size, total: n, failed: v.failed.size, finished })
156 let next = 0
157 say(false)
158 await Promise.all(Array.from({ length: Math.min(AT_ONCE, n) }, async () => {
159 while (next < n) {
160 const s = order[next++]
161 if (v.ready.has(s.id)) continue
162 await prepare(v, s)
163 say(false)
164 }
165 }))
166 say(true)
167 }
168
169 let current = await fetchTalk(null)
170 let pending = null
171 let loading = null
172 prepareAll(current, Math.max(0, Math.min(from, current.slides.length - 1)), true)
173
174 return {
175 get deckSeq () { return current.deckSeq },
176 get arrive () { return current.arrive },
177 get view () { return current.view },
178 get slides () { return current.slides },
179 get scenes () { return current.scenes },
180 /** The deckSeq of a newer version held and not yet taken, or 0. */
181 get pending () { return pending ? pending.deckSeq : 0 },
182 /** That newer version's view, or null. */
183 get pendingView () { return pending ? pending.view : null },
184 slide (id) { return current.byID.get(id) || null },
185 has (id) { return current.ready.has(id) },
186 /** Resolves true once the slide is ready, false if this version has no such slide. */
187 ready (id) {
188 if (current.ready.has(id)) return Promise.resolve(true)
189 if (!current.byID.has(id)) return Promise.resolve(false)
190 const v = current
191 return new Promise(resolve => {
192 if (!v.waiters.has(id)) v.waiters.set(id, [])
193 v.waiters.get(id).push(resolve)
194 })
195 },
196 /**
197 * Asks the server for a newer version and, if there is one, holds
198 * it beside this one (pending, from the moment it arrives) and gets
199 * it ready. Resolves true once a newer version is held and every
200 * slide of it has been tried.
201 */
202 refresh () {
203 if (loading) return loading
204 const have = pending || current
205 loading = fetchTalk(have.etag).then(async v => {
206 if (!v || v.deckSeq <= have.deckSeq) return false
207 pending = v
208 await prepareAll(v, 0, false)
209 return true
210 }).catch(() => false).finally(() => { loading = null })
211 return loading
212 },
213 /** Takes the newer version, if one is held, and returns the view it replaced (or null). */
214 adopt () {
215 if (!pending) return null
216 const before = current.view
217 // A slide both versions draw the same is ready in the new one.
218 for (const s of pending.slides) {
219 const old = current.byID.get(s.id)
220 if (old && current.ready.has(s.id) && old.html === s.html) pending.ready.add(s.id)
221 }
222 current = pending
223 pending = null
224 prepareAll(current, 0, false)
225 return before
226 },
227 /** Tries again the slides that did not get ready. */
228 retry () {
229 for (const v of [current, pending]) {
230 if (v && v.failed.size) prepareAll(v, 0, v === current)
231 }
232 }
233 }
234}
235