Format Normalisation & Validation Internals¶
GET /v1/media/convert takes two format strings — source_format and target_format — and the service does no content sniffing whatsoever. It normalises the strings, checks them against two frozen tables (ALLOWED_*_CONVERSIONS, BLOCKED_FORMATS), and only then downloads anything. This page documents that contract precisely enough to predict the HTTP status of any request without making it.
For the endpoint itself see Media Convert Reference. For the human-readable pair table see Conversion Matrix.
Base URL¶
https://media.toolkitapi.io
Availability: the standalone Media service (
apis/media) is implemented but not yet deployed. The behaviour below is the shipped contract; treat it as authoritative for clients.
Normalisation¶
Both values go through the same three-step function before any check:
def _normalise(fmt: str) -> str:
return fmt.lower().strip().lstrip(".")
| Input | Normalised |
|---|---|
" MP4 " |
mp4 |
".MOV" |
mov |
"..webm" |
webm (all leading dots stripped) |
"MP3 " |
mp3 |
"wav" |
wav |
Consequences worth knowing:
- Case never matters.
FLAC,Flac,flacare the same target. - Whitespace around the value is ignored, so values pasted from a filename extension (
.mp3) work as-is. - Internal whitespace or dots are not removed:
"m p4"stays"m p4"and fails as an unknown source. - There is no MIME-type support.
audio/mpegis not accepted — usemp3.
Validation order¶
The checks run in this exact order and the first failure wins. A request that is wrong four different ways only tells you about the first one.
| # | Check | Failure status | detail shape |
|---|---|---|---|
| 1 | src == tgt |
400 |
Source and target formats are the same: 'mp4' |
| 2 | src in BLOCKED_FORMATS |
400 |
Blocked reason, e.g. H.265/HEVC encoding requires GPU acceleration — not supported |
| 3 | tgt in BLOCKED_FORMATS |
400 |
Same reason map |
| 4 | src has no entry in the conversion table |
400 |
Unsupported source format: 'xyz'. Supported: [...] |
| 5 | tgt not in the allow-list for src |
400 |
Cannot convert 'mp4' → 'flac'. Allowed targets for 'mp4': [...] |
Two practical implications:
- Equality is checked before blocked-ness.
source_format=h265&target_format=h265returns the "same format" message, not the GPU message. - Source is checked before target.
source_format=zip&target_format=h265reports the blocked source (zip), even though both are blocked.
Allow-lists are rendered with sorted() in every message, so the order is always alphabetical (ASCII: aac, aiff, ac3, …).
All five checks happen before the URL is fetched or validated, so every 400 above costs zero bandwidth and zero transcode time — a 400 never means "your URL is bad".
Blocked formats¶
BLOCKED_FORMATS is a global deny-list applied to both sides of the conversion:
| Format | Reason returned |
|---|---|
asf |
ASF container uses proprietary codecs — not supported |
hevc, h265 |
H.265/HEVC encoding requires GPU acceleration — not supported |
av1 |
AV1 encoding is too slow on CPU for API use — not supported |
mxf |
MXF is a professional broadcast format — not supported |
r3d |
RED RAW files require proprietary SDK — not supported |
braw |
Blackmagic RAW files require proprietary SDK — not supported |
exe, bat, sh, ps1, cmd, msi, dll, so |
Format not supported |
zip, tar, gz, 7z, rar |
Format not supported |
Anything not in this list and present as a key in the conversion table is a valid source. Note that zip-family and executable extensions are rejected as formats, which is the cheap defence against pointing the service at arbitrary archives.
The two conversion tables¶
Sources are split into video and audio tables, merged into one lookup:
Video sources — mp4, webm, mov, avi, mkv, gif, flv, mpeg, mpg, mts, m2ts, 3gp, 3g2, ts, vob, m4v, ogv, wmv.
mp4→webm, gif, mp3, wav, ogg, aviwebm→mp4, gif, mp3, wav, oggmov→mp4, webm, gif, mp3, wavavi→mp4, webm, gif, mp3mkv→mp4, webm, gif, mp3gif→mp4, webm- The rest (
flv,mpeg,mpg,mts,m2ts,3gp,3g2,ts,vob,m4v,ogv,wmv) →mp4, webm, gif, mp3, wav
Audio sources — mp3, wav, ogg, flac, aac, m4a, aiff, aif, ac3, amr, au, caf, weba, m4b, wma.
- Any of
mp3,wav,ogg,flac,aac,m4a→ the other five of that core set aiff,aif,ac3,amr,au,caf,weba,m4b,wma→ all six core formats (mp3, wav, ogg, flac, aac, m4a)
Because mp4 appears in both the video and audio allow-lists (mp3 is a legal target of mp4), the merged table means you can go video → audio in one hop but never audio → video.
Extension-only validation and its failure mode¶
Validation reads strings, not bytes. A file named .mp4 that actually holds a ZIP archive passes checks 1–5, gets downloaded (up to 100 MB), and then explodes inside FFmpeg:
| Situation | Status | detail |
|---|---|---|
| Recognised pair, corrupt/mislabelled payload | 500 |
FFmpeg conversion failed: <first 500 chars of FFmpeg stderr> |
| Recognised pair, source host 404/500 | 502 |
Failed to download source file |
| Recognised pair, FFmpeg binary absent | 503 |
— |
A 500 here is terminal — retrying the same URL will fail identically. If you control the pipeline, verify the container before submitting:
ffprobe -v error -show_entries format=format_name -of default=nw=1 input.mp4
# format_name=mov,mp4,m4a,3gp,3g2,mj2
If ffprobe says zip or errors out, the file is mislabelled and the API will return 500.
Examples¶
Normalise client-side before sending¶
Strip the dot and lower-case the extension you already have, so you never trip checks 4–5 by accident.
EXT="${FILE##*.}" # "MP4"
FMT=$(echo "$EXT" | tr '[:upper:]' '[:lower:]') # "mp4"
curl -L "https://media.toolkitapi.io/v1/media/convert?url=$(python3 -c 'import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=""))' "$SRC_URL")&source_format=$FMT&target_format=mp3" \
-H "X-API-Key: $MEDIA_API_KEY" \
-o out.mp3
from pathlib import Path
def ext_of(url_or_name: str) -> str:
return Path(url_or_name.split("?")[0]).suffix.lower().lstrip(".")
resp = httpx.get(
"https://media.toolkitapi.io/v1/media/convert",
headers={"X-API-Key": MEDIA_API_KEY},
params={
"url": "https://cdn.example.com/webinar.MOV?token=abc",
"source_format": ext_of("https://cdn.example.com/webinar.MOV?token=abc"), # "mov"
"target_format": "mp4",
},
follow_redirects=True,
timeout=httpx.Timeout(60.0, read=300.0),
)
const extOf = (url) =>
new URL(url).pathname.split(".").pop().toLowerCase().replace(/^\.+/, "");
const params = new URLSearchParams({
url: "https://cdn.example.com/webinar.MOV",
source_format: extOf("https://cdn.example.com/webinar.MOV"), // "mov"
target_format: "mp4",
});
const res = await fetch(`https://media.toolkitapi.io/v1/media/convert?${params}`, {
headers: { "X-API-Key": process.env.MEDIA_API_KEY },
});
if (!res.ok) {
const { detail } = await res.json();
throw new Error(`convert failed ${res.status}: ${detail}`);
}
Mirror the validation locally (fail fast, save a request)¶
This reproduces checks 1–5 exactly, including the normalisation, so you can reject bad pairs without network I/O.
CORE_AUDIO = {"mp3", "wav", "ogg", "flac", "aac", "m4a"}
VIDEO_CORE = {"mp4", "webm", "gif", "mp3", "wav"}
VIDEO = {
"mp4": {"webm", "gif", "mp3", "wav", "ogg", "avi"},
"webm": {"mp4", "gif", "mp3", "wav", "ogg"},
"mov": {"mp4", "webm", "gif", "mp3", "wav"},
"avi": {"mp4", "webm", "gif", "mp3"},
"mkv": {"mp4", "webm", "gif", "mp3"},
"gif": {"mp4", "webm"},
**{k: VIDEO_CORE for k in
("flv", "mpeg", "mpg", "mts", "m2ts", "3gp", "3g2", "ts", "vob", "m4v", "ogv", "wmv")},
}
AUDIO = {k: CORE_AUDIO - {k} for k in CORE_AUDIO}
AUDIO.update({k: CORE_AUDIO for k in
("aiff", "aif", "ac3", "amr", "au", "caf", "weba", "m4b", "wma")})
TABLE = {**VIDEO, **AUDIO}
BLOCKED = {"asf", "hevc", "h265", "av1", "mxf", "r3d", "braw",
"exe", "bat", "sh", "ps1", "cmd", "msi", "dll", "so",
"zip", "tar", "gz", "7z", "rar"}
def normalise(fmt: str) -> str:
return fmt.lower().strip().lstrip(".")
def check(src_fmt: str, tgt_fmt: str) -> str | None:
"""Return None if the pair is valid, else the detail string the API would return."""
src, tgt = normalise(src_fmt), normalise(tgt_fmt)
if src == tgt:
return f"Source and target formats are the same: '{src}'"
if src in BLOCKED:
return "Format not supported"
if tgt in BLOCKED:
return "Format not supported"
allowed = TABLE.get(src)
if allowed is None:
return f"Unsupported source format: '{src}'."
if tgt not in allowed:
return f"Cannot convert '{src}' → '{tgt}'. Allowed targets for '{src}': {sorted(allowed)}"
return None
assert check(".MOV ", "mp4") is None
assert "Allowed targets" in check("mp4", "flac")
assert check("zip", "h265") == "Format not supported" # blocked source wins over blocked target
assert "same" in check("h265", "h265") # equality is checked first
Probe allowed targets without downloading¶
Send any known-invalid target; the 400 enumerates the whole allow-list for the source.
curl -s "https://media.toolkitapi.io/v1/media/convert?url=https%3A%2F%2Fexample.com%2Fx.webm&source_format=webm&target_format=__probe__" \
-H "X-API-Key: $MEDIA_API_KEY" | jq -r .detail
# Cannot convert 'webm' → '__probe__'. Allowed targets for 'webm': ['gif', 'mp3', 'mp4', 'ogg', 'wav']
const res = await fetch(
"https://media.toolkitapi.io/v1/media/convert?" +
new URLSearchParams({ url: "https://example.com/x.webm", source_format: "webm", target_format: "__probe__" }),
{ headers: { "X-API-Key": process.env.MEDIA_API_KEY } }
);
const { detail } = await res.json(); // res.status === 400
const allowed = JSON.parse(detail.split(": ").pop().replace(/'/g, '"'));
console.log(allowed); // ['gif','mp3','mp4','ogg','wav']
Errors¶
| Status | Meaning | Retry? |
|---|---|---|
400 |
Any of checks 1–5 failed | No |
401 |
Missing/invalid X-API-Key |
No |
422 |
A required query parameter is missing entirely | No |
500 |
FFmpeg rejected the payload (mislabelled/corrupt) | No |
502 |
Source download failed | Only for transients |
503 |
FFmpeg not installed on the host | Retry later |
Related¶
- Media Convert Reference — endpoint, headers, streaming
- Conversion Matrix — full pair table
- Format Matrix — MIME types per format