MogensR commited on
Commit
b1ff196
·
1 Parent(s): de84d79

Update processing/video/video_processor.py

Browse files
Files changed (1) hide show
  1. processing/video/video_processor.py +250 -58
processing/video/video_processor.py CHANGED
@@ -2,28 +2,31 @@
2
  """
3
  Compatibility shim: CoreVideoProcessor
4
 
5
- Bridges the legacy import
6
- from processing.video.video_processor import CoreVideoProcessor
7
- to the modern pipeline functions in utils (segment, refine, composite),
8
- using whatever models provider is passed in (e.g., models.loaders.ModelLoader).
9
-
10
- Requirements for the models provider:
11
- - get_sam2() -> predictor or None
12
- - get_matanyone() -> InferenceCore or compatible (or None)
13
  """
14
 
15
  from __future__ import annotations
16
 
17
  from dataclasses import dataclass
18
- from typing import Optional, Dict, Any, Callable
19
  import time
20
  import threading
 
 
 
 
21
 
22
  import cv2
23
  import numpy as np
24
  import torch
25
 
26
- # Logger (fallback to std logging if your project logger isn't available)
27
  try:
28
  from utils.logging_setup import make_logger
29
  _log = make_logger("processing.video.video_processor")
@@ -32,7 +35,7 @@
32
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
33
  _log = logging.getLogger(__name__)
34
 
35
- # New, hardened utils (device-safe, SAM2↔MatAnyOne interop)
36
  from utils import (
37
  segment_person_hq,
38
  refine_mask_hq,
@@ -43,6 +46,9 @@
43
  )
44
 
45
 
 
 
 
46
  @dataclass
47
  class ProcessorConfig:
48
  # Use a valid preset key from PROFESSIONAL_BACKGROUNDS (e.g., "office", "studio", …)
@@ -50,14 +56,149 @@ class ProcessorConfig:
50
  # None -> keep source fps (if available), else default to 25.0
51
  write_fps: Optional[float] = None
52
 
53
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  class CoreVideoProcessor:
55
  """
56
- Minimal, safe implementation used by app entrypoint.
57
- It relies on a models provider (e.g., ModelLoader) that implements:
58
  - get_sam2()
59
  - get_matanyone()
60
-
61
  Supports progress callback and cancellation via stop_event.
62
  """
63
 
@@ -103,10 +244,9 @@ def _prepare_background_from_config(
103
  self.log.warning("Unknown background preset '%s'; using 'office'.", choice)
104
  choice = "office"
105
 
106
- bg_rgb = create_professional_background(choice, width, height) # returns RGB
107
- return bg_rgb
108
 
109
- # ---------- Full video pipeline (first-frame seed + propagate) ----------
110
  def process_video(
111
  self,
112
  input_path: str,
@@ -119,12 +259,8 @@ def process_video(
119
  Process a full video with live progress and optional cancel.
120
  progress_callback(current_frame, total_frames, fps_live)
121
 
122
- Pipeline:
123
- - Read video (OpenCV)
124
- - Build background (once)
125
- - Frame 0: SAM2 segmentation → MatAnyOne refine (seed)
126
- - Frames 1..N: MatAnyOne propagate (no mask)
127
- - Composite each frame and write to MP4
128
  """
129
  # Validate input video
130
  ok = validate_video_file(input_path)
@@ -142,16 +278,11 @@ def process_video(
142
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
143
 
144
  fps_out = self.config.write_fps or (src_fps if src_fps and src_fps > 0 else 25.0)
145
- fourcc = cv2.VideoWriter_fourcc(*"mp4v")
146
- writer = cv2.VideoWriter(output_path, fourcc, float(fps_out), (width, height))
147
- if not writer.isOpened():
148
- cap.release()
149
- raise RuntimeError(f"Could not open writer for: {output_path}")
150
 
151
- # Build background (RGB)
152
  background_rgb = self._prepare_background_from_config(bg_config, width, height)
153
 
154
- # Models (allow fallbacks provided by app)
155
  predictor = None
156
  mat_core = None
157
  try:
@@ -165,14 +296,55 @@ def process_video(
165
  except Exception as e:
166
  self.log.warning("MatAnyOne core unavailable: %s", e)
167
 
168
- # Device (only used by helpers internally; we keep tensors on that device)
169
  device = "cuda" if torch.cuda.is_available() else "cpu"
170
- self.log.info("Starting processing on device=%s (size=%dx%d, fps_out=%.2f, frames=%s)",
171
  device, width, height, float(fps_out), total_frames or "unknown")
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  frame_count = 0
174
  start_time = time.time()
175
- refined_mask_prev: Optional[np.ndarray] = None
176
 
177
  try:
178
  # -------- First frame (seed) --------
@@ -182,33 +354,43 @@ def process_video(
182
 
183
  f0_rgb = cv2.cvtColor(f0_bgr, cv2.COLOR_BGR2RGB)
184
 
185
- # Segmentation (SAM2 preferred, else fallback)
186
- m0_hw = segment_person_hq(
187
  frame_rgb=f0_rgb,
188
  use_sam2=True,
189
  sam2_predictor=predictor
190
  )
191
- if m0_hw is None:
192
- # As an absolute last resort, use a solid foreground mask (keeps pipeline alive)
193
  self.log.warning("First-frame segmentation failed; using full-foreground mask.")
194
- m0_hw = np.ones((f0_rgb.shape[0], f0_rgb.shape[1]), dtype=np.float32)
195
 
196
- # Refine / seed MatAnyOne (first_frame=True makes the helper pass the mask)
197
- refined_mask_0 = refine_mask_hq(
198
- mask_hw_float01=m0_hw,
199
- frame_rgb=f0_rgb,
 
 
 
 
200
  use_matanyone=True,
201
  mat_core=mat_core,
202
  first_frame=True,
203
  device=device
204
  )
205
- refined_mask_prev = refined_mask_0
206
 
207
- # Composite & write
208
- comp0_rgb = replace_background_hq(f0_rgb, refined_mask_0, background_rgb)
209
- writer.write(cv2.cvtColor(comp0_rgb, cv2.COLOR_RGB2BGR))
210
- frame_count = 1
 
211
 
 
 
 
 
 
 
212
  if progress_callback:
213
  elapsed = time.time() - start_time
214
  fps_live = frame_count / elapsed if elapsed > 0 else 0.0
@@ -227,24 +409,31 @@ def process_video(
227
  if not ret:
228
  break
229
 
230
- frgb = cv2.cvtColor(fbgr, cv2.COLOR_BGR2RGB)
 
231
 
232
- # Propagate (first_frame=False -> mask ignored internally, MatAnyOne uses memory)
233
- refined_mask_t = refine_mask_hq(
234
- mask_hw_float01=refined_mask_prev if refined_mask_prev is not None else m0_hw,
235
- frame_rgb=frgb,
236
  use_matanyone=True,
237
  mat_core=mat_core,
238
  first_frame=False,
239
  device=device
240
  )
241
- refined_mask_prev = refined_mask_t
242
 
243
- comp_rgb = replace_background_hq(frgb, refined_mask_t, background_rgb)
244
- writer.write(cv2.cvtColor(comp_rgb, cv2.COLOR_RGB2BGR))
245
 
246
- frame_count += 1
 
 
 
 
 
247
 
 
248
  if progress_callback:
249
  elapsed = time.time() - start_time
250
  fps_live = frame_count / elapsed if elapsed > 0 else 0.0
@@ -255,7 +444,10 @@ def process_video(
255
 
256
  finally:
257
  cap.release()
258
- writer.release()
 
 
 
259
 
260
  self.log.info("Processed %d frames → %s", frame_count, output_path)
261
  return {
 
2
  """
3
  Compatibility shim: CoreVideoProcessor
4
 
5
+ Adds:
6
+ - Optional NVENC hardware encoding (fast, high quality) with ffmpeg.
7
+ - Optional model-only downscale (max_model_size) to speed up MatAnyOne WITHOUT reducing output resolution.
8
+
9
+ Pipeline:
10
+ frame 0: SAM2 segmentation → MatAnyOne refine (seed) → composite → write
11
+ frames 1..N: MatAnyOne propagate (no mask) composite → write
 
12
  """
13
 
14
  from __future__ import annotations
15
 
16
  from dataclasses import dataclass
17
+ from typing import Optional, Dict, Any, Callable, List
18
  import time
19
  import threading
20
+ import shutil
21
+ import subprocess
22
+ import os
23
+ import sys
24
 
25
  import cv2
26
  import numpy as np
27
  import torch
28
 
29
+ # Logger (fallback to std logging if project logger not available)
30
  try:
31
  from utils.logging_setup import make_logger
32
  _log = make_logger("processing.video.video_processor")
 
35
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
36
  _log = logging.getLogger(__name__)
37
 
38
+ # Hardened utils (device-safe, SAM2↔MatAnyOne interop)
39
  from utils import (
40
  segment_person_hq,
41
  refine_mask_hq,
 
46
  )
47
 
48
 
49
+ # -----------------------------
50
+ # Config
51
+ # -----------------------------
52
  @dataclass
53
  class ProcessorConfig:
54
  # Use a valid preset key from PROFESSIONAL_BACKGROUNDS (e.g., "office", "studio", …)
 
56
  # None -> keep source fps (if available), else default to 25.0
57
  write_fps: Optional[float] = None
58
 
59
+ # ▼ Performance knobs that DO NOT hurt final quality
60
+ # Downscale only for model inference when min(H,W) > max_model_size; composite at full-res
61
+ max_model_size: Optional[int] = None # e.g., 1280 or 1024; None = disabled
62
+
63
+ # NVENC hardware encoding (requires ffmpeg with nv-codec, e.g., on T4/L4/RTX)
64
+ use_nvenc: bool = True
65
+ nvenc_codec: str = "h264" # "h264" | "hevc"
66
+ nvenc_preset: str = "p5" # p1..p7; lower is faster, p5≈HQ
67
+ nvenc_cq: int = 19 # 14–24 typical; lower = higher quality
68
+ nvenc_tune_hq: bool = True # add -tune hq
69
+ # Set pix_fmt=yuv420p for compatibility
70
+ nvenc_pix_fmt: str = "yuv420p"
71
+
72
+
73
+ # -----------------------------
74
+ # ffmpeg NVENC writer (via pipe)
75
+ # -----------------------------
76
+ class _FFmpegNVENCWriter:
77
+ def __init__(self, path: str, width: int, height: int, fps: float,
78
+ codec: str = "h264", preset: str = "p5", cq: int = 19, tune_hq: bool = True,
79
+ pix_fmt: str = "yuv420p"):
80
+ self.path = path
81
+ self.width = int(width)
82
+ self.height = int(height)
83
+ self.fps = float(fps)
84
+ self.codec = codec
85
+ self.preset = preset
86
+ self.cq = int(cq)
87
+ self.tune_hq = bool(tune_hq)
88
+ self.pix_fmt = pix_fmt
89
+ self.proc: Optional[subprocess.Popen] = None
90
+
91
+ self._start()
92
+
93
+ @staticmethod
94
+ def _which_ffmpeg() -> Optional[str]:
95
+ return shutil.which("ffmpeg")
96
+
97
+ @staticmethod
98
+ def _encoder_name(codec: str) -> str:
99
+ return "h264_nvenc" if codec.lower() == "h264" else "hevc_nvenc"
100
+
101
+ @classmethod
102
+ def is_available(cls, codec: str) -> bool:
103
+ ffmpeg = cls._which_ffmpeg()
104
+ if not ffmpeg:
105
+ return False
106
+ # quick capability check: run a tiny encode to null
107
+ enc = cls._encoder_name(codec)
108
+ cmd = [
109
+ ffmpeg, "-hide_banner", "-loglevel", "error",
110
+ "-f", "lavfi", "-i", f"color=c=black:s=16x16:d=0.04:r=10",
111
+ "-c:v", enc, "-f", "null", "-"
112
+ ]
113
+ try:
114
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
115
+ return True
116
+ except Exception:
117
+ return False
118
+
119
+ def _start(self):
120
+ ffmpeg = self._which_ffmpeg()
121
+ if not ffmpeg:
122
+ raise RuntimeError("ffmpeg not found on PATH")
123
+
124
+ enc = self._encoder_name(self.codec)
125
+ cmd = [
126
+ ffmpeg, "-hide_banner", "-loglevel", "error",
127
+ "-f", "rawvideo",
128
+ "-pix_fmt", "rgb24",
129
+ "-s", f"{self.width}x{self.height}",
130
+ "-r", f"{self.fps:.06f}",
131
+ "-i", "-",
132
+ "-an",
133
+ "-c:v", enc,
134
+ "-preset", self.preset,
135
+ "-rc", "vbr_hq",
136
+ "-cq", str(self.cq),
137
+ "-b:v", "0",
138
+ "-pix_fmt", self.nvenc_pix_fmt if hasattr(self, "nvenc_pix_fmt") else "yuv420p",
139
+ ]
140
+ if self.tune_hq:
141
+ cmd += ["-tune", "hq"]
142
+ cmd += ["-y", self.path]
143
+
144
+ _log.info("Starting NVENC writer via ffmpeg: %s", " ".join(cmd))
145
+ self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
146
+
147
+ def write_rgb(self, frame_rgb: np.ndarray) -> None:
148
+ if self.proc is None or self.proc.stdin is None:
149
+ raise RuntimeError("NVENC writer is not started")
150
+ assert frame_rgb.dtype == np.uint8 and frame_rgb.ndim == 3 and frame_rgb.shape[2] == 3, \
151
+ "write_rgb expects HxWx3 uint8 RGB frame"
152
+ self.proc.stdin.write(frame_rgb.tobytes())
153
+
154
+ def is_opened(self) -> bool:
155
+ return self.proc is not None and self.proc.poll() is None
156
+
157
+ def release(self) -> None:
158
+ if self.proc is not None:
159
+ try:
160
+ if self.proc.stdin:
161
+ self.proc.stdin.flush()
162
+ self.proc.stdin.close()
163
+ finally:
164
+ self.proc.wait(timeout=10)
165
+ self.proc = None
166
+
167
+
168
+ # -----------------------------
169
+ # Helpers: scaling for model
170
+ # -----------------------------
171
+ def _model_scale(width: int, height: int, max_model_size: Optional[int]) -> float:
172
+ if not max_model_size:
173
+ return 1.0
174
+ m = min(width, height)
175
+ if m <= max_model_size:
176
+ return 1.0
177
+ return max_model_size / float(m)
178
+
179
+
180
+ def _resize_rgb(img_rgb: np.ndarray, scale: float, interp=cv2.INTER_AREA) -> np.ndarray:
181
+ if scale == 1.0:
182
+ return img_rgb
183
+ h, w = img_rgb.shape[:2]
184
+ new_w = max(1, int(round(w * scale)))
185
+ new_h = max(1, int(round(h * scale)))
186
+ return cv2.resize(img_rgb, (new_w, new_h), interpolation=interp)
187
+
188
+
189
+ def _resize_mask(mask_hw: np.ndarray, shape_hw: tuple[int, int], interp=cv2.INTER_CUBIC) -> np.ndarray:
190
+ H, W = shape_hw
191
+ return cv2.resize(mask_hw, (W, H), interpolation=interp)
192
+
193
+
194
+ # -----------------------------
195
+ # CoreVideoProcessor
196
+ # -----------------------------
197
  class CoreVideoProcessor:
198
  """
199
+ Uses a models provider (ModelLoader) with:
 
200
  - get_sam2()
201
  - get_matanyone()
 
202
  Supports progress callback and cancellation via stop_event.
203
  """
204
 
 
244
  self.log.warning("Unknown background preset '%s'; using 'office'.", choice)
245
  choice = "office"
246
 
247
+ return create_professional_background(choice, width, height) # RGB
 
248
 
249
+ # ---------- Full video pipeline ----------
250
  def process_video(
251
  self,
252
  input_path: str,
 
259
  Process a full video with live progress and optional cancel.
260
  progress_callback(current_frame, total_frames, fps_live)
261
 
262
+ We optionally downscale frames ONLY for model inference (not for output),
263
+ and optionally use NVENC to encode the final RGB frames.
 
 
 
 
264
  """
265
  # Validate input video
266
  ok = validate_video_file(input_path)
 
278
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
279
 
280
  fps_out = self.config.write_fps or (src_fps if src_fps and src_fps > 0 else 25.0)
 
 
 
 
 
281
 
282
+ # Background (RGB)
283
  background_rgb = self._prepare_background_from_config(bg_config, width, height)
284
 
285
+ # Models
286
  predictor = None
287
  mat_core = None
288
  try:
 
296
  except Exception as e:
297
  self.log.warning("MatAnyOne core unavailable: %s", e)
298
 
299
+ # Device
300
  device = "cuda" if torch.cuda.is_available() else "cpu"
301
+ self.log.info("Start processing on %s (%dx%d @ %.2ffps, frames=%s)",
302
  device, width, height, float(fps_out), total_frames or "unknown")
303
 
304
+ # Decide writer: NVENC or OpenCV
305
+ writer_rgb = None
306
+ nvenc_ok = False
307
+ if self.config.use_nvenc:
308
+ nvenc_ok = _FFmpegNVENCWriter.is_available(self.config.nvenc_codec)
309
+ if nvenc_ok:
310
+ try:
311
+ writer_rgb = _FFmpegNVENCWriter(
312
+ path=output_path,
313
+ width=width,
314
+ height=height,
315
+ fps=float(fps_out),
316
+ codec=self.config.nvenc_codec,
317
+ preset=self.config.nvenc_preset,
318
+ cq=self.config.nvenc_cq,
319
+ tune_hq=self.config.nvenc_tune_hq,
320
+ pix_fmt=self.config.nvenc_pix_fmt
321
+ )
322
+ self.log.info("Using NVENC (%s) via ffmpeg.", self.config.nvenc_codec)
323
+ except Exception as e:
324
+ self.log.warning("NVENC init failed (%s). Falling back to OpenCV writer.", e)
325
+ writer_rgb = None
326
+
327
+ if writer_rgb is None:
328
+ # Fallback to OpenCV VideoWriter (CPU encoding)
329
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
330
+ writer = cv2.VideoWriter(output_path, fourcc, float(fps_out), (width, height))
331
+ if not writer.isOpened():
332
+ cap.release()
333
+ raise RuntimeError(f"Could not open writer for: {output_path}")
334
+ self.log.info("Using OpenCV writer (mp4v).")
335
+ else:
336
+ writer = None # mutually exclusive
337
+
338
+ # Model-only scale
339
+ scale = _model_scale(width, height, self.config.max_model_size)
340
+ if scale != 1.0:
341
+ self.log.info("Model-only downscale enabled: scale=%.4f (max_model_size=%d)", scale, self.config.max_model_size or -1)
342
+ else:
343
+ self.log.info("Model-only downscale disabled (processing at full resolution for model).")
344
+
345
  frame_count = 0
346
  start_time = time.time()
347
+ refined_mask_prev_model: Optional[np.ndarray] = None # mask at model resolution
348
 
349
  try:
350
  # -------- First frame (seed) --------
 
354
 
355
  f0_rgb = cv2.cvtColor(f0_bgr, cv2.COLOR_BGR2RGB)
356
 
357
+ # Segmentation (SAM2 preferred, else fallback) at FULL resolution
358
+ m0_hw_full = segment_person_hq(
359
  frame_rgb=f0_rgb,
360
  use_sam2=True,
361
  sam2_predictor=predictor
362
  )
363
+ if m0_hw_full is None:
 
364
  self.log.warning("First-frame segmentation failed; using full-foreground mask.")
365
+ m0_hw_full = np.ones((f0_rgb.shape[0], f0_rgb.shape[1]), dtype=np.float32)
366
 
367
+ # Prepare model-resolution inputs (downscale if needed)
368
+ f0_rgb_model = _resize_rgb(f0_rgb, scale, interp=cv2.INTER_AREA)
369
+ m0_hw_model = _resize_mask(m0_hw_full, f0_rgb_model.shape[:2], interp=cv2.INTER_AREA)
370
+
371
+ # Refine / seed MatAnyOne at model resolution
372
+ refined_mask_model_0 = refine_mask_hq(
373
+ mask_hw_float01=m0_hw_model,
374
+ frame_rgb=f0_rgb_model,
375
  use_matanyone=True,
376
  mat_core=mat_core,
377
  first_frame=True,
378
  device=device
379
  )
380
+ refined_mask_prev_model = refined_mask_model_0
381
 
382
+ # Upscale matte to full resolution for compositing
383
+ refined_mask_full_0 = _resize_mask(refined_mask_model_0, f0_rgb.shape[:2], interp=cv2.INTER_CUBIC)
384
+
385
+ # Composite & write (RGB)
386
+ comp0_rgb = replace_background_hq(f0_rgb, refined_mask_full_0, background_rgb)
387
 
388
+ if writer_rgb is not None:
389
+ writer_rgb.write_rgb(comp0_rgb)
390
+ else:
391
+ writer.write(cv2.cvtColor(comp0_rgb, cv2.COLOR_RGB2BGR))
392
+
393
+ frame_count = 1
394
  if progress_callback:
395
  elapsed = time.time() - start_time
396
  fps_live = frame_count / elapsed if elapsed > 0 else 0.0
 
409
  if not ret:
410
  break
411
 
412
+ frgb_full = cv2.cvtColor(fbgr, cv2.COLOR_BGR2RGB)
413
+ frgb_model = _resize_rgb(frgb_full, scale, interp=cv2.INTER_AREA)
414
 
415
+ # Propagate at model resolution (first_frame=False internal memory used)
416
+ refined_mask_model_t = refine_mask_hq(
417
+ mask_hw_float01=refined_mask_prev_model if refined_mask_prev_model is not None else m0_hw_model,
418
+ frame_rgb=frgb_model,
419
  use_matanyone=True,
420
  mat_core=mat_core,
421
  first_frame=False,
422
  device=device
423
  )
424
+ refined_mask_prev_model = refined_mask_model_t
425
 
426
+ # Upscale matte to full-res for compositing
427
+ refined_mask_full_t = _resize_mask(refined_mask_model_t, frgb_full.shape[:2], interp=cv2.INTER_CUBIC)
428
 
429
+ comp_rgb = replace_background_hq(frgb_full, refined_mask_full_t, background_rgb)
430
+
431
+ if writer_rgb is not None:
432
+ writer_rgb.write_rgb(comp_rgb)
433
+ else:
434
+ writer.write(cv2.cvtColor(comp_rgb, cv2.COLOR_RGB2BGR))
435
 
436
+ frame_count += 1
437
  if progress_callback:
438
  elapsed = time.time() - start_time
439
  fps_live = frame_count / elapsed if elapsed > 0 else 0.0
 
444
 
445
  finally:
446
  cap.release()
447
+ if writer_rgb is not None:
448
+ writer_rgb.release()
449
+ else:
450
+ writer.release()
451
 
452
  self.log.info("Processed %d frames → %s", frame_count, output_path)
453
  return {