Create tools/video_encode_tool.py
Browse files- tools/video_encode_tool.py +41 -0
tools/video_encode_tool.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# video_encode_tool.py — versão simples (beta 1.0)
|
| 2 |
+
# Responsável por salvar um tensor 5D de pixels (B,C,T,H,W) em MP4, incrementalmente.
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import imageio
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
class _SimpleVideoEncoder:
|
| 9 |
+
def __init__(self, frame_log_every=8):
|
| 10 |
+
self.frame_log_every = frame_log_every
|
| 11 |
+
|
| 12 |
+
@torch.no_grad()
|
| 13 |
+
def save_video_from_tensor(self, pixel_5d: torch.Tensor, path: str, fps: int = 24, progress_callback=None):
|
| 14 |
+
"""
|
| 15 |
+
Espera pixel_5d em [0,1], shape (B,C,T,H,W).
|
| 16 |
+
Escreve MP4 incremental, convertendo cada frame para (H,W,C) uint8.
|
| 17 |
+
"""
|
| 18 |
+
# Move para CPU apenas para formar os frames HWC uint8 com baixo overhead
|
| 19 |
+
device = "cuda" if pixel_5d.is_cuda else "cpu"
|
| 20 |
+
B, C, T, H, W = pixel_5d.shape
|
| 21 |
+
if B != 1:
|
| 22 |
+
# Mantemos simples: um vídeo por chamada (B=1)
|
| 23 |
+
raise ValueError(f"Esperado B=1, recebido B={B}")
|
| 24 |
+
|
| 25 |
+
with imageio.get_writer(path, fps=int(fps), codec="libx264", quality=8) as writer:
|
| 26 |
+
for i in range(T):
|
| 27 |
+
frame_chw = pixel_5d[0, :, i] # (C,H,W)
|
| 28 |
+
frame_hwc_u8 = (frame_chw.permute(1, 2, 0)
|
| 29 |
+
.clamp(0, 1)
|
| 30 |
+
.mul(255)
|
| 31 |
+
.to(torch.uint8)
|
| 32 |
+
.cpu()
|
| 33 |
+
.numpy())
|
| 34 |
+
writer.append_data(frame_hwc_u8)
|
| 35 |
+
if progress_callback:
|
| 36 |
+
progress_callback(i + 1, T)
|
| 37 |
+
if i % self.frame_log_every == 0:
|
| 38 |
+
print(f"[DEBUG] [Encoder] frame {i}/{T} gravado ({H}x{W}@{fps}fps)")
|
| 39 |
+
|
| 40 |
+
# Singleton global de uso simples
|
| 41 |
+
video_encode_tool_singleton = _SimpleVideoEncoder()
|