diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 99bfcbfcb..aab824957 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -142,8 +142,8 @@ def reference_policy(spec, values, rules=None, *, selected_frame=False): raise ContractError('reference_invalid', '指定的首尾帧不能作为图片传入当前模型;请使用明确的图片素材引用,且不要填写主体槽位 subjectRole。', value.referenceId) if value.subjectRole is not None and rules is not None: ignored = ignored or kind not in rules.allowedKinds or (kind == 'image' and not rules.maxImages) or (kind == 'video' and not rules.maxVideos) or (kind == 'audio' and not rules.maxAudios) - if spec.kind == 'video' and spec.parameters.videoMode == 'continuation' and kind == 'video': - ignored = True # Subject clips are not a remote continuation ID. + if spec.kind == 'video' and spec.parameters.videoMode in {'continuation', 'control'} and kind == 'video': + ignored = True # Subject clips are neither a remote continuation ID nor a control video. transmission = 'context_only' if ignored else 'latent' if value.role == 'continuation' else 'metadata' if spec.kind == 'text' and kind in {'audio', 'video'} else 'content' output.append(value.model_copy(update={'transmission': transmission})) return tuple(output) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 52b12bc1d..f05de01e8 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -34,7 +34,7 @@ from opendirector.domain.video_output import apply_video_resolution from opendirector.ports.gateway import gateway from opendirector.integrations.http_settings import MODEL_JOB_CONTEXT -from opendirector.integrations.fasth3 import video_parameters +from opendirector.integrations.fasth3 import control_parameters, video_parameters from opendirector.integrations.vllm_omni import FPS, video_frame_parameters from opendirector.integrations.model_adapters import capabilities_of from opendirector.integrations.providers import GenerationProviders @@ -200,14 +200,19 @@ def _parameters(self, spec, config, node, records): else: params.pop('generate_audio', None) seconds = intent.get('durationSeconds') - if rules['profile'] == 'fasth3-omni': + control = rules['profile'] == 'fasth3-omni' and node.get('videoMode') == 'control' + if control: + params = control_parameters(node, records, resolution=str(intent.get('resolution', 'auto')).upper()) + params['seed'] = new_seed() + seconds = None # The control video sets the length. + elif rules['profile'] == 'fasth3-omni': params = video_parameters(node, records, duration_seconds=seconds) if config.get('videoAdapter') == 'fasth3_dual' and node.get('videoMode') == 'first_frame': params['num_inference_steps'] = 20 params['seed'] = new_seed() elif rules['profile'] == 'standard-video': params = {} - if seconds is None and config.get('videoCapabilities'): + if seconds is None and config.get('videoCapabilities') and not control: seconds = rules['videoCapabilities']['defaultDuration'] if seconds is not None: params['duration'] = seconds @@ -223,7 +228,9 @@ def _parameters(self, spec, config, node, records): raise ProjectError('指定视频比例前,请在模型接入中配置输出规格。', 422) preferred = next((item for item in choices if item['resolution'] == caps.get('defaultResolution')), choices[0]) output['resolution'] = preferred['resolution'] - if config['protocol'] == 'minimax_video_v2': + if control: + pass # Size and frames already follow the control video. + elif config['protocol'] == 'minimax_video_v2': params['resolution'] = (intent.get('resolution') if intent.get('resolution') != 'auto' else None) or rules['videoCapabilities']['defaultResolution'] has_frames = node['videoMode'] == 'first_frame' and any(records[key]['kind'] == 'image' for key in node['referenceIds']) if has_frames: diff --git a/packages/core/src/opendirector/application/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index b8c729395..3def2c189 100644 --- a/packages/core/src/opendirector/application/creation_media_publication.py +++ b/packages/core/src/opendirector/application/creation_media_publication.py @@ -37,7 +37,7 @@ def publish_media(service, data, payload): expected, allowed = 'video', {'audio'} if not actual.metadata.hasAudio: raise ContractError('invalid_input', '来源视频没有可提取的音轨。', actual.id) - elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation'}: + elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite'}: expected, allowed = 'video', {'video'} elif tool in {'audio-trim', 'audio-separation'}: expected, allowed = ('video' if tool == 'audio-separation' and actual.kind == 'video' else 'audio'), {'audio'} diff --git a/packages/core/src/opendirector/application/tool_operations.py b/packages/core/src/opendirector/application/tool_operations.py index 9f2fb32f8..e48333d5b 100644 --- a/packages/core/src/opendirector/application/tool_operations.py +++ b/packages/core/src/opendirector/application/tool_operations.py @@ -14,7 +14,7 @@ ) from opendirector.application.tool_image_segments import cutout, layer_decompose, select_image_objects from opendirector.application.tool_video_recipes import ( - AUDIO_MODES, audio_separation, depth_capture, frame_interpolation, partial_reshoot, + AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot, subtitle_erasure, video_edit, video_matting, video_upscale, ) @@ -84,7 +84,11 @@ def _select(key, label, options, default=None, required=True): note='智能拆分识别人物、动物、车辆、商品等常见对象;按描述拆分可写多个对象,用逗号分隔。' '接入图片编辑模型时会补全背景。'), ToolSpec('video-matting', ('video',), _needs('video.matting'), video_matting, - note='按描述跟踪对象(默认人物),多个对象用逗号分隔;透明背景输出带透明通道的 WebM。'), + note='按描述跟踪对象(默认人物),多个对象用逗号分隔;透明背景输出带透明通道的 WebM;遮罩输出黑底白色对象。'), + # Two video sources: the content first, then its mask (e.g. depth + person mask for FastH3 结构控制). + ToolSpec('video-mask-composite', ('video',), _needs(), mask_composite, + ({'key': 'stretch', 'label': '拉伸明暗范围', 'type': 'boolean', 'default': True, 'required': False},), + note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'), ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture, note='逐帧估计景深,输出灰度深度视频(近处亮、远处暗),可作为视频生成的动作与结构参考;最长 30 秒。'), ]} diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index d03ff5012..6cff2d032 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -113,7 +113,7 @@ def _write_mattes(tracks: Tracks, folder): async def video_matting(ctx: ToolContext): source = _source_video(ctx) - background = ctx.choice('background', ('black', 'green', 'transparent'), 'green') + background = ctx.choice('background', ('black', 'green', 'transparent', 'mask'), 'green') pairs = await ctx.concepts(ctx.text('prompt'), ('人物',)) with media.Workspace() as work: raw = work.write('source', source.data) @@ -132,10 +132,86 @@ async def video_matting(ctx: ToolContext): code='tool_no_video_match', label=label) await ctx.progress('正在合成抠像视频') await blocking(_write_mattes, tracks, work.path / 'mattes') + if background == 'mask': + # White where the tracked objects are, black elsewhere: an input for 遮罩合成 and other masked steps. + data = await blocking(media.encode_frames, str(work.path / 'mattes' / '%05d.png'), info['fps'], work.path / 'mask.mp4') + return [Output('video', data, 'mp4', '视频遮罩')] data, suffix = await blocking(media.matte, clip, str(work.path / 'mattes' / '%05d.png'), info['fps'], work.path / 'matted', background=background) return [Output('video', data, suffix, '视频抠像')] +COMPOSITE_MAX_FRAMES = 2048 + +def _grow(mask: Image.Image) -> Image.Image: + """The mask thresholded and grown by about four pixels, so hair and loose clothing edges stay inside.""" + return mask.point(lambda value: 255 if value > 127 else 0).filter(ImageFilter.GaussianBlur(3)).point( + lambda value: 255 if value > 16 else 0) + +def composite_frames(content: list, masks: list, folder, *, stretch: bool) -> int: + """content inside the mask (white in masks), black elsewhere; returns the frame count. + + With stretch, brightness inside the mask is spread over 50..255 from its own 1st..99.5th percentile, + so a person's depth uses the full control range and stays distinct from the black background. + """ + count = min(len(content), len(masks)) + if not count: + raise ProjectError('视频中没有可合成的画面。', 422) + curve = list(range(256)) + if stretch: + histogram = [0] * 256 + for index in range(0, count, max(1, count // 48)): + picture = Image.open(content[index]).convert('L') + mask = _grow(Image.open(masks[index]).convert('L').resize(picture.size)) + histogram = [a + b for a, b in zip(histogram, picture.histogram(mask))] + total = sum(histogram) + if not total: + raise ProjectError('遮罩视频中没有白色区域,请检查遮罩。', 422) + def percentile(share): + running = 0 + for value, number in enumerate(histogram): + running += number + if running >= share * total: + return value + return 255 + low, high = percentile(0.01), percentile(0.995) + span = max(high - low, 1) + curve = [round(50 + 205 * min(max((value - low) / span, 0.0), 1.0)) for value in range(256)] + folder.mkdir() + for index in range(count): + picture = Image.open(content[index]).convert('RGB') + frame = Image.new('RGB', picture.size, 0) + frame.paste(picture.point(curve * 3), mask=_grow(Image.open(masks[index]).convert('L').resize(picture.size))) + frame.save(folder / f'{index:05d}.png', compress_level=1) + return count + +async def mask_composite(ctx: ToolContext): + if len(ctx.sources) != 2 or any(source.kind != 'video' for source in ctx.sources): + raise ProjectError('遮罩合成需要两个视频:先选内容视频(例如深度视频),再选遮罩视频。', 422) + stretch = ctx.parameters.get('stretch', True) + if not isinstance(stretch, bool): + raise ProjectError('参数 stretch 无效。', 422) + content, mask = ctx.sources + with media.Workspace() as work: + raw = work.write('content', content.data) + info = await blocking(media.video_info, raw) + if info['duration'] * info['fps'] > COMPOSITE_MAX_FRAMES: + raise ProjectError(f'遮罩合成单次最多处理 {COMPOSITE_MAX_FRAMES} 帧,请先裁剪视频。', 422) + mask_raw = work.write('mask', mask.data) + mask_info = await blocking(media.video_info, mask_raw) + # Frames are paired by index, so the mask must share the content's timeline + # (e.g. both made from the same source clip); otherwise the mask drifts silently. + if abs(mask_info['fps'] - info['fps']) > 0.01: + raise ProjectError('遮罩视频与内容视频的帧率不一致,请使用由同一段视频生成的遮罩。', 422) + await ctx.progress('正在读取画面和遮罩') + frames = await blocking(media.frames_of, raw, work.path / 'content-frames') + mattes = await blocking(media.frames_of, mask_raw, work.path / 'mask-frames', gray=True) + if abs(len(frames) - len(mattes)) > 1: + raise ProjectError('遮罩视频与内容视频的帧数不一致,请使用由同一段视频生成的遮罩。', 422) + await ctx.progress('正在合成') + await blocking(composite_frames, frames, mattes, work.path / 'composite', stretch=stretch) + data = await blocking(media.encode_frames, str(work.path / 'composite' / '%05d.png'), info['fps'], work.path / 'composite.mp4') + return [Output('video', data, 'mp4', '遮罩合成')] + DEPTH_MAX_SECONDS = 30 DEPTH_MAX_FRAMES = 2048 diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index aff5bdfbe..eda3f4033 100644 --- a/packages/core/src/opendirector/domain/creation/editors.py +++ b/packages/core/src/opendirector/domain/creation/editors.py @@ -488,7 +488,7 @@ class SelectionBox(Contract): 'dynamic-poster', 'ecommerce-main', 'image-presets', 'grid-split', 'composition', 'annotation', 'video-edit', 'video-extend', 'video-partial-reshoot', 'video-upscale', 'video-frame-interpolation', 'video-depth-capture', 'video-subtitle-erasure', 'video-matting', 'video-crop', 'video-translation', - 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] + 'video-mask-composite', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] class ToolDraftBinding(Contract): diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 92b6ff5d8..bb2622e4d 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -12,7 +12,7 @@ from opendirector.domain.generation import GenerationFailure, ResultCheck from opendirector.domain.projects import ProjectError from opendirector.domain.rule_facts import ( - FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, LYRICS_MAX_LENGTH, MAX_REFERENCES, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, 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, @@ -154,7 +154,7 @@ class FollowingSource(Contract): class ReferenceBase(ProjectEntity): targetSpecId: UUID = Field(description='Target generation configuration ID.') - role: Literal['reference', 'first_frame', 'last_frame', 'continuation'] = Field(default='reference', description='Business role of this binding or reference.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(default='reference', description='Business role of this binding or reference.') 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. @@ -182,7 +182,7 @@ class FollowingReference(ReferenceBase): class ResolvedReference(Contract): referenceId: UUID = Field(description='Generation reference ID.') - role: Literal['reference', 'first_frame', 'last_frame', 'continuation'] = Field(description='Business role of this binding or reference.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(description='Business role of this binding or reference.') 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.') @@ -487,6 +487,19 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc raise ValueError('视频续写会沿用原视频尺寸,不能修改分辨率。') elif any(ref.role == 'continuation' for ref in references): raise ValueError('续写参考必须使用续写模式。') + if params.videoMode == 'control': + # FastH3 + ControlNet: one structure (depth) video fixes motion and layout; images give the look. + control = [ref for ref in transmitted if ref.role == 'control'] + if len(control) != 1 or control[0].asset.kind != 'video' or kinds.count('video') != 1: + raise ValueError('结构控制需要且只能连接一个控制视频(例如人物深度视频)。') + if kinds.count('audio'): + raise ValueError('结构控制模式不接受音频参考。') + seconds = control[0].metadata.durationSeconds + if seconds is None or not CONTROL_VIDEO_SECONDS[0] <= seconds <= CONTROL_VIDEO_SECONDS[1] + 0.05: + low, high = CONTROL_VIDEO_SECONDS + raise ValueError(f'控制视频需要 {low:g}–{high:g} 秒,生成时长与它一致。') + elif any(ref.role == 'control' for ref in references): + raise ValueError('控制视频必须使用结构控制模式。') if params.videoMode == 'first_frame' and (kinds.count('image') > (FRAME_IMAGE_LIMIT if rules.frameRoles and 'last_frame' in rules.frameRoles else 1) or any(kind in {'audio', 'video'} for kind in kinds)): raise ValueError('首帧模式最多只能连接一个图片参考和文本。') for role in ('first_frame', 'last_frame'): @@ -500,7 +513,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if kinds.count('audio') and not rules.audioReferenceStandalone and not (kinds.count('image') or kinds.count('video')): raise ValueError('音频参考必须同时连接图片或视频参考。') for kind in ('audio', 'video'): - seconds = [ref.metadata.durationSeconds for ref in transmitted if ref.asset.kind == kind] + # The control video is the output's timeline, not a reference clip; its own limit applies above. + seconds = [ref.metadata.durationSeconds for ref in transmitted if ref.asset.kind == kind and ref.role != 'control'] minimum = 2 if kind == 'audio' or rules.profile == 'minimax-h3-official' else 0 if any(value is None or value < minimum or value <= 0 for value in seconds) or sum(seconds) > REFERENCE_MEDIA_SECONDS: label = '视频' if kind == 'video' else '音频' @@ -512,7 +526,7 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if params.resolution not in choices: raise ValueError('当前参考模式不支持该输出分辨率。') caps = rules.videoCapabilities - if caps and params.durationSeconds is not None: + if caps and params.durationSeconds is not None and params.videoMode != 'control': choices = [output for output in caps.outputs if params.resolution == 'auto' or output.resolution == params.resolution] if not any(duration_matches(params.durationSeconds, output.durations, rules.fractionalDuration) for output in choices): raise ValueError('当前时长与分辨率组合不受支持。') diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index e0aef2457..225190ba7 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -14,7 +14,7 @@ ModelKind = Literal['agent', 'image', 'video', 'audio', 'vision'] Protocol = Literal['openai', 'volcengine', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] -VideoMode = Literal['first_frame', 'reference', 'continuation'] +VideoMode = Literal['first_frame', 'reference', 'continuation', 'control'] ImageQuality = Literal['auto', 'low', 'medium', 'high'] Count = Annotated[int, Field(strict=True, ge=0)] diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index 95294f240..bd0de3c82 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -137,10 +137,10 @@ 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 == 'continuation' and source.kind != 'video': + if reference.role == 'first_frame' 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') - or (reference.role == 'continuation' and reference.source.kind != 'video')): + or (reference.role in {'continuation', 'control'} and reference.source.kind != 'video')): raise ValueError('Reference source kind does not match its role') for spec in self.generationSpecs: if spec.promptContent: diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index 92612086c..d0b3f55e0 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -101,9 +101,9 @@ def _adapter_rules(config): 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'], outputResolutions=['480P', '768P']) + requestBytes=160 * 1024 * 1024, videoModes=['reference', 'control'], outputResolutions=['480P', '768P']) if adapter == 'fasth3_dual': - rules.update(videoModes=['reference', 'first_frame'], frameRoles=['first_frame', 'last_frame']) + rules.update(videoModes=['reference', 'first_frame', 'control'], 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/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 91f96d755..6e0fecdab 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -42,6 +42,8 @@ MUSIC_SECONDS_INITIAL = 30 REFERENCE_MEDIA_SECONDS = 15 FASTH3_MEDIA_REFERENCE_LIMIT = 12 +# FastH3 structure control: the control video sets the output length (long_video_mode=full up to 30 s). +CONTROL_VIDEO_SECONDS = (4, 30) # Identifiers sent to a speech adapter. Stored specs may also keep a Unicode # display name; that contract pattern is STORED_VOICE_PATTERN and is not a # JavaScript \\w check. @@ -75,6 +77,7 @@ def facts_payload(): 'musicSecondsInitial': MUSIC_SECONDS_INITIAL, 'referenceMediaSeconds': REFERENCE_MEDIA_SECONDS, 'fasth3MediaReferenceLimit': FASTH3_MEDIA_REFERENCE_LIMIT, + 'controlVideoSeconds': list(CONTROL_VIDEO_SECONDS), 'serviceVoicePattern': SERVICE_VOICE_PATTERN, 'storedVoicePattern': STORED_VOICE_PATTERN, 'videoAspectRatios': list(VIDEO_ASPECT_RATIOS), @@ -93,11 +96,11 @@ def aspect_ratio_choices(spec): if kind == 'image': return ['auto', *_unique(ratio for ratio in spec.get('imageOutputRatios') or [] if ratio != 'auto')] if kind == 'video' and published is not None: - if video_mode == 'first-last': + if video_mode in {'first-last', 'control'}: return ['auto'] return ['auto', *list(published)] framed = spec.get('protocol') == 'volcengine' or bool(spec.get('dimensioned')) - if kind == 'video' and video_mode != 'continuation' and framed: + if kind == 'video' and video_mode not in {'continuation', 'control'} and framed: return ['auto', *VIDEO_ASPECT_RATIOS] return ['auto'] @@ -139,8 +142,8 @@ def effective_video_mode(spec): the model allows it. The same function freezes a job and fills the menu. """ mode = spec.get('mode') - if mode == 'continuation': - return 'continuation' + if mode in {'continuation', 'control'}: + return mode if mode in {'first-last', 'first_frame'}: return 'first_frame' if spec.get('configured') and 'first_frame' not in (spec.get('allowedModes') or []): @@ -261,6 +264,8 @@ def reference_byte_limit(spec): 'durationSeconds': 5, 'capabilityOutputs': []}), ('continuation-mode', 'effectiveVideoMode', { 'mode': 'continuation', 'allowedModes': ['first_frame'], 'hasNonTextMedia': False, 'configured': True}), + ('control-mode', 'effectiveVideoMode', { + 'mode': 'control', 'allowedModes': ['reference', 'control'], 'hasNonTextMedia': True, 'configured': True}), ('first-last-mode', 'effectiveVideoMode', { 'mode': 'first-last', 'allowedModes': ['reference'], 'hasNonTextMedia': True, 'configured': True}), ('stored-first-frame-mode', 'effectiveVideoMode', { @@ -328,13 +333,14 @@ def derivation_vectors(): ]; } if (input.kind === "video" && input.publishedRatios != null) { - if (input.videoMode === "first-last") return ["auto"]; + if (input.videoMode === "first-last" || input.videoMode === "control") return ["auto"]; return ["auto", ...input.publishedRatios]; } const framed = input.protocol === "volcengine" || input.dimensioned; if ( input.kind === "video" && input.videoMode !== "continuation" && + input.videoMode !== "control" && framed ) { return ["auto", ...RULE_FACTS.videoAspectRatios]; @@ -405,8 +411,8 @@ def derivation_vectors(): readonly allowedModes: readonly string[]; readonly hasNonTextMedia: boolean; readonly configured: boolean; -}): "continuation" | "first_frame" | "reference" { - if (input.mode === "continuation") return "continuation"; +}): "continuation" | "control" | "first_frame" | "reference" { + if (input.mode === "continuation" || input.mode === "control") return input.mode; if (input.mode === "first-last" || input.mode === "first_frame") { return "first_frame"; } diff --git a/packages/core/src/opendirector/integrations/fasth3.py b/packages/core/src/opendirector/integrations/fasth3.py index fef82b3ea..8e8fb58c6 100644 --- a/packages/core/src/opendirector/integrations/fasth3.py +++ b/packages/core/src/opendirector/integrations/fasth3.py @@ -15,6 +15,12 @@ def generation_fields(parameters, *, frame_indices=None): parameters.get('fps', FPS), parameters.get('num_frames'))) extra = {'task': 'ref2va', 'audio_flow_shift': 3} steps = 8 + if parameters.get('control_type'): + # Fun ControlNet: the control video travels as control_reference with its type as a form field. + fields['control_type'] = parameters['control_type'] + extra[parameters['control_type']] = {'control_context_scale': float(parameters.get('control_scale', 1.0))} + if int(parameters.get('num_frames', 0)) > CONTROL_WINDOW_FRAMES: + extra.update(long_video=True, long_video_mode='full') if frame_indices is not None: extra.update(task='fl2va', sampler='res_multistep', frame_indices=tuple(frame_indices)) steps = parameters.get('num_inference_steps', 20) @@ -23,6 +29,26 @@ def generation_fields(parameters, *, frame_indices=None): return fields, extra +CONTROL_WINDOW_FRAMES = 17 * 20 + 5 # One native FastH3 window; longer control clips run as one long_video_mode=full pass. +CONTROL_RATIOS = ('16:9', '4:3', '1:1', '3:4', '9:16') + + +def control_parameters(node, records, *, resolution=None): + """FastH3 structure control follows its control video: the longest 17n+5 length it covers and the H3 + bucket nearest its aspect (768P unless 480P is chosen). The service holds the last control frame if short.""" + from opendirector.domain.rule_facts import CONTROL_VIDEO_SECONDS + from opendirector.domain.video_output import _ratio, h3_output_size + control = next(records[key] for key in node['referenceIds'] if records[key]['kind'] == 'video') + seconds = min(control['durationMs'] / 1000, CONTROL_VIDEO_SECONDS[1]) + frames = 17 * max((int(seconds * 24 + 1e-6) - 5) // 17, 6) + 5 + aspect = (control.get('width') or 16) / (control.get('height') or 9) + ratio = min(CONTROL_RATIOS, key=lambda name: abs(math.log(_ratio(name) / aspect))) + resolution = resolution if resolution in {'480P', '768P'} else '768P' + return {'seconds': str(math.ceil(frames / 24)), 'duration': frames / 24, 'size': h3_output_size(resolution, ratio), + 'fps': 24, 'num_frames': frames, 'num_inference_steps': 8, 'guidance_scale': 1, + 'control_type': 'depth', 'control_scale': 1.0} + + def native_prompt(task, sources): """Render each rich reference in place using H3's per-modality ordinals.""" # H3 places every video's embedded soundtrack before standalone audio refs. diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index c33704716..2073864e1 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -181,7 +181,10 @@ async def generate(self, config, task, submitted, *, result_ready=None): for index, image in zip(frame_indices, prepared['images'], strict=True)] else: for data, meta, source_kind in references(self.store, task['projectId'], task['referenceIds']): - if source_kind in {'image', 'video', 'audio'}: + 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 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'] form = {'model': config['modelId'], 'prompt': prepared['prompt']} diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 63ab3dfa1..08fef8e84 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,7 +5,7 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, ) from opendirector.domain.projects import ProjectError from opendirector.domain.minimax_image import validate_minimax_image_reference @@ -102,7 +102,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} + result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None} 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']) @@ -141,6 +141,20 @@ def generation_references(store, task, config, *, complete=True, overrides=None) result['manifest'].append(entry) continue media_bytes += len(data) + if source_kind == 'video' and kind == 'video' and mode == 'control': + # The structure video travels as control_reference: no