I had a bot that took videos and tried to set them as Telegram video avatars. Some uploads from my own iPhone just never showed up. No error, no message back. The clip sat in the chat looking fine, and the avatar never changed.
The cause was the codec. iPhones record HEVC (H.265) by default, and the video avatar pipeline rejected those files in every case I tested. The fix is a re-encode, but the details matter, so this post covers what I found, the ffmpeg command I ended up with, and a minimal aiogram 3 handler.
What the Telegram spec actually requires
Telegram doesn't publish a neat spec sheet for video avatars, so these numbers come from my own testing, not official docs:
- Square frame, 800x800. Smaller squares work, but I standardized on 800x800.
- H.264 video stream with yuv420p pixel format.
- At most 10 seconds.
- At most 2 MB.
- No audio track. Telegram ignores it anyway, and stripping it saves bytes.
If any of these is off, the upload can fail silently. That silence was the worst part of debugging this.
The ffmpeg part
The conversion has two steps. First, find the content box if the clip has black bars (letterboxed screen recordings do). Second, do a square crop, scale, and encode.
The cropdetect pass runs on the first 10 seconds only. It prints lines like crop=1920:1080:420:0 to stderr, and you want the last one because the filter settles after a few frames:
# 1. find the content box (first 10 seconds only)
CROP=$(ffmpeg -hide_banner -i "$IN" -t 10 \
-vf cropdetect=limit=24:round=2:reset=0 -f null - 2>&1 \
| grep -o 'crop=[0-9:]*' | tail -1)
# 2. square center crop, scale, encode
ffmpeg -y -i "$IN" -t 10 -an \
-vf "${CROP},crop='min(iw,ih)':'min(iw,ih)',scale=800:800:flags=lanczos,fps=30,format=yuv420p" \
-c:v libx264 -preset slow -crf 26 \
-movflags +faststart "$OUT"
stat -c%s "$OUT" # check size, must be under 2097152
A few notes on that command:
-
-t 10goes after-iso it's an output option. That trims the clip at 10 seconds without re-reading the input. -
-androps audio. -
crop='min(iw,ih)':'min(iw,ih)'forces a square from whatever is left after cropdetect. The quotes keep the commas inside the expression from being parsed as filter separators. -
fps=30flattens variable frame rate, which screen recordings love to produce. -
format=yuv420pis the pixel format Telegram accepts. HEVC files often come in 10-bit or 4:4:4 variants, and this filter converts them. -
-movflags +faststartmoves the index to the front of the file, so playback starts quicker.
CRF 26 with the slow preset gives a good size-to-quality ratio for avatars at 800x800. If the file lands over 2 MB, the simplest retry is to bump CRF by 2 or 3. I also cap duration to 8 seconds on the retry path. Telegram's limit is 10, but a little headroom avoids edge cases.
The aiogram 3 handler
Here is the minimal version. It accepts videos and GIFs (Telegram sends GIFs as MP4 animations), converts them, and sends the result back. I skipped cropdetect in the handler to keep it short. Add that pass if your inputs have black bars.
import asyncio
import tempfile
from pathlib import Path
from aiogram import F, Router
from aiogram.types import FSInputFile, Message
router = Router()
MAX_BYTES = 2 * 1024 * 1024
VF = (
"crop='min(iw,ih)':'min(iw,ih)',"
"scale=800:800:flags=lanczos,fps=30,format=yuv420p"
)
async def run_ffmpeg(src: Path, dst: Path) -> None:
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-y", "-loglevel", "error",
"-i", str(src), "-t", "10", "-an",
"-vf", VF,
"-c:v", "libx264", "-preset", "slow", "-crf", "26",
"-movflags", "+faststart", str(dst),
)
if await proc.wait() != 0:
raise RuntimeError("ffmpeg failed")
@router.message(F.video | F.animation)
async def make_avatar(message: Message) -> None:
media = message.video or message.animation
status = await message.answer("Converting...")
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "in"
dst = Path(tmp) / "avatar.mp4"
await message.bot.download(media, destination=src)
try:
await run_ffmpeg(src, dst)
except RuntimeError:
await status.edit_text("Conversion failed.")
return
if dst.stat().st_size > MAX_BYTES:
await status.edit_text("Still over 2 MB. Try a shorter clip.")
return
await message.answer_video(FSInputFile(dst), caption="Done.")
Two things I got wrong at first. I used create_subprocess_shell with string formatting, which broke on filenames with spaces and was an injection risk. Passing an argument list avoids both. I also wrote the temp directory cleanup after returning, which doesn't work. The with block has to contain the send.
How I packaged it as @liveavabot
The handler above is the core of @LiveAvaBot. Around it there is a queue so a few large uploads don't starve small ones, a size check before download, and a cleanup job for stale temp files. Users send a video or GIF, and the bot replies with an MP4 they can set as their video avatar.
It's at about 550 accounts so far. In the last 24 hours it did one conversion, so the real problem right now is getting people to find it, not the conversion code.
Lessons and edge cases
- Silent failures are the enemy. Always report back to the user, even when the cause is unclear. "Conversion failed" is better than nothing.
- Rotation metadata: iPhone portrait clips carry a rotation flag. ffmpeg applies autorotate before filters by default, so the crop works on the correct orientation. Don't pass
-noautorotate. - GIFs often run longer than 10 seconds or use a palette that looks bad when converted naively. The
-t 10cap handles the length, and yuv420p handles the palette. - 4K HEVC decodes fine but slowly. A 60-second 4K clip takes a while on a small VPS, so I run conversions in a worker queue with a timeout.
- Telegram may change these limits. Treat the numbers above as the values that worked for me at the time of writing.
Built by me: @LiveAvaBot.
If you've hit other silent failures in media uploads, I'd like to hear what they were.
Top comments (1)
You asked for other silent failures, here is one that hits exactly this pipeline: iPhone HDR. Recent iPhones can record HDR video (HLG), and format=yuv420p only changes the pixel format, not the color tags. I ran your filter chain with FFmpeg 6.1.1 on an HLG tagged 10 bit HEVC test clip, and the 800x800 H.264 output still said color_transfer=arib-std-b67 and color_primaries=bt2020. So you get an 8 bit file that claims to be HDR, which tends to look washed out or oddly bright depending on the player. No error anywhere.
What fixed it for me was tone mapping before the format step, then tagging the result as normal SDR:
plus
-color_primaries bt709 -color_trc bt709 -colorspace bt709. After that ffprobe showed bt709 for all three. You can check the input first with ffprobe's color_transfer field and only take that path for arib-std-b67 or smpte2084. Needs an FFmpeg build with zscale.