diff --git a/services/headpose/app.py b/services/headpose/app.py index 880d0276..fdafbe6a 100644 --- a/services/headpose/app.py +++ b/services/headpose/app.py @@ -130,6 +130,8 @@ def predict_frame(frame: np.ndarray) -> tuple[float, float, float, float, tuple[ def encode_browser_video(source: pathlib.Path, destination: pathlib.Path) -> None: + with tempfile.NamedTemporaryFile(prefix="headpose-browser-", suffix=".mp4", delete=False) as temporary: + local_output = pathlib.Path(temporary.name) command = [ "ffmpeg", "-hide_banner", @@ -149,12 +151,19 @@ def encode_browser_video(source: pathlib.Path, destination: pathlib.Path) -> Non "yuv420p", "-movflags", "+faststart", - str(destination), + str(local_output), ] - completed = subprocess.run(command, capture_output=True, text=True, check=False) - if completed.returncode != 0 or not destination.is_file() or destination.stat().st_size <= 0: - detail = completed.stderr.strip() or completed.stdout.strip() - raise RuntimeError(f"failed to encode browser-playable HeadPose render: {detail[:800]}") + try: + completed = subprocess.run(command, capture_output=True, text=True, check=False) + if completed.returncode != 0 or not local_output.is_file() or local_output.stat().st_size <= 0: + detail = completed.stderr.strip() or completed.stdout.strip() + raise RuntimeError(f"failed to encode browser-playable HeadPose render: {detail[:800]}") + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(local_output, destination) + if not destination.is_file() or destination.stat().st_size <= 0: + raise RuntimeError("browser-playable HeadPose render was not persisted") + finally: + local_output.unlink(missing_ok=True) def process_video(source: pathlib.Path, destination: pathlib.Path, stride: int, max_frames: int) -> list[dict[str, Any]]: diff --git a/tests/backend/test_delivery_pose_contracts.py b/tests/backend/test_delivery_pose_contracts.py index a0fb6a53..b1f90814 100644 --- a/tests/backend/test_delivery_pose_contracts.py +++ b/tests/backend/test_delivery_pose_contracts.py @@ -175,6 +175,8 @@ def test_headpose_service_skips_empty_sampled_frames_but_keeps_video_fail_closed assert '"libx264"' in source assert '"+faststart"' in source assert '"browserPlayable": True' in source + assert 'NamedTemporaryFile(prefix="headpose-browser-"' in source + assert "shutil.copy2(local_output, destination)" in source def test_package_v3_rejects_missing_required_headpose(tmp_path):