facescope 0.2.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.
- facescope/__init__.py +259 -0
- facescope/_limits.py +29 -0
- facescope/_media.py +193 -0
- facescope/_normalization.py +129 -0
- facescope/analysis.py +777 -0
- facescope/cli.py +211 -0
- facescope/diagnostics.py +463 -0
- facescope/errors.py +49 -0
- facescope/evaluation.py +491 -0
- facescope/geometry.py +135 -0
- facescope/handoff.py +316 -0
- facescope/inspection.py +1166 -0
- facescope/motion.py +96 -0
- facescope/pipeline.py +394 -0
- facescope/plan.py +1315 -0
- facescope/planner.py +541 -0
- facescope/progress.py +55 -0
- facescope/rationals.py +69 -0
- facescope/renderer.py +334 -0
- facescope/solver.py +219 -0
- facescope/verification.py +559 -0
- facescope-0.2.0.dist-info/METADATA +148 -0
- facescope-0.2.0.dist-info/RECORD +27 -0
- facescope-0.2.0.dist-info/WHEEL +4 -0
- facescope-0.2.0.dist-info/entry_points.txt +2 -0
- facescope-0.2.0.dist-info/licenses/LICENSE +21 -0
- facescope-0.2.0.dist-info/licenses/LICENSES.md +26 -0
facescope/__init__.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""FaceScope public library exports."""
|
|
2
|
+
|
|
3
|
+
from facescope.analysis import (
|
|
4
|
+
YUNET_MODEL_FILENAME,
|
|
5
|
+
YUNET_MODEL_PROVENANCE,
|
|
6
|
+
YUNET_MODEL_SHA256,
|
|
7
|
+
AdaptiveCutDetector,
|
|
8
|
+
AnalysisTransform,
|
|
9
|
+
CutDetector,
|
|
10
|
+
FaceDetector,
|
|
11
|
+
RawDetection,
|
|
12
|
+
TrackingConfig,
|
|
13
|
+
YuNetFaceDetector,
|
|
14
|
+
analyze_video,
|
|
15
|
+
associate_shot_tracks,
|
|
16
|
+
invert_canvas_box,
|
|
17
|
+
iter_decoded_bgr_frames,
|
|
18
|
+
make_analysis_transform,
|
|
19
|
+
prepare_canvas,
|
|
20
|
+
verify_model_file,
|
|
21
|
+
)
|
|
22
|
+
from facescope.diagnostics import (
|
|
23
|
+
ReviewStill,
|
|
24
|
+
draw_debug_overlay,
|
|
25
|
+
render_comparison_frame,
|
|
26
|
+
render_comparison_video,
|
|
27
|
+
render_composition_frame,
|
|
28
|
+
render_four_path_frame,
|
|
29
|
+
render_motion_refinement_frame,
|
|
30
|
+
render_review_stills,
|
|
31
|
+
)
|
|
32
|
+
from facescope.errors import (
|
|
33
|
+
AnalysisError,
|
|
34
|
+
CancelledError,
|
|
35
|
+
FaceScopeError,
|
|
36
|
+
InspectionError,
|
|
37
|
+
InvalidCandidateError,
|
|
38
|
+
PlanValidationError,
|
|
39
|
+
PlanVersionError,
|
|
40
|
+
RemuxError,
|
|
41
|
+
RenderError,
|
|
42
|
+
SolverError,
|
|
43
|
+
SourceMismatchError,
|
|
44
|
+
VerificationError,
|
|
45
|
+
)
|
|
46
|
+
from facescope.evaluation import (
|
|
47
|
+
CompositionComparison,
|
|
48
|
+
CompositionMetrics,
|
|
49
|
+
CropComparison,
|
|
50
|
+
MotionRefinementComparison,
|
|
51
|
+
PathComparison,
|
|
52
|
+
PlanEvaluationReport,
|
|
53
|
+
ShotComparison,
|
|
54
|
+
ShotEvaluation,
|
|
55
|
+
compare_composition,
|
|
56
|
+
compare_crop_paths,
|
|
57
|
+
compare_motion_refinement,
|
|
58
|
+
evaluate_crop_plan,
|
|
59
|
+
)
|
|
60
|
+
from facescope.geometry import (
|
|
61
|
+
centered_crop_top,
|
|
62
|
+
display_to_stored_x,
|
|
63
|
+
legal_crop_tops,
|
|
64
|
+
select_crop_height,
|
|
65
|
+
select_output_raster,
|
|
66
|
+
stored_to_display_x,
|
|
67
|
+
)
|
|
68
|
+
from facescope.handoff import (
|
|
69
|
+
CROP_EXPORT_VERSION,
|
|
70
|
+
FrameCropPlan,
|
|
71
|
+
PlanningClip,
|
|
72
|
+
StaticCropExport,
|
|
73
|
+
StoredCropSpan,
|
|
74
|
+
dump_crop_export_json,
|
|
75
|
+
load_crop_export_json,
|
|
76
|
+
validate_crop_export,
|
|
77
|
+
)
|
|
78
|
+
from facescope.inspection import (
|
|
79
|
+
ChapterInfo,
|
|
80
|
+
ColorInterpretation,
|
|
81
|
+
ContainerStreamInfo,
|
|
82
|
+
InspectedSource,
|
|
83
|
+
MediaProbeResult,
|
|
84
|
+
PillarboxCrop,
|
|
85
|
+
ProbeStatus,
|
|
86
|
+
inspect_mkv_source,
|
|
87
|
+
preflight_inspection_capabilities,
|
|
88
|
+
probe_media,
|
|
89
|
+
)
|
|
90
|
+
from facescope.motion import DEFAULT_MOTION_PROFILE, MotionProfile
|
|
91
|
+
from facescope.pipeline import PlanningResult, plan_frames, plan_video
|
|
92
|
+
from facescope.plan import (
|
|
93
|
+
PLAN_SCHEMA_VERSION,
|
|
94
|
+
AppliedRect,
|
|
95
|
+
ClippedObservation,
|
|
96
|
+
CompositionReason,
|
|
97
|
+
CropPlan,
|
|
98
|
+
CropReason,
|
|
99
|
+
GridSpec,
|
|
100
|
+
PlanningPolicy,
|
|
101
|
+
ProtectedRegionEvidence,
|
|
102
|
+
RefinementReason,
|
|
103
|
+
ReviewFlag,
|
|
104
|
+
ShotPlan,
|
|
105
|
+
ShotReview,
|
|
106
|
+
ShotStrategy,
|
|
107
|
+
SourceGeometry,
|
|
108
|
+
SourceIdentity,
|
|
109
|
+
StreamIdentity,
|
|
110
|
+
TargetSpec,
|
|
111
|
+
compute_source_identity,
|
|
112
|
+
dump_plan_json,
|
|
113
|
+
load_plan_json,
|
|
114
|
+
plan_from_dict,
|
|
115
|
+
plan_to_dict,
|
|
116
|
+
validate_crop_plan,
|
|
117
|
+
validate_plan_for_source,
|
|
118
|
+
)
|
|
119
|
+
from facescope.planner import (
|
|
120
|
+
FaceObservation,
|
|
121
|
+
ImportanceWeights,
|
|
122
|
+
plan_static_shot,
|
|
123
|
+
plan_static_shots,
|
|
124
|
+
retained_vertical_fraction,
|
|
125
|
+
score_shot_observations,
|
|
126
|
+
)
|
|
127
|
+
from facescope.progress import ProgressEvent, ProgressStage
|
|
128
|
+
from facescope.renderer import (
|
|
129
|
+
EncodingConfig,
|
|
130
|
+
ReplayResult,
|
|
131
|
+
preflight_replay_capabilities,
|
|
132
|
+
replay_crop_plan,
|
|
133
|
+
)
|
|
134
|
+
from facescope.verification import (
|
|
135
|
+
VerificationCheck,
|
|
136
|
+
VerificationReport,
|
|
137
|
+
verify_rendered_output,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
__all__ = [
|
|
141
|
+
"CROP_EXPORT_VERSION",
|
|
142
|
+
"DEFAULT_MOTION_PROFILE",
|
|
143
|
+
"PLAN_SCHEMA_VERSION",
|
|
144
|
+
"YUNET_MODEL_FILENAME",
|
|
145
|
+
"YUNET_MODEL_PROVENANCE",
|
|
146
|
+
"YUNET_MODEL_SHA256",
|
|
147
|
+
"AdaptiveCutDetector",
|
|
148
|
+
"AnalysisError",
|
|
149
|
+
"AnalysisTransform",
|
|
150
|
+
"AppliedRect",
|
|
151
|
+
"CancelledError",
|
|
152
|
+
"ChapterInfo",
|
|
153
|
+
"ClippedObservation",
|
|
154
|
+
"ColorInterpretation",
|
|
155
|
+
"CompositionComparison",
|
|
156
|
+
"CompositionMetrics",
|
|
157
|
+
"CompositionReason",
|
|
158
|
+
"ContainerStreamInfo",
|
|
159
|
+
"CropComparison",
|
|
160
|
+
"CropPlan",
|
|
161
|
+
"CropReason",
|
|
162
|
+
"CutDetector",
|
|
163
|
+
"EncodingConfig",
|
|
164
|
+
"FaceDetector",
|
|
165
|
+
"FaceObservation",
|
|
166
|
+
"FaceScopeError",
|
|
167
|
+
"FrameCropPlan",
|
|
168
|
+
"GridSpec",
|
|
169
|
+
"ImportanceWeights",
|
|
170
|
+
"InspectedSource",
|
|
171
|
+
"InspectionError",
|
|
172
|
+
"InvalidCandidateError",
|
|
173
|
+
"MediaProbeResult",
|
|
174
|
+
"MotionProfile",
|
|
175
|
+
"MotionRefinementComparison",
|
|
176
|
+
"PathComparison",
|
|
177
|
+
"PillarboxCrop",
|
|
178
|
+
"PlanEvaluationReport",
|
|
179
|
+
"PlanValidationError",
|
|
180
|
+
"PlanVersionError",
|
|
181
|
+
"PlanningClip",
|
|
182
|
+
"PlanningPolicy",
|
|
183
|
+
"PlanningResult",
|
|
184
|
+
"ProbeStatus",
|
|
185
|
+
"ProgressEvent",
|
|
186
|
+
"ProgressStage",
|
|
187
|
+
"ProtectedRegionEvidence",
|
|
188
|
+
"RawDetection",
|
|
189
|
+
"RefinementReason",
|
|
190
|
+
"RemuxError",
|
|
191
|
+
"RenderError",
|
|
192
|
+
"ReplayResult",
|
|
193
|
+
"ReviewFlag",
|
|
194
|
+
"ReviewStill",
|
|
195
|
+
"ShotComparison",
|
|
196
|
+
"ShotEvaluation",
|
|
197
|
+
"ShotPlan",
|
|
198
|
+
"ShotReview",
|
|
199
|
+
"ShotStrategy",
|
|
200
|
+
"SolverError",
|
|
201
|
+
"SourceGeometry",
|
|
202
|
+
"SourceIdentity",
|
|
203
|
+
"SourceMismatchError",
|
|
204
|
+
"StaticCropExport",
|
|
205
|
+
"StoredCropSpan",
|
|
206
|
+
"StreamIdentity",
|
|
207
|
+
"TargetSpec",
|
|
208
|
+
"TrackingConfig",
|
|
209
|
+
"VerificationCheck",
|
|
210
|
+
"VerificationError",
|
|
211
|
+
"VerificationReport",
|
|
212
|
+
"YuNetFaceDetector",
|
|
213
|
+
"analyze_video",
|
|
214
|
+
"associate_shot_tracks",
|
|
215
|
+
"centered_crop_top",
|
|
216
|
+
"compare_composition",
|
|
217
|
+
"compare_crop_paths",
|
|
218
|
+
"compare_motion_refinement",
|
|
219
|
+
"compute_source_identity",
|
|
220
|
+
"display_to_stored_x",
|
|
221
|
+
"draw_debug_overlay",
|
|
222
|
+
"dump_crop_export_json",
|
|
223
|
+
"dump_plan_json",
|
|
224
|
+
"evaluate_crop_plan",
|
|
225
|
+
"inspect_mkv_source",
|
|
226
|
+
"invert_canvas_box",
|
|
227
|
+
"iter_decoded_bgr_frames",
|
|
228
|
+
"legal_crop_tops",
|
|
229
|
+
"load_crop_export_json",
|
|
230
|
+
"load_plan_json",
|
|
231
|
+
"make_analysis_transform",
|
|
232
|
+
"plan_frames",
|
|
233
|
+
"plan_from_dict",
|
|
234
|
+
"plan_static_shot",
|
|
235
|
+
"plan_static_shots",
|
|
236
|
+
"plan_to_dict",
|
|
237
|
+
"plan_video",
|
|
238
|
+
"preflight_inspection_capabilities",
|
|
239
|
+
"preflight_replay_capabilities",
|
|
240
|
+
"prepare_canvas",
|
|
241
|
+
"probe_media",
|
|
242
|
+
"render_comparison_frame",
|
|
243
|
+
"render_comparison_video",
|
|
244
|
+
"render_composition_frame",
|
|
245
|
+
"render_four_path_frame",
|
|
246
|
+
"render_motion_refinement_frame",
|
|
247
|
+
"render_review_stills",
|
|
248
|
+
"replay_crop_plan",
|
|
249
|
+
"retained_vertical_fraction",
|
|
250
|
+
"score_shot_observations",
|
|
251
|
+
"select_crop_height",
|
|
252
|
+
"select_output_raster",
|
|
253
|
+
"stored_to_display_x",
|
|
254
|
+
"validate_crop_export",
|
|
255
|
+
"validate_crop_plan",
|
|
256
|
+
"validate_plan_for_source",
|
|
257
|
+
"verify_model_file",
|
|
258
|
+
"verify_rendered_output",
|
|
259
|
+
]
|
facescope/_limits.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Resource limits at the media I/O boundary, not the abstract plan geometry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import cast
|
|
6
|
+
|
|
7
|
+
from facescope.errors import FaceScopeError
|
|
8
|
+
|
|
9
|
+
MAX_MEDIA_SIDE = 1920
|
|
10
|
+
MAX_MEDIA_PIXELS = 1920 * 1080
|
|
11
|
+
MAX_PROBE_BYTES = 96 * 1024 * 1024
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def check_media_raster(width: int, height: int, *, label: str, error: type[FaceScopeError]) -> None:
|
|
15
|
+
if max(width, height) > MAX_MEDIA_SIDE or width * height > MAX_MEDIA_PIXELS:
|
|
16
|
+
raise error(
|
|
17
|
+
f"{label} {width}x{height} exceeds media limits "
|
|
18
|
+
f"({MAX_MEDIA_SIDE} pixels per side, {MAX_MEDIA_PIXELS} total pixels)"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def check_frame_limit(max_frames: int | None, *, error: type[FaceScopeError]) -> None:
|
|
23
|
+
if max_frames is not None and (type(cast(object, max_frames)) is not int or max_frames <= 0):
|
|
24
|
+
raise error("max_frames must be a positive integer or None")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_frame_count(count: int, max_frames: int | None, *, error: type[FaceScopeError]) -> None:
|
|
28
|
+
if max_frames is not None and count > max_frames:
|
|
29
|
+
raise error(f"Video frame inventory {count} exceeds limit {max_frames}")
|
facescope/_media.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Private FFmpeg/ffprobe process lifetimes and pipe I/O."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import selectors
|
|
7
|
+
import subprocess
|
|
8
|
+
import tempfile
|
|
9
|
+
from collections.abc import Callable, Generator
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from time import monotonic
|
|
12
|
+
from typing import IO, Literal
|
|
13
|
+
|
|
14
|
+
from facescope.errors import FaceScopeError
|
|
15
|
+
|
|
16
|
+
_CAPTURE_TIMEOUT = 24 * 60 * 60
|
|
17
|
+
_PIPE_TIMEOUT = 60.0
|
|
18
|
+
_POLL_INTERVAL = 0.1
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _wait_cooperatively[T](
|
|
22
|
+
wait: Callable[[float], T], timeout: float, check: Callable[[], None] | None
|
|
23
|
+
) -> T:
|
|
24
|
+
if check is None:
|
|
25
|
+
return wait(timeout)
|
|
26
|
+
deadline = monotonic() + timeout
|
|
27
|
+
while True:
|
|
28
|
+
check()
|
|
29
|
+
remaining = max(0.0, deadline - monotonic())
|
|
30
|
+
try:
|
|
31
|
+
return wait(min(remaining, _POLL_INTERVAL))
|
|
32
|
+
except subprocess.TimeoutExpired:
|
|
33
|
+
if remaining <= _POLL_INTERVAL:
|
|
34
|
+
raise
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _reap(proc: subprocess.Popen[bytes], *, graceful: bool) -> None:
|
|
38
|
+
if proc.poll() is not None:
|
|
39
|
+
return
|
|
40
|
+
if graceful:
|
|
41
|
+
proc.terminate()
|
|
42
|
+
try:
|
|
43
|
+
proc.wait(timeout=1.0)
|
|
44
|
+
return
|
|
45
|
+
except subprocess.TimeoutExpired:
|
|
46
|
+
pass
|
|
47
|
+
proc.kill()
|
|
48
|
+
proc.wait()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run_media(
|
|
52
|
+
cmd: list[str],
|
|
53
|
+
*,
|
|
54
|
+
error: type[FaceScopeError],
|
|
55
|
+
stage: str,
|
|
56
|
+
cwd: str | None = None,
|
|
57
|
+
timeout: float = _CAPTURE_TIMEOUT,
|
|
58
|
+
check: Callable[[], None] | None = None,
|
|
59
|
+
) -> subprocess.CompletedProcess[bytes]:
|
|
60
|
+
"""Drain both capture pipes and identify launch errors and overdue commands."""
|
|
61
|
+
try:
|
|
62
|
+
with subprocess.Popen(
|
|
63
|
+
cmd,
|
|
64
|
+
stdin=subprocess.DEVNULL,
|
|
65
|
+
stdout=subprocess.PIPE,
|
|
66
|
+
stderr=subprocess.PIPE,
|
|
67
|
+
cwd=cwd,
|
|
68
|
+
) as proc:
|
|
69
|
+
try:
|
|
70
|
+
stdout, stderr = _wait_cooperatively(
|
|
71
|
+
lambda interval: proc.communicate(timeout=interval), timeout, check
|
|
72
|
+
)
|
|
73
|
+
return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr)
|
|
74
|
+
finally:
|
|
75
|
+
_reap(proc, graceful=check is not None)
|
|
76
|
+
except subprocess.TimeoutExpired as exc:
|
|
77
|
+
raise error(f"{stage} timed out after {timeout:g}s") from exc
|
|
78
|
+
except OSError as exc:
|
|
79
|
+
raise error(f"Could not start {stage}: {exc}") from exc
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class MediaPipe:
|
|
83
|
+
"""One raw stream, with a deadline on waiting for the child to make progress."""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
pipe: IO[bytes],
|
|
88
|
+
selector: selectors.BaseSelector,
|
|
89
|
+
*,
|
|
90
|
+
timeout: float,
|
|
91
|
+
check: Callable[[], None] | None = None,
|
|
92
|
+
) -> None:
|
|
93
|
+
self._fd = pipe.fileno()
|
|
94
|
+
self._selector = selector
|
|
95
|
+
self._timeout = timeout
|
|
96
|
+
self._check = check
|
|
97
|
+
|
|
98
|
+
def _ready(self) -> None:
|
|
99
|
+
deadline = monotonic() + self._timeout
|
|
100
|
+
while True:
|
|
101
|
+
delay = self._timeout
|
|
102
|
+
if self._check is not None:
|
|
103
|
+
self._check()
|
|
104
|
+
delay = min(_POLL_INTERVAL, max(0.0, deadline - monotonic()))
|
|
105
|
+
if self._selector.select(delay):
|
|
106
|
+
return
|
|
107
|
+
if self._check is None or monotonic() >= deadline:
|
|
108
|
+
raise TimeoutError(f"no pipe progress for {self._timeout:g}s")
|
|
109
|
+
|
|
110
|
+
def read(self, size: int) -> bytes:
|
|
111
|
+
"""Read exactly size bytes unless the child reaches EOF first."""
|
|
112
|
+
data = bytearray()
|
|
113
|
+
while len(data) < size:
|
|
114
|
+
self._ready()
|
|
115
|
+
try:
|
|
116
|
+
chunk = os.read(self._fd, size - len(data))
|
|
117
|
+
except BlockingIOError:
|
|
118
|
+
continue
|
|
119
|
+
if not chunk:
|
|
120
|
+
break
|
|
121
|
+
data.extend(chunk)
|
|
122
|
+
return bytes(data)
|
|
123
|
+
|
|
124
|
+
def lines(self, max_bytes: int) -> Generator[bytes]:
|
|
125
|
+
"""Yield LF-delimited records without buffering more than one bounded line."""
|
|
126
|
+
pending = bytearray()
|
|
127
|
+
while chunk := self.read(8192):
|
|
128
|
+
parts = chunk.split(b"\n")
|
|
129
|
+
for i, part in enumerate(parts):
|
|
130
|
+
pending.extend(part)
|
|
131
|
+
if len(pending) > max_bytes:
|
|
132
|
+
raise ValueError(f"line exceeds {max_bytes} bytes")
|
|
133
|
+
if i < len(parts) - 1:
|
|
134
|
+
yield bytes(pending)
|
|
135
|
+
pending.clear()
|
|
136
|
+
if pending:
|
|
137
|
+
yield bytes(pending)
|
|
138
|
+
|
|
139
|
+
def write(self, data: bytes) -> None:
|
|
140
|
+
"""Send the entire frame, even when the pipe accepts only a partial write."""
|
|
141
|
+
pending = memoryview(data)
|
|
142
|
+
while pending:
|
|
143
|
+
self._ready()
|
|
144
|
+
try:
|
|
145
|
+
pending = pending[os.write(self._fd, pending) :]
|
|
146
|
+
except BlockingIOError:
|
|
147
|
+
continue
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _diagnostics(log: IO[bytes]) -> str:
|
|
151
|
+
end = log.seek(0, os.SEEK_END)
|
|
152
|
+
log.seek(max(0, end - 8192))
|
|
153
|
+
return log.read().decode("utf-8", errors="replace").strip()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@contextmanager
|
|
157
|
+
def media_pipe(
|
|
158
|
+
cmd: list[str],
|
|
159
|
+
*,
|
|
160
|
+
mode: Literal["read", "write"],
|
|
161
|
+
error: type[FaceScopeError],
|
|
162
|
+
stage: str,
|
|
163
|
+
timeout: float = _PIPE_TIMEOUT,
|
|
164
|
+
check: Callable[[], None] | None = None,
|
|
165
|
+
) -> Generator[MediaPipe]:
|
|
166
|
+
"""Drain stderr independently of raw I/O and always close and reap the child."""
|
|
167
|
+
reading = mode == "read"
|
|
168
|
+
with tempfile.TemporaryFile() as log:
|
|
169
|
+
try:
|
|
170
|
+
proc = subprocess.Popen(
|
|
171
|
+
cmd,
|
|
172
|
+
stdin=subprocess.DEVNULL if reading else subprocess.PIPE,
|
|
173
|
+
stdout=subprocess.PIPE if reading else subprocess.DEVNULL,
|
|
174
|
+
stderr=log,
|
|
175
|
+
)
|
|
176
|
+
except OSError as exc:
|
|
177
|
+
raise error(f"Could not start {stage}: {exc}") from exc
|
|
178
|
+
pipe = proc.stdout if reading else proc.stdin
|
|
179
|
+
assert pipe is not None
|
|
180
|
+
try:
|
|
181
|
+
with pipe, selectors.DefaultSelector() as selector:
|
|
182
|
+
os.set_blocking(pipe.fileno(), False)
|
|
183
|
+
selector.register(pipe, selectors.EVENT_READ if reading else selectors.EVENT_WRITE)
|
|
184
|
+
yield MediaPipe(pipe, selector, timeout=timeout, check=check)
|
|
185
|
+
returncode = _wait_cooperatively(lambda interval: proc.wait(interval), timeout, check)
|
|
186
|
+
if returncode != 0:
|
|
187
|
+
raise error(f"{stage} failed ({returncode}): {_diagnostics(log)}")
|
|
188
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
189
|
+
_reap(proc, graceful=False)
|
|
190
|
+
detail = _diagnostics(log)
|
|
191
|
+
raise error(f"{stage}: {exc}" + (f"; {detail}" if detail else "")) from exc
|
|
192
|
+
finally:
|
|
193
|
+
_reap(proc, graceful=check is not None)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Temporary, independently verified Matroska stream copy for standalone media."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
from collections.abc import Callable, Generator
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from fractions import Fraction
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from facescope._media import run_media
|
|
13
|
+
from facescope.errors import InspectionError, RemuxError, VerificationError
|
|
14
|
+
from facescope.inspection import (
|
|
15
|
+
InspectedSource,
|
|
16
|
+
inspect_mkv_source,
|
|
17
|
+
preflight_inspection_capabilities,
|
|
18
|
+
)
|
|
19
|
+
from facescope.progress import ExecutionControl, ProgressEvent, ProgressStage
|
|
20
|
+
from facescope.verification import (
|
|
21
|
+
_compare_chapters, # pyright: ignore[reportPrivateUsage]
|
|
22
|
+
_compare_streams, # pyright: ignore[reportPrivateUsage]
|
|
23
|
+
_packets_match, # pyright: ignore[reportPrivateUsage]
|
|
24
|
+
_stream_hashes, # pyright: ignore[reportPrivateUsage]
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _verify_remux(
|
|
29
|
+
source: InspectedSource,
|
|
30
|
+
normalized: InspectedSource,
|
|
31
|
+
ffmpeg: str,
|
|
32
|
+
check: Callable[[], None] | None,
|
|
33
|
+
) -> None:
|
|
34
|
+
streams = _compare_streams(source.streams, normalized.streams, video_pos=-1)
|
|
35
|
+
if not streams.passed:
|
|
36
|
+
raise RemuxError(f"Normalized stream inventory differs: {streams.detail}")
|
|
37
|
+
if (
|
|
38
|
+
source.stream_identity.stream_index != normalized.stream_identity.stream_index
|
|
39
|
+
or source.source_geometry != normalized.source_geometry
|
|
40
|
+
or source.pix_fmt != normalized.pix_fmt
|
|
41
|
+
or source.frame_rate != normalized.frame_rate
|
|
42
|
+
or source.color != normalized.color
|
|
43
|
+
):
|
|
44
|
+
raise RemuxError("Normalized video stream, geometry, cadence or color differs")
|
|
45
|
+
tolerance = Fraction(1, 1000)
|
|
46
|
+
for pts, remuxed_pts in zip(source.frame_pts_times, normalized.frame_pts_times, strict=True):
|
|
47
|
+
if check is not None:
|
|
48
|
+
check()
|
|
49
|
+
if abs(pts - remuxed_pts) > tolerance:
|
|
50
|
+
raise RemuxError("Normalized video presentation timestamps differ by more than 1 ms")
|
|
51
|
+
if any(stream.codec_type == "attachment" for stream in source.streams):
|
|
52
|
+
raise RemuxError("MP4 and AVI with attachments cannot be normalized")
|
|
53
|
+
indices = [stream.stream_index for stream in source.streams]
|
|
54
|
+
normalized_indices = [stream.stream_index for stream in normalized.streams]
|
|
55
|
+
src_hashes = _stream_hashes(ffmpeg, source.path, indices, check=check)
|
|
56
|
+
dst_hashes = _stream_hashes(ffmpeg, normalized.path, normalized_indices, check=check)
|
|
57
|
+
if len(src_hashes) != len(indices) or src_hashes != dst_hashes:
|
|
58
|
+
raise RemuxError("Normalized stream payloads differ")
|
|
59
|
+
ffprobe = preflight_inspection_capabilities()
|
|
60
|
+
for src, dst in zip(indices, normalized_indices, strict=True):
|
|
61
|
+
if src != source.stream_identity.stream_index and not _packets_match(
|
|
62
|
+
ffprobe,
|
|
63
|
+
source.path,
|
|
64
|
+
src,
|
|
65
|
+
normalized.path,
|
|
66
|
+
dst,
|
|
67
|
+
tolerance=tolerance,
|
|
68
|
+
check=check,
|
|
69
|
+
cross_container=True,
|
|
70
|
+
):
|
|
71
|
+
raise RemuxError(
|
|
72
|
+
f"Normalized packet timing, size or sample trimming differs for stream {src}"
|
|
73
|
+
)
|
|
74
|
+
chapters = _compare_chapters(source.chapters, normalized.chapters, tolerance=tolerance)
|
|
75
|
+
if not chapters.passed:
|
|
76
|
+
raise RemuxError(f"Normalized chapters differ: {chapters.detail}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@contextmanager
|
|
80
|
+
def normalized_media(
|
|
81
|
+
source: InspectedSource, *, max_frames: int | None, control: ExecutionControl
|
|
82
|
+
) -> Generator[InspectedSource]:
|
|
83
|
+
"""Yield the input MKV or a verified temporary MKV, removed on exit."""
|
|
84
|
+
if source.container == "matroska":
|
|
85
|
+
yield source
|
|
86
|
+
return
|
|
87
|
+
control.report(ProgressEvent(ProgressStage.REMUX))
|
|
88
|
+
check = None if control.cancel is None else control.check
|
|
89
|
+
ffmpeg = shutil.which("ffmpeg")
|
|
90
|
+
if ffmpeg is None:
|
|
91
|
+
raise RemuxError("Missing 'ffmpeg' on PATH; install FFmpeg first")
|
|
92
|
+
with tempfile.TemporaryDirectory(prefix="facescope-remux-") as temp:
|
|
93
|
+
candidate = Path(temp) / "normalized.mkv"
|
|
94
|
+
command = [
|
|
95
|
+
ffmpeg,
|
|
96
|
+
"-hide_banner",
|
|
97
|
+
"-loglevel",
|
|
98
|
+
"error",
|
|
99
|
+
"-nostdin",
|
|
100
|
+
"-copyts",
|
|
101
|
+
"-i",
|
|
102
|
+
str(source.path.absolute()),
|
|
103
|
+
"-map",
|
|
104
|
+
"0",
|
|
105
|
+
"-c",
|
|
106
|
+
"copy",
|
|
107
|
+
"-map_metadata",
|
|
108
|
+
"0",
|
|
109
|
+
"-map_chapters",
|
|
110
|
+
"0",
|
|
111
|
+
"-default_mode",
|
|
112
|
+
"passthrough",
|
|
113
|
+
"-avoid_negative_ts",
|
|
114
|
+
"disabled",
|
|
115
|
+
str(candidate),
|
|
116
|
+
]
|
|
117
|
+
process = run_media(command, error=RemuxError, stage="FFmpeg remux", check=check)
|
|
118
|
+
if process.returncode != 0:
|
|
119
|
+
raise RemuxError(
|
|
120
|
+
f"FFmpeg stream copy failed: {process.stderr.decode(errors='replace').strip()}"
|
|
121
|
+
)
|
|
122
|
+
try:
|
|
123
|
+
normalized = inspect_mkv_source(candidate, max_frames=max_frames, check=check)
|
|
124
|
+
_verify_remux(source, normalized, ffmpeg, check)
|
|
125
|
+
except RemuxError:
|
|
126
|
+
raise
|
|
127
|
+
except (InspectionError, VerificationError) as exc:
|
|
128
|
+
raise RemuxError(f"Unable to verify normalized MKV: {exc}") from exc
|
|
129
|
+
yield normalized
|