利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
feat(video): add local video projects (#1549)
Rudy Mizrahi Celeklie05cefb177c4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c925d608..0bdfc64b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -62,6 +62,17 @@ jobs:# 测试,避免测试文件已存在但 CI 没有真正执行。run: uv run --no-sync python -X utf8 -m coverage run -m pytest -q test+ # Keep the legacy suite's portable media backend selection unchanged.+ # Native project rendering is a separate mandatory pass after installing+ # system tools; append its coverage before enforcing the shared threshold.+ - name: Install FFmpeg for native revision-rendering tests+ run: sudo apt-get update && sudo apt-get install -y ffmpeg++ - name: Run native revision-rendering tests+ run: >-+ uv run --no-sync python -X utf8 -m coverage run --append -m pytest -q+ test/services/test_video_project.py+- name: Report test coveragerun: uv run --no-sync python -m coverage reportdiff --git a/README-en.md b/README-en.mdindex 04830d52..92bc9390 100644--- a/README-en.md+++ b/README-en.md@@ -583,3 +583,7 @@ Solution: [See how to download the model manually from Hugging Face](#subtitle-g## License 📝Click to view the [`LICENSE`](LICENSE) file++### Editable local video projects++Use [revision-aware local projects](docs/video-projects.md) to replace prepared scene media, compare revisions and rebuild only affected stages. The opt-in CLI preserves verified artifacts and the last successful export; it makes no provider calls or automatic posts.diff --git a/app/services/video_project.py b/app/services/video_project.pynew file mode 100644index 00000000..533497a6--- /dev/null+++ b/app/services/video_project.py@@ -0,0 +1,945 @@+"""Opt-in, local revision rendering. No providers, credentials or publishing.++Run ``python -m app.services.video_project --help``. Prepared footage and audio+can come from an existing MoneyPrinter task; this module does not regenerate them.+"""++from __future__ import annotations++import argparse+from contextlib import contextmanager+from dataclasses import asdict, dataclass+import hashlib+import json+import math+import os+from pathlib import Path+import re+import shutil+import subprocess+import tempfile+import time+from typing import Callable, Iterator+from uuid import uuid4++PREPARED_FORMATS = "mov,matroska,avi,mpegts,mpegvideo,ogg,flv,wav,mp3,flac,aac"+SCHEMA_VERSION = 1+RENDERER_VERSION = "local-ffmpeg-v1"+_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")+++class ProjectError(ValueError):+ pass+++class RenderCancelled(ProjectError):+ pass+++def _identifier(value: str) -> str:+ if not isinstance(value, str) or not _ID.fullmatch(value):+ raise ProjectError("IDs must be 1–64 letters, digits, underscores or hyphens")+ return value+++def _digest(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as source:+ for block in iter(lambda: source.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def _fingerprint(value: object) -> str:+ return hashlib.sha256(+ json.dumps(+ value, sort_keys=True, separators=(",", ":"), allow_nan=False+ ).encode()+ ).hexdigest()+++def _atomic_json(path: Path, value: object) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, name = tempfile.mkstemp(prefix=".write-", dir=path.parent)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as target:+ json.dump(value, target, sort_keys=True, indent=2, allow_nan=False)+ target.flush()+ os.fsync(target.fileno())+ os.replace(name, path)+ finally:+ Path(name).unlink(missing_ok=True)+++@contextmanager+def _lock(path: Path, timeout: float = 30) -> Iterator[None]:+ """OS-owned locks are released after process death; no stale PID deletion."""+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("a+b") as handle:+ if os.fstat(handle.fileno()).st_size == 0:+ handle.write(b"0")+ handle.flush()+ end = time.monotonic() + timeout+ while True:+ try:+ if os.name == "nt":+ import msvcrt++ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl++ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)+ break+ except (OSError, BlockingIOError):+ if time.monotonic() >= end:+ raise ProjectError(+ "project is busy; retry when the active operation finishes"+ )+ time.sleep(0.05)+ try:+ yield+ finally:+ if os.name == "nt":+ import msvcrt++ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ import fcntl++ fcntl.flock(handle, fcntl.LOCK_UN)+++@dataclass(frozen=True)+class RenderSettings:+ width: int = 1080+ height: int = 1920+ fps: int = 30+ narration_volume: float = 1.0+ bgm_volume: float = 0.15++ @classmethod+ def parse(cls, value: dict) -> RenderSettings:+ if not isinstance(value, dict) or set(value) - set(cls.__dataclass_fields__):+ raise ProjectError(+ "unknown render settings; credentials/provider configuration are unsupported"+ )+ result = cls(**value)+ for name, limit in (("width", 4096), ("height", 4096), ("fps", 120)):+ number = getattr(result, name)+ if type(number) is not int or not 1 <= number <= limit:+ raise ProjectError(f"{name} must be an integer from 1 to {limit}")+ if result.width % 2 or result.height % 2:+ raise ProjectError("H.264 dimensions must be even")+ for name in ("narration_volume", "bgm_volume"):+ number = getattr(result, name)+ if (+ isinstance(number, bool)+ or not isinstance(number, (int, float))+ or not math.isfinite(number)+ or not 0 <= number <= 4+ ):+ raise ProjectError(f"{name} must be finite and between 0 and 4")+ return result+++@dataclass(frozen=True)+class Stage:+ key: str+ kind: str+ fingerprint: str+ dependencies: tuple[str, ...]+ scene_id: str | None = None+++def _tool_version(executable: str) -> str:+ try:+ result = subprocess.run(+ [executable, "-version"],+ capture_output=True,+ text=True,+ check=True,+ timeout=10,+ )+ return result.stdout.splitlines()[0]+ except (OSError, subprocess.SubprocessError, IndexError) as exc:+ raise ProjectError(f"working {executable} is required") from exc+++def stage_graph(spec: dict) -> list[Stage]:+ """Pure dependency selection: BGM never invalidates an individual scene."""+ stages: list[Stage] = []+ scene_fingerprints: list[str] = []+ settings = RenderSettings.parse(spec["settings"])+ transform = [RENDERER_VERSION, spec["toolchain"]]+ for scene in spec["scenes"]:+ scene_id = scene["id"]+ audio = _fingerprint(+ [+ transform,+ "audio",+ scene["narration"],+ scene.get("audio"),+ scene["duration"] if not scene["audio"] else None,+ settings.narration_volume,+ ]+ )+ timing = _fingerprint(+ [+ transform,+ "timing",+ audio,+ scene["duration"] if not scene["audio"] else None,+ ]+ )+ render = _fingerprint(+ [+ transform,+ "scene",+ timing,+ scene["footage"],+ settings.width,+ settings.height,+ settings.fps,+ ]+ )+ stages.extend(+ [+ Stage(f"{scene_id}:audio", "audio", audio, (), scene_id),+ Stage(+ f"{scene_id}:timing",+ "timing",+ timing,+ (f"{scene_id}:audio",),+ scene_id,+ ),+ Stage(+ f"{scene_id}:scene",+ "scene",+ render,+ (f"{scene_id}:audio", f"{scene_id}:timing"),+ scene_id,+ ),+ ]+ )+ scene_fingerprints.append(render)+ assembly = _fingerprint([transform, "assembly", scene_fingerprints])+ final = _fingerprint(+ [transform, "export", assembly, spec.get("bgm"), settings.bgm_volume]+ )+ stages.extend(+ [+ Stage(+ "assembly",+ "assembly",+ assembly,+ tuple(f"{s['id']}:scene" for s in spec["scenes"]),+ ),+ Stage("export", "export", final, ("assembly",)),+ ]+ )+ return stages+++class VideoProject:+ """A local project store. All reusable artifacts belong to this project."""++ def __init__(self, directory: str | Path):+ self.directory = Path(directory).resolve()+ self.directory.mkdir(parents=True, exist_ok=True)+ self.lock_path = self.directory / ".project.lock"++ def _read(self, path: Path) -> dict:+ with path.open(encoding="utf-8") as source:+ return json.load(source)++ def metadata(self) -> dict:+ return self._read(self.directory / "project.json")++ def _revision_path(self, revision: str) -> Path:+ return self.directory / "revisions" / _identifier(revision)++ def revision(self, revision: str | None = None) -> dict:+ revision = revision or self.metadata()["current_revision"]+ return self._read(self._revision_path(revision) / "spec.json")++ def _asset(self, value: str, relative_to: Path) -> dict:+ path = Path(value)+ if not path.is_absolute():+ path = relative_to / path+ if not path.is_file():+ raise ProjectError(f"missing local asset: {value}")+ folder = self.directory / "assets"+ folder.mkdir(exist_ok=True)+ fd, name = tempfile.mkstemp(prefix=".asset-", dir=folder)+ try:+ with path.open("rb") as source, os.fdopen(fd, "wb") as target:+ shutil.copyfileobj(source, target)+ target.flush()+ os.fsync(target.fileno())+ digest = _digest(Path(name))+ destination = folder / digest+ os.replace(name, destination)+ return {+ "sha256": digest,+ "path": str(destination.relative_to(self.directory)),+ }+ finally:+ Path(name).unlink(missing_ok=True)++ def create_revision(self, request: dict, *, relative_to: str | Path = ".") -> dict:+ """Snapshot caller-supplied prepared media; unknown/credential fields fail."""+ if not isinstance(request, dict) or set(request) - {+ "project_id",+ "scenes",+ "settings",+ "bgm",+ }:+ raise ProjectError(+ "unknown project fields; this manifest accepts prepared local media only"+ )+ project_id = _identifier(request["project_id"])+ settings = RenderSettings.parse(request.get("settings", {}))+ raw_scenes = request.get("scenes")+ if not isinstance(raw_scenes, list) or not 1 <= len(raw_scenes) <= 100:+ raise ProjectError("provide between 1 and 100 scenes")+ scenes = []+ for raw in raw_scenes:+ if not isinstance(raw, dict) or set(raw) - {+ "id",+ "footage",+ "audio",+ "narration",+ "duration",+ }:+ raise ProjectError("unknown scene fields")+ scene_id = _identifier(raw["id"])+ narration = raw.get("narration", "")+ if not isinstance(narration, str) or len(narration) > 100000:+ raise ProjectError("narration must be text under 100000 characters")+ duration = raw.get("duration", 5.0)+ if (+ isinstance(duration, bool)+ or not isinstance(duration, (int, float))+ or not math.isfinite(duration)+ or not 0 < duration <= 3600+ ):+ raise ProjectError(+ "scene duration must be finite and between 0 and 3600 seconds"+ )+ if narration and not raw.get("audio"):+ raise ProjectError(+ "narration requires prepared audio; this renderer does not generate speech"+ )+ scenes.append(+ {+ "id": scene_id,+ "narration": narration,+ "duration": duration,+ "footage": self._asset(raw["footage"], Path(relative_to)),+ "audio": self._asset(raw["audio"], Path(relative_to))+ if raw.get("audio")+ else None,+ }+ )+ if len({s["id"] for s in scenes}) != len(scenes):+ raise ProjectError("scene IDs must be unique and retained across revisions")+ bgm = (+ self._asset(request["bgm"], Path(relative_to))+ if request.get("bgm")+ else None+ )+ revision_id = uuid4().hex+ spec = {+ "schema_version": SCHEMA_VERSION,+ "project_id": project_id,+ "revision_id": revision_id,+ "scenes": scenes,+ "settings": asdict(settings),+ "bgm": bgm,+ "toolchain": {+ "ffmpeg": _tool_version("ffmpeg"),+ "ffprobe": _tool_version("ffprobe"),+ },+ }+ with _lock(self.lock_path):+ metadata_path = self.directory / "project.json"+ metadata = (+ self._read(metadata_path)+ if metadata_path.exists()+ else {+ "schema_version": SCHEMA_VERSION,+ "project_id": project_id,+ "last_successful_export": None,+ }+ )+ if metadata["project_id"] != project_id:+ raise ProjectError("directory already belongs to another project")+ spec["parent_revision"] = metadata.get("current_revision")+ _atomic_json(self._revision_path(revision_id) / "spec.json", spec)+ _atomic_json(+ self._revision_path(revision_id) / "status.json",+ {"state": "pending", "stages": {}},+ )+ metadata["current_revision"] = revision_id+ _atomic_json(metadata_path, metadata)+ return spec++ def _asset_path(self, asset: dict) -> Path:+ path = self.directory / "assets" / asset["sha256"]+ if path.is_symlink() or not path.is_file() or _digest(path) != asset["sha256"]:+ raise ProjectError(+ "source snapshot failed integrity validation; create a new revision from the original asset"+ )+ return path++ def _cached(self, stage: Stage, dependencies: dict | None = None) -> dict | None:+ folder = self.directory / "artifacts" / stage.fingerprint+ record_path = folder / "record.json"+ if not record_path.is_file():+ return None+ try:+ record = self._read(record_path)+ digest = record["sha256"]+ if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):+ return None+ suffix = (+ ".json"+ if stage.kind == "timing"+ else ".wav"+ if stage.kind == "audio"+ else ".mp4"+ )+ media = folder / f"output-{digest}{suffix}"+ if dependencies is not None:+ actual_dependencies = []+ for key in stage.dependencies:+ if key not in dependencies:+ return None+ actual_dependencies.append(+ {+ "fingerprint": dependencies[key]["fingerprint"],+ "sha256": dependencies[key]["sha256"],+ }+ )+ if record.get("dependencies") != actual_dependencies:+ return None+ if (+ not media.is_symlink()+ and record["fingerprint"] == stage.fingerprint+ and record["sha256"] == _digest(media)+ and record["size"] == media.stat().st_size+ ):+ return {**record, "path": str(media)}+ except (OSError, ValueError, KeyError, TypeError):+ pass+ return None++ def plan(self, revision: str | None = None) -> list[dict]:+ spec = self.revision(revision)+ for scene in spec["scenes"]:+ self._asset_path(scene["footage"])+ if scene["audio"]:+ self._asset_path(scene["audio"])+ if spec["bgm"]:+ self._asset_path(spec["bgm"])+ parent = (+ {+ stage.key: stage.fingerprint+ for stage in stage_graph(self.revision(spec["parent_revision"]))+ }+ if spec["parent_revision"]+ else {}+ )+ planned = []+ verified = {}+ for stage in stage_graph(spec):+ cached = self._cached(stage, verified)+ if cached:+ verified[stage.key] = cached+ reason = (+ "matching dependencies and verified bytes"+ if cached+ else (+ "dependencies changed since parent revision"+ if stage.key in parent and parent[stage.key] != stage.fingerprint+ else "artifact failed integrity validation"+ if (+ self.directory / "artifacts" / stage.fingerprint / "record.json"+ ).exists()+ else "no completed artifact for these dependencies"+ )+ )+ planned.append(+ {+ **asdict(stage),+ "action": "reuse" if cached else "build",+ "reason": reason,+ }+ )+ return planned++ def status(self, revision: str | None = None) -> dict:+ revision = revision or self.metadata()["current_revision"]+ return self._read(self._revision_path(revision) / "status.json")++ def cancel(self, revision: str | None = None) -> None:+ with _lock(self.lock_path):+ revision = revision or self.metadata()["current_revision"]+ self.revision(revision)+ _atomic_json(+ self._revision_path(revision) / "cancel.json", {"cancelled": True}+ )++ def _run(self, arguments: list[str], cancel: Path, timeout: float) -> str:+ if cancel.exists():+ raise RenderCancelled("revision cancelled")+ # Prepared media may contain playlist references. Never let an input+ # silently initiate network access; allow local files and pipes only.+ secured_arguments = []+ for argument in arguments:+ if argument == "-i":+ secured_arguments.extend(["-protocol_whitelist", "file,pipe"])+ secured_arguments.append(argument)+ with tempfile.TemporaryFile() as errors:+ process = subprocess.Popen(+ secured_arguments, stdout=subprocess.PIPE, stderr=errors, text=True+ )+ deadline = time.monotonic() + timeout+ try:+ while True:+ if cancel.exists():+ raise RenderCancelled("revision cancelled")+ if time.monotonic() >= deadline:+ raise ProjectError("media command exceeded its stage deadline")+ try:+ stdout, _ = process.communicate(timeout=0.1)+ break+ except subprocess.TimeoutExpired:+ pass+ if process.returncode:+ errors.seek(0, os.SEEK_END)+ size = errors.tell()+ errors.seek(max(0, size - 8192))+ raise ProjectError(+ "media command failed: "+ + errors.read().decode(errors="replace")+ )+ return stdout+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()++ def render(+ self,+ revision: str | None = None,+ *,+ retry: bool = False,+ ffmpeg: str = "ffmpeg",+ ffprobe: str = "ffprobe",+ stage_timeout: float = 600,+ on_stage: Callable[[Stage, bool], None] | None = None,+ ) -> dict:+ if not math.isfinite(stage_timeout) or stage_timeout <= 0:+ raise ProjectError("stage timeout must be finite and positive")+ spec = self.revision(revision)+ revision = spec["revision_id"]+ folder = self._revision_path(revision)+ cancel = folder / "cancel.json"+ # One writer per revision, different revisions may build independently.+ with _lock(folder / ".render.lock"):+ status = self.status(revision)+ if (+ status["state"] in {"failed", "cancelled", "running"} or cancel.exists()+ ) and not retry:+ raise ProjectError(+ "interrupted/failed/cancelled revision requires explicit --retry"+ )+ if retry:+ cancel.unlink(missing_ok=True)+ status["state"] = "running"+ status.pop("error", None)+ _atomic_json(folder / "status.json", status)+ results = {}+ current_stage = None+ try:+ actual_tools = {+ "ffmpeg": _tool_version(ffmpeg),+ "ffprobe": _tool_version(ffprobe),+ }+ if actual_tools != spec["toolchain"]:+ raise ProjectError(+ "FFmpeg toolchain changed; create a revision to rebuild with its new fingerprint"+ )+ self.plan(revision) # Verify source snapshots before starting.+ for stage in stage_graph(spec):+ current_stage = stage.key+ if cancel.exists():+ raise RenderCancelled("revision cancelled")+ cached = self._cached(stage, results)+ reused = cached is not None+ if on_stage:+ on_stage(stage, reused)+ if cancel.exists():+ raise RenderCancelled("revision cancelled")+ if cached is None:+ cached = self._build(+ stage, spec, results, ffmpeg, ffprobe, cancel, stage_timeout+ )+ results[stage.key] = cached+ status["stages"][stage.key] = {+ "fingerprint": stage.fingerprint,+ "reused": reused,+ "sha256": cached["sha256"],+ }+ _atomic_json(folder / "status.json", status)+ with _lock(self.lock_path):+ if cancel.exists():+ raise RenderCancelled("revision cancelled")+ metadata = self.metadata()+ promoted = metadata["current_revision"] == revision+ if promoted:+ metadata["last_successful_export"] = {+ "revision_id": revision,+ **results["export"],+ }+ _atomic_json(self.directory / "project.json", metadata)+ status.update(+ state="succeeded", promoted=promoted, export=results["export"]+ )+ _atomic_json(folder / "status.json", status)+ return status+ except BaseException as exc:+ status.update(+ state="cancelled"+ if isinstance(exc, (RenderCancelled, KeyboardInterrupt))+ else "failed",+ failed_stage=current_stage,+ error=str(exc),+ )+ _atomic_json(folder / "status.json", status)+ raise++ def _build(+ self,+ stage: Stage,+ spec: dict,+ results: dict,+ ffmpeg: str,+ ffprobe: str,+ cancel: Path,+ timeout: float,+ ) -> dict:+ scene = next((s for s in spec["scenes"] if s["id"] == stage.scene_id), None)+ settings = RenderSettings.parse(spec["settings"])+ work = self.directory / ".work"+ work.mkdir(exist_ok=True)+ with tempfile.TemporaryDirectory(prefix="stage-", dir=work) as temporary:+ temporary = Path(temporary)+ suffix = (+ ".json"+ if stage.kind == "timing"+ else ".wav"+ if stage.kind == "audio"+ else ".mp4"+ )+ output = temporary / ("output" + suffix)+ base = [+ ffmpeg,+ "-hide_banner",+ "-loglevel",+ "error",+ "-nostdin",+ "-y",+ "-threads",+ "1",+ "-filter_threads",+ "1",+ ]+ if stage.kind == "audio":+ if scene["audio"]:+ source = [+ "-format_whitelist",+ PREPARED_FORMATS,+ "-i",+ str(self._asset_path(scene["audio"])),+ ]+ else:+ source = [+ "-f",+ "lavfi",+ "-i",+ "anullsrc=r=48000:cl=stereo",+ "-t",+ str(scene["duration"]),+ ]+ self._run(+ base+ + source+ + [+ "-vn",+ "-af",+ f"volume={settings.narration_volume}",+ "-ar",+ "48000",+ "-ac",+ "2",+ "-c:a",+ "pcm_s16le",+ str(output),+ ],+ cancel,+ timeout,+ )+ elif stage.kind == "timing":+ audio = results[f"{scene['id']}:audio"]["path"]+ duration = float(+ self._run(+ [+ ffprobe,+ "-v",+ "error",+ "-show_entries",+ "format=duration",+ "-of",+ "default=noprint_wrappers=1:nokey=1",+ audio,+ ],+ cancel,+ timeout,+ ).strip()+ )+ if not math.isfinite(duration) or not 0 < duration <= 3600:+ raise ProjectError(+ "prepared audio duration must be between 0 and 3600 seconds"+ )+ _atomic_json(output, {"duration": duration})+ elif stage.kind == "scene":+ duration = self._read(Path(results[f"{scene['id']}:timing"]["path"]))[+ "duration"+ ]+ vf = f"scale={settings.width}:{settings.height}:force_original_aspect_ratio=increase,crop={settings.width}:{settings.height},setsar=1,fps={settings.fps}"+ self._run(+ base+ + [+ "-stream_loop",+ "-1",+ "-format_whitelist",+ PREPARED_FORMATS,+ "-i",+ str(self._asset_path(scene["footage"])),+ "-i",+ results[f"{scene['id']}:audio"]["path"],+ "-map",+ "0:v:0",+ "-map",+ "1:a:0",+ "-vf",+ vf,+ "-t",+ str(duration),+ "-c:v",+ "libx264",+ "-preset",+ "veryfast",+ "-pix_fmt",+ "yuv420p",+ "-c:a",+ "aac",+ "-ar",+ "48000",+ "-ac",+ "2",+ "-movflags",+ "+faststart",+ str(output),+ ],+ cancel,+ timeout,+ )+ elif stage.kind == "assembly":+ # Relative numeric links avoid concat syntax/path injection, including apostrophes.+ for index, scene_spec in enumerate(spec["scenes"]):+ shutil.copyfile(+ results[f"{scene_spec['id']}:scene"]["path"],+ temporary / f"{index}.mp4",+ )+ listing = temporary / "concat.txt"+ listing.write_text(+ "".join(+ f"file '{index}.mp4'\n" for index in range(len(spec["scenes"]))+ ),+ encoding="utf-8",+ )+ self._run(+ base+ + [+ "-f",+ "concat",+ "-safe",+ "1",+ "-i",+ str(listing),+ "-c",+ "copy",+ "-movflags",+ "+faststart",+ str(output),+ ],+ cancel,+ timeout,+ )+ elif spec["bgm"] and settings.bgm_volume:+ mix = f"[1:a]volume={settings.bgm_volume}[music];[0:a][music]amix=inputs=2:duration=first:normalize=0[a]"+ self._run(+ base+ + [+ "-i",+ results["assembly"]["path"],+ "-stream_loop",+ "-1",+ "-format_whitelist",+ PREPARED_FORMATS,+ "-i",+ str(self._asset_path(spec["bgm"])),+ "-filter_complex",+ mix,+ "-map",+ "0:v:0",+ "-map",+ "[a]",+ "-c:v",+ "copy",+ "-c:a",+ "aac",+ "-movflags",+ "+faststart",+ str(output),+ ],+ cancel,+ timeout,+ )+ else:+ shutil.copyfile(results["assembly"]["path"], output)+ if cancel.exists():+ raise RenderCancelled("revision cancelled")+ with output.open("rb") as completed:+ os.fsync(completed.fileno())+ record = {+ "fingerprint": stage.fingerprint,+ "sha256": _digest(output),+ "size": output.stat().st_size,+ "renderer_version": RENDERER_VERSION,+ "kind": stage.kind,+ "dependencies": [+ {+ "fingerprint": results[key]["fingerprint"],+ "sha256": results[key]["sha256"],+ }+ for key in stage.dependencies+ ],+ }+ destination = self.directory / "artifacts" / stage.fingerprint+ with _lock(self.lock_path):+ # Another revision may have finished the same fingerprint. Keep its+ # committed bytes immutable instead of replacing a live export.+ existing = self._cached(stage, results)+ if existing is not None:+ return existing+ # Media first, commit record last. Interrupted writes are never trusted.+ destination.mkdir(parents=True, exist_ok=True)+ published = destination / f"output-{record['sha256']}{suffix}"+ os.replace(output, published)+ _atomic_json(destination / "record.json", record)+ return {**record, "path": str(published)}++ def compare(self, before: str, after: str) -> list[dict]:+ left = {stage.key: stage for stage in stage_graph(self.revision(before))}+ right = {stage.key: stage for stage in stage_graph(self.revision(after))}+ return [+ {+ "stage": key,+ "change": "added"+ if key not in left+ else "removed"+ if key not in right+ else "unchanged"+ if left[key].fingerprint == right[key].fingerprint+ else "changed",+ }+ for key in sorted(left.keys() | right.keys())+ ]+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description="Revision-aware local video projects (prepared media, no API calls)"+ )+ parser.add_argument(+ "--project",+ required=True,+ help="Project directory; project-scoped snapshots and artifacts",+ )+ commands = parser.add_subparsers(dest="command", required=True)+ revise = commands.add_parser(+ "revise",+ help="Create/current-select an immutable revision from a JSON manifest",+ )+ revise.add_argument("manifest")+ revise.add_argument("--preset", help="Reusable validated render-settings JSON")+ for name in ("plan", "status", "cancel"):+ commands.add_parser(name).add_argument("--revision")+ render = commands.add_parser("render")+ render.add_argument("--revision")+ render.add_argument("--retry", action="store_true")+ render.add_argument("--stage-timeout", type=float, default=600)+ compare = commands.add_parser("compare")+ compare.add_argument("before")+ compare.add_argument("after")+ preset = commands.add_parser(+ "save-preset",+ help="Export current render settings without assets or credentials",+ )+ preset.add_argument("output")+ args = parser.parse_args(argv)+ try:+ project = VideoProject(args.project)+ if args.command == "revise":+ manifest = Path(args.manifest).resolve()+ with manifest.open(encoding="utf-8") as source:+ request = json.load(source)+ if args.preset:+ with Path(args.preset).open(encoding="utf-8") as source:+ request["settings"] = asdict(+ RenderSettings.parse(json.load(source))+ )+ result = project.create_revision(request, relative_to=manifest.parent)+ elif args.command == "render":+ result = project.render(+ args.revision, retry=args.retry, stage_timeout=args.stage_timeout+ )+ elif args.command == "compare":+ result = project.compare(args.before, args.after)+ elif args.command == "save-preset":+ result = project.revision()["settings"]+ _atomic_json(Path(args.output), result)+ elif args.command == "cancel":+ project.cancel(args.revision)+ result = {"cancel_requested": True}+ else:+ result = getattr(project, args.command)(args.revision)+ print(json.dumps(result, indent=2))+ return 0+ except (ProjectError, OSError, ValueError, KeyError, TypeError) as exc:+ parser.exit(1, f"video project: {exc}\n")+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/docs/video-projects.md b/docs/video-projects.mdnew file mode 100644index 00000000..aa2b97e3--- /dev/null+++ b/docs/video-projects.md@@ -0,0 +1,160 @@+# Editable local video projects++Change one scene without rendering the whole episode again. This opt-in CLI+snapshots prepared local footage and narration, records immutable revisions, and+reuses artifacts only when both their dependencies and SHA-256 integrity match.+It makes no API calls and does not publish videos. Existing generation jobs and+WebUI behavior are unchanged.++This is a revision/artifact foundation for the existing scene/director proposals,+not another director or paid-provider workflow. First generate/download the+footage and narration using the existing task pipeline or your preferred tools.+Use their local output paths below. Keep a scene's ID when replacing its media;+change the order in the manifest to reorder the video.++## Requirements++Python 3.11 or newer and FFmpeg/FFprobe on PATH, including the `libx264` encoder.+Prepared inputs must be standalone encoded media: MOV/MP4, Matroska/WebM, AVI,+MPEG-TS/video, Ogg, FLV, WAV, MP3, FLAC or AAC. HLS/DASH/concat playlists and+external-reference media are rejected; copying only a playlist would not snapshot+its referenced segments. Concat is permitted only for internally generated+assembly lists. Network protocols are disabled for all render inputs.+There are no new Python dependencies. Projects are local single-host stores;+network filesystems with unreliable locking are unsupported. Reserve enough disk+for source snapshots, retained revisions and exports. There is no automatic+artifact pruning or deletion of older successful exports.++## Create, inspect and render++Save `episode.json` beside your prepared assets:++```json+{+ "project_id": "product-episode",+ "settings": {+ "width": 1080,+ "height": 1920,+ "fps": 30,+ "narration_volume": 1.0,+ "bgm_volume": 0.15+ },+ "scenes": [+ {+ "id": "opening",+ "footage": "opening.mp4",+ "audio": "opening.wav",+ "narration": "Introduce the product."+ },+ {+ "id": "product-detail",+ "footage": "detail.mp4",+ "duration": 5+ }+ ],+ "bgm": "music.mp3"+}+```++```sh+python -m app.services.video_project --project storage/projects/product-episode revise episode.json+python -m app.services.video_project --project storage/projects/product-episode plan+python -m app.services.video_project --project storage/projects/product-episode render+python -m app.services.video_project --project storage/projects/product-episode status+```++Relative asset paths resolve against the manifest's directory. Sources are copied+into the project; later editing the original file does not silently change a+revision. The revision ID printed by `revise` identifies an immutable input+snapshot. `status` reports completed stages, reused artifacts, failures and the+export path. `project.json` points to the current revision and the last successful+export, which is preserved until a newer current revision succeeds.++Audio determines the duration of narrated scenes. Silent scenes use `duration`+(default five seconds). Short footage loops; long footage is trimmed. Source+video audio is intentionally replaced with the prepared narration or silence.+All scene outputs use the same dimensions, frame rate and stereo 48kHz audio.+The final BGM mix loops music to the timeline duration and does not normalize+narration away. Zero BGM volume produces an unmixed export.++`narration` is provenance text, not a TTS request. When changing narration, provide+its newly prepared audio too; the CLI cannot verify that the recording speaks the+text. Word-aligned subtitles, transitions, overlays and provider generation are+not implemented by this first local renderer. The timing stage records duration,+not generated word alignments.++## Replace, compare and reuse++Edit only the affected scene/BGM fields, then run `revise` again with the same+`project_id` and stable scene IDs. Use the old and new printed IDs to compare:++```sh+python -m app.services.video_project --project storage/projects/product-episode compare OLD_REVISION NEW_REVISION+python -m app.services.video_project --project storage/projects/product-episode plan+python -m app.services.video_project --project storage/projects/product-episode render+```++| Change | Rebuilt stages |+|---|---|+| One scene's footage | That scene's render, assembly and final export |+| One scene's narration/audio | That scene's audio normalization, timing and render; assembly and export |+| BGM file or volume | Final mix/export only |+| Scene order | Assembly and export only |+| Dimensions/frame rate | Scene renders, assembly and export |+| Narration volume | Audio, timing, scenes, assembly and export |+| FFmpeg tool version/renderer contract | A new revision rebuilds under the changed transformation fingerprint |++The plan explains changed dependencies, missing completed artifacts and integrity+failures. Damaged artifacts are rebuilt from verified snapshots. Damaged source+snapshots fail closed: create a new revision from the original prepared media.+Caches stay inside one project; another project cannot implicitly reuse them.+There are no savings percentages or paid-generation idempotency guarantees.++## Cancellation, failures and concurrent revisions++```sh+python -m app.services.video_project --project storage/projects/product-episode cancel+python -m app.services.video_project --project storage/projects/product-episode render --retry+```++A cancellation request stops the active media subprocess and prevents promotion.+An explicit `--retry` is required after a failed, cancelled or interrupted render.+Completed verified stages remain reusable. A process crash may leave status+`running`; retry rechecks artifacts instead of assuming it completed. Temporary+uncommitted `.work` directories from an abrupt process death may be deleted when+no render is active. They are never a source of trusted reusable artifacts.++Only one renderer writes a revision at a time. Different revisions may render+concurrently and share immutable completed artifacts. If a newer revision is+created while an older one renders, the old revision may finish for comparison,+but cannot replace the current project's last successful export. OS locks release+after process death. Each external media command has a bounded deadline (600+seconds by default, adjustable with `render --stage-timeout`).++Manifests and artifact records use atomic file replacement. Artifact bytes are+published before the commit record; incomplete writes are never trusted. A+fingerprint includes the renderer contract, FFmpeg/FFprobe versions, relevant+settings and content hashes. Unknown manifest/settings fields are rejected,+including provider credentials. Store only public narration content here; no+software can infer whether arbitrary user-written text contains a secret.++## Reusable episode/brand render settings++```sh+python -m app.services.video_project --project storage/projects/product-episode save-preset brand-render.json+python -m app.services.video_project --project storage/projects/next-episode revise next-episode.json --preset brand-render.json+```++Presets reuse dimensions, frame rate and narration/BGM volume. They contain no+assets, project IDs, credentials, provider selections or claims of consistent+AI-generated characters. A supplied preset replaces the manifest's settings.+Scene assets and narration remain explicit per episode.++## Integration boundary++`VideoProject.create_revision`, `plan`, `render`, `status` and `compare` provide the+same prepared-media contract as the CLI. A future accepted director can pass its+completed narration/footage paths, retain scene IDs, and consume export/revision+receipts without changing provider ownership. Existing creative-outcome records+can reference a completed revision ID without introducing automated publishing+or treating observational performance as causal evidence.diff --git a/test/services/test_video_project.py b/test/services/test_video_project.pynew file mode 100644index 00000000..2989066b--- /dev/null+++ b/test/services/test_video_project.py@@ -0,0 +1,584 @@+"""Native FFmpeg scenarios plus deterministic storage/lifecycle checks."""++import copy+import json+from pathlib import Path+import shutil+import subprocess+import threading+from concurrent.futures import ThreadPoolExecutor++import pytest++from app.services.video_project import (+ ProjectError,+ RenderCancelled,+ RenderSettings,+ VideoProject,+ _atomic_json,+ main,+ stage_graph,+)+++def _media(arguments):+ subprocess.run(+ [+ "ffmpeg",+ "-hide_banner",+ "-loglevel",+ "error",+ "-nostdin",+ "-y",+ "-threads",+ "1",+ *arguments,+ ],+ check=True,+ )+++def native(tmp_path):+ if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):+ pytest.skip("native FFmpeg/FFprobe required; no mocked rendering claim")+ for color in ("red", "blue", "green"):+ _media(+ [+ "-f",+ "lavfi",+ "-i",+ f"color=c={color}:s=64x64:r=10:d=0.6",+ "-c:v",+ "libx264",+ "-pix_fmt",+ "yuv420p",+ str(tmp_path / f"{color}.mp4"),+ ]+ )+ for name, frequency, duration in (+ ("voice", 440, 0.6),+ ("voice2", 880, 0.9),+ ("music", 220, 0.6),+ ("music2", 330, 0.6),+ ):+ _media(+ [+ "-f",+ "lavfi",+ "-i",+ f"sine=frequency={frequency}:sample_rate=48000:duration={duration}",+ str(tmp_path / f"{name}.wav"),+ ]+ )+ request = {+ "project_id": "episode",+ "settings": {"width": 64, "height": 64, "fps": 10},+ "scenes": [+ {+ "id": "opening",+ "footage": "red.mp4",+ "audio": "voice.wav",+ "narration": "Original narration",+ },+ {"id": "closing", "footage": "blue.mp4", "duration": 0.6},+ ],+ "bgm": "music.wav",+ }+ project = VideoProject(tmp_path / "project's files")+ revision = project.create_revision(request, relative_to=tmp_path)+ return project, request, revision, tmp_path+++def _builds(project):+ return {stage["key"] for stage in project.plan() if stage["action"] == "build"}+++def _duration(path):+ return float(+ subprocess.check_output(+ [+ "ffprobe",+ "-v",+ "error",+ "-show_entries",+ "format=duration",+ "-of",+ "default=noprint_wrappers=1:nokey=1",+ path,+ ],+ text=True,+ )+ )+++def _pixel(path, second):+ raw = subprocess.check_output(+ [+ "ffmpeg",+ "-v",+ "error",+ "-ss",+ str(second),+ "-i",+ path,+ "-frames:v",+ "1",+ "-f",+ "rawvideo",+ "-pix_fmt",+ "rgb24",+ "-",+ ]+ )+ return tuple(raw[:3])+++def _audio(path):+ return subprocess.check_output(+ [+ "ffmpeg",+ "-v",+ "error",+ "-i",+ path,+ "-vn",+ "-f",+ "s16le",+ "-ac",+ "1",+ "-ar",+ "48000",+ "-",+ ]+ )+++def test_three_native_revision_scenarios(native):+ project, request, original, root = native+ first = project.render()+ initial_export = first["export"]["path"]+ assert 1.15 <= _duration(initial_export) <= 1.35+ assert _pixel(initial_export, 0.2)[0] > 200+ assert _pixel(initial_export, 0.9)[2] > 200+ assert any(_audio(initial_export))+ assert not _builds(project)++ footage = copy.deepcopy(request)+ footage["scenes"][0]["footage"] = "green.mp4"+ shot = project.create_revision(footage, relative_to=root)+ assert _builds(project) == {"opening:scene", "assembly", "export"}+ rendered = project.render()+ assert _pixel(rendered["export"]["path"], 0.2)[1] > 80+ assert _pixel(rendered["export"]["path"], 0.9)[2] > 200+ assert rendered["stages"]["opening:audio"]["reused"]+ assert rendered["stages"]["closing:scene"]["reused"]++ narration = copy.deepcopy(footage)+ narration["scenes"][0].update(audio="voice2.wav", narration="New narration")+ spoken = project.create_revision(narration, relative_to=root)+ assert _builds(project) == {+ "opening:audio",+ "opening:timing",+ "opening:scene",+ "assembly",+ "export",+ }+ narrated = project.render()+ assert 1.45 <= _duration(narrated["export"]["path"]) <= 1.65+ assert narrated["stages"]["closing:scene"]["reused"]+ assert _audio(narrated["export"]["path"]) != _audio(rendered["export"]["path"])++ music = copy.deepcopy(narration)+ music["bgm"] = "music2.wav"+ mixed = project.create_revision(music, relative_to=root)+ assert _builds(project) == {"export"}+ final = project.render()+ assert all(+ entry["reused"] for key, entry in final["stages"].items() if key != "export"+ )+ assert _audio(final["export"]["path"]) != _audio(narrated["export"]["path"])+ assert (+ project.metadata()["last_successful_export"]["revision_id"]+ == mixed["revision_id"]+ )+ assert Path(initial_export).is_file() # Previous success was never overwritten.+ assert project.compare(shot["revision_id"], spoken["revision_id"])[0]["change"] in {+ "changed",+ "unchanged",+ }+ assert stage_graph(project.revision()) == stage_graph(project.revision())+ assert original["project_id"] == mixed["project_id"]+++def test_integrity_and_source_snapshot(native):+ project, request, revision, root = native+ project.render()+ (root / "red.mp4").write_bytes(b"changed outside project")+ assert not _builds(project) # Imports are snapshots, not mutable references.+ opening = next(+ stage for stage in stage_graph(revision) if stage.key == "opening:scene"+ )+ artifact = Path(project._cached(opening)["path"])+ artifact.write_bytes(b"corrupted")+ assert _builds(project) == {"opening:scene", "assembly", "export"}+ project.render() # Repair stage from verified sources; final export remains verified.+ assert artifact.read_bytes() != b"corrupted"+ asset = project.directory / revision["scenes"][0]["footage"]["path"]+ asset.write_bytes(b"source damage")+ with pytest.raises(ProjectError, match="source snapshot"):+ project.plan()+++def test_failed_retry_and_last_success(native):+ project, request, revision, root = native+ success = project.render()+ previous = project.metadata()["last_successful_export"]+ request["scenes"][0]["footage"] = "green.mp4"+ project.create_revision(request, relative_to=root)+ with pytest.raises(ProjectError, match="working.*required"):+ project.render(ffmpeg=str(root / "missing-command"))+ assert project.status()["state"] == "failed"+ assert project.metadata()["last_successful_export"] == previous+ with pytest.raises(ProjectError, match="explicit --retry"):+ project.render()+ assert project.render(retry=True)["state"] == "succeeded"+ assert Path(success["export"]["path"]).exists()+++def test_cancel_then_explicit_retry(native):+ project, _, _, _ = native++ def cancel_scene(stage, reused):+ if stage.kind == "scene":+ project.cancel()++ with pytest.raises(RenderCancelled):+ project.render(on_stage=cancel_scene)+ assert project.status()["state"] == "cancelled"+ assert project.metadata()["last_successful_export"] is None+ with pytest.raises(ProjectError, match="explicit --retry"):+ project.render()+ assert project.render(retry=True)["state"] == "succeeded"+ assert project.status()["stages"]["opening:audio"]["reused"]+++def test_stale_revision_cannot_promote(native):+ project, request, old, root = native+ advanced = False++ def next_revision(stage, reused):+ nonlocal advanced+ if not advanced:+ advanced = True+ request["bgm"] = "music2.wav"+ project.create_revision(request, relative_to=root)++ old_result = project.render(old["revision_id"], on_stage=next_revision)+ assert old_result["state"] == "succeeded" and not old_result["promoted"]+ assert project.metadata()["last_successful_export"] is None+ assert project.render()["promoted"]+++def test_concurrent_revisions_share_immutable_verified_artifacts(native):+ project, request, old, root = native+ new = project.create_revision(request, relative_to=root)+ barrier = threading.Barrier(2)++ def render(revision):+ met = False++ def wait(stage, reused):+ nonlocal met+ if not met:+ met = True+ barrier.wait(timeout=10)++ return project.render(revision, on_stage=wait)++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(pool.map(render, [old["revision_id"], new["revision_id"]]))+ assert [result["promoted"] for result in results] == [False, True]+ assert results[0]["export"]["sha256"] == results[1]["export"]["sha256"]+ assert not _builds(project)+++def test_interrupted_status_requires_retry(native):+ project, _, revision, _ = native+ _atomic_json(+ project._revision_path(revision["revision_id"]) / "status.json",+ {"state": "running", "stages": {}},+ )+ with pytest.raises(ProjectError, match="explicit --retry"):+ project.render()+ assert project.render(retry=True)["state"] == "succeeded"+++ "settings",+ [+ {"api_key": "secret"},+ {"width": 63},+ {"fps": True},+ {"bgm_volume": float("nan")},+ {"height": -2},+ ],+)+def test_settings_validation(settings):+ with pytest.raises(ProjectError):+ RenderSettings.parse(settings)+++def test_cli_presets_compare_and_path_validation(native, capsys):+ project, request, before, root = native+ manifest = root / "input.json"+ manifest.write_text(json.dumps(request))+ preset = root / "preset.json"+ prefix = ["--project", str(project.directory)]+ assert main(prefix + ["save-preset", str(preset)]) == 0+ assert "scenes" not in json.loads(preset.read_text())+ assert main(prefix + ["revise", str(manifest), "--preset", str(preset)]) == 0+ after = project.metadata()["current_revision"]+ assert main(prefix + ["compare", before["revision_id"], after]) == 0+ assert main(prefix + ["plan"]) == 0+ assert main(prefix + ["status"]) == 0+ with pytest.raises(ProjectError):+ project.revision("../../escape")+ request["api_key"] = "do not persist"+ with pytest.raises(ProjectError, match="unknown project fields"):+ project.create_revision(request, relative_to=root)+ assert "do not persist" not in (project.directory / "project.json").read_text()+++def test_real_process_crash_recovers_completed_stages(native):+ import sys++ project, _, _, _ = native+ script = """import os,sys+from app.services.video_project import VideoProject+project=VideoProject(sys.argv[1])+def crash(stage,reused):+ if stage.kind=='scene': os._exit(37)+project.render(on_stage=crash)+"""+ crashed = subprocess.run(+ [sys.executable, "-c", script, str(project.directory)], timeout=20+ )+ assert crashed.returncode == 37+ assert project.status()["state"] == "running"+ assert "opening:audio" not in _builds(project)+ assert "opening:timing" not in _builds(project)+ assert project.metadata()["last_successful_export"] is None+ with pytest.raises(ProjectError, match="explicit --retry"):+ project.render()+ assert project.render(retry=True)["stages"]["opening:audio"]["reused"]+++def test_command_deadline_and_active_cancellation(tmp_path):+ import sys+ import time++ project = VideoProject(tmp_path)+ cancellation = tmp_path / "cancel.json"+ before = time.monotonic()+ with pytest.raises(ProjectError, match="deadline"):+ project._run(+ [sys.executable, "-c", "import time; time.sleep(60)"], cancellation, 0.15+ )+ assert time.monotonic() - before < 3+ timer = threading.Timer(+ 0.15, lambda: _atomic_json(cancellation, {"cancelled": True})+ )+ timer.start()+ try:+ with pytest.raises(RenderCancelled):+ project._run(+ [sys.executable, "-c", "import time; time.sleep(60)"], cancellation, 30+ )+ finally:+ timer.join(timeout=3)+++def test_cli_native_render(native):+ import sys++ project, _, _, _ = native+ completed = subprocess.run(+ [+ sys.executable,+ "-m",+ "app.services.video_project",+ "--project",+ str(project.directory),+ "render",+ ],+ capture_output=True,+ text=True,+ check=True,+ timeout=20,+ )+ report = json.loads(completed.stdout)+ assert report["state"] == "succeeded"+ assert Path(report["export"]["path"]).is_file()+++def test_order_and_render_settings_invalidation(native):+ project, request, before, root = native+ project.render()+ reordered = copy.deepcopy(request)+ reordered["scenes"].reverse()+ project.create_revision(reordered, relative_to=root)+ assert _builds(project) == {"assembly", "export"}+ settings = copy.deepcopy(request)+ settings["settings"]["width"] = 128+ project.create_revision(settings, relative_to=root)+ assert _builds(project) == {"opening:scene", "closing:scene", "assembly", "export"}+ settings = copy.deepcopy(request)+ settings["settings"]["narration_volume"] = 0.5+ project.create_revision(settings, relative_to=root)+ assert _builds(project) == {+ "opening:audio",+ "opening:timing",+ "opening:scene",+ "closing:audio",+ "closing:timing",+ "closing:scene",+ "assembly",+ "export",+ }+ project.create_revision(request, relative_to=root)+ assert not _builds(project)+ changed = project.compare(+ before["revision_id"], project.metadata()["current_revision"]+ )+ assert all(row["change"] == "unchanged" for row in changed)+++def test_no_cross_project_artifact_reuse(native):+ project, request, _, root = native+ project.render()+ other = VideoProject(root / "second-project")+ other.create_revision(request, relative_to=root)+ assert all(stage["action"] == "build" for stage in other.plan())+++def test_commit_record_loss_is_not_success(native):+ project, request, before, root = native+ project.render()+ stage = stage_graph(before)[0]+ record = project.directory / "artifacts" / stage.fingerprint / "record.json"+ record.unlink()+ assert "opening:audio" in _builds(project)+ assert project.render()["state"] == "succeeded"+ # A source asset extension never controls output/cache paths.+ assert not list(project.directory.glob("*.mp4"))+++def test_prepared_media_cannot_fetch_remote_playlist(tmp_path):+ if not shutil.which("ffmpeg"):+ pytest.skip("native FFmpeg required")+ playlist = tmp_path / "unexpected-video.m3u8"+ playlist.write_text(+ "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nhttp://127.0.0.1:9/private.ts\n#EXT-X-ENDLIST\n"+ )+ project = VideoProject(tmp_path / "project")+ with pytest.raises(ProjectError, match="not on whitelist"):+ project._run(+ ["ffmpeg", "-v", "error", "-i", str(playlist), "-f", "null", "-"],+ tmp_path / "cancel.json",+ 10,+ )+++def test_silent_duration_change_renders_new_duration(native):+ project, request, original, root = native+ first = project.render()+ original_audio = project.status()["stages"]["closing:audio"]["fingerprint"]+ request["scenes"][1]["duration"] = 1.2+ project.create_revision(request, relative_to=root)+ assert _builds(project) == {+ "closing:audio",+ "closing:timing",+ "closing:scene",+ "assembly",+ "export",+ }+ second = project.render()+ assert 1.75 <= _duration(second["export"]["path"]) <= 1.95+ assert second["stages"]["closing:audio"]["fingerprint"] != original_audio+ assert (+ _duration(second["export"]["path"]) > _duration(first["export"]["path"]) + 0.5+ )+++def test_different_silent_durations_do_not_collide(native):+ project, request, original, root = native+ request["scenes"][0] = {"id": "short", "footage": "red.mp4", "duration": 0.3}+ request["scenes"][1] = {"id": "long", "footage": "blue.mp4", "duration": 1.2}+ revision = project.create_revision(request, relative_to=root)+ stages = {stage.key: stage for stage in stage_graph(revision)}+ assert stages["short:audio"].fingerprint != stages["long:audio"].fingerprint+ rendered = project.render()+ short = Path(project._cached(stages["short:audio"])["path"])+ long = Path(project._cached(stages["long:audio"])["path"])+ assert abs(_duration(str(short)) - 0.3) < 0.02+ assert abs(_duration(str(long)) - 1.2) < 0.02+ assert 1.45 <= _duration(rendered["export"]["path"]) <= 1.65+++def test_local_reference_playlist_rejected_as_prepared_footage(native):+ project, request, original, root = native+ segment = root / "mutable.ts"+ _media(["-i", str(root / "red.mp4"), "-c", "copy", "-f", "mpegts", str(segment)])+ playlist = root / "external.m3u8"+ playlist.write_text(+ f"#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:1\n#EXTINF:0.6,\n{segment}\n#EXT-X-ENDLIST\n"+ )+ request["scenes"][0]["footage"] = str(playlist)+ project.create_revision(request, relative_to=root)+ with pytest.raises(ProjectError, match="not on whitelist|Invalid data found"):+ project.render()+ assert project.status()["failed_stage"] == "opening:scene"+ assert project.metadata()["last_successful_export"] is None+ assert not list(project.directory.glob("artifacts/*/*.mp4"))+++def test_dash_external_segments_cannot_escape_source_snapshot(native):+ import re++ project, request, original, root = native+ dash = root / "external.mpd"++ def segments(color):+ _media(+ [+ "-i",+ str(root / f"{color}.mp4"),+ "-c:v",+ "libx264",+ "-f",+ "dash",+ str(dash),+ ]+ )++ segments("red")+ text = dash.read_text()+ text = re.sub(+ r'(initialization|media)="([^"]+)"',+ lambda match: f'{match[1]}="{root / match[2]}"',+ text,+ )+ dash.write_text(text)+ request["scenes"][0]["footage"] = str(dash)+ revision = project.create_revision(request, relative_to=root)+ source_snapshot = project._asset_path(revision["scenes"][0]["footage"])+ unchanged_manifest = source_snapshot.read_bytes()+ segments(+ "blue"+ ) # External segments change while the hashed snapshot remains unchanged.+ assert source_snapshot.read_bytes() == unchanged_manifest+ with pytest.raises(ProjectError, match="not on whitelist"):+ project.render()+ assert project.status()["failed_stage"] == "opening:scene"+ assert project.metadata()["last_successful_export"] is None