diff options
| author | Adam Soltys <[email protected]> | 2026-11-18 22:38:42 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-11-18 22:38:42 -0700 |
| commit | 01c03a199f8aafacfcdbaac30af074dd1d56fc53 (patch) | |
| tree | eef880f8046077edc6d902acb74f90448f8830ef | |
| parent | cb5826cec34bd6933f1d8d3f1d76629b15ba44a1 (diff) | |
| download | coinosv3-01c03a199f8aafacfcdbaac30af074dd1d56fc53.tar.gz coinosv3-01c03a199f8aafacfcdbaac30af074dd1d56fc53.zip | |
GIFs loop, even ones made to play once. "My gif reply isn't looping" (Adam, 2026-11-19). The GIF from the picker (gifs.nostr.build/5d6fa840….gif, 23 frames) has no loop instruction (the NETSCAPE2.0 extension), so every browser plays it once and stops on its last frame. When the feed makes its copy of a picture, a GIF without the extension now gets "loop forever" written in after its global colour table. That copy, up to 4 MB, is what the post paints, kept on disk like the other copies. A GIF stored before this change is fetched and looped again; one that already loops, and any other picture, is untouched. Patched, that GIF reads as loop 0 with all 23 frames. New gif-loop-test passes; feed-picture-pager-test now checks that a non-looping GIF is painted from a copy that loops. feed-media-cache, gif-picker, feed-media-views and features-smoke pass.HEADmaster
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMan6TV6sjEZSpqqBen9T5
| -rw-r--r-- | src/features/messages.js | 15 | ||||
| -rw-r--r-- | src/image-thumbnails.js | 29 | ||||
| -rw-r--r-- | tools/feed-picture-pager-test.js | 15 | ||||
| -rw-r--r-- | tools/gif-loop-test.js | 21 |
4 files changed, 76 insertions, 4 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index 245e1ce..91fc22d 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -36,7 +36,7 @@ import { loadMediaIndex, saveMediaIndex, wipeMediaIndex } from '../media-cache.j import { mergeFeedWindow } from '../feed-window.js'; import { createThreadStore } from '../thread-cache.js'; import { createThreadPrefetch } from '../thread-prefetch.js'; -import { makeImageThumbnails } from '../image-thumbnails.js'; +import { makeImageThumbnails, loopGif } from '../image-thumbnails.js'; import { createFeedCache, FEED_CACHE_POSTS, FEED_SEED_POSTS } from '../feed-cache.js'; import { POPULAR_RELAYS, FIREHOSE_RELAYS, popularCandidates } from '../popular-feed.js'; import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache, searchRecipients, searchable, setLocalPeople } from '../recipient-search.js'; @@ -6988,6 +6988,8 @@ export function messagesFeature(ctx) { if (!r) return null; const dims = JSON.parse(r.headers.get('x-dims') || 'null'); if (!dims || !dims.width) return null; + // a GIF kept before GIFs were looped: made again, to loop + if (r.headers.get('x-original') === '1' && r.headers.get('x-gif') !== '1' && /\.gif(\?|$)/i.test(url)) return null; const src = r.headers.get('x-original') === '1' ? null : URL.createObjectURL(await r.blob()); return { ...dims, thumb: src }; } catch { return null; } @@ -7003,17 +7005,22 @@ export function messagesFeature(ctx) { if (e && e.corsRefused) { noteNoCors(url); corsRefused.add(url); } // refused, as corsFetch confirmed return null; } + const gif = /gif/i.test(blob.type); + // a GIF that would play once and stop is painted from a copy that loops + let looped = null; + // (up to 4 MB: the copy is kept on disk beside the column copies) + if (gif && blob.size < 4e6) { try { const fixed = loopGif(await blob.arrayBuffer()); if (fixed) looped = new Blob([fixed], { type: 'image/gif' }); } catch {} } const result = await makeImageThumbnails(blob, { width: MEDIA_THUMB_W, tileSize: tileThumbs.has(url) ? 0 : TILE_PX, }); if (!result) return null; - const dims = { width: result.width, height: result.height }, out = result.media; + const dims = { width: result.width, height: result.height }, out = result.media || looped; // Both sizes share one decode in the worker; only cache writes and object // URLs come back to the page. The lightbox still uses the original. if (result.tile) await saveTileThumb(url, result.tile).catch(() => {}); try { const store = await thumbStore(); - await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1' } })); + await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1', ...(gif ? { 'x-gif': '1' } : {}) } })); const keys = await store.keys(); for (const k of keys.slice(0, Math.max(0, keys.length - MEDIA_THUMB_MAX))) store.delete(k); } catch {} @@ -10959,7 +10966,7 @@ export function messagesFeature(ctx) { return h('img', { src: mediaSrc(url, known), 'data-pic': url, class: 'note-img clickable', loading: feedPaint || known ? 'eager' : 'lazy', alt: label || '', // a few-ms decode of the copy paints with the page; an original never holds the page for its decode - decoding: known && known.thumb ? 'sync' : 'async', + decoding: known && known.thumb && !/\.gif(\?|$)/i.test(url) ? 'sync' : 'async', // (a looped GIF's copy is the whole animation) width: size?.width, height: size?.height, style: size ? 'height:auto;aspect-ratio:' + size.width + '/' + size.height + ';--ar:' + (size.width / size.height).toFixed(4) : undefined, onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); openPicture(url, e); }, diff --git a/src/image-thumbnails.js b/src/image-thumbnails.js index 2686dac..80e6915 100644 --- a/src/image-thumbnails.js +++ b/src/image-thumbnails.js @@ -96,3 +96,32 @@ export function makeImageThumbnails(blob, { width = 0, tileSize = 0 } = {}) { || 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; +} diff --git a/tools/feed-picture-pager-test.js b/tools/feed-picture-pager-test.js index 947c6aa..5b5b80f 100644 --- a/tools/feed-picture-pager-test.js +++ b/tools/feed-picture-pager-test.js @@ -13,6 +13,8 @@ let ok = true; const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; const png = (size) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=' + size, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout; const PICS = { a1: png('400x300'), a2: png('300x400'), b: png('320x320'), d: png('360x240') }; +// a GIF made without a loop instruction (plays once in a browser) +const GIF = Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=5:duration=1', '-loop', '-1', '-f', 'gif', 'pipe:1']).stdout; const SK = generateSecretKey(), AUTHOR = getPublicKey(SK); const now = Math.floor(Date.now() / 1000); @@ -23,6 +25,7 @@ const server = Bun.serve({ port: 0, fetch: (req) => { if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); const m = /^\/(a1|a2|b|d)\.png$/.exec(path); if (m) return new Response(PICS[m[1]], { headers: { 'content-type': 'image/png' } }); + if (path === '/once.gif') return new Response(GIF, { headers: { 'content-type': 'image/gif' } }); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); const U = (n) => server.url.origin + '/' + n + '.png'; @@ -30,6 +33,7 @@ const seeded = [ post('two pictures ' + U('a1') + ' ' + U('a2'), 100), post('one picture ' + U('b'), 200), post('only words here, nothing to look at', 300), + post('a gif reply ' + server.url.origin + '/once.gif', 3000), // (past the fillers: the pager walk above doesn't meet it) post('a last picture ' + U('d'), 400), ...Array.from({ length: 12 }, (_, i) => post('filler ' + i + ' ' + 'lorem ipsum dolor sit amet. '.repeat(5), 500 + i * 60)), ]; @@ -93,6 +97,17 @@ try { }); check('two pictures in a post: one gallery, side by side, one height', gal.n === 2 && gal.sameRow && gal.h > 50 && gal.h < 300, JSON.stringify(gal)); check('a lone picture is not put in a gallery', gal.lone); + // a GIF that would play once is painted from a copy that loops + await waitFor(() => { window.scrollTo(0, document.body.scrollHeight); return [...document.querySelectorAll('.notes-feed [data-key]')].some((n) => n.textContent.includes('a gif reply') && n.querySelector('img.note-img')); }, null, 10000); + const gifLoop = await page.evaluate(async () => { + const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a gif reply')); + const img = r && r.querySelector('img.note-img'); + if (!img || !/^blob:/.test(img.src)) return { src: img && img.src.slice(0, 40) }; + const b = new Uint8Array(await (await fetch(img.src)).arrayBuffer()); + return { src: 'blob', loops: new TextDecoder('latin1').decode(b).includes('NETSCAPE2.0') }; + }); + check('a GIF without a loop is painted from a copy that loops', gifLoop.src === 'blob' && gifLoop.loops, JSON.stringify(gifLoop)); + await page.evaluate(() => window.scrollTo(0, 0)); await sleep(500); // painted from the tile copy (a proper resize), not the column copy shrunk by the browser check('gallery tiles are painted from the tile copies', await waitFor(() => { const g = document.querySelector('.notes-feed .note-gallery'); diff --git a/tools/gif-loop-test.js b/tools/gif-loop-test.js new file mode 100644 index 0000000..a135e36 --- /dev/null +++ b/tools/gif-loop-test.js @@ -0,0 +1,21 @@ +// A GIF made without a loop instruction plays once in every browser; the +// copy the feed paints from gets "loop forever" added. One that loops +// already, or isn't a GIF, is left alone. +// Run: bun tools/gif-loop-test.js +import { loopGif } from '../src/image-thumbnails.js'; +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const make = (args) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=64x48:rate=5:duration=1', ...args, '-f', 'gif', 'pipe:1']).stdout; +const once = new Uint8Array(make(['-loop', '-1'])), looping = new Uint8Array(make(['-loop', '0'])); +const has = (b) => Buffer.from(b).includes('NETSCAPE2.0'); +check('ffmpeg made one GIF without a loop and one with', !has(once) && has(looping)); +const fixed = loopGif(once); +check('the one-shot GIF gets the loop extension', !!fixed && has(fixed)); +const i = Buffer.from(fixed).indexOf('NETSCAPE2.0'); +check('…loop forever (count 0), right after the colour table', fixed[i + 11] === 3 && fixed[i + 12] === 1 && fixed[i + 13] === 0 && fixed[i + 14] === 0 && fixed[i + 15] === 0 && fixed[i - 3] === 0x21 && fixed[i - 2] === 0xff); +const probe = Bun.spawnSync(['ffprobe', '-v', 'error', '-count_frames', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', '-i', 'pipe:0'], { stdin: fixed }).stdout.toString().trim(); +check('the patched GIF still decodes, every frame', probe === '5', probe); +check('a GIF that loops already is left alone', loopGif(looping) === null); +check('not a GIF: left alone', loopGif(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])) === null); +console.log(ok ? '\n✅ GIFs loop' : '\n❌ failed'); +process.exit(ok ? 0 : 1); |
