Skip to content

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

Python
7.6 KB
Raw Blame
"""Video probing, frame extraction and re-encoding (ffmpeg / PyAV / TurboJPEG)."""

import collections
import functools
import math
import re
import shutil
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import av
import cv2
import imageio.v3 as iio
from exmr.preprocessing.image_io import read_bgr_frame
from turbojpeg import TJPF_RGB, TurboJPEG


def _run_ffmpeg(args):
    cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y", "-loglevel", "error", *map(str, args)]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"ffmpeg failed: {' '.join(cmd)}\n{result.stderr}")


def extract_frames(video_path, output_dir, quality=2):
    """Write every frame to output_dir/%06d.jpg (from 000000.jpg); returns the frame count.

    quality: ffmpeg's -q:v for MJPEG, 2 (near-lossless) .. 31; lower is better.
    """
    output_dir = Path(output_dir)
    if output_dir.exists():
        shutil.rmtree(output_dir)  # so that the returned count is exact
    output_dir.mkdir(parents=True)
    # -fps_mode passthrough: pass frames through as decoded (no duplication/dropping); same as
    # the older -vsync 0, which ffmpeg deprecated in 5.1 and newer versions reject
    _run_ffmpeg(
        ["-i", video_path, "-fps_mode", "passthrough", "-q:v", quality, "-start_number", 0,
         output_dir / "%06d.jpg"]
    )  # fmt: skip
    return len(frame_paths(output_dir))


def frame_paths(frame_dir):
    """The extracted frames' files frame_dir/%06d.jpg, in order."""
    return sorted(p for p in Path(frame_dir).glob("*.jpg") if re.fullmatch(r"\d{6}", p.stem))


def read_frames(paths, threads=8):
    """Yields the (H, W, 3) BGR uint8 images of the JPEG files paths, in order, decoded by a pool
    of threads (OpenCV releases the GIL) at most 2 * threads frames ahead. One thread decodes
    1080p JPEGs at ~200 frames/s, a fifth of OpenCV's video decoding; 8 decode them as fast, 4K
    ones twice as fast."""
    with ThreadPoolExecutor(threads) as pool:
        pending = collections.deque()
        for path in paths:
            pending.append(pool.submit(_imread, path))
            if len(pending) > 2 * threads:
                yield pending.popleft().result()
        while pending:
            yield pending.popleft().result()


def _imread(path):
    img = read_bgr_frame(path)
    if img is None:
        raise RuntimeError(f"Could not read {path}")
    return img


def frame_size(frame_dir):
    """(width, height) of the extracted frames."""
    img = read_bgr_frame(Path(frame_dir) / "000000.jpg")
    if img is None:
        raise RuntimeError(f"Could not read the first frame in {frame_dir}")
    h, w = img.shape[:2]
    return w, h


def video_lwh(video_path):
    """(num_frames, width, height) from the container (PyAV via imageio)."""
    L, H, W, _ = iio.improps(video_path, plugin="pyav").shape
    return L, W, H


def video_fps(video_path):
    """Average frame rate (frames / duration); robust to VFR and missing rate metadata."""
    with av.open(str(video_path)) as c:
        s = c.streams.video[0]
        # libav's average_rate is frames / duration
        if s.average_rate and s.average_rate > 0:
            return float(s.average_rate)

        # fallback: demux (no decoding) to count frames and measure the timestamp span; pts can
        # be out of order (B-frames), so use min/max
        n, pts = 0, []
        for pkt in c.demux(s):
            if pkt.size == 0:  # flush packet
                continue
            n += 1
            if pkt.pts is not None:
                pts.append(pkt.pts)
        if n == 0:
            raise ValueError(f"no video frames in {video_path}")
        if len(pts) >= 2:
            span = (max(pts) - min(pts)) * float(s.time_base)
            if span > 0:
                return (n - 1) / span
        return float(s.base_rate or s.guessed_rate or 0.0)


@functools.lru_cache(maxsize=1)
def _turbojpeg():
    return TurboJPEG()


def read_frame(path):
    """JPEG file -> (H, W, 3) RGB uint8 (TurboJPEG; same pixels as cv2.imread + cvtColor)."""
    with open(path, "rb") as f:
        return _turbojpeg().decode(f.read(), pixel_format=TJPF_RGB)


@functools.lru_cache(maxsize=1)
def nvenc_available():
    """Whether ffmpeg can encode H.264 on the GPU (NVENC); checked with a tiny trial encode,
    since a compiled-in encoder can still fail at runtime (no GPU, old driver)."""
    listed = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True)
    if "h264_nvenc" not in listed.stdout:
        return False
    trial = subprocess.run(
        ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi",
         "-i", "color=c=black:s=256x256:d=0.1", "-c:v", "h264_nvenc", "-preset", "p4",
         "-f", "null", "-"],
        capture_output=True,
    )  # fmt: skip
    return trial.returncode == 0


def h264_args(crf):
    """ffmpeg output codec args: GPU NVENC if available, else CPU libx264, yuv420p.

    NVENC's constant-quality scale runs ~5 points "cheaper" than x264's CRF for the same file
    size, hence the offset.
    """
    if nvenc_available():
        codec = ["-c:v", "h264_nvenc", "-preset", "p4", "-cq", crf + 5]
    else:
        codec = ["-c:v", "libx264", "-preset", "veryfast", "-crf", crf]
    return [*codec, "-pix_fmt", "yuv420p"]


def resample_fps(in_path, out_path, fps=30, crf=17):
    """Re-encode a video to a constant frame rate (drops/duplicates frames)."""
    _run_ffmpeg(["-i", in_path, "-vf", f"fps={fps}", "-an", *h264_args(crf), out_path])
    return out_path


def cut(in_path, out_path, start=None, end=None, fps=None, crf=17):
    """The frames of a video with timestamps in [start, end) (seconds; None: from its beginning /
    to its end), encoded losslessly: they are exactly the input's frames. With fps, resampled to
    that frame rate instead (re-encoded as in resample_fps)."""
    # -ss before -i: seek in the input, frame-accurate (decoded frames before start are dropped);
    # the frames' timestamps then count from start. The end is a trim filter (keeps timestamps
    # < end, then ends the stream): -t / -to would count from the first frame after start instead
    # (one frame too many if start falls between frames). In videos whose time base is the frame
    # interval (e.g. 1/25 s), a start between two frames is rounded, which can shift the end by a
    # frame
    filters = [f"trim=end={end - (start or 0):.6f}"] if end is not None else []
    if fps is None:
        codec = ["-fps_mode", "passthrough", "-c:v", "libx264", "-preset", "ultrafast", "-qp", 0]
    else:
        filters.append(f"fps={fps}")
        codec = h264_args(crf)
    _run_ffmpeg(
        ["-ss", f"{start or 0:.6f}", "-i", in_path, "-an",
         *(["-vf", ",".join(filters)] if filters else []), *codec, out_path]
    )  # fmt: skip
    with av.open(str(out_path)) as c:
        if not c.streams.video or not c.streams.video[0].frames:
            raise ValueError(f"no frames between start={start} and end={end} (seconds)")
    return out_path


def parse_time(text):
    """Seconds from a time "83.5", "1:23.5" or "0:01:23.5" ([[hh:]mm:]ss)."""
    error = ValueError(f"not a time: {text!r} (use seconds or [hh:]mm:ss)")
    parts = text.strip().split(":")
    if not 1 <= len(parts) <= 3:
        raise error
    seconds = 0.0
    for i, part in enumerate(parts):
        try:
            value = float(part)
        except ValueError:
            raise error from None
        # minutes and seconds after a colon are below 60
        if not math.isfinite(value) or value < 0 or (i > 0 and value >= 60):
            raise error
        seconds = seconds * 60 + value
    return seconds