Media Conversion Error Handling & Troubleshooting

Availability note: GET /v1/convert/media is not currently routed on the live Convert service. The handler still exists (apis/convert/app/routers/media_convert_core.py) and is exercised by unit tests, but apis/convert/app/main.py no longer calls include_router(media_convert.router), so the path returns 404 on https://convert.toolkitapi.io. Media transcoding is being consolidated into the standalone Media service (GET /v1/media/convert, see Media Conversion), which is not yet deployed. The error semantics below remain the reference for both handlers because they share _media_shared and the same fetch/FFmpeg helpers.

GET /v1/convert/media is a single endpoint with a lot of ways to fail — and most of them fail before FFmpeg ever runs. This page is the error reference: what each status means, which failures are worth retrying, and why your 2 MB GIF request came back as a 400.

For the conversion matrix and supported pairs, see Conversion Matrix Reference. For the request shape, see Media Conversion.

Base URL: https://convert.toolkitapi.io

GET /v1/convert/media?url=<encoded>&source_format=<fmt>&target_format=<fmt>

Three query parameters, all required. Auth via X-API-Key. The success response is the file — a 200 streams bytes with Content-Disposition: attachment. There is no JSON success body.


1. Error reference

Status detail shape Retry? Real cause
400 Cannot convert 'mp4' → 'flac'. Supported targets for 'mp4': [...] No Pair not in the matrix
400 Source and target are the same format ('mp4'). Nothing to convert. No source_format == target_format after normalisation
400 Unsupported source format: 'xyz'. Accepted: [...] No Source is not a known media format
400 H.265/HEVC encoding requires GPU acceleration — not supported No Format is on the explicit blocklist
400 Downloaded content exceeds maximum size of 10 MB No Source file too large for the fetch limit
400 URL validation message No Non-http(s) scheme, or a private/internal address
502 Failed to download source file Yes Origin refused, 404'd, TLS-failed, or redirect-looped
503 FFmpeg is not installed on this server — media conversion is unavailable Yes (later) Node lacks FFmpeg; transient infra issue
500 Runtime error from FFmpeg Maybe Corrupt input, codec not compiled in, OOM

The most important line: 502 is the only broadly retryable client-side failure. Everything 400 is deterministic — retrying just burns quota.


2. The 400s, one by one

2a. Unsupported pair

The matrix is directional. mp4 → gif works; gif → mp4 works; but gif → mp3 does not (gif only reaches {mp4, webm}). Audio extraction requires a video source:

# inside the API's format map
# gif:  {mp4, webm}
# mp4:  {webm, gif, mp3, wav, ogg, avi}

Note also that several formats are decode-only sources — wmv and wma appear as source keys but never as targets. You can convert from WMV/WMA, never to them.

2b. Same-format requests

Formats are normalised (lowercased, trimmed, leading dot stripped) before comparison, so ".MP4" → "mp4" and source_format=mp4&target_format=.MP4 fails with the same-format 400. If you want to re-encode for compression, the API has no re-encode path — pick a different target.

2c. The blocklist

These are rejected with a specific reason before the matrix lookup:

Format Reason returned
hevc, h265 Requires GPU acceleration
av1 Too slow on CPU for API use
asf Proprietary codecs
mxf Professional broadcast format
r3d, braw Require a proprietary SDK
arw, cr2, cr3, nef, dng Camera RAW
exe, bat, sh, ps1, cmd, msi, dll, so Executables
zip, tar, gz, 7z, rar Archives

Note the mismatch: hevc is blocked, but mkv (which often contains HEVC) is allowed as a source. An HEVC-in-MKV file will pass validation and then fail inside FFmpeg with a 500. Validate your codec, not just the container.


3. The two silent killers

3a. The 1 MB-ish download cap — 10 MB actually

fetch_url_content enforces:

MAX_DOWNLOAD_SIZE = 10 * 1024 * 1024   # 10 MB
_FETCH_TIMEOUT    = 15                 # seconds

Ten megabytes is tiny for video. A 30-second 1080p MP4 is 30–60 MB. Anything over 10 MB returns a clean 400 Downloaded content exceeds maximum size of 10 MB — which is at least honest. But note the ordering: the whole file is downloaded into memory first, then measured. A slow 9 MB fetch spends your 15 s budget on network, leaving nothing for the download check.

Design implication: the endpoint is for short clips, previews, and audio extracts — not for transcoding user uploads. For anything larger, split client-side or use a direct upload path.

3b. The 15 s combined fetch timeout

_FETCH_TIMEOUT = 15 applies to the entire httpx GET, including redirects (up to 5 are followed for presigned S3/CDN URLs). A 12 MB file on a 5 Mbit/s CDN link takes ~19 s — you get 502 Failed to download source file even though the origin is perfectly healthy.

Mitigations:

  • Serve sources from the same cloud region as the API.
  • Pre-generate a short-lived presigned URL that skips redirect chains.
  • Use HEAD-able, fast, static hosting, not an application endpoint that streams from cold storage.

4. The SSRF guard

url is validated before any fetch. Rejected:

Range Blocked range
Private 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
Loopback 127.0.0.0/8, ::1
Link-local 169.254.0.0/16, fe80::/10
Unique-local IPv6 fc00::/7

Schemes other than http/https are rejected, and the guard fails closed — an unparseable URL is a 400, not a pass. You cannot convert from localhost, an S3 endpoint addressed by private IP, or 169.254.169.254.

Practical consequence: your source must be reachable over the public internet. Upload to S3/CloudFront/R2 with a signed public URL rather than pointing at an internal file server.


5. A retry-safe client

Only 502 (and 503) deserve a retry. Everything else should surface immediately with the detail string — it is written for humans and says exactly what to fix.

import time
import requests

BASE = "https://convert.toolkitapi.io/v1/convert/media"
HEADERS = {"X-API-Key": "YOUR_KEY"}
RETRYABLE = {502, 503}

def convert(url: str, src: str, tgt: str, out: str, attempts: int = 3) -> None:
    for attempt in range(1, attempts + 1):
        resp = requests.get(
            BASE,
            headers=HEADERS,
            params={"url": url, "source_format": src, "target_format": tgt},
            stream=True,
            timeout=(10, 300),   # connect 10 s, read up to 300 s for transcode + stream
        )

        if resp.status_code == 200:
            with open(out, "wb") as fh:
                for chunk in resp.iter_content(chunk_size=1 << 16):
                    fh.write(chunk)
            return

        if resp.status_code in RETRYABLE and attempt < attempts:
            time.sleep(2 ** attempt)
            continue

        # 400s: deterministic — do not retry
        raise RuntimeError(f"{resp.status_code}: {resp.json().get('detail')}")

    raise RuntimeError("exhausted retries")
async function convert(url, sourceFormat, targetFormat) {
  const qs = new URLSearchParams({ url, source_format: sourceFormat, target_format: targetFormat });

  for (let attempt = 1; attempt <= 3; attempt++) {
    const resp = await fetch(`https://convert.toolkitapi.io/v1/convert/media?${qs}`, {
      headers: { "X-API-Key": "YOUR_KEY" },
    });

    if (resp.ok) return Buffer.from(await resp.arrayBuffer());

    const body = await resp.json().catch(() => ({}));
    if ([502, 503].includes(resp.status) && attempt < 3) {
      await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
      continue;
    }
    throw new Error(`${resp.status}: ${body.detail ?? "unknown"}`);
  }
}

Set a read timeout, not just a connect timeout. Transcoding a 10 MB video can take tens of seconds; a 30 s overall timeout will abort mid-stream and leave you a truncated file.


6. Recipes

Animated GIF that doesn't look like mud

GIF output is forced to fps=12, scale=480:-1:flags=lanczos, loop 0. You cannot change these — so choose your source resolution accordingly. Feed a 4K clip and it is downscaled to 480 px wide; feed a ≤ 480 px clip and you get a 1:1 result.

# Short, already-small clip → best GIF quality
curl -L "https://convert.toolkitapi.io/v1/convert/media?url=$(python3 -c 'import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1]))' 'https://cdn.example.com/preview.mp4')&source_format=mp4&target_format=gif" \
  -H "X-API-Key: YOUR_KEY" \
  -o preview.gif

Keep the source under ~5 s: at 12 fps that is ~60 frames, and GIF's 256-colour palette degrades badly on long, high-motion clips. For anything longer, MP4 or WebM is the right answer.

Audio extraction

mp4 → mp3 (LAME VBR -q:a 2, ~190 kbps) is the best default. mp3 → wav gives pcm_s16le PCM for downstream analysis. All audio targets strip video (-vn), so mp4 → mp3 costs nothing extra.

Note amr and au are fixed at 8 kHz mono — telephony formats. Don't route music through them.

WebM for the web

webm targets VP9 + Opus with deadline=realtime, cpu-used=5 — deliberately fast at the cost of compression efficiency, so that the request finishes inside the timeout. Expect larger files than a hand-tuned libvpx-vp9 encode. For archiving, mp4 (H.264 + AAC with +faststart) is more efficient.


7. Preflight checklist

Before you send a request, check these locally — each maps to a distinct 400:

BLOCKED = {
    "asf", "hevc", "h265", "av1", "mxf", "r3d", "braw", "arw", "cr2", "cr3",
    "nef", "dng", "exe", "bat", "sh", "ps1", "cmd", "msi", "dll", "so",
    "zip", "tar", "gz", "7z", "rar",
}

def preflight(url: str, src: str, tgt: str, size_bytes: int | None = None) -> list[str]:
    problems = []
    if not url.lower().startswith(("http://", "https://")):
        problems.append("url must be http(s) — the API rejects other schemes")
    if src.lower() == tgt.lower():
        problems.append(f"source_format and target_format are both {src!r}")
    if src.lower() in BLOCKED:
        problems.append(f"{src} is on the API blocklist")
    if tgt.lower() in BLOCKED:
        problems.append(f"{tgt} is on the API blocklist")
    if size_bytes and size_bytes > 10 * 1024 * 1024:
        problems.append(f"source is {size_bytes/1e6:.1f} MB; the fetch limit is 10 MB")
    return problems

Run HEAD on the source first to get Content-Length and catch the size problem before spending a conversion:

head = requests.head(url, allow_redirects=True, timeout=10)
size = int(head.headers.get("Content-Length", 0)) or None
if problems := preflight(url, src, tgt, size):
    raise ValueError(problems)