From 8dda5bc897fda5c7868a1dc0f6d660cda3020960 Mon Sep 17 00:00:00 2001 From: Morgan Williams Date: Wed, 24 Dec 2025 16:44:26 +0100 Subject: [PATCH] Add end-to-end pipeline for 2D to spatial video conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pipeline.py orchestrates: downscale → depth → SBS → spatial - Supports configurable encoder (vits/vitb/vitl) and disparity - Integrates with spatial CLI for MV-HEVC output - Auto-cleans intermediate files (optional --keep-intermediate) - Updated README with comprehensive documentation and usage examples --- README.md | 140 +++++++++++++++++++++++++++--- pipeline.py | 239 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 367 insertions(+), 12 deletions(-) create mode 100644 pipeline.py diff --git a/README.md b/README.md index 51c92f7..f63f3e8 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,140 @@ -# Project Objective & Next Steps +# Spatial Video Maker -## Primary Objective +Convert 2D videos to stereoscopic 3D spatial videos for viewing on VR headsets (Apple Vision Pro / Meta Quest) using local, on-device processing with Apple Silicon Metal acceleration. -**Convert 2D videos to stereoscopic 3D (side-by-side or spatial video format) for viewing on VR headsets (Apple Vision Pro / Meta Quest) using local, on-device processing with Apple Silicon Metal acceleration.** - -We will be using the [spatial cli](https://blog.mikeswanson.com/spatial_docs/) to generate spatial videos from side-by-side ("sbs") stereoscopic videos. - -## Current pipeline +## Pipeline Overview ``` Input 2D Video - -[create a downscaled copy to 1080p24fps] ↓ -[Generate depth for video using depth anything v2 (can choose model)] +[Downscale to 1080p @ 24fps] ↓ -[Create stereoscopic version (sbs)] +[Generate depth maps using Depth Anything V2] ↓ -[Create spatial version (`spatial make`)] +[Create side-by-side (SBS) stereoscopic video] + ↓ +[Convert to MV-HEVC spatial video using `spatial` CLI] ↓ MV-HEVC Spatial Video (Vision Pro/Quest compatible) +``` + +## Quick Start + +### Basic Usage + +```bash +# Run the full pipeline +python pipeline.py input_video.mp4 + +# Specify output path +python pipeline.py input_video.mp4 -o output_spatial.mov +``` + +### Options + +```bash +# Use a larger depth model for better quality (vits, vitb, vitl) +python pipeline.py input_video.mp4 --encoder vitl + +# Adjust 3D intensity (20-50 recommended for 1080p) +python pipeline.py input_video.mp4 --max-disparity 40 + +# Process only the first 10 seconds (useful for testing) +python pipeline.py input_video.mp4 --duration 10 + +# Keep intermediate files for debugging +python pipeline.py input_video.mp4 --keep-intermediate + +# Skip downscaling if input is already 1080p @ 24fps +python pipeline.py input_video.mp4 --skip-downscale +``` + +## Requirements + +### Dependencies + +```bash +# Install Python dependencies +uv sync +``` + +### External Tools + +- **ffmpeg** with VideoToolbox support (for hardware-accelerated encoding) +- **[spatial CLI](https://blog.mikeswanson.com/spatial_docs/)** for MV-HEVC spatial video creation +Install spatial CLI: +```bash +brew install spatial +``` + +### Depth Model Checkpoints + +Download Depth Anything V2 checkpoints to `Depth-Anything-V2/checkpoints/`: +- `depth_anything_v2_vits.pth` (small, fastest) +- `depth_anything_v2_vitb.pth` (base, balanced) +- `depth_anything_v2_vitl.pth` (large, best quality) + +## Individual Scripts + +### Depth Estimation + +```bash +# Generate depth maps for a video +python -c " +from depth_estimators import DepthAnythingV2Estimator +estimator = DepthAnythingV2Estimator(encoder='vits') +result = estimator.process_video('input.mp4', 'output/depth_frames') +" +``` + +### Stereo Conversion + +```bash +# Convert 2D video + depth frames to SBS stereoscopic +python scripts/stereo_converter.py input.mp4 output/depth_frames output_sbs.mp4 --max-disparity 30 +``` + +### Downscaling + +```bash +# Downscale to 1080p @ 24fps +python scripts/downscale_video.py input.mp4 output_1080p.mp4 +``` + +## Parameters Guide + +| Parameter | Description | Recommended | +|-----------|-------------|-------------| +| `--encoder` | Depth model size (vits/vitb/vitl) | `vits` for speed, `vitl` for quality | +| `--max-disparity` | 3D intensity in pixels | 20-50 for 1080p | +| `--duration` | Limit processing time | Use for testing | + +### Disparity Guidelines + +- **20-30**: Subtle 3D effect, comfortable for long viewing +- **30-40**: Moderate 3D effect, good balance +- **40-50**: Strong 3D effect, more immersive but may cause discomfort + +## Output Formats + +- **SBS (Side-by-Side)**: Half-width format, compatible with most VR players +- **MV-HEVC**: Apple's spatial video format for Vision Pro + +## Project Structure + +``` +spatial-maker/ +├── pipeline.py # End-to-end conversion pipeline +├── depth_estimators/ +│ ├── depth_anything_v2.py # Depth Anything V2 implementation +│ └── apple_depth_pro.py # Apple Depth Pro implementation +├── scripts/ +│ ├── stereo_converter.py # SBS stereoscopic conversion +│ ├── downscale_video.py # Video downscaling utility +│ └── stitch_video.py # Frame stitching utility +├── Depth-Anything-V2/ # Depth Anything V2 submodule +│ └── checkpoints/ # Model checkpoints +├── samples/ # Sample videos +└── output/ # Generated outputs ``` diff --git a/pipeline.py b/pipeline.py new file mode 100644 index 0000000..7addcae --- /dev/null +++ b/pipeline.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +""" +End-to-end pipeline for converting 2D videos to spatial 3D videos. + +Pipeline stages: +1. Downscale input video to 1080p @ 24fps +2. Generate depth maps using Depth Anything V2 +3. Create side-by-side stereoscopic video +4. Convert to MV-HEVC spatial video using spatial CLI + +Usage: + python pipeline.py input_video.mp4 -o output_spatial.mov + python pipeline.py input_video.mp4 --encoder vitb --max-disparity 40 +""" + +import argparse +import subprocess +import sys +from pathlib import Path +import shutil + +from scripts.downscale_video import downscale_to_1080p24 +from scripts.stereo_converter import convert_video_to_sbs +from depth_estimators import DepthAnythingV2Estimator + + +def check_spatial_cli(): + """Check if the spatial CLI is available.""" + try: + result = subprocess.run( + ["spatial", "--version"], + capture_output=True, + text=True, + ) + return result.returncode == 0 + except FileNotFoundError: + return False + + +def run_pipeline( + input_video: str, + output_path: str = None, + encoder: str = "vits", + max_disparity: int = 30, + keep_intermediate: bool = False, + skip_downscale: bool = False, + duration: float = None, +): + """ + Run the full 2D to spatial video conversion pipeline. + + Args: + input_video: Path to input 2D video + output_path: Path for output spatial video (default: input_spatial.mov) + encoder: Depth Anything V2 encoder (vits, vitb, vitl) + max_disparity: Maximum pixel disparity for 3D effect (20-50 for 1080p) + keep_intermediate: Keep intermediate files (depth frames, SBS video) + skip_downscale: Skip downscaling if input is already 1080p24 + duration: Optional duration limit in seconds + + Returns: + Path to the output spatial video + """ + input_path = Path(input_video) + if not input_path.exists(): + raise FileNotFoundError(f"Input video not found: {input_video}") + + # Set up output paths + if output_path is None: + output_path = input_path.parent / f"{input_path.stem}_spatial.mov" + else: + output_path = Path(output_path) + + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Create working directory for intermediate files + work_dir = output_path.parent / f"{output_path.stem}_work" + work_dir.mkdir(exist_ok=True) + + try: + # Stage 1: Downscale to 1080p @ 24fps + print("\n" + "=" * 60) + print("Stage 1: Preparing input video (1080p @ 24fps)") + print("=" * 60) + + if skip_downscale: + prepared_video = str(input_path) + print(f" Skipping downscale, using: {prepared_video}") + else: + prepared_video = downscale_to_1080p24( + str(input_path), + output_path=str(work_dir / f"{input_path.stem}_1080p.mp4") if duration else None, + duration=duration, + ) + print(f" Prepared video: {prepared_video}") + + # Stage 2: Generate depth maps + print("\n" + "=" * 60) + print(f"Stage 2: Generating depth maps (encoder: {encoder})") + print("=" * 60) + + depth_dir = work_dir / "depth_frames" + estimator = DepthAnythingV2Estimator(encoder=encoder) + depth_result = estimator.process_video(prepared_video, str(depth_dir)) + print(f" Processed {depth_result['frames_processed']} frames at {depth_result['fps']} fps") + print(f" Depth video: {depth_result['video_path']}") + + # Stage 3: Create side-by-side stereoscopic video + print("\n" + "=" * 60) + print(f"Stage 3: Creating SBS stereoscopic video (disparity: {max_disparity})") + print("=" * 60) + + sbs_video = work_dir / f"{input_path.stem}_sbs.mp4" + sbs_result = convert_video_to_sbs( + prepared_video, + str(depth_dir), + str(sbs_video), + max_disparity=max_disparity, + fps=24, + half_width=True, + ) + print(f" SBS video: {sbs_result}") + + # Stage 4: Convert to spatial video using spatial CLI + print("\n" + "=" * 60) + print("Stage 4: Converting to MV-HEVC spatial video") + print("=" * 60) + + if not check_spatial_cli(): + print(" WARNING: 'spatial' CLI not found!") + print(" Install from: https://blog.mikeswanson.com/spatial") + print(f" SBS video ready at: {sbs_result}") + print(" Run manually: spatial make --sbs -o ") + final_output = sbs_result + else: + cmd = [ + "spatial", + "make", + "--sbs", + str(sbs_video), + "-o", + str(output_path), + ] + print(f" Running: {' '.join(cmd)}") + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode != 0: + print(f" Error: {result.stderr}") + raise RuntimeError("spatial CLI failed") + print(f" Spatial video: {output_path}") + final_output = str(output_path) + + print("\n" + "=" * 60) + print("Pipeline complete!") + print("=" * 60) + print(f" Output: {final_output}") + + return final_output + + finally: + # Cleanup intermediate files unless requested to keep them + if not keep_intermediate and work_dir.exists(): + print(f"\nCleaning up intermediate files in {work_dir}") + shutil.rmtree(work_dir, ignore_errors=True) + + +def main(): + parser = argparse.ArgumentParser( + description="Convert 2D video to spatial 3D video for VR headsets", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Basic usage (uses vits encoder, default settings) + python pipeline.py video.mp4 + + # Use larger encoder for better depth quality + python pipeline.py video.mp4 --encoder vitl + + # Adjust 3D intensity + python pipeline.py video.mp4 --max-disparity 40 + + # Process only first 10 seconds + python pipeline.py video.mp4 --duration 10 + + # Keep intermediate files for debugging + python pipeline.py video.mp4 --keep-intermediate + """, + ) + parser.add_argument("input", help="Input 2D video file") + parser.add_argument( + "-o", "--output", help="Output spatial video path (default: input_spatial.mov)" + ) + parser.add_argument( + "--encoder", + choices=["vits", "vitb", "vitl"], + default="vits", + help="Depth Anything V2 encoder size (default: vits)", + ) + parser.add_argument( + "--max-disparity", + type=int, + default=30, + help="Maximum pixel disparity for 3D effect, 20-50 for 1080p (default: 30)", + ) + parser.add_argument( + "--keep-intermediate", + action="store_true", + help="Keep intermediate files (depth frames, SBS video)", + ) + parser.add_argument( + "--skip-downscale", + action="store_true", + help="Skip downscaling (use if input is already 1080p @ 24fps)", + ) + parser.add_argument( + "--duration", + type=float, + help="Process only the first N seconds of the video", + ) + + args = parser.parse_args() + + try: + result = run_pipeline( + args.input, + output_path=args.output, + encoder=args.encoder, + max_disparity=args.max_disparity, + keep_intermediate=args.keep_intermediate, + skip_downscale=args.skip_downscale, + duration=args.duration, + ) + print(f"\nSuccess! Output: {result}") + except Exception as e: + print(f"\nError: {e}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() -- knotmirror 0.0.1