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_reader/_native.py ADDED
@@ -0,0 +1,269 @@
1
+ """Private ctypes binding for the versioned, shared Rust CINE ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ import io
7
+ import os
8
+ import threading
9
+ from functools import lru_cache
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+ from ._binary import BinaryError, select_prebuilt, validate_library
15
+
16
+
17
+ class CineInfo(ct.Structure):
18
+ _fields_ = [
19
+ ("width", ct.c_uint32),
20
+ ("height", ct.c_int32),
21
+ ("bit_count", ct.c_uint32),
22
+ ("compression", ct.c_uint32),
23
+ ("real_bpp", ct.c_uint32),
24
+ ("cfa", ct.c_uint32),
25
+ ("frame_count", ct.c_uint32),
26
+ ("first_frame", ct.c_int32),
27
+ ("channels", ct.c_uint32),
28
+ ("sample_bytes", ct.c_uint32),
29
+ ("decoded_bytes", ct.c_uint64),
30
+ ("file_size", ct.c_uint64),
31
+ ]
32
+
33
+
34
+ class FrameInfo(ct.Structure):
35
+ _fields_ = [("annotation_size", ct.c_uint32), ("image_size", ct.c_uint32)]
36
+
37
+
38
+ class WriterOptions(ct.Structure):
39
+ _fields_ = [
40
+ (name, ct.c_uint32)
41
+ for name in ("width", "height", "channels", "bit_depth", "packed10", "frame_count")
42
+ ] + [("first_frame", ct.c_int32), ("cfa", ct.c_uint32), ("frame_rate", ct.c_double)]
43
+
44
+
45
+ def _path(path) -> bytes:
46
+ return str(Path(path)).encode("utf-8")
47
+
48
+
49
+ @lru_cache(maxsize=1)
50
+ def library() -> ct.CDLL:
51
+ override = os.environ.get("CINE_READER_LIBRARY")
52
+ source = Path(__file__).resolve()
53
+ try:
54
+ if override:
55
+ path = Path(override) # Explicit maintainer/test override, still ABI-checked below.
56
+ elif (source.parents[3] / "rust/cine-core/Cargo.toml").is_file():
57
+ root = source.parents[3]
58
+ try:
59
+ path, _ = validate_library(source.parent / "libs", root)
60
+ except BinaryError:
61
+ path, _ = select_prebuilt(root)
62
+ else:
63
+ path, _ = validate_library(source.parent / "libs")
64
+ try:
65
+ lib = ct.CDLL(str(path))
66
+ except OSError as exc:
67
+ raise BinaryError(f"Cannot load the native CINE backend {path}: {exc}") from exc
68
+ except BinaryError as exc:
69
+ raise ImportError(str(exc)) from exc
70
+ p, z, u, i, b = ct.c_void_p, ct.c_size_t, ct.c_uint32, ct.c_int32, ct.c_char_p
71
+ signatures = {
72
+ "cine_abi_version": (u, []),
73
+ "cine_last_error": (b, []),
74
+ "cine_reader_open": (p, [b]),
75
+ "cine_reader_close": (None, [p]),
76
+ "cine_reader_info": (i, [p, ct.POINTER(CineInfo)]),
77
+ "cine_reader_offset": (i, [p, u, ct.POINTER(ct.c_uint64)]),
78
+ "cine_reader_block": (i, [p, u, p, z, ct.POINTER(z)]),
79
+ "cine_reader_read_at": (i, [p, ct.c_uint64, p, z]),
80
+ "cine_reader_read_frame": (i, [p, u, u, p, z, ct.POINTER(FrameInfo)]),
81
+ "cine_reader_trim": (i, [p, b, u, u]),
82
+ "cine_decode": (i, [p, z, u, i, u, u, u, p, z]),
83
+ "cine_unpack10": (i, [p, z, p, z]),
84
+ "cine_writer_create": (p, [b, ct.POINTER(WriterOptions)]),
85
+ "cine_writer_write": (i, [p, p, z]),
86
+ "cine_writer_write_image": (i, [p, p, z, u, u]),
87
+ "cine_writer_finish": (i, [p]),
88
+ "cine_writer_close": (None, [p]),
89
+ "cine_process": (i, [p, p, u, u, u, u, u, u, ct.c_double]),
90
+ "cine_stats_create": (p, [z, u, u, ct.c_double, ct.c_double, u]),
91
+ "cine_stats_push": (i, [p, p, z]),
92
+ "cine_stats_finish": (i, [p, p, z, ct.POINTER(ct.c_uint64)]),
93
+ "cine_stats_close": (None, [p]),
94
+ }
95
+ for symbol, (result, args) in signatures.items():
96
+ function = getattr(lib, symbol)
97
+ function.restype, function.argtypes = result, args
98
+ if lib.cine_abi_version() != 1:
99
+ raise ImportError("Incompatible Rust CINE ABI; rebuild or reinstall cine-handler")
100
+ return lib
101
+
102
+
103
+ def check(status: int, lib=None) -> None:
104
+ if status != 0:
105
+ raw = (lib or library()).cine_last_error()
106
+ message = raw.decode("utf-8", errors="replace") if raw else "Unknown CINE backend error"
107
+ raise ValueError(message)
108
+
109
+
110
+ class NativeReader(io.RawIOBase):
111
+ """Own the Rust handle and expose legacy file-like metadata access."""
112
+
113
+ def __init__(self, filename):
114
+ super().__init__()
115
+ self.lib = library()
116
+ self._lock = threading.RLock()
117
+ self._handle = self.lib.cine_reader_open(_path(filename))
118
+ if not self._handle:
119
+ check(-1, self.lib)
120
+ self.info = CineInfo()
121
+ check(self.lib.cine_reader_info(self._handle, ct.byref(self.info)), self.lib)
122
+ self._position = 0
123
+
124
+ def _require_open(self):
125
+ if not self._handle:
126
+ raise ValueError("I/O operation on closed CINE file")
127
+
128
+ def block(self, kind: int) -> bytes:
129
+ with self._lock:
130
+ self._require_open()
131
+ length = ct.c_size_t()
132
+ check(
133
+ self.lib.cine_reader_block(self._handle, kind, None, 0, ct.byref(length)), self.lib
134
+ )
135
+ output = ct.create_string_buffer(length.value)
136
+ check(
137
+ self.lib.cine_reader_block(
138
+ self._handle, kind, output, length.value, ct.byref(length)
139
+ ),
140
+ self.lib,
141
+ )
142
+ return output.raw[: length.value]
143
+
144
+ def offset(self, index: int) -> int:
145
+ if index < 0 or index > self.info.frame_count:
146
+ raise IndexError("Image offset index out of bounds")
147
+ with self._lock:
148
+ self._require_open()
149
+ value = ct.c_uint64()
150
+ check(self.lib.cine_reader_offset(self._handle, index, ct.byref(value)), self.lib)
151
+ return value.value
152
+
153
+ def load(self, index: int, *, flags: int = 0, annotations: bool = False):
154
+ if index < 0 or index >= self.info.frame_count:
155
+ raise IndexError("image_no is out of bounds")
156
+ shape = (abs(self.info.height), self.info.width)
157
+ if self.info.channels != 1:
158
+ shape += (self.info.channels,)
159
+ frame = np.empty(shape, dtype=np.uint8 if self.info.sample_bytes == 1 else "<u2")
160
+ details = FrameInfo()
161
+ with self._lock:
162
+ self._require_open()
163
+ check(
164
+ self.lib.cine_reader_read_frame(
165
+ self._handle, index, flags, frame.ctypes.data, frame.nbytes, ct.byref(details)
166
+ ),
167
+ self.lib,
168
+ )
169
+ annotation = self.block(3) if annotations else b""
170
+ return frame, details, annotation
171
+
172
+ def trim(self, filename, index: int, count: int):
173
+ with self._lock:
174
+ self._require_open()
175
+ check(self.lib.cine_reader_trim(self._handle, _path(filename), index, count), self.lib)
176
+
177
+ def read(self, size: int = -1) -> bytes:
178
+ with self._lock:
179
+ self._require_open()
180
+ available = max(0, self.info.file_size - self._position)
181
+ size = available if size is None or size < 0 else min(int(size), available)
182
+ output = ct.create_string_buffer(size)
183
+ check(
184
+ self.lib.cine_reader_read_at(self._handle, self._position, output, size), self.lib
185
+ )
186
+ self._position += size
187
+ return output.raw
188
+
189
+ def seek(self, offset: int, whence: int = 0) -> int:
190
+ with self._lock:
191
+ self._require_open()
192
+ base = (
193
+ 0
194
+ if whence == 0
195
+ else self._position
196
+ if whence == 1
197
+ else self.info.file_size
198
+ if whence == 2
199
+ else None
200
+ )
201
+ if base is None or base + offset < 0:
202
+ raise ValueError("Invalid seek")
203
+ self._position = int(base + offset)
204
+ return self._position
205
+
206
+ def tell(self) -> int:
207
+ return self._position
208
+
209
+ def readable(self):
210
+ return True
211
+
212
+ def seekable(self):
213
+ return True
214
+
215
+ def close(self):
216
+ lock = getattr(self, "_lock", None)
217
+ if lock is not None:
218
+ with lock:
219
+ handle, self._handle = getattr(self, "_handle", None), None
220
+ if handle:
221
+ self.lib.cine_reader_close(handle)
222
+ super().close()
223
+
224
+
225
+ class NativeWriter:
226
+ def __init__(self, filename, **options):
227
+ for name in ("width", "height", "channels", "bit_depth", "frame_count", "cfa"):
228
+ if not 0 <= options[name] <= 0xFFFFFFFF:
229
+ raise ValueError(f"{name} is outside the uint32 range")
230
+ if not -(1 << 31) <= options["first_frame"] < (1 << 31):
231
+ raise ValueError("first_frame is outside the int32 range")
232
+ self.lib = library()
233
+ self._lock = threading.RLock()
234
+ config = WriterOptions(**options)
235
+ self._handle = self.lib.cine_writer_create(_path(filename), ct.byref(config))
236
+ if not self._handle:
237
+ check(-1, self.lib)
238
+
239
+ def write_frame(self, frame: np.ndarray):
240
+ with self._lock:
241
+ if not self._handle:
242
+ raise RuntimeError("CINE writer is closed")
243
+ check(
244
+ self.lib.cine_writer_write_image(
245
+ self._handle,
246
+ frame.ctypes.data,
247
+ frame.nbytes,
248
+ frame.dtype.itemsize,
249
+ frame.shape[2] if frame.ndim == 3 else 1,
250
+ ),
251
+ self.lib,
252
+ )
253
+
254
+ def finish(self):
255
+ with self._lock:
256
+ if not self._handle:
257
+ raise RuntimeError("CINE writer is closed")
258
+ check(self.lib.cine_writer_finish(self._handle), self.lib)
259
+
260
+ def close(self):
261
+ lock = getattr(self, "_lock", None)
262
+ if lock is not None:
263
+ with lock:
264
+ handle, self._handle = getattr(self, "_handle", None), None
265
+ if handle:
266
+ self.lib.cine_writer_close(handle)
267
+
268
+ def __del__(self):
269
+ self.close()