cine-handler 0.2.0__py3-none-win_amd64.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.
- cine_handler-0.2.0.dist-info/METADATA +153 -0
- cine_handler-0.2.0.dist-info/RECORD +19 -0
- cine_handler-0.2.0.dist-info/WHEEL +5 -0
- cine_handler-0.2.0.dist-info/licenses/LICENSE +21 -0
- cine_handler-0.2.0.dist-info/top_level.txt +1 -0
- cine_reader/__init__.py +36 -0
- cine_reader/_binary.py +308 -0
- cine_reader/_lookup.py +76 -0
- cine_reader/_native.py +269 -0
- cine_reader/cine.py +859 -0
- cine_reader/frame_decode.py +57 -0
- cine_reader/headers.py +498 -0
- cine_reader/image_ops.py +112 -0
- cine_reader/libs/build-info.json +15 -0
- cine_reader/libs/cine_core.dll +0 -0
- cine_reader/py.typed +0 -0
- cine_reader/stats.py +94 -0
- cine_reader/unpack.py +51 -0
- cine_reader/writer.py +424 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"abi_version": 1,
|
|
3
|
+
"artifacts": {
|
|
4
|
+
"cine_core.dll": {
|
|
5
|
+
"sha256": "3a22b653c74bbd3d246619a08ce80445660738d87108ade9288bc7254dc1d5d5",
|
|
6
|
+
"size": 360448
|
|
7
|
+
}
|
|
8
|
+
},
|
|
9
|
+
"matlab_release": "2026b",
|
|
10
|
+
"rustc_version": "rustc 1.100.0 (0ef1bc386 2026-11-09)\nbinary: rustc\ncommit-hash: 0ef1bc386059596dada8fb65b50425aab2ea637a\ncommit-date: 2026-11-09\nhost: x86_64-pc-windows-msvc\nrelease: 1.100.0\nLLVM version: 23.1.5",
|
|
11
|
+
"schema_version": 1,
|
|
12
|
+
"source_commit": "0ff7edf794c04a04a4cdb2a49447431329a94b31",
|
|
13
|
+
"source_fingerprint": "3459d760d7d18c60d915c021b3633612523b85b100b0db99b39df499eab339fe",
|
|
14
|
+
"target": "x86_64-pc-windows-msvc"
|
|
15
|
+
}
|
|
Binary file
|
cine_reader/py.typed
ADDED
|
File without changes
|
cine_reader/stats.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Streaming NumPy adapters for Rust-owned statistics accumulators."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ctypes as ct
|
|
6
|
+
import math
|
|
7
|
+
from typing import Iterable
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from ._native import check, library
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _statistics(frames, *, mode, k=1, q=0.8, sigma=2.5, min_keep=3, out_dtype=None):
|
|
15
|
+
lib = library()
|
|
16
|
+
handle = None
|
|
17
|
+
shape = None
|
|
18
|
+
dtype = out_dtype
|
|
19
|
+
try:
|
|
20
|
+
for frame in frames:
|
|
21
|
+
array = np.asarray(frame)
|
|
22
|
+
if shape is None:
|
|
23
|
+
shape = array.shape
|
|
24
|
+
dtype = array.dtype if dtype is None else dtype
|
|
25
|
+
if array.size == 0:
|
|
26
|
+
raise ValueError("Frames must contain at least one sample")
|
|
27
|
+
handle = lib.cine_stats_create(array.size, mode, k, q, sigma, min_keep)
|
|
28
|
+
if not handle:
|
|
29
|
+
check(-1, lib)
|
|
30
|
+
elif array.shape != shape:
|
|
31
|
+
raise ValueError("All frames must have the same shape")
|
|
32
|
+
values = np.ascontiguousarray(array, dtype=np.float64)
|
|
33
|
+
check(lib.cine_stats_push(handle, values.ctypes.data, values.size), lib)
|
|
34
|
+
if handle is None:
|
|
35
|
+
raise RuntimeError("No frames were provided.")
|
|
36
|
+
result = np.empty(shape, dtype=np.float64)
|
|
37
|
+
count = ct.c_uint64()
|
|
38
|
+
check(lib.cine_stats_finish(handle, result.ctypes.data, result.size, ct.byref(count)), lib)
|
|
39
|
+
return result.astype(dtype, copy=False), count.value
|
|
40
|
+
finally:
|
|
41
|
+
if handle:
|
|
42
|
+
lib.cine_stats_close(handle)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def average_from_frame_iter(
|
|
46
|
+
frames: Iterable[np.ndarray], *, out_dtype: np.dtype | None = None, chunk_size: int = 8
|
|
47
|
+
) -> tuple[np.ndarray, int]:
|
|
48
|
+
"""Mean using one Rust accumulator; chunk_size remains accepted for compatibility."""
|
|
49
|
+
if chunk_size <= 0:
|
|
50
|
+
raise ValueError("chunk_size must be > 0")
|
|
51
|
+
return _statistics(frames, mode=0, out_dtype=out_dtype)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def robust_background_mad_stack(
|
|
55
|
+
frames: Iterable[np.ndarray],
|
|
56
|
+
*,
|
|
57
|
+
q_bg: float = 0.80,
|
|
58
|
+
k_sigma: float = 2.5,
|
|
59
|
+
min_keep: int = 3,
|
|
60
|
+
out_dtype: np.dtype = np.uint16,
|
|
61
|
+
) -> np.ndarray:
|
|
62
|
+
"""Quantile/MAD background estimate; its full sample stack is owned by Rust."""
|
|
63
|
+
if not 0.0 < q_bg < 1.0:
|
|
64
|
+
raise ValueError("q_bg must be between 0 and 1")
|
|
65
|
+
if min_keep < 0 or min_keep > 0xFFFFFFFF:
|
|
66
|
+
raise ValueError("min_keep is outside the uint32 range")
|
|
67
|
+
return _statistics(
|
|
68
|
+
frames, mode=2, q=q_bg, sigma=k_sigma, min_keep=min_keep, out_dtype=out_dtype
|
|
69
|
+
)[0]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def robust_background_topk(
|
|
73
|
+
frames: Iterable[np.ndarray],
|
|
74
|
+
*,
|
|
75
|
+
frame_count: int,
|
|
76
|
+
q_bg: float = 0.80,
|
|
77
|
+
min_keep: int = 3,
|
|
78
|
+
max_keep: int | None = 96,
|
|
79
|
+
out_dtype: np.dtype = np.uint16,
|
|
80
|
+
) -> np.ndarray:
|
|
81
|
+
"""Bounded-memory background estimate retaining the k brightest samples."""
|
|
82
|
+
if frame_count <= 0:
|
|
83
|
+
raise ValueError("frame_count must be > 0")
|
|
84
|
+
if not 0.0 < q_bg < 1.0:
|
|
85
|
+
raise ValueError("q_bg must be between 0 and 1")
|
|
86
|
+
k_keep = max(min_keep, int(math.ceil((1.0 - q_bg) * frame_count)))
|
|
87
|
+
if max_keep is not None:
|
|
88
|
+
k_keep = min(k_keep, max_keep)
|
|
89
|
+
k_keep = max(1, k_keep)
|
|
90
|
+
if k_keep > 0xFFFFFFFF:
|
|
91
|
+
raise ValueError("Too many retained samples")
|
|
92
|
+
return _statistics(
|
|
93
|
+
frames, mode=1, k=k_keep, q=q_bg, min_keep=max(0, min_keep), out_dtype=out_dtype
|
|
94
|
+
)[0]
|
cine_reader/unpack.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Packed 10-bit helpers backed by the shared Rust decoder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from ._lookup import LOOKUP_TABLE
|
|
8
|
+
from ._native import check, library
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def unpack_10bit_data(data: bytes) -> np.ndarray:
|
|
12
|
+
"""Expand complete groups of four Phantom packed10 samples to linear uint16."""
|
|
13
|
+
payload = np.frombuffer(data, dtype=np.uint8)
|
|
14
|
+
samples = payload.size // 5 * 4
|
|
15
|
+
result = np.empty(samples, dtype=np.uint16)
|
|
16
|
+
if samples:
|
|
17
|
+
lib = library()
|
|
18
|
+
check(
|
|
19
|
+
lib.cine_unpack10(payload.ctypes.data, samples // 4 * 5, result.ctypes.data, samples),
|
|
20
|
+
lib,
|
|
21
|
+
)
|
|
22
|
+
return result
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def unpack_10bit_numpy(data: bytes) -> np.ndarray:
|
|
26
|
+
"""Explicit NumPy reference implementation; normal decoding uses Rust."""
|
|
27
|
+
byte_data = np.frombuffer(data, dtype=np.uint8)
|
|
28
|
+
groups = byte_data.size // 5
|
|
29
|
+
if groups == 0:
|
|
30
|
+
return np.empty(0, dtype=np.uint16)
|
|
31
|
+
|
|
32
|
+
packed = byte_data[: groups * 5].reshape(groups, 5).astype(np.uint64, copy=False)
|
|
33
|
+
combined = (
|
|
34
|
+
(packed[:, 0] << 32)
|
|
35
|
+
| (packed[:, 1] << 24)
|
|
36
|
+
| (packed[:, 2] << 16)
|
|
37
|
+
| (packed[:, 3] << 8)
|
|
38
|
+
| packed[:, 4]
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
idx0 = (combined >> 30) & 0x3FF
|
|
42
|
+
idx1 = (combined >> 20) & 0x3FF
|
|
43
|
+
idx2 = (combined >> 10) & 0x3FF
|
|
44
|
+
idx3 = combined & 0x3FF
|
|
45
|
+
|
|
46
|
+
out = np.empty(groups * 4, dtype=np.uint16)
|
|
47
|
+
out[0::4] = LOOKUP_TABLE[idx0]
|
|
48
|
+
out[1::4] = LOOKUP_TABLE[idx1]
|
|
49
|
+
out[2::4] = LOOKUP_TABLE[idx2]
|
|
50
|
+
out[3::4] = LOOKUP_TABLE[idx3]
|
|
51
|
+
return out
|
cine_reader/writer.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
"""Streaming Python conveniences around the shared Rust CINE encoder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import tempfile
|
|
9
|
+
from itertools import chain
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Iterable, Iterator
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from ._native import NativeWriter
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CineWriter:
|
|
19
|
+
"""Write frames incrementally, publishing a complete file on successful close.
|
|
20
|
+
|
|
21
|
+
Arrays use top-down image coordinates and RGB channel order. ``normal``
|
|
22
|
+
preserves uint8/uint16 values. ``packed10`` stores Phantom's nonlinear
|
|
23
|
+
10-bit codes from linear 12-bit samples; uint8 is scaled to 0..4095.
|
|
24
|
+
RGB packed10 input is sampled into a Bayer mosaic (CFA 4/RGGB by default).
|
|
25
|
+
This is necessarily lossy; normal RGB is preferable for exact preservation.
|
|
26
|
+
Existing destinations are never overwritten. A frame_count of None supports
|
|
27
|
+
generators with bounded memory and a temporary disk spool.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
filename: str | Path,
|
|
33
|
+
*,
|
|
34
|
+
width: int,
|
|
35
|
+
height: int,
|
|
36
|
+
dtype=np.uint16,
|
|
37
|
+
channels: int = 1,
|
|
38
|
+
encoding: str = "normal",
|
|
39
|
+
frame_count: int | None = None,
|
|
40
|
+
frame_rate: float = 30.0,
|
|
41
|
+
first_frame: int = 0,
|
|
42
|
+
bit_depth: int | None = None,
|
|
43
|
+
cfa: int = 0,
|
|
44
|
+
):
|
|
45
|
+
for name, value in (("first_frame", first_frame), ("cfa", cfa), ("bit_depth", bit_depth)):
|
|
46
|
+
if value is not None and int(value) != value:
|
|
47
|
+
raise ValueError(f"{name} must be an integer")
|
|
48
|
+
self.filename = str(filename)
|
|
49
|
+
self.dtype = np.dtype(dtype)
|
|
50
|
+
if self.dtype.kind != "u" or self.dtype.itemsize not in (1, 2):
|
|
51
|
+
raise TypeError("dtype must be uint8 or uint16")
|
|
52
|
+
if encoding not in ("normal", "packed10"):
|
|
53
|
+
raise ValueError("encoding must be 'normal' or 'packed10'")
|
|
54
|
+
if channels not in (1, 3):
|
|
55
|
+
raise ValueError("channels must be 1 (mono/Bayer) or 3 (RGB)")
|
|
56
|
+
if int(width) != width or int(height) != height or width <= 0 or height <= 0:
|
|
57
|
+
raise ValueError("width and height must be positive integers")
|
|
58
|
+
if frame_count is not None and (int(frame_count) != frame_count or frame_count <= 0):
|
|
59
|
+
raise ValueError("frame_count must be a positive integer or None")
|
|
60
|
+
self.width, self.height, self.channels = int(width), int(height), int(channels)
|
|
61
|
+
self.encoding = encoding
|
|
62
|
+
self.bit_depth = (
|
|
63
|
+
(12 if encoding == "packed10" else self.dtype.itemsize * 8)
|
|
64
|
+
if bit_depth is None
|
|
65
|
+
else int(bit_depth)
|
|
66
|
+
)
|
|
67
|
+
if encoding == "normal" and ((self.bit_depth == 8) != (self.dtype.itemsize == 1)):
|
|
68
|
+
raise ValueError("normal bit_depth=8 requires uint8; bit_depth=9..16 requires uint16")
|
|
69
|
+
self.cfa = int(cfa)
|
|
70
|
+
if encoding == "packed10" and channels == 3:
|
|
71
|
+
self.cfa = self.cfa or 4
|
|
72
|
+
if self.cfa not in (3, 4, 5, 6):
|
|
73
|
+
raise ValueError("RGB packed10 encoding requires CFA 3, 4, 5 or 6")
|
|
74
|
+
self._writer = NativeWriter(
|
|
75
|
+
filename,
|
|
76
|
+
width=self.width,
|
|
77
|
+
height=self.height,
|
|
78
|
+
channels=1 if encoding == "packed10" else channels,
|
|
79
|
+
bit_depth=self.bit_depth,
|
|
80
|
+
packed10=encoding == "packed10",
|
|
81
|
+
frame_count=0 if frame_count is None else int(frame_count),
|
|
82
|
+
first_frame=int(first_frame),
|
|
83
|
+
frame_rate=float(frame_rate),
|
|
84
|
+
cfa=self.cfa,
|
|
85
|
+
)
|
|
86
|
+
self.frames_written = 0
|
|
87
|
+
self.closed = False
|
|
88
|
+
|
|
89
|
+
def write_frame(self, frame: np.ndarray) -> None:
|
|
90
|
+
"""Append one frame. Shape and input dtype must match the constructor."""
|
|
91
|
+
if self.closed:
|
|
92
|
+
raise RuntimeError("CINE writer is closed")
|
|
93
|
+
frame = np.asarray(frame)
|
|
94
|
+
expected = (self.height, self.width) + ((3,) if self.channels == 3 else ())
|
|
95
|
+
if frame.shape != expected:
|
|
96
|
+
raise ValueError(f"frame shape {frame.shape} does not match {expected}")
|
|
97
|
+
if frame.dtype.kind != "u" or frame.dtype.itemsize != self.dtype.itemsize:
|
|
98
|
+
raise TypeError(f"frame dtype must match {self.dtype}")
|
|
99
|
+
payload = np.ascontiguousarray(frame, dtype="<u2" if self.dtype.itemsize == 2 else np.uint8)
|
|
100
|
+
self._writer.write_frame(payload)
|
|
101
|
+
self.frames_written += 1
|
|
102
|
+
|
|
103
|
+
def close(self) -> None:
|
|
104
|
+
"""Finalize the file; incomplete declared frame counts raise an error."""
|
|
105
|
+
if not self.closed:
|
|
106
|
+
try:
|
|
107
|
+
self._writer.finish()
|
|
108
|
+
finally:
|
|
109
|
+
self.closed = True
|
|
110
|
+
self._writer.close()
|
|
111
|
+
|
|
112
|
+
def abort(self) -> None:
|
|
113
|
+
"""Discard an unfinished output and release temporary files."""
|
|
114
|
+
if not self.closed:
|
|
115
|
+
self.closed = True
|
|
116
|
+
self._writer.close()
|
|
117
|
+
|
|
118
|
+
def __enter__(self) -> "CineWriter":
|
|
119
|
+
return self
|
|
120
|
+
|
|
121
|
+
def __exit__(self, exc_type, exc, traceback) -> bool:
|
|
122
|
+
if exc_type is None:
|
|
123
|
+
self.close()
|
|
124
|
+
else:
|
|
125
|
+
self.abort()
|
|
126
|
+
return False
|
|
127
|
+
|
|
128
|
+
def __del__(self):
|
|
129
|
+
if hasattr(self, "closed"):
|
|
130
|
+
self.abort()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def write_cine(filename: str | Path, frames: Iterable[np.ndarray], **options) -> Path:
|
|
134
|
+
"""Encode a sequence or generator of identically shaped uint8/uint16 images.
|
|
135
|
+
|
|
136
|
+
A NumPy stack is iterated on its first axis, ``[N,H,W]`` or ``[N,H,W,3]``.
|
|
137
|
+
A sized sequence avoids the extra disk pass needed by unknown-length streams.
|
|
138
|
+
The return value is the completed output path.
|
|
139
|
+
"""
|
|
140
|
+
frame_count = options.pop("frame_count", None)
|
|
141
|
+
if frame_count is None:
|
|
142
|
+
try:
|
|
143
|
+
frame_count = len(frames)
|
|
144
|
+
except TypeError:
|
|
145
|
+
pass
|
|
146
|
+
iterator = iter(frames)
|
|
147
|
+
try:
|
|
148
|
+
first = np.asarray(next(iterator))
|
|
149
|
+
except StopIteration as exc:
|
|
150
|
+
raise ValueError("Cannot write an empty image sequence") from exc
|
|
151
|
+
if first.ndim not in (2, 3) or (first.ndim == 3 and first.shape[2] != 3):
|
|
152
|
+
raise ValueError("Each image must have shape [H,W] or [H,W,3]")
|
|
153
|
+
with CineWriter(
|
|
154
|
+
filename,
|
|
155
|
+
width=first.shape[1],
|
|
156
|
+
height=first.shape[0],
|
|
157
|
+
dtype=first.dtype,
|
|
158
|
+
channels=1 if first.ndim == 2 else 3,
|
|
159
|
+
frame_count=frame_count,
|
|
160
|
+
**options,
|
|
161
|
+
) as writer:
|
|
162
|
+
for frame in chain((first,), iterator):
|
|
163
|
+
writer.write_frame(frame)
|
|
164
|
+
return Path(filename)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def write_cine_from_images(
|
|
168
|
+
filename: str | Path, image_paths: Iterable[str | Path], **options
|
|
169
|
+
) -> Path:
|
|
170
|
+
"""Encode image files in their supplied order using optional Pillow.
|
|
171
|
+
|
|
172
|
+
Paths are not sorted implicitly. RGB, grayscale and 16-bit grayscale are
|
|
173
|
+
supported. Palette images become RGB; alpha channels are discarded.
|
|
174
|
+
"""
|
|
175
|
+
try:
|
|
176
|
+
from PIL import Image
|
|
177
|
+
except ImportError as exc:
|
|
178
|
+
raise ImportError(
|
|
179
|
+
"Install image-file support with: pip install 'cine-handler[images]'"
|
|
180
|
+
) from exc
|
|
181
|
+
if "frame_count" not in options:
|
|
182
|
+
try:
|
|
183
|
+
options["frame_count"] = len(image_paths)
|
|
184
|
+
except TypeError:
|
|
185
|
+
pass
|
|
186
|
+
|
|
187
|
+
def images() -> Iterator[np.ndarray]:
|
|
188
|
+
for path in image_paths:
|
|
189
|
+
with Image.open(path) as image:
|
|
190
|
+
if image.mode in ("P", "RGBA", "CMYK", "YCbCr"):
|
|
191
|
+
image = image.convert("RGB")
|
|
192
|
+
elif image.mode in ("1", "LA"):
|
|
193
|
+
image = image.convert("L")
|
|
194
|
+
pixels = np.asarray(image)
|
|
195
|
+
if (
|
|
196
|
+
pixels.dtype.kind == "i"
|
|
197
|
+
and pixels.size
|
|
198
|
+
and pixels.min() >= 0
|
|
199
|
+
and pixels.max() <= 65535
|
|
200
|
+
):
|
|
201
|
+
pixels = pixels.astype(np.uint16)
|
|
202
|
+
yield pixels
|
|
203
|
+
|
|
204
|
+
return write_cine(filename, images(), **options)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def write_cine_from_video(
|
|
208
|
+
filename: str | Path,
|
|
209
|
+
video_filename: str | Path,
|
|
210
|
+
*,
|
|
211
|
+
encoding: str = "normal",
|
|
212
|
+
grayscale: bool = False,
|
|
213
|
+
frame_rate: float | None = None,
|
|
214
|
+
ffmpeg: str = "ffmpeg",
|
|
215
|
+
ffprobe: str = "ffprobe",
|
|
216
|
+
backend: str | None = None,
|
|
217
|
+
**options,
|
|
218
|
+
) -> Path:
|
|
219
|
+
"""Stream a video through optional PyAV into Rust, retaining one frame at a time.
|
|
220
|
+
|
|
221
|
+
Install ``cine-handler[video]`` for video input without external executables.
|
|
222
|
+
``backend='ffmpeg'`` uses separately installed FFmpeg/FFprobe instead; supplying
|
|
223
|
+
a custom ``ffmpeg`` or ``ffprobe`` path also selects that legacy backend unless
|
|
224
|
+
``backend`` is explicitly set. Decoding uses RGB8 or gray8;
|
|
225
|
+
packed10 scales this to 12-bit and RGB becomes a Bayer mosaic. The first
|
|
226
|
+
video stream is selected, stored pixel orientation is retained (rotation metadata
|
|
227
|
+
is not applied), audio is ignored, and timestamps are represented
|
|
228
|
+
by a constant rate (override frame_rate when converting variable-rate video).
|
|
229
|
+
"""
|
|
230
|
+
if backend is None:
|
|
231
|
+
backend = "ffmpeg" if ffmpeg != "ffmpeg" or ffprobe != "ffprobe" else "pyav"
|
|
232
|
+
if backend not in ("pyav", "ffmpeg"):
|
|
233
|
+
raise ValueError("backend must be 'pyav' or 'ffmpeg'")
|
|
234
|
+
if frame_rate is not None:
|
|
235
|
+
frame_rate = float(frame_rate)
|
|
236
|
+
if not np.isfinite(frame_rate) or frame_rate <= 0:
|
|
237
|
+
raise ValueError("frame_rate must be finite and positive")
|
|
238
|
+
if backend == "pyav":
|
|
239
|
+
return _write_cine_from_pyav(
|
|
240
|
+
filename,
|
|
241
|
+
video_filename,
|
|
242
|
+
encoding=encoding,
|
|
243
|
+
grayscale=grayscale,
|
|
244
|
+
frame_rate=frame_rate,
|
|
245
|
+
**options,
|
|
246
|
+
)
|
|
247
|
+
return _write_cine_from_ffmpeg(
|
|
248
|
+
filename,
|
|
249
|
+
video_filename,
|
|
250
|
+
encoding=encoding,
|
|
251
|
+
grayscale=grayscale,
|
|
252
|
+
frame_rate=frame_rate,
|
|
253
|
+
ffmpeg=ffmpeg,
|
|
254
|
+
ffprobe=ffprobe,
|
|
255
|
+
**options,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _write_cine_from_pyav(
|
|
260
|
+
filename: str | Path,
|
|
261
|
+
video_filename: str | Path,
|
|
262
|
+
*,
|
|
263
|
+
encoding: str,
|
|
264
|
+
grayscale: bool,
|
|
265
|
+
frame_rate: float | None,
|
|
266
|
+
**options,
|
|
267
|
+
) -> Path:
|
|
268
|
+
try:
|
|
269
|
+
import av
|
|
270
|
+
except ImportError as exc:
|
|
271
|
+
raise ImportError("Install video support with: pip install 'cine-handler[video]'") from exc
|
|
272
|
+
|
|
273
|
+
with av.open(str(video_filename), mode="r") as container:
|
|
274
|
+
if not container.streams.video:
|
|
275
|
+
raise ValueError("Input contains no video stream")
|
|
276
|
+
stream = container.streams.video[0]
|
|
277
|
+
if frame_rate is None:
|
|
278
|
+
for candidate in (stream.average_rate, stream.base_rate, stream.guessed_rate):
|
|
279
|
+
if candidate is not None:
|
|
280
|
+
rate = float(candidate)
|
|
281
|
+
if np.isfinite(rate) and rate > 0:
|
|
282
|
+
frame_rate = rate
|
|
283
|
+
break
|
|
284
|
+
if frame_rate is None:
|
|
285
|
+
raise ValueError("Video frame rate is unknown; specify frame_rate")
|
|
286
|
+
width, height = stream.codec_context.width, stream.codec_context.height
|
|
287
|
+
if width <= 0 or height <= 0:
|
|
288
|
+
raise ValueError("Video width and height must be positive")
|
|
289
|
+
with CineWriter(
|
|
290
|
+
filename,
|
|
291
|
+
width=width,
|
|
292
|
+
height=height,
|
|
293
|
+
channels=1 if grayscale else 3,
|
|
294
|
+
dtype=np.uint8,
|
|
295
|
+
encoding=encoding,
|
|
296
|
+
frame_rate=frame_rate,
|
|
297
|
+
**options,
|
|
298
|
+
) as writer:
|
|
299
|
+
for frame in container.decode(stream):
|
|
300
|
+
if frame.width != width or frame.height != height:
|
|
301
|
+
raise ValueError("Video frame dimensions changed during decoding")
|
|
302
|
+
writer.write_frame(frame.to_ndarray(format="gray" if grayscale else "rgb24"))
|
|
303
|
+
if writer.frames_written == 0:
|
|
304
|
+
raise ValueError("Video contains no decoded frames")
|
|
305
|
+
return Path(filename)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _write_cine_from_ffmpeg(
|
|
309
|
+
filename: str | Path,
|
|
310
|
+
video_filename: str | Path,
|
|
311
|
+
*,
|
|
312
|
+
encoding: str,
|
|
313
|
+
grayscale: bool,
|
|
314
|
+
frame_rate: float | None,
|
|
315
|
+
ffmpeg: str,
|
|
316
|
+
ffprobe: str,
|
|
317
|
+
**options,
|
|
318
|
+
) -> Path:
|
|
319
|
+
for executable in (ffmpeg, ffprobe):
|
|
320
|
+
if not shutil.which(executable):
|
|
321
|
+
raise FileNotFoundError(f"Required video tool was not found: {executable}")
|
|
322
|
+
metadata = subprocess.run(
|
|
323
|
+
[
|
|
324
|
+
ffprobe,
|
|
325
|
+
"-v",
|
|
326
|
+
"error",
|
|
327
|
+
"-select_streams",
|
|
328
|
+
"v:0",
|
|
329
|
+
"-show_entries",
|
|
330
|
+
"stream=width,height,avg_frame_rate,r_frame_rate",
|
|
331
|
+
"-of",
|
|
332
|
+
"json",
|
|
333
|
+
str(video_filename),
|
|
334
|
+
],
|
|
335
|
+
check=True,
|
|
336
|
+
capture_output=True,
|
|
337
|
+
text=True,
|
|
338
|
+
)
|
|
339
|
+
streams = json.loads(metadata.stdout).get("streams", [])
|
|
340
|
+
if not streams:
|
|
341
|
+
raise ValueError("Input contains no video stream")
|
|
342
|
+
stream = streams[0]
|
|
343
|
+
if frame_rate is None:
|
|
344
|
+
for key in ("avg_frame_rate", "r_frame_rate"):
|
|
345
|
+
try:
|
|
346
|
+
numerator, denominator = (float(part) for part in stream.get(key, "0/0").split("/"))
|
|
347
|
+
rate = numerator / denominator
|
|
348
|
+
except (ValueError, ZeroDivisionError):
|
|
349
|
+
continue
|
|
350
|
+
if np.isfinite(rate) and rate > 0:
|
|
351
|
+
frame_rate = rate
|
|
352
|
+
break
|
|
353
|
+
if frame_rate is None:
|
|
354
|
+
raise ValueError("Video frame rate is unknown; specify frame_rate")
|
|
355
|
+
width, height = int(stream["width"]), int(stream["height"])
|
|
356
|
+
channels = 1 if grayscale else 3
|
|
357
|
+
shape = (height, width) + (() if grayscale else (3,))
|
|
358
|
+
frame_bytes = width * height * channels
|
|
359
|
+
command = [
|
|
360
|
+
ffmpeg,
|
|
361
|
+
"-v",
|
|
362
|
+
"error",
|
|
363
|
+
"-noautorotate",
|
|
364
|
+
"-i",
|
|
365
|
+
str(video_filename),
|
|
366
|
+
"-map",
|
|
367
|
+
"0:v:0",
|
|
368
|
+
"-an",
|
|
369
|
+
"-sn",
|
|
370
|
+
"-dn",
|
|
371
|
+
"-fps_mode",
|
|
372
|
+
"passthrough",
|
|
373
|
+
"-f",
|
|
374
|
+
"rawvideo",
|
|
375
|
+
"-pix_fmt",
|
|
376
|
+
"gray" if grayscale else "rgb24",
|
|
377
|
+
"pipe:1",
|
|
378
|
+
]
|
|
379
|
+
with tempfile.TemporaryFile() as errors:
|
|
380
|
+
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=errors)
|
|
381
|
+
assert process.stdout is not None
|
|
382
|
+
try:
|
|
383
|
+
with CineWriter(
|
|
384
|
+
filename,
|
|
385
|
+
width=width,
|
|
386
|
+
height=height,
|
|
387
|
+
channels=channels,
|
|
388
|
+
dtype=np.uint8,
|
|
389
|
+
encoding=encoding,
|
|
390
|
+
frame_rate=frame_rate,
|
|
391
|
+
**options,
|
|
392
|
+
) as writer:
|
|
393
|
+
while True:
|
|
394
|
+
payload = bytearray(frame_bytes)
|
|
395
|
+
view = memoryview(payload)
|
|
396
|
+
position = 0
|
|
397
|
+
while position < frame_bytes:
|
|
398
|
+
size = process.stdout.readinto(view[position:])
|
|
399
|
+
if not size:
|
|
400
|
+
break
|
|
401
|
+
position += size
|
|
402
|
+
if position == 0:
|
|
403
|
+
break
|
|
404
|
+
if position != frame_bytes:
|
|
405
|
+
raise ValueError("FFmpeg returned a truncated frame")
|
|
406
|
+
writer.write_frame(np.frombuffer(payload, dtype=np.uint8).reshape(shape))
|
|
407
|
+
status = process.wait()
|
|
408
|
+
if status:
|
|
409
|
+
errors.seek(0)
|
|
410
|
+
raise RuntimeError(
|
|
411
|
+
f"FFmpeg decoding failed: {errors.read().decode(errors='replace')}"
|
|
412
|
+
)
|
|
413
|
+
if writer.frames_written == 0:
|
|
414
|
+
raise ValueError("Video contains no decoded frames")
|
|
415
|
+
finally:
|
|
416
|
+
process.stdout.close()
|
|
417
|
+
if process.poll() is None:
|
|
418
|
+
process.terminate()
|
|
419
|
+
try:
|
|
420
|
+
process.wait(timeout=5)
|
|
421
|
+
except subprocess.TimeoutExpired:
|
|
422
|
+
process.kill()
|
|
423
|
+
process.wait()
|
|
424
|
+
return Path(filename)
|