Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Add PromptHMR moving cameras and preview video export

toyxyz5233723b0cc3
diff --git a/AGENTS.md b/AGENTS.md
index 312b6af..a210ea0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,8 +7,9 @@ For model-specific files, defaults and workflow, use [docs/models/README.md](doc
For MAMMA runtime installation, native SAM 2/SDF builds or repair, follow
[docs/MAMMA_AGENT_SETUP.md](docs/MAMMA_AGENT_SETUP.md). It distinguishes automatic
setup from custom builds and requires actual CUDA verification before registering
-a manually built environment. For optional PromptHMR setup and its separate SAM2
-build, follow [docs/models/PROMPTHMR.md](docs/models/PROMPTHMR.md).
+a manually built environment. For optional PromptHMR setup, its SAM2 build and
+the optional DroidCalib/LieTorch moving-camera build, follow
+[docs/models/PROMPTHMR.md](docs/models/PROMPTHMR.md).
- This is the Windows Git/CMD distribution. Preserve the separate pinned runtimes and model-specific behavior. `install.cmd` covers ExMR/FlowHMR/GVHMR and the small shared-runtime camera support overlay used by PEAR and MAMMA gravity; MAMMA and PromptHMR remain optional through their separate setup commands. Do not merge their packages or assume `update.cmd` installs them.
- PEAR is a transient single-person bone preview. Selecting it must not start models or modify an offline project. Start/Stop controls the resident worker; see `docs/models/PEAR.md` for fixed bones, Reset Bones, One Euro filtering and World Position. Keep inference and capture off the GUI thread, use bounded latest-frame queues and preserve offline state on exit.
diff --git a/README.md b/README.md
index 40da6a6..406fa96 100644
--- a/README.md
+++ b/README.md
@@ -122,6 +122,7 @@ do not put passwords or account tokens in the agent chat.
- Export source animation as FBX or BVH (Generic/Blender or 3ds Max Biped), with an optional leading T-pose; export characters as FBX with or without meshes,
or PMX character motion as VMD for MMD.
- Export portable Blender projects with source animation, video and saved cameras; MAMMA can include animated body meshes and every camera.
+- Save side-by-side input video and the current 3D viewport as MP4 with **File > Export Preview...** (offline models).
- Inspect source-video/bone alignment in Camera Preview and display saved cameras in 3D, with optional background rotation refinement for FlowHMR/ExMR.
- Save projects with separate results for each AI model.
- Track webcam or video input in real time with PEAR's experimental body/finger bone preview; tracking and poses may be unstable.
@@ -172,7 +173,7 @@ projects, caches or retained downloads; shared files are counted once.
| --- | ---: | ---: | ---: |
| ExMR + FlowHMR + GVHMR and supported add-ons | 12.35 GiB | 28.89 GiB | 41.23 GiB |
| MAMMA additional files | 6.11 GiB | 3.53 GiB | 9.65 GiB |
-| PromptHMR additional files | 6.22 GiB | 6.13 GiB | 12.34 GiB |
+| PromptHMR additional files, Fixed Camera | 6.22 GiB | 6.13 GiB | 12.34 GiB |
| **Five offline models** | **24.68 GiB** | **38.55 GiB** | **63.22 GiB** |
| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.84 GiB | ~2.85 GiB |
@@ -180,6 +181,9 @@ Including PEAR, the estimated combined model/runtime total is about
**66.07 GiB (70.9 GB)**, before the additional space listed below. GeoCalib weights (about **0.11 GiB**) are shared by MAMMA and PEAR and counted once; both also reuse VGGT. See the
[PEAR camera guide](docs/models/PEAR.md#multiple-fixed-cameras-and-camera-align).
+Optional PromptHMR moving-camera support adds approximately **18.6 MiB** of
+native modules and **1.55 GiB** of weights beyond these totals; see its model guide.
+
**MAMMA and PromptHMR require separate runtime installation:** run
`Setup_MAMMA.cmd` or `Setup_PromptHMR.cmd` after `install.cmd`, as described
[above](#optional-model-runtimes). They are not installed by `install.cmd` or
@@ -219,7 +223,7 @@ be smaller. Batch selection and OOM retry messages appear in Console and CMD.
- [Recorded processing time, VRAM and RAM](docs/USER_GUIDE.md#recorded-processing-time-and-vram)
- [Resource modes and measured optimizations](docs/PERFORMANCE.md)
- [MAMMA: additional installation, model files and multi-video workflow](docs/MAMMA.md)
-- [PromptHMR: additional installation, model files and fixed-camera workflow](docs/models/PROMPTHMR.md)
+- [PromptHMR: additional installation, model files and camera workflows](docs/models/PROMPTHMR.md)
- [Development and builds](docs/BUILD.md)
- [Agent operating and development guide](docs/AGENT_GUIDE.md)
- [Source validation](docs/VALIDATION.md)
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index 94b1547..caf23aa 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -16,8 +16,8 @@
},
{
"path": "AGENTS.md",
- "bytes": 2174,
- "sha256": "9b25172bb63b4441a582c48a2bf3df1906aca6a3f0ffed8307a08ce7d37ecd89"
+ "bytes": 2219,
+ "sha256": "990cdee8d94201aeef3781f0d7bdf3a83fde72f7c8137669b723a85837536f93"
},
{
"path": "LICENSE",
@@ -26,8 +26,8 @@
},
{
"path": "README.md",
- "bytes": 11568,
- "sha256": "231fed2ace6b009c4d04fd13f1ded21e9e5aa3c78ac6cfab4acb73c9ae89b9ac"
+ "bytes": 11858,
+ "sha256": "dc739192a3767d917c41bc5ed18dbfd1d1ac0d2619f90ca6eac1f63b7003504a"
},
{
"path": "RGBMoCap.cmd",
@@ -41,13 +41,13 @@
},
{
"path": "Setup_PromptHMR.cmd",
- "bytes": 882,
- "sha256": "f81f365d7f7efc61f3105bf8a78905d43725ff658242920187dc74563615b208"
+ "bytes": 1436,
+ "sha256": "41ea984bcb4878ad39a9f53fa962cca22a9a84e416246ccc5412e13b192a019e"
},
{
"path": "THIRD_PARTY_NOTICES.md",
- "bytes": 9254,
- "sha256": "42364b7829e85031e5ff353df02e9dccc7c1e2df841beb3a1aceca86f872153a"
+ "bytes": 9879,
+ "sha256": "7745b1a68af85ec4885549113e8f540b70263d122feeb05f8d904e2fcac174c8"
},
{
"path": "app.py",
@@ -96,13 +96,13 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 58966,
- "sha256": "4fe9829f4d14e497e44ae81788b50abcf1d0f0ae46d839e5ce60870a8e0903e2"
+ "bytes": 63148,
+ "sha256": "b1149d40f8b54cf05f3be2017022cc57458d874ea323e4e2e9d12d53107795a2"
},
{
"path": "docs/BUILD.md",
- "bytes": 12967,
- "sha256": "327a6ae33599374f5dc56871246269591f1c6f00c69a774b0e4143b0f689c993"
+ "bytes": 13113,
+ "sha256": "3ca8d430ea8a261db29bd817c4c3674907d889af6bc9f59132d5818179866f56"
},
{
"path": "docs/CITATIONS.md",
@@ -126,13 +126,13 @@
},
{
"path": "docs/USER_GUIDE.md",
- "bytes": 59973,
- "sha256": "ca250fd26156181cd333885dfae50342eb146a72d530d013c173b3dc67d72a39"
+ "bytes": 62196,
+ "sha256": "5df7a603a8a18b7d030a109c339cb6f6a630861d55cc671d039b4c7e1034d95f"
},
{
"path": "docs/VALIDATION.md",
- "bytes": 122164,
- "sha256": "5b1d16981620860e18f471b4477f87ea987aa31989a7f8d04e03520736b6b7b6"
+ "bytes": 129029,
+ "sha256": "347aeba0ddf06c49e77dbbb3cd7965125a80565601446861a53e76bbbb3463d7"
},
{
"path": "docs/images/exmr-interaction-contact.png",
@@ -176,13 +176,13 @@
},
{
"path": "docs/models/PROMPTHMR.md",
- "bytes": 14215,
- "sha256": "037afb02834ac599660e18478b87b247353155551d9929bedc517451db68d60f"
+ "bytes": 20708,
+ "sha256": "ce4a64477b4b93dfdc4eb4045e6c3c722c1085d78a380cdeb2168dd9b765e4ad"
},
{
"path": "docs/models/README.md",
- "bytes": 6628,
- "sha256": "1fa42963d3f78e788eb3737aa706d5f25e280d91e1357b486fb37fb553be1272"
+ "bytes": 6648,
+ "sha256": "4ab9cd922cb7369f149ee9d245e3306e4c872609b2d956e622432d3ee76a1345"
},
{
"path": "docs/samples/character-retargeting.jpg",
@@ -309,6 +309,11 @@
"bytes": 1743,
"sha256": "f36fb1d7d563cbb15d8effb377470559757b92f5d5e1cbe876bf4f6f7cbf7e54"
},
+ {
+ "path": "installer/prompthmr-camera-lock.json",
+ "bytes": 1169,
+ "sha256": "a32f5c88fc465a0deed9c493792a7ffa688bee6983cfef89c479ab63362e63d2"
+ },
{
"path": "installer/prompthmr-runtime-lock.json",
"bytes": 85747,
@@ -319,6 +324,11 @@
"bytes": 2561,
"sha256": "08e1e8fb768ae7e4edf852569d70ae69fde20d2cb89dd81de4ffc2a9ca896e06"
},
+ {
+ "path": "installer/prompthmr_camera_adapters.py",
+ "bytes": 2932,
+ "sha256": "c70bdefa7e36af6f6bfbe956dd97ec1fb9431c8d4db247e96d356641487583b5"
+ },
{
"path": "installer/runtime-lock.json",
"bytes": 117713,
@@ -1034,6 +1044,11 @@
"bytes": 2905,
"sha256": "9fe3b87fbee89b300c42240d48c04610b07f23207e33549f3aff8f6834442499"
},
+ {
+ "path": "installer/verify_prompthmr_camera.py",
+ "bytes": 1825,
+ "sha256": "9ed4a92aaa76e4cb47c652baef65fa87a6029bfcd1ae635ad5a315b170e019da"
+ },
{
"path": "installer/verify_runtime.py",
"bytes": 2416,
@@ -1156,8 +1171,8 @@
},
{
"path": "mocap/camera_tracks.py",
- "bytes": 13087,
- "sha256": "b71fd476a02449f2676e0aa404eba12949873f4ef2d81bb22c3783231e2c26e4"
+ "bytes": 13972,
+ "sha256": "6cb7e777cec7ef8f36862667bf9a8afcabc7458f2b1a815e9ad641d81a3fef6a"
},
{
"path": "mocap/camera_ui.py",
@@ -1366,8 +1381,8 @@
},
{
"path": "mocap/gui.py",
- "bytes": 105342,
- "sha256": "afd459dc23ccefd56a0a3587b7208d55062fe7ad0887c32b1b953e2d58fce93a"
+ "bytes": 106069,
+ "sha256": "ba28a7320d8957e25c386da2b0b58e98563af1349b127e747898db77c9600ee4"
},
{
"path": "mocap/gvhmr_attention.py",
@@ -1501,8 +1516,8 @@
},
{
"path": "mocap/model_guide.py",
- "bytes": 12047,
- "sha256": "ff25269540fb7a571f23a9e9aba2d01ce28820cfeaef88bb4f3a54ad27f2a4ef"
+ "bytes": 12178,
+ "sha256": "3a72db257f521458ceccda08be039338ab5b0ba0ef0ace82c42c36cb1d57da5f"
},
{
"path": "mocap/model_session.py",
@@ -1511,8 +1526,8 @@
},
{
"path": "mocap/models.py",
- "bytes": 32625,
- "sha256": "ca1de9ef959cfa2383827945ebf7335834afb8ad47b5aba730f20b913bf4eee8"
+ "bytes": 32707,
+ "sha256": "514d6e3cd16c0b08a185bf542814a0ce7b92ce8e84d7b002afb304138d5a9ea8"
},
{
"path": "mocap/motion_tools.py",
@@ -1676,8 +1691,8 @@
},
{
"path": "mocap/pear_ui.py",
- "bytes": 34895,
- "sha256": "1f933754b51420bd7f4ae23905bf8ed2f0cf0a1f7b46e014a0a40cf79c866d1a"
+ "bytes": 35286,
+ "sha256": "78217cde55f9d200f8fb71fa0b3e2d909b1ca4ca682276d800cb28faeaebfa7f"
},
{
"path": "mocap/people_store.py",
@@ -1719,6 +1734,16 @@
"bytes": 22221,
"sha256": "56039242f441a693efb2ffa0823e07dbeeddf6ef300d9e2be087daf4d550bd8f"
},
+ {
+ "path": "mocap/preview_export.py",
+ "bytes": 9061,
+ "sha256": "a7227a2780138b9daec890281d7d2480b9ee3d55a48a50bdb865a9c4583e8c1a"
+ },
+ {
+ "path": "mocap/preview_export_ui.py",
+ "bytes": 15444,
+ "sha256": "18d00cba3825f614cb9d01e5a4ae629dbcec571ea477fc23834c6d29d64b73c1"
+ },
{
"path": "mocap/processing_guard.py",
"bytes": 2783,
@@ -1754,25 +1779,40 @@
"bytes": 10189,
"sha256": "0577f32e583c3667d6ebb638b7687045d0f487870d2f5abc1875b83ce4d4de64"
},
+ {
+ "path": "mocap/prompthmr_cache.py",
+ "bytes": 4730,
+ "sha256": "2e11d39c67f75e514b039855537ad29fb430370b750b416cee3d79fcb2beb7e6"
+ },
+ {
+ "path": "mocap/prompthmr_camera.py",
+ "bytes": 3712,
+ "sha256": "c01c8d8663075a8c42083bd6567159587903e9b8e112d7806b679530ae77153c"
+ },
+ {
+ "path": "mocap/prompthmr_camera_runtime.py",
+ "bytes": 2593,
+ "sha256": "4ac95a749b8a6c00962f302f6ffe56a192a8eb6d63dcdb421dfe8eb38e4c531e"
+ },
{
"path": "mocap/prompthmr_manager.py",
- "bytes": 3731,
- "sha256": "defb8be2c475fafafe4b27c55666bdc7bec42edc671a79827910f8121bfc3cfc"
+ "bytes": 4401,
+ "sha256": "09e7850cd62760acb35194caf6ea8a8b09d95c6142248a2dbb6d1f37bea1e045"
},
{
"path": "mocap/prompthmr_models.py",
- "bytes": 5520,
- "sha256": "475c9a57e906c66da3f457aecb3b2fe0ad8ca42298d56d1a0acf61386550b7ba"
+ "bytes": 6745,
+ "sha256": "cbbfb1b2adedf1353c8657f1b00b423f54dd6f4e7bdb4900a1e0e321bfb7dc5f"
},
{
"path": "mocap/prompthmr_pipeline.py",
- "bytes": 11515,
- "sha256": "b3098bbc038f9f5e25c9b9e96c9ec4fa2116226f74c645089bd328014f024e7d"
+ "bytes": 13137,
+ "sha256": "d1075279956f9443c3ff80694a9388fc9e1f2d74b3af5f9dab0714c50c2a7687"
},
{
"path": "mocap/prompthmr_publish.py",
- "bytes": 11220,
- "sha256": "f6db793dee88db0187b2fc38962d9ef149b5282cda0db46ccf825053e49ba08c"
+ "bytes": 12440,
+ "sha256": "efdd800e66c0d40ccd9c9caf5abadd163a5f002ac0ddb2ebdcd45b235d596e7a"
},
{
"path": "mocap/prompthmr_runtime.py",
@@ -1781,13 +1821,13 @@
},
{
"path": "mocap/prompthmr_scene.py",
- "bytes": 946,
- "sha256": "7e64ea32e6c7f15881555137dd9a530e8c3ccc1ab6c7257c432d4eed95ca929f"
+ "bytes": 994,
+ "sha256": "3e141a1f5d10655b94d572172b680af069049e43cd3be85312198080ab58f983"
},
{
"path": "mocap/prompthmr_ui.py",
- "bytes": 6608,
- "sha256": "6f0b3eb8375208991cde4af8055bafc6b44c1f63a549e12c6d18d2ea95e10148"
+ "bytes": 8188,
+ "sha256": "7b8f1383b6918526fe4ca0bd088fe69cfb5d20ba9906b5138f3fb2369899c08a"
},
{
"path": "mocap/queue_groups.py",
@@ -2076,8 +2116,8 @@
},
{
"path": "mocap/workspace_ui.py",
- "bytes": 37546,
- "sha256": "48d421c6fa7ffdda62ae5bd629b83a620fd39255cf1fc64d8871811b43dd2b2c"
+ "bytes": 37974,
+ "sha256": "12520e6c1d64f7d1744d47bc51b9dae2f839bcf28958105718a71d3e44cc219e"
},
{
"path": "native_compat/LICENSE",
@@ -12841,8 +12881,13 @@
},
{
"path": "tools/setup_prompthmr.py",
- "bytes": 9108,
- "sha256": "76cab672a109aaf69431d26d1b69939048324dee2055d367f47c46da3d7fe194"
+ "bytes": 9300,
+ "sha256": "067e15c0d637ff0f58dba1690f3b9765f86d1040c12d4f3bb6cdefee7a0267a1"
+ },
+ {
+ "path": "tools/setup_prompthmr_camera.py",
+ "bytes": 7067,
+ "sha256": "e013f504e214b470ff7793e6b530c4a8f7b6f0916aeb89663207126279c32717"
},
{
"path": "tools/stage_assets.py",
diff --git a/Setup_PromptHMR.cmd b/Setup_PromptHMR.cmd
index 907b4f9..b721db6 100644
--- a/Setup_PromptHMR.cmd
+++ b/Setup_PromptHMR.cmd
@@ -9,12 +9,20 @@ echo Review https://github.com/yufu-wang/PromptHMR/blob/main/LICENSE
echo Non-commercial scientific research use only; other dependencies have separate licenses.
choice /c YN /n /m "I reviewed these licenses and agree to the permitted use. Continue? [Y/N] "
if errorlevel 2 exit /b 1
+echo Optional moving-camera support uses DroidCalib [AGPL-3.0], LieTorch and Metric3D.
+echo Review https://github.com/boschresearch/DroidCalib/blob/main/LICENSE
+echo and https://github.com/YvanYin/Metric3D/blob/main/LICENSE before choosing Y.
+echo Camera support reuses Python/Torch; allow an additional 6 GiB for building,
+echo plus 1.55 GiB for the two camera models obtained separately in Model Manager.
+set "phmr_camera="
+choice /c YN /n /m "Prepare moving-camera support as well? [Y/N] "
+if not errorlevel 2 set "phmr_camera=--camera"
if not exist "runtime\python.exe" (
echo Run install.cmd first.
pause
exit /b 1
)
-"runtime\python.exe" -I -X utf8 -B tools\setup_prompthmr.py --accept-licenses
+"runtime\python.exe" -I -X utf8 -B tools\setup_prompthmr.py --accept-licenses %phmr_camera%
set "phmr_result=%errorlevel%"
pause
exit /b %phmr_result%
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 38d0241..c570c75 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -7,6 +7,15 @@ retained license files and provider agreements contain the full terms.
## AI tools and models
+PromptHMR's optional moving-camera support downloads [DroidCalib](https://github.com/boschresearch/DroidCalib)
+(AGPL-3.0), [LieTorch](https://github.com/princeton-vl/lietorch) (BSD-3-Clause),
+Eigen and torch-scatter with their provider licenses into the local support
+build. [Metric3D](https://github.com/YvanYin/Metric3D) source/weights retain their
+provider terms. Compatibility adapters do not relicense those sources or remove
+AGPL obligations. Neither camera weights nor compiled extensions are checked into
+this repository. See the [PromptHMR camera guide](docs/models/PROMPTHMR.md#moving-camera-setup-and-behavior).
+
+
Character import, baking and portable scene export use a separate, unmodified Blender 4.5 LTS runtime
(GPL; bundled license and source information in `runtime_character`). The scoped
FBX sampler in `mocap/retarget/selective_fbx.py` retains Blender's GPL terms.
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index 65c6697..61fcb8c 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -10,7 +10,7 @@ This guide is for agents helping users operate or modify RGB MoCap. It describes
- Base worker commands use explicit `-X utf8`, including isolated `-I` launches. Isolated mode ignores `PYTHONIOENCODING`/`PYTHONUTF8` from the parent environment. Any redirected/discarded text log stream must also specify UTF-8. Keep byte-oriented PEAR IPC unchanged.
- Close the app before `update.cmd`. The updater requires a clean tracked worktree and the `main` branch, uses `git pull --ff-only`, then verifies/repairs runtime configuration. It refuses tracked local edits. A plain `git pull` does not perform runtime repair; use `install.cmd` after dependency changes when needed. Do not discard local edits or force an update.
- For setup failure, read the message, check connectivity and free space, then retry `install.cmd`. Preserve models, projects and `.setup` state. Do not repeatedly reinstall or redownload models without evidence.
-- Base installation currently estimates at least 32.4 GiB free before models; ExMR/FlowHMR/GVHMR and add-ons were previously measured around 29 GiB of weights. Optional MAMMA and PromptHMR add separate runtimes and model files; see [MAMMA](MAMMA.md) and [PromptHMR](models/PROMPTHMR.md). The five offline model/runtime sets total about **63.22 GiB (67.9 GB)** excluding caches, projects, downloads and compiler tools, counting shared files once. See the [installed-size table](USER_GUIDE.md#installed-size); installed size and temporary setup headroom are different. Measurements are not guarantees.
+- Base installation currently estimates at least 32.4 GiB free before models; ExMR/FlowHMR/GVHMR and add-ons were previously measured around 29 GiB of weights. Optional MAMMA and PromptHMR add separate runtimes and model files; see [MAMMA](MAMMA.md) and [PromptHMR](models/PROMPTHMR.md). The five offline model/runtime sets total about **63.22 GiB (67.9 GB)** before optional PromptHMR moving-camera support, excluding caches, projects, downloads and compiler tools, counting shared files once. Camera support adds about **1.57 GiB** (18.6 MiB modules and 1.55 GiB weights). See the [installed-size table](USER_GUIDE.md#installed-size); installed size and temporary setup headroom are different. Measurements are not guarantees.
Multi-person reconstruction groups supported ExMR, FlowHMR and GVHMR phases
into sequential, bounded worker requests. `mocap/queue_groups.py` builds the queue;
@@ -70,7 +70,7 @@ input. Do not replace the YAML or invalidate motion to add this metadata.
| FlowHMR | Slower; best overall quality in those tests, not a universal ranking. SMPL-H. | Fingers included; Fast SAM and camera/sampling choices. Moving camera needs VGGT-Omega. |
| GVHMR | Lower overall quality in those tests but sometimes better for unusual poses such as backflips. SMPL-X. | Fingers via optional HandFlow. HTD refines body motion; FootMR refines ankles. Both are separate from contact correction. |
| MAMMA | Optional multi-view SMPL-X capture from two or more synchronized fixed cameras, without a fixed camera-count maximum. Practical capacity depends on RAM/VRAM. Not part of the single-video quality ranking. | Fingers included; separate setup and locked-head body assets. VGGT-Omega + GeoCalib or compatible manual calibration. |
-| PromptHMR | Multiple people reconstructed jointly from one video; can improve relative placement and interactions. Overall motion quality was lower than ExMR in our subjective tests. Fixed-camera Windows path, up to eight people; placement can still be wrong. | No finger tracking; fixed neutral fingers. Setup_PromptHMR.cmd; People defaults to 2, Interaction Prompt on. |
+| PromptHMR | Multiple people reconstructed jointly from one video; can improve relative placement and interactions. Overall motion quality was lower than ExMR in our subjective tests. Fixed/moving-camera Windows paths, up to eight people; placement can still be wrong. | No finger tracking; fixed neutral fingers. Setup_PromptHMR.cmd; People defaults to 2, Interaction Prompt on. |
| PEAR | Live single-person bone preview from a webcam or the video timeline; transient, with lightweight live foot lock and no recording/export or offline correction. | Fingers included; Start/Stop, fixed lengths/Reset Bones, One Euro filter, Rotation and default-on World Position. Shared support is installed by install.cmd. |
Start with the [model guide index](models/README.md), then [ExMR](models/EXMR.md), [FlowHMR](models/FLOWHMR.md), [GVHMR](models/GVHMR.md), [MAMMA](MAMMA.md) or [PromptHMR](models/PROMPTHMR.md) for exact setup and controls. The [user guide](USER_GUIDE.md#recorded-processing-time-and-vram) includes observed timings, conditions and VRAM; these are historical measurements, not minimum specifications. FlowHMR has a 5,000-frame per-take limit and available memory may require less. MAMMA retains its 4–1,800-frame common trim and eight-person limits; there is no fixed camera-count maximum. Four-column thumbnails are a layout, not admission control. Do not change numerical precision, temporal context or model settings merely to improve a benchmark.
@@ -91,6 +91,16 @@ install inside the running app. After updates, rerun the relevant optional setup
when requested by its dependency/runtime notice. Keep verified installed packages
isolated even when Torch versions match. Models are obtained separately.
+PromptHMR supporting downloads use `cache/prompthmr/torch/hub/` and
+`cache/prompthmr/hf/`, independently of video/result generations. The first empty
+cache may need internet access. `prompthmr_cache.py` checks known old project
+locations with bounded directory/hash work and imports only the exact verified
+DeepLab weights; it preserves old files and does not copy executable Hub code.
+Use the printed shared-cache location to diagnose repeated downloads. The 14 base files and two optional Moving Camera files are scoped separately. The Model Manager count excludes supplementary download caches. A reviewed exact
+pipeline-hash pair preserves valid existing inference receipts for this cache-only
+fix; do not extend that exception to numerical/weight changes. No optional-runtime
+rebuild is required. See [supporting downloads](models/PROMPTHMR.md#shared-supporting-model-download-cache).
+
Model files are in `<installation>/models/` by default. To reuse a legitimate installation, close both apps, copy the complete models folder and its receipt/license files beside `RGBMoCap.cmd`, and check readiness in Model Manager. Do not copy old `runtime*` folders. SMPL Neutral is required by PromptHMR, although it is not required for ExMR/FlowHMR/GVHMR. Standard SMPL-X Neutral is shared by ExMR/GVHMR/PromptHMR; MAMMA uses its separate locked-head bodies. Exact requirements are defined by `mocap/models.py` and the chosen stages, not by guessed filenames.
## Standard GUI workflow
@@ -102,7 +112,7 @@ separate pinned Python 3.11 runtime, not a MAMMA overlay or part of install.cmd.
Setup_PromptHMR.cmd downloads restricted upstream source, builds SAM2 with
Visual Studio 2022/CUDA Toolkit 12.8 and verifies actual CUDA operations. It
reuses standard registered SMPL-X/SMPL bodies, not MAMMA's locked-head body.
-Only fixed-camera video is integrated. Find person is hidden; actors retain one
+Fixed Camera is the default. Optional Moving Camera uses DroidCalib + Metric3D after a separately verified camera build. Find person is hidden; actors retain one
shared inferred world. The adapter accepts 4–1,800 working frames at 30 fps and
up to eight people. Both resource modes keep one-image batches and full temporal
context; extra offloading is not implemented. Preserve actual memory monitoring.
@@ -146,6 +156,34 @@ motion and the native raw result. Older published finger poses need Reconstruct
3D with a verified inference cache; Prepare Preview alone does not republish them. Optional contact
correction is a subsequent intentional pose change. Preserve other runtimes.
+### PromptHMR moving-camera extension
+
+`Setup_PromptHMR.cmd` asks separately whether to prepare camera support. Keep
+the base runtime usable when that optional build fails. The camera setup reuses
+the verified base Python/Torch; `tools/setup_prompthmr_camera.py` stages pinned
+Eigen/LieTorch sources and torch-scatter, restores build-only Torch/Python link
+libraries from the verified archives/bootstrap, builds for the actual GPU,
+and exercises LieTorch forward/backward, scatter and DroidCalib CUDA operations.
+Only then atomically register `.setup/prompthmr-camera-runtime.json`. Preserve
+previous registrations, packages, projects and weights on any failure.
+
+`installer/prompthmr_camera_adapters.py` prefixes CUDA kernel names to avoid
+MSVC merging CPU templates with GPU launch stubs, uses int64 tensor indices,
+and relative compilation source paths to avoid duplicated long object paths.
+Do not revert these compatibility fixes or mark imports alone as validation.
+Compiler tools and temporary build data are not installed runtime size.
+
+`mocap/prompthmr_camera.py` loads the two SHA-256 checked camera weights,
+invokes the pinned masked DroidCalib/Metric3D equations, uses Torch SDPA for
+Metric3D attention and one-image depth batches. Keep full temporal context and
+the actual memory guards. Invalid tracking must fail, not silently switch modes.
+The camera module identity/weights are included only for moving inference.
+`prompthmr_publish.py` preserves the common world, derives each frame's incam
+body transform with the registered pelvis pivot, and commits the native camera
+track for overlays/gizmos/Blender export. The common scene/floor anchor remains
+constant; never independently rotate/space actors or derive camera motion from
+the corrected pose. Older projects without a camera option stay fixed.
+
### MAMMA setup and verification
MAMMA runs an optional complete multi-view pipeline using a separate pinned
@@ -198,6 +236,24 @@ notices. Existing saved previews are not automatically replaced; use Apply
Correction to recompute without inference. See the v9 measurements and limits
in [validation](VALIDATION.md#contact-correction-v9-coherent-root-and-swing-transitions-2026-10-30).
+### Preview-video export
+
+**File > Export Preview...** saves one MP4 pairing the selected input-camera
+video with the actual current 3D viewport over the timeline trim. Preserve the
+user's camera/framing, visibility, overlays and Follow Actor choice. PEAR is
+excluded. The output uses timeline FPS and selected-source audio when present;
+it does not run inference, correction or skeleton export. See
+[Preview video](USER_GUIDE.md#preview-video).
+
+`preview_export_ui.py` waits for matching decoded video/3D frame indices and
+character matrices, captures the existing framebuffer on the GUI thread and
+restores frame/camera/playback afterward. `preview_export.py` composes and encodes
+off the GUI thread with a one-frame handoff, bounded FFmpeg logs and existing
+FFmpeg. Keep the window/viewport geometry fixed during capture, reject changing
+input generations and atomically replace only a finished destination. Cancel
+and window close must reap the encoder before destroying its QThread. Keep test
+projects, input media and output videos outside the public source package.
+
### Saved camera display and source export implementation
`mocap/camera_tracks.py` adapts committed camera receipts without inference or
@@ -208,7 +264,10 @@ app's Y-up world. FlowHMR/ExMR use saved rotation tracks. Flow gizmos additional
unscaled VGGT displacement; moving-camera ExMR gizmos use estimated displacement
from ORIGINAL paired world/camera root positions, never corrected poses.
Motion x defaults to 1, with 0 retaining a fixed center. Video overlay projection
-remains unchanged when this display scale changes. MAMMA/GVHMR remain fixed. Other models expose their saved reference camera only. Do not interpret
+remains unchanged when this display scale changes. PromptHMR Moving Camera uses
+its native saved per-frame DroidCalib/Metric3D trajectory for world fitting,
+overlays and Blender camera animation, without a gizmo-only translation scale.
+MAMMA/GVHMR and PromptHMR Fixed Camera remain fixed. Do not interpret
an extrinsic translation vector as the camera center: use `-R.T @ t`.
Single-person ExMR/GVHMR may also have no shared-scene camera receipt.
@@ -417,7 +476,7 @@ The app uses separate runtime profiles to maintain compatibility, with bounded b
- GUI, people, controls and logging: `mocap/gui.py`, `workspace_ui.py`, `people_ui.py`, `character_ui.py`, `console_log.py`, `tooltips.py`.
- Model selection and loading: `mocap/motion_tools.py`, `models.py`, `model_guide.py`; worker routing and runtimes: `worker.py`, `worker_progress.py`, `runtime_registry.py`, `compute_policy.py`.
- MAMMA inputs/UI: `mocap/mamma_inputs.py`, `mamma_ui.py`; processing: `mamma_pipeline.py`, `mamma_camera.py`, `mamma_publish.py`, `mamma_body.py`; runtime/assets: `mamma_runtime.py`, `mamma_manager.py`, `mamma_models.py`, `installer/mamma-runtime-lock.json`, `tools/setup_mamma.py`. Follow [the native-build runbook](MAMMA_AGENT_SETUP.md) instead of guessing module build commands.
-- PromptHMR UI/pipeline: `mocap/prompthmr_ui.py`, `prompthmr_pipeline.py`, `prompthmr_publish.py`, `prompthmr_scene.py`; runtime/assets: `prompthmr_runtime.py`, `prompthmr_manager.py`, `prompthmr_models.py`, `prompthmr_worker_boot.py`, `installer/prompthmr-runtime-lock.json`, `installer/prompthmr_adapters.py`, `installer/verify_prompthmr.py`, `tools/setup_prompthmr.py`. Follow the separate setup/verification steps above.
+- PromptHMR UI/pipeline: `mocap/prompthmr_ui.py`, `prompthmr_pipeline.py`, `prompthmr_cache.py`, `prompthmr_publish.py`, `prompthmr_scene.py`; runtime/assets: `prompthmr_runtime.py`, `prompthmr_manager.py`, `prompthmr_models.py`, `prompthmr_worker_boot.py`, `installer/prompthmr-runtime-lock.json`, `installer/prompthmr_adapters.py`, `installer/verify_prompthmr.py`, `tools/setup_prompthmr.py`. Follow the separate setup/verification steps above.
- Project storage: `project_storage.py`, `project_workspace.py`, `project_save.py`; contact correction: `correction.py`, `contact_trajectory.py`, `contact_pose_plan.py`, `contact_arm_plan.py`.
- Source mesh / bone fit and preview: `source_animation.py`, `source_surface.py`, `surface_roll.py`, `preview_data.py`, `viewer.py`, `viewport.py`; source export: `fbx_export.py`, `fbx_writer.py`, `scene_export.py`.
- Character pipeline: `mocap/retarget/` plus `character_data.py` and `character_ui.py`; Blender backend and model-specific constraints must be considered separately from source-person export.
diff --git a/docs/BUILD.md b/docs/BUILD.md
index 913d6c8..fb6ea8b 100644
--- a/docs/BUILD.md
+++ b/docs/BUILD.md
@@ -24,7 +24,9 @@ still depends on the NVIDIA driver and installed wheels.
Optional PromptHMR has a separate pinned Python 3.11 environment installed with
`Setup_PromptHMR.cmd`. It also needs C++ tools and CUDA Toolkit 12.8 to build
-SAM2; MAMMA/SDF is not required. Read [its setup/developer notes](models/PROMPTHMR.md)
+SAM2. Choosing Y for its optional moving-camera support also builds
+DroidCalib/LieTorch over that same environment and verifies actual CUDA operations;
+MAMMA/SDF is not required. Read [its setup/developer notes](models/PROMPTHMR.md)
before changing its lock, adapters, native modules or model paths.
## Environments
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 12d1c97..d9e4697 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -8,7 +8,8 @@ characters, and exporting animation for Blender or MMD. Processing runs locally.
For optional single-video capture of people together, see the
[PromptHMR setup and usage guide](models/PROMPTHMR.md). It supports fixed-camera
-video through a separate `Setup_PromptHMR.cmd` runtime, with a People count and
+video by default and optional moving-camera tracking through a separate
+`Setup_PromptHMR.cmd` runtime, with a People count and
Interaction Prompt option. It performs its own tracking and does not generate
animated fingers. Standard correction, retargeting and FBX controls apply.
@@ -145,7 +146,7 @@ Setup_PromptHMR.cmd
Review its license prompt, reopen the app, select **PromptHMR** and prepare all
files in **Model Manager**. This setup is independent of MAMMA and is also excluded
from `install.cmd`/`update.cmd`. The [PromptHMR guide](models/PROMPTHMR.md) lists
-the exact files, fixed-camera limits, native-build verification and repair steps.
+the exact files, camera modes, native-build verification and repair steps.
The Model Manager's **Runtime Setup...** button shows instructions; it does not
run installation inside the app.
@@ -181,7 +182,7 @@ Shared model files and hardlinks are counted once.
| --- | ---: | ---: | ---: |
| ExMR + FlowHMR + GVHMR, including supported add-ons | 12.35 GiB | 28.89 GiB | 41.23 GiB |
| MAMMA additional files | 6.11 GiB | 3.53 GiB | 9.65 GiB |
-| PromptHMR additional files | 6.22 GiB | 6.13 GiB | 12.34 GiB |
+| PromptHMR additional files, Fixed Camera | 6.22 GiB | 6.13 GiB | 12.34 GiB |
| **Five offline models** | **24.68 GiB** | **38.55 GiB** | **63.22 GiB** |
| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.84 GiB | ~2.85 GiB |
@@ -199,6 +200,12 @@ already counted in the base set. Its specific weights/support files alone total
about 6.09 GiB. Installed Python packages remain separate; verified identical
download archives can be reused without merging runtimes.
+The totals above exclude optional PromptHMR moving-camera support: its verified
+extension measured **18.6 MiB**, plus **1.55 GiB** of DroidCalib/Metric3D weights.
+Including these adds about **1.57 GiB**, bringing the five offline sets to about
+**64.79 GiB**, or about **67.64 GiB** with PEAR. Allow a separate **6 GiB free
+during the native camera build**, excluding weights and compiler tools.
+
**MAMMA and PromptHMR are separate optional runtime installations.** After
`install.cmd`, use `Setup_MAMMA.cmd` or `Setup_PromptHMR.cmd` for the model you
need, then prepare its weights in Model Manager. Neither requires the other.
@@ -222,13 +229,14 @@ may be outside the installation folder.
| Location | What you can remove and what happens |
| --- | --- |
-| `<install folder>\cache\` | Its contents can be deleted. This includes `huggingface`, `torch` and ExMR support caches. They are recreated or downloaded again when needed; the next run may take longer and require internet access. Saved projects and the separate `models` library remain. |
+| `<install folder>\cache\` | Its contents can be deleted. This includes `huggingface`, `torch`, ExMR support caches and PromptHMR's shared `prompthmr/torch` and `prompthmr/hf` downloads. They are recreated or downloaded again when needed; the next run may take longer and require internet access. Saved projects and the separate `models` library remain. |
| `<install folder>\projects\<project folder>\` | Delete an entire unwanted project folder. This removes its model results, prepared videos, previews, contact edits and imported/retargeted characters. Reprocessing requires the source video and AI inference; manual edits are lost. Keep projects you still need. |
| Your **Save Project As** destination | The same rule applies to each saved project folder at your chosen location. It contains a copy of the video and project data. Deleting it removes that copy; cleaning the default `projects` folder does not clean external copies. |
| `<install folder>\character_scenes\<session folder>\` | Contains characters imported before a project was opened. Old session folders can be deleted once those imports are no longer needed or have been copied into a saved project. Unsaved session imports are lost. |
| `<install folder>\.setup\downloads\`, `.setup\uv-cache\` and `.setup\tmp\` | Downloaded wheels and temporary cache can be removed only after installation or update completes. They are reused for repair and updates; deleting them may require downloading files again. Keep the rest of `.setup`, including the private Python and installation state. |
| `<install folder>\.setup\mamma-downloads\` | Optional MAMMA package/source download cache. Its contents can be removed after MAMMA setup finishes; repair may need to download them again. Keep `runtime_mamma` and `.setup/mamma-runtime.json`. |
| `<install folder>\.setup\prompthmr-downloads\` | Optional PromptHMR package/source download cache. Remove contents only after setup finishes; repair may need to download them again. Keep `runtime_prompthmr` and `.setup/prompthmr-runtime.json`. |
+| `<install folder>\.setup\prompthmr-camera-downloads\` | Optional moving-camera source/package download cache. Its contents can be removed after setup finishes. Repair may download them again. Keep `runtime_prompthmr/camera-*` and `.setup/prompthmr-camera-runtime.json`. |
| `<install folder>\.setup\pear-downloads\` | PEAR source/support and camera-alignment archives. Contents can be removed after installation/update finishes; repair may download them again. Keep `runtime_pear`, `.setup/pear-runtime.json` and `.setup/pear-alignment.json`. |
| `<install folder>\temp\` | Local PEAR Torch/kernel temporary cache. Contents can be removed after closing the app and its workers; the next run can recreate them. |
@@ -265,7 +273,7 @@ For ExMR, FlowHMR and GVHMR:
For synchronized multi-camera capture, select MAMMA before opening videos and
follow the [MAMMA workflow](MAMMA.md#reconstruct-and-export). It detects people
during reconstruction, so the **Find person** step is not used. PromptHMR also
-tracks people during reconstruction; open one fixed-camera video and start with
+tracks people during reconstruction; open one video, choose its camera mode and start with
**People = 2** and **Interaction Prompt** on. See [its workflow](models/PROMPTHMR.md#controls-and-supported-workflow).
To animate a character, follow [Character retargeting](#character-retargeting),
@@ -319,7 +327,7 @@ opening a project restores its saved model. **Prepare Preview**, below
| **FlowHMR** | Slow, but the best overall motion quality in our tests. | Included. |
| **GVHMR** | Lowest overall quality in our tests, but sometimes better for unusual poses such as backflips. | Optional **HandFlow**; not inferred by GVHMR itself. |
| **MAMMA** | Multi-view capture of human motion and interactions. Needs separate setup and overlapping synchronized views; outside the quality ranking above. | Included. |
-| **PromptHMR** | Can improve relative placement and interactions between multiple people in one fixed-camera video. Overall motion quality was lower than ExMR in our subjective tests; contacts and depth can still be wrong. Separate setup. | No finger tracking; fixed neutral pose. |
+| **PromptHMR** | Can improve relative placement and interactions between multiple people in one video. Fixed Camera is the default; Moving Camera needs optional camera setup. Overall motion quality was lower than ExMR in our subjective tests; contacts and depth can still be wrong. | No finger tracking; fixed neutral pose. |
| **PEAR** | Live single-person bone preview from a webcam or video. Lightweight live foot lock; no offline correction, recording, retargeting or export. | Included. |
The five offline models support contact correction, a 52-bone overlay, FBX/BVH export and portable Blender bundles.
@@ -498,7 +506,7 @@ selected result is missing, reconstruct it; the app reports it as unavailable.
| **MAMMA → Import Camera Data...** | Import calibration with camera names matching video filenames without extensions, original pixel intrinsics and metric translations. See the exact [camera format](MAMMA.md#manual-cameras). |
| **MAMMA → People** | Default 0 automatically detects people during reconstruction; set 1–8 if someone is missed or background people are included. Count each person once across all cameras. Find person is hidden. |
| **MAMMA → Reference Height (m)** | Numeric approximate standing height, default 1.70 m. Sets VGGT scene scale, not every actor's height; unused with metric manual calibration. |
-| **PromptHMR → People / Interaction Prompt** | People defaults to 2; 0 detects automatically up to eight. Interaction Prompt defaults on; off follows the official default video path. Fixed cameras only; no animated fingers. Both settings apply on Reconstruct 3D. See the [PromptHMR guide](models/PROMPTHMR.md). |
+| **PromptHMR → Camera / People / Interaction Prompt** | People defaults to 2; 0 detects automatically up to eight. Interaction Prompt defaults on; off follows the official default video path. Fixed Camera is the default; optional Moving Camera uses DroidCalib + Metric3D after camera setup and two additional model downloads. No animated fingers. These settings apply on Reconstruct 3D. See the [PromptHMR guide](models/PROMPTHMR.md). |
| **Resource Mode** | Automatic uses the fast path when GPU memory is sufficient and selects supported Low Memory paths when needed. Low Memory uses CPU loading/offloading and existing bounded image processing; it can be slower and use more RAM. The selection and reason appear in Console and the CMD window. |
| **Prepare Preview** | Rebuild mesh/skeleton previews from existing motion without running the AI model again. Useful for older projects. |
| **Cancel Job** | Stop queued processing; completed results are kept. |
@@ -510,7 +518,7 @@ instead of an invented percentage. FlowHMR is limited to 5,000 frames per take
(about 166.7 seconds); available memory may require a shorter clip. MAMMA's
adapter accepts 4–1,800 common frames and at most eight people. It requires
two or more synchronized fixed-camera videos, with no fixed camera-count
-maximum. PromptHMR accepts one fixed-camera video, 4–1,800 working frames at
+maximum. PromptHMR accepts one fixed- or moving-camera video, 4–1,800 working frames at
30 fps and up to eight people. Four thumbnails per row is only a layout choice. These limits do not
guarantee that a workload fits RAM or VRAM.
@@ -657,6 +665,21 @@ The first frame in **Pose Position** shows animation, which can differ from rest
Use the character workflow above for supported humanoids, or retarget the source
FBX in your animation software.
+### Preview video
+
+Use **File > Export Preview...** to choose an MP4 save location. The timeline's
+trimmed range is saved with the currently selected input camera on the left and
+the actual 3D viewport on the right. Arrange the viewport before exporting:
+the current angle, framing, Follow Actor setting, visible people/characters and
+viewport overlays are retained. No new AI inference or correction is run.
+
+The output uses the timeline frame rate and source audio when available.
+Both panels keep their aspect ratios; the current viewport capture and decoded
+video preview determine detail, with the combined image bounded to 3840 × 2160.
+Progress and Cancel are available during saving. Completion/cancellation restores
+the original frame and view; an incomplete export does not replace an existing
+destination. **PEAR live mode does not support preview export.**
+
### Portable Blender projects
Choose **Blender project + video (.blend)** in **File > Export...**, then choose
@@ -733,6 +756,9 @@ bounded display samples. Saved cameras can be outside the current 3D framing;
zoom out or orbit to inspect them.
- MAMMA displays all saved fixed camera calibrations in the fitted shared world.
+- PromptHMR Moving Camera displays its saved native DroidCalib/Metric3D rotation
+ and translation. That same estimated trajectory drives source-video overlays,
+ Camera Preview and Blender camera animation. Fixed Camera retains one camera.
- FlowHMR displays saved rotation and the estimated VGGT displacement path.
Its displacement has no measured metric scale, so the path is approximate.
- ExMR in Moving Camera mode can estimate camera displacement from the original
@@ -740,7 +766,8 @@ zoom out or orbit to inspect them.
measured camera trajectory. Static Camera mode retains a fixed position.
- When **Camera** is enabled in the ordinary 3D view, **Motion x** controls the
estimated movement display: 1 uses the estimate, 0 keeps the camera center fixed.
- The default is 1. This affects camera gizmos and their path only; source video
+ The default is 1 for FlowHMR/ExMR estimates. PromptHMR uses its native trajectory
+ without this display-scale adjustment. This affects camera gizmos and their path only; source video
overlays keep the calibrated projection and exports/motion remain unchanged.
ExMR movement requires a reference take covering the complete video; otherwise
the app shows rotation only with a notice.
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index f0ca264..90c5422 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -1,5 +1,64 @@
# Source package validation
+## PromptHMR shared download cache (2026-11-02)
+
+Torch Hub/Hugging Face download locations now belong to the app's shared
+`cache/prompthmr/` tree instead of each inference generation. Known older
+DeepLab checkpoints are imported only after full SHA-256 verification; directory
+enumeration and legacy hashing are bounded. Old project files are preserved.
+The runtime, model versions, batch size and numerical processing are unchanged.
+An exact reviewed pipeline hash pair retains existing valid inference-cache
+identities, while future source edits invalidate normally.
+
+Private tests covered two different eight-frame clips, including one and two
+people. Original and updated tracking, pose and world/post-optimization stages
+completed with network/download attempts blocked after priming the upstream Hub
+repository source cache. Both updated clips used one shared checkpoint, with no
+per-generation weight downloads. A separate empty-cache test exercised real
+torchvision/Torch Hub weight loading through a local copy of the official
+checkpoint bytes: first use requested one download, the second video requested
+none. This was not a live external-server availability test.
+
+Tracking outputs, camera-space motion, body rotations and shape were exact in
+the two independent comparisons. Fresh 2D keypoints varied by at most 0.000184
+pixels and final world translations by at most 4.64 mm; these end-to-end runs
+are not bitwise identical. Replaying identical camera-motion inputs with matched
+NumPy/Python/OpenCV RNG in the test produced exact world/post-optimization output
+before and after the fix. Production random behavior was not changed. Peak
+allocated VRAM was unchanged per corresponding stage; the two updated worker
+runs took about 42–43 seconds each. These short runs establish neither a quality
+ranking nor a general speed improvement.
+
+Additional checks passed for cross-volume copy fallback, Unicode cache paths,
+invalid-cache rejection, preserving original files, and reusing an actual old
+complete inference receipt without FFmpeg preparation or AI inference. Models,
+input videos and test artifacts remain outside the public source package.
+
+## Side-by-side preview video export (2026-11-02)
+
+File > Export Preview was checked using private copies of an ExMR project with
+an animated PMX character and a two-person MAMMA project with a non-primary
+camera selected. Twelve repeated 30-frame exports per case retained the chosen
+view and restored the original frame/camera. Saved H.264 MP4s decoded to exactly
+30 frames at 30 fps (one second); the selected source's audio was included when
+available. First/last encoded frames matched the submitted video/framebuffer
+pair within normal lossy encoding differences (mean channel error below 3/255).
+The test panels were 1404 × 684 and 1954 × 684; this is not a universal speed or
+resolution guarantee. Rendering still requires GUI-thread framebuffer capture.
+
+Cancellation preserved an existing destination and removed partial output.
+Playback resumed after export when previously running. Closing the app during
+export cancelled and reaped FFmpeg before the window/workers closed. Additional
+checks covered one frame at 30000/1001 fps, an externally changed destination,
+incomplete frame delivery, Unicode output names, input-file overwrite rejection
+and PEAR exclusion. Repeated-export testing caught Python 3.10 DummyThread
+registration through joining a Python log reader from a Qt thread; completion
+now uses an event instead. Handles and thread counts stabilized in the bounded
+repeat test; it does not establish leak freedom for hours of use or other PCs.
+No source inference/contact math or installed dependencies were changed. Test
+scripts, source media, copied projects and rendered videos remain outside the
+public source package.
+
## MAMMA background gravity before fitting (2026-11-02)
Automatic calibration now uses VGGT-Omega camera placement with GeoCalib
@@ -1857,3 +1916,48 @@ leak guarantee or a universal frame-rate claim. The known-rotation background
fixture, original PR equivalence, off restoration, cache invalidation and
worker cancellation checks also passed. Runtime locks, installer scripts,
AI worker and source-correction implementation stayed unchanged.
+
+### Optional PromptHMR moving-camera support (2026-11-02)
+
+- Built the pinned LieTorch/DroidCalib Windows CUDA extensions over the existing
+ PromptHMR Python 3.11 / Torch 2.7.1 CUDA 12.8 runtime. Real LieTorch
+ forward/backward, scatter and DroidCalib CUDA operations passed on RTX 5090
+ (compute capability 12.0). Setup also retained the verified extension on retry.
+ Base runtime pins and installed packages did not change. The installed
+ extension measured 19,547,213 bytes; its two managed weights total
+ 1,664,022,188 bytes. Compiler/download/build caches are excluded.
+- The 80-frame, 30 fps, single-person moving-camera test completed all five
+ normal worker stages, including fresh tracking and correction/export
+ preparation, in 130.3 seconds of wall time. Phase times were 1.4s preparation,
+ 33.2s tracking, 57.2s camera/keypoints/motion, 31.0s world optimization and 7.4s
+ publication/correction. Peak allocated/reserved Torch VRAM was 6.73/6.93 GiB;
+ sampled worker-tree RSS peaked at 7.42 GiB. These are one-PC short-clip
+ observations, not minimum memory or long-clip guarantees.
+- The complete 80-frame camera trajectory loaded both with and without a shared
+ scene context. Published incam translations and rotation matrices matched
+ direct per-frame world-to-camera conversion within 1.2e-7 m and 1.9e-7
+ respectively, including the registered shape-dependent pelvis pivot.
+ Original and corrected sources remained exportable. Blender 4.5 reopened
+ the portable bundle with relative synchronized video and 52 body/finger bones;
+ sampled camera matrix errors stayed below 1.2e-7. Armature objects had no
+ animation keys. These are serialization/coordinate checks, not ground-truth
+ camera-accuracy measurements.
+- A separate eight-frame, two-person fixed-camera regression reran image/video
+ inference and world fitting before/after. Body/root camera-space motion stayed
+ exact; independent GPU runs differed by at most 0.000123 px in saved 2D
+ keypoints and about 3.0 mm in native final world translation. Replaying
+ identical camera-motion intermediates produced exact world outputs across
+ 121 compared arrays in the overall regression. No new physical correction
+ or precision reduction was introduced. An older fixed-camera inference
+ receipt was reused without FFmpeg or inference; moving identities retain
+ their actual camera code/module/model fingerprints.
+- App controls restored Moving Camera, loaded its 80-frame saved track and
+ showed 16/16 ready models. Switching to Fixed Camera showed 14/14 and a
+ reconstruction notice without processing or replacing the current motion.
+ Legacy options restored Fixed Camera. Corrupted extension files, stale or
+ escaped camera paths and a simulated failed repair were rejected; prior
+ registrations and the base runtime remained intact.
+
+No clean Windows installation, other-GPU verification, long-video stability or
+absolute SLAM scale/accuracy claim follows from these checks. Tracking loss,
+zoom/cuts, poor texture and scale drift remain possible.
diff --git a/docs/models/PROMPTHMR.md b/docs/models/PROMPTHMR.md
index 00bacec..0b5586e 100644
--- a/docs/models/PROMPTHMR.md
+++ b/docs/models/PROMPTHMR.md
@@ -49,7 +49,8 @@ review. A PromptHMR setup failure must not prevent the base models from working.
(PowerShell: `.\Setup_PromptHMR.cmd`). Setup downloads pinned sources/packages,
builds SAM2 for the installed
GPU and verifies real CUDA operations before registering the environment.
-4. Reopen the app, select **PromptHMR**, and prepare every file in **Model Manager**.
+4. For moving footage, choose **Y** at the additional moving-camera setup prompt. This builds DroidCalib/LieTorch for the installed GPU and verifies CUDA operations. The existing PromptHMR Python/Torch environment is reused; fixed-camera support remains available if the optional camera build fails. Review the linked DroidCalib AGPL and dependency terms before choosing Y.
+5. Reopen the app, select **PromptHMR**, and prepare the required files in **Model Manager**. The two rows named **Moving Camera** are optional for Fixed Camera.
Google Drive may require a manual browser download; use **Manual Download... >
Import** if automatic downloading fails. **Runtime Setup...** shows instructions
and copies the command; it does not install anything inside the running app.
@@ -72,8 +73,9 @@ files including SMPL Neutral, plus **6.22 GiB** of cache-free runtime, for about
PromptHMR's ViTPose COCO-25, SAM2 tiny and detector checkpoints differ from
similarly named files in other workflows. Imports verify the supported hashes.
-Select **PromptHMR > Model Manager** for the complete 14-file checklist. Locations
-below are relative to `models/`; obtain the exact files listed by the manager.
+Select **PromptHMR > Model Manager** for the 14 base model/body files and two
+optional Moving Camera rows. Locations below are relative to `models/`; obtain
+the exact files listed by the manager.
| Component | Files or folder |
| --- | --- |
@@ -84,6 +86,31 @@ below are relative to `models/`; obtain the exact files listed by the manager.
| Body correspondence / means / regressors | Four files under `prompthmr/body_models/`, listed individually in Model Manager |
| Registered standard bodies | `body_models/smplx/SMPLX_NEUTRAL.npz`, `body_models/smpl/SMPL_NEUTRAL.pkl` |
+### Shared supporting-model download cache
+
+The upstream tracking backend also uses torchvision DeepLab segmentation
+weights (about 161 MiB) and Torch Hub source files. These supplementary downloads
+are stored once under `cache/prompthmr/torch/hub/` and reused across videos and
+reconstruction attempts. Hugging Face downloads use `cache/prompthmr/hf/`.
+Readiness counts 14 base files in Fixed Camera and 16 files in Moving Camera;
+these supplementary caches are not part of either count.
+The first use of an empty cache may require internet access.
+
+The connector first checks known old project `torch-cache/hub/checkpoints`
+locations and imports the supported DeepLab weights only after full SHA-256
+verification. It hardlinks when possible, otherwise copies once. Existing
+projects and their caches are preserved; downloaded Python Hub source trees
+are not imported from old projects. The Console/CMD prints the shared cache path
+and successful weight reuse. An invalid shared DeepLab file produces a checksum
+error instead of being loaded silently.
+
+After confirming a successful updated run and closing the app, old
+`<project>/prompthmr/inference/<generation>/torch-cache/` folders may be removed
+to reclaim duplicate downloads. Keep the other inference/result files. Deleting
+the new shared cache is also allowed, but its downloads will be needed again.
+This cache reuse needs no runtime reinstall. Moving-camera inference has a
+separate optional native setup and two managed weights, described below.
+
On one volume, the connector hardlinks verified weights into the private engine
without storing another copy. If hardlinks are unavailable, it reports the copy
and uses extra disk space. Installed Python packages remain separate.
@@ -113,10 +140,55 @@ of rebuilding the runtime. If native GPU verification fails after moving to
another GPU architecture, run setup on that PC; do not copy compiled modules
from an arbitrary machine or edit registration files to mark them Ready.
+## Moving-camera setup and behavior
+
+Close the app and rerun `Setup_PromptHMR.cmd`, choosing **Y** for moving-camera
+support. The base runtime is verified and retained. A separate, versioned native
+support folder is built over its pinned Python 3.11 / Torch 2.7.1 CUDA 12.8;
+other model runtimes are not changed. No Linux, WSL or Docker is required.
+The verified installed camera extension measured **18.6 MiB** on the test PC,
+excluding build archives and weights.
+Use Visual Studio 2022 C++ Build Tools / Windows SDK and CUDA Toolkit 12.8.
+Allow an additional **6 GiB free for building**, excluding models and compiler
+tools. Downloaded build archives are retained separately from installed modules.
+
+Prepare **DroidCalib** (16,049,525 bytes) and **Metric3D ViT-Large**
+(1,647,972,663 bytes) in Model Manager. Together they add **1.55 GiB**
+(1.66 GB) of weights, separate from the 14 base model/body files. Imports and
+downloads use the declared SHA-256 hashes. Tracking masks, PromptHMR weights,
+SPEC gravity and registered bodies are reused. Metric3D reads the verified file
+directly; it does not download another copy into each video generation.
+
+Select Moving Camera and **Reconstruct 3D**. The official masked DroidCalib
+path estimates background camera poses and refines a constant focal length;
+Metric3D provides an estimated metric scale. Native world fitting and
+post-optimization use this trajectory, preserving the joint multi-person scene.
+The usual optional app correction is applied afterward. The saved track also
+drives Camera Preview, source-video bone overlays, viewport camera gizmos and
+portable Blender camera animation. Display controls do not rerun inference.
+
+Moving-camera results have separate inference identities, including camera
+modules and model stamps. Changing the mode requires reconstruction; the previous
+result stays available until replacement succeeds. Missing/modified support or
+failed tracking produces an error rather than silently substituting a fixed
+camera. These are estimated poses/scale, not measured camera calibration. Foot
+height, drift, missed masks and occlusion can still affect the motion.
+
+Windows adaptations retain the SLAM equations and full frame sequence, use
+64-bit tensor indices, avoid CPU/CUDA kernel-name collisions, and use native
+Torch SDPA for Metric3D attention. Depth batches are one image in both resource
+modes; the keyframe buffer covers the selected clip plus trajectory-fill slots.
+The existing memory/OOM guards remain active; long trims can need much more
+memory. Additional PromptHMR block offloading is not implemented.
+
+Camera setup logs: `.setup/logs/prompthmr-camera-*.log`.
+Registration: `.setup/prompthmr-camera-runtime.json`. Never edit it to bypass a
+failed build. Rerun setup on a new GPU architecture. Providers' source/licenses
+are downloaded locally; compiled camera modules and weights are not in Git.
+
## Controls and supported workflow
-- **One fixed-camera video**, without camera movement or zoom. Moving-camera
- DROID is not implemented in this Windows integration.
+- **One video**. **Camera > Fixed Camera** is the default and preserves the previous workflow. **Moving Camera / DroidCalib + Metric3D** tracks camera rotation and translation from the background. It requires the optional camera build and two additional models. Continuous focal-length changes/zoom, shot cuts, blur and poor background texture can break tracking or scale.
- **People** defaults to **2**. **0** detects automatically, up to eight. This is
a maximum count, not an identity selector. The intended people should be
visible near the start; background people and occlusion can confuse tracking.
@@ -157,6 +229,18 @@ NMS and native attention on the user's GPU.
## Recorded validation
+A moving-camera test used 80 frames at 30 fps (2.67 seconds), one person and
+the existing RTX 5090 test PC. The installed Windows path completed preparation,
+fresh tracking, DroidCalib/Metric3D, motion inference, native world optimization
+and app correction/export preparation in **130.3 seconds** including process
+startup. Stage wall times were 1.4 / 33.2 / 57.2 / 31.0 / 7.4 seconds.
+Peak PyTorch allocated VRAM was **6.73 GiB**, reserved **6.93 GiB**; sampled
+worker-tree RAM peaked at **7.42 GiB**. Other GPU allocations can add to that.
+This short sample is not a long-video capacity or camera-accuracy benchmark.
+The saved 80-frame camera track loaded in the app and exported as Blender
+camera animation with synchronized relative video. A two-person fixed-camera
+regression and reuse of an older fixed-camera inference receipt also passed.
+
A 422-frame, 14.1-second, two-person fixed-camera clip completed in **3 min 56 sec**
on the documented RTX 5090 test PC, with Interaction Prompt and app correction
enabled. Preparation took 4.8 s; tracking 73.5 s; camera/keypoints/motion 103.0 s;
@@ -200,12 +284,15 @@ and four Blender FBX imports retained fixed local finger rotations.
| Weights | `models/prompthmr/`, shared `models/body_models/` |
| Runtime | `runtime_prompthmr/<generation>/` |
| Runtime registration | `.setup/prompthmr-runtime.json` |
+| Optional camera extension / registration | `runtime_prompthmr/camera-<generation>/`, `.setup/prompthmr-camera-runtime.json` |
+| Shared supporting downloads | `cache/prompthmr/torch/hub/`, `cache/prompthmr/hf/` |
| Setup logs / retained archives | `.setup/logs/prompthmr-*.log`, `.setup/prompthmr-downloads/` |
| Native inference | `<project>/prompthmr/inference/<generation>/results.pkl` |
| Published actors/takes | `<project>/prompthmr/results/<generation>/` |
| Lock / Windows adaptations / CUDA verification | `installer/prompthmr-runtime-lock.json`, `installer/prompthmr_adapters.py`, `installer/verify_prompthmr.py` |
| Setup implementation | `tools/setup_prompthmr.py` |
-| App connector | `mocap/prompthmr_pipeline.py`, `prompthmr_publish.py`, `prompthmr_scene.py`, `prompthmr_ui.py`, `prompthmr_runtime.py` |
+| Camera build / verification | `tools/setup_prompthmr_camera.py`, `installer/prompthmr-camera-lock.json`, `installer/prompthmr_camera_adapters.py`, `installer/verify_prompthmr_camera.py` |
+| App connector | `mocap/prompthmr_pipeline.py`, `prompthmr_cache.py`, `prompthmr_publish.py`, `prompthmr_scene.py`, `prompthmr_ui.py`, `prompthmr_runtime.py` |
Native inference, derived correction and export generations remain separate.
Cancelled/incomplete new work does not replace the saved active project. Verified
diff --git a/docs/models/README.md b/docs/models/README.md
index bce69e8..0884f26 100644
--- a/docs/models/README.md
+++ b/docs/models/README.md
@@ -10,7 +10,7 @@ saved selection. Only implemented tools appear in the list.
| FlowHMR | One video; SMPL-H | Included | [FlowHMR](FLOWHMR.md) |
| GVHMR | One video; SMPL-X | Optional HandFlow | [GVHMR](GVHMR.md) |
| MAMMA | Two or more synchronized fixed-camera videos; SMPL-X | Included | [MAMMA](../MAMMA.md) |
-| PromptHMR | One fixed-camera video; jointly reconstructed people; SMPL-X | Not generated | [PromptHMR](PROMPTHMR.md) |
+| PromptHMR | One video; fixed or optional moving camera; jointly reconstructed people; SMPL-X | Not generated | [PromptHMR](PROMPTHMR.md) |
| PEAR | Experimental real-time tracking from webcam or video input; one person, one or multiple fixed views; may be unstable | Included | [PEAR](PEAR.md) |
One-video input does not mean one-person output. ExMR, FlowHMR and GVHMR can
diff --git a/installer/prompthmr-camera-lock.json b/installer/prompthmr-camera-lock.json
new file mode 100644
index 0000000..42f0f66
--- /dev/null
+++ b/installer/prompthmr-camera-lock.json
@@ -0,0 +1,25 @@
+{
+ "version": 1,
+ "sources": {
+ "lietorch": {
+ "url": "https://codeload.github.com/princeton-vl/lietorch/zip/0fa9ce8ffca86d985eca9e189a99690d6f3d4df6",
+ "sha256": "6bcb0b37cebf8f33e53ab8779d618228914ddf78688e6c947377e509b49f45bb",
+ "bytes": 6115383,
+ "commit": "0fa9ce8ffca86d985eca9e189a99690d6f3d4df6",
+ "archive_root": "lietorch-0fa9ce8ffca86d985eca9e189a99690d6f3d4df6"
+ },
+ "eigen": {
+ "url": "https://gitlab.com/libeigen/eigen/-/archive/3d4ba855e014987cad86d62a8dff533492255695/eigen-3d4ba855e014987cad86d62a8dff533492255695.zip",
+ "sha256": "845304ac33fda4c5b7049ece2c6f91e1f6056d4f4dbbfb85fc35e0b8636f4087",
+ "bytes": 3836608,
+ "commit": "3d4ba855e014987cad86d62a8dff533492255695",
+ "archive_root": "eigen-3d4ba855e014987cad86d62a8dff533492255695"
+ }
+ },
+ "scatter": {
+ "url": "https://data.pyg.org/whl/torch-2.7.0%2Bcu128/torch_scatter-2.1.2%2Bpt27cu128-cp311-cp311-win_amd64.whl",
+ "bytes": 3592648,
+ "sha256": "a02ca9018503bfe6ecf4dc7868fa7e832803dfaaf113bdaab7811ca94547fff7",
+ "filename": "torch_scatter-2.1.2+pt27cu128-cp311-cp311-win_amd64.whl"
+ }
+}
diff --git a/installer/prompthmr_camera_adapters.py b/installer/prompthmr_camera_adapters.py
new file mode 100644
index 0000000..f55ff5a
--- /dev/null
+++ b/installer/prompthmr_camera_adapters.py
@@ -0,0 +1,45 @@
+"""Windows build adaptations for separately downloaded DroidCalib/LieTorch.
+
+The providers' sources and licenses stay in the private support installation.
+These changes adapt compiler/PyTorch interfaces, not the SLAM equations.
+"""
+from pathlib import Path
+import shutil,re
+
+
+def prepare(source,engine):
+ source=Path(source);engine=Path(engine)
+ # Python modules use absolute imports inside the upstream droid_slam folder.
+ shutil.copytree(engine/'pipeline/droidcalib/droid_slam',source/'droid_slam')
+ shutil.copytree(engine/'pipeline/droidcalib/src',source/'src')
+ for name in ('LICENSE','3rd-party-licenses.txt'):
+ shutil.copy2(engine/'pipeline/droidcalib'/name,source/name)
+ for path in source.rglob('*'):
+ if path.suffix in ('.cpp','.cu'):
+ text=path.read_text(encoding='utf8').replace('.type(),','.scalar_type(),')
+ if path.parent==source/'src':text=re.sub(r'\blong\b','int64_t',text)
+ if path.name=='lietorch_gpu.cu':
+ # MSVC otherwise gives CPU templates and __global__ launch
+ # stubs identical decorated names; the linker can select the
+ # CPU body and dereference a CUDA pointer on the host.
+ for name in re.findall(r'__global__ void (\w+)\(',text):
+ text=re.sub(r'\b'+name+r'\b','lietorch_cuda_'+name,text)
+ path.write_text(text,encoding='utf8')
+ masked=(engine/'pipeline/camera/masked_droid_slam.py').read_text(encoding='utf8')
+ # Windows worker spawning would duplicate the parent/video/model memory.
+ masked=masked.replace('num_workers=8 if os.cpu_count() > 8 else os.cpu_count()', 'num_workers=0')
+ # Bound Metric3D activation storage without changing its resolution/precision.
+ masked=masked.replace('batch_size = 8','batch_size = 1').replace('batch_size = 32','batch_size = 1')
+ (source/'masked_droid_slam.py').write_text(masked,encoding='utf8')
+ (source/'setup_windows.py').write_text('''from setuptools import setup
+from torch.utils.cpp_extension import BuildExtension,CUDAExtension
+from pathlib import Path
+import os
+S=Path(__file__).resolve().parent
+os.chdir(S)
+args={'cxx':['/O2','/MD','/GL-','/wd4819'], 'nvcc':['-O2','-Xcompiler=/MD','-Xcompiler=/GL-']}
+extensions=[CUDAExtension('lietorch_backends',include_dirs=[str(S/'thirdparty/lietorch/lietorch/include'),str(S/'thirdparty/eigen')],sources=['thirdparty/lietorch/lietorch/src/'+n for n in ('lietorch.cpp','lietorch_gpu.cu','lietorch_cpu.cpp')],extra_compile_args=args),
+CUDAExtension('droid_backends_intr',include_dirs=[str(S/'thirdparty/eigen')],sources=['src/'+n for n in ('droid.cpp','droid_kernels.cu','correlation_kernels.cu','altcorr_kernel.cu')],extra_compile_args=args)]
+for e in extensions:e.library_dirs.append(str(S/'torch-libs'))
+setup(name='rgbmocap-prompthmr-camera',version='0.1',ext_modules=extensions,cmdclass={'build_ext':BuildExtension})
+''',encoding='utf8')
diff --git a/installer/verify_prompthmr_camera.py b/installer/verify_prompthmr_camera.py
new file mode 100644
index 0000000..6976e47
--- /dev/null
+++ b/installer/verify_prompthmr_camera.py
@@ -0,0 +1,26 @@
+"""Exercise native LieTorch, scatter and DroidCalib CUDA operations."""
+from pathlib import Path
+import argparse,json,sys
+
+
+def verify(folder):
+ sys.path.insert(0,str(folder))
+ import torch,lietorch,torch_scatter,droid_backends_intr
+ torch.set_num_threads(2)
+ x=torch.tensor([[.1,.2,.3,.01,.02,.03]],device='cuda',requires_grad=True)
+ transform=lietorch.SE3.exp(x);points=torch.tensor([[1.,2.,3.]],device='cuda')
+ y=transform.act(points);y.sum().backward()
+ if not torch.isfinite(x.grad).all() or not torch.allclose((transform.inv()*transform).matrix(),torch.eye(4,device='cuda')[None],atol=1e-5):raise ValueError('LieTorch CUDA verification failed.')
+ result=torch_scatter.scatter_sum(torch.tensor([1.,2.,3.],device='cuda'),torch.tensor([0,1,0],device='cuda'))
+ if result.tolist()!=[4.,2.]:raise ValueError('Scatter CUDA verification failed.')
+ poses=lietorch.SE3.Identity(2,device='cuda').data;disps=torch.ones((2,8,8),device='cuda')
+ intr=torch.tensor([[10.,10.,4.,4.]]*2,device='cuda');ii=torch.tensor([0],device='cuda');jj=torch.tensor([1],device='cuda')
+ distance=droid_backends_intr.frame_distance(poses,disps,intr[0],ii,jj,.3,2)
+ if not torch.isfinite(distance).all() or distance.abs().max()>.001:raise ValueError('DroidCalib CUDA verification failed.')
+ torch.cuda.synchronize()
+ return dict(compute_capability=list(torch.cuda.get_device_capability()),torch=torch.__version__,cuda=torch.version.cuda,lietorch_cuda=True,scatter_cuda=True,droid_cuda=True)
+
+
+if __name__=='__main__':
+ p=argparse.ArgumentParser();p.add_argument('--folder',type=Path,required=True);p.add_argument('--output',type=Path,required=True);args=p.parse_args()
+ result=verify(args.folder);args.output.write_text(json.dumps(result,indent=2),encoding='utf8');print(json.dumps(result),flush=True)
diff --git a/mocap/camera_tracks.py b/mocap/camera_tracks.py
index ab9d212..5e60274 100644
--- a/mocap/camera_tracks.py
+++ b/mocap/camera_tracks.py
@@ -143,6 +143,16 @@ def load(project,group=None,cancelled=lambda:False,reference_cache=None):
if np.any(np.abs(c.get('distortion_coeffs',[0]))>1e-8):note=warning='Distorted camera videos may not align with the pinhole overlay.'
items.append(record(e['id'],c['intrinsic_matrix'],c['image_size'],m,meta['start'],meta['fps'],'Saved fixed MAMMA calibration'))
if not np.allclose(items[0]['matrices'][0],base,atol=1e-6):raise ValueError('MAMMA camera world changed. Prepare Preview first.')
+ elif model=='prompthmr' and camera.get('camera_track'):
+ from .people_store import root_for
+ saved=camera['camera_track'];p=(project/saved['path']).resolve()
+ root=group or root_for(project,state)
+ if not p.is_relative_to(root) or file_stat(tracked(p))!=saved['stat']:raise ValueError('PromptHMR camera track is stale. Reconstruct 3D.')
+ matrices=load_array(p,'world_to_camera')
+ if matrices.ndim!=3 or matrices.shape[1:]!=(4,4):raise ValueError('Invalid PromptHMR camera track.')
+ [email protected](transform)
+ items=[record('Camera 1',camera['K'],[state['width'],state['height']],matrices,saved['start'],saved['fps'],'Native DroidCalib/Metric3D camera trajectory; metric scale is estimated')]
+ note='Estimated moving camera from masked DroidCalib and Metric3D; tracking and scale can drift.'
elif model in ('flowhmr','exmr'):
root=group or project;meta=read(tracked(root/'project.json'))
if model=='flowhmr':
diff --git a/mocap/gui.py b/mocap/gui.py
index 5bb4ac7..7009489 100644
--- a/mocap/gui.py
+++ b/mocap/gui.py
@@ -134,6 +134,7 @@ class ModelsDialog(QDialog):
keys = ({key for key in STAGE_REQUIREMENTS[self.tool.key+'_assets']} if self.tool.key in ('mamma','prompthmr','pear') else
{key for stage in (*self.tool.stages(refine=True, footmr=True, handflow=True),'people') for key in STAGE_REQUIREMENTS.get(stage, ())})
if self.tool.key=='pear':keys.update(STAGE_REQUIREMENTS['pear_align'])
+ if self.tool.key=='prompthmr':keys.update(STAGE_REQUIREMENTS['prompthmr_camera_assets'])
if self.tool.key=='flowhmr':keys.add('flow_metadata')
# Keep public automatic downloads together, followed by manual-only files.
# Stable sorting preserves the existing component order within each group.
@@ -348,8 +349,9 @@ from .character_ui import CharacterWorkspace
from .mamma_ui import MammaWorkspace
from .prompthmr_ui import PromptHMRWorkspace
from .pear_ui import PearWorkspace
+from .preview_export_ui import PreviewExportWorkspace
-class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace,QMainWindow):
+class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace,QMainWindow):
def __init__(self, video: Path | None = None):
super().__init__()
self.setWindowTitle("RGB MoCap | Motion Workspace")
@@ -402,6 +404,8 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
self.data_loader.tracked_actor_ready.connect(self.tracked_actor_ready)
build_workspace(self)
self.init_characters()
+ self.video_view.frame_presented.connect(self.refresh_preview_export_action)
+ self.scene_loader.ready.connect(self.refresh_preview_export_action)
self.timer = QTimer(self)
self.timer.setTimerType(Qt.PreciseTimer)
self.timer.setInterval(33)
@@ -434,6 +438,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
@read_only_checks
def update_readiness(self):
+ self.export_preview_action.setEnabled(self.preview_export_available())
if self._pear_active:
if hasattr(self,'camera_tools'):self.camera_tools.sync()
self.pear_sync_controls();return
@@ -449,6 +454,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
required = {key for stage in stages for key in STAGE_REQUIREMENTS.get(stage, ())}
if tool.key=='flowhmr' and self.flow_sampling.currentData()==-1:required.discard('flow_vggt')
if tool.key=='mamma' and self.mamma_camera_mode.currentData()=='manual':required.difference_update(('flow_vggt','pear_geocalib'))
+ if tool.key=='prompthmr' and self.prompthmr_camera.currentData()=='moving':required.update(STAGE_REQUIREMENTS['prompthmr_camera_assets'])
unavailable = [BY_KEY[key] for key in sorted(required) if not ready(BY_KEY[key])]
count = len(required) - len(unavailable)
text = f"{tool.label}: {count}/{len(required)} models ready"
@@ -1818,6 +1824,10 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
else:self.load_video(Path(urls[0].toLocalFile()))
def closeEvent(self, event):
+ if getattr(self, '_preview_export', None) is not None:
+ self._preview_export.cancel(close_window=True)
+ event.ignore()
+ return
if self.busy and self.process:
answer = QMessageBox.question(self, "Processing", "Cancel the current job and close the application?")
if answer != QMessageBox.Yes:
diff --git a/mocap/model_guide.py b/mocap/model_guide.py
index 02e8662..141499c 100644
--- a/mocap/model_guide.py
+++ b/mocap/model_guide.py
@@ -26,7 +26,7 @@ PROJECT_URLS = {
}
DESCRIPTIONS = {
'pear':'Experimental support. Tracking and pose estimates may be unstable. Real-time tracking of webcam or video input, with a single-person body and finger bone preview from one or multiple fixed-camera views. Select synchronized videos with Open Video, or assign distinct webcam devices using the camera-count slots and thumbnails. Start Live Tracking attempts Camera Align first, including one camera; VGGT and GeoCalib are needed for alignment. A single view uses estimated body/depth scale; multiple views use triangulation. If alignment fails or its support/models are missing, tracking continues from the selected camera with a visible warning, without camera fusion or aligned foot lock. Use Camera Align to retry. Fixed bone lengths are calibrated once; Reset Bones recalibrates from the displayed pose, then aligns cameras again. World Position is on by default; off fixes pelvis translation while preserving rotation. Body mesh is not computed per live frame. Select a webcam in the table below the video for image preview without loading PEAR; click Start Live Tracking to attempt alignment and begin tracking. Capture stays connected during Start and Camera Align; opened videos can play while models load or align. Choose None for video. Stop releases models and the webcam. Uses YOLOv8s person detection; detector boxes can affect the resulting pose. Rotation and One Euro Filter apply to both sources. One Euro Filter has independent Bone Rotation and World Position checkboxes, both on by default, with shared Filter Strength. The position-filter checkbox is separate from the World Position movement switch. Filtering reduces tremors with some motion-dependent lag and no extra inference. Seeks start from the selected frame; filtering continues during playback. After successful alignment, default-on lightweight Foot Lock stabilizes low, slow feet with smooth causal transitions, fixed lengths and preserved ankle/toe directions. Reach limits and incorrect ground estimates can leave residual sliding. No Find person, recording, offline Motion Correction, retargeting or motion export in this live mode. Single-view pelvis placement assumes a fixed camera. Camera Align estimates background gravity, camera positions, scale and floor; these are not measured calibration and feet can still slide. Changed inputs and Reset Bones trigger realignment. After moving physical cameras, click Camera Align again. Webcam arrival-time pairing is approximate, not hardware sync. Support files are included in install.cmd and update.cmd, reusing the shared runtime without upgrading its packages or requiring a CUDA compiler. Prepare the checkpoint and registered SMPL-X 2020/FLAME geometry bundle in Model Manager. See docs/models/PEAR.md.',
- 'prompthmr': 'Reconstructs multiple people together from one video. In our subjective tests, it could give more accurate relative placement and interactions, but overall motion quality was lower than ExMR. Contacts, depth and intersections can still be wrong. Fixed cameras only in this Windows integration. People defaults to 2; 0 detects automatically, up to 8. Find person is not needed. Interaction Prompt defaults on; off follows the official default video path. Body motion uses SMPL-X. No finger tracking; untracked fingers use a fixed neutral pose. Supports the usual optional foot/hand contact correction, retargeting and FBX/BVH/Blender export. Requires Setup_PromptHMR.cmd and separate weights. Non-commercial scientific research license. See docs/models/PROMPTHMR.md.',
+ 'prompthmr': 'Reconstructs multiple people together from one video. In our subjective tests, it could give more accurate relative placement and interactions, but overall motion quality was lower than ExMR. Contacts, depth and intersections can still be wrong. Fixed Camera is the default; optional Moving Camera uses masked DroidCalib + Metric3D, with a separate camera build and two additional models. Estimated tracking/scale can drift. People defaults to 2; 0 detects automatically, up to 8. Find person is not needed. Interaction Prompt defaults on; off follows the official default video path. Body motion uses SMPL-X. No finger tracking; untracked fingers use a fixed neutral pose. Supports the usual optional foot/hand contact correction, retargeting and FBX/BVH/Blender export. Requires Setup_PromptHMR.cmd and separate weights. Non-commercial scientific research license. See docs/models/PROMPTHMR.md.',
'mamma': 'Multi-view reconstruction of one or several people from two or more synchronized fixed-camera videos of the same performance. No fixed camera-count maximum; practical capacity depends on available RAM and VRAM. Detects people automatically; Find person is not needed. Uses SAM 2.1 masks and FP32 landmarks. Automatic cameras combine VGGT-Omega placement with GeoCalib background gravity before 3D fitting; manual calibration bypasses both. GeoCalib uses the base Flow support overlay and a shared checkpoint in Model Manager. Unreliable gravity needs manual calibration or clearer views; it does not fall back to the person as a vertical reference. Body and finger motion, original results and contact-corrected results are preserved. Best suited to views that complement each other; occlusion and bad masks can cause errors. Slower than single-video methods. Requires the separate Setup_MAMMA.cmd runtime and registered restricted-use models. See Model Manager > Runtime Setup and docs/MAMMA.md.',
'gvhmr': 'Lowest overall motion quality in our tests, but sometimes better for unusual poses such as backflips. '
'No native finger tracking. Optional HandFlow adds finger motion; FootMR refines ankles, and HTD refines body motion. These add processing time.',
diff --git a/mocap/models.py b/mocap/models.py
index 6f68d4f..9baf8c4 100644
--- a/mocap/models.py
+++ b/mocap/models.py
@@ -99,7 +99,7 @@ MODELS_LIST.extend([
])
from .mamma_models import ASSETS as MAMMA_ASSETS, KEYS as MAMMA_KEYS, INSTRUCTIONS as MAMMA_INSTRUCTIONS
MODELS_LIST.extend(Model(**entry) for entry in MAMMA_ASSETS)
-from .prompthmr_models import ASSETS as PHMR_ASSETS,KEYS as PHMR_KEYS,INSTRUCTIONS as PHMR_INSTRUCTIONS
+from .prompthmr_models import ASSETS as PHMR_ASSETS,KEYS as PHMR_KEYS,CAMERA_KEYS as PHMR_CAMERA_KEYS,INSTRUCTIONS as PHMR_INSTRUCTIONS
from .pear_models import ASSETS as PEAR_ASSETS,KEYS as PEAR_KEYS,INSTRUCTIONS as PEAR_INSTRUCTIONS
MODELS_LIST.extend(Model(**entry) for entry in PEAR_ASSETS)
MODELS_LIST.extend(Model(**entry) for entry in PHMR_ASSETS)
@@ -228,6 +228,7 @@ def manual_instructions_html(key: str) -> str:
STAGE_REQUIREMENTS = {
+ 'prompthmr_camera_assets': PHMR_CAMERA_KEYS,
'pear_assets': ('pear','pear_geometry','pear_yolo'),
'pear_align': ('flow_vggt','pear_geocalib'),
"people": ("yolo", "person_reid"),
diff --git a/mocap/pear_ui.py b/mocap/pear_ui.py
index 7e0d345..1b33d06 100644
--- a/mocap/pear_ui.py
+++ b/mocap/pear_ui.py
@@ -254,9 +254,12 @@ class PearWorkspace(PearMultiWorkspace):
self._pear_restart+=1;self.pear_update_tracking_button();self.pear_source_changed()
def pear_sync_controls(self):
- from .models import missing
+ from .models import ready,BY_KEY,STAGE_REQUIREMENTS
+ from .pear_models import KEYS
from .pear_runtime import status
- ok,message=status();unavailable=missing('pear_assets')
+ ok,message=status()
+ missing_models=[BY_KEY[key] for key in KEYS if not ready(BY_KEY[key])]
+ unavailable=[model for model in missing_models if model.key in STAGE_REQUIREMENTS['pear_assets']]
self.viewport_footer.show()
for key,check in self.viewport_checks.items():check.setVisible(key=='show_grid')
self.bone_overlay.setToolTip('Show fixed-length PEAR body and finger bones. Use Reset Bones to recalibrate their lengths from the displayed pose. Display only; no animation export in this mode.')
@@ -267,8 +270,9 @@ class PearWorkspace(PearMultiWorkspace):
self.status.setText("PEAR experimental preview · Tracking and pose estimates may be unstable.")
self.pear_header.show();self.model_pages.setCurrentWidget(self.pear_page);self.model_pages.show()
for widget in (self.people_panel,self.find_person_button,self.correction_group,self.compute_mode.parentWidget(),self.run_button,self.mesh_button,self.cancel_button,self.htd_refine,self.refine_description,self.footmr_refine,self.handflow_refine,self.footmr_description,self.refine_preview_note,self.analyze_button):widget.hide()
- self.models_group.setTitle('PEAR Models');self.readiness.setText('PEAR: '+('models ready' if not unavailable else str(len(unavailable))+' files missing'))
- self.readiness.setToolTip(message)
+ self.models_group.setTitle('PEAR Models');self.readiness.setText(f'PEAR: {len(KEYS)-len(missing_models)}/{len(KEYS)} models ready')
+ self.readiness.setStyleSheet('color:#ffb45c; font-weight:600;' if missing_models else '')
+ self.readiness.setToolTip(message+('\nMissing models:\n'+'\n'.join(model.name for model in missing_models) if missing_models else ''))
self.export_action.setEnabled(False);self.save_project_action.setEnabled(False);self.import_character_action.setEnabled(False)
self.slider.contacts_supported=False;self.slider.live_preview=True;self.slider._cache_key=None;self.slider.update()
self.play_button.setEnabled(self.info is not None and self.video_readable and not self.pear_using_webcams())
diff --git a/mocap/preview_export.py b/mocap/preview_export.py
new file mode 100644
index 0000000..4c8e5ec
--- /dev/null
+++ b/mocap/preview_export.py
@@ -0,0 +1,207 @@
+"""Bounded preview-video encoder. GUI widgets are never used by this worker."""
+from __future__ import annotations
+
+from collections import deque
+import math
+import os
+from pathlib import Path
+import subprocess
+from threading import Condition, Event, Lock, Thread
+import uuid
+
+from PySide6.QtCore import QRectF, Qt, QThread, Signal
+from PySide6.QtGui import QColor, QImage, QPainter
+
+
+def file_stamp(path):
+ try:
+ stat = Path(path).stat()
+ return stat.st_size, stat.st_mtime_ns
+ except FileNotFoundError:
+ return None
+
+
+def output_layout(video, viewport):
+ """Keep both complete images; even MP4 dimensions, at most a 4K frame."""
+ if min(video.width(), video.height(), viewport.width(), viewport.height()) <= 0:
+ raise ValueError('The video and 3D viewport must both be ready.')
+ height = viewport.height()
+ left = height * video.width() / video.height()
+ right = viewport.width()
+ scale = min(1., 3840 / (left + right), 2160 / height)
+ even = lambda x: max(2, int(x * scale) // 2 * 2)
+ return even(left), even(right), even(height)
+
+
+def compose_frame(video, viewport, layout):
+ left, right, height = layout
+ frame = QImage(left + right, height, QImage.Format_RGB888)
+ frame.fill(QColor('#202020'))
+ painter = QPainter(frame)
+ try:
+ painter.setRenderHint(QPainter.SmoothPixmapTransform)
+ for image, x, width in ((video, 0, left), (viewport, left, right)):
+ scale = min(width / image.width(), height / image.height())
+ w, h = image.width() * scale, image.height() * scale
+ painter.drawImage(QRectF(x + (width - w) / 2, (height - h) / 2, w, h), image)
+ finally:
+ painter.end()
+ # RGB scanlines may contain padding. Never send padding to rawvideo.
+ width_bytes = frame.width() * 3
+ bits = frame.constBits()
+ if frame.bytesPerLine() == width_bytes:
+ return bytes(bits[:width_bytes * frame.height()])
+ stride = frame.bytesPerLine()
+ return b''.join(bytes(bits[y * stride:y * stride + width_bytes]) for y in range(frame.height()))
+
+
+class PreviewEncoder(QThread):
+ frame_written = Signal(int)
+
+ def __init__(self, destination, layout, fps, frames, audio=None, audio_start=0., parent=None):
+ super().__init__(parent)
+ self.destination = Path(destination)
+ self.temporary = self.destination.with_name('.' + self.destination.stem + '-' + uuid.uuid4().hex + '.partial.mp4')
+ self.expected_destination = file_stamp(self.destination)
+ self.layout, self.fps, self.frames = layout, float(fps), int(frames)
+ self.audio = Path(audio) if audio else None
+ self.audio_start = float(audio_start)
+ self.condition, self.process_lock = Condition(), Lock()
+ self.stop_requested = Event()
+ self.pending = None
+ self.ending = False
+ self.process = None
+ self.error = None
+ self.succeeded = False
+ self.written = 0
+
+ def submit(self, index, video, viewport):
+ with self.condition:
+ if self.pending is not None or self.ending or self.stop_requested.is_set():
+ raise RuntimeError('Preview export is no longer accepting frames.')
+ self.pending = index, QImage(video), QImage(viewport)
+ self.condition.notify()
+
+ def finish_frames(self):
+ with self.condition:
+ self.ending = True
+ self.condition.notify()
+
+ def cancel(self):
+ self.stop_requested.set()
+ with self.condition:
+ self.pending = None
+ self.condition.notify()
+ with self.process_lock:
+ if self.process is not None and self.process.poll() is None:
+ try:
+ self.process.terminate()
+ except OSError:
+ pass
+
+ def run(self):
+ errors = deque(maxlen=8) # At most 32 KiB of FFmpeg output.
+ reader = None
+ drained = Event()
+ process = None
+ try:
+ from .video import executable
+ if not math.isfinite(self.fps) or self.fps <= 0 or self.frames <= 0:
+ raise ValueError('Invalid preview video timing.')
+ left, right, height = self.layout
+ command = [executable('ffmpeg'), '-hide_banner', '-loglevel', 'error', '-y',
+ '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{left + right}x{height}',
+ '-framerate', format(self.fps, '.12g'), '-i', 'pipe:0']
+ if self.audio is not None:
+ command += ['-ss', format(self.audio_start, '.12g'), '-i', str(self.audio)]
+ command += ['-map', '0:v:0']
+ if self.audio is not None:
+ command += ['-map', '1:a:0?', '-c:a', 'aac', '-b:a', '192k']
+ command += ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', '-threads', '4',
+ '-pix_fmt', 'yuv420p', '-t', format(self.frames / self.fps, '.12g'),
+ '-movflags', '+faststart', str(self.temporary)]
+ with self.process_lock:
+ if self.stop_requested.is_set():
+ return
+ process = self.process = subprocess.Popen(command, stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
+ def drain():
+ try:
+ while True:
+ chunk = process.stderr.read(4096)
+ if not chunk:
+ return
+ errors.append(chunk)
+ finally:
+ drained.set()
+ reader = Thread(target=drain, daemon=True)
+ reader.start()
+ while not self.stop_requested.is_set():
+ with self.condition:
+ while self.pending is None and not self.ending and not self.stop_requested.is_set():
+ self.condition.wait()
+ if self.stop_requested.is_set():
+ break
+ if self.pending is None:
+ break
+ index, video, viewport = self.pending
+ self.pending = None
+ payload = compose_frame(video, viewport, self.layout)
+ process.stdin.write(payload)
+ process.stdin.flush()
+ self.written += 1
+ self.frame_written.emit(index)
+ del payload, video, viewport
+ if self.stop_requested.is_set():
+ return
+ process.stdin.close()
+ if process.wait(timeout=120):
+ raise RuntimeError('FFmpeg could not finish the preview video.')
+ if self.written != self.frames:
+ raise RuntimeError('Preview export ended before every frame was written.')
+ if file_stamp(self.destination) != self.expected_destination:
+ raise RuntimeError('The destination changed during export. Choose another filename.')
+ if not self.temporary.is_file() or self.temporary.stat().st_size == 0:
+ raise RuntimeError('FFmpeg did not produce a preview video.')
+ # Only this completed file replaces the chosen destination.
+ with self.process_lock:
+ if self.stop_requested.is_set():
+ return
+ os.replace(self.temporary, self.destination)
+ self.succeeded = True
+ except Exception as exc:
+ if not self.stop_requested.is_set():
+ self.error = str(exc)
+ finally:
+ if process is not None:
+ if process.poll() is None:
+ try:
+ process.kill()
+ except OSError:
+ pass
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
+ if reader is not None:
+ # Event waiting avoids Python 3.10 registering each Qt
+ # worker as a permanent DummyThread through Thread.join.
+ drained.wait(timeout=5)
+ for stream in (process.stdin, process.stderr):
+ if stream is not None:
+ try:
+ stream.close()
+ except OSError:
+ pass
+ if self.error and errors:
+ self.error += '\n' + b''.join(errors).decode('utf-8', errors='replace')[-4000:]
+ with self.process_lock:
+ self.process = None
+ with self.condition:
+ self.pending = None
+ if not self.succeeded:
+ try:
+ self.temporary.unlink(missing_ok=True)
+ except OSError as exc:
+ self.error = (self.error or 'Preview export cancelled.') + '\nCannot remove temporary file: ' + str(exc)
diff --git a/mocap/preview_export_ui.py b/mocap/preview_export_ui.py
new file mode 100644
index 0000000..7536c52
--- /dev/null
+++ b/mocap/preview_export_ui.py
@@ -0,0 +1,336 @@
+"""Export the actual current viewport, paired with the selected decoded video."""
+from pathlib import Path
+import time
+
+from PySide6.QtCore import QObject, QTimer, Qt, Signal
+from PySide6.QtWidgets import QDialog, QFileDialog, QLabel, QMessageBox, QProgressBar, QPushButton, QVBoxLayout
+
+from .preview_export import PreviewEncoder, output_layout
+
+
+class ExportProgress(QDialog):
+ cancel_requested = Signal()
+
+ def __init__(self, parent):
+ super().__init__(parent)
+ self.setWindowTitle('Export Preview')
+ self.setWindowModality(Qt.WindowModal)
+ self.setMinimumWidth(440)
+ self.allow_close = False
+ layout = QVBoxLayout(self)
+ self.label = QLabel('Preparing preview export...')
+ self.label.setWordWrap(True)
+ layout.addWidget(self.label)
+ self.progress = QProgressBar()
+ layout.addWidget(self.progress)
+ self.cancel_button = QPushButton('Cancel')
+ self.cancel_button.clicked.connect(self.cancel_requested)
+ layout.addWidget(self.cancel_button)
+
+ def reject(self):
+ if self.allow_close:
+ super().reject()
+ else:
+ self.cancel_requested.emit()
+
+ def closeEvent(self, event):
+ if self.allow_close:
+ event.accept()
+ else:
+ self.cancel_requested.emit()
+ event.ignore()
+
+
+class PreviewExport(QObject):
+ def __init__(self, window, destination, resume=False):
+ super().__init__(window)
+ self.window, self.destination, self.resume = window, Path(destination), resume
+ self.writer = None
+ self.error = None
+ self.cancelling = self.close_window = False
+ self.phase = 'waiting'
+ self.started = self.wait_started = time.monotonic()
+ self.first, self.end = window.slider.clip_in, window.slider.clip_out
+ self.target, self.rendered = self.first, 0
+ self.fps = window.info['fps']
+ self.decoder, self.generation = window.video_view.decoder, window.video_view.generation
+ self.original_frame = window.slider.value()
+ view = window.motion_view
+ self.view_size = view.size()
+ self.context = self.scene_context()
+ self.camera = {name: getattr(view, name).copy() if hasattr(getattr(view, name), 'copy') else getattr(view, name)
+ for name in ('yaw', 'pitch', 'distance', 'pan', 'scene_center', 'auto_fit', 'view_name', 'follow')}
+ self.window_limits = window.minimumSize(), window.maximumSize()
+ self.shortcut_states = [s.isEnabled() for s in window.shortcuts]
+ self.accept_drops = window.acceptDrops()
+ self.audio, self.audio_start = self.audio_source()
+ # Reuse one native progress window across exports (including its GPU
+ # presentation resources) instead of repeatedly creating top-levels.
+ self.dialog = getattr(window, '_preview_export_dialog', None)
+ if self.dialog is None:
+ self.dialog = window._preview_export_dialog = ExportProgress(window)
+ self.dialog.allow_close = False
+ self.dialog.cancel_button.setEnabled(True)
+ self.dialog.progress.setValue(0)
+ self.dialog.cancel_requested.connect(self.cancel)
+ self.dialog.progress.setRange(0, self.end - self.first)
+ self.timer = QTimer(self)
+ self.timer.setInterval(100)
+ self.timer.timeout.connect(self.check)
+ window.video_view.decode_error.connect(self.decode_failed)
+ window.video_view.frame_presented.connect(self.video_ready)
+ window.character_loader.failed.connect(self.character_failed)
+
+ def scene_context(self):
+ w = self.window
+ v = w.motion_view
+ return (w.project, w.workspace_root, w.active_result, w.model_choice.currentData(),
+ id(v.joints), id(v.people_scene), id(v.target_frames), id(v.mesh_frames), id(v.native_vertices))
+
+ def video_ready(self, index):
+ if self.phase == 'waiting' and index == self.target:
+ QTimer.singleShot(0, self.check)
+
+ def character_failed(self, key, message):
+ w = self.window
+ if any(c.get('visible', True) and
+ (key == str(w.character_path(c['asset'])) or
+ (c.get('animation') and Path(key).is_relative_to(w.character_path(c['animation']))))
+ for c in w.characters):
+ self.fail('Cannot prepare the character preview: ' + message)
+
+ def characters_ready(self):
+ from bisect import bisect_right
+ w = self.window
+ expected = 0
+ for character in w.characters:
+ if not character.get('visible', True):
+ continue
+ takes = character.get('takes')
+ if takes:
+ starts = character.setdefault('_starts', [t['start'] for t in takes])
+ i = bisect_right(starts, w.motion_view.scene_time) - 1
+ if i < 0 or w.motion_view.scene_time >= takes[i]['start'] + takes[i]['frames'] / takes[i]['fps']:
+ continue
+ expected += 1
+ return len(list(w.character_draws())) == expected
+
+ def audio_source(self):
+ w = self.window
+ inputs = getattr(w, 'mamma_inputs', [])
+ if w.model_choice.currentData() == 'mamma' and inputs:
+ path = Path(inputs[w.mamma_active_camera]['path'])
+ else:
+ path = Path(w.video_path)
+ if path.is_file():
+ return path, w.source_offset + self.first / self.fps
+ video = w.video_view
+ return Path(self.decoder.path), (self.first + getattr(video, 'timeline_start', 0)) / self.fps
+
+ def start(self):
+ w = self.window
+ w.stop_playback()
+ w.setFixedSize(w.size())
+ w.setAcceptDrops(False)
+ for shortcut in w.shortcuts:
+ shortcut.setEnabled(False)
+ self.dialog.show()
+ self.timer.start()
+ self.request_frame()
+
+ def request_frame(self):
+ self.phase = 'waiting'
+ self.wait_started = time.monotonic()
+ w = self.window
+ w.slider.blockSignals(True)
+ w.slider.setValue(self.target)
+ w.slider.blockSignals(False)
+ w.seek(self.target)
+ QTimer.singleShot(0, self.check)
+
+ def decode_failed(self, message):
+ self.fail('Cannot export the selected video: ' + message)
+
+ def fail(self, message):
+ if self.error is None:
+ self.error = message
+ self.cancel()
+
+ def cancel(self, *, close_window=False):
+ self.close_window |= close_window
+ self.cancelling = True
+ self.dialog.cancel_button.setEnabled(False)
+ self.dialog.label.setText('Cancelling preview export...')
+ if self.writer is not None:
+ self.writer.cancel()
+ else:
+ QTimer.singleShot(0, self.finish)
+
+ def check(self):
+ if self.cancelling or self.phase == 'done':
+ return
+ w = self.window
+ elapsed = time.monotonic() - self.started
+ total = self.end - self.first
+ eta = f' · About {(total-self.rendered)*elapsed/self.rendered:.0f}s left' if self.rendered >= 3 and self.phase != 'finalizing' else ''
+ message = (f'Finishing MP4 · {elapsed:.0f}s elapsed' if self.phase == 'finalizing' else
+ f'Rendering frame {self.rendered + 1}/{total} · {elapsed:.0f}s elapsed{eta}')
+ self.dialog.label.setText(message)
+ w.status.setText('Export Preview: ' + message)
+ if self.phase != 'waiting':
+ if self.phase == 'writing' and time.monotonic() - self.wait_started > 60:
+ self.fail('The video encoder stopped responding. The destination was not changed.')
+ return
+ video, view = w.video_view, w.motion_view
+ if video.decoder is not self.decoder or video.generation != self.generation:
+ self.fail('The input video changed during export.');return
+ if view.size() != self.view_size:
+ self.fail('The viewport size changed during export. Please try again.');return
+ if self.scene_context() != self.context:
+ self.fail('The displayed motion changed during export. Please try again.');return
+ if video.frame is None or video.index != self.target or view.index != self.target:
+ if time.monotonic() - self.wait_started > 30:
+ self.fail('Timed out waiting for the matching video and 3D frame.')
+ return
+ try:
+ if not self.characters_ready():
+ if time.monotonic() - self.wait_started > 30:
+ self.fail('Timed out preparing the character animation frame.')
+ return
+ self.phase = 'capturing'
+ # Retain the chosen framing even if an asynchronous asset completes.
+ for name, value in self.camera.items():
+ setattr(view, name, value.copy() if hasattr(value, 'copy') else value)
+ if hasattr(view, 'grabFramebuffer'):
+ if not view.isValid():
+ raise RuntimeError('The 3D viewport is not ready.')
+ image = view.grabFramebuffer()
+ else:
+ image = view.grab().toImage()
+ if image.isNull():
+ raise RuntimeError('Cannot capture the current 3D viewport.')
+ if self.writer is None:
+ self.writer = PreviewEncoder(self.destination, output_layout(video.frame, image), self.fps,
+ total, self.audio, self.audio_start, self)
+ self.writer.frame_written.connect(self.written)
+ self.writer.finished.connect(self.finish)
+ self.writer.start()
+ w.log.append(f'Export Preview: {total} frames at {self.fps:g} fps → {self.destination}')
+ self.phase = 'writing'
+ self.writer.submit(self.target, video.frame, image)
+ except Exception as exc:
+ self.fail(str(exc))
+
+ def written(self, index):
+ if self.cancelling:
+ return
+ if index != self.target:
+ self.fail('Preview export received an out-of-order frame.');return
+ self.rendered += 1
+ self.dialog.progress.setValue(self.rendered)
+ if self.target + 1 == self.end:
+ self.phase = 'finalizing'
+ self.dialog.progress.setRange(0, 0)
+ self.writer.finish_frames()
+ else:
+ self.target += 1
+ self.request_frame()
+
+ def finish(self):
+ if self.phase == 'done' or (self.writer is not None and self.writer.isRunning()):
+ return
+ self.phase = 'done'
+ self.timer.stop()
+ w = self.window
+ try:
+ w.video_view.decode_error.disconnect(self.decode_failed)
+ w.video_view.frame_presented.disconnect(self.video_ready)
+ w.character_loader.failed.disconnect(self.character_failed)
+ except RuntimeError:
+ pass
+ view = w.motion_view
+ for name, value in self.camera.items():
+ setattr(view, name, value)
+ view._paint_camera = None
+ w.setMinimumSize(self.window_limits[0])
+ w.setMaximumSize(self.window_limits[1])
+ w.setAcceptDrops(self.accept_drops)
+ for shortcut, enabled in zip(w.shortcuts, self.shortcut_states):
+ shortcut.setEnabled(enabled)
+ w.slider.blockSignals(True)
+ w.slider.setValue(self.original_frame)
+ w.slider.blockSignals(False)
+ w.seek(self.original_frame)
+ self.dialog.allow_close = True
+ self.dialog.accept()
+ self.dialog.cancel_requested.disconnect(self.cancel)
+ error = self.error or (self.writer.error if self.writer is not None else None)
+ success = self.writer is not None and self.writer.succeeded
+ message = ('Preview saved: ' + str(self.destination) if success else
+ 'Export Preview failed: ' + error if error else 'Preview export cancelled. The destination was not changed.')
+ w.status.setText(message)
+ w.log.append(message)
+ w._preview_export = None
+ w.update_readiness()
+ if self.resume and not self.close_window:
+ w.toggle_play()
+ if self.close_window:
+ QTimer.singleShot(0, w.close)
+ self.deleteLater()
+
+
+class PreviewExportWorkspace:
+ def refresh_preview_export_action(self, *args):
+ self.export_preview_action.setEnabled(self.preview_export_available())
+
+ def preview_export_available(self):
+ view = self.motion_view
+ return (not getattr(self, '_pear_active', False) and self.model_choice.currentData() != 'pear'
+ and not self.busy and not self.contact_saving and not getattr(self, '_preview_export', None)
+ and not self._workspace_loading
+ and (self.model_choice.currentData() != 'mamma' or (not self.mamma_pending and not self._mamma_switching))
+ and self.info is not None and self.video_readable and self.video_view.frame is not None
+ and (self.preview_signature is None or (self.preview_data is not None
+ and self.preview_data.project == self.project))
+ and (not view.people_mode or (view.people_scene is not None and self.preview_data is not None
+ and self.preview_data.project == self.project))
+ and (view.joints is not None or view.people_scene is not None or bool(getattr(self, 'character_assets', {}))))
+
+ def save_preview(self):
+ if not self.preview_export_available():
+ return
+ resume = self.timer.isActive()
+ self.stop_playback()
+ picker = QFileDialog(self, 'Export Preview')
+ picker.setAcceptMode(QFileDialog.AcceptSave)
+ picker.setNameFilter('MP4 video (*.mp4)')
+ picker.setDefaultSuffix('mp4')
+ picker.selectFile(Path(self.video_path).stem + '-preview.mp4')
+ if not picker.exec():
+ if resume:self.toggle_play()
+ return
+ try:
+ self.start_preview_export(picker.selectedFiles()[0], resume=resume)
+ except (OSError, ValueError, RuntimeError) as exc:
+ self.status.setText('Cannot export preview: ' + str(exc))
+ QMessageBox.warning(self, 'Export Preview', str(exc))
+ if resume:self.toggle_play()
+
+ def start_preview_export(self, destination, *, resume=None):
+ if not self.preview_export_available():
+ raise ValueError('Load an offline motion and its video before exporting a preview. PEAR is not supported.')
+ path = Path(destination).resolve()
+ if path.suffix.lower() != '.mp4' or not path.parent.is_dir():
+ raise ValueError('Choose an MP4 file in an existing folder.')
+ inputs = [self.video_path, self.video_view.decoder.path]
+ inputs += [entry['path'] for entry in getattr(self, 'mamma_inputs', [])]
+ if any(p and path == Path(p).resolve() for p in inputs):
+ raise ValueError('The preview destination must not replace an input video.')
+ if not 0 <= self.slider.clip_in < self.slider.clip_out <= self.info['frames']:
+ raise ValueError('The timeline trim is invalid.')
+ from .video import executable
+ executable('ffmpeg')
+ controller = PreviewExport(self, path, self.timer.isActive() if resume is None else resume)
+ self._preview_export = controller
+ self.export_preview_action.setEnabled(False)
+ controller.start()
diff --git a/mocap/prompthmr_cache.py b/mocap/prompthmr_cache.py
new file mode 100644
index 0000000..b443116
--- /dev/null
+++ b/mocap/prompthmr_cache.py
@@ -0,0 +1,120 @@
+"""Persistent PromptHMR downloads; inference intermediates stay per generation."""
+from pathlib import Path
+import itertools
+import os
+import shutil
+import uuid
+
+from .paths import HOME
+from .storage import sha256
+
+# The installed torchvision DEFAULT weights (the hash prefix is in its URL).
+DEEPLAB = 'deeplabv3_resnet50_coco-cd0a2569.pth'
+DEEPLAB_BYTES = 168312152
+DEEPLAB_SHA256 = 'cd0a25694c4a0f7106b38f4938bf90a874f2f241cc410b8f63c7024399538f06'
+
+# Only these reviewed fixed-camera-equivalent revisions reuse the preceding
+# identity. Moving-camera preparation explicitly uses the actual code hashes.
+# Any future pipeline edit invalidates normally until separately reviewed.
+PIPELINE_CACHE_ONLY = {
+ '062f3d4f4e79fb8b4998257f73bf69a916a31c4138b31622774c5b64d791ad85':
+ 'b3098bbc038f9f5e25c9b9e96c9ec4fa2116226f74c645089bd328014f024e7d',
+ 'd1075279956f9443c3ff80694a9388fc9e1f2d74b3af5f9dab0714c50c2a7687':
+ 'b3098bbc038f9f5e25c9b9e96c9ec4fa2116226f74c645089bd328014f024e7d',
+}
+
+
+def inference_code_hash(path):
+ digest = sha256(path)
+ return PIPELINE_CACHE_ONLY.get(digest, digest) if path.name == 'prompthmr_pipeline.py' else digest
+
+
+def valid_deeplab(path):
+ try:
+ return path.is_file() and path.stat().st_size == DEEPLAB_BYTES and sha256(path) == DEEPLAB_SHA256
+ except OSError:
+ return False
+
+
+def child_directories(parent, limit):
+ try:
+ with os.scandir(parent) as entries:
+ for entry in itertools.islice(entries, limit):
+ try:
+ path = Path(entry.path)
+ if entry.is_dir(follow_symlinks=False) and path.resolve().is_relative_to(parent.resolve()):
+ yield path
+ except OSError:
+ continue
+ except OSError:
+ return
+
+
+def legacy_checkpoints(work, home):
+ """Bound the search to known generation layouts, never walk project payloads."""
+ yield work / 'torch-cache/hub/checkpoints' / DEEPLAB
+ parents = [work.parent]
+ projects = home / 'projects'
+ parents.extend(project / 'prompthmr/inference' for project in child_directories(projects, 512))
+ remaining = 512
+ seen = set()
+ for parent in parents:
+ parent = parent.resolve()
+ if parent in seen or not parent.is_dir():
+ continue
+ seen.add(parent)
+ for generation in child_directories(parent, remaining):
+ if remaining <= 0:
+ return
+ remaining -= 1
+ yield generation / 'torch-cache/hub/checkpoints' / DEEPLAB
+
+
+def configure_downloads(work, *, home=HOME):
+ """Reuse validated old weights without moving/deleting any project files."""
+ import torch
+ work, home = Path(work).resolve(), Path(home).resolve()
+ cache = home / 'cache/prompthmr'
+ torch_home = cache / 'torch'
+ hub = torch_home / 'hub'
+ target = hub / 'checkpoints' / DEEPLAB
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if target.exists():
+ if not valid_deeplab(target):
+ raise ValueError('PromptHMR shared DeepLab cache failed SHA-256 verification: ' + str(target))
+ else:
+ remaining_checks = 4 # Bound legacy hashing to about 642 MiB.
+ for source in legacy_checkpoints(work, home):
+ try:
+ if source.stat().st_size != DEEPLAB_BYTES:
+ continue
+ except OSError:
+ continue
+ if remaining_checks == 0:
+ break
+ remaining_checks -= 1
+ if not valid_deeplab(source):
+ continue
+ temporary = target.with_name(target.name + '.' + uuid.uuid4().hex + '.tmp')
+ try:
+ try:
+ os.link(source, temporary)
+ except OSError:
+ shutil.copy2(source, temporary)
+ if not valid_deeplab(temporary):
+ continue
+ # Another worker may have populated the shared cache meanwhile.
+ if target.exists():
+ if not valid_deeplab(target):
+ raise ValueError('PromptHMR shared DeepLab cache changed during reuse.')
+ else:
+ os.replace(temporary, target)
+ print('PromptHMR: reused SHA-256 verified DeepLab weights from an existing project.', flush=True)
+ break
+ finally:
+ temporary.unlink(missing_ok=True)
+ os.environ.update(TORCH_HOME=str(torch_home), HF_HOME=str(cache / 'hf'))
+ # Override any previously initialized torch.hub directory as well as env.
+ torch.hub.set_dir(str(hub))
+ print('PromptHMR: shared model download cache: ' + str(hub), flush=True)
+ return hub
diff --git a/mocap/prompthmr_camera.py b/mocap/prompthmr_camera.py
new file mode 100644
index 0000000..3f4ed40
--- /dev/null
+++ b/mocap/prompthmr_camera.py
@@ -0,0 +1,56 @@
+"""Official masked DroidCalib/Metric3D camera estimation in a bounded worker."""
+import gc,importlib.util,sys
+import numpy as np
+
+
+def estimate(pipe,emit):
+ import torch
+ from .prompthmr_camera_runtime import activate
+ from .models import BY_KEY,ready
+ from .prompthmr_models import CAMERA_LINKS,CAMERA_KEYS
+ from .prompthmr_runtime import configuration
+ from .prompthmr_pipeline import link_assets
+ folder=activate();engine=configuration()['engine']
+ if any(not ready(BY_KEY[k]) for k in CAMERA_KEYS):raise ValueError('Prepare the Moving Camera files in Model Manager.')
+ link_assets(__import__('pathlib').Path(engine),CAMERA_LINKS)
+ name='pipeline.camera._rgb_windows'
+ spec=importlib.util.spec_from_file_location(name,folder/'masked_droid_slam.py')
+ module=importlib.util.module_from_spec(spec);sys.modules[name]=module;spec.loader.exec_module(module)
+ # No network fallback: use only the Model Manager's verified Metric3D file.
+ from pipeline.yvanyin_metric3d_main import hubconf
+ # The pinned xFormers flash kernels do not support every Windows GPU.
+ # Keep the same attention equations/layout using Torch's native backend.
+ from mono.model.backbones import ViT_DINO,ViT_DINO_reg
+ def attention(q,k,v,attn_bias=None):
+ if attn_bias is not None and not isinstance(attn_bias,torch.Tensor):raise ValueError('Unsupported Metric3D attention bias.')
+ return torch.nn.functional.scaled_dot_product_attention(q.transpose(1,2),k.transpose(1,2),v.transpose(1,2),attn_mask=attn_bias,dropout_p=0.).transpose(1,2)
+ previous_attention=[(m,m.memory_efficient_attention) for m in (ViT_DINO,ViT_DINO_reg)]
+ original=hubconf.torch.hub.load_state_dict_from_url
+ def weights(url,*args,**kwargs):
+ if url.endswith('/metric_depth_vit_large_800k.pth'):
+ return torch.load(BY_KEY['phmr_metric3d'].path,map_location='cpu',weights_only=False)
+ return original(url,*args,**kwargs)
+ masks=torch.from_numpy(pipe.results['masks'])
+ if masks.shape[0]!=len(pipe.images):raise ValueError('Camera mask/video frame count differs.')
+ from pipeline.camera.slam_utils import est_calib,slam_args
+ # Allocate for every possible selected keyframe plus trajectory-fill slots;
+ # do not silently drop frames or overflow the upstream fixed-size buffer.
+ slam_args.buffer=max(32,len(pipe.images)+16)
+ emit('progress',current=0,total=0,message='Masked DroidCalib camera tracking and Metric3D scale')
+ print(f'PromptHMR camera: DroidCalib + Metric3D ViT-Large; frames={len(pipe.images)}, depth batch=1, keyframe buffer={slam_args.buffer}.',flush=True)
+ for m,_ in previous_attention:m.memory_efficient_attention=attention
+ hubconf.torch.hub.load_state_dict_from_url=weights
+ try:
+ r,t,k=module.run_metric_slam(pipe.images,masks=masks,calib=est_calib(pipe.images),
+ monodepth_method='metric3d_vit_large',use_depth_inp=False,stride=1,opt_intr=True,save_depth=False)
+ finally:
+ hubconf.torch.hub.load_state_dict_from_url=original
+ for m,previous in previous_attention:m.memory_efficient_attention=previous
+ gc.collect();torch.cuda.empty_cache()
+ r=np.asarray(r);t=np.asarray(t);k=np.asarray(k)
+ from .camera_tracks import valid_rotations
+ valid_rotations(r)
+ if r.shape!=(len(pipe.images),3,3) or t.shape!=(len(pipe.images),3) or not np.isfinite(t).all():raise ValueError('Invalid or incomplete moving-camera trajectory.')
+ if k.shape!=(4,) or not np.isfinite(k).all() or min(k[:2])<=0:raise ValueError('Invalid moving-camera intrinsics.')
+ pipe.results['camera']=dict(pred_cam_R=r,pred_cam_T=t,img_focal=k[0],img_center=k[2:])
+ pipe.results['has_slam']=True
diff --git a/mocap/prompthmr_camera_runtime.py b/mocap/prompthmr_camera_runtime.py
new file mode 100644
index 0000000..30368bb
--- /dev/null
+++ b/mocap/prompthmr_camera_runtime.py
@@ -0,0 +1,44 @@
+"""Optional native camera overlay over the unchanged PromptHMR runtime."""
+from pathlib import Path
+import hashlib,json,sys
+from .paths import ROOT
+from .storage import sha256
+
+
+def identity(root=ROOT):
+ names=('installer/prompthmr-camera-lock.json','installer/prompthmr_camera_adapters.py','installer/verify_prompthmr_camera.py')
+ return hashlib.sha256(json.dumps({n:sha256(Path(root)/n) for n in names},sort_keys=True).encode()).hexdigest()
+
+
+def inventory(folder):
+ result={};folder=Path(folder).resolve()
+ for p in folder.rglob('*'):
+ if not p.is_file() or '__pycache__' in p.parts:continue
+ if p.suffix not in ('.py','.pyd','.dll','.json') and p.name not in ('LICENSE','3rd-party-licenses.txt'):continue
+ if not p.resolve().is_relative_to(folder):raise ValueError('Invalid camera support file path.')
+ result[p.relative_to(folder).as_posix()]=sha256(p)
+ if len(result)>2048:raise ValueError('Camera support inventory exceeds its limit.')
+ return result
+
+
+def configuration(root=ROOT,verify=False):
+ from .prompthmr_runtime import configuration as base_configuration
+ base=base_configuration(root);path=Path(root)/'.setup/prompthmr-camera-runtime.json'
+ if not path.is_file():raise RuntimeError('Moving-camera support is not installed. Close the app, run Setup_PromptHMR.cmd and choose camera support. Fixed Camera remains available.')
+ if path.stat().st_size>1024**2:raise ValueError('Invalid PromptHMR camera runtime configuration.')
+ cfg=json.loads(path.read_text(encoding='utf8'))
+ if (cfg.get('version')!=1 or cfg.get('support_id')!=identity(root) or cfg.get('base_id')!=base['managed_id']
+ or cfg.get('compute_capability')!=base['compute_capability']):
+ raise RuntimeError('PromptHMR camera support needs verification. Run Setup_PromptHMR.cmd and choose camera support.')
+ folder=Path(cfg['folder']).resolve()
+ if not folder.is_relative_to((Path(root)/'runtime_prompthmr').resolve()) or not folder.is_dir():raise ValueError('Invalid PromptHMR camera support folder.')
+ if verify and inventory(folder)!=cfg['files']:raise RuntimeError('PromptHMR camera modules changed. Run Setup_PromptHMR.cmd to repair; previous motion was preserved.')
+ return cfg
+
+
+def activate():
+ cfg=configuration(verify=True)
+ import torch
+ if list(torch.cuda.get_device_capability())!=cfg['compute_capability']:raise RuntimeError('Camera kernels must be rebuilt for this GPU.')
+ folder=Path(cfg['folder']);sys.path.insert(0,str(folder));sys.path.insert(0,str(folder/'droid_slam'))
+ return folder
diff --git a/mocap/prompthmr_manager.py b/mocap/prompthmr_manager.py
index 929626f..526e0fa 100644
--- a/mocap/prompthmr_manager.py
+++ b/mocap/prompthmr_manager.py
@@ -9,6 +9,10 @@ def runtime_panel(parent):
try:
from .prompthmr_runtime import configuration
cfg=configuration();label.setText('PromptHMR runtime: Ready');label.setToolTip('Isolated Python: '+cfg['python'])
+ try:
+ from .prompthmr_camera_runtime import configuration as camera_configuration
+ camera_configuration();label.setText(label.text()+'\nMoving camera support: Ready')
+ except (OSError,ValueError,RuntimeError):label.setText(label.text()+'\nMoving camera support: Optional setup')
except (OSError,ValueError,RuntimeError) as error:
label.setText('PromptHMR runtime: Setup required');label.setToolTip(str(error));label.setStyleSheet('color:#ffb45c')
button=QPushButton('Runtime Setup...');button.setToolTip('Show separate runtime setup, disk space and license requirements. Weights are prepared below.')
@@ -23,7 +27,7 @@ def setup_instructions(parent):
report=json.loads((ROOT/'.setup/prompthmr-install-report.json').read_text(encoding='utf8'));size=f"{report['installed_bytes']/2**30:.2f} GiB on this PC"
except (OSError,ValueError,KeyError):pass
browser.setHtml(f'''<h3>PromptHMR separate Windows runtime</h3><p>Installed runtime: <b>{size}</b>, excluding weights and compiler tools. Allow about <b>18 GiB free</b> during installation. Other model environments stay unchanged.</p>
-<ol><li>Run install.cmd for the base app.</li><li>Install <a href="https://visualstudio.microsoft.com/downloads/">Visual Studio 2022 Build Tools</a> with Desktop development with C++ and Windows SDK, and <a href="https://developer.nvidia.com/cuda-12-8-0-download-archive">CUDA Toolkit 12.8</a>.</li><li>Close RGB MoCap and run <b>Setup_PromptHMR.cmd</b>. Review the official license prompt. Setup downloads pinned sources/packages, builds SAM2 for this GPU and verifies CUDA operations.</li><li>Reopen the app. Use Model Manager to download or import every required file. Existing standard SMPL-X Neutral and SMPL Neutral body files are reused; MAMMA's locked-head body is different.</li></ol>
-<p><a href="https://github.com/yufu-wang/PromptHMR/blob/main/LICENSE">PromptHMR is restricted to non-commercial scientific research</a>. Its source, weights and registered body data are not redistributed by RGB MoCap. Other components keep their own licenses.</p><p>Python 3.11 / Torch 2.7.1 CUDA 12.8 / timm 0.9.0. Torch's version overlaps with other profiles, but Python ABI and package versions differ. Installed packages remain isolated; verified identical download archives can be reused. MAMMA/SDF is not required.</p><p>Current support: one fixed-camera video, automatic tracking of up to eight people, shared world placement, optional interaction prompt, correction and FBX. No moving-camera or animated finger inference. Details: docs/models/PROMPTHMR.md. Logs: .setup/logs/prompthmr-*.log.</p>''')
+<ol><li>Run install.cmd for the base app.</li><li>Install <a href="https://visualstudio.microsoft.com/downloads/">Visual Studio 2022 Build Tools</a> with Desktop development with C++ and Windows SDK, and <a href="https://developer.nvidia.com/cuda-12-8-0-download-archive">CUDA Toolkit 12.8</a>.</li><li>Close RGB MoCap and run <b>Setup_PromptHMR.cmd</b>. Review the official license prompt. Setup downloads pinned sources/packages, builds SAM2 for this GPU and verifies CUDA operations. Choose Y at the optional camera prompt to also build DroidCalib/LieTorch (AGPL/BSD; review their licenses). Camera support reuses this Python/Torch, needs about 6 GiB extra build headroom and 1.55 GiB of additional camera weights. Fixed Camera does not require these extras.</li><li>Reopen the app. Use Model Manager to download or import every required file. Existing standard SMPL-X Neutral and SMPL Neutral body files are reused; MAMMA's locked-head body is different.</li></ol>
+<p><a href="https://github.com/yufu-wang/PromptHMR/blob/main/LICENSE">PromptHMR is restricted to non-commercial scientific research</a>. Its source, weights and registered body data are not redistributed by RGB MoCap. Other components keep their own licenses.</p><p>Python 3.11 / Torch 2.7.1 CUDA 12.8 / timm 0.9.0. Torch's version overlaps with other profiles, but Python ABI and package versions differ. Installed packages remain isolated; verified identical download archives can be reused. MAMMA/SDF is not required.</p><p>Current support: one video with a fixed or optionally tracked moving camera, automatic tracking of up to eight people, shared world placement, optional interaction prompt, correction and FBX. Optional Moving Camera adds DroidCalib + Metric3D tracking; no animated finger inference. Details: docs/models/PROMPTHMR.md. Logs: .setup/logs/prompthmr-*.log.</p>''')
layout.addWidget(browser);buttons=QHBoxLayout();copy=QPushButton('Copy Setup Command');copy.clicked.connect(lambda:QApplication.clipboard().setText('cd /d "'+str(ROOT)+'"\r\nSetup_PromptHMR.cmd'));close=QPushButton('Close');close.clicked.connect(dialog.accept)
buttons.addWidget(copy);buttons.addStretch();buttons.addWidget(close);layout.addLayout(buttons);dialog.exec();dialog.deleteLater()
diff --git a/mocap/prompthmr_models.py b/mocap/prompthmr_models.py
index 10cfb67..38c6e09 100644
--- a/mocap/prompthmr_models.py
+++ b/mocap/prompthmr_models.py
@@ -98,4 +98,18 @@ LINKS = {'phmr_checkpoint': 'data/pretrain/phmr/checkpoint.ckpt',
'phmr_video': 'data/pretrain/phmr_vid/prhmr_release_002.ckpt',
'phmr_video_config': 'data/pretrain/phmr_vid/prhmr_release_002.yaml'}
KEYS = tuple(LINKS)
+CAMERA_ASSETS = (
+ dict(key='phmr_droidcalib',name='Moving Camera / DroidCalib',relative='prompthmr/pretrain/droidcalib.pth',
+ url='https://github.com/boschresearch/DroidCalib',minimum_bytes=16049525,
+ download_url='https://raw.githubusercontent.com/boschresearch/DroidCalib/9a7174ae66c4dc4be4abdb5f6a819f1c0586a90d/droidcalib.pth',
+ expected_sha256='67c5b78f727fb5ea7a6bf31fafe2f20c8982a56ca0b4f880ab46769a244b0a6f'),
+ dict(key='phmr_metric3d',name='Moving Camera / Metric3D ViT-Large',relative='prompthmr/pretrain/metric_depth_vit_large_800k.pth',
+ url='https://huggingface.co/JUGGHM/Metric3D',minimum_bytes=1647972663,
+ download_url='https://huggingface.co/JUGGHM/Metric3D/resolve/main/metric_depth_vit_large_800k.pth',
+ expected_sha256='15328ffc42b528b95f188687418f6f03b3f123eb34ccdbd686c112abbea6d972'),
+)
+CAMERA_LINKS={'phmr_droidcalib':'data/pretrain/droidcalib.pth'}
+CAMERA_KEYS=tuple(a['key'] for a in CAMERA_ASSETS)
+ASSETS += CAMERA_ASSETS
INSTRUCTIONS = {a["key"]: "Review the official PromptHMR non-commercial license. Download the exact file from the official source, then Import it into this row. Google Drive may require a manual browser download." for a in ASSETS}
+INSTRUCTIONS.update({key:'Optional: required only for Moving Camera (DroidCalib + Metric3D). Run Setup_PromptHMR.cmd and choose camera support. Download/Import the exact verified file. Fixed Camera does not require it.' for key in CAMERA_KEYS})
diff --git a/mocap/prompthmr_pipeline.py b/mocap/prompthmr_pipeline.py
index 229ee2b..80affc9 100644
--- a/mocap/prompthmr_pipeline.py
+++ b/mocap/prompthmr_pipeline.py
@@ -1,4 +1,4 @@
-"""Atomic, cancellable fixed-camera PromptHMR pipeline for one video scene."""
+"""Atomic, cancellable PromptHMR pipeline for one video scene."""
from pathlib import Path
import argparse,gc,hashlib,json,math,os,subprocess,sys,time,uuid
from .storage import atomic_json,sha256
@@ -16,7 +16,11 @@ def options(value):
if isinstance(count,bool) or not isinstance(count,int) or not 0<=count<=8:raise ValueError('PromptHMR People must be 0 (automatic) or 1–8.')
interaction=value.get('interaction',True)
if not isinstance(interaction,bool):raise ValueError('Invalid PromptHMR interaction option.')
- return dict(people=count,interaction=interaction)
+ camera=value.get('camera','static')
+ if camera not in ('static','moving'):raise ValueError('Invalid PromptHMR camera mode.')
+ result=dict(people=count,interaction=interaction)
+ if camera=='moving':result['camera']=camera
+ return result
def request(path):
@@ -46,9 +50,15 @@ def validate_inputs(job):
if file_stat(job['video'])!=job['identity']['input']['stat']:raise ValueError('The video changed during processing. Previous results were preserved.')
for key,stamp in job['identity']['models'].items():
if file_stat(BY_KEY[key].path)!=stamp:raise ValueError('A PromptHMR model changed during processing. Previous results were preserved.')
+ if job['options'].get('camera')=='moving':
+ from .prompthmr_camera_runtime import configuration as camera_configuration
+ cfg=camera_configuration()
+ if {k:cfg[k] for k in ('support_id','base_id','compute_capability','files')}!=job['identity'].get('camera_runtime'):
+ raise ValueError('PromptHMR camera support changed during processing. Previous motion was preserved.')
def prepare(path,job):
+ from .prompthmr_cache import inference_code_hash
from .prompthmr_runtime import configuration
from .prompthmr_models import KEYS
from .models import BY_KEY,missing
@@ -62,7 +72,15 @@ def prepare(path,job):
raise ValueError('Use a trim of 4–1,800 frames (at 30 fps) within the source video. No frames were dropped.')
identity=dict(version=1,input=dict(path=job['video'],stat=file_stat(job['video'])),start=job['start'],frames=n,
options=job['options'],models={k:file_stat(BY_KEY[k].path) for k in KEYS},runtime=cfg['managed_id'],engine=cfg['engine_files'],
- code={name:sha256(ROOT/'mocap'/name) for name in ('prompthmr_pipeline.py','image_io.py')})
+ code={name:inference_code_hash(ROOT/'mocap'/name) for name in ('prompthmr_pipeline.py','image_io.py')})
+ if job['options'].get('camera')=='moving':
+ from .prompthmr_camera_runtime import configuration as camera_configuration
+ from .prompthmr_models import CAMERA_KEYS
+ if missing('prompthmr_camera_assets'):raise ValueError('Prepare the Moving Camera files in Model Manager first.')
+ camera_cfg=camera_configuration(verify=True)
+ identity['camera_runtime']={k:camera_cfg[k] for k in ('support_id','base_id','compute_capability','files')}
+ identity['models'].update({k:file_stat(BY_KEY[k].path) for k in CAMERA_KEYS})
+ identity['code'].update({name:sha256(ROOT/'mocap'/name) for name in ('prompthmr_pipeline.py','prompthmr_camera.py','prompthmr_camera_runtime.py')})
token=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()[:24]
work=job['root']/'prompthmr/inference'/token;cached=False
try:
@@ -85,11 +103,11 @@ def prepare(path,job):
atomic_json(work/'media.json',result)
-def link_assets(engine):
+def link_assets(engine,links=None):
from .models import BY_KEY,ready
from .prompthmr_models import LINKS
import shutil
- for key,name in LINKS.items():
+ for key,name in (LINKS if links is None else links).items():
model=BY_KEY[key]
if not ready(model):raise ValueError('Missing or unverified model: '+model.name)
p=engine/name;p.parent.mkdir(parents=True,exist_ok=True)
@@ -127,9 +145,11 @@ def inference(stage,job,engine):
free,total=torch.cuda.mem_get_info();torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
announce(stage,requested_mode(),'PromptHMR keeps the validated one-image batch and full temporal context in both modes. Additional block offloading is not implemented; actual RAM/VRAM guards remain active.',emit)
os.chdir(engine);sys.path.insert(0,str(engine))
- os.environ.update(TORCH_HOME=str(work/'torch-cache'),HF_HOME=str(work/'hf-cache'),MPLCONFIGDIR=str(work/'mpl-cache'),YOLO_CONFIG_DIR=str(work/'yolo-cache'))
+ from .prompthmr_cache import configure_downloads
+ configure_downloads(work)
+ os.environ.update(MPLCONFIGDIR=str(work/'mpl-cache'),YOLO_CONFIG_DIR=str(work/'yolo-cache'))
from pipeline import Pipeline
- pipe=Pipeline(static_cam=True);pipe.cfg.num_max_people=job['options']['people'] or 8
+ pipe=Pipeline(static_cam=job['options'].get('camera')!='moving');pipe.cfg.num_max_people=job['options']['people'] or 8
pipe.images,pipe.seq_folder=pipe.load_frames(str(work/'input.mp4'),str(work/'frames'))
if len(pipe.images)!=job['frames']:raise ValueError('PromptHMR decoded a different frame count.')
pipe.cfg.seq_folder=pipe.seq_folder
@@ -143,9 +163,13 @@ def inference(stage,job,engine):
save_result(pipe.results,work/'tracking.pkl')
elif stage=='prompthmr_pose':
from pipeline.spec import run_cam_calib
- emit('progress',current=0,total=0,message='Estimate fixed-camera intrinsics and gravity')
+ emit('progress',current=0,total=0,message='Estimate camera intrinsics and gravity')
pipe.results['spec_calib']=run_cam_calib(pipe.images,out_folder=str(work/'spec'),save_res=True,stride=max(1,len(pipe.images)//30),method='spec',first_frame_idx=0)
- pipe.camera_motion_estimation();pipe.estimate_2d_keypoints()
+ if job['options'].get('camera')=='moving':
+ from .prompthmr_camera import estimate
+ estimate(pipe,emit)
+ else:pipe.camera_motion_estimation()
+ pipe.estimate_2d_keypoints()
from pipeline.phmr_vid import PromptHMRVideoDataset
original=PromptHMRVideoDataset.__getitem__
def item(dataset,index):
diff --git a/mocap/prompthmr_publish.py b/mocap/prompthmr_publish.py
index 03bb7c3..ff7c5f2 100644
--- a/mocap/prompthmr_publish.py
+++ b/mocap/prompthmr_publish.py
@@ -61,7 +61,7 @@ def publish(job,emit):
if not 1<=len(record['people'])<=8:raise ValueError('PromptHMR returned an unsupported actor count.')
selected='corrected_initial' if job['correction_enabled'] else 'initial'
common=dict(version=1,source=job['source'],start=job['start'],end=job['start']+n/30,fps=30,frames=n,
- width=media['width'],height=media['height'],camera='static',stages={},timeline=dict(start=job['start'],step=1/30,frames=n),
+ width=media['width'],height=media['height'],camera=job['options'].get('camera','static'),stages={},timeline=dict(start=job['start'],step=1/30,frames=n),
pipeline=dict(model='prompthmr',result=selected),correction=job['correction'],prompthmr_options=job['options'],
workspace_root=os.path.relpath(root,group))
atomic_json(group/'project.json',common);media_link(work/'input.mp4',group/'input.mp4')
@@ -79,6 +79,19 @@ def publish(job,emit):
center=np.asarray(camera['img_center']);focal=float(camera['img_focal'])
sx=media['width']/model_width;sy=media['height']/height
K=np.array([[focal*sx,0,center[0]*sx],[0,focal*sy,center[1]*sy],[0,0,1.]])
+ moving=job['options'].get('camera')=='moving';camera_track=None
+ if moving:
+ from .camera_tracks import valid_rotations
+ rr=np.asarray(camera['Rcw'],dtype=float);tt=np.asarray(camera['Tcw'],dtype=float)
+ valid_rotations(rr)
+ if rr.shape!=(n,3,3) or tt.shape!=(n,3) or not np.isfinite(tt).all():raise ValueError('PromptHMR camera track does not cover the selected video.')
+ matrices=np.tile(np.eye(4),(n,1,1));matrices[:,:3,:3]=rr;matrices[:,:3,3]=tt
+ target=group/'camera_track.npz';temp=target.with_name('camera_track-'+__import__('uuid').uuid4().hex+'.tmp')
+ try:
+ with temp.open('wb') as stream:np.savez(stream,world_to_camera=matrices)
+ os.replace(temp,target)
+ finally:temp.unlink(missing_ok=True)
+ camera_track=dict(path='camera_track.npz',stat=file_stat(target),start=job['start'],fps=30)
people=[];projects=[]
for number,(track_id,person) in enumerate(tracks,1):
hands=hand_policy(person)
@@ -106,9 +119,10 @@ def publish(job,emit):
if not reuse:
params=convert(person['smplx_world'],body,positions,neutral_hands=hands!='native');incam={k:v.clone() for k,v in params.items()}
pelvis=body.J_regressor.numpy()[0]@body.v_template.numpy()+np.einsum('v,vci,bi->bc',body.J_regressor.numpy()[0],body.shapedirs.numpy(),params['betas'].numpy())
- r=transform[:3,:3];t=transform[:3,3]
+ r=rr[first:end] if moving else transform[:3,:3];t=tt[first:end] if moving else transform[:3,3]
incam['global_orient']=torch.from_numpy(Rotation.from_matrix([email protected]_rotvec(params['global_orient'].numpy()).as_matrix()).as_rotvec().astype('float32'))
- incam['transl']=torch.from_numpy(((params['transl'].numpy()+pelvis)@r.T+t-pelvis).astype('float32'))
+ root_positions=params['transl'].numpy()+pelvis
+ incam['transl']=torch.from_numpy(((np.einsum('tij,tj->ti',r,root_positions) if moving else [email protected])+t-pelvis).astype('float32'))
logits=np.asarray(person['smplx_cam']['static_conf_logits'],dtype=np.float32)
if logits.shape!=(len(frames),6) or not np.isfinite(logits).all():raise ValueError('Missing or invalid native PromptHMR contact confidence.')
save_tensor(dict(smpl_params_global=params,smpl_params_incam=incam,
@@ -119,8 +133,10 @@ def publish(job,emit):
else:
subprocess.run([executable('ffmpeg'),'-v','error','-i',str(group/'input.mp4'),'-vf',f'trim=start_frame={first}:end_frame={end},setpts=PTS-STARTPTS',
'-an','-c:v','libx264','-crf','18','-preset','fast','-threads','2',str(project/'input.mp4')],check=True,creationflags=0x08000000)
- atomic_json(project/'scene_camera.json',dict(version=VERSION,sources=camera_sources(project),model=file_stat(BY_KEY['smplx'].path),
- world_to_camera=transform.tolist(),K=K.tolist(),htd_compatible=False,source_model='prompthmr',method='Native shared PromptHMR world; fixed camera; no independent actor alignment'))
+ cam_record=dict(version=VERSION,sources=camera_sources(project),model=file_stat(BY_KEY['smplx'].path),
+ world_to_camera=transform.tolist(),K=K.tolist(),htd_compatible=False,source_model='prompthmr',method='Native shared PromptHMR world; no independent actor alignment')
+ if moving:cam_record['camera_track']={**camera_track,'path':os.path.relpath(group/'camera_track.npz',project)}
+ atomic_json(project/'scene_camera.json',cam_record)
row['takes'].append(dict(first=first,end=end,project=project.relative_to(group).as_posix()));projects.append(project)
if row['takes']:row['preview']=row['takes'][0]['project'];people.append(row)
emit('progress',current=number,total=len(tracks),message=f'Prepare PromptHMR source actor {number}')
diff --git a/mocap/prompthmr_scene.py b/mocap/prompthmr_scene.py
index 945a022..5f75ed8 100644
--- a/mocap/prompthmr_scene.py
+++ b/mocap/prompthmr_scene.py
@@ -1,4 +1,4 @@
-"""Preserve PromptHMR's shared world and constant fixed-camera basis."""
+"""Preserve PromptHMR's shared world and constant reference-camera basis."""
from pathlib import Path
from .storage import atomic_json
from .people_store import load_people,media_receipt
@@ -12,5 +12,5 @@ def prepare_cameras(root):
if read_camera(project) is None:raise ValueError('PromptHMR source or body changed. Reconstruct or prepare the selected source again.')
ident,project=rows[0];camera=read_camera(project);target=root/'people_scene.json'
atomic_json(target,dict(version=VERSION,input=media_receipt(root),anchor=project.relative_to(root).as_posix(),anchor_id=ident,
- world_to_camera=camera['world_to_camera'],sources=camera['sources'],floor=0.,K=camera['K'],camera_mode='static',scale=1.))
+ world_to_camera=camera['world_to_camera'],sources=camera['sources'],floor=0.,K=camera['K'],camera_mode='moving' if camera.get('camera_track') else 'static',scale=1.))
return target
diff --git a/mocap/prompthmr_ui.py b/mocap/prompthmr_ui.py
index f98f716..144d8f1 100644
--- a/mocap/prompthmr_ui.py
+++ b/mocap/prompthmr_ui.py
@@ -2,7 +2,7 @@
import json,uuid
from pathlib import Path
from PySide6.QtCore import Qt
-from PySide6.QtWidgets import QWidget,QVBoxLayout,QGroupBox,QLabel,QSpinBox,QCheckBox
+from PySide6.QtWidgets import QWidget,QVBoxLayout,QGroupBox,QLabel,QSpinBox,QCheckBox,QComboBox
class PromptHMRWorkspace:
@@ -10,6 +10,10 @@ class PromptHMRWorkspace:
page=QWidget();page.setProperty('motion_tool','prompthmr')
layout=QVBoxLayout(page);layout.setContentsMargins(0,0,0,0);layout.setSpacing(10);layout.setAlignment(Qt.AlignTop)
group=QGroupBox('PromptHMR Settings');box=QVBoxLayout(group);box.setSpacing(7);layout.addWidget(group)
+ box.addWidget(QLabel('Camera'))
+ self.prompthmr_camera=QComboBox();self.prompthmr_camera.addItem('Fixed Camera','static');self.prompthmr_camera.addItem('Moving Camera / DroidCalib + Metric3D','moving')
+ self.prompthmr_camera.setToolTip('Fixed Camera preserves the existing workflow. Moving Camera tracks background camera rotation and translation with masked DroidCalib and Metric3D scale. Requires optional camera support and two additional model files. Reconstruct 3D to apply; scale and tracking can drift.')
+ box.addWidget(self.prompthmr_camera)
box.addWidget(QLabel('People'))
self.prompthmr_people=QSpinBox();self.prompthmr_people.setRange(0,8);self.prompthmr_people.setValue(2)
self.prompthmr_people.setToolTip('Maximum number of people to track together. 0 detects automatically, up to 8 in this app. Start with 2 for a two-person interaction. The intended people should be visible near the beginning; this is not an identity selector. Applies on Reconstruct 3D.')
@@ -18,18 +22,22 @@ class PromptHMRWorkspace:
self.prompthmr_interaction.setToolTip('Ask PromptHMR to consider the people together. May improve relative placement during interaction; it does not guarantee hand contact or prevent body intersections. Off follows the official default video path. Applies on Reconstruct 3D.')
box.addWidget(self.prompthmr_interaction)
self.prompthmr_notice=QLabel();self.prompthmr_notice.setWordWrap(True);self.prompthmr_notice.setTextFormat(Qt.PlainText);box.addWidget(self.prompthmr_notice)
- group.setToolTip('Fixed-camera video only in this Windows integration. SAM2 tracking, PromptHMR image/video inference and native world post-optimization. No animated finger inference. Low Memory retains the same one-image batch; additional offloading is not implemented.')
+ group.setToolTip('Single-video fixed or moving camera. SAM2 tracking, PromptHMR image/video inference and native world post-optimization. No animated finger inference. Low Memory retains bounded image/depth batches; additional offloading is not implemented.')
+ self.prompthmr_camera.currentIndexChanged.connect(self.prompthmr_settings_changed)
self.prompthmr_people.valueChanged.connect(self.prompthmr_settings_changed)
self.prompthmr_interaction.toggled.connect(self.prompthmr_settings_changed)
self.model_pages.addWidget(page)
- self.model_choice.setItemData(self.model_choice.findData('prompthmr'),'PromptHMR: shared-scene single-video capture, especially for people interacting. Fixed cameras only; no animated fingers. Separate optional runtime.',Qt.ToolTipRole)
+ self.model_choice.setItemData(self.model_choice.findData('prompthmr'),'PromptHMR: shared-scene single-video capture, especially for people interacting. Fixed or moving camera; no animated fingers. Separate optional runtime.',Qt.ToolTipRole)
def prompthmr_options(self):
- return dict(people=self.prompthmr_people.value(),interaction=self.prompthmr_interaction.isChecked())
+ result=dict(people=self.prompthmr_people.value(),interaction=self.prompthmr_interaction.isChecked())
+ if self.prompthmr_camera.currentData()=='moving':result['camera']='moving'
+ return result
def restore_prompthmr_options(self,value):
from .prompthmr_pipeline import options
value=options(value)
+ self.prompthmr_camera.blockSignals(True);self.prompthmr_camera.setCurrentIndex(self.prompthmr_camera.findData(value.get('camera','static')));self.prompthmr_camera.blockSignals(False)
for control,setting in ((self.prompthmr_people,value['people']),(self.prompthmr_interaction,value['interaction'])):
control.blockSignals(True)
if isinstance(control,QCheckBox):control.setChecked(setting)
@@ -42,15 +50,18 @@ class PromptHMRWorkspace:
def sync_prompthmr_controls(self):
if self.model_choice.currentData()!='prompthmr':return
self.find_person_button.hide()
- self.people_help_dialog.setText('PromptHMR tracks people together during Reconstruct 3D; Find person is not needed. Use a fixed camera and set People to 2 for a two-person interaction, or 0 for automatic detection (up to 8). The intended people should be visible near the start.\n\nAfter reconstruction, check rows to show people and select a row to edit contacts. All people keep one inferred world. Interaction Prompt does not guarantee contact or prevent intersections. No animated fingers are generated.')
- self.prompthmr_people.setEnabled(not self.busy);self.prompthmr_interaction.setEnabled(not self.busy)
+ self.people_help_dialog.setText('PromptHMR tracks people together during Reconstruct 3D; Find person is not needed. Select Fixed or Moving Camera and set People to 2 for a two-person interaction, or 0 for automatic detection (up to 8). The intended people should be visible near the start.\n\nAfter reconstruction, check rows to show people and select a row to edit contacts. All people keep one inferred world. Interaction Prompt does not guarantee contact or prevent intersections. No animated fingers are generated.')
+ self.prompthmr_people.setEnabled(not self.busy);self.prompthmr_interaction.setEnabled(not self.busy);self.prompthmr_camera.setEnabled(not self.busy)
message=''
try:
from .prompthmr_runtime import configuration
configuration()
+ if self.prompthmr_camera.currentData()=='moving':
+ from .prompthmr_camera_runtime import configuration as camera_configuration
+ camera_configuration()
if self.project is not None:
state=json.loads((self.project/'project.json').read_text(encoding='utf8'));saved=state.get('prompthmr_options',{})
- if saved!=self.prompthmr_options():message='People/interaction settings changed. Reconstruct 3D to apply; previous motion is still displayed.'
+ if saved!=self.prompthmr_options():message='Camera/people/interaction settings changed. Reconstruct 3D to apply; previous motion is still displayed.'
elif state.get('pipeline',{}).get('model')=='prompthmr':
receipt=self.project/'prompthmr_source.json'
if receipt.is_file() and not json.loads(receipt.read_text(encoding='utf8')).get('native',{}).get('hand_pose_policy'):
@@ -58,7 +69,7 @@ class PromptHMRWorkspace:
except (OSError,ValueError,RuntimeError) as error:
message=str(error);self.run_button.setEnabled(False)
self.prompthmr_notice.setText(message);self.prompthmr_notice.setVisible(bool(message))
- self.run_button.setToolTip('Track and reconstruct people together from one fixed-camera video. Preserves the shared inferred scene, then optionally applies Motion Correction. No moving-camera or finger inference in this integration.')
+ self.run_button.setToolTip('Track and reconstruct people together from one video using the selected camera mode. Preserves the shared inferred scene, then optionally applies Motion Correction. No finger tracking.')
def run_prompthmr(self):
if self.busy or self.contact_saving or not self.video_path or not self.info:return
@@ -69,6 +80,11 @@ class PromptHMRWorkspace:
from .storage import atomic_json,project_key
from .prompthmr_pipeline import STAGES
configuration()
+ if self.prompthmr_camera.currentData()=='moving':
+ from .prompthmr_camera_runtime import configuration as camera_configuration
+ camera_configuration()
+ if missing('prompthmr_camera_assets'):
+ self.status.setText('Prepare the Moving Camera files in Model Manager.');self.open_model_manager();return
if missing('prompthmr_assets'):
self.status.setText('Prepare the missing PromptHMR files in Model Manager.');self.open_model_manager();return
first,end=self.processing_range()
diff --git a/mocap/workspace_ui.py b/mocap/workspace_ui.py
index 63d87ef..a45f99c 100644
--- a/mocap/workspace_ui.py
+++ b/mocap/workspace_ui.py
@@ -591,6 +591,9 @@ def build_workspace(w):
file_menu.addSeparator()
w.export_action = file_menu.addAction("Export...", w.save_fbx)
w.export_action.setToolTip(tooltip_text('Export the displayed motion as FBX, BVH or a portable Blender project. Multiple people export separately; MAMMA also offers a whole-scene Blender bundle.'))
+ w.export_preview_action = file_menu.addAction('Export Preview...', w.save_preview)
+ w.export_preview_action.setToolTip(tooltip_text('Save the selected input video beside the current 3D viewport as MP4 over the timeline trim. Keeps the current view, visible people/characters and viewport overlays. Includes source audio when available. Not available in PEAR live mode.'))
+ w.export_preview_action.setEnabled(False)
file_menu.addAction("Open Project Folder", w.open_folder)
file_menu.addSeparator()
file_menu.addAction("Exit", w.close)
diff --git a/tools/setup_prompthmr.py b/tools/setup_prompthmr.py
index 2ec812b..9ac37f6 100644
--- a/tools/setup_prompthmr.py
+++ b/tools/setup_prompthmr.py
@@ -119,6 +119,10 @@ def setup():
if __name__=='__main__':
- parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--accept-licenses',action='store_true',required=True)
- try:parser.parse_args();setup()
+ parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--accept-licenses',action='store_true',required=True);parser.add_argument('--camera',action='store_true')
+ try:
+ args=parser.parse_args();setup()
+ if args.camera:
+ from tools.setup_prompthmr_camera import setup as setup_camera
+ setup_camera()
except Exception as error:print('PromptHMR setup failed: '+str(error),file=sys.stderr);raise SystemExit(1)
diff --git a/tools/setup_prompthmr_camera.py b/tools/setup_prompthmr_camera.py
new file mode 100644
index 0000000..7fe93e2
--- /dev/null
+++ b/tools/setup_prompthmr_camera.py
@@ -0,0 +1,89 @@
+"""Transactional camera extension setup; reuse the verified PromptHMR runtime."""
+from pathlib import Path
+import json,os,shutil,sys,uuid,zipfile,urllib.request
+ROOT=Path(__file__).resolve().parents[1]
+sys.path.insert(0,str(ROOT))
+from installer import engine
+from tools.setup_mamma import compiler,quoted,extract_source,fetch_package
+from tools.setup_prompthmr import run
+from tools.support_components import download
+from tools.session_lock import app_lock
+from mocap.storage import atomic_json
+
+
+def setup(root=ROOT):
+ root=Path(root)
+ from mocap.prompthmr_runtime import configuration as base_configuration
+ from mocap.prompthmr_camera_runtime import identity,inventory,configuration
+ base=base_configuration(root);tag=identity(root);py=Path(base['python'])
+ with app_lock(root):
+ try:
+ old=configuration(root,verify=True)
+ run([py,'-I','-X','utf8',root/'installer/verify_prompthmr_camera.py','--folder',old['folder'],'--output',Path(old['folder'])/'verification.json'],root/'.setup/logs/prompthmr-camera-verify.log')
+ print('Verified PromptHMR camera support retained.',flush=True);return old
+ except (OSError,ValueError,RuntimeError,KeyError) as e:print('Preparing PromptHMR camera support: '+str(e),flush=True)
+ cuda,vc=compiler()
+ if shutil.disk_usage(root).free<6*1024**3:raise OSError('Allow 6 GiB free for the camera build, excluding the 1.55 GiB camera models.')
+ lock=json.loads((root/'installer/prompthmr-camera-lock.json').read_text(encoding='utf8'))
+ folder=root/'.setup/prompthmr-camera-staging'/uuid.uuid4().hex;folder.mkdir(parents=True)
+ cache=root/'.setup/prompthmr-camera-downloads';cache.mkdir(exist_ok=True)
+ promoted=None;committed=False
+ try:
+ source=folder/'source';source.mkdir();out=folder/'support';out.mkdir()
+ for name,spec in lock['sources'].items():
+ archive=download(cache,name+'-'+spec['commit'],spec)
+ extract_source(archive,spec,source/'thirdparty'/name)
+ from installer.prompthmr_camera_adapters import prepare
+ prepare(source,Path(base['engine']))
+ # Restore only link libraries from the already pinned Torch archive.
+ base_lock=json.loads((root/'installer/prompthmr-runtime-lock.json').read_text(encoding='utf8'))
+ wheel=fetch_package(next(p for p in base_lock['packages'] if p['name']=='torch'),root/'.setup/prompthmr-downloads')
+ libs=source/'torch-libs';libs.mkdir()
+ with zipfile.ZipFile(wheel) as z:
+ for name in z.namelist():
+ if name.startswith('torch/lib/') and name.endswith('.lib'):(libs/Path(name).name).write_bytes(z.read(name))
+ uv=root/'.setup/bootstrap-git/uv.exe'
+ try:python_lib=engine.python_home(root,base_lock['python'])/'libs/python311.lib'
+ except (OSError,ValueError,RuntimeError):python_lib=None
+ if python_lib is None or not python_lib.is_file():
+ run([uv,'python','install',base_lock['python'],'--install-dir',root/'.setup/python','--no-bin','--no-registry','--no-config'],root/'.setup/logs/prompthmr-camera-python.log')
+ shutil.copy2(engine.python_home(root,base_lock['python'])/'libs/python311.lib',libs/'python311.lib')
+ spec=lock['scatter'];archive=cache/spec['filename']
+ if not archive.exists() or archive.stat().st_size!=spec['bytes'] or engine.sha(archive)!=spec['sha256']:
+ part=archive.with_suffix('.partial')
+ try:
+ with urllib.request.urlopen(spec['url'],timeout=120) as f,part.open('wb') as stream:shutil.copyfileobj(f,stream,1024**2)
+ if part.stat().st_size!=spec['bytes'] or engine.sha(part)!=spec['sha256']:raise ValueError('Scatter package verification failed.')
+ os.replace(part,archive)
+ finally:part.unlink(missing_ok=True)
+ with zipfile.ZipFile(archive) as z:
+ for member in z.infolist():
+ name=Path(member.filename)
+ if name.is_absolute() or '..' in name.parts or ':' in member.filename or '\\' in member.filename:raise ValueError('Invalid camera package member.')
+ if not member.is_dir():
+ target=out/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(z.read(member))
+ cap='.'.join(map(str,base['compute_capability']))
+ build=folder/'build.cmd';build.write_text('\n'.join([
+ '@echo off','setlocal DisableDelayedExpansion','chcp 65001 >nul','call '+quoted(vc),'if errorlevel 1 exit /b 1',
+ 'set "CUDA_HOME='+str(cuda).replace('%','%%')+'"','set "PATH='+str(cuda/'bin').replace('%','%%')+';%PATH%"',
+ 'set "VSLANG=1033"','set "MAX_JOBS=2"','set "DISTUTILS_USE_SDK=1"','set "MSSdk=1"','set "TORCH_CUDA_ARCH_LIST='+cap+'"',
+ ' '.join(quoted(x) for x in [py,'-I','-X','utf8',source/'setup_windows.py','build_ext','--build-lib',out,'--build-temp',folder/'build']),
+ 'exit /b %errorlevel%'])+'\n',encoding='utf8')
+ run([os.environ.get('COMSPEC','cmd.exe'),'/d','/c',build],root/'.setup/logs/prompthmr-camera-build.log')
+ shutil.copytree(source/'thirdparty/lietorch/lietorch',out/'lietorch',ignore=shutil.ignore_patterns('src','include'))
+ shutil.copytree(source/'droid_slam',out/'droid_slam')
+ shutil.copy2(source/'masked_droid_slam.py',out/'masked_droid_slam.py')
+ for name in ('LICENSE','3rd-party-licenses.txt'):shutil.copy2(source/name,out/name)
+ shutil.copy2(source/'thirdparty/lietorch/LICENSE',out/'lietorch/LICENSE')
+ run([py,'-I','-X','utf8',root/'installer/verify_prompthmr_camera.py','--folder',out,'--output',out/'verification.json'],root/'.setup/logs/prompthmr-camera-verify.log')
+ dest=root/'runtime_prompthmr'/('camera-'+tag[:16]+'-'+uuid.uuid4().hex[:8]);os.replace(out,dest);promoted=dest
+ result=json.loads((dest/'verification.json').read_text(encoding='utf8'))
+ cfg=dict(version=1,support_id=tag,base_id=base['managed_id'],folder=str(dest.resolve()),compute_capability=result['compute_capability'],files=inventory(dest),
+ installed_bytes=sum(p.stat().st_size for p in dest.rglob('*') if p.is_file()))
+ if identity(root)!=tag or base_configuration(root)!=base:raise RuntimeError('Setup inputs changed. Previous camera support was preserved.')
+ atomic_json(root/'.setup/prompthmr-camera-runtime.json',cfg);committed=True
+ print('PromptHMR camera support ready: %.1f MiB; prepare the two Moving Camera models in Model Manager.'%(cfg['installed_bytes']/2**20),flush=True)
+ return cfg
+ finally:
+ if folder.exists():engine.remove_owned(root/'.setup/prompthmr-camera-staging',folder)
+ if promoted is not None and not committed:engine.remove_owned(root/'runtime_prompthmr',promoted)