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
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
"""Codec (compressed-video) preprocessing backend for LlavaOnevision2_5.

This module supplies the six symbols that
``processing_llava_onevision2_5.LlavaOnevision2_5Processor.__call__`` imports when
it is called with ``video_backend="codec"``:

    CodecConfig
    process_codec_video
    drop_padding_canvases
    codec_positions_for_processor
    rewrite_text_with_codec_positions
    codec_image_processor_outputs

Unlike the frame-sampling backend, the codec backend turns a video into a small
set of *canvases*. A canvas is a mosaic: its patches are taken from several
different source frames, chosen by bitcost energy. Each patch therefore carries
its own ``(t, h, w)`` source position, and the model consumes those positions
through ``forward(..., patch_positions=...)`` to build 3-D RoPE. Feeding the
canvases as if they were ordinary video frames would discard the temporal
information entirely.

Requires the ``codec-video-prep`` package (>= 0.3.0) for the native decoding and
canvas construction; it is imported lazily so that importing this module never
fails on installations that only use the frame-sampling path.
"""

from __future__ import annotations

import hashlib
import json
import os
import shutil
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
import torch
from PIL import Image

VISION_START = "<|vision_start|>"
VISION_END = "<|vision_end|>"
IMAGE_PAD = "<|image_pad|>"

# This checkpoint's vision tower: patch 16, 3x3 spatial merge.
DEFAULT_PATCH_SIZE = 16
DEFAULT_SPATIAL_MERGE_SIZE = 3

try:  # optional: only needed for POSIX advisory locking of the cache
    import fcntl
except ImportError:  # pragma: no cover - non-POSIX
    fcntl = None  # type: ignore[assignment]


# The canvas timestamp format lives in its own module, copied verbatim from the
# training encoder so inference and training cannot drift apart. Keep this
# import at module level: when the repo is loaded as remote code, transformers
# scans the source for relative imports and copies those siblings into its
# module cache, and an import hidden inside a function is not copied.
try:
    from .canvas_timestamp_schema import (
        SCHEMA as CANVAS_TIMESTAMP_SCHEMA,
        rewrite_existing_canvas_wrappers,
        summarize_canvases,
    )
except ImportError:  # plain directory on sys.path, not loaded as remote code
    from canvas_timestamp_schema import (  # type: ignore[no-redef]
        SCHEMA as CANVAS_TIMESTAMP_SCHEMA,
        rewrite_existing_canvas_wrappers,
        summarize_canvases,
    )


# =============================================================================
# CodecConfig
# =============================================================================

@dataclass
class CodecConfig:
    """Codec preprocessing settings.

    Defaults reproduce the released inference recipe: 512 candidate frames,
    64 canvases, patch 16, 3x3 blocks, 313600-pixel canvas budget.

    ``max_pixels`` is overwritten by the processor from its own pixel knob so
    the canvas budget and the image-processor budget cannot drift apart.

    ``options`` passes advanced ``BitcostReadinessConfig`` fields straight to
    ``codec_video_prep.prepare_video``; unknown names raise there, by design.
    """

    strategy: str = "adaptive_pwindow"
    target_canvas: int = 64
    num_sampled_frames: int = 512
    patch: int = DEFAULT_PATCH_SIZE
    block_size: int = 3
    max_pixels: int = 313600
    canvas_format: str = "png"
    cache_root: Optional[str] = None
    options: Dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        if int(self.target_canvas) <= 0:
            raise ValueError("target_canvas must be > 0")
        if int(self.num_sampled_frames) <= 0:
            raise ValueError("num_sampled_frames must be > 0")
        if int(self.patch) <= 0:
            raise ValueError("patch must be > 0")
        if int(self.max_pixels) <= 0:
            raise ValueError("max_pixels must be > 0")
        if self.canvas_format not in ("png", "jpg", "npy"):
            raise ValueError(
                f"canvas_format must be one of png/jpg/npy, got {self.canvas_format!r}"
            )

    def resolved_cache_root(self) -> Path:
        if self.cache_root:
            return Path(self.cache_root)
        env = os.environ.get("CVP_CODEC_CACHE_ROOT")
        if env:
            return Path(env)
        return Path.home() / ".cache" / "codec_video_prep" / "canvases"

    def cache_key(self, video: str) -> str:
        payload = dict(asdict(self))
        payload.pop("cache_root", None)
        payload["video"] = str(video)
        try:
            payload["mtime"] = os.path.getmtime(video)
            payload["size"] = os.path.getsize(video)
        except OSError:
            pass
        raw = json.dumps(payload, sort_keys=True, default=str)
        return hashlib.md5(raw.encode()).hexdigest()


# =============================================================================
# process_codec_video
# =============================================================================

def _require_codec_video_prep():
    try:
        import codec_video_prep  # noqa: F401
    except ImportError as exc:  # pragma: no cover
        raise ImportError(
            "video_backend='codec' needs the `codec-video-prep` package (>=0.3.0), "
            "which provides the patched FFmpeg/dav1d bitcost decoder. Install the "
            "release wheel for your Python ABI, then re-run. "
            "Use video_backend='frames' for plain frame sampling."
        ) from exc
    import codec_video_prep as cvp

    if not hasattr(cvp, "prepare_video"):
        raise ImportError(
            "The installed codec-video-prep is too old: it has no `prepare_video` "
            "(needs >= 0.3.0). Upgrade to the released wheel."
        )
    return cvp


def process_codec_video(video: str, cfg: CodecConfig) -> Dict[str, Any]:
    """Run codec preprocessing for one video and return its canvases.

    Returns a dict with ``images`` (list of RGB ``PIL.Image``), ``src_positions``
    (``int`` array ``[total_patches, 3]`` of ``(src_frame, patch_row, patch_col)``),
    ``fps``, ``out_dir`` and ``meta``.

    Results are cached per (video, config) under ``cfg.resolved_cache_root()``
    so repeated evaluation of the same video does not re-decode it.
    """
    cvp = _require_codec_video_prep()

    video = str(video)
    if not os.path.exists(video):
        raise FileNotFoundError(f"codec backend: video not found: {video}")

    root = cfg.resolved_cache_root()
    out_dir = root / f"{Path(video).stem}_{cfg.cache_key(video)}"
    done_marker = out_dir / "src_patch_position.npy"

    if done_marker.exists():
        return _load_codec_dir(cvp, out_dir)

    root.mkdir(parents=True, exist_ok=True)
    lock_path = root / f".{out_dir.name}.lock"
    lock_fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o644)
    try:
        if fcntl is not None:
            fcntl.flock(lock_fd, fcntl.LOCK_EX)
        # Another process may have finished while we waited for the lock.
        if done_marker.exists():
            return _load_codec_dir(cvp, out_dir)
        # prepare_video requires a non-existent or empty out_dir; a partial
        # directory from an earlier failure must go.
        if out_dir.exists():
            shutil.rmtree(out_dir)
        cvp.prepare_video(
            video=video,
            out_dir=str(out_dir),
            strategy=cfg.strategy,
            target_canvas=int(cfg.target_canvas),
            num_sampled_frames=int(cfg.num_sampled_frames),
            patch=int(cfg.patch),
            block_size=int(cfg.block_size),
            max_pixels=int(cfg.max_pixels),
            canvas_format=cfg.canvas_format,
            **dict(cfg.options),
        )
        return _load_codec_dir(cvp, out_dir)
    finally:
        try:
            if fcntl is not None:
                fcntl.flock(lock_fd, fcntl.LOCK_UN)
        finally:
            os.close(lock_fd)


def _load_codec_dir(cvp, out_dir: Path) -> Dict[str, Any]:
    result = cvp.load_inference_result(str(out_dir))
    return {
        "images": list(result.images),
        "src_positions": np.asarray(result.src_positions),
        "fps": float(result.fps),
        "out_dir": str(out_dir),
        "meta": getattr(result, "meta", {}),
    }


# =============================================================================
# drop_padding_canvases
# =============================================================================

def drop_padding_canvases(
    images: List[Image.Image],
    src_positions: np.ndarray,
) -> Tuple[List[Image.Image], np.ndarray, int]:
    """Remove canvases that hold no real patches, and fill stray invalid slots.

    Short videos (or strategies whose budget exceeds the available content) can
    emit canvases whose source positions are all ``-1``. Those carry no signal,
    so they are dropped rather than padded into the prompt. Within a kept
    canvas, any remaining invalid slot inherits the first valid position so the
    position array stays dense and aligned with the patch grid.

    Returns ``(images, src_positions, num_dropped)``.
    """
    src_positions = np.asarray(src_positions)
    n_canvas = len(images)
    if n_canvas == 0:
        return images, src_positions, 0

    total_patches = int(src_positions.shape[0])
    if total_patches % n_canvas != 0:
        raise ValueError(
            f"src_positions length {total_patches} is not divisible by the canvas "
            f"count {n_canvas}; the preprocessing output is inconsistent."
        )
    ppc = total_patches // n_canvas
    positions = src_positions.reshape(n_canvas, ppc, 3).copy()

    keep_mask = (positions[..., 0] >= 0).any(axis=1)
    dropped = int(n_canvas - int(keep_mask.sum()))
    if dropped:
        images = [im for im, keep in zip(images, keep_mask.tolist()) if keep]
        positions = positions[keep_mask]

    for canvas_pos in positions:
        valid = canvas_pos[:, 0] >= 0
        if bool(valid.all()):
            continue
        canvas_pos[~valid] = canvas_pos[valid][0]

    return images, positions.reshape(-1, 3), dropped


# =============================================================================
# patch-position layout
# =============================================================================

def convert_positions_to_block_layout(
    positions: torch.Tensor,
    t: int,
    h: int,
    w: int,
    spatial_merge_size: int = DEFAULT_SPATIAL_MERGE_SIZE,
) -> torch.Tensor:
    """Reorder row-major ``[t*h*w, 3]`` positions into the merger's block layout.

    The patch merger consumes patches in ``spatial_merge_size`` x
    ``spatial_merge_size`` blocks, so the positions must be permuted the same
    way the image processor permutes the pixel rows.
    """
    sms = int(spatial_merge_size)
    if sms == 1:
        return positions
    if h % sms or w % sms:
        raise ValueError(
            f"canvas patch grid {h}x{w} is not divisible by spatial_merge_size={sms}. "
            "Set the codec `block_size` equal to the vision tower's spatial_merge_size "
            "so every canvas grid aligns with the merger."
        )
    total = int(t) * int(h) * int(w)
    indices = torch.arange(total, device=positions.device).view(t, h, w)
    indices = (
        indices.view(t, h // sms, sms, w // sms, sms)
        .permute(0, 1, 3, 2, 4)
        .contiguous()
        .view(total)
    )
    return positions[indices]


def codec_positions_for_processor(
    src_positions: np.ndarray,
    image_grid_thw: torch.Tensor,
    device: Any = None,
    spatial_merge_size: int = DEFAULT_SPATIAL_MERGE_SIZE,
) -> torch.Tensor:
    """Turn codec source positions into block-layout ``patch_positions``.

    ``image_grid_thw`` has one row per canvas; the positions are split to match
    and each chunk is permuted into block layout. A length mismatch is an error
    rather than something to truncate: it means the canvas geometry and the
    position array disagree, and silently trimming would misalign every patch.
    """
    if device is None:
        device = getattr(image_grid_thw, "device", "cpu")
    positions = torch.as_tensor(np.asarray(src_positions)).long().to(device)

    chunks: List[torch.Tensor] = []
    offset = 0
    for row in image_grid_thw:
        t, h, w = (int(row[0]), int(row[1]), int(row[2]))
        n = t * h * w
        chunk = positions[offset : offset + n]
        if chunk.shape[0] != n:
            raise ValueError(
                f"codec patch positions exhausted: canvas grid needs {n} rows but only "
                f"{chunk.shape[0]} remain (total available {positions.shape[0]})."
            )
        chunks.append(
            convert_positions_to_block_layout(chunk, t, h, w, spatial_merge_size)
        )
        offset += n

    if offset != int(positions.shape[0]):
        raise ValueError(
            "codec patch position length mismatch: image_grid_thw consumes "
            f"{offset} positions but {positions.shape[0]} were produced. Check that "
            "the image processor did not rescale the canvases."
        )
    return torch.cat(chunks, dim=0)


# =============================================================================
# text rewriting
# =============================================================================

# The per-source-frame "timestamp runs" serializer that used to live here is
# gone on purpose. It split one canvas into one block per contributing source
# frame, which is not the protocol: a P-window canvas carries patches from many
# frames and takes a single time range, not one point timestamp per frame.
# Formatting now comes from canvas_timestamp_schema, the training module.


def rewrite_text_with_codec_positions(
    text: str,
    patch_positions: torch.Tensor,
    fps: float,
    decimals: int = 1,
    spatial_merge_size: int = DEFAULT_SPATIAL_MERGE_SIZE,
    image_grid_thw: Any = None,
) -> str:
    """Give every canvas one timestamp: a point if it holds a single source
    frame, a time range if its patches span several.

    This is the training-side schema ``canvas_patch_span_point_range_v1``. The
    formatting is not reimplemented here: ``canvas_timestamp_schema`` is a
    verbatim copy of the module the training encoder uses, so inference and
    training cannot drift apart.

    One canvas is one image: the vision tower runs over it once, and its patches
    may come from many source frames. Splitting that canvas into one block per
    source frame — the behaviour this function used to have — tells the language
    model that several separate images start and end inside what was a single
    image, and inflates the vision region several-fold. The canvas keeps one
    wrapper and gets one marker in front of it.
    """
    if image_grid_thw is None:
        raise ValueError(
            "canvas timestamps need image_grid_thw to know where each canvas ends; "
            "pass the grid returned by the image processor."
        )

    summaries = summarize_canvases(
        patch_positions,
        image_grid_thw,
        fps=fps,
        spatial_merge_size=spatial_merge_size,
    )

    # The chat template emits one <|vision_start|><|video_pad|><|vision_end|>
    # span for the whole video. Expand it into one wrapper per canvas, then let
    # the authoritative module prefix each wrapper with its own marker.
    # Separator between canvas wrappers. Training's mm_plugin emits a newline
    # between blocks; the frozen eval adapter joins them with nothing. Keep the
    # training form by default and let a run select the other for comparison.
    _sep = os.environ.get("CVP_CANVAS_WRAPPER_SEP")
    _sep = "\n" if _sep is None else _sep
    body = _sep.join(
        VISION_START + IMAGE_PAD * s.merged_token_count + VISION_END
        for s in summaries
    ) + _sep
    first_vs = text.find(VISION_START)
    last_ve = text.rfind(VISION_END)
    if first_vs == -1 or last_ve == -1:
        raise ValueError(
            "codec backend: the prompt has no <|vision_start|>...<|vision_end|> span to "
            "replace. Build the text with the chat template and a video placeholder."
        )
    tail_start = last_ve + len(VISION_END)
    if tail_start < len(text) and text[tail_start] == "\n":
        tail_start += 1
    expanded = text[:first_vs] + body + text[tail_start:]

    rewritten, _info = rewrite_existing_canvas_wrappers(
        expanded, summaries, decimals=decimals
    )
    return rewritten


# =============================================================================
# image-processor bridge
# =============================================================================

def codec_image_processor_outputs(
    image_processor: Any,
    images: List[Image.Image],
    max_pixels: Optional[int] = None,
    patch_size: int = DEFAULT_PATCH_SIZE,
) -> Dict[str, Any]:
    """Patchify the canvases without letting the image processor rescale them.

    A canvas's pixels and its source positions are bound together by the patch
    grid. If ``smart_resize`` shrinks a canvas, every position silently points
    at the wrong patch, so the budget is raised to at least the largest canvas
    and the resulting grid is checked against the canvases' true geometry.
    """
    if not images:
        raise ValueError("codec backend: no canvases to process.")

    largest = max(im.width * im.height for im in images)
    budget = max(int(max_pixels or 0), int(largest))

    try:
        out = image_processor(images=images, max_pixels=budget, return_tensors="pt")
    except TypeError:
        # Older/newer image processors may not accept max_pixels as a call kwarg.
        out = image_processor(images=images, return_tensors="pt")

    grid = out["image_grid_thw"]
    if int(grid.shape[0]) != len(images):
        raise ValueError(
            f"image processor returned {int(grid.shape[0])} grid rows for {len(images)} "
            "canvases; cannot align patch positions."
        )

    for i, (im, row) in enumerate(zip(images, grid)):
        exp_h, exp_w = im.height // patch_size, im.width // patch_size
        got_h, got_w = int(row[1]), int(row[2])
        if (got_h, got_w) != (exp_h, exp_w):
            raise ValueError(
                f"canvas {i} is {im.width}x{im.height} (expected patch grid "
                f"{exp_h}x{exp_w} at patch={patch_size}) but the image processor "
                f"produced {got_h}x{got_w}. The canvas was rescaled, which invalidates "
                "the source positions. Raise the processor's pixel budget, or lower the "
                "codec `max_pixels` so canvases stay within it."
            )
    return out


__all__ = [
    "CodecConfig",
    "process_codec_video",
    "drop_padding_canvases",
    "codec_positions_for_processor",
    "rewrite_text_with_codec_positions",
    "codec_image_processor_outputs",
    "convert_positions_to_block_layout",
    "CANVAS_TIMESTAMP_SCHEMA",
]