File size: 7,111 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# SPDX-License-Identifier: Apache-2.0
"""Decoding of request media (untrusted bytes): images (PNG / JPEG / WebP / BMP / GIF via Pillow, bounded pixel
count), audio (WAV PCM 8/16/24/32-bit or IEEE float via the standard library; FLAC / OGG / MP3 when ``soundfile`` is
installed; raw little-endian float32 PCM), video (a list of frames; a container file when PyAV is installed).
Standard library + numpy + Pillow (+ optional soundfile / av)."""

from __future__ import annotations

import base64
import binascii
import io
import struct
from typing import Any, Dict, List, Optional, Tuple

import numpy as np

MAX_IMAGE_PIXELS = 64_000_000          # decompression-bomb guard (8000 x 8000)
MAX_AUDIO_SECONDS_IN = 600.0           # longer uploads are refused before decoding (the model uses 30 s)


class MediaError(ValueError):
    pass


def b64bytes(s: str, what: str) -> bytes:
    if not isinstance(s, str):
        raise MediaError(f"{what}: expected a base64 string")
    if s.startswith("data:"):
        if "," not in s:
            raise MediaError(f"{what}: malformed data URL")
        s = s.split(",", 1)[1]
    try:
        return base64.b64decode(s, validate=False)
    except (binascii.Error, ValueError) as e:
        raise MediaError(f"{what}: invalid base64 ({e})") from None


def decode_image(data: bytes):
    """-> RGB PIL image (transparency composited onto white, as the official processor does)."""
    from PIL import Image

    Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
    try:
        im = Image.open(io.BytesIO(data))
        if im.width * im.height > MAX_IMAGE_PIXELS:
            raise MediaError(f"image has {im.width}x{im.height} pixels (> {MAX_IMAGE_PIXELS})")
        im.load()
        from .preprocess.image import to_rgb_pil

        return to_rgb_pil(im)
    except MediaError:
        raise
    except Exception as e:  # noqa: BLE001 -- PIL raises many types on corrupt input
        raise MediaError(f"cannot decode image: {type(e).__name__}: {e}") from None


def _wav(data: bytes) -> Tuple[np.ndarray, int]:
    """Minimal RIFF/WAVE reader: PCM 8/16/24/32-bit and IEEE float 32/64, any channel count (mixed to mono)."""
    if len(data) < 12 or data[:4] != b"RIFF" or data[8:12] != b"WAVE":
        raise MediaError("not a RIFF/WAVE file")
    pos, fmt, raw = 12, None, None
    while pos + 8 <= len(data):
        cid, size = data[pos:pos + 4], struct.unpack("<I", data[pos + 4:pos + 8])[0]
        body = data[pos + 8: pos + 8 + size]
        if cid == b"fmt ":
            if len(body) < 16:
                raise MediaError("WAV fmt chunk too short")
            tag, ch, sr, _br, _ba, bits = struct.unpack("<HHIIHH", body[:16])
            if tag == 0xFFFE and len(body) >= 26:
                tag = struct.unpack("<H", body[24:26])[0]
            fmt = (tag, ch, sr, bits)
        elif cid == b"data":
            raw = body
        pos += 8 + size + (size & 1)
    if fmt is None or raw is None:
        raise MediaError("WAV without fmt / data chunk")
    tag, ch, sr, bits = fmt
    if ch < 1 or sr < 1000:
        raise MediaError(f"WAV: {ch} channels at {sr} Hz")
    if tag == 1:
        if bits == 8:
            x = (np.frombuffer(raw, np.uint8).astype(np.float32) - 128.0) / 128.0
        elif bits == 16:
            x = np.frombuffer(raw[: len(raw) // 2 * 2], "<i2").astype(np.float32) / 32768.0
        elif bits == 24:
            b = np.frombuffer(raw[: len(raw) // 3 * 3], np.uint8).reshape(-1, 3).astype(np.int32)
            v = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
            v = np.where(v >= 1 << 23, v - (1 << 24), v)
            x = v.astype(np.float32) / float(1 << 23)
        elif bits == 32:
            x = np.frombuffer(raw[: len(raw) // 4 * 4], "<i4").astype(np.float32) / float(1 << 31)
        else:
            raise MediaError(f"WAV PCM {bits}-bit unsupported")
    elif tag == 3:
        dt = {32: "<f4", 64: "<f8"}.get(bits)
        if dt is None:
            raise MediaError(f"WAV float {bits}-bit unsupported")
        x = np.frombuffer(raw[: len(raw) // (bits // 8) * (bits // 8)], dt).astype(np.float32)
    else:
        raise MediaError(f"WAV format tag {tag} unsupported (PCM or IEEE float only)")
    n = len(x) // ch * ch
    x = x[:n].reshape(-1, ch).mean(axis=1)
    return x.astype(np.float32), int(sr)


def decode_audio(data: bytes, fmt: Optional[str] = None, sampling_rate: Optional[int] = None
                 ) -> Tuple[np.ndarray, int]:
    """-> (mono float32 waveform, sampling rate)."""
    if fmt == "pcm_f32le":
        if not sampling_rate:
            raise MediaError("raw pcm_f32le audio needs sampling_rate")
        x = np.frombuffer(data[: len(data) // 4 * 4], "<f4").astype(np.float32)
        sr = int(sampling_rate)
    elif data[:4] == b"RIFF":
        x, sr = _wav(data)
    else:
        try:
            import soundfile as sf
        except ImportError:
            raise MediaError("only WAV and raw pcm_f32le audio are supported in this container (soundfile missing)") \
                from None
        try:
            x, sr = sf.read(io.BytesIO(data), dtype="float32", always_2d=True)
            x = x.mean(axis=1)
        except Exception as e:  # noqa: BLE001
            raise MediaError(f"cannot decode audio: {type(e).__name__}: {e}") from None
    if len(x) > MAX_AUDIO_SECONDS_IN * sr:
        raise MediaError(f"audio longer than {MAX_AUDIO_SECONDS_IN:g} s")
    if not np.isfinite(x).all():
        raise MediaError("audio contains NaN / inf")
    return x, int(sr)


def decode_video_file(data: bytes, max_frames_decoded: int = 3600) -> Dict[str, Any]:
    """Container file (mp4 / webm / ...) -> dict(frames, fps, duration); needs PyAV."""
    try:
        import av
    except ImportError:
        raise MediaError("video files need PyAV (not installed): send decoded frames instead "
                         "({'type': 'video', 'frames': [base64 images], 'fps': ...})") from None
    try:
        c = av.open(io.BytesIO(data))
        st = c.streams.video[0]
        fps = float(st.average_rate) if st.average_rate else None
        frames = []
        for fr in c.decode(st):
            frames.append(fr.to_ndarray(format="rgb24"))
            if len(frames) >= max_frames_decoded:
                break
        c.close()
    except Exception as e:  # noqa: BLE001
        raise MediaError(f"cannot decode video: {type(e).__name__}: {e}") from None
    if not frames:
        raise MediaError("video has no frames")
    dur = len(frames) / fps if fps else None
    return {"frames": frames, "fps": fps, "duration": dur}


def decode_frames(frames: List[str], what: str = "video") -> List[np.ndarray]:
    out = []
    shape = None
    for i, f in enumerate(frames):
        im = np.asarray(decode_image(b64bytes(f, f"{what} frame {i}")), dtype=np.uint8)
        if shape is None:
            shape = im.shape
        elif im.shape != shape:
            raise MediaError(f"{what} frame {i} is {im.shape[1]}x{im.shape[0]}, frame 0 is {shape[1]}x{shape[0]}")
        out.append(im)
    if not out:
        raise MediaError(f"{what} has no frames")
    return out