Telegram stickers come in three formats: static WebP, animated .tgs, and video .webm. Almost nothing outside Telegram opens a .tgs, so anyone saving a pack usually wants PNG for the still ones and GIF for the moving ones. I look after a small web page that downloads sticker packs, and I recently rewrote its conversion so it runs entirely on decoders the browser already has. These are my notes on how that works, and on why the first version, built on FFmpeg.wasm, is gone.

Why FFmpeg.wasm went away

The first version converted everything with FFmpeg.wasm. It worked, but it had two costs I only measured properly when I went back over the page:

  • A conversion needed a download of about 30 MB.
  • It needed cross-origin isolation headers on the page. Those headers also stopped the analytics script (Microsoft Clarity) from loading there, so I had no session data for the page at all. (Multithreaded WASM needs SharedArrayBuffer, which is what the isolation requirement comes from.)

The decoders for all three sticker formats already exist in a browser: createImageBitmap for WebP, a <video> element for VP9 WebM, and lottie-web for the animation JSON. The only things missing were a GIF encoder and a ZIP writer, and both are small libraries (modern-gif and client-zip). With FFmpeg gone, so were the isolation headers, and the page could be prerendered like the rest of the site.

Static stickers: WebP to PNG via canvas

This is the easy case. Decode into an ImageBitmap, draw it on a canvas of the same size, and ask the canvas for a PNG. Transparency survives.

export async function convertImageToPng(source: Blob): Promise<Blob> { const bitmap = await createImageBitmap(source); try { const canvas = document.createElement('canvas'); canvas.width = bitmap.width; canvas.height = bitmap.height; canvas.getContext('2d')!.drawImage(bitmap, 0, 0); return await new Promise<Blob>((resolve, reject) => { canvas.toBlob(b => (b ? resolve(b) : reject(new Error('PNG encoding failed'))), 'image/png'); }); } finally { bitmap.close(); } } 

Animated .tgs: gunzip, then Lottie frame by frame

A .tgs file is gzipped Lottie JSON. DecompressionStream('gzip') inflates it without a library. Two guards are worth having: Telegram caps a .tgs at 64 KB, so anything over 1 MB compressed is refused, and inflating stops at 16 MB so a malformed file cannot eat memory (a small gzip can expand enormously).

const stream = new Response(bytes).body!.pipeThrough(new DecompressionStream('gzip')); const reader = stream.getReader(); let total = 0; while (true) { const { done, value } = await reader.read(); if (done) break; total += value.byteLength; if (total > MAX_INFLATED_BYTES) { await reader.cancel(); throw new Error('TGS file is too large'); } chunks.push(value); } 

I load lottie_light_canvas, the build without the expression engine (Telegram forbids expressions in stickers anyway) and with only the canvas renderer. The animation is created paused, with autoplay: false, and lottie's own clock never runs. For export I step it by hand with goToAndStop(frame, true) and read the pixels back. The willReadFrequently hint on the context matters because getImageData runs for every frame.

const frameCount = ...; // from planGif(frameRate, durationMs) for (let index = 0; index < frameCount; index += 1) { const sourceFrame = ((index * delayCs * 10) / 1000) * meta.frameRate; animation.goToAndStop(Math.min(sourceFrame, meta.totalFrames - 1), true); encoder.addFrame(context.getImageData(0, 0, size, size).data, delayCs); await yieldToBrowser(); // lottie needs the DOM, so this stays on the main thread } 

Rendering has to stay on the main thread, so the loop yields between frames through a MessageChannel to keep the page responsive.

GIF encoding: the frame-rate arithmetic

GIF delays are whole centiseconds, and browsers play anything under 2 cs as 10 cs. A 60 fps sticker therefore cannot be reproduced; I clamp the delay to at least 4 cs (25 fps) and compute the frame count so the total duration is kept:

const delayCs = Math.max(4, Math.round(100 / frameRate)); const frameCount = Math.min(300, Math.max(1, Math.round(durationMs / (delayCs * 10)))); 

The code comment records why 4 and not 3: 3 cs (33 fps) made files about a third larger for little visible gain.

Two other details. GIF has no partial alpha, so each pixel's alpha is snapped to 0 or 255 at a threshold of 128 before the frame goes to the encoder. And the encoder runs in a Web Worker, which starts from a same-origin blob: URL built from the worker source, because one deployment serves assets from a CDN origin where new Worker(url) is refused. I talk to the worker's message protocol directly instead of using the library's helper, because that helper never terminates its workers and would have leaked one per sticker.

Video stickers: seeking a <video>

Video stickers are VP9 in WebM, at most 3 seconds. There is no frame-accurate "give me frame N" API without WebCodecs, so the code seeks: set currentTime, wait for seeked, draw the video onto a canvas.

const time = Math.min((index * delayCs) / 100 + 0.001, Math.max(0, video.duration - 0.01)); await seekVideo(video, time, SEEK_TIMEOUT_MS); context.clearRect(0, 0, width, height); context.drawImage(video, 0, 0, width, height); encoder.addFrame(context.getImageData(0, 0, width, height).data, delayCs); 

The + 0.001 puts the seek just inside the frame's interval, and the clamp keeps it off the very end, where some decoders show nothing. Every wait has a timeout (10 s to load, 4 s per seek), because a stalled decoder fires neither seeked nor error. Video stickers are sampled at about 15 fps rather than 25: filmed or painted frames compress far worse in GIF than flat vector shapes, and at 25 fps and 512 px I saw 1 to 4.7 MB per sticker. Support is checked first with canPlayType('video/webm; codecs="vp9"'); a browser without it keeps the original file.

Packing it up

Conversions are cached per sticker and output format, so saving a sticker and then the whole pack does not convert twice. The batch runs through a small concurrency pool: 6 workers when only fetching, but 2 when GIFs are being made, and 1 when navigator.deviceMemory reports 4 GB or less, because one 512 px GIF in flight can hold up to roughly 100 MB of frames. If a single conversion throws, that sticker falls back to Telegram's original file and the result reports how many were kept as originals, instead of failing the whole pack.

The ZIP is client-zip's downloadZip(...).blob() over the finished blobs.

The server side is thin

The only server work is the Telegram Bot API lookup (getStickerSet, then getFile per sticker, six at a time, with a 45 s budget so a stalled upstream cannot hold the request). Files are served through a media proxy so the browser can fetch them same-origin. A pack lookup result is cached for 10 minutes, since Telegram keeps a file path valid for at least an hour; the cache only keeps complete answers, so a pack that came back with stickers missing is looked up again next time.

Numbers

These come from my own runs on the live page, so treat them as rough figures, not a benchmark:

  • 34 animated stickers converted to GIF in about 19 seconds.
  • A 50-sticker pack as a PNG ZIP: under a second.
  • A repeated pack load went from 6.9 s to 0.4 s once lookups were cached.

What I would do differently

Main-thread lottie rendering is the bottleneck for animated packs, and the yield-per-frame loop trades speed for a page that still responds. An OffscreenCanvas-based renderer or WebCodecs for the video path would likely be faster, but neither was necessary to get below the point where people give up, and the fallback behaviour (keep the original when the browser cannot convert) is simpler with the decoders the browser already ships.