I kept sending videos from my iPhone to a Telegram bot and getting nothing usable back. No error message, no avatar, just a silent failure. The clip was a normal 4-second recording, so I spent an evening figuring out why.
The answer was codec and container. iPhones record HEVC (H.265) inside a .MOV wrapper by default. Telegram's video avatar pipeline expects H.264 in MP4, and HEVC uploads looked fine in the client but never got applied.
What the video avatar spec asks for
These are the limits I target, based on my own testing:
- Codec: H.264 (AVC) with
yuv420ppixel format - Resolution: 800x800, square
- Duration: 10 seconds or less
- File size: 2 MB or less
- Audio: none, strip it
Each of these is a separate way to get rejected, and the failure doesn't tell you which one tripped. That's the annoying part.
The ffmpeg command
ffmpeg does almost all the work. The bot is a thin wrapper around it.
If the clip has black bars (letterboxed screen recordings, for example), detect them first:
ffmpeg -i input.MOV -vf cropdetect=limit=24:round=2:reset=0 -t 5 -f null - 2>&1 | grep -o 'crop=[0-9:]*' | tail -1
That prints something like crop=1080:1080:0:420. I use the result to strip bars before the square crop. For plain portrait footage you can skip this step.
Then the encode:
ffmpeg -y -i input.MOV -vf "crop='min(iw,ih)':'min(iw,ih)',scale=800:800:flags=lanczos,format=yuv420p" -an -t 10 -c:v libx264 -preset slow -crf 30 -profile:v high -movflags +faststart avatar.mp4
What each piece does:
-
crop='min(iw,ih)':'min(iw,ih)'takes the largest centered square. The single quotes stop the commas inside the expression from being read as filter separators. -
scale=800:800forces the exact size. The crop already made the frame square, so there's no letterboxing. -
format=yuv420pforces the pixel format. Without it, some HEVC sources come out as 10-bit or 4:4:4 and the avatar fails. -
-androps audio. -
-t 10caps duration. -
-crf 30is the quality knob. The bot starts here and retries at 34 if the output is over 2 MB. -
-movflags +faststartmoves the moov atom to the front. Not strictly required for avatars, but it costs nothing.
ffmpeg applies iPhone rotation metadata by default, so portrait clips don't come out sideways.
The aiogram 3 handler
The bot runs on aiogram 3. The handler downloads the file, runs ffmpeg as an async subprocess so the event loop doesn't block, and sends the result back as a document. Sending as a document stops Telegram from re-encoding it on the way out.
import asyncio
import os
import shutil
import tempfile
from aiogram import Router, F, Bot
from aiogram.types import Message, FSInputFile
router = Router()
@router.message(F.video | F.animation | F.document)
async def make_avatar(message: Message, bot: Bot):
media = message.video or message.animation or message.document
tmp = tempfile.mkdtemp()
try:
src = os.path.join(tmp, 'in.mov')
dst = os.path.join(tmp, 'avatar.mp4')
file = await bot.get_file(media.file_id)
await bot.download_file(file.file_path, destination=src)
proc = await asyncio.create_subprocess_exec(
'ffmpeg', '-y', '-i', src,
'-vf', "crop='min(iw,ih)':'min(iw,ih)',scale=800:800:flags=lanczos,format=yuv420p",
'-an', '-t', '10', '-c:v', 'libx264', '-crf', '30',
'-movflags', '+faststart', dst,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
_, err = await proc.communicate()
if proc.returncode != 0 or os.path.getsize(dst) > 2 * 1024 * 1024:
await message.reply('Could not turn this into a valid avatar.')
return
await message.reply_document(FSInputFile(dst), caption='800x800, H.264, no audio.')
finally:
shutil.rmtree(tmp, ignore_errors=True)
A few things I learned the hard way. Don't use subprocess.run inside an aiogram handler, because it blocks every other user while ffmpeg works. Check both the return code and the output size, since ffmpeg can exit 0 and still produce something over the limit. And the filter accepts any media type, so a real product should check mime_type first and reject non-video documents before spending CPU on them.
The snippet above skips the CRF retry loop for brevity. The retry is just a second call with a higher -crf when the output is too big.
Packaging it as @liveavabot
I wrapped this in a Telegram bot called @LiveAvaBot. You send it a video or GIF, and it sends back an MP4 that meets the spec. There's no magic in it, the work is all ffmpeg with some input checks and a retry on file size.
The bot exists because the failure mode is so quiet. Most people who hit this assume their video is broken, when the file is fine and only the codec is wrong.
Edge cases and what's next
A few things aren't handled well yet:
- HDR sources (Dolby Vision, HLG) are untested. I'd expect color shifts, and I haven't added a tone-mapping step.
- Variable frame rate clips from screen recordings sometimes come out jerky. I haven't added an explicit
fpsor-fps_mode cfroption yet. - Very long clips get cut at 10 seconds from the start. There's no trim UI, so users who want a different segment have to trim the source first.
Next on my list is a preview step and a start-offset option. If you've hit a source file that still fails with this pipeline, I'd like to see the ffprobe output for it.
Disclosure: I built @liveavabot.
Top comments (0)