uppercut-rawvideo-encoder 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .DS_Store
8
+ uv.lock
9
+ .env*
10
+ *.pem
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-rawvideo-encoder
3
+ Version: 0.1.0
4
+ Summary: Pipe RGB frames from Pillow renders to ffmpeg as H.264, and check that ffmpeg succeeded.
5
+ Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-rawvideo-encoder
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ Keywords: ffmpeg,frames,pillow,rawvideo,render,x264
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Multimedia :: Video
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: pillow>=10
20
+ Description-Content-Type: text/markdown
21
+
22
+ # uppercut-rawvideo-encoder
23
+
24
+ Pipes RGB frames from a Pillow (or numpy) render into ffmpeg, which writes H.264 in yuv420p. It checks ffmpeg's exit code and raises with the end of ffmpeg's error output, so a failed encode is an exception instead of the path of a file that was never written. It also carries the two helpers render scripts keep copying: `nearest()` for whole-number pixel upscales and a cached `font()` loader.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ pip install uppercut-rawvideo-encoder
30
+ ```
31
+
32
+ Requires Python 3.10 or newer and Pillow 10 or newer. `ffmpeg` with libx264 must be on your PATH.
33
+
34
+ ## Example
35
+
36
+ ```python
37
+ from PIL import Image, ImageDraw
38
+ from uppercut_rawvideo_encoder import RawVideoEncoder, font, nearest
39
+
40
+ W, H = 1920, 1080
41
+ label = font("C:/Windows/Fonts/consolab.ttf", 48) # loaded once, shared after that
42
+
43
+ with RawVideoEncoder("out.mp4", (W, H), 60, crf=16, preset="medium") as enc:
44
+ for i in range(120):
45
+ sprite = nearest(Image.open("sprite.png").convert("RGB"), 4)
46
+ frame = Image.new("RGB", (W, H))
47
+ frame.paste(sprite, (40 + i * 4, 200))
48
+ ImageDraw.Draw(frame).text((40, 40), f"frame {i}", font=label, fill="white")
49
+ enc.write(frame)
50
+ ```
51
+
52
+ Leaving the `with` block normally finishes the file and raises `EncodeError` if ffmpeg exits with a nonzero code, or if no frame was written. If your own code raises inside the block, ffmpeg is stopped, the partial file is deleted and your exception goes through unchanged.
53
+
54
+ `fps`, `crf` and `preset` have no defaults. Each caller says what it wants, so changing to this package never changes a render's quality, and a video never gets a frame rate nobody chose.
55
+
56
+ ## RawVideoEncoder
57
+
58
+ `RawVideoEncoder(path, size, fps, *, crf, preset, extra_inputs=(), output_args=(), ffmpeg="ffmpeg", tail_bytes=4096)`
59
+
60
+ | Argument | Meaning |
61
+ | --- | --- |
62
+ | `path` | The output file. Its folder must exist. |
63
+ | `size` | `(width, height)` of every frame. |
64
+ | `fps` | Frames per second as an int, float, `Fraction` or `"num/den"` such as `"24000/1001"`. Required. |
65
+ | `crf`, `preset` | The x264 settings. Required. |
66
+ | `extra_inputs` | ffmpeg arguments for more inputs, placed after the frame input. |
67
+ | `output_args` | More ffmpeg output arguments, placed after the x264 settings and before the file name. |
68
+ | `ffmpeg` | The executable, or a command prefix as a list. |
69
+ | `tail_bytes` | How much of ffmpeg's error output goes into `EncodeError`. |
70
+
71
+ | Member | What it does |
72
+ | --- | --- |
73
+ | `write(frame)` | Adds a frame: a Pillow image of the video's size (converted to RGB when it is not), or exactly width x height x 3 bytes, as `bytes` or any object with `tobytes()` such as a numpy array. A wrong size raises `ValueError`. |
74
+ | `close()` | Finishes the file. Raises `EncodeError` on a nonzero exit or when nothing was written. |
75
+ | `abort()` | Stops ffmpeg and deletes the partial file. |
76
+ | `frames` | How many frames have been written. |
77
+ | `command` | The ffmpeg argument list that was run. |
78
+
79
+ The command always carries `-nostdin`, so ffmpeg never reads keystrokes from the terminal, and `-y`, so an existing file is replaced. It reads `rgb24` from stdin at the rate you gave and writes `libx264` with `-pix_fmt yuv420p`.
80
+
81
+ `EncodeError` has `returncode`, `stderr_tail` (the end of ffmpeg's error output) and `frames`. If ffmpeg dies while you are still writing, the next `write` raises it, instead of a bare `BrokenPipeError`. A failed encode deletes its output file.
82
+
83
+ `ffmpeg_command(path, size, fps, *, crf, preset, extra_inputs=(), output_args=(), ffmpeg="ffmpeg")` returns the argument list without running it. `format_fps(fps)` is the text that goes after `-r`.
84
+
85
+ ### A soundtrack
86
+
87
+ ```python
88
+ with RawVideoEncoder(
89
+ "cut.mp4", (1920, 1080), 24, crf=14, preset="slow",
90
+ extra_inputs=["-ss", "12.5", "-t", "30", "-i", "song.wav"],
91
+ output_args=["-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k", "-shortest"],
92
+ ) as enc:
93
+ ...
94
+ ```
95
+
96
+ ## Pixel helpers
97
+
98
+ | Function | What it does |
99
+ | --- | --- |
100
+ | `nearest(img, n)` | Scales an image up by the whole number `n` with no smoothing. |
101
+ | `font(path, size, *, index=0)` | `ImageFont.truetype`, cached by file, size and index. `font.cache_clear()` empties the cache. `index` picks a face inside a `.ttc` collection. |
102
+
103
+ ## License
104
+
105
+ MIT
@@ -0,0 +1,84 @@
1
+ # uppercut-rawvideo-encoder
2
+
3
+ Pipes RGB frames from a Pillow (or numpy) render into ffmpeg, which writes H.264 in yuv420p. It checks ffmpeg's exit code and raises with the end of ffmpeg's error output, so a failed encode is an exception instead of the path of a file that was never written. It also carries the two helpers render scripts keep copying: `nearest()` for whole-number pixel upscales and a cached `font()` loader.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pip install uppercut-rawvideo-encoder
9
+ ```
10
+
11
+ Requires Python 3.10 or newer and Pillow 10 or newer. `ffmpeg` with libx264 must be on your PATH.
12
+
13
+ ## Example
14
+
15
+ ```python
16
+ from PIL import Image, ImageDraw
17
+ from uppercut_rawvideo_encoder import RawVideoEncoder, font, nearest
18
+
19
+ W, H = 1920, 1080
20
+ label = font("C:/Windows/Fonts/consolab.ttf", 48) # loaded once, shared after that
21
+
22
+ with RawVideoEncoder("out.mp4", (W, H), 60, crf=16, preset="medium") as enc:
23
+ for i in range(120):
24
+ sprite = nearest(Image.open("sprite.png").convert("RGB"), 4)
25
+ frame = Image.new("RGB", (W, H))
26
+ frame.paste(sprite, (40 + i * 4, 200))
27
+ ImageDraw.Draw(frame).text((40, 40), f"frame {i}", font=label, fill="white")
28
+ enc.write(frame)
29
+ ```
30
+
31
+ Leaving the `with` block normally finishes the file and raises `EncodeError` if ffmpeg exits with a nonzero code, or if no frame was written. If your own code raises inside the block, ffmpeg is stopped, the partial file is deleted and your exception goes through unchanged.
32
+
33
+ `fps`, `crf` and `preset` have no defaults. Each caller says what it wants, so changing to this package never changes a render's quality, and a video never gets a frame rate nobody chose.
34
+
35
+ ## RawVideoEncoder
36
+
37
+ `RawVideoEncoder(path, size, fps, *, crf, preset, extra_inputs=(), output_args=(), ffmpeg="ffmpeg", tail_bytes=4096)`
38
+
39
+ | Argument | Meaning |
40
+ | --- | --- |
41
+ | `path` | The output file. Its folder must exist. |
42
+ | `size` | `(width, height)` of every frame. |
43
+ | `fps` | Frames per second as an int, float, `Fraction` or `"num/den"` such as `"24000/1001"`. Required. |
44
+ | `crf`, `preset` | The x264 settings. Required. |
45
+ | `extra_inputs` | ffmpeg arguments for more inputs, placed after the frame input. |
46
+ | `output_args` | More ffmpeg output arguments, placed after the x264 settings and before the file name. |
47
+ | `ffmpeg` | The executable, or a command prefix as a list. |
48
+ | `tail_bytes` | How much of ffmpeg's error output goes into `EncodeError`. |
49
+
50
+ | Member | What it does |
51
+ | --- | --- |
52
+ | `write(frame)` | Adds a frame: a Pillow image of the video's size (converted to RGB when it is not), or exactly width x height x 3 bytes, as `bytes` or any object with `tobytes()` such as a numpy array. A wrong size raises `ValueError`. |
53
+ | `close()` | Finishes the file. Raises `EncodeError` on a nonzero exit or when nothing was written. |
54
+ | `abort()` | Stops ffmpeg and deletes the partial file. |
55
+ | `frames` | How many frames have been written. |
56
+ | `command` | The ffmpeg argument list that was run. |
57
+
58
+ The command always carries `-nostdin`, so ffmpeg never reads keystrokes from the terminal, and `-y`, so an existing file is replaced. It reads `rgb24` from stdin at the rate you gave and writes `libx264` with `-pix_fmt yuv420p`.
59
+
60
+ `EncodeError` has `returncode`, `stderr_tail` (the end of ffmpeg's error output) and `frames`. If ffmpeg dies while you are still writing, the next `write` raises it, instead of a bare `BrokenPipeError`. A failed encode deletes its output file.
61
+
62
+ `ffmpeg_command(path, size, fps, *, crf, preset, extra_inputs=(), output_args=(), ffmpeg="ffmpeg")` returns the argument list without running it. `format_fps(fps)` is the text that goes after `-r`.
63
+
64
+ ### A soundtrack
65
+
66
+ ```python
67
+ with RawVideoEncoder(
68
+ "cut.mp4", (1920, 1080), 24, crf=14, preset="slow",
69
+ extra_inputs=["-ss", "12.5", "-t", "30", "-i", "song.wav"],
70
+ output_args=["-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k", "-shortest"],
71
+ ) as enc:
72
+ ...
73
+ ```
74
+
75
+ ## Pixel helpers
76
+
77
+ | Function | What it does |
78
+ | --- | --- |
79
+ | `nearest(img, n)` | Scales an image up by the whole number `n` with no smoothing. |
80
+ | `font(path, size, *, index=0)` | `ImageFont.truetype`, cached by file, size and index. `font.cache_clear()` empties the cache. `index` picks a face inside a `.ttc` collection. |
81
+
82
+ ## License
83
+
84
+ MIT
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-rawvideo-encoder"
7
+ version = "0.1.0"
8
+ description = "Pipe RGB frames from Pillow renders to ffmpeg as H.264, and check that ffmpeg succeeded."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ dependencies = ["Pillow>=10"]
14
+ keywords = ["ffmpeg", "x264", "rawvideo", "pillow", "frames", "render"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Multimedia :: Video",
24
+ "Typing :: Typed",
25
+ ]
26
+
27
+ [project.urls]
28
+ Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-rawvideo-encoder"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/uppercut_rawvideo_encoder"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,14 @@
1
+ """Pipe RGB frames from Pillow renders to ffmpeg as H.264, with an exit-code check, an upscale and a cached font loader."""
2
+
3
+ from ._encoder import EncodeError, RawVideoEncoder, ffmpeg_command, format_fps
4
+ from ._pixels import font, nearest
5
+
6
+ __all__ = [
7
+ "EncodeError",
8
+ "RawVideoEncoder",
9
+ "ffmpeg_command",
10
+ "font",
11
+ "format_fps",
12
+ "nearest",
13
+ ]
14
+ __version__ = "0.1.0"
@@ -0,0 +1,236 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ import subprocess
6
+ import tempfile
7
+ from fractions import Fraction
8
+ from pathlib import Path
9
+ from typing import IO, Any, Sequence, Union
10
+
11
+ from PIL import Image
12
+
13
+ FrameRate = Union[int, float, Fraction, str]
14
+ FfmpegCommand = Union[str, "os.PathLike[str]", Sequence[str]]
15
+
16
+ _FRACTION = re.compile(r"^\d+/\d+$")
17
+
18
+
19
+ class EncodeError(RuntimeError):
20
+ """ffmpeg failed. `returncode` is its exit code (None if it was never started), `stderr_tail` the end of its
21
+ error output and `frames` how many frames had been written."""
22
+
23
+ def __init__(self, message: str, *, returncode: int | None = None, stderr_tail: str = "", frames: int = 0):
24
+ super().__init__(message)
25
+ self.returncode = returncode
26
+ self.stderr_tail = stderr_tail
27
+ self.frames = frames
28
+
29
+
30
+ def format_fps(fps: FrameRate) -> str:
31
+ """The text ffmpeg gets for `-r`. Whole numbers print without a decimal point, so 60.0 becomes `60`."""
32
+ if isinstance(fps, bool):
33
+ raise TypeError("fps must be a number, a Fraction or 'num/den'")
34
+ if isinstance(fps, str):
35
+ text = fps.strip()
36
+ if _FRACTION.match(text):
37
+ num, den = (int(part) for part in text.split("/"))
38
+ if num > 0 and den > 0:
39
+ return text
40
+ raise ValueError(f"fps must be positive, not {fps!r}")
41
+ if isinstance(fps, Fraction):
42
+ if fps <= 0:
43
+ raise ValueError(f"fps must be positive, not {fps}")
44
+ return str(fps.numerator) if fps.denominator == 1 else f"{fps.numerator}/{fps.denominator}"
45
+ if isinstance(fps, (int, float)):
46
+ if not 0 < fps < float("inf"):
47
+ raise ValueError(f"fps must be positive, not {fps!r}")
48
+ return str(int(fps)) if float(fps).is_integer() else repr(float(fps))
49
+ raise TypeError("fps must be a number, a Fraction or 'num/den'")
50
+
51
+
52
+ def _prefix(ffmpeg: FfmpegCommand) -> list[str]:
53
+ if isinstance(ffmpeg, (str, os.PathLike)):
54
+ return [os.fspath(ffmpeg)]
55
+ return [os.fspath(part) for part in ffmpeg]
56
+
57
+
58
+ def ffmpeg_command(
59
+ path: str | os.PathLike[str],
60
+ size: tuple[int, int],
61
+ fps: FrameRate,
62
+ *,
63
+ crf: int | float | str,
64
+ preset: str,
65
+ extra_inputs: Sequence[str] = (),
66
+ output_args: Sequence[str] = (),
67
+ ffmpeg: FfmpegCommand = "ffmpeg",
68
+ ) -> list[str]:
69
+ """The argument list `RawVideoEncoder` runs. Always has `-nostdin` and `-y`, reads rgb24 frames from stdin and
70
+ writes libx264 in yuv420p."""
71
+ width, height = size
72
+ if width <= 0 or height <= 0:
73
+ raise ValueError(f"size must be positive, not {size!r}")
74
+ return [
75
+ *_prefix(ffmpeg),
76
+ "-nostdin", "-y", "-loglevel", "error",
77
+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{width}x{height}", "-r", format_fps(fps), "-i", "-",
78
+ *map(str, extra_inputs),
79
+ "-c:v", "libx264", "-preset", str(preset), "-crf", str(crf), "-pix_fmt", "yuv420p",
80
+ *map(str, output_args),
81
+ os.fspath(path),
82
+ ]
83
+
84
+
85
+ class RawVideoEncoder:
86
+ """Pipes RGB frames to ffmpeg and encodes them as H.264 in yuv420p.
87
+
88
+ Frame rate, crf and preset have no defaults: each caller states the quality it wants.
89
+
90
+ with RawVideoEncoder("out.mp4", (3840, 2160), 60, crf=16, preset="medium") as enc:
91
+ for frame in frames:
92
+ enc.write(frame)
93
+
94
+ Leaving the `with` block normally closes ffmpeg's input and raises `EncodeError` if ffmpeg exits with a nonzero
95
+ code. Leaving it with an exception stops ffmpeg, deletes the partial file and lets your exception through.
96
+
97
+ Args:
98
+ path: The output file.
99
+ size: (width, height) of every frame, in pixels.
100
+ fps: Frames per second, as an int, float, Fraction or "num/den". Required.
101
+ crf, preset: The x264 quality settings. Required.
102
+ extra_inputs: ffmpeg arguments for more inputs, placed after the frame input. For a soundtrack:
103
+ `["-ss", "12.5", "-t", "30", "-i", "song.wav"]`, with `-map 0:v -map 1:a -c:a aac` in `output_args`.
104
+ output_args: More ffmpeg output arguments, placed after the x264 settings and before the file name, such as
105
+ `["-threads", "6", "-movflags", "+faststart"]`.
106
+ ffmpeg: The ffmpeg executable, or a command prefix as a list.
107
+ tail_bytes: How much of ffmpeg's error output an `EncodeError` carries.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ path: str | os.PathLike[str],
113
+ size: tuple[int, int],
114
+ fps: FrameRate,
115
+ *,
116
+ crf: int | float | str,
117
+ preset: str,
118
+ extra_inputs: Sequence[str] = (),
119
+ output_args: Sequence[str] = (),
120
+ ffmpeg: FfmpegCommand = "ffmpeg",
121
+ tail_bytes: int = 4096,
122
+ ):
123
+ self.path = Path(path)
124
+ self.size = (int(size[0]), int(size[1]))
125
+ self.frames = 0
126
+ self._frame_bytes = self.size[0] * self.size[1] * 3
127
+ self._tail_bytes = tail_bytes
128
+ self._done = False
129
+ self.command = ffmpeg_command(
130
+ self.path, self.size, fps, crf=crf, preset=preset,
131
+ extra_inputs=extra_inputs, output_args=output_args, ffmpeg=ffmpeg,
132
+ )
133
+ self._stderr: IO[bytes] = tempfile.TemporaryFile()
134
+ try:
135
+ self._proc = subprocess.Popen(
136
+ self.command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=self._stderr,
137
+ )
138
+ except OSError as exc:
139
+ self._stderr.close()
140
+ self._done = True
141
+ raise EncodeError(f"could not start {self.command[0]!r}: {exc}") from exc
142
+
143
+ def _tail(self) -> str:
144
+ self._stderr.flush()
145
+ size = self._stderr.seek(0, os.SEEK_END)
146
+ self._stderr.seek(max(0, size - self._tail_bytes))
147
+ return self._stderr.read().decode("utf-8", "replace").strip()
148
+
149
+ def _remove_output(self) -> None:
150
+ try:
151
+ self.path.unlink()
152
+ except OSError:
153
+ pass
154
+
155
+ def _fail(self, what: str, cause: BaseException | None = None) -> EncodeError:
156
+ """Reap ffmpeg and build the error. Deletes the partial file."""
157
+ try:
158
+ self._proc.stdin.close() # type: ignore[union-attr]
159
+ except OSError:
160
+ pass
161
+ returncode = self._proc.wait()
162
+ tail = self._tail()
163
+ self._finish()
164
+ self._remove_output()
165
+ message = f"{what}: ffmpeg exited with code {returncode} after {self.frames} frame(s) for {self.path}"
166
+ if tail:
167
+ message += f"\n{tail}"
168
+ error = EncodeError(message, returncode=returncode, stderr_tail=tail, frames=self.frames)
169
+ error.__cause__ = cause
170
+ return error
171
+
172
+ def _finish(self) -> None:
173
+ self._done = True
174
+ self._stderr.close()
175
+
176
+ def _as_bytes(self, frame: Any) -> Any:
177
+ if isinstance(frame, Image.Image):
178
+ if frame.size != self.size:
179
+ raise ValueError(f"frame is {frame.size[0]}x{frame.size[1]}, the video is {self.size[0]}x{self.size[1]}")
180
+ if frame.mode != "RGB":
181
+ frame = frame.convert("RGB")
182
+ return frame.tobytes()
183
+ if not isinstance(frame, (bytes, bytearray, memoryview)):
184
+ frame = frame.tobytes() # numpy arrays and anything else that dumps its pixels
185
+ if len(frame) != self._frame_bytes:
186
+ raise ValueError(f"frame is {len(frame)} bytes, expected {self._frame_bytes} (rgb24, {self.size[0]}x{self.size[1]})")
187
+ return frame
188
+
189
+ def write(self, frame: Any) -> None:
190
+ """Add one frame: a Pillow image of the video's size (converted to RGB if needed), or exactly
191
+ width x height x 3 bytes of RGB data, as bytes or as an object with `tobytes()` such as a numpy array."""
192
+ if self._done:
193
+ raise ValueError("the encoder is closed")
194
+ data = self._as_bytes(frame)
195
+ try:
196
+ self._proc.stdin.write(data) # type: ignore[union-attr]
197
+ except OSError as exc: # ffmpeg quit early: broken pipe, or EINVAL on Windows
198
+ raise self._fail("ffmpeg stopped reading frames", exc) from exc
199
+ self.frames += 1
200
+
201
+ def close(self) -> None:
202
+ """Finish the file. Raises `EncodeError` if ffmpeg exits nonzero or no frame was written."""
203
+ if self._done:
204
+ return
205
+ try:
206
+ self._proc.stdin.close() # type: ignore[union-attr]
207
+ except OSError as exc:
208
+ raise self._fail("ffmpeg stopped reading frames", exc) from exc
209
+ returncode = self._proc.wait()
210
+ if returncode != 0 or self.frames == 0:
211
+ what = "ffmpeg failed" if returncode != 0 else "no frames were written"
212
+ raise self._fail(what)
213
+ self._finish()
214
+
215
+ def abort(self) -> None:
216
+ """Stop ffmpeg now and delete the partial file."""
217
+ if self._done:
218
+ return
219
+ try:
220
+ self._proc.stdin.close() # type: ignore[union-attr]
221
+ except OSError:
222
+ pass
223
+ if self._proc.poll() is None:
224
+ self._proc.kill()
225
+ self._proc.wait()
226
+ self._finish()
227
+ self._remove_output()
228
+
229
+ def __enter__(self) -> "RawVideoEncoder":
230
+ return self
231
+
232
+ def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
233
+ if exc_type is not None:
234
+ self.abort()
235
+ else:
236
+ self.close()
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ from PIL import Image, ImageFont
7
+
8
+
9
+ def nearest(img: Image.Image, n: int) -> Image.Image:
10
+ """Scale up by a whole factor with no smoothing, for pixel art."""
11
+ if isinstance(n, bool) or not isinstance(n, int) or n < 1:
12
+ raise ValueError(f"n must be a whole number of at least 1, not {n!r}")
13
+ return img.resize((img.width * n, img.height * n), Image.Resampling.NEAREST)
14
+
15
+
16
+ @lru_cache(maxsize=None)
17
+ def _load(path: str, size: int, index: int) -> ImageFont.FreeTypeFont:
18
+ return ImageFont.truetype(path, size, index=index)
19
+
20
+
21
+ def font(path: str | os.PathLike[str], size: int, *, index: int = 0) -> ImageFont.FreeTypeFont:
22
+ """`ImageFont.truetype`, loaded once per (file, size, index) and shared after that. A render script asks for the
23
+ same few sizes thousands of times, once per frame. Use `font.cache_clear()` to drop the cache."""
24
+ return _load(os.fspath(path), int(size), int(index))
25
+
26
+
27
+ font.cache_clear = _load.cache_clear # type: ignore[attr-defined]
@@ -0,0 +1,271 @@
1
+ import json
2
+ import shutil
3
+ import subprocess
4
+ import sys
5
+ from fractions import Fraction
6
+
7
+ import pytest
8
+ from PIL import Image
9
+
10
+ from uppercut_rawvideo_encoder import EncodeError, RawVideoEncoder, ffmpeg_command, font, format_fps, nearest
11
+
12
+ needs_ffmpeg = pytest.mark.skipif(not (shutil.which("ffmpeg") and shutil.which("ffprobe")), reason="ffmpeg not installed")
13
+
14
+ SIZE = (64, 48)
15
+
16
+
17
+ def solid(value, size=SIZE):
18
+ return Image.new("RGB", size, (value, 40, 200 - value))
19
+
20
+
21
+ def fake_ffmpeg(tmp_path, body):
22
+ """A stand-in for ffmpeg: a Python script that records its arguments, then runs `body`."""
23
+ script = tmp_path / "fake_ffmpeg.py"
24
+ script.write_text(
25
+ "import json, os, sys\n"
26
+ f"open({str(tmp_path / 'argv.json')!r}, 'w').write(json.dumps(sys.argv[1:]))\n" + body
27
+ )
28
+ return [sys.executable, str(script)]
29
+
30
+
31
+ def probe(path):
32
+ out = subprocess.run(
33
+ ["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0",
34
+ "-show_entries", "stream=codec_name,pix_fmt,width,height,r_frame_rate,nb_read_frames",
35
+ "-of", "json", str(path)],
36
+ capture_output=True, text=True, check=True,
37
+ ).stdout
38
+ return json.loads(out)["streams"][0]
39
+
40
+
41
+ def test_command_always_has_nostdin_and_the_given_quality(tmp_path):
42
+ cmd = ffmpeg_command(tmp_path / "o.mp4", (3840, 2160), 60, crf=16, preset="medium")
43
+ assert cmd[:4] == ["ffmpeg", "-nostdin", "-y", "-loglevel"]
44
+ assert cmd[cmd.index("-s") + 1] == "3840x2160"
45
+ assert cmd[cmd.index("-r") + 1] == "60"
46
+ assert cmd[cmd.index("-crf") + 1] == "16"
47
+ assert cmd[cmd.index("-preset") + 1] == "medium"
48
+ assert cmd[cmd.index("-c:v") + 1] == "libx264"
49
+ assert cmd[cmd.index("-pix_fmt", cmd.index("-c:v")) + 1] == "yuv420p"
50
+ assert cmd[-1] == str(tmp_path / "o.mp4")
51
+
52
+
53
+ def test_fps_crf_and_preset_have_no_defaults(tmp_path):
54
+ with pytest.raises(TypeError):
55
+ RawVideoEncoder(tmp_path / "o.mp4", SIZE, crf=16, preset="medium") # no fps
56
+ with pytest.raises(TypeError):
57
+ RawVideoEncoder(tmp_path / "o.mp4", SIZE, 60, preset="medium") # no crf
58
+ with pytest.raises(TypeError):
59
+ RawVideoEncoder(tmp_path / "o.mp4", SIZE, 60, crf=16) # no preset
60
+
61
+
62
+ def test_format_fps():
63
+ assert format_fps(60) == "60"
64
+ assert format_fps(24.0) == "24"
65
+ assert format_fps(59.94) == "59.94"
66
+ assert format_fps(Fraction(60000, 1001)) == "60000/1001"
67
+ assert format_fps("24000/1001") == "24000/1001"
68
+ for bad in (0, -1, "0/1", "sixty", float("nan")):
69
+ with pytest.raises(ValueError):
70
+ format_fps(bad)
71
+ with pytest.raises(TypeError):
72
+ format_fps(None) # type: ignore[arg-type]
73
+
74
+
75
+ def test_extra_inputs_and_output_args_land_between_the_frame_input_and_the_file(tmp_path):
76
+ cmd = ffmpeg_command(
77
+ tmp_path / "o.mp4", SIZE, 24, crf=14, preset="slow",
78
+ extra_inputs=["-ss", "1.5", "-i", "song.wav"],
79
+ output_args=["-map", "0:v", "-map", "1:a", "-c:a", "aac"],
80
+ ffmpeg=["python", "-m", "fakeff"],
81
+ )
82
+ assert cmd[:3] == ["python", "-m", "fakeff"]
83
+ first_input = cmd.index("-i")
84
+ assert cmd[first_input + 1] == "-"
85
+ assert cmd[first_input + 2:first_input + 6] == ["-ss", "1.5", "-i", "song.wav"]
86
+ assert cmd.index("-crf") > first_input + 5
87
+ assert cmd[-7:-1] == ["-map", "0:v", "-map", "1:a", "-c:a", "aac"]
88
+
89
+
90
+ def test_failed_ffmpeg_raises_with_exit_code_and_stderr_tail(tmp_path):
91
+ ff = fake_ffmpeg(tmp_path, "sys.stdin.buffer.read()\nsys.stderr.write('x264 [error]: boom\\n')\nsys.exit(7)\n")
92
+ out = tmp_path / "o.mp4"
93
+ enc = RawVideoEncoder(out, SIZE, 60, crf=16, preset="medium", ffmpeg=ff)
94
+ enc.write(solid(10))
95
+ with pytest.raises(EncodeError) as info:
96
+ enc.close()
97
+ err = info.value
98
+ assert err.returncode == 7
99
+ assert "boom" in err.stderr_tail
100
+ assert "boom" in str(err) and "code 7" in str(err)
101
+ assert err.frames == 1
102
+ assert not out.exists()
103
+
104
+
105
+ def test_ffmpeg_dying_mid_render_raises_encode_error_not_a_broken_pipe(tmp_path):
106
+ ff = fake_ffmpeg(tmp_path, "sys.stderr.write('Invalid argument\\n')\nsys.exit(3)\n")
107
+ out = tmp_path / "o.mp4"
108
+ out.write_bytes(b"partial")
109
+ with pytest.raises(EncodeError) as info:
110
+ with RawVideoEncoder(out, SIZE, 60, crf=16, preset="medium", ffmpeg=ff) as enc:
111
+ for _ in range(500): # more than the pipe buffer holds
112
+ enc.write(solid(1))
113
+ assert info.value.returncode == 3
114
+ assert "Invalid argument" in info.value.stderr_tail
115
+ assert not out.exists()
116
+
117
+
118
+ def test_missing_ffmpeg_executable_raises_encode_error(tmp_path):
119
+ with pytest.raises(EncodeError, match="could not start"):
120
+ RawVideoEncoder(tmp_path / "o.mp4", SIZE, 60, crf=16, preset="medium", ffmpeg=str(tmp_path / "no-such-ffmpeg"))
121
+
122
+
123
+ def test_stderr_tail_is_bounded(tmp_path):
124
+ ff = fake_ffmpeg(tmp_path, "sys.stdin.buffer.read()\nsys.stderr.write('a' * 100000 + 'THE END')\nsys.exit(1)\n")
125
+ enc = RawVideoEncoder(tmp_path / "o.mp4", SIZE, 60, crf=16, preset="medium", ffmpeg=ff, tail_bytes=100)
126
+ enc.write(solid(1))
127
+ with pytest.raises(EncodeError) as info:
128
+ enc.close()
129
+ assert len(info.value.stderr_tail) <= 100
130
+ assert info.value.stderr_tail.endswith("THE END")
131
+
132
+
133
+ def test_no_frames_is_an_error_even_when_ffmpeg_exits_zero(tmp_path):
134
+ ff = fake_ffmpeg(tmp_path, "sys.stdin.buffer.read()\n")
135
+ with pytest.raises(EncodeError, match="no frames"):
136
+ with RawVideoEncoder(tmp_path / "o.mp4", SIZE, 60, crf=16, preset="medium", ffmpeg=ff):
137
+ pass
138
+
139
+
140
+ def test_exception_in_the_body_aborts_and_propagates(tmp_path):
141
+ ff = fake_ffmpeg(tmp_path, "sys.stdin.buffer.read()\nopen(sys.argv[-1], 'wb').write(b'partial')\n")
142
+ out = tmp_path / "o.mp4"
143
+ with pytest.raises(KeyError):
144
+ with RawVideoEncoder(out, SIZE, 60, crf=16, preset="medium", ffmpeg=ff) as enc:
145
+ enc.write(solid(1))
146
+ raise KeyError("render bug")
147
+ assert not out.exists()
148
+
149
+
150
+ def test_ffmpeg_stdin_is_not_the_terminal(tmp_path):
151
+ """-nostdin means ffmpeg ignores keystrokes; the frames come over the pipe and arrive intact."""
152
+ ff = fake_ffmpeg(tmp_path, "data = sys.stdin.buffer.read()\nopen(sys.argv[-1], 'wb').write(data)\n")
153
+ out = tmp_path / "raw.bin"
154
+ with RawVideoEncoder(out, SIZE, 60, crf=16, preset="medium", ffmpeg=ff) as enc:
155
+ enc.write(solid(10))
156
+ enc.write(bytes(range(256)) * (SIZE[0] * SIZE[1] * 3 // 256))
157
+ argv = json.loads((tmp_path / "argv.json").read_text())
158
+ assert "-nostdin" in argv
159
+ data = out.read_bytes()
160
+ assert data[: SIZE[0] * SIZE[1] * 3] == solid(10).tobytes()
161
+ assert len(data) == 2 * SIZE[0] * SIZE[1] * 3
162
+
163
+
164
+ def test_wrong_frame_size_is_rejected(tmp_path):
165
+ ff = fake_ffmpeg(tmp_path, "sys.stdin.buffer.read()\n")
166
+ enc = RawVideoEncoder(tmp_path / "o.mp4", SIZE, 60, crf=16, preset="medium", ffmpeg=ff)
167
+ with pytest.raises(ValueError, match="64x48"):
168
+ enc.write(solid(1, (65, 48)))
169
+ with pytest.raises(ValueError, match="bytes"):
170
+ enc.write(b"\x00" * 10)
171
+ enc.abort()
172
+ with pytest.raises(ValueError, match="closed"):
173
+ enc.write(solid(1))
174
+
175
+
176
+ def test_non_rgb_images_are_converted(tmp_path):
177
+ ff = fake_ffmpeg(tmp_path, "data = sys.stdin.buffer.read()\nopen(sys.argv[-1], 'wb').write(data)\n")
178
+ out = tmp_path / "raw.bin"
179
+ with RawVideoEncoder(out, SIZE, 60, crf=16, preset="medium", ffmpeg=ff) as enc:
180
+ enc.write(Image.new("RGBA", SIZE, (1, 2, 3, 255)))
181
+ assert out.read_bytes() == bytes([1, 2, 3]) * (SIZE[0] * SIZE[1])
182
+
183
+
184
+ def test_objects_with_tobytes_are_accepted(tmp_path):
185
+ ff = fake_ffmpeg(tmp_path, "data = sys.stdin.buffer.read()\nopen(sys.argv[-1], 'wb').write(data)\n")
186
+
187
+ class Pixels:
188
+ def tobytes(self):
189
+ return bytes([9, 8, 7]) * (SIZE[0] * SIZE[1])
190
+
191
+ out = tmp_path / "raw.bin"
192
+ with RawVideoEncoder(out, SIZE, 60, crf=16, preset="medium", ffmpeg=ff) as enc:
193
+ enc.write(Pixels())
194
+ assert out.read_bytes() == bytes([9, 8, 7]) * (SIZE[0] * SIZE[1])
195
+
196
+
197
+ @needs_ffmpeg
198
+ def test_encodes_a_playable_h264_yuv420p_file(tmp_path):
199
+ out = tmp_path / "clip.mp4"
200
+ with RawVideoEncoder(out, (64, 48), 24, crf=18, preset="ultrafast") as enc:
201
+ for i in range(12):
202
+ enc.write(solid(i * 10))
203
+ assert enc.frames == 12
204
+ info = probe(out)
205
+ assert (info["codec_name"], info["pix_fmt"]) == ("h264", "yuv420p")
206
+ assert (info["width"], info["height"], info["r_frame_rate"]) == (64, 48, "24/1")
207
+ assert info["nb_read_frames"] == "12"
208
+
209
+
210
+ @needs_ffmpeg
211
+ def test_real_ffmpeg_failure_is_reported_with_its_message(tmp_path):
212
+ out = tmp_path / "missing-folder" / "clip.mp4"
213
+ with pytest.raises(EncodeError) as info:
214
+ with RawVideoEncoder(out, (64, 48), 60, crf=16, preset="ultrafast") as enc:
215
+ enc.write(solid(1))
216
+ assert info.value.returncode != 0
217
+ assert info.value.stderr_tail # ffmpeg said why
218
+
219
+
220
+ @needs_ffmpeg
221
+ def test_soundtrack_through_extra_inputs(tmp_path):
222
+ wav = tmp_path / "tone.wav"
223
+ subprocess.run(
224
+ ["ffmpeg", "-nostdin", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=2", str(wav)],
225
+ check=True,
226
+ )
227
+ out = tmp_path / "clip.mp4"
228
+ with RawVideoEncoder(
229
+ out, (64, 48), 24, crf=18, preset="ultrafast",
230
+ extra_inputs=["-i", str(wav)],
231
+ output_args=["-map", "0:v", "-map", "1:a", "-c:a", "aac", "-shortest"],
232
+ ) as enc:
233
+ for i in range(24):
234
+ enc.write(solid(i))
235
+ streams = subprocess.run(
236
+ ["ffprobe", "-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", str(out)],
237
+ capture_output=True, text=True, check=True,
238
+ ).stdout.split()
239
+ assert sorted(streams) == ["audio", "video"]
240
+
241
+
242
+ def test_nearest_scales_by_whole_factors_without_smoothing():
243
+ img = Image.new("RGB", (2, 1))
244
+ img.putpixel((0, 0), (255, 0, 0))
245
+ img.putpixel((1, 0), (0, 0, 255))
246
+ big = nearest(img, 3)
247
+ assert big.size == (6, 3)
248
+ assert {big.getpixel((x, y)) for x in range(3) for y in range(3)} == {(255, 0, 0)}
249
+ assert {big.getpixel((x, y)) for x in range(3, 6) for y in range(3)} == {(0, 0, 255)}
250
+ for bad in (0, -2, 1.5, True):
251
+ with pytest.raises(ValueError):
252
+ nearest(img, bad) # type: ignore[arg-type]
253
+
254
+
255
+ def test_font_is_loaded_once_per_file_size_and_index(monkeypatch):
256
+ from uppercut_rawvideo_encoder import _pixels
257
+
258
+ calls = []
259
+
260
+ def fake_truetype(path, size, index=0):
261
+ calls.append((path, size, index))
262
+ return object()
263
+
264
+ monkeypatch.setattr(_pixels.ImageFont, "truetype", fake_truetype)
265
+ font.cache_clear()
266
+ a = font("a.ttf", 30)
267
+ assert font("a.ttf", 30) is a
268
+ assert font("a.ttf", 31) is not a
269
+ assert font("a.ttf", 30, index=1) is not a
270
+ assert calls == [("a.ttf", 30, 0), ("a.ttf", 31, 0), ("a.ttf", 30, 1)]
271
+ font.cache_clear()