DEV Community

liveavabot
liveavabot

Posted on

Converting iPhone HEVC Videos to Telegram Video Avatars with ffmpeg

The video Telegram quietly refuses

A user sent me a clip recorded on an iPhone. They tried to set it as a video avatar, the picker closed, and nothing changed. No error message. The avatar stayed empty.

The problem is the codec. iPhones record in HEVC (H.265) by default, and the video avatar pipeline won't take it. Telegram doesn't tell you that. The file just gets dropped.

I built @liveavabot to handle that conversion so people don't have to remember ffmpeg flags. Below is how the pipeline works and the code behind it.

What the video avatar spec actually asks for

In my testing, the constraints that matter are: H.264 video, 800 by 800 pixels, at most 10 seconds, at most 2 MB, and no audio track. The pixel format matters too. I force yuv420p, since that's the format most decoders expect and the one that encodes predictably.

The HEVC file itself is fine as a regular video. ffprobe reports codec_name=hevc, and that's the stream the avatar pipeline rejects. Re-encode the same clip to H.264 and it uploads.

Phone clips add two more problems. Screen recordings are often letterboxed, and most phone footage is 4:3 or 16:9, not square. So the conversion has to crop before it scales, or you get stretched faces.

Detect the crop, then encode

The pipeline has two passes. First, cropdetect finds the active picture area by looking for black borders. Second, I take a centered square inside that area, scale it to 800x800, and encode.

Detection on its own looks like this:

ffmpeg -hide_banner -i input.MOV -t 10 -an -vf cropdetect=limit=24:round=2:reset=0 -f null - 2>&1 | grep -o 'crop=[0-9:]*' | tail -1
Enter fullscreen mode Exit fullscreen mode

cropdetect writes its results to stderr, one line per frame. With reset=0 the values settle, so the last line is the one I trust. You get something like crop=1080:1080:0:420.

Encoding with the detected values:

ffmpeg -y -i input.MOV -t 10 -an -vf 'crop=1080:1080:0:420,scale=800:800:flags=lanczos,fps=30,format=yuv420p' -c:v libx264 -preset slow -crf 26 -movflags +faststart avatar.mp4
Enter fullscreen mode Exit fullscreen mode

A few flags here do real work. -an strips audio. -t 10 caps the duration. fps=30 normalizes the variable frame rate most phones record at. format=yuv420p gives players a pixel format they can decode. +faststart moves the moov atom to the front so the file starts playing before it's fully downloaded.

ffmpeg auto-rotates based on the rotation metadata by default, so portrait clips come out upright without extra work.

The 2 MB ceiling is the one that needs a loop. A 10 second clip at crf 26 usually lands under it, but a busy scene can push it over. The wrapper retries at crf 30 and then 34 if the output is too big. That's a blunt tool, but it works.

The aiogram 3 handler

The bot side is small. It accepts video, animation, or a document with a video MIME type, downloads the file, runs the two passes, and sends the result back. Error handling is cut for length here. In production I catch RuntimeError and send a short message.

import asyncio
import re
import tempfile
from pathlib import Path

from aiogram import Bot, F, Router
from aiogram.types import BufferedInputFile, Message

router = Router()
MAX_BYTES = 2 * 1024 * 1024


async def detect_crop(src: Path) -> str:
    proc = await asyncio.create_subprocess_exec(
        'ffmpeg', '-hide_banner', '-i', str(src), '-t', '10', '-an',
        '-vf', 'cropdetect=limit=24:round=2:reset=0', '-f', 'null', '-',
        stdout=asyncio.subprocess.DEVNULL,
        stderr=asyncio.subprocess.PIPE,
    )
    _, err = await proc.communicate()
    found = re.findall(r'crop=(\\d+):(\\d+):(\\d+):(\\d+)', err.decode(errors='replace'))
    if not found:
        raise RuntimeError('cropdetect found nothing')
    w, h, x, y = map(int, found[-1])
    side = min(w, h)
    return f'{side}:{side}:{x + (w - side) // 2}:{y + (h - side) // 2}'


async def encode(src: Path, dst: Path, crop: str, crf: int) -> None:
    proc = await asyncio.create_subprocess_exec(
        'ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-i', str(src),
        '-t', '10', '-an',
        '-vf', f'crop={crop},scale=800:800:flags=lanczos,fps=30,format=yuv420p',
        '-c:v', 'libx264', '-preset', 'slow', '-crf', str(crf),
        '-movflags', '+faststart', str(dst),
        stderr=asyncio.subprocess.PIPE,
    )
    _, err = await proc.communicate()
    if proc.returncode != 0:
        raise RuntimeError(err.decode(errors='replace')[-300:])


@router.message(F.video | F.animation | F.document)
async def make_avatar(message: Message, bot: Bot) -> None:
    if message.document and not (message.document.mime_type or '').startswith('video/'):
        return
    media = message.video or message.animation or message.document
    status = await message.answer('Converting, give me a few seconds.')
    with tempfile.TemporaryDirectory() as tmp:
        src = Path(tmp) / 'input'
        dst = Path(tmp) / 'avatar.mp4'
        await bot.download(media, destination=src)
        crop = await detect_crop(src)
        for crf in (26, 30, 34):
            await encode(src, dst, crop, crf)
            if dst.stat().st_size <= MAX_BYTES:
                break
        else:
            await status.edit_text('Could not fit this clip under 2 MB.')
            return
        await message.answer_video(
            BufferedInputFile(dst.read_bytes(), filename='avatar.mp4'),
            supports_streaming=True,
        )
    await status.delete()
Enter fullscreen mode Exit fullscreen mode

The filter on the router matches all three input types, and the MIME check keeps random documents from triggering a conversion. The crop function takes the shorter side of the detected rectangle and centers the square inside it.

Packaging it as @liveavabot

I wrapped this in a bot so you can send a clip and get back an MP4 you can save and set as your profile video in the Telegram app. Send @LiveAvaBot a video or GIF and it returns the converted file.

Lessons, edge cases, and what's next

The numbers are small, so here they are. The bot has 557 users so far. In the last 24 hours, one person converted a clip, and revenue from Telegram Stars is still zero. I'd rather say that plainly than dress it up.

Edge cases I've hit: screen recordings with a status bar, which cropdetect sometimes treats as part of the picture. Very dark clips where cropdetect latches onto nothing and returns the full frame. Phone footage with a burst of 60 fps at the start, which the fps filter handles but makes the file a bit bigger. Rotated Android clips where the rotation sits in side data rather than the container tag. ffmpeg handles most of these in my testing, but I've had to loosen the cropdetect limit for dark footage.

Next up: a trim step so people can pick which 10 seconds to keep, instead of always getting the first ten. I also want a cleaner error path for files cropdetect can't parse. 4K input takes noticeably longer to decode, and I haven't tuned for it yet.

Built by me, @liveavabot. If you hit a clip it chokes on, send me the ffprobe output and I'll look at why.

Top comments (0)