Yokan / rebuild
Course 1 8624561

VideoFrameExtractor.wasm.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.wasm.kt

implementation58 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)23package eu.friedcutlet.yokan.services.media45import kotlin.io.encoding.Base646import kotlin.js.JsString7import kotlin.js.Promise8import kotlinx.coroutines.await910/**11 * A detached muted `<video>` reads the same-origin OPFS media-worker URL; a canvas scales the frame and encodes JPEG.12 * Null when the browser cannot decode the container/codec (for example MKV/HEVC in most browsers) or within 20 s.13 * Cancelling the coroutine abandons, but cannot abort, the browser's decode; the timeout bounds it.14 */15actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = VideoFrameExtractor { url, maxDimension ->16    browserVideoFrame(url, maxDimension).await<JsString?>()?.toString()?.let(Base64::decode)17}1819private fun browserVideoFrame(url: String, maxDimension: Int): Promise<JsString?> = js("""20    (async () => {21        if (typeof document === 'undefined') return null;22        const video = document.createElement('video');23        video.muted = true; video.preload = 'auto'; video.playsInline = true;24        const next = name => new Promise((resolve, reject) => {25            const done = () => { clearTimeout(timer); video.removeEventListener(name, ok); video.removeEventListener('error', fail); };26            const ok = () => { done(); resolve(); };27            const fail = () => { done(); reject(new Error('The video could not be decoded.')); };28            const timer = setTimeout(() => { done(); reject(new Error('The video frame timed out.')); }, 20000);29            video.addEventListener(name, ok); video.addEventListener('error', fail);30        });31        try {32            const loaded = next('loadeddata');33            video.src = url;34            await loaded;35            const seeked = next('seeked');36            video.currentTime = Number.isFinite(video.duration) ? video.duration * 0.1 : 0;37            await seeked;38            const width = video.videoWidth, height = video.videoHeight;39            if (!width || !height) return null;40            const scale = Math.min(1, maxDimension / Math.max(width, height));41            const canvas = document.createElement('canvas');42            canvas.width = Math.max(1, Math.floor(width * scale));43            canvas.height = Math.max(1, Math.floor(height * scale));44            canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);45            const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.85));46            if (!blob) return null;47            const bytes = new Uint8Array(await blob.arrayBuffer());48            let binary = '';49            for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));50            return btoa(binary);51        } catch (_) {52            return null;53        } finally {54            video.removeAttribute('src');55            video.load();56        }57    })()58""")59

Search chapters, reference and source filenames.