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
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""N3DSXL device filtering and session ownership."""
|
|
2
|
+
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Literal, cast
|
|
6
|
+
|
|
7
|
+
from py3dscapture.errors import DeviceOpenError, UnsupportedDevice
|
|
8
|
+
from py3dscapture.protocol.sizes import (
|
|
9
|
+
ACCEPTED_N3DSXL_PRODUCT_IDS,
|
|
10
|
+
ACCEPTED_N3DSXL_PRODUCT_STRINGS,
|
|
11
|
+
N3DSXL_BULK_INTERFACE,
|
|
12
|
+
N3DSXL_COMMAND_INTERFACE,
|
|
13
|
+
N3DSXL_DEFAULT_CONFIGURATION,
|
|
14
|
+
N3DSXL_VENDOR_ID,
|
|
15
|
+
)
|
|
16
|
+
from py3dscapture.transport.libusb_backend import LibusbBackend, UsbDeviceInfo, UsbHandle
|
|
17
|
+
|
|
18
|
+
AcceptedProductString = Literal["N3DSXL", "N3DSXL.2"]
|
|
19
|
+
ProductStringStatus = Literal["accepted", "unreadable"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class DeviceCandidate:
|
|
24
|
+
"""A USB device accepted as a new 3DS XL capture board.
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
info: USB descriptor information used to reopen the device.
|
|
28
|
+
product_string: Accepted product string, or ``None`` when unreadable.
|
|
29
|
+
product_string_status: Whether the product string was accepted or could
|
|
30
|
+
not be read.
|
|
31
|
+
model: Normalized device model exposed to higher layers.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
info: UsbDeviceInfo
|
|
35
|
+
product_string: AcceptedProductString | None
|
|
36
|
+
product_string_status: ProductStringStatus
|
|
37
|
+
model: Literal["new_3ds_xl"] = "new_3ds_xl"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class RejectedDevice:
|
|
42
|
+
"""An FTDI-family device rejected before N3DSXL commands can be sent.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
info: USB descriptor information for the rejected device.
|
|
46
|
+
reason: Stable rejection reason such as unsupported product ID or
|
|
47
|
+
product string.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
info: UsbDeviceInfo
|
|
51
|
+
reason: str
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True)
|
|
55
|
+
class DeviceListing:
|
|
56
|
+
"""Classified devices for CLI and tests.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
candidates: Devices allowed to proceed to the explicit hardware command
|
|
60
|
+
approval boundary.
|
|
61
|
+
rejected: FTDI-family devices that were deliberately excluded.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
candidates: tuple[DeviceCandidate, ...]
|
|
65
|
+
rejected: tuple[RejectedDevice, ...]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def classify_n3dsxl_device(info: UsbDeviceInfo) -> DeviceCandidate | RejectedDevice | None:
|
|
69
|
+
"""Classify one USB device as N3DSXL candidate, rejected FTDI device, or irrelevant.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
info: USB descriptor fields gathered before opening the device.
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
``DeviceCandidate`` for accepted VID/PID and product string,
|
|
76
|
+
``RejectedDevice`` for FTDI-family devices that fail the N3DSXL safety
|
|
77
|
+
boundary, or ``None`` for unrelated vendors.
|
|
78
|
+
"""
|
|
79
|
+
if info.vendor_id != N3DSXL_VENDOR_ID:
|
|
80
|
+
return None
|
|
81
|
+
if info.product_id not in ACCEPTED_N3DSXL_PRODUCT_IDS:
|
|
82
|
+
return RejectedDevice(info=info, reason="unsupported_product_id")
|
|
83
|
+
if info.product_string is None:
|
|
84
|
+
return DeviceCandidate(
|
|
85
|
+
info=info,
|
|
86
|
+
product_string=None,
|
|
87
|
+
product_string_status="unreadable",
|
|
88
|
+
)
|
|
89
|
+
if info.product_string not in ACCEPTED_N3DSXL_PRODUCT_STRINGS:
|
|
90
|
+
return RejectedDevice(info=info, reason="unsupported_product_string")
|
|
91
|
+
return DeviceCandidate(
|
|
92
|
+
info=info,
|
|
93
|
+
product_string=cast("AcceptedProductString", info.product_string),
|
|
94
|
+
product_string_status="accepted",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def list_n3dsxl_devices(backend: LibusbBackend) -> DeviceListing:
|
|
99
|
+
"""Classify all devices visible through a backend.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
backend: USB backend used only for enumeration.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
Candidate and rejected-device groups suitable for CLI output and tests.
|
|
106
|
+
"""
|
|
107
|
+
candidates: list[DeviceCandidate] = []
|
|
108
|
+
rejected: list[RejectedDevice] = []
|
|
109
|
+
for info in backend.iter_devices():
|
|
110
|
+
classified = classify_n3dsxl_device(info)
|
|
111
|
+
if isinstance(classified, DeviceCandidate):
|
|
112
|
+
candidates.append(classified)
|
|
113
|
+
elif isinstance(classified, RejectedDevice):
|
|
114
|
+
rejected.append(classified)
|
|
115
|
+
return DeviceListing(candidates=tuple(candidates), rejected=tuple(rejected))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class N3DSXLDevice:
|
|
119
|
+
"""Open N3DSXL session owning claimed interfaces.
|
|
120
|
+
|
|
121
|
+
The session assumes the input candidate already passed device
|
|
122
|
+
classification. It owns interface release and handle close responsibility.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
candidate: DeviceCandidate,
|
|
128
|
+
handle: UsbHandle,
|
|
129
|
+
claimed_interfaces: tuple[int, ...],
|
|
130
|
+
) -> None:
|
|
131
|
+
"""Create a session from an already configured handle.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
candidate: Accepted N3DSXL candidate used for metadata and safety
|
|
135
|
+
reporting.
|
|
136
|
+
handle: Opened USB handle whose required interfaces are claimed.
|
|
137
|
+
claimed_interfaces: Interfaces this session must release on close.
|
|
138
|
+
"""
|
|
139
|
+
self.candidate = candidate
|
|
140
|
+
self.handle = handle
|
|
141
|
+
self._claimed_interfaces = list(claimed_interfaces)
|
|
142
|
+
self._closed = False
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def open(
|
|
146
|
+
cls,
|
|
147
|
+
candidate: DeviceCandidate,
|
|
148
|
+
backend: LibusbBackend,
|
|
149
|
+
) -> "N3DSXLDevice":
|
|
150
|
+
"""Open, configure, and claim a candidate device.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
candidate: Accepted N3DSXL candidate.
|
|
154
|
+
backend: USB backend used to open the descriptor.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Open session owning command and bulk interfaces.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
UnsupportedDevice: ``candidate`` is not a ``DeviceCandidate``.
|
|
161
|
+
DeviceOpenError: Opening, configuration, interface claim, cleanup, or
|
|
162
|
+
final close fails through the backend.
|
|
163
|
+
"""
|
|
164
|
+
if not isinstance(candidate, DeviceCandidate):
|
|
165
|
+
raise UnsupportedDevice
|
|
166
|
+
handle = backend.open(candidate.info)
|
|
167
|
+
claimed_interfaces: list[int] = []
|
|
168
|
+
try:
|
|
169
|
+
for interface in (N3DSXL_COMMAND_INTERFACE, N3DSXL_BULK_INTERFACE):
|
|
170
|
+
handle.detach_kernel_driver(interface)
|
|
171
|
+
handle.set_configuration(N3DSXL_DEFAULT_CONFIGURATION)
|
|
172
|
+
handle.claim_interface(N3DSXL_COMMAND_INTERFACE)
|
|
173
|
+
claimed_interfaces.append(N3DSXL_COMMAND_INTERFACE)
|
|
174
|
+
handle.claim_interface(N3DSXL_BULK_INTERFACE)
|
|
175
|
+
claimed_interfaces.append(N3DSXL_BULK_INTERFACE)
|
|
176
|
+
except Exception:
|
|
177
|
+
_cleanup_failed_open(handle, claimed_interfaces)
|
|
178
|
+
raise
|
|
179
|
+
return cls(candidate=candidate, handle=handle, claimed_interfaces=tuple(claimed_interfaces))
|
|
180
|
+
|
|
181
|
+
def close(self) -> None:
|
|
182
|
+
"""Release interfaces and close the handle.
|
|
183
|
+
|
|
184
|
+
The method is idempotent for already closed sessions. If cleanup raises
|
|
185
|
+
from more than one operation, the first cleanup error is re-raised as
|
|
186
|
+
``DeviceOpenError`` after all best-effort cleanup has run.
|
|
187
|
+
|
|
188
|
+
Raises:
|
|
189
|
+
DeviceOpenError: Interface release or handle close failed.
|
|
190
|
+
"""
|
|
191
|
+
if self._closed:
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
first_error: Exception | None = None
|
|
195
|
+
try:
|
|
196
|
+
for interface in reversed(self._claimed_interfaces):
|
|
197
|
+
try:
|
|
198
|
+
self.handle.release_interface(interface)
|
|
199
|
+
except Exception as exc: # noqa: BLE001 # pragma: no cover
|
|
200
|
+
if first_error is None:
|
|
201
|
+
first_error = exc
|
|
202
|
+
self._claimed_interfaces.clear()
|
|
203
|
+
try:
|
|
204
|
+
self.handle.close()
|
|
205
|
+
except Exception as exc: # noqa: BLE001 # pragma: no cover
|
|
206
|
+
if first_error is None:
|
|
207
|
+
first_error = exc
|
|
208
|
+
finally:
|
|
209
|
+
self._closed = True
|
|
210
|
+
|
|
211
|
+
if first_error is not None:
|
|
212
|
+
raise DeviceOpenError from first_error
|
|
213
|
+
|
|
214
|
+
def __enter__(self) -> "N3DSXLDevice":
|
|
215
|
+
"""Return this active session for context-manager use.
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
The open session itself.
|
|
219
|
+
"""
|
|
220
|
+
return self
|
|
221
|
+
|
|
222
|
+
def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
|
|
223
|
+
"""Close the session when leaving a context manager.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
exc_type: Exception type from the managed block, if any.
|
|
227
|
+
exc: Exception instance from the managed block, if any.
|
|
228
|
+
traceback: Traceback from the managed block, if any.
|
|
229
|
+
"""
|
|
230
|
+
self.close()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _cleanup_failed_open(handle: UsbHandle, claimed_interfaces: list[int]) -> None:
|
|
234
|
+
for interface in reversed(claimed_interfaces):
|
|
235
|
+
with suppress(Exception):
|
|
236
|
+
handle.release_interface(interface)
|
|
237
|
+
with suppress(Exception):
|
|
238
|
+
handle.close()
|
py3dscapture/errors.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Project exception hierarchy."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CaptureError(Exception):
|
|
7
|
+
"""Base exception for py3dscapture failures.
|
|
8
|
+
|
|
9
|
+
Catch this when callers want to handle package-level failures without
|
|
10
|
+
matching individual USB, decode, or optional-dependency errors.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnsupportedDevice(CaptureError): # noqa: N818
|
|
15
|
+
"""Raised when a USB device is not an accepted capture target.
|
|
16
|
+
|
|
17
|
+
The device failed the N3DSXL identity boundary or the object passed to a
|
|
18
|
+
session API was not an accepted candidate.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DeviceNotFound(CaptureError): # noqa: N818
|
|
23
|
+
"""Raised when no accepted capture device is visible to the selected backend."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DeviceOpenError(CaptureError):
|
|
27
|
+
"""Raised when opening or configuring a USB device fails.
|
|
28
|
+
|
|
29
|
+
This covers backend open failures, configuration selection failures,
|
|
30
|
+
interface claim failures, and cleanup failures during close.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class InterfaceClaimError(DeviceOpenError):
|
|
35
|
+
"""Raised when claiming a required USB interface fails.
|
|
36
|
+
|
|
37
|
+
Reserved for callers that need to distinguish interface ownership failures
|
|
38
|
+
from other device-open errors.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class Ftd3CommandContext:
|
|
44
|
+
"""Debug context for one failed FTD3 command.
|
|
45
|
+
|
|
46
|
+
Attributes:
|
|
47
|
+
command_name: Logical command or transfer name.
|
|
48
|
+
pipe: Pipe or endpoint associated with the failure, if known.
|
|
49
|
+
payload_length: Command payload length in bytes.
|
|
50
|
+
requested_length: Requested transfer length in bytes, if applicable.
|
|
51
|
+
transferred: Number of bytes reported by the backend, if available.
|
|
52
|
+
libusb_status: Optional libusb status code for async paths.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
command_name: str
|
|
56
|
+
pipe: int | None
|
|
57
|
+
payload_length: int
|
|
58
|
+
requested_length: int | None
|
|
59
|
+
transferred: int | None
|
|
60
|
+
libusb_status: int | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Ftd3CommandError(CaptureError):
|
|
64
|
+
"""Raised when an FTD3 command or transfer fails.
|
|
65
|
+
|
|
66
|
+
Attributes:
|
|
67
|
+
context: Structured command context for logs and artifact metadata.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
context: Ftd3CommandContext
|
|
71
|
+
|
|
72
|
+
def __init__(self, context: Ftd3CommandContext) -> None:
|
|
73
|
+
"""Create an FTD3 command failure with structured context.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
context: Structured command details captured at the failure point.
|
|
77
|
+
"""
|
|
78
|
+
super().__init__(context.command_name)
|
|
79
|
+
self.context = context
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class UnsupportedOperation(CaptureError): # noqa: N818
|
|
83
|
+
"""Raised when an operation is outside the current MVP scope.
|
|
84
|
+
|
|
85
|
+
Examples include requesting 3D capture while the implementation is limited
|
|
86
|
+
to 2D new 3DS XL frame acquisition.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class TransferOverflow(CaptureError): # noqa: N818
|
|
91
|
+
"""Raised when a transfer length is outside the accepted capture bounds.
|
|
92
|
+
|
|
93
|
+
The transport reported more bytes than the selected raw capture structure
|
|
94
|
+
allows.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class DecodeError(CaptureError):
|
|
99
|
+
"""Raised when raw frame data cannot be decoded.
|
|
100
|
+
|
|
101
|
+
This covers short raw captures, unexpected frame shapes or dtypes, invalid
|
|
102
|
+
color-space requests, and unsupported screen selection.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class OptionalDependencyError(CaptureError):
|
|
107
|
+
"""Raised when an optional adapter dependency is missing.
|
|
108
|
+
|
|
109
|
+
Optional extras currently include image conversion dependencies and the D3XX
|
|
110
|
+
backend dependency.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(self, dependency: str, extra: str) -> None:
|
|
114
|
+
"""Create an optional dependency error.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
dependency: Human-readable dependency name.
|
|
118
|
+
extra: Project extra that installs the dependency.
|
|
119
|
+
"""
|
|
120
|
+
super().__init__(f"Install {dependency} or use the {extra} extra.")
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Hardware gate helpers for N3DSXL-only commands."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from py3dscapture.protocol.sizes import (
|
|
9
|
+
ACCEPTED_N3DSXL_PRODUCT_IDS,
|
|
10
|
+
ACCEPTED_N3DSXL_PRODUCT_STRINGS,
|
|
11
|
+
N3DSXL_VENDOR_ID,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def requires_n3dsxl_tests_enabled(env: Mapping[str, str] | None = None) -> bool:
|
|
16
|
+
"""Return whether tests marked ``requires_n3dsxl`` should run.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
env: Optional environment mapping for tests. ``os.environ`` is used when
|
|
20
|
+
omitted.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
True only when ``PONKAN_RUN_N3DSXL`` is exactly ``"1"``.
|
|
24
|
+
"""
|
|
25
|
+
return _env_flag("PONKAN_RUN_N3DSXL", env)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def performance_tests_enabled(env: Mapping[str, str] | None = None) -> bool:
|
|
29
|
+
"""Return whether tests marked ``performance`` should run.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
env: Optional environment mapping for tests. ``os.environ`` is used when
|
|
33
|
+
omitted.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
True only when ``PONKAN_RUN_PERFORMANCE`` is exactly ``"1"``.
|
|
37
|
+
"""
|
|
38
|
+
return _env_flag("PONKAN_RUN_PERFORMANCE", env)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def manual_visual_tests_enabled(env: Mapping[str, str] | None = None) -> bool:
|
|
42
|
+
"""Return whether tests marked ``manual_visual`` should run.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
env: Optional environment mapping for tests. ``os.environ`` is used when
|
|
46
|
+
omitted.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
True only when ``PONKAN_RUN_MANUAL_VISUAL`` is exactly ``"1"``.
|
|
50
|
+
"""
|
|
51
|
+
return _env_flag("PONKAN_RUN_MANUAL_VISUAL", env)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def hardware_approved(env: Mapping[str, str] | None = None) -> bool:
|
|
55
|
+
"""Return whether a human approved the current hardware command.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
env: Optional environment mapping for tests. ``os.environ`` is used when
|
|
59
|
+
omitted.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
True only when ``PONKAN_HARDWARE_APPROVED`` is exactly ``"1"``.
|
|
63
|
+
"""
|
|
64
|
+
return _env_flag("PONKAN_HARDWARE_APPROVED", env)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _env_flag(name: str, env: Mapping[str, str] | None) -> bool:
|
|
68
|
+
values = os.environ if env is None else env
|
|
69
|
+
return values.get(name) == "1"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True, slots=True)
|
|
73
|
+
class HardwareCommandPlan:
|
|
74
|
+
"""Human-reviewable plan for one hardware command boundary.
|
|
75
|
+
|
|
76
|
+
Attributes:
|
|
77
|
+
product_string: USB product string when readable.
|
|
78
|
+
product_string_status: Whether the product string was accepted or could
|
|
79
|
+
not be read.
|
|
80
|
+
vid: USB vendor ID recorded for the device.
|
|
81
|
+
pid: USB product ID recorded for the device.
|
|
82
|
+
command_scope: Human-readable scope of the command to be run.
|
|
83
|
+
safety_reason: Why the command is safe for the recorded device.
|
|
84
|
+
artifact: Artifact path or description that will capture evidence.
|
|
85
|
+
cleanup: Cleanup action expected after the command.
|
|
86
|
+
command: Exact command requiring approval.
|
|
87
|
+
backend_kind: Transport backend used by the command.
|
|
88
|
+
driver_service: Optional Windows driver service observed for the device.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
product_string: str | None
|
|
92
|
+
product_string_status: Literal["accepted", "unreadable"]
|
|
93
|
+
vid: int
|
|
94
|
+
pid: int
|
|
95
|
+
command_scope: str
|
|
96
|
+
safety_reason: str
|
|
97
|
+
artifact: str
|
|
98
|
+
cleanup: str
|
|
99
|
+
command: str
|
|
100
|
+
backend_kind: Literal["libusb", "d3xx"] = "libusb"
|
|
101
|
+
driver_service: str | None = None
|
|
102
|
+
|
|
103
|
+
def is_allowed_n3dsxl_device(self) -> bool:
|
|
104
|
+
"""Return whether the recorded identity is allowed for N3DSXL commands.
|
|
105
|
+
|
|
106
|
+
Product string ``None`` is allowed only when the status records it as
|
|
107
|
+
unreadable; unsupported readable product strings are rejected.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
True when VID, PID, and product-string status satisfy the N3DSXL
|
|
111
|
+
safety boundary.
|
|
112
|
+
"""
|
|
113
|
+
product_string_allowed = (
|
|
114
|
+
self.product_string in ACCEPTED_N3DSXL_PRODUCT_STRINGS
|
|
115
|
+
if self.product_string is not None
|
|
116
|
+
else self.product_string_status == "unreadable"
|
|
117
|
+
)
|
|
118
|
+
return (
|
|
119
|
+
self.vid == N3DSXL_VENDOR_ID
|
|
120
|
+
and self.pid in ACCEPTED_N3DSXL_PRODUCT_IDS
|
|
121
|
+
and product_string_allowed
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def to_dict(self) -> dict[str, str | None]:
|
|
125
|
+
"""Return a JSON-serializable command plan.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
A dictionary with VID and PID formatted as hexadecimal strings for
|
|
129
|
+
artifact and review output.
|
|
130
|
+
"""
|
|
131
|
+
return {
|
|
132
|
+
"product_string": self.product_string,
|
|
133
|
+
"product_string_status": self.product_string_status,
|
|
134
|
+
"vid": f"0x{self.vid:04x}",
|
|
135
|
+
"pid": f"0x{self.pid:04x}",
|
|
136
|
+
"command_scope": self.command_scope,
|
|
137
|
+
"safety_reason": self.safety_reason,
|
|
138
|
+
"artifact": self.artifact,
|
|
139
|
+
"cleanup": self.cleanup,
|
|
140
|
+
"command": self.command,
|
|
141
|
+
"backend_kind": self.backend_kind,
|
|
142
|
+
"driver_service": self.driver_service,
|
|
143
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Image data models and adapters."""
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Capture frame data model."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
from typing import TYPE_CHECKING, Literal, Protocol, cast
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from numpy.typing import NDArray
|
|
9
|
+
|
|
10
|
+
from py3dscapture.errors import DecodeError, OptionalDependencyError
|
|
11
|
+
from py3dscapture.protocol.sizes import BOTTOM_WIDTH_3DS, HEIGHT_3DS, TOP_WIDTH_3DS
|
|
12
|
+
|
|
13
|
+
ColorSpace = Literal["RGB", "BGR"]
|
|
14
|
+
ScreenName = Literal["top", "bottom", "top_right"]
|
|
15
|
+
RGB8Array = NDArray[np.uint8]
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PillowImageLike(Protocol):
|
|
22
|
+
"""Small Pillow Image surface used by callers and tools.
|
|
23
|
+
|
|
24
|
+
The protocol keeps Pillow optional at runtime while documenting the surface
|
|
25
|
+
returned by ``CaptureFrame.to_pillow``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
size: tuple[int, int]
|
|
29
|
+
|
|
30
|
+
def save(self, fp: object) -> object:
|
|
31
|
+
"""Save the image to a Pillow-supported file object or path.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
fp: Destination accepted by ``PIL.Image.Image.save``.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
The value returned by Pillow's ``save`` implementation.
|
|
38
|
+
"""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True)
|
|
43
|
+
class CaptureFrame:
|
|
44
|
+
"""Decoded RGB8 top and bottom screen frame.
|
|
45
|
+
|
|
46
|
+
Attributes:
|
|
47
|
+
top: Top screen image as ``uint8`` ndarray with shape ``(240, 400, 3)``.
|
|
48
|
+
bottom: Bottom screen image as ``uint8`` ndarray with shape
|
|
49
|
+
``(240, 320, 3)``.
|
|
50
|
+
top_right: Right-eye top screen for 3D captures, or ``None`` for 2D
|
|
51
|
+
captures.
|
|
52
|
+
timestamp_ns: Optional monotonic timestamp associated with the source
|
|
53
|
+
transfer.
|
|
54
|
+
source_model: Capture target model that produced this frame.
|
|
55
|
+
mode_3d: Whether the frame came from 3D capture mode.
|
|
56
|
+
sequence: Optional streaming sequence number.
|
|
57
|
+
colorspace: Internal color channel order. Only ``"RGB"`` is accepted
|
|
58
|
+
for stored frames.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
top: RGB8Array
|
|
62
|
+
bottom: RGB8Array
|
|
63
|
+
top_right: RGB8Array | None
|
|
64
|
+
timestamp_ns: int | None
|
|
65
|
+
source_model: Literal["new_3ds_xl", "old_3ds"]
|
|
66
|
+
mode_3d: bool
|
|
67
|
+
sequence: int | None = None
|
|
68
|
+
colorspace: ColorSpace = "RGB"
|
|
69
|
+
|
|
70
|
+
def __post_init__(self) -> None:
|
|
71
|
+
"""Validate frame shapes, dtype, and internal color space.
|
|
72
|
+
|
|
73
|
+
Raises:
|
|
74
|
+
DecodeError: Any screen has an unexpected shape, non-``uint8`` dtype,
|
|
75
|
+
or the stored color space is not RGB.
|
|
76
|
+
"""
|
|
77
|
+
_validate_rgb8(self.top, (HEIGHT_3DS, TOP_WIDTH_3DS, 3))
|
|
78
|
+
_validate_rgb8(self.bottom, (HEIGHT_3DS, BOTTOM_WIDTH_3DS, 3))
|
|
79
|
+
if self.top_right is not None:
|
|
80
|
+
_validate_rgb8(self.top_right, (HEIGHT_3DS, TOP_WIDTH_3DS, 3))
|
|
81
|
+
if self.colorspace != "RGB":
|
|
82
|
+
raise DecodeError
|
|
83
|
+
|
|
84
|
+
def to_ndarray(self, screen: ScreenName = "top", colorspace: ColorSpace = "RGB") -> RGB8Array:
|
|
85
|
+
"""Return one screen as a copied RGB or BGR ndarray.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
screen: Screen to return. ``"top_right"`` is valid only when the
|
|
89
|
+
frame contains a 3D right-eye image.
|
|
90
|
+
colorspace: Channel order for the returned copy.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
A copy of the requested screen with shape ``(height, width, 3)`` and
|
|
94
|
+
dtype ``uint8``.
|
|
95
|
+
|
|
96
|
+
Raises:
|
|
97
|
+
DecodeError: The screen is unavailable, or the requested color space
|
|
98
|
+
cannot be produced.
|
|
99
|
+
"""
|
|
100
|
+
image = self._screen(screen)
|
|
101
|
+
if colorspace == self.colorspace:
|
|
102
|
+
return image.copy()
|
|
103
|
+
if colorspace == "BGR" and self.colorspace == "RGB":
|
|
104
|
+
return image[..., ::-1].copy()
|
|
105
|
+
raise DecodeError
|
|
106
|
+
|
|
107
|
+
def to_pillow(self, screen: ScreenName = "top") -> PillowImageLike:
|
|
108
|
+
"""Return one screen as a Pillow RGB image.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
screen: Screen to convert. ``"top_right"`` is valid only when the
|
|
112
|
+
frame contains a 3D right-eye image.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
A Pillow ``Image``-compatible object in RGB mode.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
OptionalDependencyError: Pillow is not installed.
|
|
119
|
+
DecodeError: The requested screen is unavailable.
|
|
120
|
+
"""
|
|
121
|
+
try:
|
|
122
|
+
image_module = import_module("PIL.Image")
|
|
123
|
+
except ImportError as exc:
|
|
124
|
+
raise OptionalDependencyError("Pillow", "image") from exc
|
|
125
|
+
fromarray = cast("Callable[..., PillowImageLike]", image_module.fromarray)
|
|
126
|
+
return fromarray(self.to_ndarray(screen=screen, colorspace="RGB"), mode="RGB")
|
|
127
|
+
|
|
128
|
+
def to_mosaic(self, gap: int = 0) -> RGB8Array:
|
|
129
|
+
"""Return top and centered bottom screens in one RGB image.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
gap: Vertical black-space pixels inserted between top and bottom.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
A new RGB ndarray with the top screen first and the bottom screen
|
|
136
|
+
centered under it.
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
ValueError: ``gap`` is negative.
|
|
140
|
+
"""
|
|
141
|
+
if gap < 0:
|
|
142
|
+
raise ValueError
|
|
143
|
+
width = TOP_WIDTH_3DS
|
|
144
|
+
height = HEIGHT_3DS * 2 + gap
|
|
145
|
+
mosaic = np.zeros((height, width, 3), dtype=np.uint8)
|
|
146
|
+
mosaic[:HEIGHT_3DS, :TOP_WIDTH_3DS] = self.top
|
|
147
|
+
bottom_x = (TOP_WIDTH_3DS - BOTTOM_WIDTH_3DS) // 2
|
|
148
|
+
bottom_y = HEIGHT_3DS + gap
|
|
149
|
+
mosaic[bottom_y : bottom_y + HEIGHT_3DS, bottom_x : bottom_x + BOTTOM_WIDTH_3DS] = (
|
|
150
|
+
self.bottom
|
|
151
|
+
)
|
|
152
|
+
return mosaic
|
|
153
|
+
|
|
154
|
+
def _screen(self, screen: ScreenName) -> RGB8Array:
|
|
155
|
+
if screen == "top":
|
|
156
|
+
return self.top
|
|
157
|
+
if screen == "bottom":
|
|
158
|
+
return self.bottom
|
|
159
|
+
if screen == "top_right" and self.top_right is not None:
|
|
160
|
+
return self.top_right
|
|
161
|
+
raise DecodeError
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _validate_rgb8(array: RGB8Array, shape: tuple[int, int, int]) -> None:
|
|
165
|
+
if array.shape != shape or array.dtype != np.uint8:
|
|
166
|
+
raise DecodeError
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Protocol constants and size calculations."""
|