Line data Source code
1 0 : export function createVideoThumbnail(
2 : source: string,
3 : signal: AbortSignal
4 : ): Promise<string | undefined> {
5 0 : if (signal.aborted) return Promise.resolve(undefined)
6 0 : const video = document.createElement('video')
7 0 : video.crossOrigin = 'anonymous'
8 0 : video.preload = 'auto'
9 0 : video.muted = true
10 0 : video.playsInline = true
11 :
12 0 : return new Promise((resolve) => {
13 0 : let settled = false
14 0 : const finish = (url?: string) => {
15 0 : if (settled) return
16 0 : settled = true
17 0 : clearTimeout(timer)
18 0 : signal.removeEventListener('abort', cancel)
19 0 : video.removeEventListener('error', cancel)
20 0 : video.removeEventListener('loadeddata', capture)
21 0 : video.pause()
22 0 : video.removeAttribute('src')
23 0 : video.load()
24 0 : resolve(url)
25 : }
26 0 : const cancel = () => finish()
27 0 : const capture = () => {
28 0 : if (!video.videoWidth || !video.videoHeight) return finish()
29 0 : try {
30 0 : const canvas = document.createElement('canvas')
31 0 : const scale = Math.min(
32 : 320 / video.videoWidth,
33 : 320 / video.videoHeight,
34 : 1
35 : )
36 0 : canvas.width = Math.max(1, Math.round(video.videoWidth * scale))
37 0 : canvas.height = Math.max(1, Math.round(video.videoHeight * scale))
38 0 : const context = canvas.getContext('2d')
39 0 : if (!context) return finish()
40 0 : context.drawImage(video, 0, 0, canvas.width, canvas.height)
41 0 : canvas.toBlob(
42 : (blob) => {
43 0 : if (!settled) finish(blob ? URL.createObjectURL(blob) : undefined)
44 : },
45 : 'image/jpeg',
46 : 0.8
47 : )
48 : } catch {
49 0 : finish()
50 : }
51 : }
52 0 : const timer = setTimeout(cancel, 15_000)
53 0 : signal.addEventListener('abort', cancel, { once: true })
54 0 : video.addEventListener('error', cancel, { once: true })
55 0 : video.addEventListener('loadeddata', capture, { once: true })
56 0 : video.src = source
57 0 : video.load()
58 : })
59 : }
|