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.
Files changed (39) hide show
  1. ponkan_python-0.1.0.dist-info/METADATA +157 -0
  2. ponkan_python-0.1.0.dist-info/RECORD +39 -0
  3. ponkan_python-0.1.0.dist-info/WHEEL +4 -0
  4. ponkan_python-0.1.0.dist-info/entry_points.txt +5 -0
  5. ponkan_python-0.1.0.dist-info/licenses/LICENSE +22 -0
  6. ponkan_python-0.1.0.dist-info/licenses/NOTICE.md +14 -0
  7. py3dscapture/__init__.py +36 -0
  8. py3dscapture/artifacts.py +66 -0
  9. py3dscapture/capture.py +599 -0
  10. py3dscapture/devices/__init__.py +1 -0
  11. py3dscapture/devices/n3dsxl_ftd3.py +238 -0
  12. py3dscapture/errors.py +120 -0
  13. py3dscapture/hardware_gate.py +143 -0
  14. py3dscapture/image/__init__.py +1 -0
  15. py3dscapture/image/frame.py +166 -0
  16. py3dscapture/protocol/__init__.py +1 -0
  17. py3dscapture/protocol/layout_3ds.py +60 -0
  18. py3dscapture/protocol/n3dsxl.py +249 -0
  19. py3dscapture/protocol/sizes.py +128 -0
  20. py3dscapture/py.typed +1 -0
  21. py3dscapture/streaming/__init__.py +1 -0
  22. py3dscapture/streaming/buffers.py +156 -0
  23. py3dscapture/streaming/engine.py +285 -0
  24. py3dscapture/streaming/policies.py +157 -0
  25. py3dscapture/streaming/stats.py +254 -0
  26. py3dscapture/tools/__init__.py +1 -0
  27. py3dscapture/tools/capture_raw.py +44 -0
  28. py3dscapture/tools/list_devices.py +68 -0
  29. py3dscapture/tools/raw_to_png.py +251 -0
  30. py3dscapture/tools/stream_n3dsxl.py +152 -0
  31. py3dscapture/transport/__init__.py +1 -0
  32. py3dscapture/transport/d3xx_backend.py +850 -0
  33. py3dscapture/transport/d3xx_native.py +268 -0
  34. py3dscapture/transport/d3xx_native_streaming.py +306 -0
  35. py3dscapture/transport/d3xx_streaming.py +202 -0
  36. py3dscapture/transport/ftd3_backend.py +275 -0
  37. py3dscapture/transport/ftd3_pipe.py +387 -0
  38. py3dscapture/transport/libusb_async.py +134 -0
  39. py3dscapture/transport/libusb_backend.py +357 -0
@@ -0,0 +1,44 @@
1
+ """Capture one raw N3DSXL frame to a fixture pair."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ from py3dscapture.capture import save_raw_capture
7
+ from py3dscapture.devices.n3dsxl_ftd3 import N3DSXLDevice, list_n3dsxl_devices
8
+ from py3dscapture.protocol.n3dsxl import N3DSXLProtocol
9
+ from py3dscapture.transport.ftd3_pipe import Ftd3Pipe
10
+ from py3dscapture.transport.libusb_backend import Usb1Backend
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> int:
14
+ """Run the raw-capture CLI.
15
+
16
+ Args:
17
+ argv: Optional command-line arguments. ``None`` uses ``sys.argv`` through
18
+ ``argparse``.
19
+
20
+ Returns:
21
+ Process status code. Zero means the raw payload and metadata sidecar were
22
+ written.
23
+ """
24
+ parser = argparse.ArgumentParser()
25
+ parser.add_argument("--model", choices=["new_3ds_xl"], default="new_3ds_xl")
26
+ parser.add_argument("--out", type=Path, required=True)
27
+ parser.add_argument("--force", action="store_true")
28
+ args = parser.parse_args(argv)
29
+
30
+ backend = Usb1Backend()
31
+ listing = list_n3dsxl_devices(backend)
32
+ if not listing.candidates:
33
+ parser.error("no N3DSXL candidate found")
34
+
35
+ with N3DSXLDevice.open(listing.candidates[0], backend=backend) as device:
36
+ protocol = N3DSXLProtocol(device, Ftd3Pipe(device))
37
+ protocol.connect(mode_3d=False)
38
+ capture = protocol.read_raw_frame(mode_3d=False)
39
+ save_raw_capture(capture, args.out, force=args.force)
40
+ return 0
41
+
42
+
43
+ if __name__ == "__main__":
44
+ raise SystemExit(main())
@@ -0,0 +1,68 @@
1
+ """List N3DSXL USB device candidates."""
2
+
3
+ from py3dscapture.devices.n3dsxl_ftd3 import DeviceListing, list_n3dsxl_devices
4
+ from py3dscapture.transport.libusb_backend import LibusbBackend, Usb1Backend
5
+
6
+
7
+ def format_device_listing(listing: DeviceListing) -> str:
8
+ """Format candidates and rejected FTDI devices for humans.
9
+
10
+ Args:
11
+ listing: Classified device listing from ``list_n3dsxl_devices``.
12
+
13
+ Returns:
14
+ Multi-line text containing accepted candidates and rejected FTDI-family
15
+ devices, or a single empty-state line.
16
+ """
17
+ if not listing.candidates and not listing.rejected:
18
+ return "No N3DSXL candidates or rejected FTDI devices found."
19
+
20
+ lines: list[str] = []
21
+ for candidate in listing.candidates:
22
+ info = candidate.info
23
+ lines.append(
24
+ "candidate "
25
+ f"{_format_location(info.bus_number, info.address)} "
26
+ f"{_format_vid_pid(info.vendor_id, info.product_id)} "
27
+ f"product={candidate.product_string or '-'} "
28
+ f"product_status={candidate.product_string_status} "
29
+ f"serial={info.serial_number or '-'}"
30
+ )
31
+ for rejected in listing.rejected:
32
+ info = rejected.info
33
+ lines.append(
34
+ "rejected "
35
+ f"{_format_location(info.bus_number, info.address)} "
36
+ f"{_format_vid_pid(info.vendor_id, info.product_id)} "
37
+ f"product={info.product_string or '-'} reason={rejected.reason}"
38
+ )
39
+ return "\n".join(lines)
40
+
41
+
42
+ def main(backend: LibusbBackend | None = None) -> int:
43
+ """Run the device-listing CLI.
44
+
45
+ Args:
46
+ backend: Optional backend injection for tests. ``Usb1Backend`` is used
47
+ when omitted.
48
+
49
+ Returns:
50
+ Process status code. Zero means the listing was printed.
51
+ """
52
+ listing = list_n3dsxl_devices(backend or Usb1Backend())
53
+ print(format_device_listing(listing))
54
+ return 0
55
+
56
+
57
+ def _format_location(bus_number: int | None, address: int | None) -> str:
58
+ bus = "-" if bus_number is None else str(bus_number)
59
+ address_text = "-" if address is None else str(address)
60
+ return f"bus={bus} address={address_text}"
61
+
62
+
63
+ def _format_vid_pid(vendor_id: int, product_id: int) -> str:
64
+ return f"0x{vendor_id:04x}:0x{product_id:04x}"
65
+
66
+
67
+ if __name__ == "__main__":
68
+ raise SystemExit(main())
@@ -0,0 +1,251 @@
1
+ """Convert raw N3DSXL fixtures to PNG images."""
2
+
3
+ import argparse
4
+ import json
5
+ from collections.abc import Iterator
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ import numpy as np
11
+
12
+ from py3dscapture.image.frame import CaptureFrame
13
+ from py3dscapture.protocol.layout_3ds import APPROVED_N3DSXL_2D_DECODER_ID, decode_rgb8_2d
14
+ from py3dscapture.protocol.sizes import BOTTOM_WIDTH_3DS, HEIGHT_3DS, TOP_WIDTH_3DS
15
+
16
+ ProbeCandidateId = Literal[
17
+ "legacy_top_first_transpose",
18
+ "legacy_top_first_rotate_cw",
19
+ "legacy_top_first_rotate_cw_flip_x",
20
+ "ftd3_cc3dsfs_2d",
21
+ ]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class _ProbeCandidate:
26
+ candidate_id: ProbeCandidateId
27
+ hypothesis: str
28
+ frame: CaptureFrame
29
+
30
+
31
+ def main(argv: list[str] | None = None) -> int:
32
+ """Run the raw-to-PNG conversion CLI.
33
+
34
+ Args:
35
+ argv: Optional command-line arguments. ``None`` uses ``sys.argv`` through
36
+ ``argparse``.
37
+
38
+ Returns:
39
+ Process status code. Zero means image outputs were written.
40
+
41
+ Raises:
42
+ FileExistsError: An output exists and ``--force`` was not provided.
43
+ DecodeError: The selected decoder cannot decode the raw video region.
44
+ OptionalDependencyError: Pillow is unavailable for PNG writing.
45
+ """
46
+ parser = argparse.ArgumentParser()
47
+ parser.add_argument("raw", type=Path)
48
+ parser.add_argument("--metadata", type=Path)
49
+ parser.add_argument("--out", type=Path, required=True)
50
+ parser.add_argument("--manifest", type=Path)
51
+ parser.add_argument("--force", action="store_true")
52
+ parser.add_argument(
53
+ "--manual-visual-status",
54
+ choices=("pending", "approved"),
55
+ default="pending",
56
+ )
57
+ parser.add_argument("--approval-evidence", type=Path)
58
+ parser.add_argument("--probe-candidates", action="store_true")
59
+ args = parser.parse_args(argv)
60
+
61
+ raw_video = _read_raw_video(args.raw, args.metadata)
62
+ args.out.mkdir(parents=True, exist_ok=True)
63
+ manifest: dict[str, object]
64
+ if args.probe_candidates:
65
+ manifest = _write_probe_outputs(
66
+ raw_video=raw_video,
67
+ raw_path=args.raw,
68
+ metadata_path=args.metadata,
69
+ out_dir=args.out,
70
+ manifest_path=args.manifest,
71
+ force=args.force,
72
+ )
73
+ else:
74
+ manifest = _write_approved_outputs(
75
+ raw_video=raw_video,
76
+ raw_path=args.raw,
77
+ metadata_path=args.metadata,
78
+ out_dir=args.out,
79
+ force=args.force,
80
+ manual_visual_status=args.manual_visual_status,
81
+ approval_evidence=args.approval_evidence,
82
+ )
83
+ if args.manifest is not None:
84
+ args.manifest.parent.mkdir(parents=True, exist_ok=True)
85
+ args.manifest.write_text(
86
+ json.dumps(manifest, indent=2, sort_keys=True),
87
+ encoding="utf-8",
88
+ )
89
+ return 0
90
+
91
+
92
+ def _write_approved_outputs(
93
+ *,
94
+ raw_video: bytes,
95
+ raw_path: Path,
96
+ metadata_path: Path | None,
97
+ out_dir: Path,
98
+ force: bool,
99
+ manual_visual_status: str,
100
+ approval_evidence: Path | None,
101
+ ) -> dict[str, object]:
102
+ frame = decode_rgb8_2d(raw_video)
103
+ outputs = _write_frame_outputs(
104
+ frame=frame,
105
+ out_dir=out_dir,
106
+ filename_prefix="",
107
+ force=force,
108
+ )
109
+ return {
110
+ "raw_path": str(raw_path),
111
+ "metadata_path": str(metadata_path) if metadata_path is not None else None,
112
+ "out_dir": str(out_dir),
113
+ "manual_visual_status": manual_visual_status,
114
+ "decoder_id": APPROVED_N3DSXL_2D_DECODER_ID,
115
+ "approval_evidence": str(approval_evidence) if approval_evidence is not None else None,
116
+ "outputs": outputs,
117
+ }
118
+
119
+
120
+ def _write_probe_outputs(
121
+ *,
122
+ raw_video: bytes,
123
+ raw_path: Path,
124
+ metadata_path: Path | None,
125
+ out_dir: Path,
126
+ manifest_path: Path | None,
127
+ force: bool,
128
+ ) -> dict[str, object]:
129
+ probes: list[dict[str, object]] = []
130
+ for candidate in _iter_probe_candidates(raw_video):
131
+ outputs = _write_frame_outputs(
132
+ frame=candidate.frame,
133
+ out_dir=out_dir,
134
+ filename_prefix=f"probe_{candidate.candidate_id}_",
135
+ force=force,
136
+ )
137
+ probes.append(
138
+ {
139
+ "candidate_id": candidate.candidate_id,
140
+ "hypothesis": candidate.hypothesis,
141
+ "manual_visual_status": "pending",
142
+ "outputs": outputs,
143
+ }
144
+ )
145
+ return {
146
+ "raw_path": str(raw_path),
147
+ "metadata_path": str(metadata_path) if metadata_path is not None else None,
148
+ "out_dir": str(out_dir),
149
+ "manifest_path": str(manifest_path) if manifest_path is not None else None,
150
+ "probe_mode": True,
151
+ "probes": probes,
152
+ }
153
+
154
+
155
+ def _write_frame_outputs(
156
+ *,
157
+ frame: CaptureFrame,
158
+ out_dir: Path,
159
+ filename_prefix: str,
160
+ force: bool,
161
+ ) -> list[dict[str, object]]:
162
+ outputs: list[dict[str, object]] = []
163
+ for screen in ("top", "bottom"):
164
+ out_path = out_dir / f"{filename_prefix}{screen}.png"
165
+ if out_path.exists() and not force:
166
+ raise FileExistsError
167
+ image = frame.to_pillow(screen=screen)
168
+ image.save(out_path)
169
+ outputs.append(
170
+ {
171
+ "screen": screen,
172
+ "path": str(out_path),
173
+ "width": image.size[0],
174
+ "height": image.size[1],
175
+ }
176
+ )
177
+ return outputs
178
+
179
+
180
+ def _iter_probe_candidates(raw_video: bytes) -> Iterator[_ProbeCandidate]:
181
+ yield _ProbeCandidate(
182
+ candidate_id="legacy_top_first_transpose",
183
+ hypothesis="obsolete top-first split with transpose display transform",
184
+ frame=_decode_legacy_top_first(raw_video, transform="transpose"),
185
+ )
186
+ yield _ProbeCandidate(
187
+ candidate_id="legacy_top_first_rotate_cw",
188
+ hypothesis="obsolete top-first split with clockwise display rotation",
189
+ frame=_decode_legacy_top_first(raw_video, transform="rotate_cw"),
190
+ )
191
+ yield _ProbeCandidate(
192
+ candidate_id="legacy_top_first_rotate_cw_flip_x",
193
+ hypothesis="obsolete top-first split with clockwise rotation and horizontal flip",
194
+ frame=_decode_legacy_top_first(raw_video, transform="rotate_cw_flip_x"),
195
+ )
196
+ yield _ProbeCandidate(
197
+ candidate_id=APPROVED_N3DSXL_2D_DECODER_ID,
198
+ hypothesis="approved cc3dsfs FTD3 2D deinterleave layout",
199
+ frame=decode_rgb8_2d(raw_video),
200
+ )
201
+
202
+
203
+ def _decode_legacy_top_first(
204
+ raw_video: bytes,
205
+ *,
206
+ transform: Literal["transpose", "rotate_cw", "rotate_cw_flip_x"],
207
+ ) -> CaptureFrame:
208
+ stacked = np.frombuffer(raw_video, dtype=np.uint8).reshape(
209
+ (TOP_WIDTH_3DS + BOTTOM_WIDTH_3DS, HEIGHT_3DS, 3)
210
+ )
211
+ top_source = stacked[:TOP_WIDTH_3DS]
212
+ bottom_source = stacked[TOP_WIDTH_3DS:]
213
+ return CaptureFrame(
214
+ top=_transform_legacy_source(top_source, transform=transform),
215
+ bottom=_transform_legacy_source(bottom_source, transform=transform),
216
+ top_right=None,
217
+ timestamp_ns=None,
218
+ source_model="new_3ds_xl",
219
+ mode_3d=False,
220
+ colorspace="RGB",
221
+ )
222
+
223
+
224
+ def _transform_legacy_source(
225
+ source: np.ndarray,
226
+ *,
227
+ transform: Literal["transpose", "rotate_cw", "rotate_cw_flip_x"],
228
+ ) -> np.ndarray:
229
+ if transform == "transpose":
230
+ return source.transpose(1, 0, 2).copy()
231
+ if transform == "rotate_cw":
232
+ return np.rot90(source, k=-1).copy()
233
+ return np.flip(np.rot90(source, k=-1), axis=1).copy()
234
+
235
+
236
+ def _read_raw_video(raw_path: Path, metadata_path: Path | None) -> bytes:
237
+ raw_payload = raw_path.read_bytes()
238
+ if metadata_path is None:
239
+ return raw_payload
240
+
241
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
242
+ video_size_value = metadata.get("video_size")
243
+ if not isinstance(video_size_value, int):
244
+ raise TypeError
245
+ if len(raw_payload) < video_size_value:
246
+ raise ValueError
247
+ return raw_payload[:video_size_value]
248
+
249
+
250
+ if __name__ == "__main__":
251
+ raise SystemExit(main())
@@ -0,0 +1,152 @@
1
+ """Stream N3DSXL frames and print stats."""
2
+
3
+ import argparse
4
+ import json
5
+ import time
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Literal, cast
8
+
9
+ from py3dscapture.artifacts import write_json_artifact
10
+ from py3dscapture.streaming.engine import StreamingEngine
11
+ from py3dscapture.streaming.stats import PerformanceStats, StreamingBackendKind
12
+ from py3dscapture.transport.libusb_async import LibusbAsyncBackend
13
+
14
+ if TYPE_CHECKING:
15
+ from py3dscapture.streaming.policies import DropPolicy
16
+
17
+
18
+ def run_streaming_smoke(
19
+ engine: StreamingEngine,
20
+ *,
21
+ duration: float,
22
+ noop_consumer: bool,
23
+ product_string: str | None,
24
+ product_string_status: Literal["accepted", "unreadable"],
25
+ mode_3d: bool,
26
+ raw_slots: int,
27
+ output_queue_size: int,
28
+ drop_policy: str,
29
+ backend_kind: StreamingBackendKind = "libusb",
30
+ driver_service: str | None = None,
31
+ poll_interval: float = 0.004,
32
+ ) -> PerformanceStats:
33
+ """Run a bounded streaming smoke loop and return performance stats.
34
+
35
+ Args:
36
+ engine: Streaming engine to start, poll, and stop.
37
+ duration: Requested run duration in seconds.
38
+ noop_consumer: Drain decoded frames without inspecting them when true.
39
+ product_string: USB product string recorded for the run.
40
+ product_string_status: Whether the product string was accepted or
41
+ unreadable.
42
+ mode_3d: Capture mode recorded in the report.
43
+ raw_slots: Raw slot count used by the engine.
44
+ output_queue_size: Decoded frame queue capacity used by the engine.
45
+ drop_policy: Decoded-frame overflow policy.
46
+ backend_kind: Transport backend recorded in the report.
47
+ driver_service: Optional Windows driver service recorded in the report.
48
+ poll_interval: Sleep interval between completion polls.
49
+
50
+ Returns:
51
+ JSON-serializable performance report.
52
+ """
53
+ started = time.monotonic()
54
+ engine_started = False
55
+ shutdown_seconds = 0.0
56
+ try:
57
+ engine.start()
58
+ engine_started = True
59
+ while time.monotonic() - started < duration:
60
+ engine.process_completed(limit=8)
61
+ if noop_consumer:
62
+ for _frame in engine.frames():
63
+ pass
64
+ time.sleep(poll_interval)
65
+ finally:
66
+ shutdown_started = time.monotonic()
67
+ if engine_started:
68
+ engine.stop()
69
+ shutdown_seconds = time.monotonic() - shutdown_started
70
+
71
+ return PerformanceStats.from_stream_stats(
72
+ engine.stats(),
73
+ product_string=product_string,
74
+ product_string_status=product_string_status,
75
+ backend_kind=backend_kind,
76
+ driver_service=driver_service,
77
+ mode_3d=mode_3d,
78
+ duration_seconds=duration,
79
+ raw_slots=raw_slots,
80
+ output_queue_size=output_queue_size,
81
+ drop_policy=drop_policy,
82
+ shutdown_seconds=shutdown_seconds,
83
+ timing=engine.timing_summary(),
84
+ )
85
+
86
+
87
+ def main(argv: list[str] | None = None) -> int:
88
+ """Run the streaming smoke CLI.
89
+
90
+ Args:
91
+ argv: Optional command-line arguments. ``None`` uses ``sys.argv`` through
92
+ ``argparse``.
93
+
94
+ Returns:
95
+ Process status code. Zero means the smoke loop completed and requested
96
+ stats output was written.
97
+ """
98
+ parser = argparse.ArgumentParser()
99
+ parser.add_argument("--duration", type=float, default=10.0)
100
+ parser.add_argument("--stats", action="store_true")
101
+ parser.add_argument("--stats-json", type=Path)
102
+ parser.add_argument("--force", action="store_true")
103
+ parser.add_argument("--noop-consumer", action="store_true")
104
+ parser.add_argument("--product-string")
105
+ parser.add_argument(
106
+ "--product-string-status",
107
+ choices=("accepted", "unreadable"),
108
+ )
109
+ parser.add_argument("--raw-slots", type=int, default=2)
110
+ parser.add_argument("--output-queue-size", type=int, default=2)
111
+ parser.add_argument("--poll-interval", type=float, default=0.004)
112
+ parser.add_argument("--collect-timing", action="store_true")
113
+ parser.add_argument(
114
+ "--drop-policy",
115
+ choices=("drop_oldest", "drop_newest", "block"),
116
+ default="drop_oldest",
117
+ )
118
+ args = parser.parse_args(argv)
119
+
120
+ drop_policy = cast("DropPolicy", args.drop_policy)
121
+ product_string_status = args.product_string_status or (
122
+ "accepted" if args.product_string is not None else "unreadable"
123
+ )
124
+ engine = StreamingEngine(
125
+ LibusbAsyncBackend(),
126
+ raw_slots=args.raw_slots,
127
+ output_queue_size=args.output_queue_size,
128
+ drop_policy=drop_policy,
129
+ collect_timing=args.collect_timing,
130
+ )
131
+ stats = run_streaming_smoke(
132
+ engine,
133
+ duration=args.duration,
134
+ noop_consumer=args.noop_consumer,
135
+ product_string=args.product_string,
136
+ product_string_status=cast("Literal['accepted', 'unreadable']", product_string_status),
137
+ mode_3d=False,
138
+ raw_slots=args.raw_slots,
139
+ output_queue_size=args.output_queue_size,
140
+ drop_policy=args.drop_policy,
141
+ poll_interval=args.poll_interval,
142
+ )
143
+
144
+ if args.stats:
145
+ print(json.dumps(stats.to_dict(), sort_keys=True))
146
+ if args.stats_json is not None:
147
+ write_json_artifact(args.stats_json, stats.to_dict(), force=args.force)
148
+ return 0
149
+
150
+
151
+ if __name__ == "__main__":
152
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """USB transport helpers."""