DEV Community

liveavabot
liveavabot

Posted on

Converting iPhone HEVC Videos to Telegram Avatars with ffmpeg

I wanted a short looping clip as my Telegram video avatar. I recorded it on an iPhone, uploaded it, and nothing happened. No error, no preview, the avatar just stayed the same. The file was HEVC (H.265), and Telegram quietly rejects that for this feature. This post covers what the spec requires, the ffmpeg commands that produce a valid file, and a minimal aiogram 3 handler that runs them.

What Telegram actually wants

Video avatars have a short list of hard requirements. The video must be H.264 in an MP4 container. The frame is 800x800, square. Duration is 10 seconds at most. The file must be 2 MB or less. Audio gets stripped, so you don't need it.

Most of these are easy to hit with ffmpeg. The codec is the trap. iPhones record HEVC by default unless you switched the camera to Most Compatible, so the clip plays fine on your phone and fails on Telegram's side without a useful message.

Watch for rotation metadata too. Portrait phone clips are often stored as landscape frames with a rotate flag. ffmpeg applies that rotation by default, so you get the right orientation as long as you don't disable autorotate. Crop after rotation, not before.

The ffmpeg pipeline

The pipeline has two steps. First, find the crop box. Portrait footage often has black bars or more height than the square we want, and cropdetect reports the region with actual content. It writes its result to stderr, so the command captures that output and greps it.

# 1. Detect the crop box from the first 10 seconds (cropdetect reports to stderr)
ffmpeg -hide_banner -i input.MOV -t 10 -vf cropdetect=limit=24:round=2:reset=0 -an -f null - 2>&1 | grep -o 'crop=[0-9:]*' | tail -n 1
# example output: crop=1080:1920:0:0

# 2. Crop, fill an 800x800 square, center crop, re-encode to H.264 without audio
ffmpeg -i input.MOV -t 10 -vf "crop=1080:1920:0:0,scale=800:800:force_original_aspect_ratio=increase,crop=800:800,format=yuv420p" -c:v libx264 -preset medium -crf 26 -an -movflags +faststart avatar.mp4
Enter fullscreen mode Exit fullscreen mode

The second command takes the detected box, scales it so the shorter side fills 800 pixels, and crops the center square. Then it sets the pixel format to yuv420p, which Telegram needs for broad playback. The -an flag drops audio. The -movflags +faststart option moves the index to the front of the file, which helps with streaming.

The 2 MB limit is where most of the tuning happens. CRF 26 works for most short clips at 800x800, but a noisy or high-motion clip can blow past 2 MB. I step CRF up to 30 and then 34, and stop at the first file that fits. Ten seconds at CRF 34 almost always fits.

The aiogram 3 handler

The handler accepts video, animations (GIFs arrive as animations with no audio), and documents whose MIME type starts with video/. Documents matter because Telegram delivers uncompressed files as documents, and that's how a lot of iPhone videos arrive when users send them as files.

import asyncio
import re
import tempfile
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 run(*args: str) -> str:
    proc = await asyncio.create_subprocess_exec(
        *args,
        stdout=asyncio.subprocess.DEVNULL,
        stderr=asyncio.subprocess.PIPE,
    )
    _, err = await proc.communicate()
    if proc.returncode != 0:
        raise RuntimeError(err.decode(errors="replace")[-400:])
    return err.decode(errors="replace")


async def detect_crop(src: Path) -> str | None:
    err = await run(
        "ffmpeg", "-hide_banner", "-i", str(src), "-t", "10",
        "-vf", "cropdetect=limit=24:round=2:reset=0", "-an", "-f", "null", "-",
    )
    found = re.findall(r"crop=[0-9]+:[0-9]+:[0-9]+:[0-9]+", err)
    return found[-1] if found else None


@router.message(F.video | F.animation | F.document)
async def make_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

    workdir = Path(tempfile.mkdtemp())
    src = workdir / "input"
    out = workdir / "avatar.mp4"
    await bot.download(media.file_id, destination=src)

    crop = await detect_crop(src)
    filters = ["scale=800:800:force_original_aspect_ratio=increase", "crop=800:800", "format=yuv420p"]
    if crop:
        filters.insert(0, crop)

    for crf in (26, 30, 34):
        await run(
            "ffmpeg", "-y", "-hide_banner", "-i", str(src), "-t", "10",
            "-vf", ",".join(filters),
            "-c:v", "libx264", "-preset", "medium", "-crf", str(crf),
            "-an", "-movflags", "+faststart", str(out),
        )
        if out.stat().st_size <= MAX_BYTES:
            break

    if out.stat().st_size > MAX_BYTES:
        await message.reply("Still over 2 MB after re-encoding. Try a shorter clip.")
        return

    await message.reply_video(FSInputFile(out))
Enter fullscreen mode Exit fullscreen mode

The detect step and the encode both go through asyncio subprocesses, so the bot keeps handling other updates while ffmpeg works. I left out cleanup of the temp directory and proper error reporting, which you'd want in production. The run helper raises on a non-zero exit code, and that becomes an unhandled exception in aiogram unless you wrap it.

On a 4K 60fps clip, the encode takes a while. If you expect a burst of uploads, put the encode behind an asyncio.Semaphore so two heavy jobs don't fight over the CPU.

Packaging it as @liveavabot

I wrapped this in a bot so people don't need ffmpeg installed. You send a video or GIF to @LiveAvaBot. It returns an 800x800 H.264 MP4 under 2 MB with audio removed, and you set it as your video avatar in the app.

It runs on a small VPS. So far it has 559 users, one conversion in the last 24 hours, and zero Telegram Stars revenue. The numbers are small. I'm sharing them because a dev.to readership will tell me what's missing faster than I can figure it out alone.

Edge cases and what's next

A few things still bite. Very long clips get cut to 10 seconds, which is the point, but people don't expect it. 4K 60fps input is slow to encode. Nearly static clips compress to tiny files, which is fine. Telegram could change the spec, so I verify output with ffprobe instead of trusting my memory of the requirements:

ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,width,height,pix_fmt -of csv=p=0 avatar.mp4
# expected: h264,800,800,yuv420p
Enter fullscreen mode Exit fullscreen mode

Next on my list are a preview step before the final send, and cropping around a detected face instead of the center. If you've hit other HEVC or avatar quirks, I'd like to hear about them.

Built by me: @liveavabot. Take the pitch with that in mind.

Top comments (0)