From 46fe85dde5bd96cf92eda4db06a57118473a859f Mon Sep 17 00:00:00 2001 From: Dragonborn <1078757180@qq.com> Date: Mon, 30 Nov 2026 23:34:09 +0800 Subject: [PATCH 1/9] [feat] video: add editable reference shot breakdowns --- README.md | 2 + README.zh-CN.md | 4 +- apps/api/src/opendirector_api/creation.py | 26 +- apps/api/src/opendirector_api/localization.py | 9 + apps/api/src/opendirector_api/main.py | 2 +- docs/guides/user-guide.md | 10 + docs/guides/user-guide.zh-CN.md | 10 + .../application/creation_canvas.py | 5 + .../application/creation_shots.py | 121 +++ .../application/shot_descriptions.py | 217 ++++ .../opendirector/domain/creation/commands.py | 2 +- .../opendirector/domain/creation/editors.py | 76 +- .../integrations/model_adapters.py | 4 +- .../src/opendirector/media/shot_detection.py | 814 +++++++++++++++ pyproject.toml | 1 + scripts/analyze_reference_shots.py | 72 ++ scripts/describe_reference_shots.py | 180 ++++ src/backend/creationProjection.ts | 11 +- src/canvas/NodeSelectionToolbar.tsx | 10 + src/canvas/ShotBreakdownEditor.tsx | 929 ++++++++++++++++++ src/canvas/shot-breakdown-editor.css | 321 ++++++ src/canvas/workspace/WorkspaceView.tsx | 22 +- src/contracts/creation.schema.json | 557 ++++++++++- src/contracts/generated.ts | 106 +- src/i18n/messages/en-US/editors.ts | 107 ++ src/i18n/messages/zh-CN/editors.ts | 95 ++ tests/test_creation_shots.py | 189 ++++ tests/test_shot_descriptions.py | 266 +++++ tests/test_shot_detection.py | 420 ++++++++ 29 files changed, 4558 insertions(+), 30 deletions(-) create mode 100644 packages/core/src/opendirector/application/creation_shots.py create mode 100644 packages/core/src/opendirector/application/shot_descriptions.py create mode 100644 packages/core/src/opendirector/media/shot_detection.py create mode 100644 scripts/analyze_reference_shots.py create mode 100644 scripts/describe_reference_shots.py create mode 100644 src/canvas/ShotBreakdownEditor.tsx create mode 100644 src/canvas/shot-breakdown-editor.css create mode 100644 tests/test_creation_shots.py create mode 100644 tests/test_shot_descriptions.py create mode 100644 tests/test_shot_detection.py diff --git a/README.md b/README.md index 2d3c755c9..19c13a90a 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,8 @@ Configure a model service in **Settings → Model connections** to use AI chat a Use Chrome or Edge for MP4 export, and keep the page and editor open while rendering. +For a reference video, [edit its shot breakdown](docs/guides/user-guide.md#edit-a-reference-videos-shot-breakdown) to review detected cuts, adjust shot ranges, and save descriptions with the project. + ## Documentation - [Installation and updates](docs/guides/installation.md): Prerequisites, platform instructions, startup, and updates. diff --git a/README.zh-CN.md b/README.zh-CN.md index 7b4d4894c..1f71a67db 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -30,7 +30,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作 OpenDirector 官方 B 站账号 -

+

## 最新动态 @@ -98,6 +98,8 @@ opendirector serve 导出 MP4 推荐使用 Chrome 或 Edge,合成期间需保持页面和编辑器打开。 +有参考视频时,可以[编辑分镜](docs/guides/user-guide.zh-CN.md#编辑参考视频的分镜),复核检测切点、调整镜头区间,并将描述保存在项目中。 + ## 文档 - [安装与更新](docs/guides/installation.zh-CN.md):环境准备、各平台安装、启动与更新。 diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 76d6d100f..6776b945e 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -12,29 +12,31 @@ from urllib.parse import quote, unquote from fastapi import APIRouter, Header, Query, Request -from pydantic import BaseModel, Field from fastapi.responses import FileResponse, Response, StreamingResponse from filelock import Timeout +from pydantic import BaseModel, ConfigDict, Field from starlette.background import BackgroundTask, BackgroundTasks from starlette.concurrency import run_in_threadpool from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_canvas import CreationCanvas from opendirector.application.creation_history import CreationHistory +from opendirector.application.creation_shots import CreationShots from opendirector.application.creation_timeline_packages import CreationTimelinePackages from opendirector.application.creation_video_compatibility import CreationVideoCompatibility, VideoConversionTask -from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt from opendirector.domain.creation.assets import Asset, UploadInfo from opendirector.domain.creation.base import MediaKind from opendirector.domain.creation.commands import Command, CommandReceipt, Query as CreationQuery +from opendirector.domain.creation.editors import ShotBreakdownDocument from opendirector.domain.creation.project import ProjectSnapshot, ViewState +from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt from opendirector.domain.projects import ProjectError from opendirector.application.prompt_optimization import PromptOptimizationInput from opendirector.domain.timeline_errors import timeline_error, timeline_error_message from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font from opendirector_api.models import AssetSource, Session -from opendirector_api.localization import localized_receipt +from opendirector_api.localization import localized_receipt, wants_english from opendirector_api.localization import localized_error_for_language @@ -82,13 +84,19 @@ async def disconnected(): await asyncio.gather(work, disconnect, return_exceptions=True) -def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None): +class ShotBreakdownRequest(BaseModel): + model_config = ConfigDict(extra='forbid') + modelConfigId: UUID | None = None + + +def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None, model_configs=None): router = APIRouter(prefix='/api/creation', tags=['Unified creation projects']) reference_checks = asyncio.Semaphore(2) assets = CreationAssets(projects) canvas = CreationCanvas(projects) history = CreationHistory(projects, assets=assets) timeline_packages = CreationTimelinePackages(projects) + shots = CreationShots(projects, model_configs) video_compat = CreationVideoCompatibility(projects) def localized_video_task(request: Request, task: VideoConversionTask) -> VideoConversionTask: @@ -437,6 +445,16 @@ def list_assets(project_id: UUID): def describe_asset(project_id: UUID, asset_id: UUID): return assets.get(project_id, asset_id) + @router.get('/projects/{project_id}/assets/{asset_id}/shot-breakdown', response_model=ShotBreakdownDocument | None) + def read_shots(project_id: UUID, asset_id: UUID): + return shots.get(project_id, asset_id) + + @router.post('/projects/{project_id}/assets/{asset_id}/shot-breakdown', response_model=ShotBreakdownDocument) + async def analyze_shots(project_id: UUID, asset_id: UUID, value: ShotBreakdownRequest, request: Request, + x_opendirector_session: UUID = Header()): + return await shots.create(project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId, + language='en-US' if wants_english(request) else 'zh-CN') + @router.get('/projects/{project_id}/assets/{asset_id}/thumbnail') def thumbnail(project_id: UUID, asset_id: UUID): value, asset = assets.thumbnail(project_id, asset_id) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index cf7a982f5..dc19e731c 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -90,6 +90,15 @@ 'voice_provider_timeout': 'The voice service timed out. Check its status and try again.', 'voice_name_taken': 'This account already has a voice with that name. Choose another name.', 'voice_provider_quota': 'The voice service account has insufficient balance or resource packages. Top up and try again.', + "shot_evidence_immutable": "The original detection and model suggestions are read-only.", + "shot_video_required": "Select a video stored in this project.", + "shot_video_duration": "Shot analysis accepts videos up to 120 seconds.", + "shot_analysis_failed": "Could not analyze the video. Check that it can be decoded and is at most 120 seconds.", + "shot_dependencies": "Install opendirector[shot-analysis] to analyze reference videos.", + "shot_analysis_busy": "Another reference video is being analyzed. Try again shortly.", + "shot_count_limit": "The video has more than 48 shots. Analyze a shorter excerpt.", + "shot_model_required": "Select a chat model that accepts images.", + "shot_model_limit": "Only 12 shots can be described at once. Run detection alone for longer breakdowns.", "moss_speech_text": "Enter the text to read aloud.", "moss_speech_voice": "Enter a Voice ID available to your MOSS account.", "moss_speech_reference": "MOSS speech generation does not accept references. Enter speech text and a Voice ID.", diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index d0f0a3abf..8b4eca1fd 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -91,7 +91,7 @@ async def lifespan(app): app = FastAPI(title="OpenDirector Local API", version="0.1.6", lifespan=lifespan) app.include_router(creation_routes(creation_projects, creation_generation, PromptOptimization(creation_projects, model_configs, chat_provider or ChatCompletions(), - cli_rewrite=_cli_prompt_rewrite))) + cli_rewrite=_cli_prompt_rewrite), model_configs=model_configs)) app.include_router(agent_routes(creation_projects, creation_generation, model_configs, chat_provider, active=active_agents)) app.include_router(library_routes(creation_projects)) app.include_router(voice_routes(creation_generation.voices)) diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 9e406fdef..e33ec955e 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -208,6 +208,16 @@ Select a node, then choose an action from its toolbar. For a local edit, mark an area or create a selection first, then enter your instructions and confirm the action. If a required model capability is missing, follow the tool's instructions to configure it. Hover over a disabled control for an explanation. +## Edit a reference video's shot breakdown + +Install the optional analyzer in the same Python environment as OpenDirector with `python -m pip install 'opendirector[shot-analysis]'`, or `python -m pip install -e '.[shot-analysis]'` from a source checkout. Make FFmpeg and FFprobe available. Import a video, select its canvas node, and choose **Shot breakdown**. **Analyze shots** detects cuts on the CPU and saves a representative frame for each shot. + +To get suggestions for subjects, scenes, and framing, choose an image-capable chat model before the first analysis. The model receives one JPEG per shot. If the model stops early, the detected shots and completed suggestions are saved. Analysis supports videos up to 120 seconds and 48 detected shots. A run with model suggestions supports up to 12 shots. + +Compare the detected range with the draft in the source video, then use **Save breakdown** to save your edited ranges and descriptions. The detected boundaries, representative frames, and model suggestions remain available when you reopen the same video. Ranges use normalized source timestamps with an exclusive end. To remove an extra cut, select the shot just after it and choose **Join previous shot** when the two draft ranges touch. Use **Restore cut** to bring the cut back. + +Save your changes before asking the assistant to continue editing. If the assistant saves a newer version while you have unsaved changes, the editor keeps your draft and asks before discarding it on reload. + ## Arrange and export videos 1. Create a timeline node and open its editor. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 6eec424b3..e324b2f9d 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -208,6 +208,16 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制 需要局部修改时先标记区域或创建选区,再填写要求并确认执行。缺少所需模型能力时,按工具提示补充配置;灰色入口以悬停提示为准。 +## 编辑参考视频的分镜 + +在运行 OpenDirector 的 Python 环境执行 `python -m pip install 'opendirector[shot-analysis]'` 安装可选分析依赖,源码工作区可执行 `python -m pip install -e '.[shot-analysis]'`。准备好 FFmpeg 和 FFprobe。把视频导入画布,选中视频节点并打开**分镜**。点击**分析镜头**后,应用用 CPU 检测切点,为每镜保存一张代表帧。 + +如果需要主体、场景和构图建议,在首次分析前选择支持图片输入的对话模型。模型每镜收到一张 JPEG。模型中途出错时,已检测的镜头和已完成的建议会保存下来。分析支持 120 秒以内、最多 48 个镜头的视频。使用模型建议时,每次最多处理 12 镜。 + +在原片里对照检测区间和草稿边界,修改后点击**保存分镜**。重开同一个视频仍可查看原检测区间、代表帧和模型建议。区间使用源视频的归一化时间戳,终点不含在区间内。多切了一刀时,选中切点后的镜头。若两段草稿首尾相接,点击**与上一镜合并**。用**恢复此切点**可加回切点。 + +让助手接着编辑前,先保存自己的修改。如果助手保存了新版本,编辑器会保留你尚未保存的草稿,重新加载前会请你确认是否丢弃。 + ## 编排和导出视频 1. 创建时间线节点并打开编辑器。 diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 00d698c47..e4335fc51 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -535,6 +535,11 @@ def _mutate(self, data, kind, payload): immutable = ('kind', 'purpose', 'currentResultId') if key == 'spec' else ('kind',) if any(obj[field] != old[field] for field in (*immutable, 'projectId')): raise ContractError('role_restricted', '配置编辑不能修改对象角色或结果选择。', UUID(obj['id'])) + if key == 'document' and obj['kind'] == 'shot_breakdown': + from opendirector.domain.creation.editors import ShotBreakdownDocument + basis = ShotBreakdownDocument.model_validate(old).data.analysis_basis() + if payload.document.data.analysis_basis() != basis: + raise ContractError('shot_evidence_immutable', '不能修改原始分镜检测或模型建议。', UUID(obj['id'])) for item in data['canvasItems']: binding = item['binding'] ref = binding.get('objectRef') or binding.get('draftSpec') diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py new file mode 100644 index 000000000..c5d5dda1c --- /dev/null +++ b/packages/core/src/opendirector/application/creation_shots.py @@ -0,0 +1,121 @@ +"""Build a retained shot breakdown from a pinned project video.""" +import asyncio +from pathlib import Path +from shutil import copyfileobj +from tempfile import TemporaryDirectory +from uuid import uuid5 + +from opendirector.application.creation_assets import CreationAssets +from opendirector.application.creation_canvas import asset_ref +from opendirector.application.creation_tool_assets import CreationToolAssets +from opendirector.application.shot_descriptions import describe_shot_frame, validate_frame_description_config +from opendirector.domain.creation.commands import parse_command +from opendirector.domain.projects import ProjectError +from opendirector.media.async_work import blocking +from opendirector.media.shot_detection import DEFAULT_MAX_DURATION_SECONDS, inspect_video_shots + +MAX_SHOTS = 48 +MAX_DESCRIBED_SHOTS = 12 + + +class CreationShots: + def __init__(self, projects, model_configs): + self.projects = projects + self.model_configs = model_configs + self.assets = CreationAssets(projects) + self.outputs = CreationToolAssets(projects) + self.analysis_slot = asyncio.Lock() + + def get(self, project_id, asset_id): + snapshot = self.projects.snapshot(project_id) + return next((doc for doc in snapshot.editorDocuments + if doc.kind == 'shot_breakdown' and doc.data.source.assetId == asset_id), None) + + def _require_session(self, project_id, session): + with self.projects.local.transaction() as db: + self.projects._recover() + project_path, _ = self.projects._find(db, project_id) + self.projects._lease(db, project_id, project_path, session) + + def _inspect(self, project_id, asset_id, session, directory): + self._require_session(project_id, session) + asset = self.assets.get(project_id, asset_id) + if asset.kind != 'video': + raise ProjectError('仅支持工程内的视频素材。', code='shot_video_required') + if asset.metadata.durationSeconds and asset.metadata.durationSeconds > DEFAULT_MAX_DURATION_SECONDS: + raise ProjectError('分镜分析仅支持 120 秒以内的视频。', code='shot_video_duration') + video = directory / 'source' + stream, source = self.assets.open_media(project_id, asset_id) + with stream, video.open('wb') as target: + copyfileobj(stream, target) + try: + analysis = inspect_video_shots(video, directory) + except (ImportError, RuntimeError, ValueError) as exc: + if isinstance(exc, ImportError) or isinstance(exc.__cause__, ImportError): + raise ProjectError('分镜分析需要可选依赖。请安装 opendirector[shot-analysis]。', + 503, code='shot_dependencies') from exc + raise ProjectError('无法分析这段视频。请确认视频可解码且时长不超过 120 秒。', + code='shot_analysis_failed') from exc + if source.fingerprint != 'sha256:' + analysis['source']['sha256']: + raise ProjectError('视频内容已变化,请重新导入后分析。', 409, code='storage_unavailable') + return source, analysis + + def _save(self, project_id, source, analysis, descriptions, directory, session): + self._require_session(project_id, session) + document_id = uuid5(source.id, 'reference-shot-breakdown') + source_ref = asset_ref(source) + shots = [] + for shot, suggestion in zip(analysis['shots'], descriptions, strict=True): + frame = shot['representative'] + start, end = shot['startPts'], shot['endPts'] + frame_id = uuid5(document_id, f"{shot['id']}:{frame['pts']}") + path = directory / frame['path'] + imported = self.outputs.import_file(project_id, frame_id, f"{source.fingerprint[7:15]}-{path.name}", + path.read_bytes(), session, sources=(source_ref,)) + image = self.assets.get(project_id, imported['id']) + shots.append(dict(id=shot['id'], measured=dict(startPts=start, endPts=end, + representativePts=frame['pts'], representative=asset_ref(image)), + frameSuggestion=suggestion, edit=dict(startPts=start, endPts=end, description=''))) + video = analysis['source'] + command = parse_command(dict(commandId=uuid5(document_id, 'create'), projectId=project_id, + type='editor.create', payload=dict(document=dict(id=document_id, projectId=project_id, + kind='shot_breakdown', data=dict(source=source_ref, timeBase=video['timeBase'], + originPts=video['originPts'], durationPts=shots[-1]['measured']['endPts'], shots=shots))))) + receipt = self.projects.execute(command, session=session) + if receipt.status != 'applied': + code = receipt.issues[0].code if receipt.issues else 'operation_rejected' + raise ProjectError('保存分镜失败,请重新打开工程后再试。', 409, code=code) + return self.get(project_id, source.id) + + async def create(self, project_id, asset_id, session, *, model_config_id=None, language='en-US'): + if self.analysis_slot.locked(): + raise ProjectError('正在分析另一段参考视频,请稍后重试。', 409, code='shot_analysis_busy') + async with self.analysis_slot: + saved = await asyncio.to_thread(self.get, project_id, asset_id) + if saved is not None: + return saved + config = None + if model_config_id is not None: + config = await asyncio.to_thread(self.model_configs.agent, str(model_config_id)) + try: + validate_frame_description_config(config) + except ValueError as exc: + raise ProjectError('请选择支持图片输入的对话模型。', code='shot_model_required') from exc + with TemporaryDirectory(prefix='opendirector-shots-') as temporary: + directory = Path(temporary) + source, analysis = await blocking(self._inspect, project_id, asset_id, session, directory) + if len(analysis['shots']) > MAX_SHOTS: + raise ProjectError('切镜超过 48 个。请截取较短的参考片段再试。', code='shot_count_limit') + descriptions = [None] * len(analysis['shots']) + if config is not None: + if len(descriptions) > MAX_DESCRIBED_SHOTS: + raise ProjectError('单次最多描述 12 个镜头。可先仅检测切镜。', + code='shot_model_limit') + for index, shot in enumerate(analysis['shots']): + frame = (directory / shot['representative']['path']).read_bytes() + try: + row = await describe_shot_frame(config, shot, frame, language=language) + except (ProjectError, ValueError): + break + descriptions[index] = dict(modelId=row['model']['modelId'], **row['description']) + return await blocking(self._save, project_id, source, analysis, descriptions, directory, session) diff --git a/packages/core/src/opendirector/application/shot_descriptions.py b/packages/core/src/opendirector/application/shot_descriptions.py new file mode 100644 index 000000000..d8c7b4b1f --- /dev/null +++ b/packages/core/src/opendirector/application/shot_descriptions.py @@ -0,0 +1,217 @@ +"""Bounded frame-only descriptions for explicitly selected reference shots. + +One representative JPEG is described per request through the configured chat +adapter. The result records the exact frame bytes and measured timing as model +inference; it is never treated as a source fact or a user edit. +""" + +from fractions import Fraction +import hashlib +import json +import re +import time + +from opendirector.domain.capabilities import ChatRequest, agent_input_modalities +from opendirector.domain.input_rules import input_rules +from opendirector.integrations.model_adapters import adapter_for +from opendirector.integrations.reference_inputs import data_uri, image_type, request_size + +SCHEMA_VERSION = 1 +DEFAULT_MAX_TOKENS = 384 +MAX_FIELD_CHARS = 1200 +LANGUAGES = { + "en-US": "Write the three field values in English.", + "zh-CN": "字段值请使用简体中文;画面无法确认的内容写“无法判断”。", +} +_FENCE = re.compile(r"^```(?:json)?\s*(.*?)\s*```$", re.S) +_SYSTEM = ( + "You describe one representative still frame from a video shot. Return only " + "a JSON object with exactly three non-empty string fields: \"subject\", " + "\"scene\", and \"framing\". Report only what is visible in this single frame. " + "You may mention visible pose or objects being held. Do not claim or infer " + "temporal change, motion, actions across time, camera movement, audio, " + "identities, named people, story meaning, or events that one frame cannot " + "show. Write \"unclear\" instead of guessing. Your text is model inference " + "about the frame, not a source fact or a user edit. Do not add prose outside " + "the JSON object." +) + + +def validate_frame_description_config(config, *, transport=None): + """Reject a configuration that cannot serve one frame description.""" + if not isinstance(config, dict): + raise ValueError("镜头描述需要已配置的对话模型。") + if config.get("kind") != "agent": + raise ValueError("镜头描述需要已配置的对话模型(kind=agent)。") + modalities = agent_input_modalities(config["kind"], config.get("inputModalities")) + if "image" not in modalities: + raise ValueError("镜头描述需要支持图片输入的对话模型,请启用图片输入模态。") + if not config.get("id") or not config.get("modelId") or not config.get("url"): + raise ValueError("模型配置缺少 id、modelId 或 url。") + adapter = adapter_for(config, transport) + if adapter is None or "text.chat" not in adapter.capabilities: + raise ValueError("所选模型不提供文本对话能力,不能用于镜头描述。") + + +def frame_reference(shot): + """Validate one shot and return its exact representative-frame provenance.""" + if not isinstance(shot, dict): + raise ValueError("镜头记录无效。") + shot_id = shot.get("id") + if not isinstance(shot_id, str) or not shot_id.strip(): + raise ValueError("镜头缺少有效 id。") + representative = shot.get("representative") + if not isinstance(representative, dict): + raise ValueError(f"镜头 {shot_id} 缺少代表帧。") + path = representative.get("path") + if not isinstance(path, str) or not path.strip(): + raise ValueError(f"镜头 {shot_id} 的代表帧缺少路径。") + start_pts = _integer(shot.get("startPts"), "startPts", shot_id) + end_pts = _integer(shot.get("endPts"), "endPts", shot_id) + pts = _integer(representative.get("pts"), "representative.pts", shot_id) + if not start_pts <= pts < end_pts: + raise ValueError( + f"镜头 {shot_id} 的代表帧 PTS {pts} 不在区间 " + f"[{start_pts}, {end_pts}) 内。" + ) + shot_time_base = _time_base(shot.get("timeBase"), "timeBase", shot_id) + representative_time_base = _time_base( + representative.get("timeBase"), "representative.timeBase", shot_id + ) + if shot_time_base != representative_time_base: + raise ValueError(f"镜头 {shot_id} 的镜头与代表帧 timeBase 不一致。") + seconds = round(float(Fraction(pts) * shot_time_base), 6) + return { + "path": path, + "pts": pts, + "timeBase": _time_base_text(shot_time_base), + "seconds": seconds, + "startSeconds": round(float(Fraction(start_pts) * shot_time_base), 6), + "endSeconds": round(float(Fraction(end_pts) * shot_time_base), 6), + } + + +async def describe_shot_frame( + config, shot, image_bytes, *, transport=None, + max_tokens=DEFAULT_MAX_TOKENS, language="en-US" +): + """Describe one representative JPEG and return a frame-only provenance row.""" + validate_frame_description_config(config, transport=transport) + frame = frame_reference(shot) + if not isinstance(image_bytes, (bytes, bytearray)) or not image_bytes: + raise ValueError("代表帧图片为空。") + if image_type(image_bytes) != "image/jpeg": + raise ValueError("镜头描述只接受 JPEG 代表帧。") + if ( + not isinstance(max_tokens, int) + or isinstance(max_tokens, bool) + or max_tokens < 1 + ): + raise ValueError("max_tokens 必须是正整数。") + if language not in LANGUAGES: + raise ValueError("language 必须是 en-US 或 zh-CN。") + + rules = input_rules(config) + if len(image_bytes) > rules["imageBytes"]: + raise ValueError("代表帧图片超过当前对话模型的参考图片大小限制。") + messages = _messages(shot["id"], frame, image_bytes, language) + request_size(messages, rules["requestBytes"]) + + adapter = adapter_for(config, transport) + started = time.perf_counter() + content = await adapter.chat( + config, ChatRequest(messages=tuple(messages), max_tokens=max_tokens) + ) + request_seconds = round(time.perf_counter() - started, 6) + description = _parse_description(content) + + return { + "shotId": shot["id"], + "mode": "frame_only", + "interpretation": "model_inference", + "language": language, + "inputFrame": { + "path": frame["path"], + "sha256": hashlib.sha256(image_bytes).hexdigest(), + "pts": frame["pts"], + "timeBase": frame["timeBase"], + "seconds": frame["seconds"], + }, + "model": {"configId": config["id"], "modelId": config["modelId"]}, + "description": description, + "requestSeconds": request_seconds, + } + + +def _messages(shot_id, frame, image_bytes, language): + text = ( + f"Shot {shot_id}: measured interval {frame['startSeconds']:.6f}s to " + f"{frame['endSeconds']:.6f}s. Representative frame timestamp " + f"{frame['seconds']:.6f}s (pts {frame['pts']}, " + f"timeBase {frame['timeBase']}). Describe only this single still frame " + "and return the JSON object with subject, scene, and framing." + ) + return [ + {"role": "system", "content": _SYSTEM + " " + LANGUAGES[language]}, + { + "role": "user", + "content": [ + {"type": "text", "text": text}, + { + "type": "image_url", + "image_url": {"url": data_uri(image_bytes, "image/jpeg")}, + }, + ], + }, + ] + + +def _parse_description(content): + if not isinstance(content, str) or not content.strip(): + raise ValueError("模型没有返回镜头描述。") + text = content.strip() + match = _FENCE.match(text) + if match: + text = match.group(1).strip() + try: + value = json.loads(text) + except (TypeError, ValueError): + raise ValueError("模型返回的镜头描述不是有效 JSON。") from None + if not isinstance(value, dict) or set(value) != {"subject", "scene", "framing"}: + raise ValueError( + "模型返回的镜头描述必须且只能包含 subject、scene、framing。" + ) + description = {} + for key in ("subject", "scene", "framing"): + item = value[key] + if not isinstance(item, str): + raise ValueError(f"模型返回的 {key} 必须是非空字符串。") + item = item.strip() + if not item or len(item) > MAX_FIELD_CHARS: + raise ValueError( + f"模型返回的 {key} 必须为 1–{MAX_FIELD_CHARS} 个字符。" + ) + description[key] = item + return description + + +def _integer(value, field, shot_id): + if not isinstance(value, int) or isinstance(value, bool): + raise ValueError(f"镜头 {shot_id} 的 {field} 必须是整数 PTS。") + return value + + +def _time_base(value, field, shot_id): + if value is None: + raise ValueError(f"镜头 {shot_id} 缺少 {field}。") + try: + result = Fraction(str(value).strip()) + except (TypeError, ValueError, ZeroDivisionError): + raise ValueError(f"镜头 {shot_id} 的 {field} 不是有理时间基。") from None + if result <= 0: + raise ValueError(f"镜头 {shot_id} 的 {field} 必须为正数。") + return result + + +def _time_base_text(value): + return f"{value.numerator}/{value.denominator}" diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 72dc22cef..c27076c3f 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -525,7 +525,7 @@ def command_fingerprint(command: Command) -> str: 'voice_not_found', 'voice_delete_unsupported', 'voice_consent_required', 'voice_name_invalid', 'voice_audio_invalid', 'voice_format', 'voice_size', 'voice_duration', 'voice_provider_protocol', 'voice_provider_error', 'voice_provider_timeout', 'voice_model_unsupported', - 'voice_name_taken', 'voice_provider_quota'] + 'voice_name_taken', 'voice_provider_quota', 'shot_evidence_immutable'] class ContractIssue(Contract): diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index eda3f4033..701ff76dc 100644 --- a/packages/core/src/opendirector/domain/creation/editors.py +++ b/packages/core/src/opendirector/domain/creation/editors.py @@ -12,6 +12,8 @@ from .assets import AssetRef from .base import Contract, Identifier, NonNegative, Number, Point, Positive, PositiveInt, ProjectEntity, unique +ShotTick = Annotated[int, Field(strict=True, ge=0)] + Color = Annotated[str, Field(pattern=r'^#[0-9a-fA-F]{6}$')] Unit = Annotated[float, Field(strict=True, ge=0, le=1)] @@ -635,5 +637,77 @@ class MediaEditDocument(EditorDocumentBase): data: MediaEditData = Field(description='Typed editable document contents.') +class MeasuredShot(Contract): + startPts: ShotTick = Field(description='Detected inclusive start in normalized source ticks.') + endPts: PositiveInt = Field(description='Detected exclusive end in normalized source ticks.') + representativePts: ShotTick = Field(description='PTS of the selected source frame.') + representative: AssetRef = Field(description='Pinned representative image.') + + @model_validator(mode='after') + def evidence(self): + if self.representative.kind != 'image' or not self.startPts <= self.representativePts < self.endPts: + raise ValueError('The representative must be an image inside the detected interval') + return self + + +class ShotFrameSuggestion(Contract): + modelId: str = Field(min_length=1, description='Model that described the representative frame.') + subject: str = Field(min_length=1, max_length=1200, description='Subject visible in the representative frame.') + scene: str = Field(min_length=1, max_length=1200, description='Scene visible in the representative frame.') + framing: str = Field(min_length=1, max_length=1200, description='Framing visible in the representative frame.') + + +class ShotEdit(Contract): + startPts: ShotTick = Field(description='Edited inclusive start in normalized source ticks.') + endPts: PositiveInt = Field(description='Edited exclusive end in normalized source ticks.') + description: str = Field(default='', max_length=2000, description='Description entered by the user or Agent.') + joinPrevious: StrictBool = Field(default=False, exclude_if=lambda value: not value, + description='Remove the cut before this shot in the edited sequence. The preceding and current edited intervals must touch.') + + +class BreakdownShot(Contract): + id: Identifier = Field(description='Stable ID within the breakdown.') + measured: MeasuredShot = Field(description='Original detector evidence.') + frameSuggestion: ShotFrameSuggestion | None = Field(default=None, description='Optional still-frame interpretation.') + edit: ShotEdit = Field(description='Editable interval and description.') + + +class ShotBreakdownData(Contract): + source: AssetRef = Field(description='Pinned reference video.') + timeBase: str = Field(pattern=r'^[1-9][0-9]*/[1-9][0-9]*$', description='Seconds per source tick.') + originPts: int = Field(strict=True, description='Stream PTS of the first decoded frame.') + durationPts: PositiveInt = Field(description='Exclusive end of the analyzed video in normalized ticks.') + shots: tuple[BreakdownShot, ...] = Field(min_length=1, description='Ordered detected shots and their editable versions.') + + @model_validator(mode='after') + def evidence(self): + unique([shot.id for shot in self.shots], 'shot IDs') + if self.source.kind != 'video': + raise ValueError('Shot breakdown requires a video source') + cursor = 0 + previous_edit_end = None + for shot in self.shots: + if shot.measured.startPts != cursor: + raise ValueError('Detected intervals must cover the source continuously') + cursor = shot.measured.endPts + if not shot.edit.startPts < shot.edit.endPts <= self.durationPts: + raise ValueError('Edited shot exceeds the analyzed video interval') + if shot.edit.joinPrevious and shot.edit.startPts != previous_edit_end: + raise ValueError('A shot can only join a contiguous preceding shot') + previous_edit_end = shot.edit.endPts + if cursor != self.durationPts: + raise ValueError('Last measured shot must end at the analyzed video end') + return self + + def analysis_basis(self): + return (self.source, self.timeBase, self.originPts, self.durationPts, + tuple((shot.id, shot.measured, shot.frameSuggestion) for shot in self.shots)) + + +class ShotBreakdownDocument(EditorDocumentBase): + kind: Literal['shot_breakdown'] = Field(description='Reference video shot breakdown.') + data: ShotBreakdownData = Field(description='Source video, measured evidence, suggestions and user edits.') + + EditorDocument = Annotated[TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | - ToolDocument | DirectorDocument | MediaEditDocument, Field(discriminator='kind')] + ToolDocument | DirectorDocument | MediaEditDocument | ShotBreakdownDocument, Field(discriminator='kind')] diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index 560269231..96422ab1a 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -853,8 +853,8 @@ async def work(): async with client.stream('POST', endpoint(config['url'], '/chat/completions'), headers=auth_headers(config), json=payload) as response: value = json.loads(await bounded(response, stage='submit', secrets=(config.get('apiKey', ''),))) - return value['choices'][0]['message']['content'] or '' - return self.THINKING.sub('', await _call('submit', work)).strip() + return self.THINKING.sub('', value['choices'][0]['message']['content'] or '').strip() + return await _call('submit', work) class VllmOmniSegmentation(ModelAdapter): diff --git a/packages/core/src/opendirector/media/shot_detection.py b/packages/core/src/opendirector/media/shot_detection.py new file mode 100644 index 000000000..017306e99 --- /dev/null +++ b/packages/core/src/opendirector/media/shot_detection.py @@ -0,0 +1,814 @@ +"""Bounded shot analysis for reference videos. + +This internal analysis slice decodes a bounded source with PyAV, feeds real frame +timestamps to PySceneDetect's AdaptiveDetector, and writes representative JPEGs. +It does not call a VLM, create descriptions, or persist project objects. +""" + +from bisect import bisect_left +from fractions import Fraction +import hashlib +import json +import math +from pathlib import Path +import subprocess +import time + +from opendirector.media.probe import probe_file, require_ffprobe + +SCHEMA_VERSION = 1 +DEFAULT_MAX_DURATION_SECONDS = 120.0 +DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD = 12.0 +_JPEG_QUALITY = 85 +_REPRESENTATIVE_CANDIDATE_LIMIT = 3 +_REPRESENTATIVE_SAMPLE_WIDTH = 64 +_FFPROBE_STREAM_FIELDS = ( + "index,codec_name,width,height,time_base,avg_frame_rate,r_frame_rate," + "duration,duration_ts,start_time,start_pts,nb_frames" +) + + +def inspect_video_shots( + path, + output_directory, + adaptive_threshold=3.0, + min_scene_seconds=0.1, + min_content_val=15.0, + max_width=640, + representative_intensity_threshold=DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD, + *, + max_duration_seconds=DEFAULT_MAX_DURATION_SECONDS, +): + """Decode a bounded video and return a concise shot analysis record. + + Representative frames are written below ``output_directory/frames``. All PTS + values in shots are normalized to the first decoded frame and expressed in + ``source.timeBase`` units. ``source.originPts`` and ``lastFramePts`` retain + native stream PTS. Seconds never come from a frame ordinal divided by FPS. + + Brightness of up to three sampled frames is a heuristic, not a semantic + quality score. Dark footage remains valid and can be marked low_visibility. + """ + source_path = Path(path) + output_path = Path(output_directory) + if not source_path.is_file(): + raise ValueError(f"Video does not exist: {source_path}") + if not math.isfinite(adaptive_threshold) or adaptive_threshold <= 0: + raise ValueError("adaptive_threshold must be a positive finite number") + if not math.isfinite(min_scene_seconds) or min_scene_seconds < 0: + raise ValueError("min_scene_seconds must be a non-negative finite number") + if not math.isfinite(min_content_val) or min_content_val < 0: + raise ValueError("min_content_val must be a non-negative finite number") + if not isinstance(max_width, int) or max_width < 1: + raise ValueError("max_width must be a positive integer") + if not math.isfinite(representative_intensity_threshold) or not ( + 0 <= representative_intensity_threshold <= 255 + ): + raise ValueError( + "representative_intensity_threshold must be a finite number " + "between 0 and 255" + ) + if not math.isfinite(max_duration_seconds) or max_duration_seconds <= 0: + raise ValueError("max_duration_seconds must be a positive finite number") + + output_path.mkdir(parents=True, exist_ok=True) + (output_path / "frames").mkdir(parents=True, exist_ok=True) + + probe_started = time.perf_counter() + try: + probe_info = probe_file( + source_path, "video", include_container=True, include_codecs=True + ) + except Exception as exc: + raise RuntimeError(f"Could not probe video {source_path.name}") from exc + stream_info = _ffprobe_video_stream(source_path) + stream_duration = _positive_float(stream_info.get("duration")) + if stream_duration is not None and stream_duration > max_duration_seconds: + raise ValueError( + f"Video is {stream_duration:.3f}s, above the {max_duration_seconds:.3f}s limit" + ) + if stream_duration is None: + probe_duration = _positive_float(probe_info.get("durationSeconds")) + if probe_duration is not None and probe_duration > max_duration_seconds: + raise ValueError( + f"Video is {probe_duration:.3f}s, above the {max_duration_seconds:.3f}s limit" + ) + probe_seconds = time.perf_counter() - probe_started + + hash_started = time.perf_counter() + digest = _sha256(source_path) + hash_seconds = time.perf_counter() - hash_started + + detection_started = time.perf_counter() + detection = _detect_cuts( + source_path, + probe_info, + stream_info, + adaptive_threshold=adaptive_threshold, + min_scene_seconds=min_scene_seconds, + min_content_val=min_content_val, + max_width=max_width, + max_duration_seconds=max_duration_seconds, + ) + detection_seconds = time.perf_counter() - detection_started + + time_base = detection["time_base"] + frame_pts = detection["frame_pts"] + shots = _shot_records( + frame_pts, + time_base, + detection["cut_pts"], + detection["end_pts"], + detection["end_method"], + representative_intensity_threshold, + ) + + thumbnail_started = time.perf_counter() + _save_representatives( + source_path, + detection["origin_pts"], + time_base, + shots, + output_path, + max_width, + representative_intensity_threshold, + ) + thumbnail_seconds = time.perf_counter() - thumbnail_started + + avg_rate = _rate_fraction(stream_info.get("avg_frame_rate")) or _rate_fraction( + probe_info.get("frameRate") + ) + r_rate = _rate_fraction(stream_info.get("r_frame_rate")) + origin_pts = detection["origin_pts"] + + return { + "schemaVersion": SCHEMA_VERSION, + "source": { + "filename": source_path.name, + "sha256": digest, + "width": int(probe_info["width"]), + "height": int(probe_info["height"]), + "durationSeconds": _round_seconds(_pts_seconds(detection["end_pts"], time_base)), + "avgFrameRate": _fraction_text(avg_rate), + "rFrameRate": _fraction_text(r_rate), + "timeBase": _fraction_text(time_base), + "originPts": int(origin_pts), + "lastFramePts": int(origin_pts) + frame_pts[-1], + "decodedFrameCount": len(frame_pts), + "ptsSemantics": ( + "Shot and representative PTS values are original stream PTS minus " + "originPts; seconds are PTS * timeBase." + ), + "videoStreamDurationSeconds": _round_seconds(stream_duration) + if stream_duration is not None + else None, + "vfr": _vfr_summary(frame_pts, time_base), + }, + "detector": { + "name": "AdaptiveDetector", + "version": detection["version"], + "parameters": { + "adaptiveThreshold": adaptive_threshold, + "minSceneSeconds": min_scene_seconds, + "minContentVal": min_content_val, + "windowWidth": 2, + "maxWidth": max_width, + "maxDurationSeconds": max_duration_seconds, + "representativeIntensityThreshold": float( + representative_intensity_threshold + ), + }, + }, + "shots": shots, + "timings": { + "probeSeconds": _round_seconds(probe_seconds), + "hashSeconds": _round_seconds(hash_seconds), + "detectionSeconds": _round_seconds(detection_seconds), + "thumbnailSeconds": _round_seconds(thumbnail_seconds), + }, + } + + +def _detect_cuts( + path, + probe_info, + stream_info, + *, + adaptive_threshold, + min_scene_seconds, + min_content_val, + max_width, + max_duration_seconds, +): + try: + import scenedetect + from scenedetect import AdaptiveDetector, FrameTimecode + from scenedetect.common import Timecode + from av.video.reformatter import VideoReformatter + except ImportError as exc: + raise RuntimeError( + "Shot analysis requires PySceneDetect 0.7.1 and PyAV" + ) from exc + + rate = _detector_rate(probe_info, stream_info) + container, stream, time_base = _open_video(path) + detector = AdaptiveDetector( + adaptive_threshold=adaptive_threshold, + min_scene_len=min_scene_seconds, + min_content_val=min_content_val, + ) + frame_pts = [] + cuts = [] + origin_pts = None + last_frame_duration = None + resize = VideoReformatter() + to_bgr = VideoReformatter() + try: + for frame in container.decode(stream): + if frame.pts is None: + raise RuntimeError("Decoded video frame has no presentation timestamp") + if frame.time_base != time_base: + raise RuntimeError("Decoded frame and stream time bases differ") + original_pts = int(frame.pts) + if origin_pts is None: + origin_pts = original_pts + normalized_pts = _normalize_pts(original_pts, origin_pts) + if frame_pts and normalized_pts <= frame_pts[-1]: + raise RuntimeError("Video frame PTS values are not strictly increasing") + if _pts_seconds(normalized_pts, time_base) > max_duration_seconds: + raise ValueError( + f"Video exceeds the {max_duration_seconds:.3f}s analysis limit" + ) + frame_pts.append(normalized_pts) + frame_duration = getattr(frame, "duration", None) + last_frame_duration = ( + int(frame_duration) + if frame_duration is not None and int(frame_duration) > 0 + else None + ) + timecode = FrameTimecode(Timecode(normalized_pts, time_base), rate) + picture = frame + if frame.width > max_width: + picture = resize.reformat(frame, width=max_width, + height=max(1, round(frame.height * max_width / frame.width))) + cuts.extend( + detector.process_frame( + timecode, to_bgr.reformat(picture, format="bgr24").to_ndarray() + ) + ) + finally: + container.close() + + if origin_pts is None or not frame_pts: + raise ValueError("Video contains no decodable frames") + + last_timecode = FrameTimecode(Timecode(frame_pts[-1], time_base), rate) + cuts.extend(detector.post_process(last_timecode)) + cut_pts = sorted({int(timecode.pts) for timecode in cuts}) + + end_pts, end_method = _end_boundary( + frame_pts, + time_base, + last_frame_duration, + _normalized_stream_end(stream_info, origin_pts, time_base), + ) + return { + "version": str(getattr(scenedetect, "__version__", "unknown")), + "time_base": time_base, + "origin_pts": origin_pts, + "frame_pts": frame_pts, + "cut_pts": cut_pts, + "end_pts": end_pts, + "end_method": end_method, + } + + +def _save_representatives( + path, + origin_pts, + time_base, + shots, + output_path, + max_width, + representative_intensity_threshold, +): + candidate_owner = {} + for shot_index, shot in enumerate(shots): + for sample in shot["representative"]["selection"]["sampledFrames"]: + pts = int(sample["pts"]) + if pts in candidate_owner: + raise RuntimeError( + "Representative candidate frames are not unique across shots" + ) + candidate_owner[pts] = shot_index + + selected = {} + current_index = None + requested_candidates = len(candidate_owner) + seen_candidates = 0 + + def finalize(shot_index): + record = selected[shot_index] + shot = shots[shot_index] + target = output_path / shot["representative"]["path"] + _save_thumbnail(record["image"], target, max_width) + shot["representative"]["pts"] = int(record["pts"]) + shot["representative"]["timeBase"] = _fraction_text(time_base) + shot["representative"]["seconds"] = _round_seconds( + _pts_seconds(record["pts"], time_base) + ) + shot["representative"]["visibility"] = record["visibility"] + del selected[shot_index] + + container, stream, second_time_base = _open_video(path) + if second_time_base != time_base: + container.close() + raise RuntimeError("Video time base changed between analysis passes") + try: + for frame in container.decode(stream): + if frame.pts is None: + raise RuntimeError("Decoded video frame has no presentation timestamp") + normalized_pts = _normalize_pts(int(frame.pts), origin_pts) + shot_index = candidate_owner.get(normalized_pts) + if shot_index is None: + continue + seen_candidates += 1 + if current_index is not None and shot_index != current_index: + finalize(current_index) + current_index = None + shot = shots[shot_index] + sample = next( + candidate + for candidate in shot["representative"]["selection"]["sampledFrames"] + if int(candidate["pts"]) == normalized_pts + ) + image = frame.to_image() + mean_intensity = _mean_intensity(image) + sample["meanIntensity"] = round(float(mean_intensity), 3) + candidate = { + "pts": normalized_pts, + "meanIntensity": mean_intensity, + "visibility": ( + "visible" + if mean_intensity >= representative_intensity_threshold + else "low_visibility" + ), + "image": image, + } + midpoint = _midpoint_pts(shot["startPts"], shot["endPts"]) + if _prefer_candidate( + candidate, + selected.get(shot_index), + representative_intensity_threshold, + midpoint, + ): + selected[shot_index] = candidate + current_index = shot_index + if seen_candidates >= requested_candidates: + break + if current_index is not None: + finalize(current_index) + finally: + container.close() + + missing = [ + int(sample["pts"]) + for shot in shots + for sample in shot["representative"]["selection"]["sampledFrames"] + if "meanIntensity" not in sample + ] + if missing: + raise RuntimeError( + "Representative frames were not found during the second decode: " + + ", ".join(str(value) for value in sorted(missing)) + ) + + +def _mean_intensity(image, max_sample_width=_REPRESENTATIVE_SAMPLE_WIDTH): + try: + from PIL import Image + except ImportError as exc: + raise RuntimeError("Shot analysis requires Pillow") from exc + + sample = image.convert("RGB") + if sample.width > max_sample_width: + height = max(1, round(sample.height * max_sample_width / sample.width)) + sample = sample.resize( + (max_sample_width, height), Image.Resampling.BILINEAR + ) + data = sample.tobytes() + if not data: + return 0.0 + return sum(data) / len(data) + + +def _save_thumbnail(image, target, max_width): + try: + from PIL import Image + except ImportError as exc: + raise RuntimeError("Shot analysis requires Pillow") from exc + + if image.width > max_width: + height = max(1, round(image.height * max_width / image.width)) + image = image.resize((max_width, height), Image.Resampling.LANCZOS) + image.convert("RGB").save(target, "JPEG", quality=_JPEG_QUALITY) + + +def _open_video(path): + try: + import av + except ImportError as exc: + raise RuntimeError("Shot analysis requires PyAV") from exc + try: + container = av.open(str(path)) + except Exception as exc: + raise RuntimeError(f"PyAV could not open video {path.name}") from exc + try: + if not container.streams.video: + raise RuntimeError(f"Video {path.name} has no video stream") + stream = container.streams.video[0] + time_base = _time_base(stream.time_base) + except BaseException: + container.close() + raise + return container, stream, time_base + + +def _time_base(value): + try: + result = Fraction(value) + except (TypeError, ValueError, ZeroDivisionError) as exc: + raise RuntimeError("Video stream has no valid rational time base") from exc + if result <= 0: + raise RuntimeError("Video stream time base must be positive") + return result + + +def _detector_rate(probe_info, stream_info): + rate = ( + _rate_fraction(stream_info.get("avg_frame_rate")) + or _rate_fraction(stream_info.get("r_frame_rate")) + or _rate_fraction(probe_info.get("frameRate")) + ) + if rate is None: + raise RuntimeError("Video stream has no valid frame rate") + return rate + + +def _ffprobe_video_stream(path): + try: + require_ffprobe() + except Exception as exc: + raise RuntimeError("ffprobe is required for shot analysis") from exc + try: + process = subprocess.run( + [ + "ffprobe", + "-v", + "error", + "-protocol_whitelist", + "file,pipe", + "-select_streams", + "v:0", + "-show_entries", + f"stream={_FFPROBE_STREAM_FIELDS}", + "-of", + "json", + str(path), + ], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=15, + check=True, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise RuntimeError(f"ffprobe failed for {path.name}") from exc + if len(process.stdout) > 1024 * 1024: + raise RuntimeError("ffprobe video stream metadata is unexpectedly large") + try: + value = json.loads(process.stdout) + except (TypeError, ValueError) as exc: + raise RuntimeError(f"ffprobe returned invalid JSON for {path.name}") from exc + streams = value.get("streams") or [] + if not streams: + raise RuntimeError(f"Video {path.name} has no video stream") + return streams[0] + + +def _sha256(path): + digest = hashlib.sha256() + with path.open("rb") as source: + while True: + chunk = source.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) + return digest.hexdigest() + + +def _normalize_pts(original_pts, origin_pts): + return int(original_pts) - int(origin_pts) + + +def _pts_seconds(pts, time_base): + return float(Fraction(pts) * time_base) + + +def _vfr_summary(frame_pts, time_base): + intervals = [ + float(Fraction(later - earlier) * time_base) + for earlier, later in zip(frame_pts, frame_pts[1:]) + if later > earlier + ] + if not intervals: + return { + "intervalCount": 0, + "isVariable": False, + "minIntervalSeconds": None, + "maxIntervalSeconds": None, + "meanIntervalSeconds": None, + "distinctIntervalCount": 0, + "observed": [], + } + + counts = {} + for value in intervals: + key = round(value, 6) + counts[key] = counts.get(key, 0) + 1 + observed = [ + {"seconds": seconds, "count": count} + for seconds, count in sorted( + counts.items(), key=lambda item: (-item[1], item[0]) + )[:8] + ] + minimum = min(intervals) + maximum = max(intervals) + mean = sum(intervals) / len(intervals) + tolerance = max(1e-6, mean * 0.001) + return { + "intervalCount": len(intervals), + "isVariable": (maximum - minimum) > tolerance, + "minIntervalSeconds": round(minimum, 6), + "maxIntervalSeconds": round(maximum, 6), + "meanIntervalSeconds": round(mean, 6), + "distinctIntervalCount": len(counts), + "observed": observed, + } + + +def _end_boundary(frame_pts, time_base, last_frame_duration, stream_duration): + last_pts = frame_pts[-1] + if isinstance(last_frame_duration, int) and last_frame_duration > 0: + return last_pts + last_frame_duration, "last-frame-duration" + if stream_duration is not None: + end_pts = round(Fraction(str(stream_duration)) / time_base) + if end_pts > last_pts: + return int(end_pts), "video-stream-duration" + if len(frame_pts) > 1: + interval = frame_pts[-1] - frame_pts[-2] + if interval > 0: + return last_pts + interval, "estimated-last-interval" + return last_pts + 1, "estimated-timebase-tick" + + +def _normalized_stream_end(stream_info, origin_pts, time_base): + """Locate the stream end relative to the first frame, never the audio end.""" + try: + stream_base = _time_base(stream_info["time_base"]) + end = (int(stream_info["start_pts"]) + int(stream_info["duration_ts"])) * stream_base + except (KeyError, TypeError, ValueError, RuntimeError): + duration = _positive_float(stream_info.get("duration")) + if duration is None: + return None + try: + start = Fraction(str(stream_info["start_time"])) + except (KeyError, TypeError, ValueError, ZeroDivisionError): + return None + end = start + Fraction(str(duration)) + relative_end = end - origin_pts * time_base + return float(relative_end) if relative_end > 0 else None + + +def _midpoint_pts(start_pts, end_pts): + return Fraction(int(start_pts) + int(end_pts), 2) + + +def _nearest_frame_pts(frame_pts, target_pts, start_pts, end_pts): + """Return the frame nearest ``target_pts`` within ``[start_pts, end_pts)``. + + ``frame_pts`` is the strictly increasing decoded PTS sequence produced by + ``_detect_cuts``. Binary search avoids rescanning every frame for each + representative candidate. + """ + if not frame_pts or end_pts <= start_pts: + return None + first = bisect_left(frame_pts, start_pts) + stop = bisect_left(frame_pts, end_pts) + if first >= stop: + return None + insertion = bisect_left(frame_pts, target_pts, first, stop) + best_key = None + best_pts = None + if insertion > first: + pts = int(frame_pts[insertion - 1]) + best_key = (abs(Fraction(pts) - target_pts), pts) + best_pts = pts + if insertion < stop: + pts = int(frame_pts[insertion]) + key = (abs(Fraction(pts) - target_pts), pts) + if best_key is None or key < best_key: + best_key = key + best_pts = pts + return best_pts + + +def _representative_pts(frame_pts, start_pts, end_pts): + return _nearest_frame_pts( + frame_pts, _midpoint_pts(start_pts, end_pts), start_pts, end_pts + ) + + +def _representative_candidates( + frame_pts, + start_pts, + end_pts, + limit=_REPRESENTATIVE_CANDIDATE_LIMIT, +): + start = int(start_pts) + end = int(end_pts) + if end <= start: + return [] + span = end - start + candidates = [] + seen = set() + for numerator in (1, 2, 3): + target = Fraction(start, 1) + Fraction(span * numerator, 4) + pts = _nearest_frame_pts(frame_pts, target, start, end) + if pts is None or pts in seen: + continue + seen.add(pts) + candidates.append(pts) + if len(candidates) >= limit: + break + return candidates + + +def _representative_sort_key(pts, midpoint): + return (abs(Fraction(int(pts)) - midpoint), int(pts)) + + +def _prefer_candidate(candidate, current, threshold, midpoint): + if current is None: + return True + candidate_visible = candidate["meanIntensity"] >= threshold + current_visible = current["meanIntensity"] >= threshold + if candidate_visible != current_visible: + return candidate_visible + return _representative_sort_key( + candidate["pts"], midpoint + ) < _representative_sort_key(current["pts"], midpoint) + + +def _select_representative(samples, start_pts, end_pts, threshold): + if not samples: + raise ValueError("Cannot select a representative without sampled frames") + midpoint = _midpoint_pts(start_pts, end_pts) + chosen = None + for sample in samples: + candidate = { + "pts": int(sample["pts"]), + "meanIntensity": float(sample["meanIntensity"]), + } + if _prefer_candidate(candidate, chosen, threshold, midpoint): + chosen = candidate + return { + "pts": chosen["pts"], + "visibility": ( + "visible" + if chosen["meanIntensity"] >= threshold + else "low_visibility" + ), + } + + +def _shot_records( + frame_pts, + time_base, + cut_pts, + end_pts, + end_method, + representative_intensity_threshold=DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD, +): + if not frame_pts: + raise ValueError("Cannot build shots without decoded frames") + if end_pts <= frame_pts[-1]: + raise ValueError("Shot end must be after the last decoded frame") + + frame_set = set(frame_pts) + starts = [frame_pts[0]] + for pts in sorted({int(value) for value in cut_pts}): + if pts in frame_set and pts > starts[-1]: + starts.append(pts) + bounds = starts + [int(end_pts)] + time_base_text = _fraction_text(time_base) + + shots = [] + for index, (start_pts, stop_pts) in enumerate(zip(bounds, bounds[1:]), 1): + if stop_pts <= start_pts: + continue + candidates = _representative_candidates(frame_pts, start_pts, stop_pts) + if not candidates: + raise RuntimeError(f"Shot {index} contains no decoded frame") + midpoint = _midpoint_pts(start_pts, stop_pts) + representative_pts = _representative_pts(frame_pts, start_pts, stop_pts) + if representative_pts not in candidates: + representative_pts = min( + candidates, + key=lambda pts: _representative_sort_key(pts, midpoint), + ) + is_last = index == len(bounds) - 1 + shots.append( + { + "id": f"shot-{index:04d}", + "startSeconds": _round_seconds(_pts_seconds(start_pts, time_base)), + "endSeconds": _round_seconds(_pts_seconds(stop_pts, time_base)), + "startPts": int(start_pts), + "endPts": int(stop_pts), + "timeBase": time_base_text, + "representative": { + "path": f"frames/shot-{index:04d}.jpg", + "pts": int(representative_pts), + "timeBase": time_base_text, + "seconds": _round_seconds( + _pts_seconds(representative_pts, time_base) + ), + "selection": { + "method": "visible-near-midpoint", + "scope": "sampled_frames", + "intensityThreshold": float( + representative_intensity_threshold + ), + "sampledFrames": [ + { + "pts": int(pts), + "seconds": _round_seconds( + _pts_seconds(pts, time_base) + ), + } + for pts in candidates + ], + }, + }, + "endMethod": end_method if is_last else "next-cut", + "description": None, + } + ) + return shots + + +def _rate_fraction(value): + if value is None: + return None + if isinstance(value, Fraction): + return value if value > 0 else None + if isinstance(value, (int, float)): + if not math.isfinite(value) or value <= 0: + return None + return Fraction(value).limit_denominator(1001) + text = str(value).strip() + if not text or text.lower() in {"n/a", "unknown", "0/0"}: + return None + try: + if "/" in text: + numerator, denominator = text.split("/", 1) + result = Fraction(int(numerator), int(denominator)) + else: + number = float(text) + if not math.isfinite(number) or number <= 0: + return None + result = Fraction(number).limit_denominator(1001) + except (ValueError, ZeroDivisionError, OverflowError): + return None + return result if result > 0 else None + + +def _fraction_text(value): + if value is None: + return None + return f"{value.numerator}/{value.denominator}" + + +def _positive_float(value): + try: + number = float(value) + except (TypeError, ValueError): + return None + if not math.isfinite(number) or number <= 0: + return None + return number + + +def _round_seconds(value): + if value is None: + return None + return round(float(value), 6) diff --git a/pyproject.toml b/pyproject.toml index 992c4e7c0..8d04a6009 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,7 @@ dependencies = [ [project.optional-dependencies] test = ["pytest>=8,<10", "distlib>=0.4,<1", "import-linter>=2.1,<3"] +shot-analysis = ["av>=16,<17", "scenedetect-headless==0.7.1"] [project.scripts] opendirector = "opendirector.cli:main" diff --git a/scripts/analyze_reference_shots.py b/scripts/analyze_reference_shots.py new file mode 100644 index 000000000..d648991c2 --- /dev/null +++ b/scripts/analyze_reference_shots.py @@ -0,0 +1,72 @@ +"""Analyze a reference video into shots and representative JPEGs. + +Example: + python scripts/analyze_reference_shots.py input.mp4 --output /tmp/shots +""" + +import argparse +import json +from pathlib import Path +import sys + +root = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(root / "packages/core/src")) + +from opendirector.media.shot_detection import ( # noqa: E402 + DEFAULT_MAX_DURATION_SECONDS, + DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD, + inspect_video_shots, +) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path, help="Reference video to analyze") + parser.add_argument( + "--output", type=Path, required=True, help="Directory for analysis.json and frames/" + ) + parser.add_argument("--adaptive-threshold", type=float, default=3.0) + parser.add_argument("--min-scene-seconds", type=float, default=0.1) + parser.add_argument("--min-content-val", type=float, default=15.0) + parser.add_argument("--max-width", type=int, default=640) + parser.add_argument( + "--representative-intensity-threshold", + type=float, + default=DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD, + help="Heuristic mean RGB threshold (0-255) for sampled-frame visibility", + ) + parser.add_argument( + "--max-duration-seconds", + type=float, + default=DEFAULT_MAX_DURATION_SECONDS, + ) + arguments = parser.parse_args() + + result = inspect_video_shots( + arguments.input, + arguments.output, + adaptive_threshold=arguments.adaptive_threshold, + min_scene_seconds=arguments.min_scene_seconds, + min_content_val=arguments.min_content_val, + max_width=arguments.max_width, + representative_intensity_threshold=( + arguments.representative_intensity_threshold + ), + max_duration_seconds=arguments.max_duration_seconds, + ) + + analysis_path = arguments.output / "analysis.json" + analysis_path.write_text( + json.dumps(result, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + print( + f"{result['source']['filename']}: {len(result['shots'])} shot(s), " + f"{result['source']['decodedFrameCount']} frames, " + f"{result['timings']['detectionSeconds']:.3f}s detection" + ) + print(f"analysis: {analysis_path}") + + +if __name__ == "__main__": + main() diff --git a/scripts/describe_reference_shots.py b/scripts/describe_reference_shots.py new file mode 100644 index 000000000..0acdccd08 --- /dev/null +++ b/scripts/describe_reference_shots.py @@ -0,0 +1,180 @@ +"""Describe explicitly selected reference shots from an analysis.json sidecar. + +Example: + python scripts/describe_reference_shots.py \ + --analysis /tmp/shots/analysis.json \ + --repository /path/to/repository \ + --model-config-id 00000000-0000-0000-0000-000000000000 \ + --shot-id shot-0001 --shot-id shot-0002 \ + --output /tmp/shots/descriptions.json +""" + +import argparse +import asyncio +import json +from pathlib import Path +import sys +from uuid import UUID + +root = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(root / "packages/core/src")) + +from opendirector.application.shot_descriptions import ( # noqa: E402 + DEFAULT_MAX_TOKENS, + LANGUAGES, + SCHEMA_VERSION, + describe_shot_frame, + frame_reference, + validate_frame_description_config, +) +from opendirector.infrastructure.model_configs import ModelConfigs # noqa: E402 +from opendirector.integrations.reference_inputs import image_type # noqa: E402 + + +def _resolve_frame_path(base, relative): + base = Path(base).resolve() + candidate = Path(relative) + if candidate.is_absolute(): + raise ValueError("代表帧路径必须是 analysis 目录内的相对路径。") + try: + resolved = (base / candidate).resolve(strict=True) + except OSError: + raise ValueError(f"代表帧不存在:{relative}") from None + if resolved != base and base not in resolved.parents: + raise ValueError(f"代表帧路径越出 analysis 目录:{relative}") + if not resolved.is_file(): + raise ValueError(f"代表帧不是普通文件:{relative}") + return resolved + + +def _validate_output(analysis_path, output_path): + if analysis_path.resolve() == output_path.resolve(): + raise ValueError("输出文件不能与 analysis 文件相同。") + if output_path.exists() or output_path.is_symlink(): + raise ValueError(f"输出文件已存在,请显式选择新路径:{output_path}") + + +def _load_analysis(path): + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + raise ValueError(f"无法读取 analysis 文件:{path}") from None + source = value.get("source") if isinstance(value, dict) else None + source_sha = source.get("sha256") if isinstance(source, dict) else None + if not isinstance(source_sha, str) or not source_sha: + raise ValueError("analysis 文件缺少 source.sha256。") + if not isinstance(value.get("shots"), list): + raise ValueError("analysis 文件缺少 shots 列表。") + return value, source_sha + + +def _selected_ids(shot_ids): + ids = list(shot_ids) + if not ids: + raise ValueError("请明确选择至少一个镜头。") + if len(set(ids)) != len(ids): + raise ValueError("所选镜头 id 不能重复。") + return ids + + +def _selected_shots(analysis, shot_ids): + by_id = { + shot.get("id"): shot + for shot in analysis["shots"] + if isinstance(shot, dict) + } + shots = [] + for shot_id in _selected_ids(shot_ids): + shot = by_id.get(shot_id) + if shot is None: + raise ValueError(f"analysis 中不存在镜头:{shot_id}") + shots.append(shot) + return shots + + +def _write_output(output_path, source_sha, rows): + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps( + { + "schemaVersion": SCHEMA_VERSION, + "sourceSha256": source_sha, + "descriptions": rows, + }, + ensure_ascii=False, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + +async def _describe_all(config, entries, output_path, source_sha, max_tokens, language): + rows = [] + for shot, data in entries: + row = await describe_shot_frame( + config, shot, data, max_tokens=max_tokens, language=language + ) + rows.append(row) + _write_output(output_path, source_sha, rows) + print(f"{row['shotId']}: described in {row['requestSeconds']:.3f}s") + return rows + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--analysis", type=Path, required=True) + parser.add_argument("--repository", type=Path, required=True) + parser.add_argument("--model-config-id", required=True) + parser.add_argument("--shot-id", action="append", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--max-tokens", type=int, default=DEFAULT_MAX_TOKENS) + parser.add_argument("--language", choices=tuple(LANGUAGES), default="en-US") + arguments = parser.parse_args() + + if arguments.max_tokens < 1: + parser.error("--max-tokens 必须是正整数") + try: + config_id = str(UUID(arguments.model_config_id)) + except (AttributeError, TypeError, ValueError): + parser.error("--model-config-id 必须是 UUID") + + analysis_path = arguments.analysis.resolve() + output_path = arguments.output + _validate_output(analysis_path, output_path) + analysis, source_sha = _load_analysis(analysis_path) + shots = _selected_shots(analysis, arguments.shot_id) + + models_path = arguments.repository.resolve() / ".opendirector" / "models.json" + if not models_path.is_file(): + raise ValueError( + f"未找到已有模型配置:{models_path};请先在现有设置中配置对话模型。" + ) + config = ModelConfigs(arguments.repository).resolve(config_id, "agent") + validate_frame_description_config(config) + + analysis_dir = analysis_path.parent + entries = [] + for shot in shots: + frame = frame_reference(shot) + frame_path = _resolve_frame_path(analysis_dir, frame["path"]) + data = frame_path.read_bytes() + if image_type(data) != "image/jpeg": + raise ValueError(f"代表帧不是 JPEG:{frame['path']}") + entries.append((shot, data)) + + asyncio.run( + _describe_all( + config, + entries, + output_path, + source_sha, + arguments.max_tokens, + arguments.language, + ) + ) + print(f"descriptions: {output_path}") + + +if __name__ == "__main__": + main() diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index 373db6884..a913c404b 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -9,6 +9,7 @@ import type { EditorDocumentInput, EditorInputConnection, EditorInputConnectionInput, + EditorRef, GenerationSpec, GenerationSpecInput, ObjectVersion, @@ -457,6 +458,8 @@ export class CreationProjection { height: doc.data.height, }, }; + case "shot_breakdown": + return {}; case "media_edit": { // A changed source starts a fresh edit; keep the old document in history // rather than applying its mask to unrelated pixels of the same size. @@ -1128,11 +1131,11 @@ export class CreationProjection { private async editorInput( node: CanvasNode, - kind: EditorDocument["kind"], + kind: EditorRef["kind"], current?: EditorDocument, edges: CanvasDocument["edges"] = [], nodes: readonly CanvasNode[] = [], - ): Promise { + ): Promise> { // A link the domain already recorded is retained: the source may have moved // on since, and the snapshot deliberately keeps the original relation. const retained = new Map( @@ -1636,7 +1639,7 @@ export class CreationProjection { : undefined; const doc = await this.editorInput( node, - kind as EditorDocument["kind"], + kind as EditorRef["kind"], current, document.edges, [...document.nodes, ...(document.hiddenNodes ?? [])], @@ -1649,7 +1652,7 @@ export class CreationProjection { else { const previous = await this.editorInput( old ?? node, - kind as EditorDocument["kind"], + kind as EditorRef["kind"], current, this.baseline.edges, [...this.baseline.nodes, ...(this.baseline.hiddenNodes ?? [])], diff --git a/src/canvas/NodeSelectionToolbar.tsx b/src/canvas/NodeSelectionToolbar.tsx index 09b33f921..e2b4d13fd 100644 --- a/src/canvas/NodeSelectionToolbar.tsx +++ b/src/canvas/NodeSelectionToolbar.tsx @@ -39,6 +39,7 @@ export interface NodeSelectionToolbarProps { outputBusy?: boolean; onCaptureFrame?: (position: "first" | "last") => void; onGridSplit?: (rows: number, columns: number) => void; + onShotBreakdown?: () => void; onPreview?: () => void; onDownload?: () => void; onAssistant?: () => void; @@ -149,6 +150,7 @@ export function NodeSelectionToolbar({ outputBusy = false, onCaptureFrame, onGridSplit, + onShotBreakdown, onPreview, onDownload, onAssistant, @@ -453,6 +455,14 @@ export function NodeSelectionToolbar({ "subject", ); addEditor("video-trim", t("canvas.selection.trimVideo"), "trim", "trim"); + if (onShotBreakdown && node.data.backendAssetId) + editing.push({ + id: "shot-breakdown", + label: t("editors.shotBreakdown.open"), + icon: "clapperboard", + run: onShotBreakdown, + disabled: locked, + }); addMenu( "sound-separation", t("canvas.selection.audioSeparation"), diff --git a/src/canvas/ShotBreakdownEditor.tsx b/src/canvas/ShotBreakdownEditor.tsx new file mode 100644 index 000000000..bcfd37cf3 --- /dev/null +++ b/src/canvas/ShotBreakdownEditor.tsx @@ -0,0 +1,929 @@ +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, +} from "react"; + +import { errorMessage, json, request } from "../backend/api.ts"; +import { creationClient, objectVersion } from "../backend/creationClient.ts"; +import type { ModelConfig } from "../backend/rules.ts"; +import type { AssetRef, EditorDocument } from "../contracts/generated.ts"; +import { useT } from "../i18n/I18nProvider.tsx"; +import { CanvasIcon } from "./CanvasIcon"; +import { EditorModal } from "./EditorModal"; +import type { CanvasNode } from "./model"; +import "./shot-breakdown-editor.css"; + +type ShotBreakdown = Extract; +type FrameSuggestion = NonNullable< + ShotBreakdown["data"]["shots"][number]["frameSuggestion"] +>; + +interface DraftShot { + id: string; + measured: { + startPts: number; + endPts: number; + representativePts: number; + representative: AssetRef; + }; + frameSuggestion: FrameSuggestion | null; + edit: ShotBreakdown["data"]["shots"][number]["edit"]; +} + +interface DraftData { + source: AssetRef; + timeBase: string; + originPts: number; + durationPts: number; + shots: DraftShot[]; +} + +function validInterval( + { startPts, endPts }: DraftShot["edit"], + durationPts: number, +) { + return ( + Number.isInteger(startPts) && + Number.isInteger(endPts) && + startPts >= 0 && + endPts > startPts && + endPts <= durationPts + ); +} + +export function ShotBreakdownEditor({ + node, + projectId, + onClose, +}: { + node: CanvasNode; + projectId: string; + onClose: () => void; +}) { + const t = useT(); + const assetId = node.data.backendAssetId!; + const path = `/creation/projects/${projectId}/assets/${assetId}/shot-breakdown`; + const client = useMemo(() => creationClient(projectId), [projectId]); + const subscribe = useCallback( + (notify: () => void) => client.listen(notify), + [client], + ); + const readDocument = useCallback( + () => + client.snapshot?.editorDocuments.find( + (document): document is ShotBreakdown => + document.kind === "shot_breakdown" && + document.data.source.assetId === assetId, + ) ?? null, + [client, assetId], + ); + const savedDocument = useSyncExternalStore(subscribe, readDocument); + const [pending, setPending] = useState<{ + base: ShotBreakdown; + data: DraftData; + } | null>(null); + const document = pending?.base ?? savedDocument; + const draft = useMemo( + () => pending?.data ?? (savedDocument ? toDraft(savedDocument) : null), + [pending, savedDocument], + ); + const [busy, setBusy] = useState(false); + const [notice, setNotice] = useState(""); + const [error, setError] = useState(""); + const conflict = + pending && + (pending.base.id !== savedDocument?.id || + pending.base.revision !== savedDocument.revision); + const [models, setModels] = useState([]); + const [modelConfigId, setModelConfigId] = useState(""); + const [selectedShotId, setSelectedShotId] = useState(null); + const [videoSrc, setVideoSrc] = useState(""); + const [videoTime, setVideoTime] = useState(0); + const [playbackOrigin, setPlaybackOrigin] = useState(null); + const video = useRef(null); + const mounted = useRef(true); + + const attachVideo = useCallback((element: HTMLVideoElement | null) => { + video.current = element; + if (!element) return; + setVideoTime(0); + if (typeof element.requestVideoFrameCallback !== "function") { + setPlaybackOrigin(0); + return; + } + setPlaybackOrigin(null); + const callback = element.requestVideoFrameCallback((_, frame) => { + setPlaybackOrigin(frame.mediaTime); + }); + return () => { + element.cancelVideoFrameCallback(callback); + video.current = null; + }; + }, []); + + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + + useEffect(() => { + const controller = new AbortController(); + request("/model-configs", { signal: controller.signal }) + .then((value) => { + if (!controller.signal.aborted) setModels(value); + }) + .catch(() => { + if (!controller.signal.aborted) setModels([]); + }); + return () => controller.abort(); + }, []); + + const timeScale = useMemo( + () => (draft ? parseTimeBase(draft.timeBase) : null), + [draft], + ); + const agentModels = useMemo( + () => + models.filter( + (model) => + model.kind === "agent" && + (model.inputModalities ?? []).includes("image"), + ), + [models], + ); + + const sourceId = document?.data.source.assetId; + useEffect(() => { + if (!sourceId) { + setVideoSrc(""); + return; + } + let active = true; + client + .mediaUrl(sourceId) + .then((url) => { + if (active) setVideoSrc(url); + }) + .catch(() => { + if (active) setVideoSrc(""); + }); + return () => { + active = false; + }; + }, [client, sourceId]); + + const selectedIndex = draft + ? Math.max( + 0, + draft.shots.findIndex((shot) => shot.id === selectedShotId), + ) + : 0; + const selectedShot = draft?.shots[selectedIndex] ?? null; + const previousShot = draft?.shots[selectedIndex - 1]; + const joinsPrevious = selectedShot?.edit.joinPrevious === true; + const nextJoins = draft?.shots[selectedIndex + 1]?.edit.joinPrevious === true; + const canJoinPrevious = + draft != null && + selectedShot != null && + previousShot != null && + validInterval(previousShot.edit, draft.durationPts) && + validInterval(selectedShot.edit, draft.durationPts) && + previousShot.edit.endPts === selectedShot.edit.startPts; + let firstJoined = selectedIndex; + let lastJoined = selectedIndex; + while (draft?.shots[firstJoined]?.edit.joinPrevious) firstJoined--; + while (draft?.shots[lastJoined + 1]?.edit.joinPrevious) lastJoined++; + const canSeek = !!videoSrc && playbackOrigin !== null && timeScale !== null; + const canSeekDraft = + canSeek && selectedShot != null && draft != null && + validInterval(selectedShot.edit, draft.durationPts); + + const analyze = async () => { + setBusy(true); + setError(""); + setNotice(""); + try { + const value = await request( + path, + json("POST", modelConfigId ? { modelConfigId } : {}), + ); + await client.refresh(); + if (!mounted.current) return; + const total = value.data.shots.length; + const described = value.data.shots.filter((shot) => shot.frameSuggestion).length; + setNotice( + modelConfigId && described < total + ? t("editors.shotBreakdown.notice.partial", { described, total }) + : t("editors.shotBreakdown.notice.analyzed"), + ); + } catch (failure) { + if (mounted.current) + setError( + t("editors.shotBreakdown.error.analyze", { + reason: errorMessage(failure), + }), + ); + } finally { + if (mounted.current) setBusy(false); + } + }; + + const reload = async () => { + if (pending && !window.confirm(t("editors.shotBreakdown.discardReload"))) return; + setBusy(true); + setError(""); + try { + await client.refresh(); + if (!mounted.current) return; + setPending(null); + setNotice( + readDocument() + ? t("editors.shotBreakdown.notice.reloaded") + : t("editors.shotBreakdown.notice.empty"), + ); + } catch (failure) { + if (mounted.current) + setError( + t("editors.shotBreakdown.error.load", { + reason: errorMessage(failure), + }), + ); + } finally { + if (mounted.current) setBusy(false); + } + }; + + const editShot = (patch: (shot: DraftShot) => DraftShot) => { + if (!document || !draft || !selectedShot) return; + setPending((current) => { + const data = current?.data ?? draft; + return { + base: current?.base ?? document, + data: { + ...data, + shots: data.shots.map((shot) => + shot.id === selectedShot.id ? patch(shot) : shot, + ), + }, + }; + }); + setNotice(t("editors.shotBreakdown.notice.draft")); + setError(""); + }; + + const editRange = (value: string): number => + value.trim() === "" ? Number.NaN : Number(value); + + const seek = (pts: number) => { + const element = video.current; + const scale = timeScale; + if (!element || !scale || playbackOrigin === null || !Number.isFinite(pts)) + return; + const seconds = Math.max(0, playbackOrigin + pts * scale); + element.currentTime = Number.isFinite(element.duration) + ? Math.min(seconds, element.duration) + : seconds; + element.pause(); + }; + + const invalidShot = draft?.shots.findIndex( + (shot) => !validInterval(shot.edit, draft.durationPts), + ) ?? -1; + + const save = async () => { + if (!draft || !document || busy) return; + if (invalidShot !== -1) { + setError(t("editors.shotBreakdown.error.interval", { number: invalidShot + 1 })); + return; + } + setBusy(true); + setError(""); + setNotice(""); + try { + const revised: ShotBreakdown = { + ...document, + data: { + ...document.data, + ...draft, + shots: draft.shots.map((shot) => ({ + id: shot.id, + measured: shot.measured, + frameSuggestion: shot.frameSuggestion, + edit: shot.edit, + })), + }, + }; + await client.command( + "editor.save", + { document: revised }, + [objectVersion("editor_document", document)], + ); + if (!mounted.current) return; + setPending(null); + setNotice(t("editors.shotBreakdown.notice.saved")); + } catch (failure) { + if (!mounted.current) return; + setError( + t("editors.shotBreakdown.error.save", { + reason: errorMessage(failure), + }), + ); + } finally { + if (mounted.current) setBusy(false); + } + }; + + const close = () => { + if (busy) return; + if (pending && !window.confirm(t("editors.shotBreakdown.discardClose"))) return; + onClose(); + }; + + return ( + void save() : undefined} + applyLabel={t("editors.shotBreakdown.save")} + disabled={busy || !document} + error={error} + className="cw-shot-breakdown-dialog" + actions={ + document ? ( + + ) : undefined + } + > +
+ {!document || !draft ? ( +
+ +

{t("editors.shotBreakdown.empty.title")}

+

{t("editors.shotBreakdown.empty.body")}

+ +

+ {modelConfigId + ? t("editors.shotBreakdown.model.selectedHint") + : t("editors.shotBreakdown.model.defaultHint")} +

+ +
+ ) : ( + <> +
+ + {t("editors.shotBreakdown.badge.detected")} + + + {t("editors.shotBreakdown.summary.shots", { + count: draft.shots.length, + })} + + + {t("editors.shotBreakdown.summary.draftShots", { + count: draft.shots.filter((shot) => !shot.edit.joinPrevious).length, + })} + + + {t("editors.shotBreakdown.summary.duration")} ·{" "} + {formatPts(draft.durationPts)} ·{" "} + {formatSeconds(draft.durationPts, timeScale)} + + + {t("editors.shotBreakdown.summary.timeBase")} · {draft.timeBase} + +
+ {notice && ( +

+ {notice} +

+ )} + {conflict && ( +

+ {t("editors.shotBreakdown.conflict")} +

+ )} +
+
+ {videoSrc ? ( +
+
    + {draft.shots.map((shot, index) => ( +
  1. + +
  2. + ))} +
+
+ {selectedShot && draft && ( +
+
+

+ {t("editors.shotBreakdown.shotNumber", { + number: selectedIndex + 1, + })} +

+ {t("editors.shotBreakdown.detailHint")} +
+
+
+

+ + {t("editors.shotBreakdown.badge.detected")} + + {t("editors.shotBreakdown.measured.title")} +

+
+
+
{t("editors.shotBreakdown.measured.start")}
+
+ {formatSeconds( + selectedShot.measured.startPts, + timeScale, + )}{" "} + · PTS {formatPts(selectedShot.measured.startPts)} +
+
+
+
{t("editors.shotBreakdown.measured.end")}
+
+ {formatSeconds( + selectedShot.measured.endPts, + timeScale, + )}{" "} + · PTS {formatPts(selectedShot.measured.endPts)} +
+
+
+
+ {t("editors.shotBreakdown.measured.representative")} +
+
+ {formatSeconds( + selectedShot.measured.representativePts, + timeScale, + )}{" "} + · PTS{" "} + {formatPts(selectedShot.measured.representativePts)} +
+
+
+
+ + + +
+
+ {selectedShot.frameSuggestion ? ( +
+

+ + {t("editors.shotBreakdown.badge.model")} + + {t("editors.shotBreakdown.suggestion.title", { + model: selectedShot.frameSuggestion.modelId, + })} +

+

+ {t("editors.shotBreakdown.suggestion.note")} +

+
+
+
+ {t("editors.shotBreakdown.suggestion.subject")} +
+
{selectedShot.frameSuggestion.subject}
+
+
+
{t("editors.shotBreakdown.suggestion.scene")}
+
{selectedShot.frameSuggestion.scene}
+
+
+
+ {t("editors.shotBreakdown.suggestion.framing")} +
+
{selectedShot.frameSuggestion.framing}
+
+
+
+ ) : ( +
+

+ {t("editors.shotBreakdown.suggestion.titleEmpty")} +

+

+ {t("editors.shotBreakdown.suggestion.empty")} +

+
+ )} +
+

+ + {t("editors.shotBreakdown.badge.draft")} + + {t("editors.shotBreakdown.edit.title")} +

+ {firstJoined !== lastJoined && ( +

+ {t("editors.shotBreakdown.edit.joinedRange", { + first: firstJoined + 1, + last: lastJoined + 1, + start: formatSeconds(draft.shots[firstJoined]!.edit.startPts, timeScale), + end: formatSeconds(draft.shots[lastJoined]!.edit.endPts, timeScale), + })} +

+ )} + {previousShot && ( +
+ + {!joinsPrevious && !canJoinPrevious && ( + {t("editors.shotBreakdown.edit.joinHint")} + )} +
+ )} + + +