"""与 MEMO FrameExtractor 采样完全一致的流式解码器(含负 PTS edit-list 视频安全回退)。 MEMO 的 `FrameExtractor.extract` 会把 1 fps 的全部帧一次性放进内存(1 小时视频约 20GB), 多卡并行时会逼近内存上限。这里用同一套 `calculate_video_frame_range` + `build_sample_indices` 计算绝对帧号,按时序逐批解码、逐帧 yield,时间戳仍为 `native_index / native_fps`。 当遇到 FFmpeg `-c copy` 裁剪产生的负起始 PTS(`elst` 预卷包导致 `decord.get_batch` 死循环)时, 自动切换至 `cv2.VideoCapture` 顺序解码有效正时间轴帧,彻底杜绝解码卡死。 """ from typing import Iterator, Optional import numpy as np def has_elst_negative_pts(vr) -> bool: """检测视频首帧是否存在明显负向 PTS(FFmpeg edit-list 裁剪流特征,会导致 decord 随机/批量 seek 死循环)。""" try: if len(vr) <= 0: return False ts0 = vr.get_frame_timestamp(0) start_pts = float(ts0[0]) if hasattr(ts0, '__len__') else float(ts0) return start_pts < -0.1 except Exception: return False def decode_all_rgb_cv2(video_path: str) -> tuple[float, list[np.ndarray]]: """使用 OpenCV 顺序读取经过容器 edit-list 过滤后的真实显示帧序列(RGB uint8)。""" import cv2 cap = cv2.VideoCapture(str(video_path)) if not cap.isOpened(): cap.release() raise RuntimeError(f'cv2 无法打开视频文件: {video_path}') fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) if fps <= 0.0 or fps > 240.0 or np.isnan(fps): fps = 24.0 frames = [] try: while True: ok, bgr = cap.read() if not ok or bgr is None: break rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) if rgb.dtype != np.uint8: rgb = np.clip(rgb, 0, 255).astype(np.uint8) frames.append(rgb) finally: cap.release() return fps, frames def iter_frames(video_path: str, target_fps: float = 1.0, max_time: Optional[float] = None, chunk_size: int = 64, stats: Optional[dict] = None) -> Iterator[tuple]: import time import decord from decord import VideoReader, cpu from memo.stage1.sampling import build_sample_indices, calculate_video_frame_range decord.bridge.set_bridge('torch') t_open = time.perf_counter() vr = VideoReader(video_path, ctx=cpu(0), num_threads=0) use_cv2_fallback = has_elst_negative_pts(vr) if use_cv2_fallback: del vr t0 = time.perf_counter() native_fps, cv_frames = decode_all_rgb_cv2(video_path) if stats is not None: stats['decode_seconds'] = stats.get('decode_seconds', 0.0) + (time.perf_counter() - t0) total_frames = len(cv_frames) if total_frames <= 0: return start_frame, end_frame, _ = calculate_video_frame_range( total_frames=total_frames, video_fps=native_fps, video_start=0.0, video_end=None) seg_total = end_frame - start_frame + 1 seg_idx = build_sample_indices(total_frames=seg_total, video_fps=native_fps, target_fps=target_fps, max_frames=None, anchor_end=False) if not seg_idx and total_frames > 0: seg_idx = [0] idx_abs = [start_frame + i for i in seg_idx] yielded = 0 for offset, native in enumerate(idx_abs): native = int(min(max(0, native), total_frames - 1)) ts = float(native) / float(native_fps) if max_time is not None and ts > max_time + 1e-6: if yielded == 0 and offset == 0: ts = float(max_time) else: return yielded += 1 yield ts, native, cv_frames[native] return try: native_fps = float(vr.get_avg_fps()) total_frames = len(vr) start_frame, end_frame, _ = calculate_video_frame_range( total_frames=total_frames, video_fps=native_fps, video_start=0.0, video_end=None) seg_total = end_frame - start_frame + 1 seg_idx = build_sample_indices(total_frames=seg_total, video_fps=native_fps, target_fps=target_fps, max_frames=None, anchor_end=False) # 对超短视频(如 <1s 片段),若 1 fps 未抽到任何帧但原视频本身有帧,兜底抽取首帧(index=0),防止 seen==0 异常丢题 if not seg_idx and total_frames > 0: seg_idx = [0] idx_abs = [start_frame + i for i in seg_idx] yielded = 0 for chunk_start in range(0, len(idx_abs), chunk_size): chunk = idx_abs[chunk_start: chunk_start + chunk_size] t0 = time.perf_counter() batch = vr.get_batch(chunk) batch_np = batch.asnumpy() if hasattr(batch, 'asnumpy') else batch.cpu().numpy() if stats is not None: stats['decode_seconds'] = stats.get('decode_seconds', 0.0) + (time.perf_counter() - t0) for offset, image in enumerate(batch_np): native = int(chunk[offset]) ts = float(native) / float(native_fps) if max_time is not None and ts > max_time + 1e-6: if yielded == 0 and offset == 0: ts = float(max_time) else: return if image.dtype != np.uint8: image = np.clip(image, 0, 255).astype(np.uint8) yielded += 1 yield ts, native, image finally: del vr