diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index cf7a982f5..f04ee71e2 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,6 +16,12 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + 'keyframe_unsupported': 'This model or mode does not support keyframes. Clear the keyframe times or choose another model.', + 'keyframe_mode': 'Keyframes work in material-reference mode only, not with first/last frames, continuation or structure control.', + 'keyframe_kind': 'A keyframe must be an image.', + 'keyframe_count': 'There are more keyframes than this model accepts.', + 'keyframe_needs_reference': 'Keyframes also need at least one ordinary reference image or video.', + 'keyframe_time': 'Each keyframe needs its own time, earlier than the end of the video and at least 1/24 second from the others.', 'higgsfield_model': 'Choose MAGI-2 with the official Higgsfield Open API address.', 'higgsfield_key': 'Enter your Higgsfield Open KEY_ID:KEY_SECRET.', 'higgsfield_output': 'MAGI-2 supports 1080p and whole-second durations from 4 to 30 seconds.', diff --git a/docs/README.md b/docs/README.md index dff1456cc..1568878f5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ This directory is the entry point for the repository's shared documentation. The | [UI performance design](development/ui-performance.md) | Interaction design principles, latency budgets, and measurement | A UI performance principle, target, or measurement method changes | | [macOS installation validation](development/macos-install-validation.md) | Installation and usage scenarios verified on Apple Silicon | The corresponding acceptance checks are repeated | | [Bilingual interface](development/i18n.md) | Language selection, message organization, and checks | Language policy, message structure, or checks change | +| [H3 conditioning features](development/h3-conditioning-features.md) (中文) | Structure control, latent continuation, masked editing and keyframes for self-hosted H3 models, with result examples | The H3 request shapes or the vLLM-Omni capabilities they rely on change | | [Python installation and packaging](development/packaging.md) | Installation, platform wheel builds, and isolated verification | Packaging, resource paths, or build process changes | | [Business CLI](guides/cli.md) | Querying, editing, and generating through a terminal or Agent Shell | Commands, authorization, or receipt semantics change | | [DeepSeek Harness plugin](../plugins/deepseek-harness/README.md) | Installing the DSH bundle and editing an OpenDirector project from DSH | Plugin setup, tools, or creation workflows change | diff --git a/docs/development/assets/h3-conditioning/control-person-depth.mp4 b/docs/development/assets/h3-conditioning/control-person-depth.mp4 new file mode 100644 index 000000000..2df3e614c Binary files /dev/null and b/docs/development/assets/h3-conditioning/control-person-depth.mp4 differ diff --git a/docs/development/assets/h3-conditioning/keyframe-a.jpg b/docs/development/assets/h3-conditioning/keyframe-a.jpg new file mode 100644 index 000000000..2d8ae9397 Binary files /dev/null and b/docs/development/assets/h3-conditioning/keyframe-a.jpg differ diff --git a/docs/development/assets/h3-conditioning/keyframe-b.jpg b/docs/development/assets/h3-conditioning/keyframe-b.jpg new file mode 100644 index 000000000..84b2a5979 Binary files /dev/null and b/docs/development/assets/h3-conditioning/keyframe-b.jpg differ diff --git a/docs/development/assets/h3-conditioning/reference-picture.jpg b/docs/development/assets/h3-conditioning/reference-picture.jpg new file mode 100644 index 000000000..4183d320b Binary files /dev/null and b/docs/development/assets/h3-conditioning/reference-picture.jpg differ diff --git a/docs/development/assets/h3-conditioning/result-continuation.mp4 b/docs/development/assets/h3-conditioning/result-continuation.mp4 new file mode 100644 index 000000000..0e32408e3 Binary files /dev/null and b/docs/development/assets/h3-conditioning/result-continuation.mp4 differ diff --git a/docs/development/assets/h3-conditioning/result-keyframes.mp4 b/docs/development/assets/h3-conditioning/result-keyframes.mp4 new file mode 100644 index 000000000..3a0135fec Binary files /dev/null and b/docs/development/assets/h3-conditioning/result-keyframes.mp4 differ diff --git a/docs/development/assets/h3-conditioning/result-structure-control.mp4 b/docs/development/assets/h3-conditioning/result-structure-control.mp4 new file mode 100644 index 000000000..28ea2d071 Binary files /dev/null and b/docs/development/assets/h3-conditioning/result-structure-control.mp4 differ diff --git a/docs/development/assets/h3-conditioning/result-video-edit.mp4 b/docs/development/assets/h3-conditioning/result-video-edit.mp4 new file mode 100644 index 000000000..fa3aa8b67 Binary files /dev/null and b/docs/development/assets/h3-conditioning/result-video-edit.mp4 differ diff --git a/docs/development/assets/h3-conditioning/source-dance.mp4 b/docs/development/assets/h3-conditioning/source-dance.mp4 new file mode 100644 index 000000000..5a23295ab Binary files /dev/null and b/docs/development/assets/h3-conditioning/source-dance.mp4 differ diff --git a/docs/development/h3-conditioning-features.md b/docs/development/h3-conditioning-features.md new file mode 100644 index 000000000..c3c88d64b --- /dev/null +++ b/docs/development/h3-conditioning-features.md @@ -0,0 +1,182 @@ +# H3 系列模型的条件生成能力:接入方案 + +本文说明如何让 OpenDirector 对所有自部署的 MiniMax-H3 衍生模型开放四项条件生成能力:结构控制(含姿态)、潜空间接续、局部重绘、指定时间点的关键帧。范围限于 `vllm_omni` 协议的视频模型。 + +## 1. 背景 + +vLLM-Omni 已经让每一种 H3 权重都能使用这四项能力(vllm-project/vllm-omni#11078):原版 H3、FastH3 Omni,以及 LightX2V Turbo、Pika Flex Turbo、alibaba-pai Acc 这三类蒸馏适配器。OpenDirector 仍按最初接入时的划分,把能力绑定在两个互不重叠的档案上: + +| 档案(`inputRules.profile`) | 适配器 | 视频模式 | 局部重绘工具 | +| --- | --- | --- | --- | +| `vllm-omni-h3` | `minimax_h3` | 首帧、素材参考、接续 | 可用 | +| `fasth3-omni` | `fasth3` / `fasth3_dual` | 素材参考、结构控制(`fasth3_dual` 另有首尾帧) | 不可用 | + +结果是:用 `fasth3` 请求格式的模型(FastH3 Omni、Pika H3 等 8 步蒸馏模型)用不了接续和局部重绘;用 `minimax_h3` 的原版 H3 用不了结构控制;关键帧在两边都只有「首帧 / 尾帧」两个固定位置。 + +## 2. 实测依据 + +2026-11-27 在 4×B300 上用「原版 H3 Ref2VA + Pika Flex Turbo 8 步 LoRA + Fun ControlNet Union」实测,832×480、124 帧,每项一个提示词、一个种子。 + +- 同一个服务(张量并行 4,启动时带 `--controlnet-model-path`)在不同请求里分别完成了:姿态控制、深度控制、潜空间遮罩重绘、时间线关键帧、`continue_from` 接续。 +- 结构控制与另外三项不能出现在同一个请求里,服务端返回 400:控制 + 关键帧、控制 + 遮罩重绘、控制 + `continue_from`。 +- 按 vLLM-Omni 文档,控制分支只支持张量并行,不支持 Ulysses 序列并行(后者未实测)。张量并行 4 与此前的 Ulysses 4 在这组请求上速度相同,约 3 秒一段。 +- 服务端不做预处理:`control_type=pose` 只读取上传的骨架画面,姿态、边缘、深度图都要由客户端准备。 + +## 3. 设计原则 + +**把「权重能做什么」和「请求怎么采样」分开。** 目前 `videoAdapter` 同时决定了两件事。四项能力属于 H3 这一族,与采样方式无关;采样约定才因权重而异。 + +- **能力**由 H3 族和服务的分区决定,写进输入规则,前端从 `inputRules` 读取,不再按适配器名判断。 +- **采样约定**由适配器决定:步数、引导强度、流偏移、采样器、是否需要 LoRA。 + +分区限制是真实的,需要在规则里表达: + +| 服务分区 | 文生 / 首帧 | 素材参考 | 结构控制 | 接续 | 局部重绘 | 关键帧 | +| --- | --- | --- | --- | --- | --- | --- | +| FL2VA(`--task-type fl2va`) | 是 | 否 | 是(无参考) | 是 | 是 | 是 | +| Ref2VA(`--task-type ref2va`,含 FastH3 Omni) | 否 | 是 | 是(带参考) | 是,衔接较松 | 是,需一张参考图 | 是 | +| 合并服务(两个 DiT) | 是 | 是 | 否 | 是 | 是 | 是 | + +## 4. 分项方案 + +改动量参照结构控制最初接入的那次提交(`51dedd70`,52 个文件、约 840 行,其中包含两个工具)。 + +### 4.1 潜空间接续(改动最小) + +界面上已有「接续」模式和「延长」按钮,`useWorkspaceEditor.ts` 在模型支持接续时会自动把「延长」升级为接续。缺的只是 `fasth3-omni` 档案不声明这个模式,以及它的请求路径不发 `continue_from`。 + +1. `domain/input_rules.py`:给 `fasth3-omni` 的 `videoModes` 加上 `continuation`。 +2. `integrations/fasth3.py` 的 `generation_fields`:接续时写入 `extra['continue_from']`。 +3. `integrations/providers.py`:接续模式下不上传源视频。来源解析沿用 `reference_inputs.continuation_source`。 +4. `domain/creation/generation.py`、`model_availability.py`、`rule_facts.py` 的用例向量:把 `fasth3-omni` 纳入接续的校验与可用性判断。 + +来源必须是同一服务生成且缓存还在的任务,上传的视频不能接续。对上传的视频,「延长」继续走素材参考模式并截取结尾时间窗。Ref2VA 权重对潜变量尾部跟得较松,接缝可能可见,应在模式说明里写明。 + +### 4.2 局部重绘 + +界面(`VideoActionEditor`)、三个工具和后端流程都已存在,只是 `adapter_for` 只在 `vllm-omni-h3` 档案下返回提供 `video.edit` 的适配器。 + +1. `integrations/model_adapters.py`:`adapter_for` 对 `fasth3-omni` 也返回一个编辑适配器。 +2. 该适配器按 Ref2VA 的约定发请求:`task=ref2va`、固定步数与引导强度,并附一张参考图(取源片段的第一帧)。现有的 `VllmOmniVideo.edit_video` 发的是 `task=t2va`,在只有 Ref2VA 的服务上不可用。 +3. `domain/capability_contract.py`:`video_to_video` 档案的必需输入增加参考图的情况。 + +**参考图决定片段的开头。** Ref2VA 模型会让片段开头贴近参考图:重绘区域在开头显示的是参考图在该处的内容,提示词描述的画面要过一段时间才出现。以源片段首帧作参考图时,成片第 0 帧的重绘区域与原片相同(固定种子 9 次中 9 次),修改最早在第 32 帧前后出现,慢的要到片尾。把参考图里的重绘区域涂灰、裁掉,或改写提示词,都不能消除这一点:结果随种子而变,涂灰时开头可能出现灰块,裁剪时可能把参考图里的人物再画一遍。服务端不接受不带参考图的请求。 + +因此框选重绘跑两遍:第一遍以源片段首帧为参考图,到片尾时已是修改后的画面;第二遍以第一遍结果中修改覆盖的最后一帧为参考图,修改从第 0 帧起就在。两遍的请求除参考图外完全相同,耗时约为一遍的两倍。固定种子实测:同一提示词下 6 次中 5 次从第 0 帧起就是修改后的画面,另 1 次在前约半秒内淡入。整帧的时间段重绘(局部重拍)仍只跑一遍:片段开头是保留的画面,首帧正是要延续的样子;时间段从片头开始时,改取时间段结束后的第一帧。后一种情况固定种子各测 3 次:以首帧为参考图时,要求的修改 2 次完全没有出现、1 次只短暂出现;改取时间段之后的第一帧,3 次都在整个时间段内出现。 + +### 4.3 结构控制的类型 + +现在 `fasth3.control_parameters` 把类型写死为 `depth`,界面没有选择。 + +1. `VideoParameters` 增加 `controlType`(`depth`、`pose`、`canny`、`hed`、`mlsd`)和 `controlScale`,重新生成契约。 +2. `NodeComposer.tsx` 在结构控制模式下增加类型下拉和强度输入,补中英文文案。 +3. 给原版 H3(`vllm-omni-h3`)也开放 `control` 模式:FL2VA 服务上是无参考的 T2VA 请求。合并服务不提供。 +4. 预处理工具:已有「深度动捕」;新增「姿态提取」和「边缘提取」,产出可直接连接为控制视频的素材。边缘可用本地 FFmpeg 完成;姿态需要一个检测模型,可以做成本地工具进程,也可以接一个新的模型协议。 + +### 4.4 指定时间点的关键帧(改动最大) + +现有的首尾帧只存两个节点 ID,引用上没有时间字段,`frame_indices` 只会是 0 或 -1。 + +1. 契约:在引用上增加可选的 `frameTimeMs`(或在 `VideoParameters` 上增加关键帧列表),角色增加 `keyframe`,重新生成契约。 +2. 画布:`NodeComposer.tsx` 的帧槽位从固定两格扩展为列表,每一项选一张已连接的图片并填写时间点;`creationProjection.ts` 负责双向映射。 +3. 后端:`creation_generation.task()` 把时间随 `referenceRoles` 传下去;`reference_inputs.py` 换算成帧号;请求发送 `timeline_guides` 清单、`guide_files` 上传和 `quality=lossless`。 +4. 校验:最多 8 项;时间点落在输出时长内;与结构控制、接续、局部重绘互斥。 + +首帧和尾帧可以统一成时间为 0 和结尾的关键帧,这样 Ref2VA 权重也能有首尾帧,不必依赖 `fasth3_dual` 的第二个 DiT。 + +### 4.5 采样约定与 LoRA + +Pika、LightX2V Turbo、PAI Acc 都要求每个请求带 `lora` 字段,并使用各自固定的步数和流偏移。OpenDirector 现在不发 `lora`,部署时只能在中间加一层转发来补。 + +- 在模型配置上增加可选的采样约定:`steps`、`guidanceScale`、`flowShift`、`lora`(名称、服务端路径、强度)。`fasth3` 这条请求路径读取它们,而不是写死 8 步。 +- 更好的来源是服务自己声明。OpenDirector 已经会查询 `/v1/omni/capabilities`,当前 vLLM-Omni 对它返回 404。等服务端提供该接口后,能力、分区和采样约定都应从那里读取,手工配置只作兜底。 + +## 5. 互斥规则 + +前端在 `rules.ts` 的 `backendBlocker`、后端在 `validate_generation` 中各校验一次: + +- 结构控制不与关键帧、接续、局部重绘同时使用。 +- 关键帧不与接续、局部重绘同时使用。 +- 结构控制模式下输出时长跟随控制视频,现有规则不变。 + +## 6. 实现情况 + +已实现: + +- **潜空间接续(4.1)**:`fasth3-omni` 档案声明 `continuation`;请求发送 `continue_from` 并沿用来源画幅,不上传源视频;服务端已无缓存时给出专门的说明。 +- **局部重绘(4.2)**:`FastH3VideoEdit` 适配器为 `fasth3-omni` 提供 `video.edit`,按 Ref2VA 发请求。框选重绘跑两遍,第二遍以第一遍结果的最后一帧作参考图,使修改从片头就出现。 +- **指定帧(4.4)**:引用新增角色 `keyframe` 和字段 `frameTimeMs`,输入规则新增 `maxKeyframes`(两个 H3 档案均为 8);画布设置为 `pinnedFrames`;两条 H3 请求路径都发送 `timeline_guides`。目前只在素材参考模式下提供。 + +未实现: + +- **采样约定与 LoRA(4.5)**:OpenDirector 的请求仍固定 8 步、不带 `lora`;现在由随应用启动的视频转发层按模型名补上步数、流偏移和 `lora`(见[视频转发层指南](../guides/video-gateway.zh-CN.md))。模型配置里直接填写采样约定仍未实现。 +- **结构控制的类型(4.3)**:仍固定为深度。用现有的「视频抠像」「深度动捕」「蒙版合成」可以做出只有人物的深度视频,实测比姿态骨架更贴合动作,所以姿态的优先级可以降低。 +- **原版 H3 的结构控制**、**首帧模式下的指定帧**、**用关键帧统一首尾帧**。 +- 复制节点时 `pinnedFrames` 会改指向副本里的图片,图片不在副本里的时间被丢弃;删除或断开图片时同样丢弃。导入画布归档时是否保留未验证;重新从工程加载时按后端引用恢复。 +- 局部重绘工具只支持框选区域和时间段,不支持任意形状的遮罩。 + + +## 7. 界面 + +以下截图来自自部署的「原版 MiniMax-H3 Ref2VA + Pika Flex Turbo 8 步 LoRA」服务,请求格式为 FastH3-Omni,素材见第 8 节。 + +指定帧:素材参考模式下,每张已连接的图片对应一个时间框(中文 / English)。 + +![指定帧(中文)](images/h3-conditioning/keyframes-zh.png) + +![Keyframes (English)](images/h3-conditioning/keyframes-en.png) + +潜空间接续:对该模型生成的视频选择「视频延长」后,模式自动为「接续」。 + +![Continue mode](images/h3-conditioning/continuation-en.png) + +局部重绘:「视频编辑」在 FastH3-Omni 请求格式的模型上可用。 + +![视频编辑](images/h3-conditioning/video-edit-zh.png) + +## 8. 敦煌素材实测 + +同一组素材在 OpenDirector 里走完四项能力,服务同第 7 节。每项只跑了一个种子,没有挑选:能说明功能通不通,不能说明质量高低。 + +素材与结果都在 [`assets/h3-conditioning/`](assets/h3-conditioning/),视频为便于入库压缩到 540 像素宽: + +| 文件 | 内容 | +| --- | --- | +| [`source-dance.mp4`](assets/h3-conditioning/source-dance.mp4) | 原始舞蹈视频,25.5 秒,提供动作。来源:哔哩哔哩 BV1yFyWziEGF,由原作者上传,仅作测试输入 | +| [`reference-picture.jpg`](assets/h3-conditioning/reference-picture.jpg) | 敦煌飞天造型图,提供服装和风格,由测试者提供 | +| [`control-person-depth.mp4`](assets/h3-conditioning/control-person-depth.mp4) | 人物深度控制视频:视频分割得到的人物遮罩与深度图相乘,凳子和房间不在其中 | +| [`result-structure-control.mp4`](assets/h3-conditioning/result-structure-control.mp4) | 结构控制:控制视频加造型图,768×1344、600 帧,音轨换成了原视频的音乐 | +| [`result-continuation.mp4`](assets/h3-conditioning/result-continuation.mp4) | 潜空间接续:接在上一段成片之后,119 帧 | +| [`result-video-edit.mp4`](assets/h3-conditioning/result-video-edit.mp4) | 局部重绘:对接续结果用「视频编辑」框选画面上方 37%,重画成夜空 | +| [`keyframe-a.jpg`](assets/h3-conditioning/keyframe-a.jpg)、[`keyframe-b.jpg`](assets/h3-conditioning/keyframe-b.jpg) | 两张指定帧图片,取自结构控制成片 | +| [`result-keyframes.mp4`](assets/h3-conditioning/result-keyframes.mp4) | 指定帧:两张图片分别钉在 1.25 秒和 4.583 秒,480×832、124 帧 | + +结构控制:原始视频、人物深度控制视频、成片,同一时间段(第 8–14 秒)。 + +![结构控制](images/h3-conditioning/dunhuang-structure-control.gif) + +潜空间接续:前 2 秒是上一段成片的结尾,之后是接续出的片段。 + +![潜空间接续](images/h3-conditioning/dunhuang-continuation.gif) + +局部重绘:左为重绘前(接续片段),右为重绘后。 + +![局部重绘](images/h3-conditioning/dunhuang-video-edit.gif) + +指定帧:左为钉在 1.25 秒的图片,右为钉在 4.583 秒的图片,中间是成片。 + +![指定帧](images/h3-conditioning/dunhuang-keyframes.gif) + +动图为 8 帧/秒的缩小版,完整画质见上表中的视频文件。 + +| 能力 | 入口 | 测量 | 耗时 | +| --- | --- | --- | ---: | +| 结构控制 | 视频节点的「结构控制」模式 | 另一版提示词下,与原动作的平均关键点距离为画面对角线的 0.026;成片未单独重测 | 126 秒 | +| 潜空间接续 | 视频节点的「接续」模式 | 接缝两帧 SSIM 0.878,片内相邻帧 0.926 | 20 秒 | +| 局部重绘 | 「视频编辑」工具 | 框外 PSNR 39.2 dB,框内 17.5 dB | 50 秒(两遍) | +| 指定帧 | 素材参考模式下给图片填时间 | 两帧与指定图 SSIM 0.82 和 0.80(输出 480×832,比较时放大到 768×1344) | 11 秒 | + +- 结构控制的入口原本就有,另外三项是这次为 FastH3-Omni 请求格式新增的。 +- 原视频里舞者坐在凳子上。提示词把人物写成悬浮在空中的飞天、脚下是空的石地;只写「没有凳子」时,模型会因为坐姿再画一个。 +- 局部重绘最初只跑一遍,月亮和夜空到片段后半段才出现;改为两遍后从第 0 帧起就在(见 4.2),表中是两遍的结果。 +- 结构控制的输出长度取不超过控制视频的最大 `17n+5` 帧,可能比控制视频短不到 0.7 秒。 diff --git a/docs/development/images/h3-conditioning/continuation-en.png b/docs/development/images/h3-conditioning/continuation-en.png new file mode 100644 index 000000000..b3cd11505 Binary files /dev/null and b/docs/development/images/h3-conditioning/continuation-en.png differ diff --git a/docs/development/images/h3-conditioning/dunhuang-continuation.gif b/docs/development/images/h3-conditioning/dunhuang-continuation.gif new file mode 100644 index 000000000..0bf30f923 Binary files /dev/null and b/docs/development/images/h3-conditioning/dunhuang-continuation.gif differ diff --git a/docs/development/images/h3-conditioning/dunhuang-keyframes.gif b/docs/development/images/h3-conditioning/dunhuang-keyframes.gif new file mode 100644 index 000000000..d4b8703ef Binary files /dev/null and b/docs/development/images/h3-conditioning/dunhuang-keyframes.gif differ diff --git a/docs/development/images/h3-conditioning/dunhuang-structure-control.gif b/docs/development/images/h3-conditioning/dunhuang-structure-control.gif new file mode 100644 index 000000000..cb70f6f76 Binary files /dev/null and b/docs/development/images/h3-conditioning/dunhuang-structure-control.gif differ diff --git a/docs/development/images/h3-conditioning/dunhuang-video-edit.gif b/docs/development/images/h3-conditioning/dunhuang-video-edit.gif new file mode 100644 index 000000000..52c1bb610 Binary files /dev/null and b/docs/development/images/h3-conditioning/dunhuang-video-edit.gif differ diff --git a/docs/development/images/h3-conditioning/keyframes-en.png b/docs/development/images/h3-conditioning/keyframes-en.png new file mode 100644 index 000000000..afb77c095 Binary files /dev/null and b/docs/development/images/h3-conditioning/keyframes-en.png differ diff --git a/docs/development/images/h3-conditioning/keyframes-zh.png b/docs/development/images/h3-conditioning/keyframes-zh.png new file mode 100644 index 000000000..e363322e4 Binary files /dev/null and b/docs/development/images/h3-conditioning/keyframes-zh.png differ diff --git a/docs/development/images/h3-conditioning/video-edit-zh.png b/docs/development/images/h3-conditioning/video-edit-zh.png new file mode 100644 index 000000000..7f3ebf9f2 Binary files /dev/null and b/docs/development/images/h3-conditioning/video-edit-zh.png differ diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 5e23d068d..213876408 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -47,6 +47,17 @@ example vLLM's 4096 default) rejects every request with HTTP 400. For vLLM-Omni video connections, enter fractional seconds directly, for example `6.583333`. The CLI accepts `opendirector video create --duration 6.583333` together with the other required options. Read `opendirector video create --help` and `opendirector model list` first; `inputRules.fractionalDuration` identifies support, and each output's duration list defines the allowed range. H3 can align output to its supported frame count, so inspect the actual result duration before assembling segments. +A vLLM-Omni material-reference model (the FastH3-Omni request shape, which Pika H3 adapters also use) reads at most 15 seconds of reference video in total. A longer video is accepted and sent as its final part: one video contributes its last 15 seconds, and when several videos together exceed the limit, the short ones stay whole while the longest are cut to an equal length, each keeping its end. **Extend** therefore continues from the end of a long clip. The project keeps the original video; only the uploaded reference is cut, with its sound. Trim the clip yourself first when you need a different part. Other providers still refuse reference videos beyond their own limit. + +Self-hosted H3 models add four ways to condition a video. They work on native MiniMax-H3 and on models using the FastH3-Omni request shape alike, except where noted: + +- **Continue**: generate a video with the model, choose **Extend** on it, and the next clip continues from where it ended, picture and sound. This only continues clips this same service generated and still holds; for an uploaded video, **Extend** uses the video as a reference instead. +- **Keyframes**: in material-reference mode, each connected image shows a time box above the prompt. Give an image a time and the video shows that picture at that moment; leave it empty and the image stays an ordinary reference. Up to eight keyframes, each earlier than the end of the video and at least 1/24 second from the others (a keyframe is pinned to one frame), and at least one image or video must stay unpinned. Copying the node together with its pictures keeps the times. The CLI takes `opendirector video create --keyframe ITEM_UUID@SECONDS`. +- **Redraw part of a video**: **Partial reshoot**, **Video edit** and **Subtitle erasure** redraw a time span or a boxed region and keep the rest of the clip. On a model that uses the FastH3-Omni request format, a boxed redraw is generated twice so that the change is there from the first frame, which takes about twice as long. +- **Structure control**: connect a depth video and choose structure control, as before. This needs a service started with the ControlNet weights and is available on the FastH3-Omni request shape. + +Structure control, continuation and keyframes cannot be combined in one generation. + To use few-step H3 adapters such as Pika Flex Turbo, which need a LoRA and their own step count on every request, or to offer several such variants from one vLLM-Omni server, see the [video gateway](video-gateway.md) that starts with OpenDirector. For detailed video settings, see [Video model capability configuration](video-model-capabilities.md). When no explicit output specification is provided, use **Auto** or **Service default duration**. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 4a582659d..383b44951 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -59,6 +59,17 @@ HTTP 400。 vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可使用 `opendirector video create --duration 6.583333` 并填写其余必需参数。先运行 `opendirector video create --help` 和 `opendirector model list`;`inputRules.fractionalDuration` 表示支持小数秒,各输出规格的时长列表定义允许范围。H3 可能按模型支持的帧数对齐,拼接分段前应核对结果的实际时长。 +vLLM-Omni 的素材参考模型(FastH3-Omni 请求格式,Pika H3 适配也使用它)读取的参考视频总时长最多 15 秒。超出的视频不会被拒绝,而是只发送结尾部分:单个视频取最后 15 秒;多个视频合计超限时,较短的保持完整,较长的截到相同长度,各自保留结尾。因此对长视频使用「延长」会从它的结尾接续。工程中保留原视频,只有上传的参考被截取,声音一并保留。需要其他片段时,请先自行裁剪。其他服务商仍按各自上限拒绝过长的参考视频。 + +自部署的 H3 模型提供四种条件生成方式。除另有说明外,原版 MiniMax-H3 和使用 FastH3-Omni 请求格式的模型都可用: + +- **接续**:用模型生成一段视频后,对它使用「延长」,下一段会从它结束的地方接着生成,画面和声音都连续。只能接续同一个服务生成、且服务仍保留着的片段;对上传的视频,「延长」改为把它当作参考。 +- **指定帧**:在全能参考模式下,每张已连接的图片在提示词上方都有一个时间框。给图片填一个时间,生成的视频会在那一刻出现这个画面;留空则仍是普通参考。最多 8 个指定帧,时间须早于视频结束、彼此至少相隔 1/24 秒(每个指定帧钉在一帧上),并且至少留一张图片或一段视频不指定时间。连同图片一起复制节点时会保留这些时间。命令行使用 `opendirector video create --keyframe ITEM_UUID@SECONDS`。 +- **重画视频的一部分**:「局部重拍」「视频编辑」「字幕擦除」会重画某个时间段或框选区域,其余部分保持原样。使用 FastH3-Omni 请求格式的模型上,框选重绘会生成两遍,使修改从第一帧起就出现,耗时约为一遍的两倍。 +- **结构控制**:与此前相同,连接一段深度视频并选择结构控制。需要服务启动时加载 ControlNet 权重,适用于 FastH3-Omni 请求格式。 + +结构控制、接续和指定帧不能在同一次生成中同时使用。 + 使用 Pika Flex Turbo 等少步数 H3 适配器(每个请求都需要 LoRA 和对应的步数),或想用一个 vLLM-Omni 服务提供多个这样的变体时,参见随 OpenDirector 一起启动的[视频转发层](video-gateway.zh-CN.md)。 ## 制作第一支短片 diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 00d698c47..a0360d091 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -125,7 +125,7 @@ def resolve_reference(snapshot, reference): asset = assets.get(ref.assetId) if asset is None or asset.fingerprint != ref.fingerprint: raise ContractError('reference_invalid', '参考素材不存在或内容已变化。', reference.id) - resolved.append(ResolvedReference(referenceId=reference.id, role=reference.role, asset=asset_ref(asset), + resolved.append(ResolvedReference(referenceId=reference.id, role=reference.role, frameTimeMs=reference.frameTimeMs, asset=asset_ref(asset), metadata=asset.metadata, sourceVersion=source_version, documentVersion=document_version, subjectRole=subject_role, name=asset.name, sourceTitle=source_title)) return resolved @@ -713,6 +713,9 @@ def _mutate(self, data, kind, payload): if any(other['id'] != old['id'] and other['active'] and (other['targetSpecId'], other['binding'], other['source']) == (ref['targetSpecId'], ref['binding'], ref['source']) for other in data['references']): raise ContractError('reference_invalid', '该参考来源已连接到目标配置。', payload.reference.id) old.update(ref) + if 'frameTimeMs' not in ref: + # An unset pin is omitted from the dump, so merging alone would keep the previous time. + old.pop('frameTimeMs', None) if ref['binding'] == 'follow_current': source = self._get(data, 'canvas_item', ref['source']['id']) source_kind = source['kind'] diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 4a9f82c95..e5185e05a 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -162,7 +162,8 @@ def task(self, job): kind=spec.kind, status=job.status, phase=job.phase, recovery=job.recovery, resumeAllowed=job.resumeAllowed, modelConfigId=str(model.modelConfigId), model=model.modelId, baseURL=model.url, protocol=model.protocol, title=spec.prompt[:80] or spec.kind, prompt=prompt, promptContent=content, referenceIds=reference_ids, - referenceRoles=[{'assetId': str(r.asset.assetId), 'role': r.role} for r in job.inputSnapshot.references if r.transmission != 'context_only'], + referenceRoles=[{'assetId': str(r.asset.assetId), 'role': r.role} | ({'frameTimeMs': r.frameTimeMs} if r.frameTimeMs is not None else {}) + for r in job.inputSnapshot.references if r.transmission != 'context_only'], referenceInputs={'profile': profile}, videoMode=spec.parameters.videoMode if spec.kind == 'video' else 'first_frame', parameters=job.adapterParameters, externalTaskId=job.externalTaskId, assetId=str(job.asset.assetId) if job.asset else None, diff --git a/packages/core/src/opendirector/application/model_availability.py b/packages/core/src/opendirector/application/model_availability.py index 2fc4f352d..48087f06f 100644 --- a/packages/core/src/opendirector/application/model_availability.py +++ b/packages/core/src/opendirector/application/model_availability.py @@ -74,7 +74,8 @@ def generation_request(config, spec, references, *, parameters=None): candidates = requests_for(config) if not candidates: return None - transmitted = [item for item in references if item.transmission == 'content'] + # A keyframe travels as a timeline guide beside the request's declared inputs, so it counts toward none of them. + transmitted = [item for item in references if item.transmission == 'content' and getattr(item, 'role', None) != 'keyframe'] kinds = {item.asset.kind for item in transmitted} if spec.kind == 'image': profile = 'image_to_image' if 'image' in kinds else 'text_to_image' diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index a59c2fdf0..12b4266d7 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -756,16 +756,28 @@ def video_create(ctx: typer.Context, x: Annotated[float, typer.Option(help="Canvas X coordinate. Choose using the current item positions and sizes.")], y: Annotated[float, typer.Option(help="Canvas Y coordinate. Choose using the current item positions and sizes.")], first_frame: Annotated[UUID | None, typer.Option(help="Source image canvas item for first-frame mode.")] = None, - reference_item: Annotated[list[UUID] | None, typer.Option(help="Source canvas items for reference mode. Repeat for multiple inputs.")] = None): + reference_item: Annotated[list[UUID] | None, typer.Option(help="Source canvas items for reference mode. Repeat for multiple inputs.")] = None, + keyframe: Annotated[list[str] | None, typer.Option(help="Pin an image canvas item at a moment of the output, as ITEM_UUID@SECONDS (e.g. 3f2a...@1.25). Repeat for several keyframes. Needs reference mode, at least one --reference-item, and a model whose inputRules.maxKeyframes is set.")] = None): client = ctx.obj client.command = ctx.command_path config = select_model([value for value in client.models() if value["kind"] == "video"], model) - if first_frame and reference_item: - raise ProjectError("Choose --first-frame or --reference-item for the selected video mode.") + if first_frame and (reference_item or keyframe): + raise ProjectError("Choose --first-frame, or --reference-item with optional --keyframe, for the selected video mode.") + pinned = [] + for value in keyframe or []: + item, _, seconds = value.partition("@") + try: + pinned.append((UUID(item), round(float(seconds) * 1000))) + except (ValueError, OverflowError): # also inf and nan, which cannot be rounded + raise ProjectError(f"--keyframe expects ITEM_UUID@SECONDS, got {value!r}.") from None + if pinned[-1][1] < 0: + raise ProjectError("--keyframe time must not be negative.") + if pinned and not config["inputRules"].get("maxKeyframes"): + raise ProjectError("Selected model does not support keyframes (inputRules.maxKeyframes is not set).") allowed = config["inputRules"]["videoModes"] if first_frame: mode = "first_frame" - elif reference_item: + elif reference_item or pinned: mode = "reference" else: mode = allowed[0] @@ -783,6 +795,13 @@ def video_create(ctx: typer.Context, references.append({"id": str(uuid5(operation, f"reference-{index}")), "projectId": project_id, "targetSpecId": spec_id, "role": "first_frame" if first_frame else "reference", "order": index, "binding": "follow_current", "source": {"id": str(source_id)}}) + for source_id, milliseconds in pinned: + if not any(item["id"] == str(source_id) and item["kind"] == "image" for item in snapshot["canvasItems"]): + raise ProjectError(f"Keyframe canvas item {source_id} is not an image in this project.") + index = len(references) + references.append({"id": str(uuid5(operation, f"reference-{index}")), "projectId": project_id, + "targetSpecId": spec_id, "role": "keyframe", "frameTimeMs": milliseconds, + "order": index, "binding": "follow_current", "source": {"id": str(source_id)}}) receipt = client.execute("canvas.createGeneration", { "spec": {"id": spec_id, "projectId": project_id, "kind": "video", "purpose": "generation", "modelConfigId": config["id"], "prompt": prompt, diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 72dc22cef..00df30965 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -506,6 +506,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'canvas_run_layout_group', 'canvas_run_layout_conflict', 'canvas_run_layout_extent', 'canvas_run_layout_shared_object', 'missing_object', 'reference_invalid', 'image_quality_unsupported', + 'keyframe_unsupported', 'keyframe_mode', 'keyframe_kind', 'keyframe_count', 'keyframe_needs_reference', 'keyframe_time', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', 'kling_model', 'kling_mode', 'kling_image', 'kling_frames', 'kling_prompt', 'kling_aspect', 'kling_output', 'kling_cancel', diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 513c705e7..5113265af 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -12,8 +12,9 @@ from opendirector.domain.projects import ProjectError from opendirector.domain.generation import GenerationFailure, ResultCheck from opendirector.domain.projects import ProjectError +from opendirector.domain.reference_windows import windows_reference_videos from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, LYRICS_MAX_LENGTH, MAX_REFERENCES, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, KEYFRAME_FPS, keyframe_frame, LYRICS_MAX_LENGTH, MAX_REFERENCES, MUSIC_SECONDS_INITIAL, MUSIC_SECONDS_MAX, MUSIC_SECONDS_MIN, PROMPT_MAX_LENGTH, REFERENCE_MEDIA_SECONDS, STORED_VOICE_PATTERN, TEXT_DEFAULT_MAX_TOKENS, TEXT_MAX_TOKENS, duration_matches, effective_video_mode, generate_audio_options, prompt_optional_with_media, @@ -158,7 +159,9 @@ class FollowingSource(Contract): class ReferenceBase(ProjectEntity): targetSpecId: UUID = Field(description='Target generation configuration ID.') - role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(default='reference', description='Business role of this binding or reference.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control', 'keyframe'] = Field(default='reference', description='Business role of this binding or reference.') + frameTimeMs: int | None = Field(default=None, ge=0, strict=True, exclude_if=lambda value: value is None, + description='For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.') order: int = Field(default=0, ge=0, strict=True, description='Reference ordering within the target configuration.') active: bool = Field(default=True, description='Whether this reference participates in generation.') # Retained tombstone prevents revision ABA on undo. @@ -186,7 +189,9 @@ class FollowingReference(ReferenceBase): class ResolvedReference(Contract): referenceId: UUID = Field(description='Generation reference ID.') - role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(description='Business role of this binding or reference.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control', 'keyframe'] = Field(description='Business role of this binding or reference.') + frameTimeMs: int | None = Field(default=None, ge=0, exclude_if=lambda value: value is None, + description='For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.') asset: AssetRef = Field(description='Immutable asset version.') metadata: MediaMetadata = Field(description='Verified media properties.') sourceVersion: ObjectVersion | None = Field(default=None, description='Captured source object version.') @@ -382,6 +387,30 @@ def implicit_text_prompt(spec: GenerationSpec, references: tuple[ResolvedReferen ref.asset.kind == 'text' and ref.transmission == 'content' for ref in references) +def validate_keyframes(spec, rules, keyframes, *, has_reference): + """Pictures pinned at chosen moments of the output (H3 timeline guides).""" + if not rules.maxKeyframes: + raise ProjectError('当前模型不支持指定帧生成,请移除关键帧或更换模型。', 422, code='keyframe_unsupported') + if spec.parameters.videoMode != 'reference': + raise ProjectError('关键帧只能用于素材参考模式,不能与首尾帧、接续或结构控制同时使用。', 422, code='keyframe_mode') + if any(ref.asset.kind != 'image' for ref in keyframes): + raise ProjectError('关键帧必须是图片。', 422, code='keyframe_kind') + if len(keyframes) > rules.maxKeyframes: + raise ProjectError(f'最多指定 {rules.maxKeyframes} 个关键帧,当前为 {len(keyframes)} 个。', 422, code='keyframe_count') + if not has_reference: + raise ProjectError('指定帧生成还需要至少一张普通参考图片或一段参考视频。', 422, code='keyframe_needs_reference') + seconds = spec.parameters.durationSeconds + times = [ref.frameTimeMs for ref in keyframes] + if any(value is None for value in times): + raise ProjectError('每个关键帧都需要指定时间点。', 422, code='keyframe_time') + # A guide is pinned to one output frame, so times are compared as the frames they land on. + frames = [keyframe_frame(value) for value in times] + if seconds is not None and any(frame >= round(seconds * KEYFRAME_FPS) for frame in frames): + raise ProjectError(f'关键帧的时间点必须早于视频结束({seconds:g} 秒)。', 422, code='keyframe_time') + if len(set(frames)) != len(frames): + raise ProjectError('两个关键帧不能落在同一帧上,请把时间点至少错开 1/24 秒。', 422, code='keyframe_time') + + def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, references: tuple[ResolvedReference, ...] = (), *, submitting: bool = False): """Pure shared validation; it never submits, uploads or changes a project.""" @@ -422,8 +451,13 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc unique([(ref.referenceId, ref.asset.assetId) for ref in references], 'resolved reference assets') if spec.promptContent and any(isinstance(part, PromptReference) and part.referenceId not in {ref.referenceId for ref in references} for part in spec.promptContent): raise ValueError('提示词引用了未解析的参考素材。') + # Every keyframe is checked, also one a mode would otherwise leave out as context: it must be refused, not dropped. + keyframes = [ref for ref in references if ref.role == 'keyframe'] + # A keyframe is pinned to the output's timeline as a guide; it is not one of the model's reference pictures. + references = tuple(ref for ref in references if ref not in keyframes) transmitted = [ref for ref in references if ref.role != 'continuation' and ref.transmission != 'context_only'] - if sum(ref.metadata.size for ref in transmitted) > rules.requestBytes: + # Keyframes are uploaded too (as timeline guides), so their bytes count toward the request. + if sum(ref.metadata.size for ref in (*transmitted, *keyframes)) > rules.requestBytes: raise ValueError('参考素材总大小超过模型请求上限。') for ref in transmitted: limit = (rules.imageBytes if ref.asset.kind == 'image' else rules.videoBytes if ref.asset.kind == 'video' @@ -464,9 +498,11 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if spec.kind == 'audio' and spec.promptContent is not None and not any(part.type == 'text' and part.text.strip() for part in spec.promptContent): raise ValueError('语音生成需要实际文本,不能只使用参考标签。') if spec.kind != 'video': - if any(ref.role != 'reference' for ref in references): + if keyframes or any(ref.role != 'reference' for ref in references): raise ValueError('首尾帧和续写参考只能用于视频生成。') return + if keyframes: + validate_keyframes(spec, rules, keyframes, has_reference=any(ref.asset.kind in {'image', 'video'} for ref in transmitted)) params = spec.parameters if rules.profile == 'minimax-h3-official': if model.modelId not in MINIMAX_MODELS: @@ -531,7 +567,9 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc minimum = 2 if kind == 'audio' or rules.profile == 'minimax-h3-official' else 0 minimum = rules.referenceMediaMinSeconds if rules.referenceMediaMinSeconds is not None else minimum maximum = rules.referenceMediaSeconds if rules.referenceMediaSeconds is not None else REFERENCE_MEDIA_SECONDS - if any(value is None or value < minimum or value <= 0 for value in seconds) or sum(seconds) > maximum: + # Over-long videos are sent as their final window on these profiles, so only a known length is required. + windowed = kind == 'video' and windows_reference_videos(rules.profile) + if any(value is None or value < minimum or value <= 0 for value in seconds) or (not windowed and sum(seconds) > maximum): label = '视频' if kind == 'video' else '音频' if rules.referenceMediaSeconds is not None: raise ProjectError('参考视频和音频每段须为 2–30 秒,同类素材总时长不能超过 30 秒。', 422, code='higgsfield_duration') diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 6897ff9f5..cd72c26af 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -63,6 +63,8 @@ class InputRules(Contract): maxImages: Count = Field(description='Maximum reference image count.') maxVideos: Count = Field(description='Maximum reference video count.') maxAudios: Count = Field(description='Maximum reference audio count.') + maxKeyframes: Count = Field(default=0, exclude_if=lambda value: not value, + description='Maximum pictures that can be pinned at chosen moments of a generated video; omitted when unsupported.') imageBytes: Count = Field(description='Maximum bytes per reference image.') videoBytes: Count = Field(description='Maximum bytes per reference video.') audioBytes: Count | None = Field(default=None, exclude_if=lambda value: value is None, diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index eaa230f88..3d5e4e0a8 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -139,11 +139,13 @@ def project_relations(self): source = items.get(reference.source.id) if source is None or source.kind not in {'text', 'image', 'video', 'audio', 'subject'}: raise ValueError('Following reference needs a stable logical media source') - if reference.role == 'first_frame' and source.kind != 'image' or reference.role in {'continuation', 'control'} and source.kind != 'video': + if reference.role in {'first_frame', 'keyframe'} and source.kind != 'image' or reference.role in {'continuation', 'control'} and source.kind != 'video': raise ValueError('Reference source kind does not match its role') - elif ((reference.role == 'first_frame' and reference.source.kind != 'image') + elif ((reference.role in {'first_frame', 'keyframe'} and reference.source.kind != 'image') or (reference.role in {'continuation', 'control'} and reference.source.kind != 'video')): raise ValueError('Reference source kind does not match its role') + if (reference.frameTimeMs is not None) != (reference.role == 'keyframe') and reference.active: + raise ValueError('frameTimeMs is set exactly on keyframe references') for spec in self.generationSpecs: if spec.promptContent: for part in spec.promptContent: diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index ac5ada2e7..8e5f0966a 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -13,6 +13,8 @@ from .zhipu_speech import ZHIPU_DEFAULT_VOICE, ZHIPU_SPEECH_CHARACTERS, is_zhipu_speech VideoMode = Literal['first_frame', 'reference', 'continuation'] +# H3 timeline guides: pictures pinned at chosen frames of the output; the service accepts eight entries. +H3_KEYFRAMES = 8 def _adapter_rules(config): @@ -112,14 +114,17 @@ def _adapter_rules(config): # references) stays zero. rules.update(profile='vllm-omni-h3', allowedKinds=['text', 'image', 'video', 'audio'], maxImages=9, maxAudios=3, imageBytes=30 * 1024 * 1024, requestBytes=64 * 1024 * 1024, videoModes=['first_frame', 'reference', 'continuation'], - outputResolutions=['480P', '768P']) + outputResolutions=['480P', '768P'], maxKeyframes=H3_KEYFRAMES) return rules if kind == 'video' and config.get('protocol') == 'vllm_omni' and adapter in {'fasth3', 'fasth3_dual'}: rules.update(profile='fasth3-omni', allowedKinds=['text', 'image', 'video', 'audio'], maxImages=9, maxVideos=3, maxAudios=3, imageBytes=30 * 1024 * 1024, - requestBytes=160 * 1024 * 1024, videoModes=['reference', 'control'], outputResolutions=['480P', '768P']) + requestBytes=160 * 1024 * 1024, videoModes=['reference', 'control', 'continuation'], + outputResolutions=['480P', '768P'], maxKeyframes=H3_KEYFRAMES) + # continuation: every H3 weight set continues its own clips from cached latents (continue_from); + # the source video is named by job ID and never uploaded. if adapter == 'fasth3_dual': - rules.update(videoModes=['reference', 'first_frame', 'control'], frameRoles=['first_frame', 'last_frame']) + rules.update(videoModes=['reference', 'first_frame', 'control', 'continuation'], frameRoles=['first_frame', 'last_frame']) return rules if kind == 'video' and config.get('protocol') == 'vllm_omni': rules.update(profile='standard-video', maxImages=1, videoModes=['first_frame']) diff --git a/packages/core/src/opendirector/domain/reference_windows.py b/packages/core/src/opendirector/domain/reference_windows.py new file mode 100644 index 000000000..aaff144db --- /dev/null +++ b/packages/core/src/opendirector/domain/reference_windows.py @@ -0,0 +1,41 @@ +"""Time windows for reference videos longer than a model's reference budget. + +A model that reads reference videos accepts only a short total length. Profiles +listed here take the end of an over-long clip instead of refusing it: the last +seconds are what an extension continues from, and they are a deterministic +choice that needs no extra setting. Admission and execution both derive the +windows from the same asset durations, so an accepted job always transmits the +range its snapshot implies. +""" + +from opendirector.domain.rule_facts import REFERENCE_MEDIA_SECONDS + +# Self-hosted vLLM-Omni Ref2VA (FastH3-Omni request shape, also Pika H3 adapters). +WINDOWED_PROFILES = frozenset({'fasth3-omni'}) + + +def windows_reference_videos(profile: str) -> bool: + return profile in WINDOWED_PROFILES + + +def reference_video_windows(durations_ms, limit_ms: int = REFERENCE_MEDIA_SECONDS * 1000): + """Per-video `(start_ms, end_ms)` to transmit, or `None` where the whole clip is sent. + + Clips that fit the budget together are untouched. Otherwise the budget is + shared by water-filling: short clips stay whole and the longest ones are cut + to one common length, each keeping its final part. + """ + durations = [int(value) for value in durations_ms] + if any(value <= 0 for value in durations): + raise ValueError('reference video durations must be positive') + if sum(durations) <= limit_ms: + return [None] * len(durations) + remaining, left, cap = limit_ms, len(durations), 0 + for value in sorted(durations): + if value * left <= remaining: + remaining -= value + left -= 1 + else: + cap = remaining // left + break + return [(value - cap, value) if value > cap else None for value in durations] diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 4ee1fd661..8afe6095b 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -477,3 +477,11 @@ def typescript_module(): facts = json.dumps(facts_payload(), ensure_ascii=False, indent=2) vectors = json.dumps(derivation_vectors(), ensure_ascii=False, indent=2) return _TYPESCRIPT.replace('__FACTS__', facts).replace('__VECTORS__', vectors) + + +KEYFRAME_FPS = 24 # H3 output rate; timeline guides are addressed by frame + + +def keyframe_frame(milliseconds: int) -> int: + """The output frame a keyframe time is pinned to.""" + return round(milliseconds * KEYFRAME_FPS / 1000) diff --git a/packages/core/src/opendirector/integrations/fasth3.py b/packages/core/src/opendirector/integrations/fasth3.py index 8e8fb58c6..a8acb9d4e 100644 --- a/packages/core/src/opendirector/integrations/fasth3.py +++ b/packages/core/src/opendirector/integrations/fasth3.py @@ -4,9 +4,10 @@ from opendirector.domain.projects import ProjectError from opendirector.domain.references import project_content +from opendirector.domain.rule_facts import REFERENCE_MEDIA_SECONDS -def generation_fields(parameters, *, frame_indices=None): +def generation_fields(parameters, *, frame_indices=None, continue_from=None, continue_size=None): """Prepare the same FastH3 fields for capability checks and HTTP submission.""" from opendirector.integrations.vllm_omni import FPS, video_frame_parameters fields = {} @@ -26,6 +27,13 @@ def generation_fields(parameters, *, frame_indices=None): steps = parameters.get('num_inference_steps', 20) fields.update(size=parameters.get('size', '832x480'), num_inference_steps=steps, guidance_scale=1, fps=24, seed=parameters.get('seed', 1234)) + if continue_from is not None: + extra['continue_from'] = continue_from + # The service samples a window over the earlier job's cached latent tail; latents cannot change size. + # The capability check knows the size before the job has an ID to continue from, and checks what is sent. + width, height = continue_size or (None, None) + if width and height: + fields['size'] = f'{width}x{height}' return fields, extra @@ -93,7 +101,8 @@ def video_parameters(node, records, *, duration_seconds=None): # Legacy callers without that field retain the prompt/source/default policy. seconds = float(duration_seconds) if duration_seconds is not None else ( float(next(group for group in explicit.groups() if group)) if explicit else ( - max(4.0, basis['durationMs'] / 1000) if edit else 5.0)) + # An over-long source is sent as its final reference window, so an edit covers that window. + max(4.0, min(basis['durationMs'] / 1000, REFERENCE_MEDIA_SECONDS)) if edit else 5.0)) if not 4 <= seconds <= 15: raise ProjectError('当前 FastH3 支持生成 4—15 秒的视频,请调整输出时长;未提交生成。') requested_frames = round(seconds * 24) diff --git a/packages/core/src/opendirector/integrations/generation_capability_parameters.py b/packages/core/src/opendirector/integrations/generation_capability_parameters.py index f8de030ba..3b818dc26 100644 --- a/packages/core/src/opendirector/integrations/generation_capability_parameters.py +++ b/packages/core/src/opendirector/integrations/generation_capability_parameters.py @@ -53,7 +53,7 @@ def generation_capability_parameters(config, kind, parameters, *, has_images=Fal has_audio=has_audio, continue_size=continue_size)) elif profile == 'fasth3-omni': from opendirector.integrations.fasth3 import generation_fields - fields, extra = generation_fields(parameters, frame_indices=frame_indices) + fields, extra = generation_fields(parameters, frame_indices=frame_indices, continue_size=continue_size) result = {**fields, **extra} else: result = {key: parameters[key] for key in ('size',) if key in parameters} diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index 560269231..d07796818 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -762,6 +762,74 @@ async def work(): return await _call('poll', work) +class FastH3VideoEdit(VllmOmniVideo): + """Latent-mask editing on a Ref2VA-only H3 service: FastH3 Omni and the few-step adapters served the same way. + + These weights run Ref2VA on a fixed eight-step schedule and need a reference picture. A Ref2VA model + opens a clip close to that picture: whatever the picture shows where the edit redraws is what the first + frames show there, and the prompt only takes over as the clip runs. No frame of the source shows the + edited look, so a boxed redraw runs twice. The first pass takes the source's first frame and arrives at + the edit by its end; the second takes that pass's last edited frame, so the edit is there from the start. + """ + + capabilities = frozenset({'video.edit'}) + + @classmethod + def edit_parameters(cls, seconds, width, height): + values, _ = super().edit_parameters(seconds, width, height) + return {**values, 'num_inference_steps': 8, 'guidance_scale': 1}, {'task': 'ref2va', 'audio_flow_shift': 3} + + @classmethod + def _last_edited_frame(cls, data, end: float | None): + """The last frame a redraw covers: the clip's final picture, or the one before `end` when the edit stops earlier.""" + with media.Workspace() as work: + path = work.write('in.mp4', data) + moment = media.last_frame_time(path) + if end is not None: + moment = min(end - 1 / cls.FPS, moment) + # Half a frame early: a seek lands on the first picture at or after it, and must not overshoot the last one. + return media.frame_at(path, max(moment - 0.5 / cls.FPS, 0.0), work.path / 'frame.png') + + @classmethod + def _source_still(cls, data, mask: EditMask | None): + """The frame of the source clip that shows the look to keep: its first, unless that frame is redrawn whole. + + A redraw of a whole-frame time span that opens the clip takes the first frame after the span, which + shows the look the kept part has, rather than a frame the edit replaces. A span that runs to the + clip's real end keeps nothing, so the first frame stays the only look there is. + """ + with media.Workspace() as work: + path = work.write('in.mp4', data) + moment = 0.0 + if mask is not None and mask.region is None and not mask.start and mask.end is not None: + kept = math.ceil(mask.end * cls.FPS - 1e-6) # picture_mask redraws frames below end * FPS + if kept <= round(media.last_frame_time(path) * cls.FPS): + # Half a frame early: a seek lands on the first picture at or after it. + moment = max(kept - 0.5, 0.0) / cls.FPS + return media.frame_at(path, moment, work.path / 'frame.png') + + async def edit_video(self, config, request: VideoEditRequest, *, submitted=None) -> MediaResult: + values, extra = self.edit_parameters(request.seconds, request.width, request.height) + frames = values['num_frames'] + width, height = map(int, values['size'].split('x')) + source = await blocking(self._conformed, request.source, width, height) + # Guidance is fixed at 1 on these weights, so there is no negative prompt to send. + fields = self._fields(config, ' ' + request.prompt, values, extra) + masks = [('video_noise_mask', ('video-mask.json', json.dumps(self.picture_mask(request.picture, frames)).encode(), 'application/json')), + ('audio_noise_mask', ('audio-mask.json', json.dumps(self.sound_mask(request.sound, frames)).encode(), 'application/json'))] + + async def redraw(still): + files = [('input_references', ('reference.png', still, 'image/png')), ('source_video', ('source.mp4', source, 'video/mp4')), *masks] + return await self._job(config, fields, files, submitted) + + still = await blocking(self._source_still, source, request.picture) + mask = request.picture + if mask is not None and mask.region is not None: + draft = await redraw(still) + still = await blocking(self._last_edited_frame, draft.data, mask.end) + return await redraw(still) + + class OpenAISpeech(ModelAdapter): """OpenAI-compatible /audio/speech (also served by vLLM-Omni TTS).""" @@ -983,6 +1051,8 @@ def adapter_for(config, transport=None, poll_interval=3, *, image_policy=None, l return OpenAIImages(transport, poll_interval, **image_options) if kind == 'video' and profile == 'vllm-omni-h3': return VllmOmniVideo(transport, poll_interval) + if kind == 'video' and profile == 'fasth3-omni': + return FastH3VideoEdit(transport, poll_interval) if kind == 'audio' and profile == 'vllm-omni-music': return VllmOmniMusic(transport, poll_interval) if kind == 'audio' and protocol in {'openai', 'vllm_omni'}: diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index da687d58f..271122c65 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -20,13 +20,14 @@ from opendirector.integrations.kling_video import KlingVideoGeneration from opendirector.integrations.higgsfield_open import HiggsfieldOpenGeneration from opendirector.integrations.bigmodel_video import BigModelVideoGeneration -from opendirector.integrations.vllm_omni import VllmOmniGeneration, _upload +from opendirector.integrations.vllm_omni import VllmOmniGeneration, _continuation_failure, _missing_latents, _upload, timeline_guide_parts from opendirector.integrations.fasth3 import generation_fields as fasth3_generation_fields from opendirector.integrations.vllm_omni_image import VllmOmniImageGeneration from opendirector.integrations.model_adapters import (BigModelImages, MinimaxH3Images, MinimaxSpeech, MossImages, MossSpeech, OpenAISpeech, VllmOmniMusic, VllmOmniScore, ZhipuSpeech, image_parts) from opendirector.domain.capabilities import ImageRequest, MusicRequest, ScoreRequest, SpeechRequest from opendirector.media.probe import require_ffprobe +from opendirector.media.processing import clip class GenerationProviders(VolcengineGeneration): @@ -95,6 +96,17 @@ async def _json(self, client, method, url, config, **kwargs): raise protocol_failure('poll' if method == 'GET' else 'submit') return json.loads(data) + async def _submit_continuation(self, client, url, config, form, files): + """Submit a continue_from request; a 400 for a clip the service no longer holds gets its own explanation.""" + secrets = (config.get('apiKey', ''),) + async with client.stream('POST', url, headers=auth_headers(config), data=form, files=files, + extensions={'model_parameters': {'fields': form, 'file_count': len(files)}}) as response: + if response.status_code == 400: + value = json.loads(await response.aread()) + raise _continuation_failure('submit') if _missing_latents(value) else provider_failure( + value, stage='submit', headers=response.headers, http_status=400, secrets=secrets) + return json.loads(await bounded(response, stage='submit', secrets=secrets)) + async def resume_result(self, config, suffix, url): # Accepted results remain downloadable after a model leaves the catalog. if config and is_minimax_speech(config): @@ -186,10 +198,25 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery files = [('input_references', _upload(image, 'first_frame' if index == 0 else 'last_frame')) for index, image in zip(frame_indices, prepared['images'], strict=True)] else: + continuing = task.get('videoMode') == 'continuation' + roles = {} + for value in task.get('referenceRoles') or []: + roles.setdefault(str(value['assetId']), set()).add(value['role']) for data, meta, source_kind in references(self.store, task['projectId'], task['referenceIds']): + if continuing and source_kind == 'video': + continue # Continued from the service's cached latents by job ID; never uploaded. + if roles.get(str(meta['id'])) == {'keyframe'}: + continue # A keyframe travels as a timeline guide below, not as a reference picture. if fast and str(meta['id']) == str(prepared.get('control')): # FastH3 + ControlNet: the structure video conditions every frame, not as a reference clip. files.append(('control_reference', (meta['name'], data, meta['type']))) + elif source_kind == 'video' and str(meta['id']) in (prepared.get('windows') or {}): + # An over-long reference video travels as its planned final window, cut once as the job runs. + start, end = prepared['windows'][str(meta['id'])] + window = await asyncio.to_thread(clip, data, start / 1000, end / 1000) + if len(window) > input_rules(config)['videoBytes']: + raise ProjectError(f'“{meta["name"]}”截取后的参考片段仍超过当前接口参考视频大小限制。', 413) + files.append(('input_references' if fast else 'input_reference', (meta['name'], window, 'video/mp4'))) elif source_kind in {'image', 'video', 'audio'}: files.append(('input_references' if fast else 'input_reference', (meta['name'], data, image_type(data) if source_kind == 'image' else meta['type']))) parameters = task['parameters'] @@ -201,11 +228,17 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery form['seconds'] = str(int(seconds)) if float(seconds).is_integer() else str(seconds) if 'size' in parameters: form['size'] = parameters['size'] if fast: - values, extra = fasth3_generation_fields(parameters, frame_indices=frame_indices) + values, extra = fasth3_generation_fields(parameters, frame_indices=frame_indices, + continue_from=prepared.get('continueFrom'), continue_size=prepared.get('continueSize')) form.update({key: str(value) for key, value in values.items()}) form['extra_params'] = json.dumps(extra) + guide_fields, guide_files = timeline_guide_parts(prepared) + form.update(guide_fields) + files.extend(guide_files) # Force multipart even for an empty reference list. - value = await self._json(client, 'POST', url, config, data=form, files=files or {'_multipart': (None, '1')}) + files = files or {'_multipart': (None, '1')} + value = (await self._submit_continuation(client, url, config, form, files) if prepared.get('continueFrom') + else await self._json(client, 'POST', url, config, data=form, files=files)) external_id = value['id'] if not isinstance(external_id, str) or not external_id or len(external_id) > 200: raise protocol_failure(stage) @@ -221,6 +254,8 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery await result_ready('mp4', content_url) return await self.resume_result(config, 'mp4', content_url) if value.get('status') in {'failed', 'cancelled', 'expired'}: + if value.get('status') == 'failed' and task.get('videoMode') == 'continuation' and _missing_latents(value): + raise _continuation_failure('poll') raise provider_failure(value, stage='poll', http_status=200, secrets=secrets) if value.get('status') not in {'queued', 'in_progress', 'running'}: raise protocol_failure('poll') diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 08fef8e84..5e4c7ff09 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,10 +5,11 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, keyframe_frame, ) from opendirector.domain.projects import ProjectError from opendirector.domain.minimax_image import validate_minimax_image_reference +from opendirector.domain.reference_windows import reference_video_windows, windows_reference_videos from opendirector.domain.references import project_content from opendirector.media import heif_type @@ -102,7 +103,7 @@ def generation_references(store, task, config, *, complete=True, overrides=None) rules = input_rules({**config, 'kind': 'agent' if kind == 'text' else kind}) mode = task.get('videoMode', 'first_frame') prompt = project_content(task['promptContent'], speech=kind == 'audio')[0] if task.get('promptContent') is not None else task['prompt'] - result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None} + result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None, 'windows': {}, 'guides': []} if kind == 'text': result['content'] = reference_content(store, task['projectId'], {'text': task['prompt'], 'content': task.get('promptContent'), 'assets': [{'id': asset_id} for asset_id in task['referenceIds']]}, manifest=result['manifest'], overrides=overrides) request_size(result['content'], rules['requestBytes']) @@ -129,7 +130,17 @@ def generation_references(store, task, config, *, complete=True, overrides=None) for value in task.get('referenceRoles') or []: roles_by_asset.setdefault(str(value['assetId']), []).append(value['role']) slot_roles = set() - for index, (data, meta, source_kind) in enumerate(references(store, task['projectId'], task['referenceIds'], overrides), 1): + sources = list(references(store, task['projectId'], task['referenceIds'], overrides)) + # Reference videos beyond the model's budget travel as their final window. The plan + # depends only on asset durations, so admission and execution agree; the sender cuts + # the planned range when the job runs, and the source stays the size-checked input here. + windows = {} + if kind == 'video' and mode == 'reference' and windows_reference_videos(rules['profile']): + clips = [(position, meta.get('durationMs')) for position, (_, meta, source_kind) in enumerate(sources, 1) if source_kind == 'video'] + if clips and all(duration and duration > 0 for _, duration in clips): + planned = reference_video_windows([duration for _, duration in clips]) + windows = {position: window for (position, _), window in zip(clips, planned) if window} + for index, (data, meta, source_kind) in enumerate(sources, 1): entry = {'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': source_kind, 'transmission': 'content'} if source_kind == 'video' and kind == 'video' and mode == 'continuation': if result['continueFrom']: @@ -174,6 +185,27 @@ def generation_references(store, task, config, *, complete=True, overrides=None) text_context.append(context) entry['role'] = 'text' elif source_kind == 'image': + # A keyframe is a timeline guide: pinned to one output frame, uploaded apart from the reference + # pictures and never given a label. The same asset may also be an ordinary reference. + asset_roles = [value for value in task.get('referenceRoles') or [] if str(value['assetId']) == str(meta['id'])] + pinned = [value['frameTimeMs'] for value in asset_roles if value['role'] == 'keyframe'] + if pinned: + if not (kind == 'video' and mode == 'reference' and rules.get('maxKeyframes')): + raise ProjectError('当前模型或生成模式不支持指定帧生成,请移除关键帧。', 422, code='keyframe_unsupported') + guide_mime = image_type(data) + if guide_mime not in {'image/png', 'image/jpeg', 'image/webp'} or len(data) > rules['imageBytes']: + raise ProjectError(f'“{meta["name"]}”不能作为关键帧:需为不超过大小限制的 PNG、JPEG 或 WEBP 图片。') + for milliseconds in pinned: + result['guides'].append({'assetId': str(meta['id']), 'name': meta['name'], 'data': data, 'mime': guide_mime, + 'frame': keyframe_frame(milliseconds)}) + result['manifest'].append({**entry, 'role': 'keyframe', 'frameTimeMs': milliseconds}) + # Every pinned time uploads the picture once more as a guide. + media_bytes += len(data) * len(pinned) + if all(value['role'] == 'keyframe' for value in asset_roles): + # Not also a reference picture: the source itself is never uploaded. + media_bytes -= len(data) + source_metadata.pop() + continue mime = image_type(data) if rules['profile'] == 'minimax-h3-image': mime = mime or heif_type(data) @@ -217,8 +249,14 @@ def generation_references(store, task, config, *, complete=True, overrides=None) duration = meta.get('durationMs') if meta['type'] not in {'video/mp4', 'video/quicktime'} or len(data) > rules['videoBytes']: raise ProjectError(f'参考视频需为不超过 {rules["videoBytes"] // (1024 * 1024)} MB 的 MP4 或 MOV。') - if duration is None or not 0 < duration <= REFERENCE_MEDIA_SECONDS * 1000: + window = windows.get(index) + if duration is None or duration <= 0 or (window is None and duration > REFERENCE_MEDIA_SECONDS * 1000): raise ProjectError(f'参考视频需为不超过 {REFERENCE_MEDIA_SECONDS} 秒的有效视频。') + if window is not None: + start, end = window + entry['window'] = {'startMs': start, 'endMs': end} + result['windows'][str(meta['id'])] = window + duration = end - start total_video_ms += duration result['videos'].append(data_uri(data, meta['type'])) number = len(result['videos']) @@ -260,6 +298,9 @@ def generation_references(store, task, config, *, complete=True, overrides=None) raise ProjectError('结构控制需要连接一个控制视频(例如人物深度视频)。') if complete and mode == 'continuation' and not result['continueFrom']: raise ProjectError('接续生成需要引用上一段由 vLLM-Omni H3 生成的视频。') + result['guides'].sort(key=lambda guide: guide['frame']) + if len(result['guides']) > rules.get('maxKeyframes', 0): + raise ProjectError(f'最多指定 {rules.get("maxKeyframes", 0)} 个关键帧。', 422, code='keyframe_count') if len(result['videos']) > rules.get('maxVideos', 0) or total_video_ms > REFERENCE_MEDIA_SECONDS * 1000: raise ProjectError(f'视频参考最多 3 段,总时长不超过 {REFERENCE_MEDIA_SECONDS} 秒。') if rules['profile'] == 'fasth3-omni' and len(result['images']) + len(result['videos']) + len(result['audios']) > FASTH3_MEDIA_REFERENCE_LIMIT: @@ -279,5 +320,7 @@ def generation_references(store, task, config, *, complete=True, overrides=None) validate_moss_image_prompt(result['prompt']) if len(result['prompt']) > 20000: raise ProjectError('正文及文本参考超过当前生成长度限制,请缩短后重试。') - request_size({key: result[key] for key in ('prompt', 'images', 'audios', 'videos')}, rules['requestBytes'] - 4096) + # Guides travel beside the data-URI inputs; reserve their encoded size from the same request budget. + guide_bytes = sum(4 * ((len(guide['data']) + 2) // 3) for guide in result['guides']) + request_size({key: result[key] for key in ('prompt', 'images', 'audios', 'videos')}, rules['requestBytes'] - 4096 - guide_bytes) return result diff --git a/packages/core/src/opendirector/integrations/vllm_omni.py b/packages/core/src/opendirector/integrations/vllm_omni.py index 1b974a105..859903445 100644 --- a/packages/core/src/opendirector/integrations/vllm_omni.py +++ b/packages/core/src/opendirector/integrations/vllm_omni.py @@ -62,6 +62,19 @@ def capability_parameters(fields, extra): return result +def timeline_guide_parts(prepared): + """H3 timeline guides for the prepared keyframes: the manifest field and its uploads, or nothing. + + Guided requests must ask for lossless quality; cache acceleration is rejected with guides. + """ + guides = prepared.get('guides') or [] + if not guides: + return {}, [] + manifest = [{'frame_index': guide['frame'], 'image': {'upload_index': index}} for index, guide in enumerate(guides)] + files = [('guide_files', (guide['name'], guide['data'], guide['mime'])) for guide in guides] + return {'timeline_guides': json.dumps(manifest), 'quality': 'lossless'}, files + + def _upload(data_uri, name): header, payload = data_uri.split(',', 1) mime = header.removeprefix('data:').split(';', 1)[0] @@ -107,6 +120,9 @@ def form(self, config, task, prepared): prepared = {**prepared, 'images': []} files.extend(('input_references', _upload(image, f'image_{index}')) for index, image in enumerate(prepared['images'], 1)) files.extend(('input_references', _upload(audio, f'audio_{index}')) for index, audio in enumerate(prepared['audios'], 1)) + guide_fields, guide_files = timeline_guide_parts(prepared) + fields.update(guide_fields) + files.extend(guide_files) fields['extra_params'] = json.dumps(extra) return fields, files diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index f901d942b..cbe41e520 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -152,6 +152,16 @@ def frame_at(path: Path, seconds: float, out: Path) -> bytes: return out.read_bytes() +def last_frame_time(path: Path) -> float: + """When a clip shows its final picture. Its sound may run longer, so the file's length does not say.""" + value = json.loads(_run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-count_packets', + '-show_entries', 'stream=nb_read_packets,r_frame_rate', '-of', 'json', str(path)], timeout=60)) + picture = (value.get('streams') or [{}])[0] + numerator, _, denominator = (picture.get('r_frame_rate') or '24/1').partition('/') + fps = float(numerator) / float(denominator or 1) if float(denominator or 1) else 24.0 + return max(int(picture.get('nb_read_packets') or 1) - 1, 0) / (fps or 24.0) + + def _normalized(source: Path, out: Path, info: dict, *, start=None, end=None): """One segment re-encoded to the reference size, rate and stereo AAC (silence when missing).""" width, height, fps = info['width'] - info['width'] % 2, info['height'] - info['height'] % 2, info['fps'] @@ -197,6 +207,17 @@ def trim(source: Path, seconds: float, out: Path) -> Path: return out +def clip(data: bytes, start: float, end: float) -> bytes: + """Seconds [start, end) of a video as H.264/AAC MP4, keeping its size, frame rate and soundtrack.""" + with Workspace() as workspace: + source, out = workspace.write('source', data), workspace.path / 'clip.mp4' + # Decoding from an input-side seek and limiting the output length is frame-exact when re-encoding. + _run(['ffmpeg', '-v', 'error', '-y', '-ss', f'{max(start, 0):.3f}', '-i', str(source), '-t', f'{end - start:.3f}', + '-map', '0:v:0', '-map', '0:a:0?', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', '-pix_fmt', 'yuv420p', + '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', str(out)]) + return out.read_bytes() + + def upscale(source: Path, long_edge: int, out: Path) -> bytes: info = video_info(source) if max(info['width'], info['height']) >= long_edge: diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index 0d5153c4b..5b4e62e06 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -36,7 +36,7 @@ import { mediaBlobDataUrl } from "../canvas/localMediaRuntime.ts"; import { generationContentPatch } from "../canvas/generationReferenceContent.ts"; import { assemblyResource, staleAssembly } from "../canvas/editorAssembly.ts"; import { RULE_FACTS } from "../contracts/ruleFacts.generated.ts"; -import { canvasReferenceRole, MUSIC_SECONDS } from "./rules.ts"; +import { canvasReferenceFrameTime, canvasReferenceRole, MUSIC_SECONDS } from "./rules.ts"; import { assetReference, CreationClient, @@ -876,6 +876,15 @@ export class CreationProjection { ? "lastFrameNodeId" : "firstFrameNodeId" ] = frame.source.id; + const pinned = currentReferences.flatMap((ref) => + ref.targetSpecId === spec.id && + ref.role === "keyframe" && + ref.binding === "follow_current" && + typeof ref.frameTimeMs === "number" + ? [{ nodeId: ref.source.id, seconds: ref.frameTimeMs / 1000 }] + : [], + ); + if (pinned.length) node.data.settings.pinnedFrames = pinned; } const selected = snapshot.results.find( (r) => r.id === spec.currentResultId, @@ -1889,11 +1898,15 @@ export class CreationProjection { ? items.get(ref.source.id)?.kind : ref.source.kind; const role = canvasReferenceRole(settings, sourceKind, ref); - if (role !== ref.role) { + const frameTimeMs = canvasReferenceFrameTime(settings, sourceKind, ref); + if (role !== ref.role || (frameTimeMs ?? null) !== (ref.frameTimeMs ?? null)) { expect("reference", ref); + const { frameTimeMs: _previous, ...rest } = ref; operations.push({ type: "reference.update", - payload: { reference: { ...ref, role } }, + payload: { + reference: { ...rest, role, ...(frameTimeMs !== undefined ? { frameTimeMs } : {}) }, + }, }); } } @@ -1910,9 +1923,13 @@ export class CreationProjection { ?.type ?? items.get(ref.source.id)?.kind) : ref.source.kind; const role = canvasReferenceRole(settings, sourceKind, ref); + const frameTimeMs = canvasReferenceFrameTime(settings, sourceKind, ref); + const { frameTimeMs: _previous, ...rest } = ref; operations[index] = { type: op.type, - payload: { reference: { ...ref, role } }, + payload: { + reference: { ...rest, role, ...(frameTimeMs !== undefined ? { frameTimeMs } : {}) }, + }, }; } } diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 5da816653..8ec98de7c 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -47,6 +47,8 @@ export interface InputRules { audioBytes?: number | null; referenceMediaMinSeconds?: number | null; referenceMediaSeconds?: number | null; + /** Pictures that can be pinned at chosen moments of a generated video; absent when unsupported. */ + maxKeyframes?: number; requestBytes?: number; maxPromptCharacters?: number | null; voiceRequired?: boolean | null; @@ -99,7 +101,9 @@ export interface ModelConfig { export interface BackendReference { node: CanvasNode; - role: "reference" | "firstFrame" | "lastFrame" | "continuation" | "control"; + role: "reference" | "firstFrame" | "lastFrame" | "continuation" | "control" | "keyframe"; + /** For role keyframe: seconds from the start of the output where the picture is pinned. */ + seconds?: number; } /** SAM configurations serve editing tools, including legacy vision entries. */ @@ -315,15 +319,41 @@ export function backendReferences( .map((node) => ({ node, role: "reference" as const })), ]; } - return usable.map((node) => ({ - node, - role: - settings.videoMode === "continuation" && node.data.kind === "video" - ? "continuation" - : settings.videoMode === "control" && node.data.kind === "video" - ? "control" - : "reference", - })); + return usable.map((node) => { + const pinned = settings.mode === "video" ? pinnedFrameSeconds(settings, node.data.kind, node.id) : undefined; + if (pinned !== undefined) return { node, role: "keyframe" as const, seconds: pinned }; + return { + node, + role: + settings.videoMode === "continuation" && node.data.kind === "video" + ? ("continuation" as const) + : settings.videoMode === "control" && node.data.kind === "video" + ? ("control" as const) + : ("reference" as const), + }; + }); +} + +/** Seconds at which a connected image is pinned to the output, when the node is in reference mode. */ +export function pinnedFrameSeconds( + settings: Pick | undefined, + sourceKind: string | undefined, + sourceId: string | undefined, +): number | undefined { + if (!settings || sourceKind !== "image" || !sourceId) return undefined; + if ((settings.videoMode ?? "reference") !== "reference") return undefined; + return settings.pinnedFrames?.find((frame) => frame.nodeId === sourceId)?.seconds; +} + +/** Keyframe time for a saved reference, in the backend's milliseconds; undefined for every other role. */ +export function canvasReferenceFrameTime( + settings: Pick | undefined, + sourceKind: string | undefined, + ref: { binding: string; source: { id?: string } | { assetId: string } }, +): number | undefined { + const sourceId = ref.binding === "follow_current" && "id" in ref.source ? ref.source.id : undefined; + const seconds = pinnedFrameSeconds(settings, sourceKind, sourceId); + return seconds === undefined ? undefined : Math.round(seconds * 1000); } /** Canvas slot assignment for a saved reference. The backend stores this role. */ @@ -331,7 +361,7 @@ export function canvasReferenceRole( settings: | Pick< GenerationSettings, - "videoMode" | "firstFrameNodeId" | "lastFrameNodeId" + "videoMode" | "firstFrameNodeId" | "lastFrameNodeId" | "pinnedFrames" > | undefined, sourceKind: string | undefined, @@ -340,8 +370,9 @@ export function canvasReferenceRole( role?: string | null; source: { id?: string } | { assetId: string }; }, -): "reference" | "first_frame" | "last_frame" | "continuation" | "control" { +): "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe" { const sourceId = "id" in ref.source ? ref.source.id : undefined; + if (canvasReferenceFrameTime(settings, sourceKind, ref) !== undefined) return "keyframe"; if (settings?.videoMode === "continuation" && sourceKind === "video") { return "continuation"; } @@ -734,9 +765,24 @@ export function backendBlocker( return tNow("errors.rules.controlDuration", { low, high }); } } + const keyframes = references.filter((item) => item.role === "keyframe"); + if (keyframes.length) { + // Keyframes are timeline guides beside the reference pictures, with their own limit. + const limit = rules.maxKeyframes ?? 0; + if (!limit) return tNow("errors.rules.keyframeUnsupported"); + if (keyframes.length > limit) return tNow("errors.rules.keyframeCount", { limit }); + // A guide is pinned to one output frame (24 per second), so times are compared as the frames they land on. + const frames = keyframes.map((item) => keyframeFrame(item.seconds ?? 0)); + if (frames.some((frame) => frame >= Math.round(settings.durationSeconds * KEYFRAME_FPS))) + return tNow("errors.rules.keyframeTime", { seconds: settings.durationSeconds }); + if (new Set(frames).size !== frames.length) return tNow("errors.rules.keyframeDuplicate"); + if (!references.some((item) => item.role === "reference" && ["image", "video"].includes(String(item.node.data.kind)))) + return tNow("errors.rules.keyframeReference"); + } const count = (kind: string) => references.filter( - (item) => item.role !== "continuation" && item.role !== "control" && item.node.data.kind === kind, + (item) => + item.role !== "continuation" && item.role !== "control" && item.role !== "keyframe" && item.node.data.kind === kind, ).length; for (const kind of ["image", "video", "audio"] as const) { const limit = availabilityInputLimit(config, profile, kind); @@ -759,22 +805,29 @@ export function backendBlocker( return null; } +/** H3 output rate: a keyframe time is pinned to one of these frames. Mirrors rule_facts.keyframe_frame. */ +export const KEYFRAME_FPS = 24; +export const keyframeFrame = (seconds: number) => + Math.round((Math.round(seconds * 1000) * KEYFRAME_FPS) / 1000); + /** The same budget applies to following nodes, pinned assets and expanded subjects. */ export function referenceBudgetIssue( sources: readonly CanvasNode[], config: ModelConfig, settings?: GenerationSettings, ) { - const usable = settings - ? backendReferences(settings, sources, config) - .filter((ref) => ref.role !== "continuation") - .map((ref) => ref.node) + const sent = settings + ? backendReferences(settings, sources, config).filter((ref) => ref.role !== "continuation") + : undefined; + // Keyframes are uploaded as timeline guides: their bytes count, but not toward reference counts or lengths. + const usable = sent + ? sent.filter((ref) => ref.role !== "keyframe").map((ref) => ref.node) : sources.flatMap((node) => node.type === "subject" ? subjectReferenceNodes(node) : [node], ); let total = 0; const seen = new Set(); - for (const source of usable) { + for (const source of sent ? sent.map((ref) => ref.node) : usable) { const key = `${source.id}:${source.type}:${source.data.src ?? source.data.text ?? ""}`; if (seen.has(key)) continue; seen.add(key); diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 0910201d6..d5366683f 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -429,6 +429,18 @@ export function NodeComposer({ const frameCandidates = incomingNodes.filter( (node) => node.data.kind === "image", ); + // H3 reference mode: any connected image can also be pinned at a moment of the output. + // The boxes stay while a time is set, also after a change to a model or mode without keyframes: + // otherwise the blocker would ask to clear times that nothing on screen can clear. + const pinnableFrames = + mode === "video" && + backend && + frameCandidates.length > 0 && + (settings.videoMode ?? "reference") === "reference" && + ((config?.inputRules.maxKeyframes ?? 0) > 0 || + frameCandidates.some((node) => + settings.pinnedFrames?.some((frame) => frame.nodeId === node.id), + )); const serviceSeconds = backendDurations(config); const duration = backend && mode === "video" @@ -694,6 +706,57 @@ export function NodeComposer({ )} + {pinnableFrames && ( +
+ {t("generation.keyframes.title")} + {frameCandidates.map((node) => { + const pinned = settings.pinnedFrames?.find((frame) => frame.nodeId === node.id); + const usable = node.data.src && node.data.assetState !== "missing"; + const name = node.data.title || t("generation.keyframes.untitled"); + return ( + + ); + })} + {!!settings.pinnedFrames?.length && ( + // The service rejects cache acceleration with guides, so guided requests always ask for lossless. + {t("generation.keyframes.lossless")} + )} +
+ )} {referenceVisibility.showStrip && (
+ record(frame) && + nonempty(frame.nodeId) && + finite(frame.seconds) && + Number(frame.seconds) >= 0, + ))) && (value.audioCreationType === undefined || value.audioCreationType === "audio" || value.audioCreationType === "music") && diff --git a/src/canvas/model.ts b/src/canvas/model.ts index 82068db8e..c9f2d8821 100644 --- a/src/canvas/model.ts +++ b/src/canvas/model.ts @@ -64,6 +64,8 @@ export interface GenerationSettings { firstFrameNodeId?: string; lastFrameNodeId?: string; frameSlotsInitialized?: boolean; + /** Reference mode on H3: connected images pinned at a moment of the output (seconds from its start). */ + pinnedFrames?: { nodeId: string; seconds: number }[]; audioCreationType?: "audio" | "music"; audioMode?: "unified" | "tts"; voiceName?: string; @@ -1215,5 +1217,20 @@ export function mapSettingsNodeReferences( if (after === undefined) delete next[key]; else next[key] = after; } + if (settings.pinnedFrames?.length) { + // A time whose picture is not part of the copy has nothing to pin and is dropped. + const pinned = settings.pinnedFrames.flatMap((frame) => { + const nodeId = resolve(frame.nodeId); + return nodeId === undefined ? [] : [{ ...frame, nodeId }]; + }); + const unchanged = + pinned.length === settings.pinnedFrames.length && + pinned.every((frame, index) => frame.nodeId === settings.pinnedFrames![index]!.nodeId); + if (!unchanged) { + if (next === settings) next = { ...settings }; + if (pinned.length) next.pinnedFrames = pinned; + else delete next.pinnedFrames; + } + } return next; } diff --git a/src/canvas/nodeActionWorkflow.ts b/src/canvas/nodeActionWorkflow.ts index 9b53f01b0..0ff86198a 100644 --- a/src/canvas/nodeActionWorkflow.ts +++ b/src/canvas/nodeActionWorkflow.ts @@ -9,9 +9,24 @@ import { type ResultSource, } from "./linkedResults.ts"; import { tNow } from "../i18n/messages.ts"; -import { createNode, type CanvasDocument } from "./model.ts"; +import { createNode, type CanvasDocument, type CanvasNode } from "./model.ts"; /** Source toolbar action creates a new connected draft; generation later fills that draft. */ +/** + * Whether a clip can be continued from the service's own cached latents: only one that the same model + * configuration generated. An upload, an edit or another model's clip is extended as a reference video. + */ +export function continuesOwnClip( + source: Pick, + modelConfigId: string | undefined, +): boolean { + return ( + Boolean(modelConfigId) && + source.data.generationProvenance?.source === "generated" && + source.data.settings?.modelConfigId === modelConfigId + ); +} + export function createVideoExtensionDraft( document: CanvasDocument, source: Readonly, diff --git a/src/canvas/nodes.css b/src/canvas/nodes.css index 37a241348..2e8fd17e5 100644 --- a/src/canvas/nodes.css +++ b/src/canvas/nodes.css @@ -647,6 +647,54 @@ .cw-frame-last { order: 2; } +.cw-keyframes { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding-bottom: 6px; +} +.cw-keyframes-title, +.cw-keyframes-note { + flex: 0 0 100%; + font-size: 12px; + opacity: 0.7; +} +.cw-keyframe { + display: flex; + align-items: center; + gap: 6px; + padding: 2px 8px 2px 2px; + border: 1px solid #ffffff0a; + border-radius: 9px; + background: #ffffff05; + color: #bfc0c9; + font-size: 12px; +} +.cw-keyframe.is-pinned { + border-color: #9b93f4; +} +.cw-keyframe:focus-within { + outline: 2px solid #9b93f4; + outline-offset: 2px; +} +.cw-keyframe .cw-frame-thumbnail { + flex: 0 0 36px; + width: 36px; + height: 36px; + border-radius: 7px; + overflow: hidden; +} +.cw-workspace .cw-composer .cw-keyframe input { + width: 7em; /* room for the English placeholder */ + min-width: 0; + padding: 2px 4px; + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-variant-numeric: tabular-nums; +} .cw-frame-unavailable { border-color: #967052; } diff --git a/src/canvas/workspace/useWorkspaceEditor.ts b/src/canvas/workspace/useWorkspaceEditor.ts index 37c20a4d8..a59ecff46 100644 --- a/src/canvas/workspace/useWorkspaceEditor.ts +++ b/src/canvas/workspace/useWorkspaceEditor.ts @@ -11,7 +11,7 @@ import { workspaceProjection } from "../../backend/workspace"; import { lockedNodeIds } from "../hierarchy"; import { captureEditorSource, validateNodeActionSource, type LinkedMediaResult, type ResultSource } from "../linkedResults"; import { type CanvasDocument, type CanvasNode, type CanvasNodeData } from "../model"; -import { createVideoExtensionDraft } from "../nodeActionWorkflow"; +import { continuesOwnClip, createVideoExtensionDraft } from "../nodeActionWorkflow"; import { getNodeGenerationSettings } from "../NodeComposer"; import { resourceFromNode } from "../operations"; @@ -286,12 +286,14 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) { return; } // A model that continues its own clips (H3) extends seamlessly from cached latents. + // Any other clip has no latents on the service and stays a reference video. const draft = next.document.nodes.find((node) => node.id === next.ids[0]); const settings = draft && getNodeGenerationSettings(draft, backendCatalog.models); if ( draft && settings && + continuesOwnClip(source, settings.modelConfigId) && backendModel( settings, backendCatalog.models, diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 62bccdf6a..bd0d05dbe 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4361,6 +4361,12 @@ "missing_object", "reference_invalid", "image_quality_unsupported", + "keyframe_unsupported", + "keyframe_mode", + "keyframe_kind", + "keyframe_count", + "keyframe_needs_reference", + "keyframe_time", "bigmodel_video_model", "bigmodel_video_output", "bigmodel_video_image", @@ -6049,11 +6055,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -8173,6 +8194,13 @@ "title": "Maxaudios", "type": "integer" }, + "maxKeyframes": { + "default": 0, + "description": "Maximum pictures that can be pinned at chosen moments of a generated video; omitted when unsupported.", + "minimum": 0, + "title": "Maxkeyframes", + "type": "integer" + }, "imageBytes": { "description": "Maximum bytes per reference image.", "minimum": 0, @@ -10988,11 +11016,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -12748,11 +12791,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -13079,11 +13137,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "asset": { "$ref": "#/$defs/AssetRef", "description": "Immutable asset version." @@ -22758,6 +22831,12 @@ "missing_object", "reference_invalid", "image_quality_unsupported", + "keyframe_unsupported", + "keyframe_mode", + "keyframe_kind", + "keyframe_count", + "keyframe_needs_reference", + "keyframe_time", "bigmodel_video_model", "bigmodel_video_output", "bigmodel_video_image", @@ -24497,11 +24576,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -26717,6 +26811,13 @@ "title": "Maxaudios", "type": "integer" }, + "maxKeyframes": { + "default": 0, + "description": "Maximum pictures that can be pinned at chosen moments of a generated video; omitted when unsupported.", + "minimum": 0, + "title": "Maxkeyframes", + "type": "integer" + }, "imageBytes": { "description": "Maximum bytes per reference image.", "minimum": 0, @@ -29613,11 +29714,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -31428,11 +31544,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -31769,11 +31900,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "asset": { "$ref": "#/$defs/AssetRef", "description": "Immutable asset version." diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 8b7e370a4..67e74ba96 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -483,7 +483,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "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"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "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"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -820,6 +820,7 @@ export interface InputRulesInput extends ContractInput { readonly maxImages: number; readonly maxVideos: number; readonly maxAudios: number; + readonly maxKeyframes?: number; readonly imageBytes: number; readonly videoBytes: number; readonly audioBytes?: number | null; @@ -1294,7 +1295,8 @@ export interface ReferenceAddCommandOperationInput { export interface ReferenceBaseInput extends ProjectEntityInput { readonly targetSpecId: string; - readonly role?: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role?: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly order?: number; readonly active?: boolean; } @@ -1339,7 +1341,8 @@ export interface ReferenceWriteInput extends ContractInput { export interface ResolvedReferenceInput extends ContractInput { readonly referenceId: string; - readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly asset: AssetRefInput; readonly metadata: MediaMetadataInput; readonly sourceVersion?: ObjectVersionInput | null; @@ -2376,7 +2379,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "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"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "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"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -2713,6 +2716,7 @@ export interface InputRules extends Contract { readonly maxImages: number; readonly maxVideos: number; readonly maxAudios: number; + readonly maxKeyframes?: number; readonly imageBytes: number; readonly videoBytes: number; readonly audioBytes?: number | null; @@ -3186,7 +3190,8 @@ export interface ReferenceAddCommandOperation { export interface ReferenceBase extends ProjectEntity { readonly targetSpecId: string; - readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly order: number; readonly active: boolean; } @@ -3231,7 +3236,8 @@ export interface ReferenceWrite extends Contract { export interface ResolvedReference extends Contract { readonly referenceId: string; - readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly asset: AssetRef; readonly metadata: MediaMetadata; readonly sourceVersion: ObjectVersion | null; diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index 7c68ae9f2..105f4cc5e 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -162,6 +162,13 @@ export const errors = { "errors.rules.controlDuration": "The control video must be {low}–{high} seconds", "errors.rules.continuationSource": "Continuation needs a video generated by the current H3 service as the previous segment.", + "errors.rules.keyframeUnsupported": + "This model does not support keyframes. Clear the times on the images or choose another model.", + "errors.rules.keyframeCount": "Up to {limit} keyframes.", + "errors.rules.keyframeTime": "A keyframe must be earlier than the end of the video ({seconds} s).", + "errors.rules.keyframeDuplicate": "Two keyframes cannot land on the same frame. Keep their times at least 1/24 second apart.", + "errors.rules.keyframeReference": + "Keyframes also need at least one unpinned reference image or a reference video.", "errors.rules.serviceInputLimit": "Up to {limit} {kind} inputs; currently {current}.", "errors.rules.referenceLimit": "Too many {kind} references for this model (limit: {limit}).", diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index 948dc8969..96e8a5bfa 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -179,6 +179,14 @@ export const generation = { "generation.lyricsReferencePlaceholder": "Lyrics (optional; leave blank for instrumental music). Follow the sections and phrases of the reference, with each section tag on its own line, for example:\n[verse]\nRain falls by the window\n[chorus]\nLet the melody answer what I cannot say", + "generation.keyframes.title": + "Keyframes: give an image a time and the video shows that picture at that moment", + "generation.keyframes.placeholder": "Unpinned", + "generation.keyframes.unit": "s", + "generation.keyframes.untitled": "Untitled image", + "generation.keyframes.time": "Second at which to pin “{title}”", + "generation.keyframes.lossless": + "With keyframes the video is generated at lossless quality, which takes longer.", "generation.frame.title": "First and last frame references", "generation.frame.first": "First frame", "generation.frame.last": "Last frame", diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index 652cb0cff..2941324cf 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -115,6 +115,11 @@ export const errors = { "errors.rules.controlDuration": "控制视频需要 {low}–{high} 秒", "errors.rules.continuationSource": "接续需要连接一段由当前 H3 服务生成的视频作为上一段。", + "errors.rules.keyframeUnsupported": "当前模型不支持指定帧,请清除图片上的时间或更换模型。", + "errors.rules.keyframeCount": "最多指定 {limit} 个关键帧。", + "errors.rules.keyframeTime": "关键帧的时间必须早于视频结束({seconds} 秒)。", + "errors.rules.keyframeDuplicate": "两个关键帧不能落在同一帧上,请把时间至少错开 1/24 秒。", + "errors.rules.keyframeReference": "指定帧生成还需要至少一张不指定时间的参考图片或一段参考视频。", "errors.rules.referenceLimit": "参考{kind}超过当前模型上限({limit} 个)。", "errors.rules.serviceInputLimit": "最多支持 {limit} 个{kind},当前为 {current} 个。", "errors.rules.referenceFileSize": "参考文件超过当前模型的大小限制", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index d7a1bc86a..a7e338022 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -164,6 +164,12 @@ export const generation = { "generation.lyricsReferencePlaceholder": "歌词(可选,留空生成纯音乐)。按参照音乐的段落和乐句填写,段落标签单独成一行,例如:\n[verse]\n雨落在窗前\n[chorus]\n说不出的话,让旋律回答", + "generation.keyframes.title": "指定帧:给图片填一个时间,生成的视频会在那一刻出现这个画面", + "generation.keyframes.placeholder": "不指定", + "generation.keyframes.unit": "秒", + "generation.keyframes.untitled": "未命名图片", + "generation.keyframes.time": "把“{title}”钉在第几秒", + "generation.keyframes.lossless": "指定关键帧后会以无损质量生成,耗时更长。", "generation.frame.title": "首尾帧参考", "generation.frame.first": "首帧", "generation.frame.last": "尾帧", diff --git a/tests/backendRules.test.ts b/tests/backendRules.test.ts index e53df21c2..dcb5709d0 100644 --- a/tests/backendRules.test.ts +++ b/tests/backendRules.test.ts @@ -124,6 +124,30 @@ test("MAGI-2 keeps ordinary image references, optional media prompts and native assert.ok(referenceBudgetIssue([sound], magi, settings)); }); +test("keyframe pictures share the request byte budget but not the reference counts", () => { + const megabyte = 1024 * 1024; + const guided = config("video", { + maxImages: 1, maxKeyframes: 8, imageBytes: 30 * megabyte, requestBytes: 64 * megabyte, + videoModes: ["first_frame", "reference", "continuation"], + }); + const sized = (bytes: number) => { + const node = media("image"); + node.data.byteSize = bytes; + return node; + }; + const costume = sized(20 * megabyte), left = sized(25 * megabyte), right = sized(25 * megabyte); + const pin = (...nodes: CanvasNode[]) => ({ + ...video({ videoMode: "reference" }), + modelConfigId: guided.id, + pinnedFrames: nodes.map((node, index) => ({ nodeId: node.id, seconds: index + 1 })), + }); + // One reference picture plus a keyframe fits, and the keyframe is not a second reference image. + assert.equal(referenceBudgetIssue([costume, left], guided, pin(left)), null); + // The guides are uploaded too: two of them take the request over its 64 MB. + setActiveLocale("zh-CN"); + assert.ok(referenceBudgetIssue([costume, left, right], guided, pin(left, right))); +}); + test("SAM stays tool-only in both media categories and legacy vision configurations", () => { for (const kind of ["image", "video"] as const) { const sam = { diff --git a/tests/keyframeReferences.test.ts b/tests/keyframeReferences.test.ts new file mode 100644 index 000000000..bdc3ecf4f --- /dev/null +++ b/tests/keyframeReferences.test.ts @@ -0,0 +1,78 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + canvasReferenceFrameTime, + canvasReferenceRole, + keyframeFrame, + pinnedFrameSeconds, +} from "../src/backend/rules.ts"; +import { mapSettingsNodeReferences } from "../src/canvas/model.ts"; +import { continuesOwnClip } from "../src/canvas/nodeActionWorkflow.ts"; + +const follow = (id: string) => ({ binding: "follow_current", role: "reference", source: { id } }); + +test("a pinned image becomes a keyframe at its time in milliseconds", () => { + const settings = { videoMode: "reference" as const, pinnedFrames: [{ nodeId: "pose", seconds: 1.25 }] }; + assert.equal(canvasReferenceRole(settings, "image", follow("pose")), "keyframe"); + assert.equal(canvasReferenceFrameTime(settings, "image", follow("pose")), 1250); + // Other connected images stay ordinary references and carry no time. + assert.equal(canvasReferenceRole(settings, "image", follow("costume")), "reference"); + assert.equal(canvasReferenceFrameTime(settings, "image", follow("costume")), undefined); +}); + +test("pins apply to images in reference mode only", () => { + const pinnedFrames = [{ nodeId: "clip", seconds: 2 }]; + assert.equal(pinnedFrameSeconds({ videoMode: "reference", pinnedFrames }, "video", "clip"), undefined); + for (const videoMode of ["first-last", "continuation", "control"] as const) + assert.equal(pinnedFrameSeconds({ videoMode, pinnedFrames }, "image", "clip"), undefined); + // An unset mode is reference mode, as everywhere else on the canvas. + assert.equal(pinnedFrameSeconds({ pinnedFrames }, "image", "clip"), 2); + assert.equal(canvasReferenceRole({ videoMode: "control", pinnedFrames }, "video", follow("clip")), "control"); +}); + +test("a pinned asset version is not tied to a canvas node, so it keeps its stored role", () => { + const settings = { videoMode: "reference" as const, pinnedFrames: [{ nodeId: "pose", seconds: 1 }] }; + const pinnedAsset = { binding: "pinned", role: "reference", source: { assetId: "pose" } }; + assert.equal(canvasReferenceFrameTime(settings, "image", pinnedAsset), undefined); + assert.equal(canvasReferenceRole(settings, "image", pinnedAsset), "reference"); +}); + +test("times are compared as the output frames they land on", () => { + // 24 frames per second: 1.00 s and 1.02 s are the same frame, 1.05 s is the next one. + assert.equal(keyframeFrame(1), 24); + assert.equal(keyframeFrame(1.02), 24); + assert.equal(keyframeFrame(1.05), 25); + // The same rounding as the backend, which converts whole milliseconds. + assert.equal(keyframeFrame(4.4583), Math.round((4458 * 24) / 1000)); +}); + +test("a copied node keeps its keyframe times on the copied pictures", () => { + const settings = { + videoMode: "reference" as const, + firstFrameNodeId: "first", + pinnedFrames: [{ nodeId: "pose", seconds: 1.25 }, { nodeId: "left-behind", seconds: 3 }], + }; + const copies: Record = { first: "first-copy", pose: "pose-copy" }; + const mapped = mapSettingsNodeReferences(settings as never, (id) => copies[id]); + // A time whose picture is not in the copy has nothing to pin. + assert.deepEqual(mapped.pinnedFrames, [{ nodeId: "pose-copy", seconds: 1.25 }]); + assert.equal(mapped.firstFrameNodeId, "first-copy"); + assert.deepEqual(settings.pinnedFrames.map((frame) => frame.nodeId), ["pose", "left-behind"]); + // Nothing to remap leaves the settings object itself. + const same = { videoMode: "reference" as const, pinnedFrames: [{ nodeId: "pose", seconds: 1 }] }; + assert.equal(mapSettingsNodeReferences(same as never, (id) => id), same); + const none = mapSettingsNodeReferences(same as never, () => undefined); + assert.equal(none.pinnedFrames, undefined); +}); + +test("extend continues only a clip the same model configuration generated", () => { + const clip = (source: string, modelConfigId?: string) => + ({ data: { generationProvenance: { source }, settings: modelConfigId ? { modelConfigId } : undefined } }) as never; + assert.equal(continuesOwnClip(clip("generated", "pika"), "pika"), true); + // An upload, an edited clip and another model's clip have no latents on this service. + assert.equal(continuesOwnClip(clip("upload"), "pika"), false); + assert.equal(continuesOwnClip(clip("edited", "pika"), "pika"), false); + assert.equal(continuesOwnClip(clip("generated", "other"), "pika"), false); + assert.equal(continuesOwnClip(clip("generated", "pika"), undefined), false); + assert.equal(continuesOwnClip({ data: {} } as never, "pika"), false); +}); diff --git a/tests/test_agent_metadata.py b/tests/test_agent_metadata.py index db301a44a..f4b9416f4 100644 --- a/tests/test_agent_metadata.py +++ b/tests/test_agent_metadata.py @@ -95,7 +95,7 @@ async def parameters(**options): spec = await parameters(path='payload.spec', modelConfigId=config['id']) assert 'parameters' in spec['required'] compact = await parameters(path='payload.spec.parameters', modelConfigId=config['id']) - assert compact['fields']['videoMode']['enum'] == ['reference', 'control'] + assert compact['fields']['videoMode']['enum'] == ['reference', 'control', 'continuation'] assert 'default' not in compact['fields']['videoMode'] assert 'videoMode' in compact['required'] assert compact['fields']['generateAudio']['enum'] == [True] diff --git a/tests/test_capability_input_projection.py b/tests/test_capability_input_projection.py index fe9e99652..41a749408 100644 --- a/tests/test_capability_input_projection.py +++ b/tests/test_capability_input_projection.py @@ -131,6 +131,17 @@ def test_continuation_does_not_claim_video_upload_but_honors_route_pause(service assert availability.decision(config, request)['status'] == 'unknown' +def test_a_keyframe_is_not_counted_as_a_reference_image(service): + configs, saved, state, availability = service + config = {**private(configs, saved), 'kind': 'video', 'protocol': 'vllm_omni'} + spec = SimpleNamespace(kind='video', parameters=SimpleNamespace(videoMode='reference')) + guide = SimpleNamespace(asset=SimpleNamespace(kind='image'), transmission='content', role='keyframe') + ordinary = SimpleNamespace(asset=SimpleNamespace(kind='image'), transmission='content', role='reference') + request = generation_request(config, spec, [ordinary, guide, guide]) + # The guides travel beside the request's declared inputs; only the reference picture is one of them. + assert dict(request.input_counts) == {'text': 1, 'image': 1, 'reference_image': 1} + + @pytest.mark.parametrize('route,unavailable', [ ({'method': 'POST', 'path': '/v1/videos', 'transport': 'http', 'exposure': 'disabled'}, True), ({'method': 'GET', 'path': '/v1/videos', 'transport': 'http', 'exposure': 'disabled'}, False), diff --git a/tests/test_fasth3_continuation.py b/tests/test_fasth3_continuation.py new file mode 100644 index 000000000..f3cd42a2c --- /dev/null +++ b/tests/test_fasth3_continuation.py @@ -0,0 +1,115 @@ +"""Latent continuation (continue_from) on the FastH3-style Ref2VA request path.""" +import asyncio +import json +from email.parser import BytesParser +from email.policy import default +from types import SimpleNamespace +from uuid import uuid4 + +import httpx +import pytest + +from opendirector.domain.generation import GenerationError +from opendirector.domain.input_rules import input_rules +from opendirector.domain.projects import ProjectError +from opendirector.integrations.fasth3 import generation_fields, video_parameters +from opendirector.integrations.providers import GenerationProviders + + +pytestmark = pytest.mark.cpu + +CONFIG = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', + 'videoAdapter': 'fasth3', 'apiKey': '', 'authMode': 'none'} + + +@pytest.mark.parametrize('adapter', ['fasth3', 'fasth3_dual']) +def test_every_fasth3_shaped_model_offers_continuation(adapter): + assert 'continuation' in input_rules({**CONFIG, 'videoAdapter': adapter})['videoModes'] + + +def test_fields_name_the_source_job_and_keep_its_canvas(): + fields, extra = generation_fields({'duration': 5, 'size': '832x480'}, continue_from='video_gen_1', continue_size=(768, 1344)) + assert extra['continue_from'] == 'video_gen_1' and extra['task'] == 'ref2va' + # Latents cannot change size: the source canvas replaces the panel's size. + assert fields['size'] == '768x1344' and fields['num_inference_steps'] == 8 + assert 'continue_from' not in generation_fields({'duration': 5})[1] + + +def test_the_capability_check_sees_the_size_the_continuation_sends(): + """The check runs before the job has an ID to continue from, and must still see the source's size.""" + from opendirector.integrations.generation_capability_parameters import generation_capability_parameters + config = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', 'videoAdapter': 'fasth3'} + parameters = {'duration': 5, 'size': '832x480'} + checked = generation_capability_parameters(config, 'video', parameters, video_mode='continuation', continue_size=(768, 1344)) + sent, _ = generation_fields(parameters, continue_from='video_gen_1', continue_size=(768, 1344)) + assert checked['size'] == sent['size'] == '768x1344' + + +def fixture(source_job, **source_meta): + video = {'id': str(uuid4()), 'name': 'part1.mp4', 'kind': 'video', 'type': 'video/mp4', 'fingerprint': 'fixture', + 'durationMs': 5167, 'width': 768, 'height': 1344, 'generationTaskId': 'task-1', **source_meta} + picture = {'id': str(uuid4()), 'name': 'costume.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + assets = {video['id']: (b'source-video-bytes', video), picture['id']: (b'\x89PNG\r\n\x1a\nfixture', picture)} + store = SimpleNamespace(asset=lambda owner, key: assets[key], generation_task=lambda owner, key: source_job) + task = {'kind': 'video', 'projectId': 'owner', 'prompt': '她缓缓落地', 'referenceIds': list(assets), 'videoMode': 'continuation'} + task['parameters'] = video_parameters(task, {key: pair[1] for key, pair in assets.items()}, duration_seconds=5) + return store, task + + +def run(store, task, handle): + async def submitted(value): + assert value == 'video_gen_2' + provider = GenerationProviders(store, httpx.MockTransport(handle), poll_interval=0) + return asyncio.run(provider.generate(CONFIG, task, submitted)) + + +SOURCE_JOB = {'kind': 'video', 'status': 'succeeded', 'externalTaskId': 'video_gen_1', 'baseURL': CONFIG['url'], 'model': CONFIG['modelId']} + + +def test_the_wire_carries_the_job_id_and_not_the_source_video(): + store, task = fixture(SOURCE_JOB) + seen = {} + + def handle(request): + if request.method == 'POST': + prefix = 'Content-Type: ' + request.headers['content-type'] + '\r\n\r\n' + message = BytesParser(policy=default).parsebytes(prefix.encode() + request.content) + for part in message.iter_parts(): + seen.setdefault(part.get_param('name', header='content-disposition'), []).append(part.get_payload(decode=True)) + return httpx.Response(200, json={'id': 'video_gen_2'}) + if request.url.path.endswith('/content'): + return httpx.Response(200, content=b'generated') + return httpx.Response(200, json={'status': 'completed'}) + + assert run(store, task, handle) == ('mp4', b'generated') + extra = json.loads(seen['extra_params'][0]) + assert extra['continue_from'] == 'video_gen_1' and extra['task'] == 'ref2va' + assert seen['size'] == [b'768x1344'] and seen['num_inference_steps'] == [b'8'] + # The picture still travels as a reference; the source clip stays server-side. + assert len(seen['input_references']) == 1 and b'source-video-bytes' not in b''.join(seen['input_references']) + + +def test_an_uploaded_or_foreign_clip_cannot_be_continued(): + for job in ({**SOURCE_JOB, 'model': 'another-model'}, {**SOURCE_JOB, 'status': 'failed'}): + store, task = fixture(job) + with pytest.raises(ProjectError, match='不能接续'): + run(store, task, lambda request: pytest.fail('nothing may be sent')) + store, task = fixture(SOURCE_JOB, generationTaskId=None) + with pytest.raises(ProjectError, match='不能接续'): + run(store, task, lambda request: pytest.fail('nothing may be sent')) + + +@pytest.mark.parametrize('answer', [ + httpx.Response(400, json={'error': {'message': 'continue_from job video_gen_1 has no cached latents'}}), + None, +]) +def test_a_clip_the_service_no_longer_holds_is_explained(answer): + store, task = fixture(SOURCE_JOB) + + def handle(request): + if request.method == 'POST': + return answer or httpx.Response(200, json={'id': 'video_gen_2'}) + return httpx.Response(200, json={'status': 'failed', 'error': {'message': 'continue_from: cached latents were evicted'}}) + + with pytest.raises(GenerationError, match='接续缓存'): + run(store, task, handle) diff --git a/tests/test_fasth3_video_edit.py b/tests/test_fasth3_video_edit.py new file mode 100644 index 000000000..59f07ff0d --- /dev/null +++ b/tests/test_fasth3_video_edit.py @@ -0,0 +1,155 @@ +"""Latent-mask editing for Ref2VA-only H3 services (FastH3 Omni and few-step adapters served the same way).""" +import asyncio +import json + +import pytest + +from opendirector.domain.capabilities import EditMask, MediaResult, VideoEditRequest +from opendirector.integrations.model_adapters import FastH3VideoEdit, VllmOmniVideo, adapter_for, capabilities_of +from opendirector.integrations.vllm_omni import capability_parameters + + +pytestmark = pytest.mark.cpu + +CONFIG = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', + 'videoAdapter': 'fasth3', 'apiKey': '', 'authMode': 'none'} + + +@pytest.mark.parametrize('adapter', ['fasth3', 'fasth3_dual']) +def test_fasth3_shaped_models_provide_local_redraw_only(adapter): + config = {**CONFIG, 'videoAdapter': adapter} + assert isinstance(adapter_for(config), FastH3VideoEdit) + # A Ref2VA service has no text-to-video or first-frame task, so only editing is offered to tools. + assert capabilities_of(config) == {'video.edit'} + assert capabilities_of({**CONFIG, 'videoAdapter': 'minimax_h3'}) == VllmOmniVideo.capabilities + + +def recorded(monkeypatch, adapter): + """Run the adapter without a service: every submitted request is kept, and each answers with its own draft.""" + calls, reported = [], [] + + async def job(config, fields, files, submitted): + calls.append((fields, files)) + if submitted: + await submitted(f'job-{len(calls)}') + return MediaResult(f'draft-{len(calls)}'.encode(), 'mp4') + + async def submitted(external_id): + reported.append(external_id) + + monkeypatch.setattr(adapter, '_job', job) + monkeypatch.setattr(adapter, '_conformed', lambda source, *_: source) + monkeypatch.setattr(adapter, '_source_still', lambda source, mask: b'source-still-of-' + source) + monkeypatch.setattr(adapter, '_last_edited_frame', lambda clip, end: b'last-frame-before-%r-of-' % end + clip) + return calls, reported, submitted + + +def test_edit_request_is_ref2va_on_the_fixed_schedule_with_a_source_frame_as_reference(monkeypatch): + adapter = FastH3VideoEdit() + calls, _, submitted = recorded(monkeypatch, adapter) + checked = capability_parameters(*adapter.edit_parameters(5, 768, 1344)) + asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='把背景换成月夜', source=b'video', seconds=5, width=768, height=1344, + picture=EditMask(1.0, region=((0.0, 1.0),)), avoid='凳子'), submitted=submitted)) + fields, files = calls[0] + extra = json.loads(fields['extra_params']) + assert extra == {'task': 'ref2va', 'audio_flow_shift': 3} + assert (fields['num_inference_steps'], fields['guidance_scale'], fields['num_frames'], fields['size']) == ('8', '1', '124', '768x1344') + # The checked parameters are the transmitted ones. + sent = {key: value for key, value in fields.items() if key not in {'model', 'prompt', 'extra_params'}} | extra + assert {key: str(value) for key, value in checked.items() if key not in {'width', 'height'}} == {key: str(value) for key, value in sent.items()} + assert fields['prompt'] == ' 把背景换成月夜' and 'negative_prompt' not in fields + assert [name for name, _ in files] == ['input_references', 'source_video', 'video_noise_mask', 'audio_noise_mask'] + assert files[0][1][1] == b'source-still-of-video' + assert json.loads(files[2][1][1]) == [[0.0, 1.0]] and json.loads(files[3][1][1]) == 0.0 + + +def test_a_boxed_redraw_runs_again_with_its_own_last_edited_frame_as_reference(monkeypatch): + """A Ref2VA model opens the clip on its reference picture, so the edit must already be in that picture.""" + adapter = FastH3VideoEdit() + calls, reported, submitted = recorded(monkeypatch, adapter) + result = asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='moon', source=b'video', seconds=5, width=768, height=1344, + picture=EditMask(1.0, region=((1.0, 0.0),))), submitted=submitted)) + assert [files[0][1][1] for _, files in calls] == [b'source-still-of-video', b'last-frame-before-None-of-draft-1'] + # Apart from the reference picture the second request is the first one again, on the same source and mask. + assert calls[0][0] == calls[1][0] and calls[0][1][1:] == calls[1][1][1:] + assert result.data == b'draft-2' + # Both jobs are reported, so a cancel reaches whichever is running. + assert reported == ['job-1', 'job-2'] + + +def test_a_boxed_redraw_that_stops_early_takes_the_last_frame_it_covers(monkeypatch): + adapter = FastH3VideoEdit() + calls, _, submitted = recorded(monkeypatch, adapter) + asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='moon', source=b'video', seconds=5, width=768, height=1344, + picture=EditMask(1.0, region=((1.0, 0.0),), start=1.0, end=3.0)), submitted=submitted)) + assert calls[1][1][0][1][1] == b'last-frame-before-3.0-of-draft-1' + + +@pytest.mark.parametrize('mask', [EditMask(1.0, None, 1.0, 3.0), EditMask(1.0, None, 0.0, 2.5), EditMask(1.0, None), None], + ids=['span-inside', 'span-opens-clip', 'whole-clip', 'sound-only']) +def test_a_whole_frame_redraw_runs_once(monkeypatch, mask): + adapter = FastH3VideoEdit() + calls, _, submitted = recorded(monkeypatch, adapter) + result = asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='green dress', source=b'video', seconds=5, width=768, height=1344, + picture=mask, sound=EditMask(1.0)), submitted=submitted)) + assert len(calls) == 1 and result.data == b'draft-1' + assert calls[0][1][0][1][1] == b'source-still-of-video' + + +@pytest.fixture(scope='module') +def two_tone(tmp_path_factory): + """Two seconds at 24 fps: red for the first second, blue for the second, under three seconds of sound.""" + import shutil + import subprocess + if not shutil.which('ffmpeg'): + pytest.skip('FFmpeg is required to build the clip') + clip = tmp_path_factory.mktemp('edit') / 'clip.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=red:s=64x48:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=blue:s=64x48:r=24:d=1', + '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-filter_complex', '[0:v][1:v]concat=n=2:v=1:a=0[v]', + '-map', '[v]', '-map', '2:a', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', str(clip)], check=True) + return clip.read_bytes() + + +def colour(still): + from io import BytesIO + + from PIL import Image + red, _, blue = Image.open(BytesIO(still)).convert('RGB').getpixel((32, 24)) + return 'red' if red > 200 and blue < 60 else 'blue' if blue > 200 and red < 60 else (red, blue) + + +@pytest.mark.parametrize('mask, expected', [ + (None, 'red'), # nothing redrawn in the picture: the clip's first frame + (EditMask(1.0, ((1.0, 0.0),)), 'red'), # a boxed redraw starts from the first frame too + (EditMask(1.0, None, 1.0, 1.5), 'red'), # the clip opens on kept frames + (EditMask(1.0, None, 0.0, 1.0), 'blue'), # the span opens the clip: the first kept frame is frame 24 + (EditMask(1.0, None, None, 0.5), 'red'), # ... and here frame 12, still in the first second + (EditMask(1.0, None, 0.0, 2.0), 'red'), # the span runs to the clip's real end: nothing is kept after it + (EditMask(1.0, None, 0.0, 2.9), 'red'), # ... also when it ends inside the sound that outlasts the picture + (EditMask(1.0, None, 0.0, 47 / 24), 'blue'), # the very last frame is kept +], ids=['no-picture-mask', 'boxed', 'span-inside', 'span-opens-clip', 'short-opening-span', 'span-to-the-end', 'span-past-the-picture', 'last-frame-kept']) +def test_the_source_still_is_a_frame_the_edit_keeps(two_tone, mask, expected): + assert colour(FastH3VideoEdit._source_still(two_tone, mask)) == expected + + +def test_the_final_picture_is_found_when_the_sound_runs_longer(tmp_path): + import shutil + import subprocess + + from opendirector.media import processing as media + if not shutil.which('ffmpeg'): + pytest.skip('FFmpeg is required to build the clip') + clip = tmp_path / 'clip.mp4' + # One second of red, then one frame short of a second of blue, under three seconds of sound. + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=red:s=64x48:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=blue:s=64x48:r=24', + '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-filter_complex', '[1:v]trim=end_frame=23[b];[0:v][b]concat=n=2:v=1:a=0[v]', + '-map', '[v]', '-map', '2:a', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', str(clip)], check=True) + assert media.video_info(clip)['duration'] == pytest.approx(3, abs=0.1) + assert media.last_frame_time(clip) == pytest.approx(46 / 24) + from io import BytesIO + + from PIL import Image + red, green, blue = Image.open(BytesIO(FastH3VideoEdit._last_edited_frame(clip.read_bytes(), None))).convert('RGB').getpixel((32, 24)) + assert blue > 200 and red < 60 + red, green, blue = Image.open(BytesIO(FastH3VideoEdit._last_edited_frame(clip.read_bytes(), 0.5))).convert('RGB').getpixel((32, 24)) + assert red > 200 and blue < 60 diff --git a/tests/test_h3_keyframes.py b/tests/test_h3_keyframes.py new file mode 100644 index 000000000..b780cbd9c --- /dev/null +++ b/tests/test_h3_keyframes.py @@ -0,0 +1,281 @@ +"""Keyframes: pictures pinned at chosen moments of an H3 video, sent as timeline guides.""" +import asyncio +import json +from email.parser import BytesParser +from email.policy import default +from types import SimpleNamespace +from uuid import uuid4 + +import httpx +import pytest + +from opendirector.domain.creation.assets import AssetRef, MediaMetadata +from opendirector.domain.creation.generation import (ResolvedReference, VideoGenerationSpec, VideoParameters, + validate_generation) +from opendirector.domain.creation.models import ModelConfigPublic +from opendirector.domain.input_rules import input_rules +from opendirector.domain.projects import ProjectError +from opendirector.integrations.fasth3 import video_parameters +from opendirector.integrations.providers import GenerationProviders +from opendirector.integrations.reference_inputs import generation_references +from opendirector.integrations.vllm_omni import VllmOmniGeneration + + +pytestmark = pytest.mark.cpu + +PNG = b'\x89PNG\r\n\x1a\n' +OMNI = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', + 'videoAdapter': 'fasth3', 'apiKey': '', 'authMode': 'none'} + + +@pytest.mark.parametrize('adapter, expected', [('fasth3', 8), ('fasth3_dual', 8), ('minimax_h3', 8), ('standard', None)]) +def test_every_h3_adapter_declares_keyframes(adapter, expected): + assert input_rules({**OMNI, 'videoAdapter': adapter}).get('maxKeyframes') == expected + + +def model(**extra): + config = {'kind': 'video', 'url': 'http://model.test/v1', 'modelId': 'Pika-H3', 'connectionType': 'self_hosted', + 'protocol': 'vllm_omni', 'authMode': 'none', 'videoAdapter': 'fasth3', **extra} + return ModelConfigPublic(id=uuid4(), inputRules=input_rules(config), **config) + + +def picture(role='reference', time=None, kind='image', transmission='content'): + return ResolvedReference(referenceId=uuid4(), role=role, frameTimeMs=time, transmission=transmission, + asset=AssetRef(assetId=uuid4(), revision=1, fingerprint='sha256:' + '0' * 64, kind=kind), + metadata=MediaMetadata(mimeType='image/png' if kind == 'image' else 'video/mp4', size=10, width=32, height=24, + durationSeconds=None if kind == 'image' else 5)) + + +def spec(target, mode='reference', seconds=5): + return VideoGenerationSpec(id=uuid4(), projectId=uuid4(), kind='video', purpose='generation', modelConfigId=target.id, + prompt='A dancer', parameters=VideoParameters(videoMode=mode, durationSeconds=seconds)) + + +def test_submission_accepts_keyframes_beside_a_reference(): + omni = model() + validate_generation(spec(omni), omni, (picture(), picture('keyframe', 1250), picture('keyframe', 4583)), submitting=True) + # Keyframes are guides: nine reference pictures plus eight keyframes stay within both limits. + validate_generation(spec(omni), omni, (*[picture() for _ in range(9)], *[picture('keyframe', 100 * n) for n in range(8)]), submitting=True) + + +@pytest.mark.parametrize('references, message', [ + (lambda: (picture('keyframe', 1000),), '普通参考'), + (lambda: (picture(), picture('keyframe', None)), '时间点'), + (lambda: (picture(), picture('keyframe', 5000)), '早于视频结束'), + (lambda: (picture(), picture('keyframe', 1000), picture('keyframe', 1000)), '同一帧'), + # A guide is pinned to a frame: 1.00 s and 1.02 s are both frame 24, and 4.99 s rounds to the frame past the last. + (lambda: (picture(), picture('keyframe', 1000), picture('keyframe', 1020)), '同一帧'), + (lambda: (picture(), picture('keyframe', 4990)), '早于视频结束'), + (lambda: (picture(), *[picture('keyframe', 100 * n) for n in range(9)]), '最多指定 8 个'), +]) +def test_submission_rejects_invalid_keyframes(references, message): + omni = model() + with pytest.raises(ProjectError, match=message): + validate_generation(spec(omni), omni, references(), submitting=True) + + +def test_keyframe_bytes_count_toward_the_request(): + """Guides are uploaded with the request, so they share its byte budget with the reference pictures.""" + omni = model() + def sized(role, size, time=None): + return picture(role, time).model_copy(update={'metadata': MediaMetadata(mimeType='image/png', size=size, width=32, height=24)}) + megabyte = 1024 * 1024 + validate_generation(spec(omni), omni, (sized('reference', megabyte), *[sized('keyframe', 20 * megabyte, 100 * n) for n in range(7)]), + submitting=True) + with pytest.raises(ValueError, match='总大小超过'): + validate_generation(spec(omni), omni, (sized('reference', megabyte), *[sized('keyframe', 25 * megabyte, 100 * n) for n in range(7)]), + submitting=True) + + +def test_native_h3_request_size_includes_its_guides(): + """The native H3 request has a 64 MB budget; guides must not slip past it beside the data-URI inputs.""" + native = {**OMNI, 'videoAdapter': 'minimax_h3'} + megabyte = 1024 * 1024 + costume = {'id': str(uuid4()), 'name': 'costume.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + poses = [{'id': str(uuid4()), 'name': f'pose-{index}.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + for index in range(2)] + def task_with(pose_bytes): + assets = {costume['id']: (PNG + b'c' * (20 * megabyte), costume), + **{pose['id']: (PNG + b'p' * pose_bytes, pose) for pose in poses}} + task = {'kind': 'video', 'projectId': 'owner', 'prompt': '飞天起舞', 'referenceIds': list(assets), 'videoMode': 'reference', + 'parameters': {'seconds': 5}, + 'referenceRoles': [{'assetId': costume['id'], 'role': 'reference'}, + *[{'assetId': pose['id'], 'role': 'keyframe', 'frameTimeMs': 1000 * (n + 1)} for n, pose in enumerate(poses)]]} + return SimpleNamespace(asset=lambda owner, key: assets[key]), task + store, task = task_with(megabyte) + assert len(generation_references(store, task, native)['guides']) == 2 + store, task = task_with(15 * megabyte) + with pytest.raises(ProjectError, match='请求过大'): + generation_references(store, task, native) + + +def test_keyframes_need_reference_mode_and_a_supporting_model(): + omni = model() + control = picture('control', kind='video') + with pytest.raises(ProjectError, match='素材参考模式'): + validate_generation(spec(omni, 'control'), omni, (control, picture(), picture('keyframe', 1000)), submitting=True) + plain = model(videoAdapter='standard') + with pytest.raises(ProjectError, match='不支持指定帧'): + validate_generation(spec(plain, 'first_frame'), plain, (picture('keyframe', 1000),), submitting=True) + + +def test_a_keyframe_a_mode_leaves_out_is_refused_and_not_dropped(): + """First-frame mode resolves an extra picture as context only; a keyframe among them must still be answered.""" + omni = model(videoAdapter='fasth3_dual') + first = picture('first_frame') + with pytest.raises(ProjectError, match='素材参考模式') as error: + validate_generation(spec(omni, 'first_frame'), omni, (first, picture('keyframe', 2000, transmission='context_only')), submitting=True) + assert error.value.code == 'keyframe_mode' + + +def test_keyframe_codes_reach_clients_and_read_in_english(): + from typing import get_args + + from opendirector.domain.creation.commands import IssueCode + from opendirector_api.localization import localized_error_for_language + + def flat(annotation): + return {name for item in get_args(annotation) for name in (flat(item) if get_args(item) else {item})} + + codes = {'keyframe_unsupported', 'keyframe_mode', 'keyframe_kind', 'keyframe_count', 'keyframe_needs_reference', 'keyframe_time'} + assert codes <= flat(IssueCode) + for code in codes: + english = localized_error_for_language('en-US', chinese='关键帧必须是图片。', status=422, code=code) + assert english.isascii() and 'keyframe' in english.lower() + assert localized_error_for_language('zh-CN', chinese='关键帧必须是图片。', status=422, code=code) == '关键帧必须是图片。' + + +def test_the_cli_refuses_a_time_that_is_not_a_finite_number(): + from typer.testing import CliRunner + + from opendirector.cli import app + for moment in ('inf', 'nan', '1e400', 'soon'): + result = CliRunner().invoke(app, ['--project', str(uuid4()), 'video', 'create', '--model', str(uuid4()), '--prompt', 'x', '--duration', '5', + '--x', '0', '--y', '0', '--reference-item', str(uuid4()), '--keyframe', f'{uuid4()}@{moment}']) + assert not isinstance(result.exception, OverflowError), moment + + +def fixture(times=(1250, 4583)): + costume = {'id': str(uuid4()), 'name': 'costume.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + poses = [{'id': str(uuid4()), 'name': f'pose-{index}.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + for index in range(len(times))] + assets = {costume['id']: (PNG + b'costume', costume), **{pose['id']: (PNG + pose['name'].encode(), pose) for pose in poses}} + store = SimpleNamespace(asset=lambda owner, key: assets[key]) + task = {'kind': 'video', 'projectId': 'owner', 'prompt': '飞天起舞', 'referenceIds': list(assets), 'videoMode': 'reference', + 'referenceRoles': [{'assetId': costume['id'], 'role': 'reference'}, + *[{'assetId': pose['id'], 'role': 'keyframe', 'frameTimeMs': time} for pose, time in zip(poses, times)]]} + task['parameters'] = video_parameters(task, {key: pair[1] for key, pair in assets.items()}, duration_seconds=5) + return store, task, costume, poses + + +def test_a_keyframe_is_a_guide_and_not_a_reference_picture(): + store, task, costume, poses = fixture() + prepared = generation_references(store, task, OMNI) + assert len(prepared['images']) == 1 + assert [(guide['name'], guide['frame']) for guide in prepared['guides']] == [('pose-0.png', 30), ('pose-1.png', 110)] + # Only the reference picture is labelled; guides never shift . + assert prepared['prompt'].count(' 15000: + assert sum(sent) > 15000 - len(durations) # Only integer rounding is left unused. + + +def test_windows_reject_unknown_lengths(): + with pytest.raises(ValueError): + reference_video_windows([0, 5000]) + + +def model(adapter='fasth3', **extra): + config = {'kind': 'video', 'url': 'http://model.test/v1', 'modelId': 'FastH3-Omni', 'connectionType': 'self_hosted', + 'protocol': 'vllm_omni', 'authMode': 'none', 'videoAdapter': adapter, **extra} + return ModelConfigPublic(id=uuid4(), inputRules=input_rules(config), **config) + + +def reference(seconds): + return ResolvedReference(referenceId=uuid4(), role='reference', + asset=AssetRef(assetId=uuid4(), revision=1, fingerprint='sha256:' + '0' * 64, kind='video'), + metadata=MediaMetadata(mimeType='video/mp4', size=10, width=32, height=24, durationSeconds=seconds)) + + +def spec(target): + return VideoGenerationSpec(id=uuid4(), projectId=uuid4(), kind='video', purpose='generation', + modelConfigId=target.id, prompt='Continue the scene', + parameters=VideoParameters(videoMode='reference', durationSeconds=5)) + + +def test_submission_accepts_a_long_reference_video_only_where_it_is_windowed(): + omni = model() + validate_generation(spec(omni), omni, (reference(78),), submitting=True) + validate_generation(spec(omni), omni, (reference(78), reference(40)), submitting=True) + # The length still has to be known to plan a window. + with pytest.raises(ValueError, match='时长必须已知'): + validate_generation(spec(omni), omni, (reference(None),), submitting=True) + # Audio keeps its total limit on the same profile. + audio = ResolvedReference(referenceId=uuid4(), role='reference', + asset=AssetRef(assetId=uuid4(), revision=1, fingerprint='sha256:' + '0' * 64, kind='audio'), + metadata=MediaMetadata(mimeType='audio/wav', size=10, durationSeconds=20)) + with pytest.raises(ValueError, match='音频参考'): + validate_generation(spec(omni), omni, (reference(5), audio), submitting=True) + + +def video_asset(name, seconds, data=b'video-bytes'): + meta = {'id': str(uuid4()), 'name': name, 'kind': 'video', 'type': 'video/mp4', 'fingerprint': 'fixture', + 'durationMs': seconds * 1000, 'hasAudio': True} + return meta, data + + +def task_for(assets, prompt='延长这段视频'): + return {'kind': 'video', 'projectId': 'owner', 'prompt': prompt, 'referenceIds': [meta['id'] for meta, _ in assets], + 'videoMode': 'reference'} + + +def store_for(assets): + by_id = {meta['id']: (data, meta) for meta, data in assets} + return SimpleNamespace(asset=lambda owner, key: by_id[key]) + + +def test_planning_records_the_window_without_cutting_anything(): + long, short = video_asset('long.mp4', 78), video_asset('short.mp4', 4) + assets = [long, short] + prepared = generation_references(store_for(assets), task_for(assets), OMNI) + entries = {entry['assetId']: entry for entry in prepared['manifest']} + # 15 s budget minus the whole 4 s clip leaves the last 11 s of the long one. + assert entries[long[0]['id']]['window'] == {'startMs': 67000, 'endMs': 78000} + assert 'window' not in entries[short[0]['id']] + assert prepared['windows'] == {long[0]['id']: (67000, 78000)} + + +def test_other_profiles_still_refuse_a_long_reference_video(): + long = video_asset('long.mp4', 78) + seedance = {'kind': 'video', 'modelId': 'doubao-seedance-2.0', 'url': 'https://ark.cn-beijing.volces.com/api/plan/v3', 'apiKey': 'private'} + with pytest.raises(ProjectError, match='不超过 15 秒'): + generation_references(store_for([long]), task_for([long]), seedance) + + +def test_an_edit_without_a_chosen_length_covers_the_window(): + meta, _ = video_asset('long.mp4', 78) + node = {'referenceIds': [meta['id']], 'prompt': '替换视频人物'} + parameters = video_parameters(node, {meta['id']: meta}) + assert parameters['duration'] == 15 and parameters['num_frames'] == 362 + + +@pytest.fixture(scope='module') +def two_tone_video(tmp_path_factory): + """Three red seconds, then three blue ones, with a soundtrack.""" + if not shutil.which('ffmpeg') or not shutil.which('ffprobe'): + pytest.skip('FFmpeg is required to cut reference windows') + folder = tmp_path_factory.mktemp('reference-window') + path = folder / 'two-tone.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=red:s=64x48:r=24:d=3', + '-f', 'lavfi', '-i', 'color=c=blue:s=64x48:r=24:d=3', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=6', + '-filter_complex', '[0:v][1:v]concat=n=2:v=1:a=0[v]', '-map', '[v]', '-map', '2:a', + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', str(path)], check=True) + return path.read_bytes() + + +def probe(data, tmp_path): + path = tmp_path / 'probe.mp4' + path.write_bytes(data) + value = json.loads(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration:stream=codec_type', + '-of', 'json', str(path)], check=True, capture_output=True).stdout) + pixel = subprocess.run(['ffmpeg', '-v', 'error', '-i', str(path), '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', + '-s', '1x1', 'pipe:1'], check=True, capture_output=True).stdout + return float(value['format']['duration']), {stream['codec_type'] for stream in value['streams']}, tuple(pixel[:3]) + + +def test_clip_is_the_requested_range_with_its_sound(two_tone_video, tmp_path): + duration, streams, (red, _, blue) = probe(clip(two_tone_video, 4.0, 6.0), tmp_path) + assert duration == pytest.approx(2.0, abs=0.15) + assert streams == {'video', 'audio'} + # The range starts after the cut to blue, so its first frame is blue. + assert blue > 150 and red < 100 + + +def test_the_wire_carries_the_final_window(two_tone_video, tmp_path, monkeypatch): + """78 s is refused today; here a clip over a lowered budget shows the tail, not the source, is uploaded.""" + import opendirector.domain.reference_windows as windows_module + import opendirector.integrations.reference_inputs as inputs + monkeypatch.setattr(inputs, 'reference_video_windows', + lambda durations: windows_module.reference_video_windows(durations, limit_ms=2000)) + meta, data = video_asset('two-tone.mp4', 6, two_tone_video) + task = task_for([(meta, data)]) + task['parameters'] = video_parameters(task, {meta['id']: meta}, duration_seconds=5) + uploads = [] + + def handle(request): + if request.method == 'POST': + prefix = 'Content-Type: ' + request.headers['content-type'] + '\r\n\r\n' + message = BytesParser(policy=default).parsebytes(prefix.encode() + request.content) + uploads.extend((part.get_filename(), part.get_content_type(), part.get_payload(decode=True)) + for part in message.iter_parts() if part.get_filename()) + return httpx.Response(200, json={'id': 'window-job'}) + if request.url.path.endswith('/content'): + return httpx.Response(200, content=b'generated') + return httpx.Response(200, json={'status': 'completed'}) + + async def submitted(value): + assert value == 'window-job' + + provider = GenerationProviders(store_for([(meta, data)]), httpx.MockTransport(handle), poll_interval=0) + assert asyncio.run(provider.generate(OMNI, task, submitted)) == ('mp4', b'generated') + (name, mime, body), = uploads + assert (name, mime) == ('two-tone.mp4', 'video/mp4') and body != data + duration, streams, (red, _, blue) = probe(body, tmp_path) + assert duration == pytest.approx(2.0, abs=0.15) and streams == {'video', 'audio'} + assert blue > 150 and red < 100