Skip to content

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

Python

Skip intermediate MAMMA SAM PNG frames

toyxyz3912be65d631
diff --git a/README.md b/README.md
index 89443b2..fbdaae2 100644
--- a/README.md
+++ b/README.md
@@ -212,7 +212,7 @@ and **6.10 to 2.77 GiB** for FlowHMR. Separate short-clip tests of connected
processing phases cut worker time by **44% for ExMR** and **24% for FlowHMR**,
with unchanged measured peak VRAM. These are different tests, not full-job
speed guarantees. See [resource modes, measured savings and acceleration](docs/PERFORMANCE.md)
-for conditions, per-model results and output differences.
+for conditions, per-model results, direct-video preprocessing and output differences.
FlowHMR's **Adaptive Batching** selects 1–16 Fast SAM frames from available memory;
Low Memory uses one. Warm feature tests took 16–23% less time at batch 16 than at
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index b3eb64f..294662c 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -26,8 +26,8 @@
},
{
"path": "README.md",
- "bytes": 12425,
- "sha256": "0085bb68c8ea6ae8c133d37bfa960fbbc32a090f5a170ef16fb5e2b98617d42b"
+ "bytes": 12453,
+ "sha256": "8d0805bd478dc38ff39680b37b0744a7cb8783d26a22614ac9cc684300651938"
},
{
"path": "RGBMoCap.cmd",
@@ -96,8 +96,8 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 68225,
- "sha256": "5ea3fc662da00e09b88ffb9f7153ce74887a13b72c836d87e670e4d3be802a97"
+ "bytes": 69250,
+ "sha256": "f1f7beb2be54f32d55c6e3d061038f4c9a8bbbe60af71a9aacd3bd752f972c31"
},
{
"path": "docs/BUILD.md",
@@ -111,8 +111,8 @@
},
{
"path": "docs/MAMMA.md",
- "bytes": 26044,
- "sha256": "b39269e68b68ad1d1644083114a4adab39a321b7a57430c2e299932b8448e350"
+ "bytes": 27478,
+ "sha256": "d944c829870df59e1f8b70f40cbf903f4a53f4d1903a55dccc8ef69ab3dff4f9"
},
{
"path": "docs/MAMMA_AGENT_SETUP.md",
@@ -121,8 +121,8 @@
},
{
"path": "docs/PERFORMANCE.md",
- "bytes": 23477,
- "sha256": "9a7930c96cde25c9d56ecfe1981ccd57b1099207e408aabced2961ad6cd6fce9"
+ "bytes": 25858,
+ "sha256": "a258094f5bbdd9321e2bc48bb58cc9a3ebdd58372cbf7a12280c8ebf2295ec5e"
},
{
"path": "docs/USER_GUIDE.md",
@@ -131,8 +131,8 @@
},
{
"path": "docs/VALIDATION.md",
- "bytes": 137180,
- "sha256": "bc42cbb32f6756739822483e2d3029933b9e8228e1470684f8e91d194fa05cdb"
+ "bytes": 139455,
+ "sha256": "8b1931274cece344694bcd749ef66e465fc14b566a46fed3fa9604c3b5fc9334"
},
{
"path": "docs/images/exmr-interaction-contact.png",
@@ -1476,8 +1476,8 @@
},
{
"path": "mocap/mamma_pipeline.py",
- "bytes": 19453,
- "sha256": "21dd73e239904ab95bf147b0544bdd460cccf6979b35975095106363dfc2b069"
+ "bytes": 19048,
+ "sha256": "5c90318cfc520bfad4f84d0239a47bdc38b95be14f2f3fc79baf9d9c7e9f32ba"
},
{
"path": "mocap/mamma_publish.py",
@@ -1489,6 +1489,11 @@
"bytes": 5812,
"sha256": "2e69b856b0969aed3b1e34b02130432f35c3fa434d4e669f11e40943aa6d9757"
},
+ {
+ "path": "mocap/mamma_sam_frames.py",
+ "bytes": 4132,
+ "sha256": "1fb23a91f5df5b092e63d48e87e1d87d557a16268d8422c4c7f54c6aa488fb3f"
+ },
{
"path": "mocap/mamma_scene.py",
"bytes": 995,
@@ -1531,8 +1536,8 @@
},
{
"path": "mocap/model_guide.py",
- "bytes": 13352,
- "sha256": "eadbea53fe399296eeba27669dec0e4bf557f4944dec955e93dd274cf4c4d490"
+ "bytes": 13618,
+ "sha256": "d96ba65d31bb49fe3b31a7a54a8795b9a9f6acc064546c69c83b1a5257a93c44"
},
{
"path": "mocap/model_session.py",
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index 3922013..138e0df 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -222,6 +222,20 @@ verification, registration and rollback, use the
validate actual native CUDA operations. Do not overwrite a working runtime to
test a new native module, or use cached inference as evidence of a new build.
+MAMMA's SAM 2.1 input uses `mocap/mamma_sam_frames.py` to decode the already
+prepared video directly, without intermediate RGB PNGs or empty index files.
+Keep the same PIL resize, float64 pixel division into FP32 frame storage,
+in-place normalization and CPU frame/state offload. Final masks and existing
+matching/fitting settings remain unchanged. The adapter is worker-scoped,
+restores upstream hooks even on exceptions, and holds only the current camera's
+frame-source reference; it owns no new captures or background queues. Other
+frame-source types keep the upstream path. Include the helper in the MAMMA code
+identity; never reuse a mixed/incomplete generation. Existing completed results
+remain readable and are not automatically reprocessed on open. No runtime setup
+change is needed. Paired 7/14.2-second mask tests cut time 17–21%, changed RAM by
++23/−3 MiB and retained all masks; these are stage-only results. See
+[performance and measurement limits](PERFORMANCE.md#mamma-direct-sam-video-input-2026-11-03).
+
### Capture, correction and export
1. Select an AI Motion Model and prepare its models, then **File > Open Video** and optionally trim the Video track. Select MAMMA before opening multiple videos. New work defaults to ExMR.
diff --git a/docs/MAMMA.md b/docs/MAMMA.md
index c4706ae..9df371f 100644
--- a/docs/MAMMA.md
+++ b/docs/MAMMA.md
@@ -219,6 +219,28 @@ diagnostics. VGGT samples up to three times per fixed camera at its 512 input
setting and omits unneeded depth output. Matching completed inference is reused;
contact edits and correction do not require another MAMMA inference.
+SAM input now comes directly from the prepared camera videos instead of writing
+and rereading intermediate RGB PNG frames. The same decoded pixels, PIL resize,
+FP32 frame storage and normalization are retained. Final person masks still save
+normally for the landmark stage. Both Automatic and Low Memory use this path;
+it changes neither camera estimation nor fitting/contact settings and adds no
+package, checkpoint or runtime installation requirement.
+
+Paired four-camera, two-person tests at 1920×1080/30 fps measured the mask stage:
+
+| Common duration | Time: PNG → direct input | Peak RAM working set: PNG → direct | Peak allocated VRAM: PNG → direct |
+| --- | ---: | ---: | ---: |
+| 7 s / 210 frames | 221.79 → 184.40 s | 6.569 → 6.592 GiB | 2.536 → 2.536 GiB |
+| 14.2 s / 426 frames | 398.88 → 314.52 s | 10.053 → 10.050 GiB | 2.536 → 2.536 GiB |
+
+This was **17–21% less mask-stage time**, with RAM differences of +23/−3 MiB
+and all 5,088 compared person-mask images pixel-identical. These are stage
+measurements on one PC, not full-job speedups or long-video memory guarantees.
+RAM still grows with clip length in both paths; this change removes disk I/O,
+not SAM's existing CPU frame/state storage. Existing completed projects remain
+readable; explicitly reconstruct to use the new input path. See the
+[measurement scope](PERFORMANCE.md#mamma-direct-sam-video-input-2026-11-03).
+
Earlier four-view, two-person, 30-frame tests on the RTX 5090 test PC measured:
| Applied change | Stage time before → after | Time reduction |
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
index 52b8eb9..d6fd986 100644
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@ -348,7 +348,45 @@ figures, not combined parent/desktop RAM peaks or universal requirements. The
parent releases its GPU model before the child starts. Warm timings from earlier
standalone FP32 crop experiments have a different scope and precision.
-### MAMMA
+### MAMMA direct SAM video input (2026-11-03)
+
+MAMMA now skips the intermediate lossless RGB PNG write/read before SAM 2.1.
+It uses the existing video reader and the same PIL resize, FP32 tensor and
+normalization. YOLO/CLIP matching, mask prompts, propagation, tiny-component
+cleanup, landmark inference, cameras, fitting and correction are unchanged.
+Final person masks remain available for downstream stages. This optimization
+is used in both resource modes and needs no new runtime or weights.
+
+Independent paired measurements on the RTX 5090 / 96 GB RAM test PC used four
+1920×1080 videos, two people, 30 fps, and the same source prefix at both lengths.
+Each variant ran in a fresh process, once per duration, with CPU frame/state
+offload unchanged. Time covers mask-model setup, input preparation, matching,
+propagation, mask saving and cleanup; camera/landmark/3D fitting are excluded.
+
+| Duration | Time: PNG / direct | Peak RAM working set: PNG / direct | Peak allocated VRAM: PNG / direct |
+| --- | ---: | ---: | ---: |
+| 7 s / 210 frames | 221.79 / 184.40 s | 6.569 / 6.592 GiB | 2.536 / 2.536 GiB |
+| 14.2 s / 426 frames | 398.88 / 314.52 s | 10.053 / 10.050 GiB | 2.536 / 2.536 GiB |
+
+Mask-stage time fell **16.9% / 21.2%** (1.20× / 1.27× throughput).
+RAM changed **+23 / −3 MiB**, with identical allocated/reserved CUDA peaks
+within each pair. Windows private-commit peaks were 10.661 / 10.670 GiB for
+7 seconds and 13.989 / 13.981 GiB for 14.2 seconds. Private commit is not
+physical RAM; working set is the OS process peak, including short transients.
+
+All **5,088 paired person-mask images** were pixel-identical. PNG input payloads
+of 2.57 / 5.23 GiB were avoided; final masks and other necessary outputs still
+write to disk. Process logical writes fell 3.89→1.32 / 7.88→2.65 GiB; these are
+Windows process I/O counters, not physical SSD writes. The SAM CPU tensor alone
+uses about 12 MiB per frame at its 1024-square setting in either path, so long
+clips can still need substantial RAM. These tests do not establish minute-scale
+memory use, universal speedups or less RAM for every input.
+
+An earlier separate four-view, three-second comparison also retained identical
+masks, landmarks, final mesh and joints. The app-path regression and remaining
+scope are recorded in [validation](VALIDATION.md#mamma-direct-sam-input-2026-11-03).
+
+### Other MAMMA optimizations
The current MAMMA adapter uses exact-coordinate ROI preprocessing, CPU checkpoint
loading, a mask-based landmark path without an unnecessary detector, fewer
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index a3a442d..ba91b3d 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -2086,3 +2086,38 @@ Ctrl+wheel, text/keyboard edits, frame/camera and idle processing state. Six
offscreen create/close cycles retained 419 handles and 34 threads; the final
repeat's RSS ranged 81.56–84.43 MiB. This short trend does not establish long-session leak freedom.
Inference, correction, preview math and installed packages were unchanged.
+
+## MAMMA direct SAM input (2026-11-03)
+
+The app now reads SAM 2.1 frames through the prepared-video reader instead of
+saving and rereading intermediate lossless RGB PNGs. The adapter creates no
+empty frame-index files. PIL resize, float64 division into FP32 storage,
+normalization, CPU video/state offload, prompts, matching, propagation and final
+mask cleanup are unchanged. Final person-mask PNGs are still saved normally.
+The helper is included in inference code identities. Existing committed results
+are not rewritten on open; explicit reconstruction uses a new generation.
+
+Independent four-camera, two-person 1080p tests used the same video prefix at
+210/426 frames (7/14.2 seconds, 30 fps). All 5,088 paired person-mask images
+were pixel-identical, with no memory-protection stop or OOM. Mask-stage time
+fell 16.9%/21.2%; peak RAM differences were +23/−3 MiB, with the same allocated
+and reserved CUDA peaks within each pair. These were fresh-process, single-run
+measurements on RTX 5090 / 96 GB RAM, not minute-scale or other-GPU guarantees.
+See [performance](PERFORMANCE.md#mamma-direct-sam-video-input-2026-11-03).
+
+The integrated app path was then exercised on a separate dynamic 90-frame,
+four-view/two-person 1080p segment through masks, FP32 landmarks and 3D fitting.
+Against the earlier PNG control with identical prepared inputs and calibration,
+all 720 person-mask images, landmark/contact arrays, final meshes and joints
+were bit-identical. The new mask worker took 91.48 s with 4.731 GiB maximum RAM
+working set and 2.536 GiB allocated / 2.861 GiB reserved CUDA memory. This is
+the mask stage only; fresh camera estimation, app correction, GUI playback and
+exports were not rerun for this input-loading change.
+
+Controlled checks covered sequential reads, the same normalized tensor as PNG,
+Unicode path registration, empty-source rejection, unregistered/image-source
+fallback, and restoration on success, decode/OOM/cancellation exceptions and
+repeated app-wrapper failures. The adapter owns no additional readers, queues
+or threads. The updated Model Guide rendered in offscreen Qt. The installed
+MAMMA engine's 368 checked source files were unchanged. Tests/inputs remained
+outside the public checkout; no runtime package or model weight was added.
diff --git a/mocap/mamma_pipeline.py b/mocap/mamma_pipeline.py
index 16e4c7b..fee0442 100644
--- a/mocap/mamma_pipeline.py
+++ b/mocap/mamma_pipeline.py
@@ -105,7 +105,7 @@ def prepare(path, job):
# All connector code contributes, not just the model prediction script.
from .paths import ROOT
from .storage import sha256
- identity['code']={name:sha256(ROOT/'mocap'/name) for name in ('mamma_pipeline.py','mamma_camera.py','mamma_gravity.py','mamma_gravity_worker.py','mamma_inputs.py','image_io.py','memory_mode.py','gpu_offload.py','worker_progress.py','runtime_registry.py','pear/alignment_support.py')}
+ identity['code']={name:sha256(ROOT/'mocap'/name) for name in ('mamma_pipeline.py','mamma_sam_frames.py','mamma_camera.py','mamma_gravity.py','mamma_gravity_worker.py','mamma_inputs.py','image_io.py','memory_mode.py','gpu_offload.py','worker_progress.py','runtime_registry.py','pear/alignment_support.py')}
token=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()[:24]
slot=job['root']/'mamma'/'inference'/token
cached=False
@@ -169,21 +169,11 @@ def masks(engine, work, job):
raise ValueError('Unsupported MAMMA appearance model; no automatic downloads are allowed.')
kwargs['pretrained']=str(BY_KEY['mamma_clip'].path)
return original_clip(name,*args,**kwargs)
- open_clip.create_model_and_transforms=local_clip
sys.path[:0]=[str(engine/'segmentation'),str(engine)]
from core.pipeline import SegmentMultipleFrames
from core.frame_source import VideoSource
- original=SegmentMultipleFrames._resolve_sam_video_source
- def resolve(self,frames,cam_data=None):
- if not isinstance(frames,VideoSource):return original(self,frames,cam_data)
- dest=Path(self.output_path)/frames.cam_name/'_sam_frames_lossless'
- dest.mkdir(parents=True,exist_ok=True)
- for i in range(len(frames)):
- if i%30==0:emit('progress',current=i,total=len(frames),message='Prepare SAM frames: '+frames.cam_name)
- if not write_image(str(dest/f'{i:06}.png'),frames.reader.read_bgr(i)):
- raise OSError('Cannot write a lossless SAM input frame.')
- return str(dest)
- SegmentMultipleFrames._resolve_sam_video_source=resolve
+ import sam2.sam2_video_predictor as sam_video
+ from .mamma_sam_frames import direct_video_frames
names=[v['id'] for v in job['inputs']]
config=yaml.safe_load((engine/'segmentation/configs/sam2.yaml').read_text(encoding='utf-8'))
# Frozen settings from the completed occlusion trials: a single anatomical
@@ -202,7 +192,12 @@ def masks(engine, work, job):
'--skip_masked_outputs','--skip_collage','--cfg',config_path]
people=job['options'].get('people',0)
if people:args+=['--expected_subjects',people]
- run_script(engine,'segmentation','run_ma_masks.py',args)
+ open_clip.create_model_and_transforms=local_clip
+ try:
+ with direct_video_frames(SegmentMultipleFrames,VideoSource,sam_video,emit):
+ run_script(engine,'segmentation','run_ma_masks.py',args)
+ finally:
+ open_clip.create_model_and_transforms=original_clip
raw=work/'masks/mamma_example/motion'
cleaned=work/'clean-masks/motion'
count=0
diff --git a/mocap/mamma_sam_frames.py b/mocap/mamma_sam_frames.py
new file mode 100644
index 0000000..e947cdf
--- /dev/null
+++ b/mocap/mamma_sam_frames.py
@@ -0,0 +1,87 @@
+"""Lossless, worker-scoped SAM input from MAMMA's existing video reader."""
+from contextlib import contextmanager
+import os
+
+
+@contextmanager
+def direct_video_frames(pipeline_type, video_source_type, sam_video, progress):
+ """Replace only registered VideoSource inputs; restore upstream hooks on exit.
+
+ The pinned SAM loader otherwise reads lossless PNGs into one CPU FP32 frame
+ tensor. Keep its PIL resize, float64 division, FP32 assignment and in-place
+ normalization exactly, but decode through the same reader used by YOLO/CLIP.
+ Image-directory inputs retain the upstream loader. Readers belong to the
+ upstream pipeline; this adapter owns no captures or background threads.
+ """
+ import cv2
+ import numpy as np
+ import torch
+ from PIL import Image
+
+ original_resolve = pipeline_type._resolve_sam_video_source
+ original_load = sam_video.load_video_frames
+ registered = {}
+
+ def key(path):
+ return os.path.normcase(os.path.abspath(os.fspath(path)))
+
+ def resolve(self, frames, cam_data=None):
+ if not isinstance(frames, video_source_type):
+ return original_resolve(self, frames, cam_data)
+ # Cameras are processed sequentially. Do not retain every camera's reader
+ # or create empty image files just to give SAM a list of frame indices.
+ registered.clear()
+ registered[key(frames.video_path)] = frames
+ return str(frames.video_path)
+
+ def load(video_path, image_size, offload_video_to_cpu,
+ async_loading_frames=False, compute_device=torch.device('cuda'), **kwargs):
+ frames = registered.get(key(video_path))
+ if frames is None:
+ return original_load(video_path=video_path, image_size=image_size,
+ offload_video_to_cpu=offload_video_to_cpu,
+ async_loading_frames=async_loading_frames,
+ compute_device=compute_device, **kwargs)
+ n = len(frames)
+ if n < 1:
+ raise ValueError('MAMMA SAM input has no video frames.')
+ # Like the pinned eager loader: one normalized tensor plus one decoded
+ # image at a time. This is not an additional whole-video RGB cache.
+ images = torch.zeros(n, 3, image_size, image_size, dtype=torch.float32)
+ height = width = None
+ for i in range(n):
+ if i % 30 == 0:
+ progress('progress', current=i, total=n,
+ message='Prepare SAM input: ' + frames.cam_name)
+ bgr = frames.reader.read_bgr(i)
+ if bgr is None or bgr.ndim != 3 or bgr.shape[2] != 3:
+ raise ValueError(f'Cannot decode MAMMA SAM frame {i} in {frames.cam_name}.')
+ h, w = bgr.shape[:2]
+ if height is not None and (h, w) != (height, width):
+ raise ValueError('MAMMA camera resolution changed during decoding.')
+ height, width = h, w
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
+ with Image.fromarray(rgb) as image:
+ with image.resize((image_size, image_size)) as resized:
+ pixels = np.array(resized) / 255.
+ images[i] = torch.from_numpy(pixels).permute(2, 0, 1)
+ mean = torch.tensor(kwargs.get('img_mean', (.485, .456, .406)), dtype=torch.float32)[:, None, None]
+ std = torch.tensor(kwargs.get('img_std', (.229, .224, .225)), dtype=torch.float32)[:, None, None]
+ if not offload_video_to_cpu:
+ images = images.to(compute_device)
+ mean = mean.to(compute_device)
+ std = std.to(compute_device)
+ images -= mean
+ images /= std
+ progress('progress', current=n, total=n,
+ message='SAM input ready without intermediate PNGs: ' + frames.cam_name)
+ return images, height, width
+
+ pipeline_type._resolve_sam_video_source = resolve
+ sam_video.load_video_frames = load
+ try:
+ yield
+ finally:
+ pipeline_type._resolve_sam_video_source = original_resolve
+ sam_video.load_video_frames = original_load
+ registered.clear()
diff --git a/mocap/model_guide.py b/mocap/model_guide.py
index 731da3b..a212aad 100644
--- a/mocap/model_guide.py
+++ b/mocap/model_guide.py
@@ -65,7 +65,10 @@ be faster. These three models used the same seven-second clip; their times exclu
tracking, app correction and preview/export.</p>
<p>MAMMA used a different clip: three synchronized videos resized within 1920×1080,
two people and 413 frames at 30 fps. Its time includes preparation, correction and preview;
-memory covers masks, landmarks, VGGT and 3D fitting. This is not a direct speed comparison.</p>
+memory covers masks, landmarks, VGGT and 3D fitting. This is not a direct speed comparison.
+That row predates direct SAM video input. New paired four-view tests skipped intermediate
+RGB PNGs and cut mask-stage time by 17–21% with nearly unchanged RAM/VRAM and identical
+masks; this is not a whole-job speedup. See docs/MAMMA.md and docs/PERFORMANCE.md.</p>
<p>PromptHMR used 422 frames at 30 fps, one fixed-camera video and two people, with
Interaction Prompt and app correction on. Time includes tracking, native inference,
post-optimization, correction and preview/bone preparation; writing public FBX files is excluded.