77from contextlib import contextmanager
88from dataclasses import dataclass
99from fractions import Fraction
10- from math import ceil
10+ from math import ceil , prod
1111from pathlib import Path
1212
1313import numpy as np
1414
15+ from hflow ._field_guards import require_positive_int
16+ from hflow ._frame_budget import DEFAULT_MAXIMUM_FRAME_PIXELS , ffmpeg_decoder_maximum_pixels
17+
1518from ._bounded_process import BoundedProcessError , run_bounded_process
1619from ._frame_integrity import cleanly_decoded_frame_indices
1720from ._toolchain import VideoMeasurementToolchain
@@ -26,6 +29,8 @@ class RawFrameError(RuntimeError):
2629MAXIMUM_DECODED_FRAME_HASH_OUTPUT_BYTES = 256 * 1024 * 1024
2730FFPROBE_TIMEOUT_SECONDS = 600.0
2831MAXIMUM_FFPROBE_OUTPUT_BYTES = 256 * 1024 * 1024
32+ # rgb24 is the widest pixel format these readers request.
33+ _MAXIMUM_BYTES_PER_PIXEL = 3
2934
3035
3136@dataclass (frozen = True )
@@ -54,7 +59,9 @@ def _run_ffprobe(video: Path, toolchain: VideoMeasurementToolchain, arguments: l
5459 return completed_process .stdout
5560
5661
57- def _probe_frame_shape (video : Path , toolchain : VideoMeasurementToolchain ) -> tuple [int , int ]:
62+ def _probe_frame_shape (
63+ video : Path , toolchain : VideoMeasurementToolchain , * , maximum_frame_pixels : int
64+ ) -> tuple [int , int ]:
5865 """Return the coded ``(height, width)`` of the first video stream."""
5966 output = _run_ffprobe (
6067 video ,
@@ -85,9 +92,27 @@ def _probe_frame_shape(video: Path, toolchain: VideoMeasurementToolchain) -> tup
8592 or frame_height <= 0
8693 ):
8794 raise RawFrameError (f"ffprobe reported invalid video dimensions for { video } " )
95+ _require_frame_within_pixel_budget (video , (frame_height , frame_width ), maximum_frame_pixels )
8896 return frame_height , frame_width
8997
9098
99+ def _require_frame_within_pixel_budget (
100+ video : Path , frame_shape : tuple [int , ...], maximum_frame_pixels : int
101+ ) -> None :
102+ """Refuse a ``(height, width[, channels])`` frame larger than the pixel budget."""
103+ require_positive_int (maximum_frame_pixels , "maximum_frame_pixels" )
104+ frame_height , frame_width , * channel_dimensions = frame_shape
105+ if frame_height * frame_width > maximum_frame_pixels :
106+ raise RawFrameError (
107+ f"{ video } has { frame_width } x{ frame_height } frames, which exceed the "
108+ f"{ maximum_frame_pixels } -pixel frame budget"
109+ )
110+ if prod (channel_dimensions ) > _MAXIMUM_BYTES_PER_PIXEL :
111+ raise RawFrameError (
112+ f"raw frames for { video } cannot exceed { _MAXIMUM_BYTES_PER_PIXEL } bytes per pixel"
113+ )
114+
115+
91116def _probe_frame_rate (video : Path , toolchain : VideoMeasurementToolchain ) -> float :
92117 """Return the stream's declared constant frame rate."""
93118 output = _run_ffprobe (
@@ -170,6 +195,7 @@ def _decoded_frame_hashes(
170195 filter_graph : str ,
171196 source_fps : float ,
172197 sample_fps : float | None ,
198+ maximum_frame_pixels : int = DEFAULT_MAXIMUM_FRAME_PIXELS ,
173199) -> tuple [list [int ], dict [int , set [str ]]]:
174200 """Trace decoded RGB digests without writing frame data or a sidecar file."""
175201 command = [
@@ -179,6 +205,8 @@ def _decoded_frame_hashes(
179205 "-loglevel" ,
180206 "error" ,
181207 "-noautorotate" ,
208+ "-max_pixels" ,
209+ str (ffmpeg_decoder_maximum_pixels (maximum_frame_pixels )),
182210 "-i" ,
183211 str (video ),
184212 "-map" ,
@@ -269,16 +297,20 @@ def _raw_frame_stream(
269297 toolchain : VideoMeasurementToolchain ,
270298 filter_graph : str ,
271299 frame_shape : tuple [int , ...],
300+ maximum_frame_pixels : int = DEFAULT_MAXIMUM_FRAME_PIXELS ,
272301) -> Generator [Iterator [np .ndarray ], None , None ]:
273302 """Yield complete ``uint8`` frames from one owned FFmpeg process."""
274- frame_byte_count = int (np .prod (frame_shape ))
303+ _require_frame_within_pixel_budget (video , frame_shape , maximum_frame_pixels )
304+ frame_byte_count = prod (frame_shape )
275305 command = [
276306 str (toolchain .ffmpeg_executable ),
277307 "-nostdin" ,
278308 "-hide_banner" ,
279309 "-loglevel" ,
280310 "error" ,
281311 "-noautorotate" ,
312+ "-max_pixels" ,
313+ str (ffmpeg_decoder_maximum_pixels (maximum_frame_pixels )),
282314 "-i" ,
283315 str (video ),
284316 "-map" ,
@@ -330,15 +362,22 @@ def read_frames() -> Iterator[np.ndarray]:
330362
331363@contextmanager
332364def luma_frames (
333- video : Path , * , toolchain : VideoMeasurementToolchain
365+ video : Path ,
366+ * ,
367+ toolchain : VideoMeasurementToolchain ,
368+ maximum_frame_pixels : int = DEFAULT_MAXIMUM_FRAME_PIXELS ,
334369) -> Generator [Iterator [np .ndarray ], None , None ]:
335- """Yield coded-size ``(height, width)`` 8-bit luma frames in order."""
336- frame_shape = _probe_frame_shape (video , toolchain )
370+ """Yield coded-size ``(height, width)`` 8-bit luma frames in order.
371+
372+ A video whose frames exceed ``maximum_frame_pixels`` raises before decoding.
373+ """
374+ frame_shape = _probe_frame_shape (video , toolchain , maximum_frame_pixels = maximum_frame_pixels )
337375 with _raw_frame_stream (
338376 video ,
339377 toolchain = toolchain ,
340378 filter_graph = LUMA_FRAME_FILTER_GRAPH ,
341379 frame_shape = frame_shape ,
380+ maximum_frame_pixels = maximum_frame_pixels ,
342381 ) as frames :
343382 yield frames
344383
@@ -351,6 +390,7 @@ def rgb_frames(
351390 frames_per_second : float | None = None ,
352391 long_edge_pixels : int | None = None ,
353392 source_fps : float | None = None ,
393+ maximum_frame_pixels : int = DEFAULT_MAXIMUM_FRAME_PIXELS ,
354394) -> Generator [Iterator [SampledRGBFrame ], None , None ]:
355395 """Yield sampled RGB frames with their original sample and source positions.
356396
@@ -359,11 +399,14 @@ def rgb_frames(
359399 comparing their digests filters out frames the ``fps`` filter repeated to
360400 fill decoder gaps. No full-video pixel buffer or temporary file is needed.
361401 ``sample_index`` preserves the original tick so callers can keep labels
362- aligned when a tick is omitted.
402+ aligned when a tick is omitted. A source or sample frame that exceeds
403+ ``maximum_frame_pixels`` raises before decoding.
363404 """
364405 if frames_per_second is not None and frames_per_second <= 0 :
365406 raise ValueError (f"frames_per_second must be positive, got { frames_per_second } " )
366- source_height , source_width = _probe_frame_shape (video , toolchain )
407+ source_height , source_width = _probe_frame_shape (
408+ video , toolchain , maximum_frame_pixels = maximum_frame_pixels
409+ )
367410 frame_height , frame_width = _scaled_frame_shape ((source_height , source_width ), long_edge_pixels )
368411 if source_fps is None :
369412 source_fps = _probe_frame_rate (video , toolchain )
@@ -385,12 +428,16 @@ def rgb_frames(
385428 decoded_filter_graph = "," .join (decoded_filters )
386429 sampled_filter_graph = "," .join (sampled_filters )
387430 frame_shape = (frame_height , frame_width , 3 )
431+ # An upscaling ``long_edge_pixels`` would otherwise make FFmpeg build
432+ # oversized frames for the digest trace before the raw reader refuses them.
433+ _require_frame_within_pixel_budget (video , frame_shape , maximum_frame_pixels )
388434 decoded_indices , decoded_hashes = _decoded_frame_hashes (
389435 video ,
390436 toolchain = toolchain ,
391437 filter_graph = decoded_filter_graph ,
392438 source_fps = source_fps ,
393439 sample_fps = effective_sample_fps ,
440+ maximum_frame_pixels = maximum_frame_pixels ,
394441 )
395442 clean_decoded_indices = cleanly_decoded_frame_indices (
396443 set (decoded_indices ),
@@ -403,6 +450,7 @@ def rgb_frames(
403450 toolchain = toolchain ,
404451 filter_graph = sampled_filter_graph ,
405452 frame_shape = frame_shape ,
453+ maximum_frame_pixels = maximum_frame_pixels ,
406454 ) as candidate_frames :
407455
408456 def read_frames () -> Iterator [SampledRGBFrame ]:
0 commit comments