File size: 5,715 Bytes
4b3a024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Video loading utilities for efficient video processing.
"""

import os
import torch
import numpy as np
from decord import VideoReader


def load_video_rgb_fchw(video_path: str, wh: tuple[int, int], 
                       start: int | None = None, count: int | None = None, 
                       accurate_seek: bool = False, read_full: bool = False):
    """Load video frames as RGB tensor [F,C,H,W] in [-1,1] range.
    
    Args:
        video_path: Path to video file
        wh: Target (width, height) for resizing
        start: Starting frame index
        count: Number of frames to read
        accurate_seek: Whether to use accurate seeking (unused with decord)
        read_full: Whether to read full video first then slice
        
    Returns:
        torch.Tensor: Video frames [F,C,H,W] in [-1,1] range, or None if failed
    """
    W, H = wh
    
    try:
        # Create VideoReader
        vr = VideoReader(video_path)
        total_frames = len(vr)
        
        if total_frames == 0:
            return None
        
        # Determine frame indices to read
        if read_full:
            frame_indices = list(range(total_frames))
        elif start is not None and count is not None:
            start_idx = max(0, min(start, total_frames - 1))
            end_idx = min(start_idx + count, total_frames)
            frame_indices = list(range(start_idx, end_idx))
        elif start is not None:
            start_idx = max(0, min(start, total_frames - 1))
            frame_indices = list(range(start_idx, total_frames))
        elif count is not None:
            frame_indices = list(range(min(count, total_frames)))
        else:
            frame_indices = list(range(total_frames))
        
        if not frame_indices:
            return None
        
        # Batch read frames - much more efficient
        frames_np = vr.get_batch(frame_indices).asnumpy()  # [F,H,W,C] in RGB
        
        if frames_np.size == 0:
            return None
        
        # Resize frames if needed
        if (frames_np.shape[2] != W) or (frames_np.shape[1] != H):
            import cv2
            resized_frames = []
            for frame in frames_np:
                resized_frame = cv2.resize(frame, (W, H), interpolation=cv2.INTER_AREA)
                resized_frames.append(resized_frame)
            frames_np = np.stack(resized_frames, axis=0)
        
        # Convert to torch tensor [F,C,H,W] in [-1,1] range for WAN VAE
        frames_tensor = torch.from_numpy(frames_np).permute(0,3,1,2).float()
        frames_tensor = (frames_tensor / 255.0) * 2.0 - 1.0  # [0,1] -> [-1,1]
        return frames_tensor
        
    except Exception as e:
        print(f"⚠️ Failed to load video {video_path}: {e}")
        return None


def infer_video_path_from_cache(pt_file_path: str, video_root: str | None = None):
    """Infer original video path from cache .pt filename.
    
    Args:
        pt_file_path: Path to .pt cache file
        video_root: Root directory for original videos
        
    Returns:
        str | None: Inferred video path or None if not found
    """
    base_name = os.path.basename(pt_file_path)
    video_name = base_name.replace('.pt', '.mp4')
    
    if video_root:
        candidate = os.path.join(video_root, video_name)
        return candidate if os.path.exists(candidate) else None
    
    # Try alongside cache directory as fallback
    pt_dir = os.path.dirname(pt_file_path)
    candidate = os.path.join(pt_dir, video_name)
    return candidate if os.path.exists(candidate) else None


def choose_window_start(F_lm: int, F_vid: int | None, N: int | None, 
                       valid_mask: torch.Tensor | None, strict: bool = True, 
                       max_invalid: int = 0):
    """Choose optimal window start index for aligned landmark and video data.
    
    Args:
        F_lm: Number of landmark frames
        F_vid: Number of video frames (optional)
        N: Desired window length (optional)
        valid_mask: Boolean mask for valid landmark frames
        strict: Whether to require all frames in window to be valid
        max_invalid: Maximum number of invalid frames allowed in non-strict mode
        
    Returns:
        int: Start index for the window
    """
    if F_lm is None or F_lm <= 0:
        return 0
    
    if valid_mask is None or valid_mask.numel() != F_lm:
        # No mask; choose based on lengths only
        if N is None:
            return 0
        if F_vid is not None:
            max_start = min(F_lm, F_vid) - N
        else:
            max_start = F_lm - N
        if max_start < 0:
            return 0
        return int(torch.randint(0, max_start + 1, (1,)).item())
    
    # Helper to test window validity
    def window_ok(s, n):
        if s < 0 or s + n > F_lm:
            return False
        if strict:
            return bool(valid_mask[s:s+n].all().item())
        else:
            invalid = (~valid_mask[s:s+n]).sum().item()
            return invalid <= max_invalid
    
    if N is None:
        # Choose first valid frame as start
        for s in range(F_lm):
            if valid_mask[s]:
                return s
        return 0
    
    # Candidate range by lengths
    if F_vid is not None:
        max_start = min(F_lm, F_vid) - N
    else:
        max_start = F_lm - N
    if max_start < 0:
        return 0
    
    # Collect all valid starts; random pick for diversity
    valids = [s for s in range(0, max_start + 1) if window_ok(s, N)]
    if valids:
        ridx = int(torch.randint(0, len(valids), (1,)).item())
        return valids[ridx]
    
    # Fallback: pick any start in range
    return int(torch.randint(0, max_start + 1, (1,)).item())