{"record":{"id":"c5d82f4e3a6a14dc","repo":"unslothai/unsloth","slug":"invalid-base64-media-data-exc","errorCode":null,"errorMessage":"Invalid base64 media data: {exc}","messagePattern":"Invalid base64 media data: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"studio/backend/core/inference/video.py","lineNumber":421,"sourceCode":"\n# Enough for a 15-second reference video after base64 decoding.\n_MAX_REFERENCE_MEDIA_BYTES = 96 * 1024 * 1024\n\n\ndef _decode_b64_media(data: Optional[str]) -> bytes:\n    \"\"\"Decode a base64 media payload, optionally wrapped in a data URL.\"\"\"\n    import base64\n    import binascii\n\n    raw = (data or \"\").strip()\n    if not raw:\n        raise ValueError(\"A reference was sent empty.\")\n    if raw.startswith(\"data:\"):\n        _, _, raw = raw.partition(\",\")\n    try:\n        blob = base64.b64decode(raw, validate = False)\n    except (binascii.Error, ValueError) as exc:\n        raise ValueError(f\"Invalid base64 media data: {exc}\") from exc\n    if not blob:\n        raise ValueError(\"A reference decoded to no data.\")\n    if len(blob) > _MAX_REFERENCE_MEDIA_BYTES:\n        raise ValueError(\n            f\"A reference is too large ({len(blob) / 1e6:.0f} MB); the limit is \"\n            f\"{_MAX_REFERENCE_MEDIA_BYTES / 1e6:.0f} MB.\"\n        )\n    return blob\n\n\nclass _VideoGenerationCancelled(Exception):\n    \"\"\"Unwinds a denoise loop that has no cooperative interrupt (no step callback);\n    generate() maps it to the VIDEO_CANCELLED_MSG sentinel the routes 409 on.\"\"\"\n\n\n@contextlib.contextmanager\ndef _scheduler_step_progress(pipe: Any, on_step: Any):\n    \"\"\"Progress + cancellation for pipelines WITHOUT callback_on_step_end.","sourceCodeStart":403,"sourceCodeEnd":439,"githubUrl":"https://github.com/unslothai/unsloth/blob/203007d19051dcd2ae33876786d117c99f6b0368/studio/backend/core/inference/video.py#L403-L439","documentation":"base64.b64decode raised binascii.Error/ValueError while decoding the reference media payload, and _decode_b64_media re-wraps it as ValueError with the underlying reason. validate=False means only genuinely malformed input (wrong length, non-base64 alphabet characters after the data: prefix split) triggers this.","triggerScenarios":"Sending a reference that is not valid base64: raw binary bytes, a URL-encoded file, truncated base64, or a data URL whose header portion contains characters outside the base64 alphabet because partition(',') split at the wrong comma.","commonSituations":"Reading a file as text instead of base64-encoding it; double-encoding or half-decoding in a proxy; hand-truncated payloads in tests; a data URL with a comma inside the MIME parameters.","solutions":["Encode the media properly: base64.b64encode(open(file,'rb').read()).decode('ascii').","For data URLs, keep the standard form 'data:<mime>;base64,<payload>' so partition(',') finds the right split.","Validate with a client-side b64decode before sending."],"exampleFix":"# before\npayload['reference_video'] = raw_bytes.decode('latin-1')  # not base64\n\n# after\nimport base64\npayload['reference_video'] = base64.b64encode(raw_bytes).decode('ascii')","handlingStrategy":"validation","validationCode":"import base64, binascii\n\ndef is_valid_b64(ref: str | None) -> bool:\n    if not ref or not ref.strip():\n        return False\n    raw = ref.strip()\n    if raw.startswith('data:'):\n        raw = raw.partition(',')[2]\n    try:\n        return len(base64.b64decode(raw)) > 0\n    except (binascii.Error, ValueError):\n        return False","typeGuard":"def is_b64_media(value: str) -> bool:\n    raw = value.strip()\n    if raw.startswith('data:'):\n        raw = raw.partition(',')[2]\n    try:\n        base64.b64decode(raw)\n        return True\n    except (binascii.Error, ValueError):\n        return False","tryCatchPattern":"try:\n    blob = _decode_b64_media(ref)\nexcept ValueError as e:\n    if 'Invalid base64' in str(e):\n        raise UserPayloadError(f'bad reference encoding: {e}') from e\n    raise","preventionTips":["Always encode binary media with base64.b64encode(...).decode('ascii').","Use the canonical 'data:<mime>;base64,<payload>' shape so the comma split is unambiguous.","Run a client-side b64decode round-trip before sending."],"tags":["video","base64","reference-media","payload"],"backgroundTag":null,"analyzedSha":"203007d19051dcd2ae33876786d117c99f6b0368","analyzedAt":"2026-08-15T02:48:39.846Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}