Skip to content
3 changes: 3 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@
'capability_connection_changed': 'The model connection changed during the capability check. Submit again.',
'tool_concept_translation': 'Use a short English subject description, or add a chat model in Models to translate it automatically.',
'tool_no_video_match': 'The requested subject was not found in the video. Try a different description.',
'tool_structure_reference_duration': 'Structure reference needs a clip no longer than 30 seconds. Trim the video first.',
'tool_structure_reference_frames': 'Structure reference processes at most 2048 frames at a time. Trim the video or lower its frame rate first.',
'tool_structure_reference_misaligned': 'Tracking or depth returned a different number of frames than the video, so the frames cannot be aligned. Try again.',
'voice_upload_type': 'Upload the voice recording using multipart/form-data.',
'voice_upload_form': 'Check the recording, form fields and text lengths, then try the upload again.',
'voice_model_unsupported': 'This checkpoint does not accept uploaded voices. Choose a Base model for voice cloning or a compatible built-in voice.',
Expand Down
16 changes: 16 additions & 0 deletions docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,22 @@ opendirector video compression-task TASK_ID
opendirector video compression-task TASK_ID --action publish
```

## Structure reference / 结构参考

**Structure reference** turns a clip of up to 30 seconds into a silent reference video on the source's timeline: the scene as gray relief and each tracked subject (people by default) in one solid color. It needs a video tracking model (such as SAM 3) and a model on the vLLM-Omni depth protocol. The task keeps the original; publishing a successful task places the structure reference on a new canvas node.

**结构参考**把不超过 30 秒的视频转换成与原片时间对齐的无声参考视频:场景为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色。需要接入视频跟踪模型(如 SAM 3)和 vLLM-Omni 深度接口上的模型。任务保留原片;任务成功后发布,会把结构参考放到新的画布节点上。

From the CLI, supply the source asset ID and a stable operation ID, which is also the task ID. `--resolution` is `480P` (default) or `720P`; `--subjects` names the subjects to color, separated by commas. Query the task, request cancellation with `--action cancel`, or publish a successful result with `--action publish`. Agents use the `video_structure_reference` and `structure_reference_task` tools with the same fields.

在 CLI 中传入源素材 ID 和固定的操作 ID,操作 ID 同时也是任务 ID。`--resolution` 为 `480P`(默认)或 `720P`;`--subjects` 填写要着色的对象,多个用逗号分隔。可以查询任务,用 `--action cancel` 请求取消,或用 `--action publish` 将成功结果发布到画布。Agent 使用字段相同的 `video_structure_reference` 和 `structure_reference_task` 工具。

```sh
opendirector video structure-reference --asset-id ASSET_ID --operation-id TASK_ID --resolution 720P --subjects "person, dog"
opendirector video structure-reference-task TASK_ID
opendirector video structure-reference-task TASK_ID --action publish
```

## Web Motion documents and rendering / 动效编辑文档与渲染

Motion nodes are saved as `editor` documents with `kind: "motion"` and managed via `editor create`, `editor save`, `canvas show`, and `canvas attach-editor`. Use the `motion` command group to inspect skills, run rendered frame diagnostics, export local MP4 files, or atomically publish the rendered MP4 as a video node linked to its source Motion node (`provenance.source: "rendered"` and `provenance.sourceItemId`) through the same server-side headless Chrome + FFmpeg pipeline used by Motion Studio:
Expand Down
2 changes: 2 additions & 0 deletions docs/guides/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ To make music from a reference recording, connect an audio node to a YuE2 music

To use **Depth motion capture** on a video, add a video model with the **vLLM-Omni depth** protocol, for example `depth-anything/Video-Depth-Anything-Small` served by `vllm serve <model> --omni`. The tool turns a clip of up to 30 seconds into a grayscale depth video at 480P or 720P, frame for frame, with near objects bright and far ones dark, ready to use as a motion and structure reference. The depth model does not generate video.

**Structure reference** turns a video of up to 30 seconds into a reference for regenerating it with the same motion, timing and camera: a video aligned frame by frame with the source, in which the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame rate and duration match the source, and so does the frame count of a constant-frame-rate clip; a variable-frame-rate clip is first resampled at its nominal rate, so the structure reference lines up with the source by time. The output is silent and capped at 8 Mbit/s. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The structure reference is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The structure reference is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. Agents and the CLI run the same task with the `video_structure_reference` and `structure_reference_task` tools or `opendirector video structure-reference` and `video structure-reference-task` (see the [CLI guide](cli.md)).

In **General** settings, you can switch themes and adjust the watermark removal option. Watermark settings affect only content generated afterward, and the actual effect depends on support from the model service.

## Make your first short film
Expand Down
2 changes: 2 additions & 0 deletions docs/guides/user-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ HTTP 400。

使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve <model> --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。

**结构参考** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的结构参考视频,用于以相同的动作、节奏和机位重新生成:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧率和时长与原片一致,恒定帧率的素材帧数也一致;可变帧率的素材会先按其标称帧率重采样,结构参考按时间与原片对齐。输出没有声音,码率上限为 8 Mbit/s。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。结构参考视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。结构参考由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的结构参考。Agent 和 CLI 通过 `video_structure_reference`、`structure_reference_task` 工具或 `opendirector video structure-reference`、`video structure-reference-task` 命令执行同一任务(见 [CLI 指南](cli.md))。

在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。

vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可使用 `opendirector video create --duration 6.583333` 并填写其余必需参数。先运行 `opendirector video create --help` 和 `opendirector model list`;`inputRules.fractionalDuration` 表示支持小数秒,各输出规格的时长列表定义允许范围。H3 可能按模型支持的帧数对齐,拼接分段前应核对结果的实际时长。
Expand Down
29 changes: 26 additions & 3 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,20 @@ def tools() -> list[dict]:
{'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'},
'action': {'type': 'string', 'enum': ['get', 'cancel', 'publish']}},
'required': ['taskId', 'action'], 'additionalProperties': False}))
result.append(tool_schema('video_structure_reference',
'Start a structure reference of a video (gray relief scene and one solid color per tracked subject, frame-aligned and silent) '
'without overwriting the source. Needs video tracking and depth models; clips up to 30 seconds. '
'Returns a durable task; inspect with structure_reference_task and publish explicitly after success.',
{'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'},
'sourceAssetId': {'type': 'string', 'format': 'uuid'},
'resolution': {'type': 'string', 'enum': ['480P', '720P']},
'subjects': {'type': 'string', 'description': 'Comma-separated subjects to color, e.g. "person, dog". People when omitted.'}},
'required': ['taskId', 'sourceAssetId', 'resolution'], 'additionalProperties': False}))
result.append(tool_schema('structure_reference_task',
'Inspect, request cancellation, or publish a successful structure reference as a new canvas node. Reuse the original task ID.',
{'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'},
'action': {'type': 'string', 'enum': ['get', 'cancel', 'publish']}},
'required': ['taskId', 'action'], 'additionalProperties': False}))
result.append(tool_schema('prompt_optimize',
'Rewrite an image or video draft with its saved references and the configured text model. '
'Return a draft only; does not edit the node or generate media. Use [[OD_REF_n]] and inlineReferences to retain inline reference positions.',
Expand Down Expand Up @@ -404,6 +418,10 @@ async def cli_prompt_rewrite(runtime, model, thinking, messages):
return await prompt_rewrite.rewrite(runtime, model, thinking, messages)


TASK_TOOLS = {'compression_task': ('video-compress', 'Select a video compression task.'),
'structure_reference_task': ('video-structure-reference', 'Select a structure reference task.')}


class AgentTools:
def __init__(self, projects, generation, configs, chat_provider=None):
self.prompt_optimization = PromptOptimization(projects, configs, chat_provider or ChatCompletions(),
Expand All @@ -418,17 +436,22 @@ def __init__(self, projects, generation, configs, chat_provider=None):
async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: str,
name: str, arguments: dict, roots: list[Path], config: dict | None, native_runtime: str | None = None,
execution_directory: Path | None = None, *, runtime_model=None, thinking='auto') -> JsonValue:
if name in {'video_compress', 'compression_task'}:
if name in {'video_compress', 'video_structure_reference', *TASK_TOOLS}:
service = self.generation.tool_tasks
task_id = str(UUID(arguments['taskId']))
pid = str(project_id)
if name == 'video_compress':
return await service.submit(pid, dict(id=task_id, tool='video-compress',
sourceAssetIds=[str(UUID(arguments['sourceAssetId']))],
parameters={'preset': arguments['preset']}), session)
if name == 'video_structure_reference':
return await service.submit(pid, dict(id=task_id, tool='video-structure-reference',
sourceAssetIds=[str(UUID(arguments['sourceAssetId']))],
parameters={'resolution': arguments['resolution'], 'prompt': arguments.get('subjects', '')}), session)
tool, refusal = TASK_TOOLS[name]
task = await asyncio.to_thread(service.get, pid, task_id)
if task['tool'] != 'video-compress':
raise ProjectError('Select a video compression task.', 422, code='invalid_input')
if task['tool'] != tool:
raise ProjectError(refusal, 422, code='invalid_input')
if arguments['action'] == 'cancel':
return await service.cancel(pid, task_id, session, wait=False)
if arguments['action'] == 'publish':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def publish_media(service, data, payload, *, staged=frozenset()):
expected, allowed = 'video', {'audio'}
if not actual.metadata.hasAudio:
raise ContractError('invalid_input', '来源视频没有可提取的音轨。', actual.id)
elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite'}:
elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite', 'video-structure-reference'}:
expected, allowed = 'video', {'video'}
elif tool in {'audio-trim', 'audio-separation'}:
expected, allowed = ('video' if tool == 'audio-separation' and actual.kind == 'video' else 'audio'), {'audio'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from opendirector.domain.image_presets import PRESETS, preset_instructions
from opendirector.application.tool_video_recipes import (
AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot,
subtitle_erasure, video_edit, video_matting, video_upscale,
structure_reference, subtitle_erasure, video_edit, video_matting, video_upscale,
)

# Editor previews and tool tasks import this helper from the catalog module.
Expand Down Expand Up @@ -111,4 +111,7 @@ def _preset_select():
note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'),
ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture,
note='逐帧估计景深,输出灰度深度视频(近处亮、远处暗),可作为视频生成的动作与结构参考;最长 30 秒。'),
ToolSpec('video-structure-reference', ('video',), _needs('video.matting', 'video.motion_capture'), structure_reference,
note='去除外观,只保留原片的动作、时序、机位和场景结构,作为以相同动作、节奏和机位重新生成视频的参考:'
'场景渲染为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色;输出与原片逐帧对齐的无声结构参考视频,最长 30 秒。'),
]}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from opendirector.domain.projects import ProjectError
from opendirector.media import processing as media
from opendirector.media.async_work import blocking
from opendirector.media.structure_reference import write_structure_reference


def _source_video(ctx: ToolContext) -> Source:
Expand Down Expand Up @@ -242,6 +243,50 @@ async def depth_capture(ctx: ToolContext):
data = await ctx.depth(clip.read_bytes())
return [Output('video', data, 'mp4', f'深度动作捕捉 {resolution}')]

STRUCTURE_REFERENCE_CRF = 20

STRUCTURE_REFERENCE_MAX_MEGABITS = 8

STRUCTURE_REFERENCE_FRAMES = f'结构参考单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。'

STRUCTURE_REFERENCE_MISALIGNED = '跟踪或深度结果的帧数与视频不一致,无法逐帧对齐,请重试。'

async def structure_reference(ctx: ToolContext):
source = _source_video(ctx)
resolution = ctx.choice('resolution', tuple(DEPTH_SHORT_EDGES), '480P')
with media.Workspace() as work:
raw = work.write('source', source.data)
info = await blocking(media.video_info, raw)
if not 0 < info['duration'] <= DEPTH_MAX_SECONDS + 0.05:
raise ProjectError(f'结构参考需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422, code='tool_structure_reference_duration')
if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里用容器时长 × 标称帧率卡 2048,但下游吃的是 conform 之后的帧。你贴的 VFR 样例正好说明这两个口径会分开:4.792 s × 24 约 115 帧,实际转出 121 帧。靠近上限时,估算过关不等于送模帧数过关。能否保留这里的快速预检,再在任何模型调用(含主体翻译)前按归一化后的实际帧数做硬校验,并补 2048/2049 的 VFR 边界用例?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5779b98. The estimate from duration and nominal rate stays as the cheap first check; after conforming, the recipe counts the clip's actual frames and refuses more than 2048 before any model call, the subject translation included. test_structure_reference_bounds_the_frames_it_sends_when_the_container_understates_its_length covers a variable-rate clip at 2048 frames (sent to tracking) and at 2049 (refused with no request, a chat model configured and a subject that would need translation). On real services, a 72 fps variable-rate pattern whose container states 27.79 s (2001 frames by the estimate) succeeds when it conforms to 2048 frames and is refused with tool_structure_reference_frames and no model call when it conforms to 2049 (receipts, file 13 in this comment).

raise ProjectError(STRUCTURE_REFERENCE_FRAMES, 422, code='tool_structure_reference_frames')
await ctx.progress('正在整理视频')
width, height = _depth_size(info['width'], info['height'], DEPTH_SHORT_EDGES[resolution])
clip = await blocking(media.constant_rate_picture, raw, work.path / 'clip.mp4', width=width, height=height, fps=info['fps'])
count = await blocking(media.frame_count, clip)
if count > DEPTH_MAX_FRAMES:
raise ProjectError(STRUCTURE_REFERENCE_FRAMES, 422, code='tool_structure_reference_frames')
named = await ctx.concepts(ctx.text('prompt'), ())
pairs = named or await ctx.concepts('', ('人物',))
label = '、'.join(label for _, label in pairs)
await ctx.progress(f'正在识别并跟踪「{label}」')
tracks = await ctx.track(clip.read_bytes(), tuple(concept for concept, _ in pairs))
if len(tracks.frames) != count:
raise ProjectError(STRUCTURE_REFERENCE_MISALIGNED, 502, code='tool_structure_reference_misaligned')
if named and not any(tracks.frames):
raise ToolInputError(f'视频中没有识别到「{label}」,请换一种描述后重试。', code='tool_no_video_match', label=label)
await ctx.progress('正在估计每一帧的深度')
depth = work.write('depth.mp4', await ctx.depth(clip.read_bytes()))
await ctx.progress('正在渲染结构参考')
frames = await blocking(media.frames_of, depth, work.path / 'depth-frames', gray=True)
if len(frames) != count:
raise ProjectError(STRUCTURE_REFERENCE_MISALIGNED, 502, code='tool_structure_reference_misaligned')
await blocking(write_structure_reference, frames, tracks, work.path / 'reference')
data = await blocking(media.encode_frames, str(work.path / 'reference' / '%05d.png'), info['fps'], work.path / 'reference.mp4',
crf=STRUCTURE_REFERENCE_CRF, max_megabits=STRUCTURE_REFERENCE_MAX_MEGABITS)
return [Output('video', data, 'mp4', f'结构参考 {resolution}')]

async def video_edit(ctx: ToolContext):
source = _source_video(ctx)
prompt = ctx.text('prompt')
Expand Down
Loading