ponkan-python 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.
- ponkan_python-0.1.0.dist-info/METADATA +157 -0
- ponkan_python-0.1.0.dist-info/RECORD +39 -0
- ponkan_python-0.1.0.dist-info/WHEEL +4 -0
- ponkan_python-0.1.0.dist-info/entry_points.txt +5 -0
- ponkan_python-0.1.0.dist-info/licenses/LICENSE +22 -0
- ponkan_python-0.1.0.dist-info/licenses/NOTICE.md +14 -0
- py3dscapture/__init__.py +36 -0
- py3dscapture/artifacts.py +66 -0
- py3dscapture/capture.py +599 -0
- py3dscapture/devices/__init__.py +1 -0
- py3dscapture/devices/n3dsxl_ftd3.py +238 -0
- py3dscapture/errors.py +120 -0
- py3dscapture/hardware_gate.py +143 -0
- py3dscapture/image/__init__.py +1 -0
- py3dscapture/image/frame.py +166 -0
- py3dscapture/protocol/__init__.py +1 -0
- py3dscapture/protocol/layout_3ds.py +60 -0
- py3dscapture/protocol/n3dsxl.py +249 -0
- py3dscapture/protocol/sizes.py +128 -0
- py3dscapture/py.typed +1 -0
- py3dscapture/streaming/__init__.py +1 -0
- py3dscapture/streaming/buffers.py +156 -0
- py3dscapture/streaming/engine.py +285 -0
- py3dscapture/streaming/policies.py +157 -0
- py3dscapture/streaming/stats.py +254 -0
- py3dscapture/tools/__init__.py +1 -0
- py3dscapture/tools/capture_raw.py +44 -0
- py3dscapture/tools/list_devices.py +68 -0
- py3dscapture/tools/raw_to_png.py +251 -0
- py3dscapture/tools/stream_n3dsxl.py +152 -0
- py3dscapture/transport/__init__.py +1 -0
- py3dscapture/transport/d3xx_backend.py +850 -0
- py3dscapture/transport/d3xx_native.py +268 -0
- py3dscapture/transport/d3xx_native_streaming.py +306 -0
- py3dscapture/transport/d3xx_streaming.py +202 -0
- py3dscapture/transport/ftd3_backend.py +275 -0
- py3dscapture/transport/ftd3_pipe.py +387 -0
- py3dscapture/transport/libusb_async.py +134 -0
- py3dscapture/transport/libusb_backend.py +357 -0
py3dscapture/capture.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
"""Raw capture models and high-level capture reader facade."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import AsyncIterator, Callable, Iterator
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Literal, Protocol, cast, overload
|
|
10
|
+
|
|
11
|
+
from py3dscapture.errors import (
|
|
12
|
+
DecodeError,
|
|
13
|
+
DeviceNotFound,
|
|
14
|
+
TransferOverflow,
|
|
15
|
+
UnsupportedOperation,
|
|
16
|
+
)
|
|
17
|
+
from py3dscapture.image.frame import CaptureFrame, ColorSpace, RGB8Array
|
|
18
|
+
from py3dscapture.streaming.policies import DropPolicy
|
|
19
|
+
from py3dscapture.streaming.stats import StreamStats
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from py3dscapture.protocol.n3dsxl import N3DSXLPipe, N3DSXLSessionIdentity
|
|
23
|
+
from py3dscapture.transport.d3xx_streaming import D3xxStreamHandle
|
|
24
|
+
from py3dscapture.transport.libusb_async import AsyncTransferBackend
|
|
25
|
+
|
|
26
|
+
CaptureSource = int | str
|
|
27
|
+
CaptureBackend = Literal["auto", "libusb", "d3xx", "d3xx-native"]
|
|
28
|
+
|
|
29
|
+
_VALID_BACKENDS = frozenset(("auto", "libusb", "d3xx", "d3xx-native"))
|
|
30
|
+
_VALID_COLORSPACES = frozenset(("RGB", "BGR"))
|
|
31
|
+
_VALID_DROP_POLICIES = frozenset(("drop_oldest", "drop_newest", "block"))
|
|
32
|
+
_COMPLETION_PROCESS_LIMIT = 8
|
|
33
|
+
_BACKEND_CONFIG_ERROR = "backend must be auto, libusb, d3xx, or d3xx-native"
|
|
34
|
+
_COLORSPACE_CONFIG_ERROR = "colorspace must be RGB or BGR"
|
|
35
|
+
_DROP_POLICY_CONFIG_ERROR = "drop_policy must be drop_oldest, drop_newest, or block"
|
|
36
|
+
_OUTPUT_QUEUE_SIZE_CONFIG_ERROR = "output_queue_size must be positive"
|
|
37
|
+
_POLL_INTERVAL_CONFIG_ERROR = "poll_interval must be positive"
|
|
38
|
+
_RAW_SLOTS_CONFIG_ERROR = "raw_slots must be positive"
|
|
39
|
+
_READ_TIMEOUT_CONFIG_ERROR = "read_timeout must be non-negative or None"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _ReadTimeoutUnset:
|
|
43
|
+
__slots__ = ()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_READ_TIMEOUT_UNSET = _ReadTimeoutUnset()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CaptureOutput(StrEnum):
|
|
50
|
+
"""Screen layout returned by ``CaptureReader.read``."""
|
|
51
|
+
|
|
52
|
+
TOP = "top"
|
|
53
|
+
BOTTOM = "bottom"
|
|
54
|
+
BOTH_VERTICAL = "both_vertical"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(slots=True)
|
|
58
|
+
class CaptureConfig:
|
|
59
|
+
"""High-level capture reader configuration."""
|
|
60
|
+
|
|
61
|
+
source: CaptureSource = 0
|
|
62
|
+
model: Literal["new_3ds_xl"] = "new_3ds_xl"
|
|
63
|
+
backend: CaptureBackend = "auto"
|
|
64
|
+
mode_3d: bool = False
|
|
65
|
+
output: CaptureOutput = CaptureOutput.BOTH_VERTICAL
|
|
66
|
+
colorspace: ColorSpace = "RGB"
|
|
67
|
+
raw_slots: int = 2
|
|
68
|
+
output_queue_size: int = 2
|
|
69
|
+
drop_policy: DropPolicy = "drop_oldest"
|
|
70
|
+
poll_interval: float = 0.004
|
|
71
|
+
read_timeout: float | None = 1.0
|
|
72
|
+
collect_timing: bool = False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class CaptureReaderEngine(Protocol):
|
|
76
|
+
"""Streaming engine surface consumed by ``CaptureReader``."""
|
|
77
|
+
|
|
78
|
+
def start(self) -> None:
|
|
79
|
+
"""Start frame acquisition."""
|
|
80
|
+
...
|
|
81
|
+
|
|
82
|
+
def process_completed(self, *, limit: int | None = None) -> int:
|
|
83
|
+
"""Process pending backend completions."""
|
|
84
|
+
...
|
|
85
|
+
|
|
86
|
+
def frames(self, *, max_frames: int | None = None) -> Iterator[CaptureFrame]:
|
|
87
|
+
"""Yield currently queued decoded frames."""
|
|
88
|
+
...
|
|
89
|
+
|
|
90
|
+
def stop(self, timeout: float | None = None) -> None:
|
|
91
|
+
"""Stop acquisition and release owned backend resources."""
|
|
92
|
+
...
|
|
93
|
+
|
|
94
|
+
def stats(self) -> StreamStats:
|
|
95
|
+
"""Return streaming counters."""
|
|
96
|
+
...
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class _D3xxHandle(Protocol):
|
|
100
|
+
def close(self) -> None:
|
|
101
|
+
"""Close the opened transport handle."""
|
|
102
|
+
...
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class _D3xxBackend(Protocol):
|
|
106
|
+
def iter_device_candidates(self) -> tuple[object, ...]:
|
|
107
|
+
"""Return accepted N3DSXL candidates visible through the backend."""
|
|
108
|
+
...
|
|
109
|
+
|
|
110
|
+
def open(self, candidate: object) -> _D3xxHandle:
|
|
111
|
+
"""Open one accepted candidate."""
|
|
112
|
+
...
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class _N3DSXLConnectProtocol(Protocol):
|
|
116
|
+
def connect(self, *, mode_3d: bool) -> None:
|
|
117
|
+
"""Run the N3DSXL connect sequence."""
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
CaptureOpener = Callable[[CaptureConfig], CaptureReaderEngine]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(slots=True)
|
|
125
|
+
class CaptureReader:
|
|
126
|
+
"""High-level reader that returns decoded N3DSXL frames or selected arrays."""
|
|
127
|
+
|
|
128
|
+
engine: CaptureReaderEngine
|
|
129
|
+
config: CaptureConfig = field(default_factory=CaptureConfig)
|
|
130
|
+
_started: bool = False
|
|
131
|
+
_closed: bool = False
|
|
132
|
+
|
|
133
|
+
def read(
|
|
134
|
+
self,
|
|
135
|
+
*,
|
|
136
|
+
output: CaptureOutput | str | None = None,
|
|
137
|
+
colorspace: ColorSpace | None = None,
|
|
138
|
+
timeout: float | None = None,
|
|
139
|
+
) -> RGB8Array | None:
|
|
140
|
+
"""Return the next selected screen layout as an RGB or BGR ndarray.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
output: Screen layout to return. ``None`` uses reader config.
|
|
144
|
+
colorspace: Channel order to return. ``None`` uses reader config.
|
|
145
|
+
timeout: Optional timeout override in seconds. ``None`` uses reader
|
|
146
|
+
config.
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
A copied ``uint8`` ndarray, or ``None`` when no frame arrives before
|
|
150
|
+
the effective timeout.
|
|
151
|
+
"""
|
|
152
|
+
frame = self.read_frame(timeout=timeout)
|
|
153
|
+
if frame is None:
|
|
154
|
+
return None
|
|
155
|
+
selected_output = _coerce_output(self.config.output if output is None else output)
|
|
156
|
+
selected_colorspace = self.config.colorspace if colorspace is None else colorspace
|
|
157
|
+
_validate_colorspace(selected_colorspace)
|
|
158
|
+
if selected_output == CaptureOutput.TOP:
|
|
159
|
+
return frame.to_ndarray("top", selected_colorspace)
|
|
160
|
+
if selected_output == CaptureOutput.BOTTOM:
|
|
161
|
+
return frame.to_ndarray("bottom", selected_colorspace)
|
|
162
|
+
mosaic = frame.to_mosaic(gap=0)
|
|
163
|
+
if selected_colorspace == "RGB":
|
|
164
|
+
return mosaic
|
|
165
|
+
return mosaic[..., ::-1].copy()
|
|
166
|
+
|
|
167
|
+
def read_frame(self, *, timeout: float | None = None) -> CaptureFrame | None:
|
|
168
|
+
"""Return the latest decoded ``CaptureFrame`` available before timeout.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
timeout: Optional timeout override in seconds. ``None`` uses reader
|
|
172
|
+
config.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
Latest decoded frame from the currently queued frames, or ``None``
|
|
176
|
+
on timeout or after close.
|
|
177
|
+
"""
|
|
178
|
+
if self._closed:
|
|
179
|
+
return None
|
|
180
|
+
self._ensure_started()
|
|
181
|
+
timeout_seconds = self.config.read_timeout if timeout is None else timeout
|
|
182
|
+
deadline = None if timeout_seconds is None else time.monotonic() + timeout_seconds
|
|
183
|
+
while True:
|
|
184
|
+
self.engine.process_completed(limit=_COMPLETION_PROCESS_LIMIT)
|
|
185
|
+
latest = self._latest_available_frame()
|
|
186
|
+
if latest is not None:
|
|
187
|
+
return latest
|
|
188
|
+
if deadline is not None:
|
|
189
|
+
remaining = deadline - time.monotonic()
|
|
190
|
+
if remaining <= 0:
|
|
191
|
+
return None
|
|
192
|
+
time.sleep(min(self.config.poll_interval, remaining))
|
|
193
|
+
else:
|
|
194
|
+
time.sleep(self.config.poll_interval)
|
|
195
|
+
|
|
196
|
+
def stats(self) -> StreamStats:
|
|
197
|
+
"""Return a snapshot of streaming counters."""
|
|
198
|
+
return self.engine.stats()
|
|
199
|
+
|
|
200
|
+
def close(self) -> None:
|
|
201
|
+
"""Stop acquisition and release resources once."""
|
|
202
|
+
if self._closed:
|
|
203
|
+
return
|
|
204
|
+
self._closed = True
|
|
205
|
+
self.engine.stop()
|
|
206
|
+
|
|
207
|
+
def __enter__(self) -> "CaptureReader":
|
|
208
|
+
"""Return this reader for context-manager use."""
|
|
209
|
+
return self
|
|
210
|
+
|
|
211
|
+
def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
|
|
212
|
+
"""Close the reader when leaving a context manager."""
|
|
213
|
+
_ = exc_type, exc, traceback
|
|
214
|
+
self.close()
|
|
215
|
+
|
|
216
|
+
def _ensure_started(self) -> None:
|
|
217
|
+
if self._started:
|
|
218
|
+
return
|
|
219
|
+
self.engine.start()
|
|
220
|
+
self._started = True
|
|
221
|
+
|
|
222
|
+
def _latest_available_frame(self) -> CaptureFrame | None:
|
|
223
|
+
latest: CaptureFrame | None = None
|
|
224
|
+
for frame in self.engine.frames():
|
|
225
|
+
latest = frame
|
|
226
|
+
return latest
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@overload
|
|
230
|
+
def open_capture(
|
|
231
|
+
source: CaptureSource = 0,
|
|
232
|
+
*,
|
|
233
|
+
config: CaptureConfig | None = None,
|
|
234
|
+
backend: CaptureBackend | None = None,
|
|
235
|
+
output: CaptureOutput | str | None = None,
|
|
236
|
+
colorspace: ColorSpace | None = None,
|
|
237
|
+
read_timeout: float | None = None,
|
|
238
|
+
_opener: "CaptureOpener | None" = None,
|
|
239
|
+
) -> CaptureReader: ...
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@overload
|
|
243
|
+
def open_capture(
|
|
244
|
+
source: CaptureSource = 0,
|
|
245
|
+
*,
|
|
246
|
+
config: CaptureConfig | None = None,
|
|
247
|
+
backend: CaptureBackend | None = None,
|
|
248
|
+
output: CaptureOutput | str | None = None,
|
|
249
|
+
colorspace: ColorSpace | None = None,
|
|
250
|
+
_opener: "CaptureOpener | None" = None,
|
|
251
|
+
) -> CaptureReader: ...
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def open_capture(
|
|
255
|
+
source: CaptureSource = 0,
|
|
256
|
+
*,
|
|
257
|
+
config: CaptureConfig | None = None,
|
|
258
|
+
backend: CaptureBackend | None = None,
|
|
259
|
+
output: CaptureOutput | str | None = None,
|
|
260
|
+
colorspace: ColorSpace | None = None,
|
|
261
|
+
read_timeout: float | None | _ReadTimeoutUnset = _READ_TIMEOUT_UNSET,
|
|
262
|
+
_opener: "CaptureOpener | None" = None,
|
|
263
|
+
) -> CaptureReader:
|
|
264
|
+
"""Open a high-level N3DSXL capture reader.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
source: Initial source selector. ``0`` and ``"new_3ds_xl"`` are
|
|
268
|
+
supported by the MVP.
|
|
269
|
+
config: Optional base configuration.
|
|
270
|
+
backend: Optional backend preference override.
|
|
271
|
+
output: Optional default output layout override.
|
|
272
|
+
colorspace: Optional default output color-space override.
|
|
273
|
+
read_timeout: Optional default read timeout override.
|
|
274
|
+
_opener: Internal test injection. Production callers should omit it.
|
|
275
|
+
|
|
276
|
+
Returns:
|
|
277
|
+
Open high-level reader.
|
|
278
|
+
"""
|
|
279
|
+
resolved = _resolve_config(
|
|
280
|
+
source=source,
|
|
281
|
+
config=config,
|
|
282
|
+
backend=backend,
|
|
283
|
+
output=output,
|
|
284
|
+
colorspace=colorspace,
|
|
285
|
+
read_timeout=read_timeout,
|
|
286
|
+
)
|
|
287
|
+
opener = _open_hardware_engine if _opener is None else _opener
|
|
288
|
+
return CaptureReader(opener(resolved), config=resolved)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _resolve_config(
|
|
292
|
+
*,
|
|
293
|
+
source: CaptureSource,
|
|
294
|
+
config: CaptureConfig | None,
|
|
295
|
+
backend: CaptureBackend | None,
|
|
296
|
+
output: CaptureOutput | str | None,
|
|
297
|
+
colorspace: ColorSpace | None,
|
|
298
|
+
read_timeout: float | None | _ReadTimeoutUnset,
|
|
299
|
+
) -> CaptureConfig:
|
|
300
|
+
resolved = config or CaptureConfig(source=source)
|
|
301
|
+
if config is not None and source != 0:
|
|
302
|
+
resolved = replace(resolved, source=source)
|
|
303
|
+
if backend is not None:
|
|
304
|
+
resolved = replace(resolved, backend=backend)
|
|
305
|
+
if output is not None:
|
|
306
|
+
resolved = replace(resolved, output=_coerce_output(output))
|
|
307
|
+
if colorspace is not None:
|
|
308
|
+
resolved = replace(resolved, colorspace=colorspace)
|
|
309
|
+
if not isinstance(read_timeout, _ReadTimeoutUnset):
|
|
310
|
+
resolved = replace(resolved, read_timeout=read_timeout)
|
|
311
|
+
_validate_config(resolved)
|
|
312
|
+
return resolved
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _validate_config(config: CaptureConfig) -> None:
|
|
316
|
+
if config.source not in (0, "new_3ds_xl"):
|
|
317
|
+
raise UnsupportedOperation
|
|
318
|
+
if config.model != "new_3ds_xl":
|
|
319
|
+
raise UnsupportedOperation
|
|
320
|
+
if config.backend not in _VALID_BACKENDS:
|
|
321
|
+
raise ValueError(_BACKEND_CONFIG_ERROR)
|
|
322
|
+
if config.mode_3d:
|
|
323
|
+
raise UnsupportedOperation
|
|
324
|
+
_coerce_output(config.output)
|
|
325
|
+
_validate_colorspace(config.colorspace)
|
|
326
|
+
if config.raw_slots <= 0:
|
|
327
|
+
raise ValueError(_RAW_SLOTS_CONFIG_ERROR)
|
|
328
|
+
if config.output_queue_size <= 0:
|
|
329
|
+
raise ValueError(_OUTPUT_QUEUE_SIZE_CONFIG_ERROR)
|
|
330
|
+
if config.drop_policy not in _VALID_DROP_POLICIES:
|
|
331
|
+
raise ValueError(_DROP_POLICY_CONFIG_ERROR)
|
|
332
|
+
if config.poll_interval <= 0:
|
|
333
|
+
raise ValueError(_POLL_INTERVAL_CONFIG_ERROR)
|
|
334
|
+
if config.read_timeout is not None and config.read_timeout < 0:
|
|
335
|
+
raise ValueError(_READ_TIMEOUT_CONFIG_ERROR)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _coerce_output(output: CaptureOutput | str) -> CaptureOutput:
|
|
339
|
+
if isinstance(output, CaptureOutput):
|
|
340
|
+
return output
|
|
341
|
+
return CaptureOutput(output)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _validate_colorspace(colorspace: str) -> None:
|
|
345
|
+
if colorspace not in _VALID_COLORSPACES:
|
|
346
|
+
raise ValueError(_COLORSPACE_CONFIG_ERROR)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _open_hardware_engine(config: CaptureConfig) -> CaptureReaderEngine:
|
|
350
|
+
if config.backend == "libusb":
|
|
351
|
+
raise UnsupportedOperation
|
|
352
|
+
native = config.backend == "d3xx-native"
|
|
353
|
+
return _open_d3xx_engine(config, native=native)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _open_d3xx_engine(config: CaptureConfig, *, native: bool) -> CaptureReaderEngine:
|
|
357
|
+
backend = _new_d3xx_backend()
|
|
358
|
+
candidates = backend.iter_device_candidates()
|
|
359
|
+
if not candidates:
|
|
360
|
+
raise DeviceNotFound
|
|
361
|
+
d3xx_candidate = candidates[0]
|
|
362
|
+
handle = backend.open(d3xx_candidate)
|
|
363
|
+
try:
|
|
364
|
+
protocol = _new_n3dsxl_protocol(handle)
|
|
365
|
+
protocol.connect(mode_3d=False)
|
|
366
|
+
async_backend = (
|
|
367
|
+
_new_d3xx_native_backend(handle, config) if native else _new_d3xx_backend_async(handle)
|
|
368
|
+
)
|
|
369
|
+
return _new_streaming_engine(async_backend, config)
|
|
370
|
+
except Exception:
|
|
371
|
+
handle.close()
|
|
372
|
+
raise
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _new_d3xx_backend() -> _D3xxBackend:
|
|
376
|
+
from py3dscapture.transport.d3xx_backend import D3xxBackend # noqa: PLC0415
|
|
377
|
+
|
|
378
|
+
return D3xxBackend()
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _new_n3dsxl_protocol(handle: _D3xxHandle) -> _N3DSXLConnectProtocol:
|
|
382
|
+
from py3dscapture.protocol.n3dsxl import N3DSXLProtocol # noqa: PLC0415
|
|
383
|
+
|
|
384
|
+
return N3DSXLProtocol(
|
|
385
|
+
cast("N3DSXLSessionIdentity", handle),
|
|
386
|
+
cast("N3DSXLPipe", handle),
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _new_d3xx_backend_async(handle: _D3xxHandle) -> object:
|
|
391
|
+
from py3dscapture.transport.d3xx_streaming import D3xxAsyncBackend # noqa: PLC0415
|
|
392
|
+
|
|
393
|
+
return D3xxAsyncBackend(cast("D3xxStreamHandle", handle))
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _new_d3xx_native_backend(handle: _D3xxHandle, config: CaptureConfig) -> object:
|
|
397
|
+
from py3dscapture.transport.d3xx_native_streaming import ( # noqa: PLC0415
|
|
398
|
+
D3xxNativeFastPathBackend,
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
return D3xxNativeFastPathBackend(handle, slot_count=config.raw_slots)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _new_streaming_engine(async_backend: object, config: CaptureConfig) -> CaptureReaderEngine:
|
|
405
|
+
from py3dscapture.streaming.engine import StreamingEngine # noqa: PLC0415
|
|
406
|
+
|
|
407
|
+
return StreamingEngine(
|
|
408
|
+
cast("AsyncTransferBackend", async_backend),
|
|
409
|
+
raw_slots=config.raw_slots,
|
|
410
|
+
output_queue_size=config.output_queue_size,
|
|
411
|
+
drop_policy=config.drop_policy,
|
|
412
|
+
collect_timing=config.collect_timing,
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@dataclass(slots=True)
|
|
417
|
+
class RawCapture:
|
|
418
|
+
"""Raw transfer payload and metadata for one capture frame.
|
|
419
|
+
|
|
420
|
+
Attributes:
|
|
421
|
+
model: Capture target model that produced the payload.
|
|
422
|
+
mode_3d: Whether the transfer was captured in 3D mode.
|
|
423
|
+
payload: Raw bytes returned by the transport. Only the first
|
|
424
|
+
``transferred`` bytes are considered part of the transfer.
|
|
425
|
+
transferred: Number of bytes reported by the transport.
|
|
426
|
+
video_size: Number of RGB8 video bytes expected at the start of the
|
|
427
|
+
payload.
|
|
428
|
+
capture_size: Maximum accepted transfer size for the selected mode.
|
|
429
|
+
timestamp_ns: Optional monotonic timestamp associated with completion.
|
|
430
|
+
sequence: Optional stream sequence number.
|
|
431
|
+
metadata: Additional JSON-serializable capture metadata.
|
|
432
|
+
"""
|
|
433
|
+
|
|
434
|
+
model: Literal["new_3ds_xl"]
|
|
435
|
+
mode_3d: bool
|
|
436
|
+
payload: bytes
|
|
437
|
+
transferred: int
|
|
438
|
+
video_size: int
|
|
439
|
+
capture_size: int
|
|
440
|
+
timestamp_ns: int | None
|
|
441
|
+
sequence: int | None
|
|
442
|
+
metadata: dict[str, object] = field(default_factory=dict)
|
|
443
|
+
|
|
444
|
+
def __post_init__(self) -> None:
|
|
445
|
+
"""Validate transfer bounds and payload length.
|
|
446
|
+
|
|
447
|
+
Raises:
|
|
448
|
+
DecodeError: The transfer is too short for the video region, or the
|
|
449
|
+
payload does not contain the reported transfer length.
|
|
450
|
+
TransferOverflow: The transport reported more bytes than the
|
|
451
|
+
selected capture mode accepts.
|
|
452
|
+
"""
|
|
453
|
+
if self.transferred < self.video_size:
|
|
454
|
+
raise DecodeError
|
|
455
|
+
if self.transferred > self.capture_size:
|
|
456
|
+
raise TransferOverflow
|
|
457
|
+
if len(self.payload) < self.transferred:
|
|
458
|
+
raise DecodeError
|
|
459
|
+
|
|
460
|
+
def video_region(self) -> bytes:
|
|
461
|
+
"""Return the raw RGB8 video region.
|
|
462
|
+
|
|
463
|
+
Returns:
|
|
464
|
+
The leading ``video_size`` bytes from ``payload``. Audio, unused,
|
|
465
|
+
and error-buffer regions are intentionally excluded.
|
|
466
|
+
"""
|
|
467
|
+
return self.payload[: self.video_size]
|
|
468
|
+
|
|
469
|
+
def to_metadata(self) -> dict[str, object]:
|
|
470
|
+
"""Return JSON-serializable metadata.
|
|
471
|
+
|
|
472
|
+
Existing metadata is copied before standard capture fields are added.
|
|
473
|
+
``decoder_version`` and ``manual_visual_status`` are populated with
|
|
474
|
+
default values when the caller did not provide them.
|
|
475
|
+
|
|
476
|
+
Returns:
|
|
477
|
+
A JSON-serializable dictionary suitable for sidecar artifact files.
|
|
478
|
+
"""
|
|
479
|
+
data = dict(self.metadata)
|
|
480
|
+
data.update(
|
|
481
|
+
{
|
|
482
|
+
"model": self.model,
|
|
483
|
+
"mode_3d": self.mode_3d,
|
|
484
|
+
"transferred": self.transferred,
|
|
485
|
+
"video_size": self.video_size,
|
|
486
|
+
"capture_size": self.capture_size,
|
|
487
|
+
"sequence": self.sequence,
|
|
488
|
+
"timestamp_ns": self.timestamp_ns,
|
|
489
|
+
}
|
|
490
|
+
)
|
|
491
|
+
data.setdefault("decoder_version", None)
|
|
492
|
+
data.setdefault("manual_visual_status", "pending")
|
|
493
|
+
return data
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def save_raw_capture(
|
|
497
|
+
capture: RawCapture,
|
|
498
|
+
out_path: Path,
|
|
499
|
+
*,
|
|
500
|
+
force: bool = False,
|
|
501
|
+
) -> tuple[Path, Path]:
|
|
502
|
+
"""Save raw bytes and JSON metadata using the same stem.
|
|
503
|
+
|
|
504
|
+
The binary file is written to ``out_path``. The metadata file is written
|
|
505
|
+
next to it with the same stem and a ``.json`` suffix.
|
|
506
|
+
|
|
507
|
+
Args:
|
|
508
|
+
capture: Raw capture whose payload contains at least ``transferred``
|
|
509
|
+
bytes.
|
|
510
|
+
out_path: Destination path for the raw binary payload.
|
|
511
|
+
force: Overwrite an existing binary or metadata file when true.
|
|
512
|
+
|
|
513
|
+
Returns:
|
|
514
|
+
``(bin_path, metadata_path)`` for the files written by this call.
|
|
515
|
+
|
|
516
|
+
Raises:
|
|
517
|
+
FileExistsError: Either destination exists and ``force`` is false.
|
|
518
|
+
"""
|
|
519
|
+
bin_path = out_path
|
|
520
|
+
metadata_path = out_path.with_suffix(".json")
|
|
521
|
+
if not force and (bin_path.exists() or metadata_path.exists()):
|
|
522
|
+
raise FileExistsError
|
|
523
|
+
|
|
524
|
+
bin_path.parent.mkdir(parents=True, exist_ok=True)
|
|
525
|
+
bin_path.write_bytes(capture.payload[: capture.transferred])
|
|
526
|
+
metadata_path.write_text(
|
|
527
|
+
json.dumps(capture.to_metadata(), indent=2, sort_keys=True),
|
|
528
|
+
encoding="utf-8",
|
|
529
|
+
)
|
|
530
|
+
return bin_path, metadata_path
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
class FrameEngine(Protocol):
|
|
534
|
+
"""Small streaming engine surface exposed by CaptureSession.
|
|
535
|
+
|
|
536
|
+
Implementations may be real hardware streaming engines or test doubles.
|
|
537
|
+
They are expected to yield already decoded ``CaptureFrame`` objects.
|
|
538
|
+
"""
|
|
539
|
+
|
|
540
|
+
def frames(self, *, max_frames: int | None = None) -> Iterator[CaptureFrame]:
|
|
541
|
+
"""Yield decoded frames.
|
|
542
|
+
|
|
543
|
+
Args:
|
|
544
|
+
max_frames: Maximum number of frames to yield, or ``None`` to yield
|
|
545
|
+
until the engine has no currently available frame.
|
|
546
|
+
|
|
547
|
+
Yields:
|
|
548
|
+
Decoded capture frames from the engine.
|
|
549
|
+
"""
|
|
550
|
+
...
|
|
551
|
+
|
|
552
|
+
def frames_async(self, *, max_frames: int | None = None) -> AsyncIterator[CaptureFrame]:
|
|
553
|
+
"""Yield decoded frames asynchronously.
|
|
554
|
+
|
|
555
|
+
Args:
|
|
556
|
+
max_frames: Maximum number of frames to yield, or ``None`` to yield
|
|
557
|
+
until the engine has no currently available frame.
|
|
558
|
+
|
|
559
|
+
Yields:
|
|
560
|
+
Decoded capture frames from the engine.
|
|
561
|
+
"""
|
|
562
|
+
...
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
@dataclass(slots=True)
|
|
566
|
+
class CaptureSession:
|
|
567
|
+
"""Public capture session facade.
|
|
568
|
+
|
|
569
|
+
Attributes:
|
|
570
|
+
engine: Streaming engine or compatible test double that owns frame
|
|
571
|
+
production.
|
|
572
|
+
"""
|
|
573
|
+
|
|
574
|
+
engine: FrameEngine
|
|
575
|
+
|
|
576
|
+
def frames(self, *, max_frames: int | None = None) -> Iterator[CaptureFrame]:
|
|
577
|
+
"""Yield decoded frames from the underlying engine.
|
|
578
|
+
|
|
579
|
+
Args:
|
|
580
|
+
max_frames: Maximum number of frames to yield, or ``None`` to yield
|
|
581
|
+
all currently available frames.
|
|
582
|
+
|
|
583
|
+
Yields:
|
|
584
|
+
Decoded capture frames.
|
|
585
|
+
"""
|
|
586
|
+
yield from self.engine.frames(max_frames=max_frames)
|
|
587
|
+
|
|
588
|
+
async def frames_async(self, *, max_frames: int | None = None) -> AsyncIterator[CaptureFrame]:
|
|
589
|
+
"""Yield decoded frames asynchronously from the underlying engine.
|
|
590
|
+
|
|
591
|
+
Args:
|
|
592
|
+
max_frames: Maximum number of frames to yield, or ``None`` to yield
|
|
593
|
+
all currently available frames.
|
|
594
|
+
|
|
595
|
+
Yields:
|
|
596
|
+
Decoded capture frames.
|
|
597
|
+
"""
|
|
598
|
+
async for frame in self.engine.frames_async(max_frames=max_frames):
|
|
599
|
+
yield frame
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Capture device helpers."""
|