Repository navigation
Expand file tree
/
Copy pathapi_service.py
More file actions
2811 lines (2406 loc) · 102 KB
/
Copy pathapi_service.py
File metadata and controls
2811 lines (2406 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""ML-Sharp SBS and Apple Spatial Video Conversion API Service.
A FastAPI service for converting 2D videos to SBS and MV-HEVC Spatial MOV.
"""
from __future__ import annotations
import gc
import hashlib
import json
import logging
import queue
import shutil
import subprocess
import tempfile
import contextlib
import threading
import time
import uuid
import zipfile
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import imageio.v2 as iio
import imageio_ffmpeg
import numpy as np
import torch
import uvicorn
from fastapi import (
BackgroundTasks,
FastAPI,
File,
Form,
HTTPException,
Query,
UploadFile,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from PIL import Image
from pydantic import BaseModel, Field
from sharp.models import PredictorParams, RGBGaussianPredictor, create_predictor
from sharp.utils import gsplat, io
from sharp.utils.gaussians import Gaussians3D, unproject_gaussians
from spatial_video import SpatialVideoPipeline, probe_video, validate_mv_hevc_container
import comfygallery_publisher
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s"
)
LOGGER = logging.getLogger(__name__)
# Silence werkzeug if imported elsewhere
try:
logging.getLogger("werkzeug").setLevel(logging.ERROR)
except Exception:
pass
# Constants
OUTPUT_DIR = Path("output")
OUTPUT_DIR.mkdir(exist_ok=True)
DEFAULT_MODEL_URL = "https://ml-site.cdn-apple.com/models/sharp/sharp_2572gikvuh.pt"
# Supported video formats
SUPPORTED_VIDEO_FORMATS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
# Global model cache
_model_cache = {"predictor": None, "device": None, "loading": False, "lock": threading.Lock()}
# Serialize complete GPU/media pipelines. Batch items and legacy single SBS jobs
# share the same model, renderer, and native encoding tools.
pipeline_execution_lock = threading.Lock()
# ============================================================================
# Data Models
# ============================================================================
class JobStatus(str, Enum):
"""Job status enumeration."""
QUEUED = "queued"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
class ProcessingStage(str, Enum):
"""Processing stage for progress tracking."""
QUEUED = "queued"
DOWNLOADING_MODEL = "downloading_model"
EXTRACTING_AUDIO = "extracting_audio"
PROCESSING_FRAMES = "processing_frames"
ENCODING_VIDEO = "encoding_video"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class JobInfo:
"""Job information data class."""
job_id: str
status: JobStatus
stage: ProcessingStage
progress: float # 0.0 to 1.0
processed_frames: int
total_frames: int
current_frame: int
created_at: datetime
started_at: Optional[datetime]
completed_at: Optional[datetime]
error_message: Optional[str]
output_files: List[str]
input_filename: str
settings: Dict[str, Any]
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
d = asdict(self)
d["created_at"] = self.created_at.isoformat()
d["started_at"] = self.started_at.isoformat() if self.started_at else None
d["completed_at"] = self.completed_at.isoformat() if self.completed_at else None
d["status"] = self.status.value
d["stage"] = self.stage.value
return d
# Pydantic models for API
class JobCreateResponse(BaseModel):
"""Response for job creation."""
job_id: str
status: JobStatus
message: str
class JobStatusResponse(BaseModel):
"""Response for job status query."""
job_id: str
status: JobStatus
stage: ProcessingStage
progress: float = Field(..., ge=0.0, le=1.0)
processed_frames: int
total_frames: int
current_frame: int
created_at: str
started_at: Optional[str]
completed_at: Optional[str]
error_message: Optional[str]
output_files: List[str]
input_filename: str
settings: Dict[str, Any]
class JobListResponse(BaseModel):
"""Response for job list."""
jobs: List[JobStatusResponse]
total: int
queued: int
running: int
completed: int
failed: int
class ServerStatusResponse(BaseModel):
"""Response for server status."""
status: str
device: str
model_loaded: bool
cuda_available: bool
active_jobs: int
total_jobs_processed: int
class ErrorResponse(BaseModel):
"""Error response."""
error: str
detail: Optional[str] = None
class SpatialBatchRecoveryRequest(BaseModel):
"""Settings used to adopt pre-manifest batch directories after a crash."""
quality: str = "balanced"
precision: str = "auto"
batch_size: int = Field(1, ge=1, le=8)
frame_skip: int = Field(1, ge=1, le=10)
opacity_threshold: float = Field(0.0, ge=0.0, le=1.0)
stereo_offset: float = Field(0.015, ge=0.0, le=0.1)
brightness_factor: float = Field(1.0, ge=0.1, le=3.0)
spatial_quality: str = "high"
spatial_preset: str = "medium"
camera_baseline: float = Field(64.0, gt=0.0)
horizontal_fov: float = Field(80.0, gt=0.0, lt=180.0)
disparity_adjustment: float = Field(0.0, ge=-1.0, le=1.0)
class SpatialBatchResumeRequest(BaseModel):
"""Choose where a paused batch should re-enter the FIFO queue."""
position: str = "end"
class SpatialBatchPublishRequest(BaseModel):
"""Trigger ComfyGallery publishing for a batch on demand.
`files` (optional) restricts the job to specific original_file names; when
omitted, every completed file that is not already published is published.
`force` re-publishes files even if they are already marked published.
"""
files: Optional[List[str]] = None
converter_name: str = comfygallery_publisher.DEFAULT_CONVERTER_NAME
converter_version: str = comfygallery_publisher.DEFAULT_CONVERTER_VERSION
force: bool = False
class SpatialBatchFileRemoveRequest(BaseModel):
"""Remove one or more files from an active/queued batch.
Removed files are skipped by the worker (if not yet processed) and their
copied original + SBS + spatial artifacts are deleted from disk.
"""
files: List[str]
# ============================================================================
# Job Queue Management
# ============================================================================
class JobQueue:
"""Thread-safe job queue with status tracking."""
def __init__(self, max_concurrent_jobs: int = 1):
"""Initialize the queue and start its background processor."""
self.max_concurrent_jobs = max_concurrent_jobs
self.jobs: Dict[str, JobInfo] = {}
self.lock = threading.Lock()
self.processing_thread: Optional[threading.Thread] = None
self.running = True
self.total_processed = 0
self._start_processor()
def _start_processor(self):
"""Start the background job processor thread."""
self.processing_thread = threading.Thread(target=self._process_queue, daemon=True)
self.processing_thread.start()
def _process_queue(self):
"""Background thread to process queued jobs."""
while self.running:
with self.lock:
running_jobs = [
j
for j in self.jobs.values()
if j.status in (JobStatus.RUNNING, JobStatus.QUEUED)
]
active_jobs = [j for j in running_jobs if j.status == JobStatus.RUNNING]
# Start new jobs if capacity available
if len(active_jobs) < self.max_concurrent_jobs:
queued_jobs = [j for j in running_jobs if j.status == JobStatus.QUEUED]
for job in queued_jobs[: self.max_concurrent_jobs - len(active_jobs)]:
self._start_job(job)
time.sleep(0.5)
def _start_job(self, job: JobInfo):
"""Start a job in a background thread."""
job.status = JobStatus.RUNNING
job.started_at = datetime.now()
job.stage = ProcessingStage.PROCESSING_FRAMES
thread = threading.Thread(target=self._run_job_wrapper, args=(job,), daemon=True)
thread.start()
def _run_job_wrapper(self, job: JobInfo):
"""Wrapper to run job and handle completion."""
try:
with pipeline_execution_lock:
run_sbs_conversion_job(job)
with self.lock:
job.status = JobStatus.COMPLETED
job.stage = ProcessingStage.COMPLETED
job.progress = 1.0
job.completed_at = datetime.now()
self.total_processed += 1
except Exception as e:
LOGGER.exception(f"Job {job.job_id} failed")
with self.lock:
job.status = JobStatus.FAILED
job.stage = ProcessingStage.FAILED
job.error_message = str(e)
job.completed_at = datetime.now()
def create_job(
self, job_id: str, input_path: Path, input_filename: str, settings: Dict[str, Any]
) -> JobInfo:
"""Create a new job."""
job = JobInfo(
job_id=job_id,
status=JobStatus.QUEUED,
stage=ProcessingStage.QUEUED,
progress=0.0,
processed_frames=0,
total_frames=0,
current_frame=0,
created_at=datetime.now(),
started_at=None,
completed_at=None,
error_message=None,
output_files=[],
input_filename=input_filename,
settings=settings,
)
with self.lock:
self.jobs[job_id] = job
return job
def get_job(self, job_id: str) -> Optional[JobInfo]:
"""Get job by ID."""
with self.lock:
return self.jobs.get(job_id)
def list_jobs(self, status: Optional[JobStatus] = None) -> List[JobInfo]:
"""List all jobs, optionally filtered by status."""
with self.lock:
jobs = list(self.jobs.values())
if status:
jobs = [j for j in jobs if j.status == status]
return sorted(jobs, key=lambda j: j.created_at, reverse=True)
def cancel_job(self, job_id: str) -> bool:
"""Cancel a job."""
with self.lock:
job = self.jobs.get(job_id)
if job and job.status in (JobStatus.QUEUED, JobStatus.RUNNING):
job.status = JobStatus.CANCELLED
job.stage = ProcessingStage.FAILED
job.error_message = "Job cancelled by user"
job.completed_at = datetime.now()
return True
return False
def cleanup_old_jobs(self, max_age_hours: int = 24):
"""Clean up old completed jobs."""
cutoff = datetime.now() - timedelta(hours=max_age_hours)
with self.lock:
to_remove = [
job_id
for job_id, job in self.jobs.items()
if job.completed_at and job.completed_at < cutoff
]
for job_id in to_remove:
del self.jobs[job_id]
# Global job queue
job_queue = JobQueue(max_concurrent_jobs=1)
# ============================================================================
# Device and Model Management
# ============================================================================
def get_device() -> torch.device:
"""Get the best available device."""
if _model_cache["device"] is not None:
return _model_cache["device"]
if torch.cuda.is_available():
return torch.device("cuda")
elif torch.mps.is_available():
return torch.device("mps")
else:
return torch.device("cpu")
def get_predictor() -> tuple[RGBGaussianPredictor, torch.device]:
"""Get or create the Gaussian predictor model (thread-safe)."""
# Fast path: already loaded
if _model_cache["predictor"] is not None:
return _model_cache["predictor"], _model_cache["device"]
# Use lock to prevent multiple threads from loading simultaneously
with _model_cache["lock"]:
# Double-check after acquiring lock
if _model_cache["predictor"] is not None:
return _model_cache["predictor"], _model_cache["device"]
# Prevent re-entry if already loading
if _model_cache["loading"]:
# Wait for loading to complete
while _model_cache["loading"]:
time.sleep(0.1)
return _model_cache["predictor"], _model_cache["device"]
_model_cache["loading"] = True
try:
target_device = torch.device("cpu")
if torch.cuda.is_available():
target_device = torch.device("cuda")
try:
gpu_name = torch.cuda.get_device_name(0)
LOGGER.info(f"CUDA GPU detected: {gpu_name}")
except Exception:
LOGGER.info("CUDA GPU detected (name unknown)")
elif torch.mps.is_available():
target_device = torch.device("mps")
LOGGER.info("Apple MPS acceleration detected.")
else:
LOGGER.info("No active GPU detected. Using CPU.")
LOGGER.info(f"Targeting device for inference: {target_device}")
LOGGER.info(f"Downloading model from {DEFAULT_MODEL_URL}")
state_dict = torch.hub.load_state_dict_from_url(
DEFAULT_MODEL_URL, progress=True, map_location="cpu"
)
LOGGER.info("Initializing predictor...")
predictor = create_predictor(PredictorParams())
predictor.load_state_dict(state_dict)
predictor.eval()
final_device = torch.device("cpu")
if target_device.type != "cpu":
try:
LOGGER.info(f"Moving model to {target_device}...")
predictor.to(target_device)
dummy = torch.zeros(1).to(target_device)
del dummy
final_device = target_device
except RuntimeError as e:
LOGGER.warning(f"Failed to initialize on {target_device}: {e}.")
LOGGER.warning("Falling back to CPU mode.")
predictor.to("cpu")
final_device = torch.device("cpu")
else:
predictor.to("cpu")
_model_cache["predictor"] = predictor
_model_cache["device"] = final_device
LOGGER.info(f"Model successfully loaded and running on: {final_device}")
return predictor, final_device
finally:
_model_cache["loading"] = False
def get_next_job_prefix() -> str:
"""Scan output dir and return the next available 3-digit prefix."""
try:
max_idx = 0
for item in OUTPUT_DIR.iterdir():
if item.name[:3].isdigit() and item.name[3] == "_":
try:
idx = int(item.name[:3])
if idx > max_idx:
max_idx = idx
except ValueError:
continue
return f"{max_idx + 1:03d}"
except Exception as e:
LOGGER.error(f"Error calculating job prefix: {e}")
return "000"
# ============================================================================
# Video Processing Functions
# ============================================================================
@torch.no_grad()
def predict_batch(
predictor: RGBGaussianPredictor,
images: list[np.ndarray],
f_px: float,
device: torch.device,
use_fp16: bool = False,
) -> list[Gaussians3D]:
"""Predict Gaussians from a batch of images."""
if not images:
return []
internal_shape = (1536, 1536)
batch_np = np.stack(images)
batch_pt = torch.from_numpy(batch_np).float().to(device).permute(0, 3, 1, 2) / 255.0
batch_size, _, height, width = batch_pt.shape
disparity_val = f_px / width
disparity_factor = torch.full((batch_size,), disparity_val, device=device, dtype=torch.float32)
batch_resized_pt = torch.nn.functional.interpolate(
batch_pt,
size=(internal_shape[1], internal_shape[0]),
mode="bilinear",
align_corners=True,
)
if use_fp16 and device.type == "cuda":
with torch.amp.autocast("cuda", dtype=torch.float16):
gaussians_ndc = predictor(batch_resized_pt, disparity_factor)
else:
gaussians_ndc = predictor(batch_resized_pt, disparity_factor)
intrinsics = (
torch.tensor(
[
[f_px, 0, width / 2, 0],
[0, f_px, height / 2, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
)
.float()
.to(device)
)
intrinsics_resized = intrinsics.clone()
intrinsics_resized[0] *= internal_shape[0] / width
intrinsics_resized[1] *= internal_shape[1] / height
gaussians_batch = unproject_gaussians(
gaussians_ndc, torch.eye(4).to(device), intrinsics_resized, internal_shape
)
results = []
for i in range(batch_size):
results.append(
Gaussians3D(
mean_vectors=gaussians_batch.mean_vectors[i : i + 1],
singular_values=gaussians_batch.singular_values[i : i + 1],
quaternions=gaussians_batch.quaternions[i : i + 1],
colors=gaussians_batch.colors[i : i + 1],
opacities=gaussians_batch.opacities[i : i + 1],
)
)
return results
def update_job_progress(
job: JobInfo, progress: float, processed_frames: int, stage: ProcessingStage = None
):
"""Update job progress."""
with job_queue.lock:
job.progress = progress
job.processed_frames = processed_frames
job.current_frame = processed_frames
if stage:
job.stage = stage
def run_sbs_conversion_job(job: JobInfo):
"""Run the SBS video conversion job.
This function is called in a background thread by the JobQueue.
"""
predictor = None
device = None
reader = None
tmp_path = None
work_dir = None
try:
# Verify CUDA for rendering
predictor, device = get_predictor()
if device.type != "cuda":
raise RuntimeError("SBS Rendering requires a CUDA GPU. CPU/MPS not supported.")
# Load video info from settings
tmp_path = Path(job.settings.get("tmp_path"))
original_stem = job.settings.get("original_stem", "video")
# Processing parameters
use_fp16 = job.settings.get("use_fp16", False)
batch_size = job.settings.get("batch_size", 1)
frame_skip = job.settings.get("frame_skip", 1)
opacity_threshold = job.settings.get("opacity_threshold", 0.0)
stereo_offset = job.settings.get("stereo_offset", 0.015)
brightness_factor = job.settings.get("brightness_factor", 1.0)
fps = job.settings.get("fps", 30.0)
# Determine folder names. Batch callers can provide exact paths while
# legacy single-file jobs keep their numbered output convention.
job_prefix = job.settings.get("job_prefix") or get_next_job_prefix()
requested_work_dir = job.settings.get("work_dir")
work_dir = (
Path(requested_work_dir)
if requested_work_dir
else OUTPUT_DIR / f"{job_prefix}_{original_stem}_frames"
)
work_dir.mkdir(parents=True, exist_ok=True)
audio_path = work_dir / "audio.aac"
LOGGER.info(f"Job {job.job_id} [{job_prefix}] | Batch: {batch_size} | Folder: {work_dir}")
# Update job stage
update_job_progress(job, 0.0, 0, ProcessingStage.EXTRACTING_AUDIO)
# 1. Extract Audio
LOGGER.info(f"Job {job.job_id}: Extracting audio...")
ffmpeg_exe = imageio_ffmpeg.get_ffmpeg_exe()
audio_cmd = [
ffmpeg_exe,
"-y",
"-i",
str(tmp_path),
"-vn",
"-acodec",
"copy",
str(audio_path),
]
has_audio = False
try:
subprocess.run(
audio_cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
if audio_path.exists() and audio_path.stat().st_size > 0:
has_audio = True
except subprocess.CalledProcessError:
LOGGER.warning(f"Job {job.job_id}: No audio track found or extraction failed.")
# 2. Setup Processing
reader = iio.get_reader(tmp_path)
total_frames_raw = reader.count_frames()
total_frames = (total_frames_raw + frame_skip - 1) // frame_skip
with job_queue.lock:
job.total_frames = total_frames
LOGGER.info(
f"Job {job.job_id}: {total_frames_raw} total frames, "
f"{total_frames} to render (skip={frame_skip})"
)
# Get video dimensions from first frame
first_frame = reader.get_data(0)
h, w = first_frame.shape[:2]
# USE INPUT VIDEO DIMENSIONS for render resolution
render_h = h
render_w = w
# SBS output will be 2x width (for side-by-side)
sbs_width = render_w * 2
LOGGER.info(
f"Job {job.job_id}: Input dimensions {w}x{h}, SBS output {sbs_width}x{render_h}"
)
# Initialize Renderer
try:
renderer = gsplat.GSplatRenderer(color_space="linearRGB")
except Exception as e:
if "cl" in str(e) or "DLL" in str(e):
raise RuntimeError("gsplat compilation failed. Install VS Build Tools.")
raise e
png_files = []
batch_frames = []
batch_indices = []
# Cache stereo camera extrinsics
_cached_ext_left = torch.eye(4, device=device)
_cached_ext_left[0, 3] = stereo_offset
_cached_ext_right = torch.eye(4, device=device)
_cached_ext_right[0, 3] = -stereo_offset
_cached_intrinsics_template = None
_cached_frame_dims = None
update_job_progress(job, 0.0, 0, ProcessingStage.PROCESSING_FRAMES)
def process_sbs_batch(frames, indices):
nonlocal _cached_intrinsics_template, _cached_frame_dims
try:
# Preprocess
clean_frames = []
for f in frames:
if f.shape[2] > 3:
clean_frames.append(f[:, :, :3])
else:
clean_frames.append(f)
fh, fw = clean_frames[0].shape[:2]
f_px = io.convert_focallength(fw, fh, 30.0)
# Predict Batch
gaussians_list = predict_batch(
predictor, clean_frames, f_px, device, use_fp16=use_fp16
)
# Cache intrinsics if frame dimensions match
if _cached_frame_dims != (fh, fw):
f_px_render = f_px * (render_w / fw)
_cached_intrinsics_template = torch.tensor(
[
[f_px_render, 0, render_w / 2, 0],
[0, f_px_render, render_h / 2, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
],
device=device,
dtype=torch.float32,
)
_cached_frame_dims = (fh, fw)
intrinsics = _cached_intrinsics_template
ext_left = _cached_ext_left
ext_right = _cached_ext_right
for k, gaussians in enumerate(gaussians_list):
idx = indices[k]
# Check if job was cancelled
with job_queue.lock:
if job.status == JobStatus.CANCELLED:
raise InterruptedError("Job cancelled")
# Halo Removal
if opacity_threshold > 0.0:
mask = gaussians.opacities[0] > opacity_threshold
gaussians = Gaussians3D(
mean_vectors=gaussians.mean_vectors[:, mask],
singular_values=gaussians.singular_values[:, mask],
quaternions=gaussians.quaternions[:, mask],
colors=gaussians.colors[:, mask],
opacities=gaussians.opacities[:, mask],
)
f_px_render = f_px * (render_w / fw)
intrinsics = torch.tensor(
[
[f_px_render, 0, render_w / 2, 0],
[0, f_px_render, render_h / 2, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
],
device=device,
dtype=torch.float32,
)
ext_left = torch.eye(4, device=device)
ext_left[0, 3] = stereo_offset
ext_right = torch.eye(4, device=device)
ext_right[0, 3] = -stereo_offset
# Render Left
out_left = renderer(
gaussians,
extrinsics=ext_left.unsqueeze(0),
intrinsics=intrinsics.unsqueeze(0),
image_width=render_w,
image_height=render_h,
)
img_left_tensor = (out_left.color[0] * brightness_factor).clamp(0, 1)
img_left = (img_left_tensor.permute(1, 2, 0) * 255).byte().cpu().numpy()
# Render Right
out_right = renderer(
gaussians,
extrinsics=ext_right.unsqueeze(0),
intrinsics=intrinsics.unsqueeze(0),
image_width=render_w,
image_height=render_h,
)
img_right_tensor = (out_right.color[0] * brightness_factor).clamp(0, 1)
img_right = (img_right_tensor.permute(1, 2, 0) * 255).byte().cpu().numpy()
# Stitch
img_sbs = np.concatenate((img_left, img_right), axis=1)
frame_name = f"frame_{idx:05d}.png"
frame_path = work_dir / frame_name
Image.fromarray(img_sbs).save(frame_path)
png_files.append(frame_path)
# Update progress
progress = (idx + 1) / total_frames
update_job_progress(job, progress, idx + 1)
del (
gaussians,
out_left,
out_right,
img_left_tensor,
img_right_tensor,
img_left,
img_right,
img_sbs,
)
# Cleanup
torch.cuda.empty_cache()
gc.collect()
except RuntimeError as e:
if "out of memory" in str(e).lower() and len(frames) > 1:
LOGGER.warning(f"OOM in SBS job with batch {len(frames)}. Switching to 1.")
torch.cuda.empty_cache()
for i in range(len(frames)):
process_sbs_batch([frames[i]], [indices[i]])
return True
else:
raise e
return False
# 3. Frame Loop
fallback_mode = False
output_frame_idx = 0
for i, frame in enumerate(reader):
# Check cancellation
with job_queue.lock:
if job.status == JobStatus.CANCELLED:
LOGGER.info(f"Job {job.job_id} cancelled by user.")
raise InterruptedError("Job cancelled")
# Frame skip logic
if i % frame_skip != 0:
continue
batch_frames.append(frame)
batch_indices.append(output_frame_idx)
output_frame_idx += 1
effective_bs = 1 if fallback_mode else batch_size
if len(batch_frames) >= effective_bs:
oom = process_sbs_batch(batch_frames, batch_indices)
if oom:
fallback_mode = True
batch_frames = []
batch_indices = []
if i % 10 == 0:
LOGGER.info(f"Job {job.job_id}: SBS Rendered frame {i + 1}/{total_frames_raw}")
# Process remainder
if batch_frames:
process_sbs_batch(batch_frames, batch_indices)
reader.close()
# 4. Final Assembly
if png_files:
update_job_progress(job, 0.95, total_frames, ProcessingStage.ENCODING_VIDEO)
requested_output_path = job.settings.get("output_path")
if requested_output_path:
output_path = Path(requested_output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_filename = output_path.name
else:
output_filename = f"{job_prefix}_{original_stem}_SBS.mp4"
output_path = OUTPUT_DIR / output_filename
LOGGER.info(f"Job {job.job_id}: Encoding SBS video to {output_filename}...")
output_fps = fps / frame_skip
LOGGER.info(
f"Job {job.job_id}: Output FPS adjusted from {fps} to "
f"{output_fps} (frame_skip={frame_skip})"
)
input_pattern = str(work_dir / "frame_%05d.png")
cmd = [ffmpeg_exe, "-y", "-framerate", str(output_fps), "-i", input_pattern]
if has_audio:
cmd.extend(["-i", str(audio_path)])
cmd.extend(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-preset", "fast"])
if has_audio:
cmd.append("-shortest")
cmd.append(str(output_path))
try:
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
with job_queue.lock:
job.output_files.append(output_filename)
LOGGER.info(f"Job {job.job_id}: SBS video encoding complete: {output_filename}")
except subprocess.CalledProcessError as e:
LOGGER.error(f"FFmpeg encoding failed: {e.stderr.decode()}")
raise RuntimeError("Video encoding failed.")
else:
raise RuntimeError("No frames were processed.")
except InterruptedError:
# Job was cancelled, just exit
LOGGER.info(f"Job {job.job_id} processing interrupted")
raise
except Exception:
LOGGER.exception(f"Job {job.job_id} failed")
raise
finally:
# Cleanup
if reader:
try:
reader.close()
except Exception:
pass
if job.settings.get("delete_input", True) and tmp_path and tmp_path.exists():
try:
tmp_path.unlink()
except Exception:
pass
# NOTE: Keep work_dir for debugging/output files
# ============================================================================
# Sequential Original -> SBS -> Spatial Batch Management
# ============================================================================
SPATIAL_BATCH_MAX_FILES = 20
SPATIAL_BATCH_STATE_DIRNAME = ".spatial_batch_state"
spatial_batches: Dict[str, Dict[str, Any]] = {}
spatial_batch_runtime: Dict[str, Dict[str, Any]] = {}
spatial_batches_lock = threading.Lock()
spatial_batch_queue: queue.Queue[str] = queue.Queue()
spatial_batch_recovery_lock = threading.Lock()
spatial_batch_recovery_started = False
def _spatial_batch_state_path(batch_id: str) -> Path:
"""Return the durable state path for one server-generated batch ID."""
return OUTPUT_DIR / SPATIAL_BATCH_STATE_DIRNAME / f"{batch_id}.json"
def _persist_spatial_batch(batch_id: str) -> None:
"""Atomically persist public state and runtime settings for restart recovery."""
with spatial_batches_lock:
public_state = spatial_batches.get(batch_id)
runtime = spatial_batch_runtime.get(batch_id)
if public_state is None:
return
payload = {
"version": 1,
"public_state": json.loads(json.dumps(public_state)),
"runtime": json.loads(json.dumps(runtime)) if runtime is not None else None,
}
state_path = _spatial_batch_state_path(batch_id)
state_path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = state_path.with_suffix(".json.tmp")
temporary_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
temporary_path.replace(state_path)
def _safe_batch_names(filename: str, index: int, used_stems: set[str]) -> tuple[str, str, str, str]:
"""Return a safe, collision-free original/SBS/spatial filename set."""
leaf_name = Path((filename or "").replace("\\", "/")).name
suffix = Path(leaf_name).suffix.lower()
raw_stem = Path(leaf_name).stem
safe_stem = "".join(
character if character.isalnum() or character in "-_" else "_" for character in raw_stem
).strip("._")
safe_stem = safe_stem or f"video_{index:03d}"
candidate = safe_stem
duplicate_index = 2
while candidate.casefold() in used_stems:
candidate = f"{safe_stem}_{duplicate_index}"
duplicate_index += 1
used_stems.add(candidate.casefold())
return (
candidate,
f"{candidate}{suffix}",
f"{candidate}_sbs.mp4",
f"{candidate}_spatial.mov",
)