Why my iPhone video got silently rejected
I wanted a video avatar on my profile. I recorded a six second clip on my iPhone, set it through the Telegram client, and nothing happened. No error, the option just never took. The file was HEVC (H.265) inside a .MOV container, which is the default on recent iPhones. Telegram's avatar pipeline doesn't accept that combination, and it doesn't tell you why.
That failure is what led me to build @liveavabot, a small Telegram bot that takes any video or GIF and returns a file you can use as a video avatar. Under the hood it's ffmpeg doing the heavy lifting. I wrote the wrapper, the crop logic, and the retry loop around it.
What the spec actually requires
Telegram doesn't publish a neat spec for video avatars, so these numbers come from testing files against the client. The target I settled on:
- 800x800 pixels, square
- H.264 video in yuv420p pixel format
- 10 seconds or less
- Under about 2 MB
- No audio track
The pixel format matters as much as the codec. Forcing yuv420p also avoids 10-bit sources, which some clients refuse to render.
Cropping to a square with cropdetect
Phone footage is almost never square. It's 16:9 landscape or 9:16 portrait, and a plain scale to 800x800 would stretch it. So the pipeline has two steps. First, cropdetect finds the actual picture area and strips letterbox bars. Then I take the largest centered square from that area and scale it down.
Run the detection pass first:
ffmpeg -i input.mov -vf cropdetect=24:2:0 -t 10 -f null - 2>&1 | grep -o 'crop=[0-9:]*' | tail -n 1 The arguments are the black threshold (24), the rounding (2, which keeps dimensions even for yuv420p), and reset (0, never reset). The last line wins because cropdetect refines its estimate frame by frame. For a 1920x1080 clip with no bars, it prints crop=1920:1080:0:0.
Then encode with the square crop:
ffmpeg -i input.mov -vf crop=1080:1080:420:0,scale=800:800,format=yuv420p -an -t 10 -c:v libx264 -preset slow -crf 30 -movflags +faststart avatar.mp4 The 1080 is the shorter side of the detected crop. The x offset of 420 is (1920 - 1080) / 2, so the square stays centered. In the wrapper I compute those numbers from the detected crop rather than hardcoding them. -an drops audio, -t 10 caps duration, and +faststart moves the moov atom to the front so clients can start playback early.
The crf of 30 is only a starting point. A ten-second clip with a lot of motion can blow past 2 MB at that setting, so the wrapper retries at higher crf values until the file fits. It's the least elegant part of the whole thing, but it works on the files I've tested.
The aiogram 3 handler
Here's the bot side. It downloads the upload, runs the two ffmpeg passes, retries on size, and sends the result back as a document.
import asyncio from pathlib import Path from aiogram import Bot, F, Router from aiogram.types import FSInputFile, Message router = Router() MAX_BYTES = 2 * 1024 * 1024 async def detect_crop(src: Path) -> str: proc = await asyncio.create_subprocess_exec( 'ffmpeg', '-i', str(src), '-vf', 'cropdetect=24:2:0', '-t', '10', '-f', 'null', '-', stderr=asyncio.subprocess.PIPE, ) _, err = await proc.communicate() crops = [line.split('crop=')[1].split()[0] for line in err.decode(errors='ignore').splitlines() if 'crop=' in line] if not crops: raise ValueError('cropdetect found no picture area') return crops[-1] # e.g. '1920:1080:0:0' def square_filter(crop: str) -> str: w, h, x, y = (int(v) for v in crop.split(':')) side = min(w, h) sx = x + (w - side) // 2 sy = y + (h - side) // 2 return f'crop={side}:{side}:{sx}:{sy},scale=800:800,format=yuv420p' async def encode(src: Path, dst: Path, vf: str, crf: int) -> None: proc = await asyncio.create_subprocess_exec( 'ffmpeg', '-y', '-i', str(src), '-vf', vf, '-an', '-t', '10', '-c:v', 'libx264', '-preset', 'slow', '-crf', str(crf), '-movflags', '+faststart', str(dst), ) if await proc.wait() != 0: raise RuntimeError('ffmpeg failed') @router.message(F.video | F.animation | F.document) async def to_avatar(message: Message, bot: Bot) -> None: media = message.video or message.animation or message.document if media is None: return if message.document and not (message.document.mime_type or '').startswith('video/'): return src = Path(f'/tmp/{media.file_unique_id}.in') dst = Path(f'/tmp/{media.file_unique_id}.mp4') await bot.download(media, destination=src) vf = square_filter(await detect_crop(src)) for crf in (30, 34, 38): await encode(src, dst, vf, crf) if dst.stat().st_size <= MAX_BYTES: break await message.answer_document( FSInputFile(dst), caption='800x800, H.264, no audio.', ) Two things the snippet skips. There's no real error handling, and the /tmp files never get cleaned up. The production version wraps each job in its own temp directory and reports failures back to the user. Also, the Bot API can't set a user's profile video for you, so the reply is a file you save and set from the Telegram app. Sending it as a document keeps Telegram from recompressing it, which the photo path would do.
Packaging it as @liveavabot
The bot runs on a single small VPS. A worker process pulls conversion jobs from a queue, so ffmpeg runs don't block polling. Each job gets its own temp directory and a timeout. You can try it at @LiveAvaBot, send any video or GIF, and it replies with the converted file. So far 536 accounts have used it.
Edge cases and what's next
A few things I've run into:
- Portrait 9:16 clips work, but check rotation metadata. ffmpeg auto-rotates by default, so most sideways phone files come out right, but I still verify the crop on them.
- Variable frame rate GIFs can produce odd timing. Adding
-r 30to the encode normalizes it. - Audio tracks get dropped on purpose. Avatars don't play sound anyway.
What's next: I haven't stress-tested 4K HEVC yet. Decode time climbs fast, and the 10 second cap doesn't reduce decode cost. I want a per-job timeout and a queue limit so one 4K upload can't stall the worker.
Built by me, @liveavabot.
What's the worst file Telegram has refused to accept for you?