uppercut-rawvideo-encoder 0.1.0__py3-none-any.whl

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,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]
File without changes
@@ -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,7 @@
1
+ uppercut_rawvideo_encoder/__init__.py,sha256=IkkM_ZDw8pse1be8j9b7HfhcnVpSE_L_LMcVkUtjGD8,385
2
+ uppercut_rawvideo_encoder/_encoder.py,sha256=Pvhd8yzjrMiN92WXzvfIXeFsLGDiwFKS6iA9ZYRrbm0,9281
3
+ uppercut_rawvideo_encoder/_pixels.py,sha256=CPzH6mp9Bt4k2Pj1UBB5SqpLONkGOmaUoXj1AppHZYY,1058
4
+ uppercut_rawvideo_encoder/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ uppercut_rawvideo_encoder-0.1.0.dist-info/METADATA,sha256=uOmMMt1VrQNT2YoEXx45RUz8adLN8fhxmYng35hipuE,5177
6
+ uppercut_rawvideo_encoder-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ uppercut_rawvideo_encoder-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any