// clip-poster.mjs — a clip's poster: the picture of its video's first // frame, drawn by the uploader's browser (scenes and clips spec §4) and // held to a still's 4 MiB, the same limit registration holds it to // (internal/slides/clips.go's posterFor). import { UploadError } from './uploads.mjs' /** A poster's ceiling, a still's. */ export const MAX_POSTER_BYTES = 4 * 1024 * 1024 /** A poster is drawn at the video's own size, never wider than this. */ const POSTER_WIDTH = 1920 /** Throws when a drawn poster is over 4 MiB: an upload that can't finish, said in the usual words. */ export function checkPoster (blob) { if (!blob || !(blob.size > 0) || blob.size > MAX_POSTER_BYTES) throw new UploadError('poster_too_large') } const once = (el, type) => new Promise((resolve, reject) => { el.addEventListener(type, resolve, { once: true }) el.addEventListener('error', () => reject(new Error('the video cannot be read')), { once: true }) }) /** * The poster, from the video's bytes as this app serves them back while * staged (GET /d/{sqid}/uploads/{ref}: the page's policy loads media * from this origin alone, never a blob:), sought to 0 and drawn on a * canvas at its own size, at most 1920 wide, as WebP at quality 0.85 * (PNG where there is no WebP). Resolves {file, width, height, * duration}, duration in whole milliseconds (0 when the file does not * say); rejects when this browser cannot show the video, and with an * UploadError when the picture is over 4 MiB. */ export async function capturePoster (url, name, doc = globalThis.document) { const v = doc.createElement('video') v.muted = true v.playsInline = true v.preload = 'auto' try { const meta = once(v, 'loadeddata') v.src = url await meta const sought = once(v, 'seeked') v.currentTime = 0 await sought const scale = Math.min(1, POSTER_WIDTH / (v.videoWidth || 1)) const width = Math.round(v.videoWidth * scale) const height = Math.round(v.videoHeight * scale) if (!width || !height) throw new Error('the video has no picture') const c = doc.createElement('canvas') c.width = width c.height = height c.getContext('2d').drawImage(v, 0, 0, width, height) const blob = await new Promise(resolve => c.toBlob(resolve, 'image/webp', 0.85)) if (!blob || !['image/webp', 'image/png'].includes(blob.type)) throw new Error('no picture of the frame') checkPoster(blob) const file = new File([blob], String(name || 'clip').replace(/\.[^.]*$/, '') + (blob.type === 'image/webp' ? '.webp' : '.png'), { type: blob.type }) const duration = Number.isFinite(v.duration) && v.duration > 0 ? Math.round(v.duration * 1000) : 0 return { file, width, height, duration } } finally { v.removeAttribute('src') } }