From 73e90be0f57a976efebb9c57faca0ddf6ca3df49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Wed, 2 Dec 2026 04:58:11 +0000 Subject: [PATCH 01/17] [feat] canvas: rebuild a video as a 3D blockout from its cameras and people MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the Video blockout tool (`video-blockout`, 视频脱模) for RFC #444. It turns a clip of up to 30 seconds into a video in which a gray 3D scene and one solid-colored body model per person are rendered from the source's own camera on every frame, with the source's frame count, frame rate and size, and saves the reconstruction it rendered as a layout file. - Models: SAM 3 tracks people (`video.matting`); Depth Anything 3 on the vLLM-Omni depth protocol estimates per-frame depth and cameras (new capability `video.camera`, chosen by the served model name, so Video Depth Anything configurations keep offering depth capture only); SAM 3D Body on the new `vllm_omni_bodies` protocol reconstructs metric bodies and meshes (new capability `video.body_capture`). Bodies are requested with the tracker's masks, boxes tightened to each mask's largest part, and Depth Anything 3's intrinsics, so both share one square-pixel camera. - Scene: depth of up to eight estimated frames, smoothed and meshed, with people, their body silhouettes, what they hold and the least confident pixels cut out, merged in Depth Anything 3's world frame; the keyframe nearest in time is drawn first and the others fill its gaps. - Scale: per person and estimated frame, the median ratio of depth-model depth to rendered body depth over the person's pixels, smoothed over time; its overall median gives meters per depth unit for the layout. - Rendering: a numpy z-buffer rasterizer (triangles grouped by bounding box size, vectorized per group) with flat shading and edge lines; frames are rendered on four threads and encoded at CRF 20 under 8 Mbit/s. - Layout (`视频脱模布局.json`, a file asset with the tool task's provenance): every frame's camera in meters, the scale and its spread, scene keyframes, and per person and frame the box, translation, depth correction, world root, rig parameters and 3D keypoints, plus the served model names. - numpy becomes a dependency of the core package. - UI: toolbar entry and panel note on video nodes, progress and refusal codes (`tool_blockout_duration`, `tool_blockout_frames`, `tool_blockout_misaligned`), protocol option and notes for the 3D body model, in both locales; both user guides describe the tool. The capability contract, its fixtures and contracts are updated for the two new capability ids. Like the other tool tasks, it is reachable from the canvas and the tool-task HTTP endpoint; there is no agent or CLI command for it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: 汪志鹏 --- apps/api/src/opendirector_api/localization.py | 3 + apps/api/src/opendirector_api/models.py | 2 +- docs/architecture/capability-contract.md | 2 +- docs/guides/user-guide.md | 2 + docs/guides/user-guide.zh-CN.md | 2 + .../application/creation_media_publication.py | 2 +- .../opendirector/application/tool_context.py | 15 +- .../application/tool_operations.py | 5 +- .../opendirector/application/tool_tasks.py | 11 +- .../application/tool_video_recipes.py | 38 ++ .../src/opendirector/domain/capabilities.py | 57 +- .../domain/capability_contract.py | 2 + .../domain/capability_messages.py | 3 +- .../opendirector/domain/creation/editors.py | 2 +- .../domain/creation/generation.py | 2 + .../opendirector/domain/creation/models.py | 4 +- .../src/opendirector/domain/input_rules.py | 3 + .../opendirector/domain/model_connection.py | 2 +- .../opendirector/domain/video_capabilities.py | 2 + .../integrations/model_adapters.py | 122 ++++- .../opendirector/integrations/providers.py | 2 + .../core/src/opendirector/media/blockout.py | 494 ++++++++++++++++++ .../core/src/opendirector/media/processing.py | 19 +- .../core/src/opendirector/media/rasterizer.py | 117 +++++ pyproject.toml | 2 +- requirements.txt | 2 + src/backend/rules.ts | 13 +- src/canvas/ModelCapabilityCard.tsx | 2 +- src/canvas/ModelServiceForm.tsx | 5 + src/canvas/NodeSelectionToolbar.tsx | 1 + src/canvas/VideoActionEditor.tsx | 3 + src/canvas/providerPresets.ts | 3 + src/canvas/toolCatalog.ts | 8 + src/canvas/toolReasonText.ts | 2 + src/canvas/toolTaskText.ts | 7 + src/canvas/toolText.ts | 4 + src/canvas/videoActionRuntime.ts | 5 + src/contracts/creation.schema.json | 26 +- src/contracts/generated.ts | 12 +- src/i18n/messages/en-US/canvasShell.ts | 1 + src/i18n/messages/en-US/errors.ts | 14 + src/i18n/messages/en-US/models.ts | 8 +- src/i18n/messages/en-US/tools.ts | 2 + src/i18n/messages/zh-CN/canvasShell.ts | 1 + src/i18n/messages/zh-CN/errors.ts | 12 + src/i18n/messages/zh-CN/models.ts | 9 +- src/i18n/messages/zh-CN/tools.ts | 2 + tests/fixtures/omni-capabilities/absent.json | 6 + tests/fixtures/omni-capabilities/full.json | 2 + .../fixtures/omni-capabilities/malformed.json | 4 + tests/fixtures/omni-capabilities/partial.json | 8 + tests/test_blockout.py | 204 ++++++++ tests/test_capability_contract.py | 4 +- tests/test_localization.py | 10 + tests/test_video_blockout.py | 250 +++++++++ tests/toolCatalog.test.ts | 10 + tests/toolReasonText.test.ts | 4 + tests/toolTaskText.test.ts | 14 + tests/videoActionRuntime.test.ts | 5 + 59 files changed, 1533 insertions(+), 45 deletions(-) create mode 100644 packages/core/src/opendirector/media/blockout.py create mode 100644 packages/core/src/opendirector/media/rasterizer.py create mode 100644 tests/test_blockout.py create mode 100644 tests/test_video_blockout.py diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index d826de4e3..cf0240848 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -82,6 +82,9 @@ 'capability_connection_changed': 'The model connection changed during the capability check. Submit again.', 'tool_concept_translation': 'Use a short English subject description, or add a chat model in Models to translate it automatically.', 'tool_no_video_match': 'The requested subject was not found in the video. Try a different description.', + 'tool_blockout_duration': 'Video blockout needs a clip no longer than 30 seconds. Trim the video first.', + 'tool_blockout_frames': 'Video blockout processes at most 2048 frames at a time. Trim the video or lower its frame rate first.', + 'tool_blockout_misaligned': 'Tracking and camera estimation returned different frames, so they cannot be aligned. Try again.', 'voice_upload_type': 'Upload the voice recording using multipart/form-data.', 'voice_upload_form': 'Check the recording, form fields and text lengths, then try the upload again.', 'voice_model_unsupported': 'This checkpoint does not accept uploaded voices. Choose a Base model for voice cloning or a compatible built-in voice.', diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index a095e33f5..889dde41a 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -29,7 +29,7 @@ class UrlSource(Model): class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' - protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] | None = None + protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] | None = None authMode: Literal['none', 'bearer'] | None = None proxyMode: Literal['system', 'direct'] | None = None capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None) diff --git a/docs/architecture/capability-contract.md b/docs/architecture/capability-contract.md index 5fdce95c1..40c74c36b 100644 --- a/docs/architecture/capability-contract.md +++ b/docs/architecture/capability-contract.md @@ -94,7 +94,7 @@ One boundary is left, and it now cuts the other way: a route this table cannot p ## Routes without an operation -`/v1/images/segmentations`, `/v1/videos/segmentations` and `/v1/videos/depth` are registered endpoints that no operation owns; upstream's docs state that "segmentation and depth estimation do not acquire one of these operations merely by being present in a registry" (`docs/serving/capabilities.md:41-43`). `image.segment`, `video.matting` and `video.motion_capture` therefore stay `unknown` with `no_upstream_profile` — the endpoint does not publish the ability, so it cannot be judged, and it must never read as `missing`. `audio.score` is `no_upstream_operation`; `image.cutout` is `parameter_only` (a request field of a published operation, granted per adapter rather than per profile); `audio.separate` is `no_local_adapter`. None of these six ids is a value of `OPERATION_PROFILES`, so `unknown` falls out of "no evidence" rather than a special case. +`/v1/images/segmentations`, `/v1/videos/segmentations` and `/v1/videos/depth` are registered endpoints that no operation owns; upstream's docs state that "segmentation and depth estimation do not acquire one of these operations merely by being present in a registry" (`docs/serving/capabilities.md:41-43`). `/v1/videos/bodies` (3D body reconstruction) is likewise an endpoint without an operation. `image.segment`, `video.matting`, `video.motion_capture`, `video.camera` (cameras and depth from `/v1/videos/depth`) and `video.body_capture` therefore stay `unknown` with `no_upstream_profile` — the endpoint does not publish the ability, so it cannot be judged, and it must never read as `missing`. `audio.score` is `no_upstream_operation`; `image.cutout` is `parameter_only` (a request field of a published operation, granted per adapter rather than per profile); `audio.separate` is `no_local_adapter`. None of these eight ids is a value of `OPERATION_PROFILES`, so `unknown` falls out of "no evidence" rather than a special case. ## ASR: an upstream gap, not a missing row diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 44908aea4..79509fab5 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -87,6 +87,8 @@ To make music from a reference recording, connect an audio node to a YuE2 music To use **Depth motion capture** on a video, add a video model with the **vLLM-Omni depth** protocol, for example `depth-anything/Video-Depth-Anything-Small` served by `vllm serve --omni`. The tool turns a clip of up to 30 seconds into a grayscale depth video at 480P or 720P, frame for frame, with near objects bright and far ones dark, ready to use as a motion and structure reference. The depth model does not generate video. +**Video blockout** rebuilds a clip of up to 30 seconds in 3D and renders it from the source camera: the scene becomes gray geometry and each person a body model in one fixed color (the first person red), with the same frame count, frame rate and size as the source and no sound. It needs three models: a segmentation model that tracks through video (SAM 3), **Depth Anything 3** on the **vLLM-Omni depth** protocol (for example `depth-anything/DA3-LARGE-1.1`; it estimates the camera of every frame and the scene's depth), and **SAM 3D Body** on the **vLLM-Omni 3D body** protocol (for example `jetjodh/sam-3d-body-dinov3`; it reconstructs each tracked person's pose in meters). A Depth Anything 3 configuration serves video blockout only, not depth motion capture. The scene is built from the estimated depth of up to eight frames with the people, and what they hold, removed, so it stays fixed while the camera moves; areas the depth model is least sure of, such as sky and distant foliage, are left as background. Depth Anything 3 measures depth in a unit of its own, so each person's depth is matched to the depth of their own pixels and the scale in meters is recorded. Next to the video, the tool saves a layout file (`视频脱模布局.json`) with every frame's camera, the scale, and each person's position and body parameters per frame. Bodies that the tracker does not follow, objects other than people, and limbs hidden throughout are not reconstructed, and the layout cannot be edited on the canvas yet. Use the blockout as a reference video so new footage follows the source's motion, timing and camera. + In **General** settings, you can switch themes and adjust the watermark removal option. Watermark settings affect only content generated afterward, and the actual effect depends on support from the model service. ## Make your first short film diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index b246ba3b6..a6a37e207 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -74,6 +74,8 @@ HTTP 400。 使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。 +**视频脱模** 把一段不超过 30 秒的视频在三维中重建,并按原片机位逐帧渲染:场景为灰色模型,每个人物为一个固定颜色的人体模型(第一个人物为红色),帧数、帧率和尺寸与原片一致,没有声音。它需要三个模型:可跟踪视频的分割模型(SAM 3)、在 **vLLM-Omni 深度接口** 上部署的 **Depth Anything 3**(如 `depth-anything/DA3-LARGE-1.1`,估计每一帧的相机和场景深度),以及在 **vLLM-Omni 三维人体接口** 上部署的 **SAM 3D Body**(如 `jetjodh/sam-3d-body-dinov3`,以米为单位重建每个被跟踪人物的姿态)。Depth Anything 3 的配置只用于视频脱模,不用于深度动作捕捉。场景由最多八帧去掉人物及其手持物后的深度构成,因此镜头移动时场景保持不动;深度模型最不确定的区域(如天空和远处的树丛)留作背景。Depth Anything 3 的深度单位不固定,因此每个人物的深度会与其自身像素的深度对齐,并记录换算成米的比例。工具会在视频旁另存一个布局文件(`视频脱模布局.json`),记录每一帧的相机、比例,以及每个人物逐帧的位置和人体参数。未被跟踪的人物、人物以外的物体和始终被遮挡的肢体不会重建,布局暂不能在画布上编辑。可将白模视频作为参考视频,让新画面沿用原片的动作、节奏和机位。 + 在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。 vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可使用 `opendirector video create --duration 6.583333` 并填写其余必需参数。先运行 `opendirector video create --help` 和 `opendirector model list`;`inputRules.fractionalDuration` 表示支持小数秒,各输出规格的时长列表定义允许范围。H3 可能按模型支持的帧数对齐,拼接分段前应核对结果的实际时长。 diff --git a/packages/core/src/opendirector/application/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index 4db1eb96a..c69beeaac 100644 --- a/packages/core/src/opendirector/application/creation_media_publication.py +++ b/packages/core/src/opendirector/application/creation_media_publication.py @@ -59,7 +59,7 @@ def publish_media(service, data, payload, *, staged=frozenset()): expected, allowed = 'video', {'audio'} if not actual.metadata.hasAudio: raise ContractError('invalid_input', '来源视频没有可提取的音轨。', actual.id) - elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite'}: + elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite', 'video-blockout'}: 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_context.py b/packages/core/src/opendirector/application/tool_context.py index 6fdce8f5b..4bbc1baf6 100644 --- a/packages/core/src/opendirector/application/tool_context.py +++ b/packages/core/src/opendirector/application/tool_context.py @@ -11,8 +11,8 @@ from PIL import Image from opendirector.domain.capabilities import ( - ChatRequest, CutoutRequest, DepthRequest, ImageRequest, SegmentRequest, TrackRequest, - Tracks, VideoEditRequest, VideoRequest, + BodyCapture, BodyRequest, CameraRequest, CameraTrack, ChatRequest, CutoutRequest, DepthRequest, ImageRequest, + SegmentRequest, TrackRequest, Tracks, VideoEditRequest, VideoRequest, ) from opendirector.domain.projects import ProjectError from opendirector.media import processing as media @@ -45,7 +45,7 @@ class ToolContext: def __init__(self, *, sources, mask, boxes, parameters, image_model, video_model, progress, video_submitted=None, cutout_model=None, edit_model=None, edit_seconds=(4.0, 15.0), chat_model=None, segment_model=None, track_model=None, edit_keeps_layout=True, annotation=None, edit_max_images=1, segment_available=False, depth_model=None, - native_mask=False, video_execution=None): + native_mask=False, video_execution=None, camera_model=None, body_model=None): self.sources: list[Source] = sources self.mask: bytes | None = mask self.annotation: bytes | None = annotation @@ -57,6 +57,7 @@ def __init__(self, *, sources, mask, boxes, parameters, image_model, video_model self.parameters: dict = parameters self._image, self._video, self._cutout, self._edit = image_model, video_model, cutout_model, edit_model self._segment, self._track, self._depth = segment_model, track_model, depth_model + self._camera, self._bodies = camera_model, body_model # img2img models redraw in place by strength; instruction editors recompose the picture. self.edit_keeps_layout = edit_keeps_layout # Shortest and longest clip one redraw accepts; longer sources are processed piecewise. @@ -119,6 +120,14 @@ async def depth(self, clip: bytes) -> bytes: """A grayscale depth video of clip at its size and rate; near is bright.""" return (await self._depth(DepthRequest(video=clip))).data + async def camera(self, clip: bytes) -> CameraTrack: + """Depth maps and one camera for frames of clip, estimated jointly.""" + return await self._camera(CameraRequest(video=clip)) + + async def bodies(self, clip: bytes, tracks: Tracks, intrinsics) -> BodyCapture: + """A metric 3D body for every tracked person on every frame, seen through each frame's intrinsics.""" + return await self._bodies(BodyRequest(video=clip, tracks=tracks, intrinsics=intrinsics)) + async def concepts(self, text: str, default: tuple[str, ...]) -> list[tuple[str, str]]: """(English concept, label) pairs from a comma-separated description; segmentation models read English.""" parts = list(dict.fromkeys(item.strip() for item in re.split(r'[,,、;;\n]+', text) if item.strip())) diff --git a/packages/core/src/opendirector/application/tool_operations.py b/packages/core/src/opendirector/application/tool_operations.py index b41173623..174c08cf7 100644 --- a/packages/core/src/opendirector/application/tool_operations.py +++ b/packages/core/src/opendirector/application/tool_operations.py @@ -17,7 +17,7 @@ from opendirector.domain.image_presets import PRESETS, preset_instructions from opendirector.application.tool_video_recipes import ( AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot, - subtitle_erasure, video_edit, video_matting, video_upscale, + subtitle_erasure, video_blockout, video_edit, video_matting, video_upscale, ) # Editor previews and tool tasks import this helper from the catalog module. @@ -111,4 +111,7 @@ def _preset_select(): note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'), ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture, note='逐帧估计景深,输出灰度深度视频(近处亮、远处暗),可作为视频生成的动作与结构参考;最长 30 秒。'), + ToolSpec('video-blockout', ('video',), _needs('video.matting', 'video.camera', 'video.body_capture'), video_blockout, + note='在三维中重建原片的机位、场景和人物:场景为灰色白模,每个人物为一个固定颜色的人体模型,按原机位逐帧渲染;' + '输出与原片帧数、帧率和尺寸一致的无声视频,并保存相机、尺度和人体参数布局;最长 30 秒。'), ]} diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 4b139324b..39b4ecffb 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -514,6 +514,14 @@ async def depth_model(request): config, adapter = frozen_model('video.motion_capture') return await self._model_call(task, 'video.motion_capture', lambda _: adapter.depth(config, request)) + async def camera_model(request): + config, adapter = frozen_model('video.camera') + return await self._model_call(task, 'video.camera', lambda _: adapter.camera(config, request)) + + async def body_model(request): + config, adapter = frozen_model('video.body_capture') + return await self._model_call(task, 'video.body_capture', lambda _: adapter.bodies(config, request)) + keeps_layout, edit_max_images = True, 1 if 'image.edit' in task['requires']: _, painter = frozen_model('image.edit') @@ -536,7 +544,8 @@ async def chat_model(request): segment_model=segment_model, track_model=track_model, edit_keeps_layout=keeps_layout, annotation=annotation, edit_max_images=edit_max_images, native_mask=task.get('imageExecutionPolicy') is not None and task.get('imageExecution', {}).get('mode') == 'native_mask', - segment_available='image.segment' in task['requires'], depth_model=depth_model) + segment_available='image.segment' in task['requires'], depth_model=depth_model, + camera_model=camera_model, body_model=body_model) outputs = await spec.recipe(context) # Preserve already-produced bytes even if cancellation arrives # during registration. Each asset is checkpointed independently. diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index 6cff2d032..5d8ba1903 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -6,6 +6,7 @@ from opendirector.application.tool_context import Output, Source, ToolContext, ToolInputError from opendirector.domain.capabilities import EditMask, Tracks from opendirector.domain.projects import ProjectError +from opendirector.media import blockout from opendirector.media import processing as media from opendirector.media.async_work import blocking @@ -242,6 +243,43 @@ async def depth_capture(ctx: ToolContext): data = await ctx.depth(clip.read_bytes()) return [Output('video', data, 'mp4', f'深度动作捕捉 {resolution}')] +BLOCKOUT_SHORT_EDGE = 720 + +BLOCKOUT_CRF = 20 + +BLOCKOUT_MAX_MEGABITS = 8 + +async def video_blockout(ctx: ToolContext): + source = _source_video(ctx) + with media.Workspace() as work: + raw = work.write('source', source.data) + info = await blocking(media.video_info, raw) + if not 0 < info['duration'] <= DEPTH_MAX_SECONDS + 0.05: + raise ProjectError(f'视频脱模需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422, code='tool_blockout_duration') + if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES: + raise ProjectError(f'视频脱模单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422, code='tool_blockout_frames') + await ctx.progress('正在整理视频') + width, height = _depth_size(info['width'], info['height'], BLOCKOUT_SHORT_EDGE) + clip = (await blocking(media.constant_rate_picture, raw, work.path / 'clip.mp4', width=width, height=height, + fps=info['fps'])).read_bytes() + await ctx.progress('正在跟踪人物') + tracks = await blocking(blockout.people_tracks, await ctx.track(clip, ('person',))) + await ctx.progress('正在估计相机和场景') + camera = await ctx.camera(clip) + if (tracks.width, tracks.height) != (width, height) or not tracks.frames or camera.frame_indices[-1] >= len(tracks.frames): + raise ProjectError('跟踪结果与相机估计的帧数不一致,无法逐帧对齐,请重试。', 502, code='tool_blockout_misaligned') + bodies = None + if any(tracks.frames): + await ctx.progress('正在重建三维人体') + _, cameras = blockout.frame_cameras(camera, width, height, len(tracks.frames)) + bodies = await ctx.bodies(clip, tracks, tuple(item.intrinsics.tolist() for item in cameras)) + await ctx.progress('正在渲染白模') + layout = await blocking(blockout.render_blockout, tracks, camera, bodies, work.path / 'frames', fps=info['fps']) + size = (info['width'] - info['width'] % 2, info['height'] - info['height'] % 2) + data = await blocking(media.encode_frames, str(work.path / 'frames' / '%05d.png'), info['fps'], work.path / 'blockout.mp4', + crf=BLOCKOUT_CRF, max_megabits=BLOCKOUT_MAX_MEGABITS, size=size) + return [Output('video', data, 'mp4', '视频脱模'), Output('file', blockout.layout_json(layout), 'json', '视频脱模布局')] + async def video_edit(ctx: ToolContext): source = _source_video(ctx) prompt = ctx.text('prompt') diff --git a/packages/core/src/opendirector/domain/capabilities.py b/packages/core/src/opendirector/domain/capabilities.py index cff91e6ce..92748cfeb 100644 --- a/packages/core/src/opendirector/domain/capabilities.py +++ b/packages/core/src/opendirector/domain/capabilities.py @@ -13,6 +13,7 @@ Capability = Literal[ 'text.chat', 'image.generate', 'image.edit', 'image.cutout', 'video.generate', 'video.first_frame', 'video.edit', 'audio.speech', 'audio.music', 'audio.score', 'image.segment', 'video.matting', 'video.motion_capture', + 'video.camera', 'video.body_capture', # Declared so operations can name what they lack; no current adapter offers it. 'audio.separate', ] @@ -32,6 +33,8 @@ 'video.matting': '视频抠像', 'audio.separate': '音轨分离', 'video.motion_capture': '深度动作捕捉', + 'video.camera': '相机与场景估计', + 'video.body_capture': '三维人体重建', } @@ -90,11 +93,17 @@ class TrackRequest: @dataclass(frozen=True) class Tracks: - """Per decoded frame, the COCO uncompressed RLE counts of each visible instance (column-major).""" + """Per decoded frame, the COCO uncompressed RLE counts of each visible instance (column-major). + + When the tracker reports them, identities and boxes ([x0, y0, x1, y1] in pixels) follow the same + per-frame order; an identity names the same object on every frame. + """ width: int height: int fps: float frames: tuple[tuple[tuple[int, ...], ...], ...] + identities: tuple[tuple[int, ...], ...] = () + boxes: tuple[tuple[tuple[float, float, float, float], ...], ...] = () @dataclass(frozen=True) @@ -103,6 +112,52 @@ class DepthRequest: video: bytes +@dataclass(frozen=True) +class CameraRequest: + """Depth and a camera for frames of a clip, estimated jointly.""" + video: bytes + + +@dataclass(frozen=True) +class CameraTrack: + """Estimated frames of a clip: their depth maps and one pinhole camera each. + + maps is an NPZ archive with float16 `depth` and `conf` arrays of shape [frames, height, width]. + intrinsics are 3x3 in pixels of those maps; extrinsics are 3x4 world-to-camera matrices in OpenCV + axes (x right, y down, z forward) whose world is the first estimated frame's camera. Depth and + translations share one unit of arbitrary scale. + """ + model: str + width: int + height: int + frame_indices: tuple[int, ...] + intrinsics: tuple[tuple[tuple[float, ...], ...], ...] + extrinsics: tuple[tuple[tuple[float, ...], ...], ...] + maps: bytes + + +@dataclass(frozen=True) +class BodyRequest: + """3D bodies for the tracked people of a clip, seen through one 3x3 camera matrix per frame (clip pixels).""" + video: bytes + tracks: Tracks + intrinsics: tuple[tuple[tuple[float, ...], ...], ...] + + +@dataclass(frozen=True) +class BodyCapture: + """One metric body per tracked person and frame, and their meshes. + + Each body is the service's record (camera translation, root-relative keypoints, rig parameters) + with its `frame_index` and track `id`. Every archive of meshes holds float16 root-relative + `vertices`, shared `faces`, and the `frame_index` and `id` of each mesh. + """ + model: str + keypoint_names: tuple[str, ...] + bodies: tuple[dict, ...] + meshes: tuple[bytes, ...] + + @dataclass(frozen=True) class VideoRequest: prompt: str diff --git a/packages/core/src/opendirector/domain/capability_contract.py b/packages/core/src/opendirector/domain/capability_contract.py index 5d6a3e5a0..b459dda0c 100644 --- a/packages/core/src/opendirector/domain/capability_contract.py +++ b/packages/core/src/opendirector/domain/capability_contract.py @@ -434,6 +434,8 @@ 'image.segment': NO_UPSTREAM_PROFILE, 'video.matting': NO_UPSTREAM_PROFILE, 'video.motion_capture': NO_UPSTREAM_PROFILE, + 'video.camera': NO_UPSTREAM_PROFILE, + 'video.body_capture': NO_UPSTREAM_PROFILE, # Upstream publishes no transcription operation at all. 'audio.score': NO_UPSTREAM_OPERATION, # Request field of an operation that does publish a profile. diff --git a/packages/core/src/opendirector/domain/capability_messages.py b/packages/core/src/opendirector/domain/capability_messages.py index 2e509a738..120ee7884 100644 --- a/packages/core/src/opendirector/domain/capability_messages.py +++ b/packages/core/src/opendirector/domain/capability_messages.py @@ -11,7 +11,8 @@ 'video.first_frame': 'first-frame video generation', 'video.edit': 'video inpainting', 'audio.speech': 'speech synthesis', 'audio.music': 'music generation', 'audio.score': 'music transcription', 'image.segment': 'image segmentation', 'video.matting': 'video matting', - 'video.motion_capture': 'depth motion capture', 'audio.separate': 'audio separation', + 'video.motion_capture': 'depth motion capture', 'video.camera': 'camera and scene estimation', + 'video.body_capture': '3D body reconstruction', 'audio.separate': 'audio separation', } diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index 95c33fffb..f9c83915d 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', - 'video-mask-composite', 'video-compress', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] + 'video-mask-composite', 'video-compress', 'video-blockout', '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 b0877872f..89677c440 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -419,6 +419,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc raise ValueError('视觉分割模型仅用于选区、分割和抠像,请选择生成模型。') if model.inputRules.profile == 'vllm-omni-depth': raise ValueError('视频深度模型仅用于深度动作捕捉,请选择生成模型。') + if model.inputRules.profile == 'vllm-omni-bodies': + raise ValueError('三维人体模型仅用于视频脱模,请选择生成模型。') if model.inputRules.profile == 'vllm-omni-score': raise ValueError('扒谱模型仅用于参照音乐生成,请选择音乐生成模型。') written = (any(isinstance(part, PromptReference) or part.text.strip() for part in spec.promptContent) diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index cd72c26af..2cb59901f 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -13,7 +13,7 @@ from .base import Contract ModelKind = Literal['agent', 'image', 'video', 'audio', 'vision'] -Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] +Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] VideoMode = Literal['first_frame', 'reference', 'continuation', 'control'] ImageQuality = Literal['auto', 'low', 'medium', 'high'] Count = Annotated[int, Field(strict=True, ge=0)] @@ -144,7 +144,7 @@ def model_name(cls, value): @model_validator(mode='after') def connection(self): allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, + 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} if self.protocol not in allowed[self.kind]: raise ValueError('Protocol is incompatible with model category') diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index b5889807a..81c47e6ff 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -75,6 +75,9 @@ def _adapter_rules(config): # Video depth estimation service (Video Depth Anything), never a generator. rules.update(profile='vllm-omni-depth', allowedKinds=[], maxImages=0, videoModes=[]) return rules + if config.get('protocol') == 'vllm_omni_bodies': + rules.update(profile='vllm-omni-bodies', allowedKinds=[], maxImages=0, videoModes=[]) + return rules if config.get('protocol') == 'vllm_omni_score': # SheetSage2 transcription service: it turns a reference recording into # a score for music generation and never generates audio itself. diff --git a/packages/core/src/opendirector/domain/model_connection.py b/packages/core/src/opendirector/domain/model_connection.py index 0e7ffd3f0..e94ecca57 100644 --- a/packages/core/src/opendirector/domain/model_connection.py +++ b/packages/core/src/opendirector/domain/model_connection.py @@ -10,7 +10,7 @@ def connection_fields(kind, connection_type='api', protocol=None, auth_mode=None protocol = protocol or ('openai' if kind == 'agent' or connection_type == 'self_hosted' and kind not in {'video', 'vision'} else 'vllm_omni' if connection_type == 'self_hosted' else 'volcengine') allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, + 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} auth_mode = auth_mode or ('none' if connection_type == 'self_hosted' else 'bearer') proxy_mode = proxy_mode if proxy_mode is not None else 'system' diff --git a/packages/core/src/opendirector/domain/video_capabilities.py b/packages/core/src/opendirector/domain/video_capabilities.py index ea9aac979..ac9ae1170 100644 --- a/packages/core/src/opendirector/domain/video_capabilities.py +++ b/packages/core/src/opendirector/domain/video_capabilities.py @@ -139,6 +139,8 @@ def check_video_config(kind, protocol, adapter, capabilities): raise ProjectError('视觉分割接口不支持视频生成输出规格。') if protocol == 'vllm_omni_depth' and (adapter != 'auto' or capabilities is not None): raise ProjectError('视频深度接口不支持视频生成输出规格。') + if protocol == 'vllm_omni_bodies' and (adapter != 'auto' or capabilities is not None): + raise ProjectError('三维人体接口不支持视频生成输出规格。') if adapter != 'auto' and protocol != 'vllm_omni': raise ProjectError('所选视频适配方式需要 /videos 接口协议。') if capabilities is not None: diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index e882b0171..936dfe601 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -19,9 +19,9 @@ from opendirector.domain.assets import MAX_ASSET_BYTES from opendirector.domain.capability_messages import constraint_rejection -from opendirector.domain.capabilities import (ChatRequest, CutoutRequest, DepthRequest, EditMask, ImageRequest, MediaResult, MusicRequest, - ScoreRequest, Segment, SegmentRequest, SpeechRequest, TrackRequest, Tracks, VideoEditRequest, - VideoRequest) +from opendirector.domain.capabilities import (BodyCapture, BodyRequest, CameraRequest, CameraTrack, ChatRequest, CutoutRequest, + DepthRequest, EditMask, ImageRequest, MediaResult, MusicRequest, ScoreRequest, Segment, + SegmentRequest, SpeechRequest, TrackRequest, Tracks, VideoEditRequest, VideoRequest) from opendirector.domain.input_rules import input_rules from opendirector.domain.image_inputs import image_input_policy, validate_image_request from opendirector.domain.bigmodel_image import validate_bigmodel_image @@ -160,6 +160,12 @@ async def track(self, config, request: TrackRequest) -> Tracks: async def depth(self, config, request: DepthRequest) -> MediaResult: raise ProjectError('所选模型不支持深度动作捕捉。', 409) + async def camera(self, config, request: CameraRequest) -> CameraTrack: + raise ProjectError('所选模型不支持相机与场景估计。', 409) + + async def bodies(self, config, request: BodyRequest) -> BodyCapture: + raise ProjectError('所选模型不支持三维人体重建。', 409) + class BigModelImages(ModelAdapter): """BigModel's synchronous GLM-Image API, with a recoverable result locator.""" @@ -952,7 +958,15 @@ async def work(): limit=512 * 1024 * 1024)) frames = tuple(tuple(tuple(int(count) for count in item['mask']['counts']) for item in frame['instances']) for frame in value['frames']) - return Tracks(int(value['width']), int(value['height']), float(value['fps'] or 24), frames) + identities = tuple(tuple(item.get('id') for item in frame['instances']) for frame in value['frames']) + if any(isinstance(identity, bool) or not isinstance(identity, int) for frame in identities for identity in frame): + identities = () + boxes = tuple(tuple(tuple(float(number) for number in item['box']) for item in frame['instances']) + for frame in value['frames']) if all('box' in item for frame in value['frames'] + for item in frame['instances']) else () + if any(len(box) != 4 for frame in boxes for box in frame): + boxes = () + return Tracks(int(value['width']), int(value['height']), float(value['fps'] or 24), frames, identities, boxes) return await _call('submit', work) @@ -991,6 +1005,102 @@ def _inverse(data, near, far): return media.disparity(work.write('meters.mp4', data), work.path / 'inverse.mp4', near=near, far=far) +def is_camera_model(config) -> bool: + """Depth Anything 3 checkpoints estimate a camera for every depth map; other depth models do not.""" + name = config['modelId'].rstrip('/').rsplit('/', 1)[-1].lower() + return name.startswith('da3') or 'depth-anything-3' in name + + +class VllmOmniCamera(ModelAdapter): + """vLLM-Omni Depth Anything 3: /videos/depth estimates depth and a camera per sampled frame, jointly. + + Up to 128 frames are estimated per clip; the service picks the stride for longer clips. The + network works at 504 pixels on the longer side, so the maps are requested at that size. + """ + + capabilities = frozenset({'video.camera'}) + MAP_EDGE = 504 + RESPONSE_BYTES = 384 * 1024 * 1024 + + async def camera(self, config, request: CameraRequest) -> CameraTrack: + form = {'model': config['modelId'], 'max_res': str(self.MAP_EDGE), 'return_depth': 'true', 'colormap': 'grayscale'} + + async def work(): + async with _client(self, config, timeout=1800) as client: + async with client.stream('POST', endpoint(config['url'], '/videos/depth'), headers=auth_headers(config), + data=form, files=[('video', ('clip.mp4', request.video, 'video/mp4'))], + extensions={'model_parameters': {'fields': form, 'file_count': 1}}) as response: + value = json.loads(await bounded(response, stage='submit', secrets=(config.get('apiKey', ''),), + limit=self.RESPONSE_BYTES)) + cameras = value['cameras'] + indices = tuple(int(item) for item in value['frame_indices']) + intrinsics = tuple(tuple(tuple(float(number) for number in row) for row in matrix) for matrix in cameras['intrinsics']) + extrinsics = tuple(tuple(tuple(float(number) for number in row) for row in matrix) for matrix in cameras['extrinsics']) + shapes = {len(indices), len(intrinsics), len(extrinsics), int(value['num_frames'])} + if (value['inverse'] is not False or cameras.get('convention') != 'opencv_world_to_camera' or len(shapes) != 1 + or not indices or list(indices) != sorted(set(indices)) or indices[0] < 0 + or any(len(matrix) != 3 or any(len(row) != 3 for row in matrix) for matrix in intrinsics) + or any(len(matrix) != 3 or any(len(row) != 4 for row in matrix) for matrix in extrinsics)): + raise ValueError('camera response') + return CameraTrack(str(value['model']), int(value['width']), int(value['height']), indices, intrinsics, extrinsics, + base64.b64decode(value['depth'], validate=True)) + return await _call('submit', work) + + +class VllmOmniBodies(ModelAdapter): + """vLLM-Omni SAM 3D Body: /videos/bodies reconstructs one metric body per given person box and frame. + + Boxes, masks and track identities come from the tracker; requests are split so that each carries + at most MAX_BODIES people with their meshes. + """ + + capabilities = frozenset({'video.body_capture'}) + MAX_BODIES = 512 + RESPONSE_BYTES = 192 * 1024 * 1024 + + async def bodies(self, config, request: BodyRequest) -> BodyCapture: + tracks = request.tracks + frames = [] + for index, counts in enumerate(tracks.frames): + if counts: + frames.append({'frame_index': index, 'instances': [ + {'id': int(tracks.identities[index][slot]), 'box': [round(value, 2) for value in tracks.boxes[index][slot]], + 'mask': {'size': [tracks.height, tracks.width], 'counts': list(counts[slot])}} + for slot in range(len(counts))]}) + chunks, current = [], [] + for frame in frames: + if current and sum(len(item['instances']) for item in current) + len(frame['instances']) > self.MAX_BODIES: + chunks.append(current) + current = [] + current.append(frame) + if current: + chunks.append(current) + model, names, bodies, meshes = config['modelId'], (), [], [] + for chunk in chunks: + listed = json.dumps(chunk) + matrices = json.dumps({str(frame['frame_index']): request.intrinsics[frame['frame_index']] for frame in chunk}) + form = {'model': config['modelId'], 'use_masks': 'true', 'return_vertices': 'true'} + + async def work(): + async with _client(self, config, timeout=1800) as client: + async with client.stream('POST', endpoint(config['url'], '/videos/bodies'), headers=auth_headers(config), data=form, + files=[('video', ('clip.mp4', request.video, 'video/mp4')), + ('frames', ('frames.json', listed.encode(), 'application/json')), + ('intrinsics', ('intrinsics.json', matrices.encode(), 'application/json'))], + extensions={'model_parameters': {'fields': form, 'file_count': 3}}) as response: + value = json.loads(await bounded(response, stage='submit', secrets=(config.get('apiKey', ''),), + limit=self.RESPONSE_BYTES)) + found = [dict(body, frame_index=int(frame['frame_index'])) for frame in value['frames'] for body in frame['bodies']] + if len(found) != sum(len(frame['instances']) for frame in chunk) or not value['vertices']: + raise ValueError('bodies response') + names = tuple(str(name) for name in value['keypoint_names']) + return str(value['model']), names, found, base64.b64decode(value['vertices'], validate=True) + model, names, found, archive = await _call('submit', work) + bodies.extend(found) + meshes.append(archive) + return BodyCapture(model, names, tuple(bodies), tuple(meshes)) + + def adapter_for(config, transport=None, poll_interval=3, *, image_policy=None, legacy_image_policy=False) -> ModelAdapter | None: """The adapter serving a configuration, chosen from its explicit profile and protocol.""" kind, protocol = config['kind'], config.get('protocol') @@ -1006,7 +1116,9 @@ def adapter_for(config, transport=None, poll_interval=3, *, image_policy=None, l if profile == 'vllm-omni-segmentation': return VllmOmniSegmentation(transport, poll_interval) if profile == 'vllm-omni-depth': - return VllmOmniDepth(transport, poll_interval) + return (VllmOmniCamera if is_camera_model(config) else VllmOmniDepth)(transport, poll_interval) + if profile == 'vllm-omni-bodies': + return VllmOmniBodies(transport, poll_interval) if profile == 'vllm-omni-score': return VllmOmniScore(transport, poll_interval) if kind == 'agent': diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 4c9eacbe4..0f3c76b61 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -71,6 +71,8 @@ def validate(self, kind, config): raise ProjectError('视觉分割模型仅用于选区、分割和抠像,请选择生成模型。') if input_rules(config)['profile'] == 'vllm-omni-depth': raise ProjectError('视频深度模型仅用于深度动作捕捉,请选择生成模型。') + if input_rules(config)['profile'] == 'vllm-omni-bodies': + raise ProjectError('三维人体模型仅用于视频脱模,请选择生成模型。') if input_rules(config)['profile'] == 'vllm-omni-score': raise ProjectError('扒谱模型仅用于参照音乐生成,请选择音乐生成模型。') adapter = self._profile_adapter(config) diff --git a/packages/core/src/opendirector/media/blockout.py b/packages/core/src/opendirector/media/blockout.py new file mode 100644 index 000000000..1c035f053 --- /dev/null +++ b/packages/core/src/opendirector/media/blockout.py @@ -0,0 +1,494 @@ +"""3D blockout frames: a gray scene proxy from estimated depth and cameras, and posed body meshes. + +Cameras follow the OpenCV convention (x right, y down, z forward) with +world-to-camera extrinsics [R | t]. The scene keeps the depth model's unit; +bodies arrive in meters in each frame's camera and are brought into that unit +by a ratio measured against the depth of the person's own pixels. +""" +import io +import json +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, replace +from pathlib import Path + +import numpy as np +from PIL import Image, ImageFilter + +from opendirector.domain.capabilities import BodyCapture, CameraTrack, Tracks +from opendirector.domain.projects import ProjectError +from opendirector.media.rasterizer import face_normals, rasterize + +SCENE_STEP = 4 +SCENE_SEAM = 0.12 +SCENE_KEYFRAMES = 8 +SCENE_SMOOTHING = 3 +SCENE_PRIORITY = 1.03 +MIN_CONFIDENCE = 1.05 +MASK_GROWTH = 5 +HELD_MARGIN = 0.2 +HELD_DEPTH = 1.08 +SCENE_ALBEDO = np.array([0.86, 0.86, 0.87]) +BACKGROUND = np.array([0.93, 0.93, 0.94]) +PEOPLE = ((0.86, 0.17, 0.12), (0.16, 0.42, 0.86), (0.93, 0.68, 0.10), (0.18, 0.62, 0.32), + (0.58, 0.30, 0.80), (0.92, 0.45, 0.14), (0.12, 0.66, 0.70), (0.86, 0.34, 0.62)) +LIGHT = np.array([-0.3, -0.45, -1.0]) / np.linalg.norm([-0.3, -0.45, -1.0]) +AMBIENT, DIFFUSE = 0.5, 0.5 +EDGE_DEPTH = 0.035 +EDGE_CREASE = 0.5 + + +@dataclass(frozen=True) +class Camera: + """One frame's square-pixel pinhole camera: intrinsics 3x3 and world-to-camera rotation and translation.""" + intrinsics: np.ndarray + rotation: np.ndarray + translation: np.ndarray + + +def square_intrinsics(intrinsics, source_size, target_size) -> np.ndarray: + """Intrinsics for target_size with the focal length of the longer side on both axes and a centered principal point.""" + (source_width, source_height), (width, height) = source_size, target_size + focal = (intrinsics[0, 0] * width / source_width if width >= height else intrinsics[1, 1] * height / source_height) + return np.array([[focal, 0, width / 2], [0, focal, height / 2], [0, 0, 1]], dtype=np.float64) + + +def _quaternion(rotation): + m = rotation + trace = np.trace(m) + if trace > 0: + s = 2 * np.sqrt(trace + 1) + q = np.array([s / 4, (m[2, 1] - m[1, 2]) / s, (m[0, 2] - m[2, 0]) / s, (m[1, 0] - m[0, 1]) / s]) + else: + i = int(np.argmax(np.diag(m))) + j, k = (i + 1) % 3, (i + 2) % 3 + s = 2 * np.sqrt(1 + m[i, i] - m[j, j] - m[k, k]) + q = np.empty(4) + q[0] = (m[k, j] - m[j, k]) / s + q[1 + i] = s / 4 + q[1 + j] = (m[j, i] + m[i, j]) / s + q[1 + k] = (m[k, i] + m[i, k]) / s + return q / np.linalg.norm(q) + + +def _rotation(q): + w, x, y, z = q / np.linalg.norm(q) + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +def _slerp(a, b, weight): + dot = float(np.dot(a, b)) + if dot < 0: + b, dot = -b, -dot + if dot > 0.9995: + return (1 - weight) * a + weight * b + angle = np.arccos(dot) + return (np.sin((1 - weight) * angle) * a + np.sin(weight * angle) * b) / np.sin(angle) + + +def frame_poses(frame_indices, extrinsics, count) -> list[tuple[np.ndarray, np.ndarray]]: + """World-to-camera (R, t) for every frame 0..count-1: estimated frames as given, others interpolated + spherically in rotation and linearly in camera center, and held beyond the first and last estimate.""" + extrinsics = np.asarray(extrinsics, dtype=np.float64) + rotations = extrinsics[:, :, :3] + centers = -np.einsum('nji,nj->ni', rotations, extrinsics[:, :, 3]) + quaternions = [_quaternion(item) for item in rotations] + indices = list(frame_indices) + poses = [] + for frame in range(count): + upper = int(np.searchsorted(indices, frame)) + if upper < len(indices) and indices[upper] == frame: + rotation, center = rotations[upper], centers[upper] + elif upper == 0 or upper == len(indices): + nearest = 0 if upper == 0 else len(indices) - 1 + rotation, center = rotations[nearest], centers[nearest] + else: + lower = upper - 1 + weight = (frame - indices[lower]) / (indices[upper] - indices[lower]) + rotation = _rotation(_slerp(quaternions[lower], quaternions[upper], weight)) + center = (1 - weight) * centers[lower] + weight * centers[upper] + poses.append((rotation, -rotation @ center)) + return poses + + +def _block_mean(values, valid, step): + height, width = values.shape[0] // step * step, values.shape[1] // step * step + values, valid = values[:height, :width], valid[:height, :width] + shape = (height // step, step, width // step, step) + weight = valid.reshape(shape).sum(axis=(1, 3)) + total = np.where(valid, values, 0).reshape(shape).sum(axis=(1, 3)) + return np.where(weight > step * step // 2, total / np.maximum(weight, 1), np.nan) + + +def _box(values, radius): + padded = np.pad(values, radius, mode='edge') + total = np.pad(padded.cumsum(0).cumsum(1), ((1, 0), (1, 0))) + size = 2 * radius + 1 + return total[size:, size:] - total[:-size, size:] - total[size:, :-size] + total[:-size, :-size] + + +def smooth_depth(depth, valid, radius=SCENE_SMOOTHING): + """Depth averaged in inverse depth over a box of valid pixels, twice; invalid pixels stay invalid.""" + inverse = np.where(valid, 1 / np.where(valid, depth, 1), 0) + weight = valid.astype(np.float64) + for _ in range(2): + count = _box(weight, radius) + inverse = np.where(count > 0, _box(inverse * weight, radius) / np.maximum(count, 1e-9), 0) + return np.where(valid, 1 / np.where(inverse > 0, inverse, 1), np.nan) + + +def depth_mesh(depth, excluded, camera: Camera, step=SCENE_STEP, seam=SCENE_SEAM): + """World vertices and triangles of a depth map, smoothed and sampled every step pixels; excluded + pixels and cells whose corners differ in depth by more than the seam ratio stay open.""" + valid = np.isfinite(depth) & (depth > 0) & ~excluded + grid = _block_mean(smooth_depth(depth.astype(np.float64), valid), valid, step) + rows, cols = grid.shape + v, u = np.mgrid[:rows, :cols] + focal, cx, cy = camera.intrinsics[0, 0], camera.intrinsics[0, 2], camera.intrinsics[1, 2] + u, v = (u + 0.5) * step, (v + 0.5) * step + points = np.stack([(u - cx) / focal * grid, (v - cy) / focal * grid, grid], axis=-1).reshape(-1, 3) + world = (points - camera.translation) @ camera.rotation + index = np.arange(rows * cols).reshape(rows, cols) + a, b, c, d = index[:-1, :-1].ravel(), index[:-1, 1:].ravel(), index[1:, :-1].ravel(), index[1:, 1:].ravel() + faces = np.concatenate([np.stack([a, b, c], 1), np.stack([b, d, c], 1)]) + z = grid.ravel()[faces] + keep = np.isfinite(z).all(axis=1) + faces, z = faces[keep], z[keep] + faces = faces[z.max(axis=1) <= z.min(axis=1) * (1 + seam)] + used, faces = np.unique(faces, return_inverse=True) + return world[used], faces.reshape(-1, 3) + + +def grow(mask: np.ndarray, pixels: int) -> np.ndarray: + """A boolean mask widened by about pixels in every direction.""" + if pixels <= 0 or not mask.any(): + return mask + image = Image.fromarray(mask.astype(np.uint8) * 255).filter(ImageFilter.MaxFilter(2 * pixels + 1)) + return np.asarray(image) > 127 + + +def resize_mask(mask: np.ndarray, width: int, height: int) -> np.ndarray: + if mask.shape == (height, width): + return mask + image = Image.fromarray(mask.astype(np.uint8) * 255).resize((width, height), Image.Resampling.BILINEAR) + return np.asarray(image) > 63 + + +@dataclass(frozen=True) +class Scene: + """World-space gray proxy: vertices, triangles, unit normals and the keyframe each vertex comes from.""" + vertices: np.ndarray + faces: np.ndarray + normals: np.ndarray + keyframes: np.ndarray + + +def scene_proxy(depths, people_masks, cameras: list[Camera], keyframes, confidences=None) -> Scene: + """Merge the depth meshes of the keyframes, with people (their masks and body silhouettes) and least-confident + pixels cut out, into one world-space proxy.""" + vertices, faces, normals, sources, offset = [], [], [], [], 0 + for index in keyframes: + depth = np.asarray(depths[index], dtype=np.float32) + excluded = grow(resize_mask(people_masks[index], depth.shape[1], depth.shape[0]), MASK_GROWTH) + if confidences is not None: + excluded |= np.asarray(confidences[index], dtype=np.float32) < MIN_CONFIDENCE + world, triangles = depth_mesh(depth, excluded, cameras[index]) + if not len(triangles): + continue + camera = cameras[index] + local = world @ camera.rotation.T + camera.translation + normals.append(face_normals(local, triangles) @ camera.rotation) + vertices.append(world) + sources.append(np.full(len(world), index)) + faces.append(triangles + offset) + offset += len(world) + if not faces: + return Scene(np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), np.zeros(0, dtype=np.int64)) + return Scene(np.concatenate(vertices), np.concatenate(faces), np.concatenate(normals), np.concatenate(sources)) + + +def held_objects(depth, mask, margin=HELD_MARGIN, depth_slack=HELD_DEPTH) -> np.ndarray: + """Pixels around a person (their box grown by margin of its size) no farther than the person's median depth + times depth_slack: what they hold or what glares in front of them, which moves with them.""" + depth = np.asarray(depth, dtype=np.float32) + height, width = depth.shape + mask = resize_mask(mask, width, height) + if not mask.any(): + return np.zeros((height, width), dtype=bool) + rows, cols = np.nonzero(mask) + grow_y, grow_x = (rows.max() - rows.min() + 1) * margin, (cols.max() - cols.min() + 1) * margin + region = np.zeros((height, width), dtype=bool) + region[max(0, int(rows.min() - grow_y)):int(rows.max() + grow_y) + 1, max(0, int(cols.min() - grow_x)):int(cols.max() + grow_x) + 1] = True + return region & (depth <= np.median(depth[mask]) * depth_slack) + + +def keyframes_of(count: int, limit=SCENE_KEYFRAMES) -> list[int]: + """Evenly spaced indices into count estimated frames, first and last included.""" + if count <= limit: + return list(range(count)) + return sorted({round(item) for item in np.linspace(0, count - 1, limit)}) + + +def depth_ratio(depth, mask, body_depth) -> tuple[float, int] | None: + """Median of depth-model depth over body depth on the person's pixels the body also covers.""" + depth = np.asarray(depth, dtype=np.float64) + height, width = depth.shape + shared = resize_mask(mask, width, height) & np.isfinite(body_depth) & np.isfinite(depth) & (depth > 0) + shared &= ~grow(~resize_mask(mask, width, height), 1) + if shared.sum() < 24: + return None + return float(np.median(depth[shared] / body_depth[shared])), int(shared.sum()) + + +def smooth_series(frames, values, count, window=2) -> np.ndarray: + """Values measured at some frames as a per-frame series: a running median over window + measurements on each side, interpolated between measurements and held beyond them.""" + if not len(frames): + return np.full(count, np.nan) + frames, values = np.asarray(frames), np.asarray(values, dtype=np.float64) + order = np.argsort(frames) + frames, values = frames[order], values[order] + smoothed = np.array([np.median(values[max(0, i - window):i + window + 1]) for i in range(len(values))]) + return np.interp(np.arange(count), frames, smoothed) + + +def render_frame(scene: Scene, bodies, faces, camera: Camera, width: int, height: int, keyframe=None) -> np.ndarray: + """An RGB uint8 frame of the gray scene and the bodies, given as (camera-space vertices, color) pairs. + + Where keyframe meshes overlap, the given keyframe's surface is drawn; the others fill its gaps.""" + rotation, translation, intrinsics = camera.rotation, camera.translation, camera.intrinsics + local = scene.vertices @ rotation.T + translation + if keyframe is not None: + local = local * np.where(scene.keyframes == keyframe, 1.0, SCENE_PRIORITY)[:, None] + layers = [(local, scene.faces, scene.normals @ rotation.T, SCENE_ALBEDO)] + for vertices, color in bodies: + layers.append((vertices, faces, face_normals(vertices, faces), np.asarray(color))) + vertices = np.concatenate([layer[0] for layer in layers]) + offsets = np.cumsum([0] + [len(layer[0]) for layer in layers]) + triangles = np.concatenate([layer[1] + offsets[index] for index, layer in enumerate(layers)]) + normals = np.concatenate([layer[2] for layer in layers]) + albedo = np.concatenate([np.broadcast_to(layer[3], (len(layer[1]), 3)) for layer in layers]) + raster = rasterize(vertices, triangles, intrinsics, width, height) + hit = raster.triangle >= 0 + owner = np.where(hit, raster.triangle, 0) + light = rotation @ LIGHT + shade = AMBIENT + DIFFUSE * np.clip(normals[owner] @ light, 0, 1) + color = np.where(hit[..., None], albedo[owner] * shade[..., None], BACKGROUND) + color *= _edges(raster.depth, normals[owner], hit)[..., None] + return (np.clip(color, 0, 1) * 255 + 0.5).astype(np.uint8) + + +def _edges(depth, normals, hit): + """Darkening factor for depth steps and creases, measured against the right and lower neighbors.""" + factor = np.ones(depth.shape) + log = np.log(np.where(hit, depth, 1.0)) + for axis in (0, 1): + ahead = [slice(None), slice(None)] + behind = [slice(None), slice(None)] + ahead[axis], behind[axis] = slice(1, None), slice(None, -1) + ahead, behind = tuple(ahead), tuple(behind) + both = hit[ahead] & hit[behind] + step = both & (np.abs(log[ahead] - log[behind]) > EDGE_DEPTH) + crease = both & (np.einsum('...i,...i->...', normals[ahead], normals[behind]) < EDGE_CREASE) + rim = hit[ahead] != hit[behind] + line = np.where(step | rim, 0.55, np.where(crease, 0.8, 1.0)) + far_side = np.where(log[ahead] >= log[behind], 1, 0) + target = np.ones(depth.shape) + target[ahead] = np.where(far_side == 1, line, 1.0) + target[behind] = np.minimum(target[behind], np.where(far_side == 0, line, 1.0)) + factor = np.minimum(factor, target) + return factor + + +WORKERS = 4 +LAYOUT_FORMAT = 'opendirector.video-blockout.layout' +MIN_SHARED_PIXELS = 24 + + +def decode_mask(counts, width: int, height: int) -> np.ndarray: + """A COCO uncompressed RLE (column-major, starting with background) as a boolean [height, width] mask.""" + counts = np.asarray(counts, dtype=np.int64) + if counts.sum() != width * height: + raise ProjectError('分割结果与视频尺寸不一致。', 502) + flat = np.repeat(np.arange(len(counts)) % 2 == 1, counts) + return flat.reshape(width, height).T + + +def component_box(counts, width: int, height: int) -> tuple[float, float, float, float] | None: + """The [x0, y0, x1, y1] box of the largest 4-connected part of an RLE mask, read from its runs.""" + ends = np.cumsum(counts) + starts = ends - np.asarray(counts) + segments = [] + for start, end in zip(starts[1::2], ends[1::2]): + while start < end: + column, row = divmod(int(start), height) + stop = min(int(end), (column + 1) * height) + segments.append((column, row, row + stop - start)) + start = stop + if not segments: + return None + parent = list(range(len(segments))) + + def root(item): + while parent[item] != item: + parent[item] = parent[parent[item]] + item = parent[item] + return item + previous, current, column = [], [], -1 + for index, (col, top, bottom) in enumerate(segments): + if col != column: + previous, current, column = (current if col == column + 1 else []), [], col + for other in previous: + if segments[other][1] < bottom and top < segments[other][2]: + parent[root(index)] = root(other) + current.append(index) + sizes, boxes = {}, {} + for index, (col, top, bottom) in enumerate(segments): + key = root(index) + sizes[key] = sizes.get(key, 0) + bottom - top + x0, y0, x1, y1 = boxes.get(key, (col, top, col, bottom - 1)) + boxes[key] = (min(x0, col), min(y0, top), max(x1, col), max(y1, bottom - 1)) + return tuple(float(value) for value in boxes[max(sizes, key=sizes.get)]) + + +def people_tracks(tracks: Tracks) -> Tracks: + """Tracks with an identity for every instance (its slot when the tracker gives none) and boxes + around each mask's largest part, so stray mask pixels do not stretch the person's crop.""" + identities = tracks.identities or tuple(tuple(range(len(frame))) for frame in tracks.frames) + frames, kept_identities, boxes = [], [], [] + for counts, names in zip(tracks.frames, identities): + kept = [(item, name, component_box(item, tracks.width, tracks.height)) for item, name in zip(counts, names)] + kept = [entry for entry in kept if entry[2] is not None] + frames.append(tuple(entry[0] for entry in kept)) + kept_identities.append(tuple(entry[1] for entry in kept)) + boxes.append(tuple(entry[2] for entry in kept)) + return replace(tracks, frames=tuple(frames), identities=tuple(kept_identities), boxes=tuple(boxes)) + + +def frame_cameras(capture: CameraTrack, width: int, height: int, count: int): + """Square-pixel cameras at the depth maps' size for the estimated frames, and at width x height for every frame.""" + intrinsics = np.asarray(capture.intrinsics, dtype=np.float64) + extrinsics = np.asarray(capture.extrinsics, dtype=np.float64) + maps = [Camera(square_intrinsics(matrix, (capture.width, capture.height), (capture.width, capture.height)), + pose[:, :3], pose[:, 3]) for matrix, pose in zip(intrinsics, extrinsics)] + focal = [square_intrinsics(matrix, (capture.width, capture.height), (width, height))[0, 0] for matrix in intrinsics] + frames = [] + for frame, (rotation, translation) in enumerate(frame_poses(capture.frame_indices, extrinsics, count)): + length = float(np.interp(frame, capture.frame_indices, focal)) + frames.append(Camera(np.array([[length, 0, width / 2], [0, length, height / 2], [0, 0, 1]]), rotation, translation)) + return maps, frames + + +def _meshes(capture: BodyCapture | None): + vertices, faces = {}, None + for archive in (capture.meshes if capture else ()): + with np.load(io.BytesIO(archive), allow_pickle=False) as values: + faces, points = values['faces'].astype(np.int64), values['vertices'] + for row, (frame, identity) in enumerate(zip(values['frame_index'], values['id'])): + vertices[(int(frame), int(identity))] = points[row] + return vertices, faces + + +def _rounded(values, digits=4): + return np.round(np.asarray(values, dtype=np.float64), digits).tolist() + + +def render_blockout(tracks: Tracks, capture: CameraTrack, bodies: BodyCapture | None, folder: Path, *, fps: float) -> dict: + """Write one PNG per tracked frame of the 3D blockout into folder and return its layout record.""" + width, height, count = tracks.width, tracks.height, len(tracks.frames) + with np.load(io.BytesIO(capture.maps), allow_pickle=False) as values: + depth, confidence = values['depth'], values['conf'] + estimated = len(capture.frame_indices) + if depth.shape != (estimated, capture.height, capture.width) or confidence.shape != depth.shape: + raise ProjectError('相机估计结果与深度图不一致,请重试。', 502, code='tool_blockout_misaligned') + if capture.frame_indices[-1] >= count: + raise ProjectError('跟踪结果与相机估计的帧数不一致,无法逐帧对齐,请重试。', 502, code='tool_blockout_misaligned') + map_cameras, cameras = frame_cameras(capture, width, height, count) + masks = [{identity: decode_mask(counts, width, height) for identity, counts in zip(names, frame)} + for names, frame in zip(tracks.identities, tracks.frames)] + people = [np.any(list(frame.values()), axis=0) if frame else np.zeros((height, width), dtype=bool) for frame in masks] + keyframes = keyframes_of(estimated) + + vertices, faces = _meshes(bodies) + records = {(int(body['frame_index']), int(body['id'])): body for body in (bodies.bodies if bodies else ())} + placed = {key: vertices[key].astype(np.float64) + np.asarray(body['camera_translation'], dtype=np.float64) + for key, body in records.items() if key in vertices} + samples, covered = {}, [] + for slot, frame in enumerate(capture.frame_indices): + cut = resize_mask(people[frame], capture.width, capture.height) + for identity in masks[frame]: + cut |= held_objects(depth[slot], masks[frame][identity]) + if (frame, identity) not in placed: + continue + raster = rasterize(placed[(frame, identity)], faces, map_cameras[slot].intrinsics, capture.width, capture.height) + cut |= raster.triangle >= 0 + found = depth_ratio(depth[slot], masks[frame][identity], raster.depth) + if found: + samples.setdefault(identity, []).append((frame, found[0])) + covered.append(cut) + scene = scene_proxy(depth, covered, map_cameras, keyframes, confidence) + ratios = [ratio for values in samples.values() for _, ratio in values] + overall = float(np.median(ratios)) if ratios else None + identities = sorted({identity for _, identity in placed}, key=lambda name: (min(f for f, i in placed if i == name), name)) + series = {} + for identity in identities: + measured = samples.get(identity, []) + series[identity] = (smooth_series([f for f, _ in measured], [r for _, r in measured], count) if measured + else np.full(count, overall if overall else 1.0)) + colors = {identity: PEOPLE[index % len(PEOPLE)] for index, identity in enumerate(identities)} + folder.mkdir() + + def draw(frame): + shown = [(placed[(frame, identity)] * series[identity][frame], colors[identity]) + for identity in masks[frame] if (frame, identity) in placed] + nearest = min(keyframes, key=lambda slot: abs(capture.frame_indices[slot] - frame)) + image = render_frame(scene, shown, faces if faces is not None else np.zeros((0, 3), dtype=np.int64), + cameras[frame], width, height, keyframe=nearest) + Image.fromarray(image).save(folder / f'{frame:05d}.png', compress_level=1) + + with ThreadPoolExecutor(max_workers=WORKERS) as pool: + list(pool.map(draw, range(count))) + + meters = 1 / overall if overall else None + unit = meters or 1.0 + camera_frames = [{'frame': frame, 'estimated': frame in capture.frame_indices, + 'intrinsics': _rounded(camera.intrinsics, 3), + 'extrinsics': _rounded(np.concatenate([camera.rotation, camera.translation[:, None] * unit], 1), 5)} + for frame, camera in enumerate(cameras)] + tracks_out = [] + for identity in identities: + entries = [] + for frame in range(count): + body = records.get((frame, identity)) + if body is None or (frame, identity) not in placed: + continue + correction = float(series[identity][frame] * meters) if meters else 1.0 + root = np.asarray(body['camera_translation'], dtype=np.float64) * correction + camera = cameras[frame] + world = camera.rotation.T @ (root - camera.translation * unit) + entries.append({'frame': frame, 'box': _rounded(body['box'], 1), + 'cameraTranslation': _rounded(body['camera_translation']), 'depthCorrection': round(correction, 4), + 'worldRoot': _rounded(world), 'globalRotation': _rounded(body['global_rotation']), + 'bodyPose': _rounded(body['body_pose']), 'handPose': _rounded(body['hand_pose']), + 'shape': _rounded(body['shape']), 'skeletonScale': _rounded(body['scale']), + 'keypoints3d': _rounded(body['keypoints_3d'])}) + tracks_out.append({'id': identity, 'color': '#%02x%02x%02x' % tuple(round(value * 255) for value in colors[identity]), + 'frames': entries}) + spread = (np.percentile(np.asarray(ratios) * meters, [10, 50, 90]).round(4).tolist() if meters else None) + return { + 'format': LAYOUT_FORMAT, 'version': 1, 'frames': count, 'fps': fps, 'width': width, 'height': height, + 'camera': {'model': capture.model, 'axes': 'opencv', 'extrinsics': 'world_to_camera', 'world': 'first_frame_camera', + 'unit': 'meter' if meters else 'depth_model_unit', 'metersPerDepthUnit': round(meters, 6) if meters else None, + 'estimatedFrames': list(capture.frame_indices), 'frames': camera_frames}, + 'scene': {'keyframes': [capture.frame_indices[slot] for slot in keyframes], 'triangles': int(len(scene.faces)), + 'gridPixels': SCENE_STEP, 'minimumConfidence': MIN_CONFIDENCE}, + 'alignment': {'samples': len(ratios), 'correctionPercentiles': {'p10': spread[0], 'p50': spread[1], 'p90': spread[2]} + if spread else None}, + 'people': {'model': bodies.model if bodies else None, 'keypointNames': list(bodies.keypoint_names) if bodies else [], + 'tracks': tracks_out}, + } + + +def layout_json(layout: dict) -> bytes: + return json.dumps(layout, ensure_ascii=False, separators=(',', ':')).encode() diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index 2e461537b..6d6c540a8 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -253,6 +253,14 @@ def picture(source: Path, out: Path, *, width: int, height: int) -> Path: return out +def constant_rate_picture(source: Path, out: Path, *, width: int, height: int, fps: float) -> Path: + """The silent picture at width x height and a constant fps, one output frame per frame slot from the start.""" + _run(['ffmpeg', '-v', 'error', '-y', '-i', str(source), + '-vf', f'scale={width}:{height},setsar=1,fps={fps:.6f},format=yuv420p', '-an', + _frame_sync_option(), 'passthrough', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', str(out)]) + return out + + def frames_of(source: Path, folder: Path, *, gray=False) -> list[Path]: """Every decoded frame of source as a PNG, in order (grayscale when gray).""" folder.mkdir() @@ -261,10 +269,13 @@ def frames_of(source: Path, folder: Path, *, gray=False) -> list[Path]: return sorted(folder.glob('*.png')) -def encode_frames(pattern: str, fps: float, out: Path) -> bytes: - """A silent H.264 clip from an image-sequence pattern.""" - _run(['ffmpeg', '-v', 'error', '-y', '-framerate', f'{fps:.6f}', '-i', pattern, '-vf', 'format=yuv420p', - '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '12', '-movflags', '+faststart', str(out)]) +def encode_frames(pattern: str, fps: float, out: Path, *, crf: int = 12, max_megabits: int | None = None, + size: tuple[int, int] | None = None) -> bytes: + """A silent H.264 clip from an image-sequence pattern, optionally scaled to size and capped in bitrate.""" + ceiling = ['-maxrate', f'{max_megabits}M', '-bufsize', f'{2 * max_megabits}M'] if max_megabits else [] + scale = f'scale={size[0]}:{size[1]}:flags=lanczos,setsar=1,' if size else '' + _run(['ffmpeg', '-v', 'error', '-y', '-framerate', f'{fps:.6f}', '-i', pattern, '-vf', f'{scale}format=yuv420p', + '-c:v', 'libx264', '-preset', 'veryfast', '-crf', str(crf), *ceiling, '-movflags', '+faststart', str(out)]) return out.read_bytes() diff --git a/packages/core/src/opendirector/media/rasterizer.py b/packages/core/src/opendirector/media/rasterizer.py new file mode 100644 index 000000000..7dcaeb298 --- /dev/null +++ b/packages/core/src/opendirector/media/rasterizer.py @@ -0,0 +1,117 @@ +"""A small z-buffer triangle rasterizer on numpy, for camera-space meshes. + +Triangles are grouped by the size of their pixel bounding box; every group is +tested against its candidate pixel centers in one vectorized pass, and the +nearest fragment per pixel wins (a tie keeps one of the tied triangles). Depth is interpolated perspective-correctly. +""" +from dataclasses import dataclass + +import numpy as np + +NEAR = 1e-3 +CANDIDATES_PER_PASS = 1 << 20 + + +@dataclass(frozen=True) +class Raster: + """Per pixel: camera z of the nearest surface (float32, inf where empty) and its triangle (-1 where empty).""" + depth: np.ndarray + triangle: np.ndarray + + +def project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + """Camera points [N, 3] to pixel coordinates [N, 2]; pixel (u, v) has its center at u + 0.5, v + 0.5.""" + z = points[:, 2] + return np.stack([intrinsics[0, 0] * points[:, 0] / z + intrinsics[0, 2], + intrinsics[1, 1] * points[:, 1] / z + intrinsics[1, 2]], axis=1) + + +def rasterize(vertices: np.ndarray, faces: np.ndarray, intrinsics: np.ndarray, width: int, height: int) -> Raster: + """Rasterize camera-space vertices [V, 3] with triangles [F, 3]; triangles touching the near plane are dropped.""" + vertices = np.asarray(vertices, dtype=np.float64) + faces = np.asarray(faces, dtype=np.int64) + depth = np.full(height * width, np.inf, dtype=np.float32) + triangle = np.full(height * width, -1, dtype=np.int64) + if not len(faces): + return Raster(depth.reshape(height, width), triangle.reshape(height, width)) + corners = vertices[faces] + front = (corners[:, :, 2] > NEAR).all(axis=1) + ids = np.nonzero(front)[0] + corners = corners[front] + pixels = project(corners.reshape(-1, 3), intrinsics).reshape(-1, 3, 2) - 0.5 + x, y, z = pixels[:, :, 0], pixels[:, :, 1], corners[:, :, 2] + area = (x[:, 1] - x[:, 0]) * (y[:, 2] - y[:, 0]) - (x[:, 2] - x[:, 0]) * (y[:, 1] - y[:, 0]) + x0 = np.maximum(np.ceil(x.min(axis=1)), 0) + x1 = np.minimum(np.floor(x.max(axis=1)), width - 1) + y0 = np.maximum(np.ceil(y.min(axis=1)), 0) + y1 = np.minimum(np.floor(y.max(axis=1)), height - 1) + keep = (np.abs(area) > 1e-12) & (x1 >= x0) & (y1 >= y0) + ids, x, y, z, area = ids[keep], x[keep], y[keep], z[keep], area[keep] + x0, y0, x1, y1 = x0[keep], y0[keep], x1[keep], y1[keep] + coefficients = _plane_coefficients(x, y, z, area, x0, y0) + columns = _bucket(x1 - x0 + 1) + rows = _bucket(y1 - y0 + 1) + left, top = x0.astype(np.int64), y0.astype(np.int64) + found_pixel, found_depth, found_triangle = [], [], [] + stride = 2 * (width + height) + 8 + shapes, groups = np.unique(columns * stride + rows, return_inverse=True) + order = np.argsort(groups, kind='stable') + bounds = np.concatenate([[0], np.cumsum(np.bincount(groups, minlength=len(shapes)))]) + for shape_index, shape in enumerate(shapes): + size_x, size_y = divmod(int(shape), stride) + members = order[bounds[shape_index]:bounds[shape_index + 1]] + offsets = np.arange(size_x * size_y) + dx, dy = (offsets % size_x).astype(np.float32), (offsets // size_x).astype(np.float32) + step = max(1, CANDIDATES_PER_PASS // (size_x * size_y)) + for start in range(0, len(members), step): + group = members[start:start + step] + a, b, c = coefficients[group, :, 0, None], coefficients[group, :, 1, None], coefficients[group, :, 2, None] + values = a * dx + b * dy + c + inside = (values[:, 0] >= 0) & (values[:, 1] >= 0) & (values[:, 2] >= 0) + hit_rows, hit_cols = np.nonzero(inside) + if not len(hit_rows): + continue + px = left[group[hit_rows]] + (hit_cols % size_x) + py = top[group[hit_rows]] + (hit_cols // size_x) + on_image = (px < width) & (py < height) + hit_rows, px, py = hit_rows[on_image], px[on_image], py[on_image] + found_pixel.append(py * width + px) + found_depth.append(1 / values[hit_rows, 3, hit_cols[on_image]]) + found_triangle.append(ids[group[hit_rows]]) + if found_pixel: + pixel, near, owner = np.concatenate(found_pixel), np.concatenate(found_depth), np.concatenate(found_triangle) + np.minimum.at(depth, pixel, near) + nearest = near == depth[pixel] + triangle[pixel[nearest]] = owner[nearest] + return Raster(depth.reshape(height, width), triangle.reshape(height, width)) + + +def _plane_coefficients(x, y, z, area, left, top): + """Per triangle, (a, b, c) such that a * dx + b * dy + c gives the three barycentric weights and + the inverse depth at pixel (left + dx, top + dy); float32 stays exact enough near the origin.""" + result = np.empty((len(x), 4, 3)) + for weight, (first, second) in enumerate(((1, 2), (2, 0), (0, 1))): + ex, ey = x[:, second] - x[:, first], y[:, second] - y[:, first] + result[:, weight, 0] = -ey / area + result[:, weight, 1] = ex / area + result[:, weight, 2] = (ey * (x[:, first] - left) - ex * (y[:, first] - top)) / area + result[:, 3] = np.einsum('nk,nkc->nc', 1 / z, result[:, :3]) + return result.astype(np.float32) + + +def _bucket(span: np.ndarray) -> np.ndarray: + """Spans rounded up to 1, 2, 3, 4, then steps of about a quarter, so similar triangles share one pass.""" + span = span.astype(np.int64) + exponent = np.floor(np.log2(np.maximum(span, 1))).astype(np.int64) + unit = np.maximum(1, (1 << exponent) // 4) + return -(-span // unit) * unit + + +def face_normals(vertices: np.ndarray, faces: np.ndarray) -> np.ndarray: + """Unit normals of camera-space triangles, turned to face the camera at the origin.""" + corners = np.asarray(vertices, dtype=np.float64)[faces] + normal = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]) + normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-12) + facing = np.einsum('ij,ij->i', normal, corners.mean(axis=1)) > 0 + normal[facing] *= -1 + return normal diff --git a/pyproject.toml b/pyproject.toml index cf11a9583..cc0c059d5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ requires-python = ">=3.11" dependencies = [ "PyYAML>=6,<7", "filelock>=3.16,<4", "httpx[socks]>=0.27,<1", "anyio>=4,<5", "pydantic>=2.12,<3", "typer>=0.27.3,<0.28", "Pillow>=12,<14", "pillow-heif>=1.8.1,<2", - "fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1", + "fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1", "numpy>=2,<3", "starlette>=1.8,<2", "python-multipart>=0.0.33,<1", "yt-dlp>=2026.11.23", "distlib>=0.4,<1; sys_platform == 'win32'", ] diff --git a/requirements.txt b/requirements.txt index d21534ecd..5b21b4703 100644 --- a/requirements.txt +++ b/requirements.txt @@ -54,6 +54,8 @@ markdown-it-py==4.2.0 # via rich mdurl==0.1.2 # via markdown-it-py +numpy==2.5.5 + # via opendirector (pyproject.toml) opentelemetry-api==1.45.1 # via fastapi packaging==26.3 diff --git a/src/backend/rules.ts b/src/backend/rules.ts index cea000706..68983ba04 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -89,6 +89,7 @@ export interface ModelConfig { | "vllm_omni_music" | "vllm_omni_depth" | "vllm_omni_score" + | "vllm_omni_bodies" | null; authMode: "none" | "bearer" | null; proxyMode?: "system" | "direct"; @@ -116,6 +117,11 @@ export function isDepthModel(model: Pick) { return model.protocol === "vllm_omni_depth"; } +/** SAM 3D Body configurations reconstruct people for video blockout only. */ +export function isBodyModel(model: Pick) { + return model.protocol === "vllm_omni_bodies"; +} + /** SheetSage2 configurations transcribe reference music into scores only. */ export function isScoreModel(model: Pick) { return model.protocol === "vllm_omni_score"; @@ -183,7 +189,10 @@ export function isGenerationModel( model: Pick, ) { return ( - !isSegmentationModel(model) && !isDepthModel(model) && !isScoreModel(model) + !isSegmentationModel(model) && + !isDepthModel(model) && + !isScoreModel(model) && + !isBodyModel(model) ); } @@ -618,6 +627,8 @@ export function backendBlocker( return tNow("errors.rules.depthModel"); if (isScoreModel(config)) return tNow("errors.rules.transcriptionModel"); + if (isBodyModel(config)) + return tNow("errors.rules.bodyModel"); if (!isGenerationModel(config)) return tNow("errors.rules.segmentationModel"); const references = backendReferences(settings, [...incoming, ...pinned], config); diff --git a/src/canvas/ModelCapabilityCard.tsx b/src/canvas/ModelCapabilityCard.tsx index b7f1f0176..c70452262 100644 --- a/src/canvas/ModelCapabilityCard.tsx +++ b/src/canvas/ModelCapabilityCard.tsx @@ -78,7 +78,7 @@ export function ModelCapabilityCard({ nativeCapabilities?.outputs.flatMap((output) => output.durations) ?? []; const video = connection.kind === "video" && - !["vllm_omni_segmentation", "vllm_omni_depth"].includes( + !["vllm_omni_segmentation", "vllm_omni_depth", "vllm_omni_bodies"].includes( connection.protocol, ); const updateDraft = (next: VideoCapabilityDraft, nextAdapter = adapter) => { diff --git a/src/canvas/ModelServiceForm.tsx b/src/canvas/ModelServiceForm.tsx index 7311da83d..9ae49e7c5 100644 --- a/src/canvas/ModelServiceForm.tsx +++ b/src/canvas/ModelServiceForm.tsx @@ -47,6 +47,7 @@ const PROTOCOLS: Record< ["volcengine", "models.protocolOption.volcengine"], ["vllm_omni_segmentation", "models.protocolOption.segmentation"], ["vllm_omni_depth", "models.protocolOption.depth"], + ["vllm_omni_bodies", "models.protocolOption.bodies"], ], audio: [ ["openai", "models.protocolOption.tts"], @@ -146,6 +147,7 @@ export function ModelServiceForm({ const segmentation = value.protocol === "vllm_omni_segmentation"; const depth = value.protocol === "vllm_omni_depth"; const score = value.protocol === "vllm_omni_score"; + const bodies = value.protocol === "vllm_omni_bodies"; const preset = PROVIDER_PRESETS.find((item) => item.id === presetId); const mediaPresetModels = kind === "agent" ? undefined : preset?.modelsByKind?.[kind]; const hasSavedKey = Boolean( @@ -585,6 +587,9 @@ export function ModelServiceForm({ {score && (

{t("models.service.scoreNote")}

)} + {bodies && ( +

{t("models.service.bodiesNote")}

+ )}