// Keep decode, resize and WebP encoding off the scrolling thread. A blob // worker also works in the standalone wallet without a separately hosted file. // This function is serialized: all its dependencies must live inside it. function thumbnailWorker() { const encode = async (canvas, quality) => { let blob = await canvas.convertToBlob({ type: 'image/webp', quality }); if (!/webp/.test(blob.type)) blob = await canvas.convertToBlob({ type: 'image/jpeg', quality }); return blob; }; self.onmessage = async ({ data: { blob, width, tileSize } }) => { let bitmap; try { bitmap = await createImageBitmap(blob); const result = { width: bitmap.width, height: bitmap.height, media: null, tile: null }; // GIFs must keep animating; a canvas copy would freeze their first frame. if (!/gif/i.test(blob.type)) { // The grid's tile: the picture in its own shape (justified rows), // tileSize tall, its middle cut to between 1:2 and 2:1 — the most a // tile stretches either way. if (tileSize) { const W = bitmap.width, H = bitmap.height; const cw = Math.min(W, H * 2), ch = Math.min(H, W * 2); const th = Math.min(tileSize, ch), tw = Math.max(1, Math.round(th * cw / ch)); let cut; try { cut = await createImageBitmap(bitmap, (W - cw) / 2, (H - ch) / 2, cw, ch, { resizeWidth: tw, resizeHeight: th, resizeQuality: 'high' }); const canvas = new OffscreenCanvas(tw, th); canvas.getContext('2d').drawImage(cut, 0, 0); result.tile = await encode(canvas, 0.8); } catch {} finally { cut?.close(); } } if (width && bitmap.width > width * 1.25) { try { const height = Math.max(1, Math.round(bitmap.height * width / bitmap.width)); const canvas = new OffscreenCanvas(width, height), ctx = canvas.getContext('2d'); ctx.imageSmoothingQuality = 'high'; ctx.drawImage(bitmap, 0, 0, width, height); result.media = await encode(canvas, 0.82); } catch {} } } self.postMessage(result); } catch { self.postMessage(null); } finally { bitmap?.close(); } }; } // One image at a time bounds concurrent decoding/encoding and its CPU/memory // pressure. If workers are unavailable, callers keep displaying originals. const JOB_MS = 15000, MAX_QUEUE = 24, MAX_STRIKES = 3; let worker = null, disabled = false, current = null, timer = null, strikes = 0; const queue = []; function finish(job, data) { clearTimeout(timer); timer = null; job?.resolve(data); } // Workers can't be made here (constructor refused, script won't load): // thumbnails are off for this session. function failWorker() { disabled = true; worker?.terminate(); worker = null; const job = current; current = null; finish(job, null); for (const j of queue.splice(0)) j.resolve(null); } // A picture that hung or crashed the worker is given up and the worker // starts fresh for the next one — one bad file mustn't cost every later // thumbnail. Three failures in a row and it's treated as broken. function resetWorker() { if (++strikes >= MAX_STRIKES) return failWorker(); worker?.terminate(); worker = null; const job = current; current = null; finish(job, null); drain(); } function drain() { if (current || !queue.length || disabled) return; if (!worker) { let url; try { url = URL.createObjectURL(new Blob(['(' + thumbnailWorker.toString() + ')()'], { type: 'text/javascript' })); worker = new Worker(url, { name: 'image-thumbnails' }); worker.onerror = resetWorker; worker.onmessageerror = resetWorker; worker.onmessage = ({ data }) => { strikes = 0; const job = current; current = null; finish(job, data); drain(); }; } catch { failWorker(); return; } finally { if (url) URL.revokeObjectURL(url); } } current = queue.shift(); timer = setTimeout(resetWorker, JOB_MS); try { worker.postMessage(current.input); } catch { resetWorker(); } } export function makeImageThumbnails(blob, { width = 0, tileSize = 0 } = {}) { if (disabled || typeof Worker === 'undefined' || typeof OffscreenCanvas === 'undefined' || typeof createImageBitmap === 'undefined' || queue.length >= MAX_QUEUE) return Promise.resolve(null); return new Promise((resolve) => { queue.push({ input: { blob, width, tileSize }, resolve }); drain(); }); } // A GIF with no loop instruction (the NETSCAPE2.0 application extension) // plays once and stops on its last frame: every browser reads it that way. // Plenty of GIFs are made without one (a gifs.nostr.build reply GIF froze // after a second, Adam, 2026-11-19), and people expect a GIF to loop. The // extension, "loop forever", goes right after the global colour table. // Returns the patched bytes, or null when the file loops already or isn't // a GIF. export function loopGif(bytes) { const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); if (b.length < 13 || b[0] !== 0x47 || b[1] !== 0x49 || b[2] !== 0x46) return null; // "GIF" const tag = [0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30]; // NETSCAPE2.0 const anim = [0x41, 0x4e, 0x49, 0x4d, 0x45, 0x58, 0x54, 0x53, 0x31, 0x2e, 0x30]; // ANIMEXTS1.0 outer: for (let i = 13; i < b.length - 11; i++) { if (b[i] !== 0x4e && b[i] !== 0x41) continue; const t = b[i] === 0x4e ? tag : anim; for (let j = 1; j < 11; j++) if (b[i + j] !== t[j]) continue outer; return null; } const packed = b[10]; const at = 13 + (packed & 0x80 ? 3 * 2 ** ((packed & 7) + 1) : 0); if (at > b.length) return null; const ext = new Uint8Array([0x21, 0xff, 0x0b, ...tag, 0x03, 0x01, 0x00, 0x00, 0x00]); const out = new Uint8Array(b.length + ext.length); out.set(b.subarray(0, at), 0); out.set(ext, at); out.set(b.subarray(at), at + ext.length); return out; }