oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// clip-poster.mjs — a clip's poster: the picture of its video's first
2// frame, drawn by the uploader's browser (scenes and clips spec §4) and
3// held to a still's 4 MiB, the same limit registration holds it to
4// (internal/slides/clips.go's posterFor).
5import { UploadError } from './uploads.mjs'
6
7/** A poster's ceiling, a still's. */
8export const MAX_POSTER_BYTES = 4 * 1024 * 1024
9
10/** A poster is drawn at the video's own size, never wider than this. */
11const POSTER_WIDTH = 1920
12
13/** Throws when a drawn poster is over 4 MiB: an upload that can't finish, said in the usual words. */
14export function checkPoster (blob) {
15 if (!blob || !(blob.size > 0) || blob.size > MAX_POSTER_BYTES) throw new UploadError('poster_too_large')
16}
17
18const once = (el, type) => new Promise((resolve, reject) => {
19 el.addEventListener(type, resolve, { once: true })
20 el.addEventListener('error', () => reject(new Error('the video cannot be read')), { once: true })
21})
22
23/**
24 * The poster, from the video's bytes as this app serves them back while
25 * staged (GET /d/{sqid}/uploads/{ref}: the page's policy loads media
26 * from this origin alone, never a blob:), sought to 0 and drawn on a
27 * canvas at its own size, at most 1920 wide, as WebP at quality 0.85
28 * (PNG where there is no WebP). Resolves {file, width, height,
29 * duration}, duration in whole milliseconds (0 when the file does not
30 * say); rejects when this browser cannot show the video, and with an
31 * UploadError when the picture is over 4 MiB.
32 */
33export async function capturePoster (url, name, doc = globalThis.document) {
34 const v = doc.createElement('video')
35 v.muted = true
36 v.playsInline = true
37 v.preload = 'auto'
38 try {
39 const meta = once(v, 'loadeddata')
40 v.src = url
41 await meta
42 const sought = once(v, 'seeked')
43 v.currentTime = 0
44 await sought
45 const scale = Math.min(1, POSTER_WIDTH / (v.videoWidth || 1))
46 const width = Math.round(v.videoWidth * scale)
47 const height = Math.round(v.videoHeight * scale)
48 if (!width || !height) throw new Error('the video has no picture')
49 const c = doc.createElement('canvas')
50 c.width = width
51 c.height = height
52 c.getContext('2d').drawImage(v, 0, 0, width, height)
53 const blob = await new Promise(resolve => c.toBlob(resolve, 'image/webp', 0.85))
54 if (!blob || !['image/webp', 'image/png'].includes(blob.type)) throw new Error('no picture of the frame')
55 checkPoster(blob)
56 const file = new File([blob], String(name || 'clip').replace(/\.[^.]*$/, '') + (blob.type === 'image/webp' ? '.webp' : '.png'), { type: blob.type })
57 const duration = Number.isFinite(v.duration) && v.duration > 0 ? Math.round(v.duration * 1000) : 0
58 return { file, width, height, duration }
59 } finally {
60 v.removeAttribute('src')
61 }
62}
63