diff --git a/benchmark/__main__.py b/benchmark/__main__.py index 2f4f9a3f..6c569162 100644 --- a/benchmark/__main__.py +++ b/benchmark/__main__.py @@ -54,7 +54,7 @@ def _run_predictions( pred_scene_list = detect(str(sample.video_file), detector_cls(), backend=backend) elapsed = time.time() - start predictions[sample.video_file] = Prediction( - predicted_cuts=[scene[1].frame_num for scene in pred_scene_list], + predicted_cuts=[scene[1].frame_number for scene in pred_scene_list], ground_truth=sample.ground_truth, elapsed=elapsed, ) diff --git a/benchmark/sweep.py b/benchmark/sweep.py index dbd20d78..1d794d25 100644 --- a/benchmark/sweep.py +++ b/benchmark/sweep.py @@ -166,7 +166,7 @@ def worker(i: int, params: dict[str, Any]) -> None: t0 = time.time() sm.detect_scenes(video=stream) elapsed = time.time() - t0 - cuts = [scene[1].frame_num for scene in sm.get_scene_list()] + cuts = [scene[1].frame_number for scene in sm.get_scene_list()] results[i] = (cuts, elapsed) except BaseException as exc: errors[i] = exc diff --git a/scenedetect/__init__.py b/scenedetect/__init__.py index c07e60c5..60735f46 100644 --- a/scenedetect/__init__.py +++ b/scenedetect/__init__.py @@ -33,17 +33,19 @@ # Note that order of importants is important! from scenedetect.platform import init_logger as init_logger # noqa: I001 from scenedetect.common import ( - FrameTimecode as FrameTimecode, + FramePosition as FramePosition, + FrameDuration as FrameDuration, + Timecode as Timecode, FrameRate as FrameRate, SceneList as SceneList, CutList as CutList, CropRegion as CropRegion, - TimecodePair as TimecodePair, + PositionPair as PositionPair, TimecodeLike as TimecodeLike, Interpolation as Interpolation, ) from scenedetect.platform import StrPath as StrPath -from scenedetect.video_stream import VideoStream as VideoStream +from scenedetect.video_stream import VideoStream as VideoStream, FrameNumbering as FrameNumbering from scenedetect.video_stream import VideoOpenFailure as VideoOpenFailure from scenedetect.output import ( save_images as save_images, @@ -80,7 +82,7 @@ # Used for module identification and when printing version & about info # (e.g. calling `scenedetect version` or `scenedetect about`). -__version__ = "0.7.4-dev0" +__version__ = "0.8-dev0" init_logger() logger = getLogger("pyscenedetect") @@ -147,7 +149,11 @@ def open_video( backend_type = VideoStreamCv2 logger.warning("Trying another backend: %s", backend_type.BACKEND_NAME) try: - return backend_type(path, frame_rate) + return backend_type( + path, + frame_rate, + frame_numbering=kwargs.get("frame_numbering", FrameNumbering.RELATIVE), + ) except VideoOpenFailure as ex: logger.debug("Failed to open video: %s", str(ex)) if last_error is None: @@ -179,12 +185,13 @@ def detect( determine a better threshold value. show_progress: Show a progress bar with estimated time remaining. Default is False. start_time: Starting point in video, in the form of a timecode ``HH:MM:SS[.nnn]`` (`str`), - number of seconds ``123.45`` (`float`), or number of frames ``200`` (`int`). - end_time: Starting point in video, in the form of a timecode ``HH:MM:SS[.nnn]`` (`str`), - number of seconds ``123.45`` (`float`), or number of frames ``200`` (`int`). + number of seconds ``123.45`` (`float`), a zero-based source frame ordinal ``200`` + (`int`), or a :class:`~scenedetect.common.Timecode`. + end_time: Exclusive ending point, in the same formats as `start_time`. With the default + relative numbering, integer limits count from zero after the start seek. start_in_scene: Assume the video begins in a scene. This means that when detecting fast cuts with `ContentDetector`, if no cuts are found, the resulting scene list - will contain a single scene spanning the entire video (instead of no scenes). + will contain a single scene spanning the processed range (instead of no scenes). When detecting fades with `ThresholdDetector`, the beginning portion of the video will always be included until the first fade-out event is detected. backend: Name of the backend to use for video decoding. See @@ -193,7 +200,7 @@ def detect( is unavailable or fails to open the video. Returns: - List of scenes as pairs of (start, end) :class:`~scenedetect.common.FrameTimecode` objects. + List of scenes as pairs of (start, end) :class:`~scenedetect.common.FramePosition` objects. Raises: :class:`VideoOpenFailure`: `video_path` could not be opened. @@ -203,8 +210,7 @@ def detect( """ video = open_video(video_path, backend=backend) if start_time is not None: - video.seek(FrameTimecode(start_time, video.frame_rate)) - end_timecode = FrameTimecode(end_time, video.frame_rate) if end_time is not None else None + video.seek(start_time) # To reduce memory consumption when not required, we only add a StatsManager if we # need to save frame metrics to disk. scene_manager = SceneManager(StatsManager() if stats_file_path else None) @@ -212,7 +218,7 @@ def detect( scene_manager.detect_scenes( video=video, show_progress=show_progress, - end_time=end_timecode, + end_time=end_time, ) if scene_manager.stats_manager is not None and stats_file_path is not None: scene_manager.stats_manager.save_to_csv(csv_file=stats_file_path) diff --git a/scenedetect/_cli/__init__.py b/scenedetect/_cli/__init__.py index ee29c9f2..0546bea2 100644 --- a/scenedetect/_cli/__init__.py +++ b/scenedetect/_cli/__init__.py @@ -35,11 +35,10 @@ DEFAULT_JPG_QUALITY, DEFAULT_WEBP_QUALITY, RangeValue, - TimecodeValue, ) from scenedetect._cli.context import USER_CONFIG, CliContext, check_split_video_requirements from scenedetect.backends import AVAILABLE_BACKENDS -from scenedetect.common import FrameTimecode +from scenedetect.common import Timecode, parse_frame_or_time from scenedetect.detectors import ( AdaptiveDetector, ContentDetector, @@ -246,6 +245,15 @@ def print_command_help(ctx: click.Context, command: click.Command): default=None, help="Override frame rate with value as frames/sec.", ) +@click.option( + "--frame-numbering", + type=click.Choice(CHOICE_MAP["global"]["frame-numbering"], case_sensitive=False), + default=None, + help=( + "Relative restarts frame numbering at 0 after a seek. Source counts " + "frames from the beginning of the video.{}" + ).format(USER_CONFIG.get_help_string("global", "frame-numbering")), +) @click.option( "--min-scene-len", "-m", @@ -347,6 +355,7 @@ def scenedetect( stats: str | None, config: str | None, frame_rate: float | None, + frame_numbering: str | None, min_scene_len: str | None, drop_short_scenes: bool | None, merge_last_scene: bool | None, @@ -368,6 +377,7 @@ def scenedetect( frame_rate=frame_rate, stats_file=stats, frame_skip=frame_skip, + frame_numbering=frame_numbering, min_scene_len=min_scene_len, drop_short_scenes=drop_short_scenes, merge_last_scene=merge_last_scene, @@ -515,21 +525,13 @@ def time_command( ctx.start_time = ctx.parse_timecode(start, correct_pts=True) ctx.end_time = ctx.parse_timecode(end) ctx.duration = ctx.parse_timecode(duration) - if ctx.start_time and ctx.end_time and (ctx.start_time + 1) > ctx.end_time: + invalid_range = False + if isinstance(ctx.start_time, int) and isinstance(ctx.end_time, int): + invalid_range = ctx.end_time <= ctx.start_time + elif isinstance(ctx.start_time, Timecode) and isinstance(ctx.end_time, Timecode): + invalid_range = ctx.end_time.seconds <= ctx.start_time.seconds + if invalid_range: raise click.BadParameter("-e/--end time must be greater than -s/--start") - # Reject start times past EOF before any backend seeks. OpenCV/PyAV previously - # continued and produced inconsistent errors; MoviePy raised SeekError (#380). - video_duration = ctx.video_stream.duration if ctx.video_stream is not None else None - if ( - ctx.start_time is not None - and video_duration is not None - and video_duration > 0 - and ctx.start_time >= video_duration - ): - raise click.BadParameter( - "start time is beyond the end of the video", - param_hint="-s/--start", - ) DETECT_CONTENT_HELP = """Find fast cuts using differences in HSL (filtered). @@ -986,13 +988,15 @@ def detect_hash_command( ctx.add_detector(HashDetector, detector_args) -LOAD_SCENES_HELP = """Load scenes from CSV instead of detecting. Can be used with CSV generated by `list-scenes`. Scenes are loaded using the specified column as cut locations (frame number or timecode). +LOAD_SCENES_HELP = """Load saved scene ranges from CSV instead of detecting. Requires start/end frame and time columns, defaulting to those written by `list-scenes`. + +Time limits select complete saved scenes. Limits inside a saved scene are rejected. Examples: {scenedetect_with_video} load-scenes -i scenes.csv - {scenedetect_with_video} load-scenes -i scenes.csv --start-col-name "Start Timecode" + {scenedetect_with_video} load-scenes -i scenes.csv --start-time-col-name "Start Timecode" --end-time-col-name "End Timecode" """ @@ -1007,22 +1011,51 @@ def detect_hash_command( help="Scene list to read cut information from.", ) @click.option( - "--start-col-name", - "-c", - metavar="STRING", + "--start-frame-col-name", + type=click.STRING, + default=None, + help="Column containing one-based scene start frames.{}".format( + USER_CONFIG.get_help_string("load-scenes", "start-frame-col-name") + ), +) +@click.option( + "--start-time-col-name", + type=click.STRING, + default=None, + help="Column containing scene start times.{}".format( + USER_CONFIG.get_help_string("load-scenes", "start-time-col-name") + ), +) +@click.option( + "--end-frame-col-name", + type=click.STRING, + default=None, + help="Column containing exclusive scene end ordinals.{}".format( + USER_CONFIG.get_help_string("load-scenes", "end-frame-col-name") + ), +) +@click.option( + "--end-time-col-name", type=click.STRING, default=None, - help="Name of column used to mark scene cuts.{}".format( - USER_CONFIG.get_help_string("load-scenes", "start-col-name") + help="Column containing scene end times.{}".format( + USER_CONFIG.get_help_string("load-scenes", "end-time-col-name") ), ) @click.pass_context -def load_scenes_command(ctx: click.Context, input: str | None, start_col_name: str | None): +def load_scenes_command( + ctx: click.Context, + input: str | None, + start_frame_col_name: str | None, + start_time_col_name: str | None, + end_frame_col_name: str | None, + end_time_col_name: str | None, +): ctx = ctx.obj assert isinstance(ctx, CliContext) check_not_stdin(ctx, "load-scenes") - logger.debug("Will load scenes from %s (start_col_name = %s)", input, start_col_name) + logger.debug("Will load scenes from %s", input) assert ctx.scene_manager is not None if ctx.scene_manager.get_num_detectors() > 0: raise click.ClickException("The load-scenes command cannot be used with detectors.") @@ -1036,9 +1069,16 @@ def load_scenes_command(ctx: click.Context, input: str | None, start_col_name: s f"Could not load scenes, file does not exist: {input}", param_hint="-i/--input" ) ctx.load_scenes_input = input - ctx.load_scenes_column_name = ctx.config.get_value( - "load-scenes", "start-col-name", start_col_name - ) + ctx.load_scenes_columns = { + "start_frame": ctx.config.get_value( + "load-scenes", "start-frame-col-name", start_frame_col_name + ), + "start_time": ctx.config.get_value( + "load-scenes", "start-time-col-name", start_time_col_name + ), + "end_frame": ctx.config.get_value("load-scenes", "end-frame-col-name", end_frame_col_name), + "end_time": ctx.config.get_value("load-scenes", "end-time-col-name", end_time_col_name), + } SAVE_HTML_HELP = """Save scene list to HTML file. @@ -1329,8 +1369,8 @@ def list_scenes_command( "--expand", is_flag=True, flag_value=True, - default=False, - help="Extend the first/last output clips to cover the full input video, even if `time -s/-e` limited the analysis window. Useful for keeping content outside the analyzed region attached to the adjacent split.{}".format( + default=None, + help="Extend the first/last output clips to cover the full input video, even if `time -s/-e` limited the analysis window. Useful for keeping content outside the analyzed region attached to the adjacent split. Expanded filename boundary variables use zero for the first start and a blank last end.{}".format( USER_CONFIG.get_help_string("split-video", "expand") ), ) @@ -1346,7 +1386,7 @@ def split_video_command( preset: str | None, args: str | None, mkvmerge: bool, - expand: bool, + expand: bool | None, ): ctx = ctx.obj assert isinstance(ctx, CliContext) @@ -1644,13 +1684,13 @@ def save_images_command( ) if interval is not None: try: - TimecodeValue(interval) + parsed_interval = parse_frame_or_time(interval) except ValueError as ex: raise click.BadParameter( "Interval must be in frames (24), seconds (1.5s), or HH:MM:SS.", param_hint="-i/--interval", ) from ex - if FrameTimecode(timecode=interval, fps=ctx.video_stream.frame_rate).seconds <= 0: + if parsed_interval <= 0: raise click.BadParameter("Interval must be greater than 0.", param_hint="-i/--interval") elif num_images is None: if not ctx.config.is_default("save-images", "interval") and not ctx.config.is_default( @@ -1664,7 +1704,7 @@ def save_images_command( num_images = ctx.config.get_value("save-images", "num-images") else: interval_value: str = ctx.config.get_value("save-images", "interval") - if FrameTimecode(timecode=interval_value, fps=ctx.video_stream.frame_rate).seconds <= 0: + if parse_frame_or_time(interval_value) <= 0: raise click.BadParameter( "interval in the config file must be greater than 0.", param_hint="save-images", @@ -1900,7 +1940,7 @@ def save_qp_command( SAVE_KEYFRAMES_HELP = """Save detected cuts using keyframe format v1. -Frame numbers are currently approximate for variable framerate (VFR) video. +Frame numbers zero-based. """ diff --git a/scenedetect/_cli/commands.py b/scenedetect/_cli/commands.py index 1576b4cd..625ff5a8 100644 --- a/scenedetect/_cli/commands.py +++ b/scenedetect/_cli/commands.py @@ -19,8 +19,9 @@ import webbrowser from string import Template -from scenedetect._cli.config import FcpFormat +from scenedetect._cli.config import FcpFormat, TimecodeFormat from scenedetect._cli.context import CliContext +from scenedetect.common import TimecodeLike from scenedetect.output import save_images as save_images_impl from scenedetect.output import ( split_video_ffmpeg, @@ -34,12 +35,7 @@ write_scene_list_otio, ) from scenedetect.platform import get_and_create_path -from scenedetect.scene_manager import ( - CutList, - Interpolation, - SceneList, - expand_scenes_to_bounds, -) +from scenedetect.scene_manager import CutList, Interpolation, SceneList logger = logging.getLogger("pyscenedetect") @@ -93,13 +89,13 @@ def save_qp( Template(filename).safe_substitute(VIDEO_NAME=context.video_stream.name), output, ) - start_frame = context.start_time.frame_num if context.start_time else 0 + start_frame = context.start_pos.frame_number if context.start_pos is not None else 0 shift_start = not disable_shift offset = start_frame if shift_start else 0 with open(qp_path, "w") as qp_file: qp_file.write(f"{0 if shift_start else start_frame} I -1\n") # Place another I frame at each detected cut. - qp_file.writelines(f"{cut.frame_num - offset} I -1\n" for cut in cuts) + qp_file.writelines(f"{cut.frame_number - offset} I -1\n" for cut in cuts) logger.info(f"QP file written to: {qp_path}") @@ -120,9 +116,7 @@ def save_keyframes( # https://aegisub.org/docs/latest/video/#keyframe-file-specification keyframes_file.write("fps 0\n") keyframes_file.write("0\n") - # TODO(https://scenedetect.com/issues/569): Frame numbers are approximate for VFR - # input until exact presentation-frame ordinals are tracked. - keyframes_file.writelines(f"{cut.frame_num}\n" for cut in cuts) + keyframes_file.writelines(f"{cut.frame_number}\n" for cut in cuts) logger.info(f"Keyframes written to: {keyframes_path}") @@ -137,7 +131,7 @@ def list_scenes( quiet: bool, display_scenes: bool, display_cuts: bool, - cut_format: str, + cut_format: TimecodeFormat, col_separator: str, row_separator: str, ): @@ -178,8 +172,8 @@ def list_scenes( -----------------------------------------------------------------------""", "\n".join( [ - f" | {i + 1:5d} | {start_time.frame_num + 1:11d} | {start_time.get_timecode()} | {end_time.frame_num:11d} | {end_time.get_timecode()} |" - for i, (start_time, end_time) in enumerate(scenes) + f" | {i + 1:5d} | {start_pos.frame_number + 1:11d} | {start_pos.timecode.get_timecode()} | {end_pos.frame_number:11d} | {end_pos.timecode.get_timecode()} |" + for i, (start_pos, end_pos) in enumerate(scenes) ] ), ) @@ -196,18 +190,18 @@ def save_images( scenes: SceneList, cuts: CutList, num_images: int | None, - interval: str | None, + interval: TimecodeLike | None, min_images: int, max_images: int | None, - frame_margin: int, + frame_margin: TimecodeLike, image_extension: str, encoder_param: int, filename: str, output: str | None, show_progress: bool, - scale: int, - height: int, - width: int, + scale: float | None, + height: int | None, + width: int | None, interpolation: Interpolation, threading: bool, ): @@ -253,17 +247,6 @@ def split_video( del cuts # split-video only uses scenes. assert context.video_stream is not None - if expand and scenes: - video_duration = context.video_stream.duration - if video_duration is None: - logger.warning("Cannot --expand: video duration is unavailable for this stream.") - else: - scenes = expand_scenes_to_bounds( - scenes, - start=context.video_stream.base_timecode, - end=video_duration, - ) - if use_mkvmerge: name_format = name_format.removesuffix("-$SCENE_NUMBER") @@ -282,6 +265,7 @@ def split_video( scene_list=scenes, output_dir=output, output_file_template=name_format, + expand=expand, show_output=show_output, ) else: @@ -290,6 +274,7 @@ def split_video( scene_list=scenes, output_dir=output, output_file_template=name_format, + expand=expand, arg_override=ffmpeg_args, show_progress=not context.quiet_mode, show_output=show_output, @@ -346,6 +331,7 @@ def save_edl( title=Template(title).safe_substitute(VIDEO_NAME=video_name), reel=reel, start_timecode=start_timecode, + frame_rate=context.video_stream.frame_rate, ) diff --git a/scenedetect/_cli/config.py b/scenedetect/_cli/config.py index 6dea3251..033b482a 100644 --- a/scenedetect/_cli/config.py +++ b/scenedetect/_cli/config.py @@ -27,12 +27,13 @@ import click from platformdirs import user_config_dir -from scenedetect.common import FrameTimecode +from scenedetect.common import FramePosition, parse_frame_or_time from scenedetect.detector import FlashFilter from scenedetect.detectors import ContentDetector from scenedetect.output.video import _DEFAULT_FFMPEG_ARGS from scenedetect.platform import DEBUG_MODE from scenedetect.scene_manager import Interpolation +from scenedetect.video_stream import FrameNumbering PYAV_THREADING_MODES = ["NONE", "SLICE", "FRAME", "AUTO"] @@ -80,7 +81,7 @@ class TimecodeValue(ValidatedValue): def __init__(self, value: int | float | str): # Ensure value is a valid timecode. - FrameTimecode(timecode=value, fps=100.0) + parse_frame_or_time(value) self._value = value @property @@ -335,13 +336,13 @@ class TimecodeFormat(Enum): SECONDS = 2 """Print timecodes in seconds SSS.sss.""" - def format(self, timecode: FrameTimecode) -> str: + def format(self, position: FramePosition) -> str: if self == TimecodeFormat.FRAMES: - return str(timecode.frame_num) + return str(position.frame_number) if self == TimecodeFormat.TIMECODE: - return timecode.get_timecode() + return position.timecode.get_timecode() if self == TimecodeFormat.SECONDS: - return f"{timecode.seconds:.3f}" + return f"{float(position.timecode.seconds):.3f}" raise RuntimeError("Unhandled format specifier.") @@ -425,7 +426,10 @@ def default_to_str(value: ConfigValue) -> str: "threshold": RangeValue(12.0, min_val=0.0, max_val=255.0), }, "load-scenes": { - "start-col-name": "Start Frame", + "start-frame-col-name": "Start Frame", + "start-time-col-name": "Start Time (seconds)", + "end-frame-col-name": "End Frame", + "end-time-col-name": "End Time (seconds)", }, "list-scenes": { "cut-format": TimecodeFormat.TIMECODE, @@ -445,6 +449,7 @@ def default_to_str(value: ConfigValue) -> str: "default-detector": "detect-adaptive", "downscale": 0, "downscale-method": Interpolation.LINEAR, + "frame-numbering": FrameNumbering.RELATIVE.value, "drop-short-scenes": False, "frame-skip": 0, "merge-last-scene": False, @@ -542,6 +547,7 @@ def default_to_str(value: ConfigValue) -> str: "detect-hist", ], "downscale-method": [value.name.lower() for value in Interpolation], + "frame-numbering": [mode.value for mode in FrameNumbering], "verbosity": ["debug", "info", "warning", "error", "none"], }, "list-scenes": { diff --git a/scenedetect/_cli/context.py b/scenedetect/_cli/context.py index c367e08d..31ae7491 100644 --- a/scenedetect/_cli/context.py +++ b/scenedetect/_cli/context.py @@ -14,6 +14,7 @@ import logging import sys import typing as ty +from fractions import Fraction import click @@ -28,7 +29,13 @@ ScoreWeightsValue, ) from scenedetect.backends import VideoStreamAv -from scenedetect.common import MAX_FPS_DELTA, FrameTimecode +from scenedetect.common import ( + MAX_FPS_DELTA, + FramePosition, + Timecode, + TimecodeLike, + parse_frame_or_time, +) from scenedetect.detector import SceneDetector from scenedetect.detectors import ( AdaptiveDetector, @@ -41,7 +48,12 @@ from scenedetect.platform import DEBUG_MODE, init_logger from scenedetect.scene_manager import SceneManager from scenedetect.stats_manager import StatsManager -from scenedetect.video_stream import FrameRateUnavailable, VideoOpenFailure, VideoStream +from scenedetect.video_stream import ( + FrameNumbering, + FrameRateUnavailable, + VideoOpenFailure, + VideoStream, +) logger = logging.getLogger("pyscenedetect") @@ -105,21 +117,23 @@ def __init__(self): self.save_images: bool = False # True if the save-images command was specified # Result of save-images used by save-html: (image filenames, output directory). self.save_images_result: tuple[dict[int, list[str]], str | None] | None = None + # Preserve the processing start even if short scenes are removed. + self.start_pos: FramePosition | None = None # Input: self.video_stream: VideoStream | None = None self.use_stdin: bool = False # --stdin self.load_scenes_input: str | None = None # load-scenes -i/--input - self.load_scenes_column_name: str | None = None # load-scenes -c/--start-col-name - self.start_time: FrameTimecode | None = None # time -s/--start - self.end_time: FrameTimecode | None = None # time -e/--end - self.duration: FrameTimecode | None = None # time -d/--duration + self.load_scenes_columns: dict[str, str] = {} + self.start_time: int | Timecode | None = None # time -s/--start + self.end_time: int | Timecode | None = None # time -e/--end + self.duration: int | Timecode | None = None # time -d/--duration self.frame_skip: int | None = None # Options: self.drop_short_scenes: bool | None = None self.merge_last_scene: bool | None = None - self.min_scene_len: FrameTimecode | None = None + self.min_scene_len: int | Timecode | None = None self.default_detector: tuple[type[SceneDetector], dict[str, ty.Any]] | None = None self.output: str | None = None self.stats_file_path: str | None = None @@ -153,21 +167,21 @@ def ensure_detector(self): (detector_type, detector_args) = self.default_detector self.add_detector(detector_type, detector_args) - def _resolve_min_scene_len(self, command: str, override: str | None) -> int: - """Resolve the minimum scene length (in frames) for a `detect-*` command, honoring + def _resolve_min_scene_len(self, command: str, override: str | None) -> int | Timecode: + """Resolve the minimum scene length for a `detect-*` command, honoring the `--drop-short-scenes` flag, command-specific config, and global default.""" if self.drop_short_scenes: return 0 if override is not None: parsed = self.parse_timecode(override) assert parsed is not None - return parsed.frame_num + return parsed if self.config.is_default(command, "min-scene-len"): assert self.min_scene_len is not None - return self.min_scene_len.frame_num + return self.min_scene_len parsed = self.parse_timecode(self.config.get_value(command, "min-scene-len")) assert parsed is not None - return parsed.frame_num + return parsed @staticmethod def _kernel_size_value(kernel_size: int | None) -> KernelSizeValue | None: @@ -195,9 +209,12 @@ def _weights_value( except ValueError as ex: raise click.BadParameter(str(ex), param_hint="weights") from ex - def parse_timecode(self, value: str | None, correct_pts: bool = False) -> FrameTimecode | None: - """Parses a user input string into a FrameTimecode assuming the given framerate. If `value` - is None it will be passed through without processing. + def parse_timecode( + self, value: TimecodeLike | None, correct_pts: bool = False + ) -> int | Timecode | None: + """Parse a CLI/config value as integer frames or an exact Timecode. + None is returned unchanged. With correct_pts, positive frame inputs + are converted from CLI one-based numbering to zero-based numbering. Raises: click.BadParameter, click.ClickException @@ -207,13 +224,12 @@ def parse_timecode(self, value: str | None, correct_pts: bool = False) -> FrameT try: if self.video_stream is None: raise click.ClickException("No input video (-i/--input) was specified.") - timecode: int | str - if correct_pts and value.isdigit(): - int_value = int(value) - timecode = int_value - 1 if int_value >= 1 else int_value - else: - timecode = value - return FrameTimecode(timecode=timecode, fps=self.video_stream.frame_rate) + parsed = parse_frame_or_time(value) + if isinstance(parsed, int): + if correct_pts and parsed > 0: + parsed -= 1 + return parsed + return Timecode(pts=parsed.numerator, time_base=Fraction(1, parsed.denominator)) except ValueError as ex: raise click.BadParameter( "timecode must be in seconds (100.0), frames (100), or HH:MM:SS" @@ -225,6 +241,7 @@ def handle_options( use_stdin: bool, output: str | None, frame_rate: float | None, + frame_numbering: str | None, stats_file: str | None, frame_skip: int | None, min_scene_len: str | None, @@ -311,11 +328,14 @@ def handle_options( if input_path is None and not use_stdin: return - # Load the input video to obtain a time base for parsing timecodes. + numbering = FrameNumbering( + self.config.get_value("global", "frame-numbering", frame_numbering).lower() + ) + # Open the input video before configuring detection. if use_stdin: - self._open_stdin_stream(frame_rate, backend) + self._open_stdin_stream(frame_rate, backend, frame_numbering=numbering) else: - self._open_video_stream(input_path, frame_rate, backend) + self._open_video_stream(input_path, frame_rate, backend, frame_numbering=numbering) self.output = self.config.get_value("global", "output", output) if self.output: @@ -400,7 +420,7 @@ def get_detect_content_params( filter_mode: str | None = None, ) -> dict[str, ty.Any]: """Get a dict containing user options to construct a ContentDetector with.""" - min_scene_len_frames = self._resolve_min_scene_len("detect-content", min_scene_len) + resolved_min_scene_len = self._resolve_min_scene_len("detect-content", min_scene_len) return { "weights": self.config.get_value( @@ -410,7 +430,7 @@ def get_detect_content_params( "detect-content", "kernel-size", self._kernel_size_value(kernel_size) ), "luma_only": luma_only or self.config.get_value("detect-content", "luma-only"), - "min_scene_len": min_scene_len_frames, + "min_scene_len": resolved_min_scene_len, "threshold": self.config.get_value("detect-content", "threshold", threshold), "filter_mode": self.config.get_value("detect-content", "filter-mode", filter_mode), } @@ -427,7 +447,7 @@ def get_detect_adaptive_params( ) -> dict[str, ty.Any]: """Handle detect-adaptive command options and return args to construct one with.""" - min_scene_len_frames = self._resolve_min_scene_len("detect-adaptive", min_scene_len) + resolved_min_scene_len = self._resolve_min_scene_len("detect-adaptive", min_scene_len) return { "adaptive_threshold": self.config.get_value("detect-adaptive", "threshold", threshold), @@ -441,7 +461,7 @@ def get_detect_adaptive_params( "min_content_val": self.config.get_value( "detect-adaptive", "min-content-val", min_content_val ), - "min_scene_len": min_scene_len_frames, + "min_scene_len": resolved_min_scene_len, "window_width": self.config.get_value("detect-adaptive", "frame-window", frame_window), } @@ -455,13 +475,13 @@ def get_detect_threshold_params( ) -> dict[str, ty.Any]: """Handle detect-threshold command options and return args to construct one with.""" - min_scene_len_frames = self._resolve_min_scene_len("detect-threshold", min_scene_len) + resolved_min_scene_len = self._resolve_min_scene_len("detect-threshold", min_scene_len) # TODO(v1.0): add_last_scene cannot be disabled right now. return { "add_final_scene": add_last_scene or self.config.get_value("detect-threshold", "add-last-scene"), "fade_bias": self.config.get_value("detect-threshold", "fade-bias", fade_bias), - "min_scene_len": min_scene_len_frames, + "min_scene_len": resolved_min_scene_len, "min_out_length": self.parse_timecode( self.config.get_value("detect-threshold", "min-out-length", min_out_length) ), @@ -476,10 +496,10 @@ def get_detect_hist_params( ) -> dict[str, ty.Any]: """Handle detect-hist command options and return args to construct one with.""" - min_scene_len_frames = self._resolve_min_scene_len("detect-hist", min_scene_len) + resolved_min_scene_len = self._resolve_min_scene_len("detect-hist", min_scene_len) return { "bins": self.config.get_value("detect-hist", "bins", bins), - "min_scene_len": min_scene_len_frames, + "min_scene_len": resolved_min_scene_len, "threshold": self.config.get_value("detect-hist", "threshold", threshold), } @@ -537,7 +557,12 @@ def _initialize_logging( # Initialize logger with the set CLI args / user configuration. init_logger(log_level=curr_verbosity, show_stdout=not self.quiet_mode, log_file=logfile) - def _open_stdin_stream(self, frame_rate: float | None, backend: str | None): + def _open_stdin_stream( + self, + frame_rate: float | None, + backend: str | None, + frame_numbering: FrameNumbering = FrameNumbering.RELATIVE, + ): if backend not in (None, "pyav") or VideoStreamAv is None: raise click.BadParameter( "--stdin requires the pyav backend. Install it with `pip install av`.", @@ -549,13 +574,14 @@ def _open_stdin_stream(self, frame_rate: float | None, backend: str | None): "--stdin requires a video to be piped to the program.", param_hint="--stdin" ) self.use_stdin = True - self._open_video_stream(None, frame_rate, "pyav") + self._open_video_stream(None, frame_rate, "pyav", frame_numbering=frame_numbering) def _open_video_stream( self, input_path: str | None, frame_rate: float | None, backend: str | None, + frame_numbering: FrameNumbering = FrameNumbering.RELATIVE, ): input_hint = "--stdin" if self.use_stdin else "-i/--input" if input_path is not None and "%" in input_path and backend != "opencv": @@ -579,6 +605,7 @@ def _open_video_stream( # _PipeReader only implements the part of BinaryIO that PyAV uses. ty.cast(ty.BinaryIO, _PipeReader(sys.stdin.buffer)), frame_rate=frame_rate, + frame_numbering=frame_numbering, name="stdin", threading_mode=self.config.get_value("backend-pyav", "threading-mode"), suppress_output=self.config.get_value("backend-pyav", "suppress-output"), @@ -587,6 +614,7 @@ def _open_video_stream( self.video_stream = open_video( path=input_path, frame_rate=frame_rate, + frame_numbering=frame_numbering, backend=backend, threading_mode=self.config.get_value("backend-pyav", "threading-mode"), suppress_output=self.config.get_value("backend-pyav", "suppress-output"), @@ -595,6 +623,7 @@ def _open_video_stream( self.video_stream = open_video( path=input_path, frame_rate=frame_rate, + frame_numbering=frame_numbering, backend=backend, max_decode_attempts=self.config.get_value( "backend-opencv", "max-decode-attempts" @@ -606,20 +635,30 @@ def _open_video_stream( path=input_path, frame_rate=frame_rate, backend=backend, + frame_numbering=frame_numbering, ) if not self.video_stream.name: logger.warning( "Could not determine a video name from the input path, so $VIDEO_NAME will be" " empty in output filenames." ) + duration_str = "unknown" duration = self.video_stream.duration - duration_str = f"{duration} ({duration.frame_num} frames)" if duration else "unknown" + if duration is not None: + duration_str = Timecode( + pts=duration.numerator, + time_base=Fraction(1, duration.denominator), + ).get_timecode() + frame_count = self.video_stream.frame_count + frame_count_str = str(frame_count) if frame_count is not None else "unknown" + rate = self.video_stream.frame_rate logger.debug(f"""Video information: Backend: {type(self.video_stream).__name__} Resolution: {self.video_stream.frame_size} Frame rate: {float(rate):.3f} ({rate.numerator}/{rate.denominator}) - Duration: {duration_str}""") + Duration: {duration_str} + Frame count: {frame_count_str}""") except FrameRateUnavailable as ex: if DEBUG_MODE: diff --git a/scenedetect/_cli/controller.py b/scenedetect/_cli/controller.py index 329d5685..bc810cec 100644 --- a/scenedetect/_cli/controller.py +++ b/scenedetect/_cli/controller.py @@ -16,13 +16,19 @@ import os import time import warnings +from fractions import Fraction from scenedetect._cli.context import CliContext from scenedetect.backends import VideoStreamCv2, VideoStreamMoviePy -from scenedetect.common import FrameTimecode +from scenedetect.common import ( + FramePosition, + PositionPair, + Timecode, + parse_frame_or_time, +) from scenedetect.platform import get_and_create_path -from scenedetect.scene_manager import CutList, SceneList, get_scenes_from_cuts -from scenedetect.video_stream import SeekError +from scenedetect.scene_manager import CutList, SceneList +from scenedetect.video_stream import FrameNumbering, SeekError logger = logging.getLogger("pyscenedetect") @@ -55,6 +61,7 @@ def run_scenedetect(context: CliContext) -> bool: if context.stats_file_path: logger.warning("WARNING: -s/--stats will be ignored due to load-scenes.") scenes, cuts = _load_scenes(context) + context.start_pos = scenes[0][0] if scenes else None scenes = _postprocess_scene_list(context, scenes) logger.info("Loaded %d scenes.", len(scenes)) else: @@ -63,6 +70,7 @@ def run_scenedetect(context: CliContext) -> bool: if result is None: return False scenes, cuts = result + context.start_pos = scenes[0][0] if scenes else None scenes = _postprocess_scene_list(context, scenes) # Handle -s/--stats option. _save_stats(context) @@ -70,8 +78,10 @@ def run_scenedetect(context: CliContext) -> bool: logger.info( "Detected %d scenes, average shot length %.1f seconds.", len(scenes), - sum([(end_time - start_time).seconds for start_time, end_time in scenes]) - / float(len(scenes)), + float( + sum((end_pos - start_pos).elapsed for start_pos, end_pos in scenes) + / len(scenes) + ), ) else: logger.info("No scenes detected.") @@ -83,25 +93,27 @@ def run_scenedetect(context: CliContext) -> bool: def _postprocess_scene_list(context: CliContext, scene_list: SceneList) -> SceneList: + if context.min_scene_len is None: + return scene_list + minimum = parse_frame_or_time(context.min_scene_len) + if minimum == 0: + return scene_list + + def is_short(scene: PositionPair): + start_pos, end_pos = scene + if isinstance(minimum, int): + return end_pos.frame_number - start_pos.frame_number < minimum + return (end_pos - start_pos).elapsed < minimum + # Handle --merge-last-scene. If set, when the last scene is shorter than --min-scene-len, # it will be merged with the previous one. - if ( - context.merge_last_scene - and context.min_scene_len is not None - and context.min_scene_len > 0 - and len(scene_list) > 1 - and (scene_list[-1][1] - scene_list[-1][0]) < context.min_scene_len - ): + if context.merge_last_scene and len(scene_list) > 1 and is_short(scene_list[-1]): new_last_scene = (scene_list[-2][0], scene_list[-1][1]) scene_list = [*scene_list[:-2], new_last_scene] # Handle --drop-short-scenes. - if ( - context.drop_short_scenes - and context.min_scene_len is not None - and context.min_scene_len > 0 - ): - scene_list = [s for s in scene_list if (s[1] - s[0]) >= context.min_scene_len] + if context.drop_short_scenes: + scene_list = [s for s in scene_list if not is_short(s)] return scene_list @@ -112,24 +124,70 @@ def _detect(context: CliContext) -> tuple[SceneList, CutList] | None: assert context.video_stream is not None assert context.frame_skip is not None + # Reject start times past EOF before any backend seeks. OpenCV/PyAV previously + # continued and produced inconsistent errors; MoviePy raised SeekError (#380). + if context.start_time is not None: + if isinstance(context.start_time, int): + frame_count = context.video_stream.frame_count + beyond_end = frame_count is not None and context.start_time >= frame_count + else: + video_duration = context.video_stream.duration + beyond_end = video_duration is not None and context.start_time.seconds >= video_duration + if beyond_end: + logger.critical("start time is beyond the end of the video") + return None + if ( + isinstance(context.start_time, Timecode) + and isinstance(context.end_time, int) + and context.video_stream is not None + and context.video_stream.frame_numbering is FrameNumbering.RELATIVE + ): + logger.critical( + "An integer --end with a timestamp --start requires --frame-numbering source. " + "Use a timestamp --end or --duration with relative numbering." + ) + return None + context.ensure_detector() if context.start_time is not None: + target_description = ( + f"frame {context.start_time}" + if isinstance(context.start_time, int) + else context.start_time.get_timecode() + ) logger.debug("Seeking to start time...") try: context.video_stream.seek(target=context.start_time) except SeekError as ex: - logger.critical( - "Failed to seek to %s / frame %d: %s", - context.start_time.get_timecode(), - context.start_time.frame_num, - str(ex), - ) + logger.critical("Failed to seek to %s: %s", target_description, ex) + return None + + if context.video_stream.peek_timecode() is None: + logger.critical("No frames available at requested start %s.", target_description) + return None + + end_time = context.end_time + if ( + isinstance(context.start_time, int) + and isinstance(end_time, int) + and context.video_stream.frame_numbering is FrameNumbering.RELATIVE + ): + # Relative seek resets frame number to 0, so we count till end_time - start_time + end_time -= context.start_time + if end_time is not None: + if isinstance(end_time, int): + empty_range = context.video_stream.frame_number + 1 >= end_time + else: + first_timecode = context.video_stream.peek_timecode() + empty_range = first_timecode is not None and first_timecode.seconds >= end_time.seconds + if empty_range: + logger.critical("No frames fall within the requested detection range.") return None num_frames = context.scene_manager.detect_scenes( video=context.video_stream, duration=context.duration, - end_time=context.end_time, + end_time=end_time, frame_skip=context.frame_skip, show_progress=not context.quiet_mode, ) @@ -188,48 +246,134 @@ def _save_stats(context: CliContext) -> None: def _load_scenes(context: CliContext) -> tuple[SceneList, CutList]: assert context.load_scenes_input - assert context.load_scenes_column_name is not None - assert context.video_stream is not None + assert context.load_scenes_columns assert os.path.exists(context.load_scenes_input) - video_stream = context.video_stream - with open(context.load_scenes_input) as input_file: - file_reader = csv.reader(input_file) - csv_headers = next(file_reader) - if context.load_scenes_column_name not in csv_headers: - csv_headers = next(file_reader) - # Check to make sure column headers are present and then load the data. - if context.load_scenes_column_name not in csv_headers: - raise ValueError("specified column header for scene start is not present") - col_idx = csv_headers.index(context.load_scenes_column_name) - - def calculate_timecode(value: str) -> FrameTimecode: - # Assume other columns are in seconds except frame numbers. - if value.isdigit(): - # Frame numbers start from index 1 in the CLI output so we correct for that. - return FrameTimecode(int(value) - 1, fps=video_stream.frame_rate) - return FrameTimecode(value, fps=video_stream.frame_rate) - - cut_list = sorted(calculate_timecode(row[col_idx]) for row in file_reader) - # `SceneDetector` works on cuts, so we have to skip the first scene and place the first - # cut point where the next scenes starts. - if cut_list: - cut_list = cut_list[1:] - - start_time = context.video_stream.base_timecode - if context.start_time is not None: - start_time = context.start_time - cut_list = [cut for cut in cut_list if cut > context.start_time] - - video_duration = context.video_stream.duration - assert video_duration is not None - end_time = video_duration - if context.end_time is not None: - end_time = min(context.end_time, video_duration) - elif context.duration is not None: - end_time = min(start_time + context.duration, video_duration) - - cut_list = [cut for cut in cut_list if cut < end_time] - scene_list = get_scenes_from_cuts(cut_list=cut_list, start_pos=start_time, end_pos=end_time) - - return (scene_list, cut_list) + columns = context.load_scenes_columns + scene_list: SceneList = [] + with open(context.load_scenes_input, newline="", encoding="utf-8-sig") as input_file: + reader = csv.DictReader(input_file) + if reader.fieldnames and reader.fieldnames[0] == "Timecode List:": + reader = csv.DictReader(input_file) + + missing_columns = set(columns.values()) - set(reader.fieldnames or []) + if missing_columns: + raise ValueError(f"Missing scene columns: {', '.join(sorted(missing_columns))}") + + for row in reader: + if any(row[column] is None for column in columns.values()): + raise ValueError("Scene row is missing a required boundary value.") + + start_frame = int(row[columns["start_frame"]]) - 1 + end_frame = int(row[columns["end_frame"]]) + start_seconds = _parse_csv_seconds(row[columns["start_time"]]) + end_seconds = _parse_csv_seconds(row[columns["end_time"]]) + + if start_frame < 0 or end_frame <= start_frame: + raise ValueError("Invalid scene frame range.") + if end_seconds < start_seconds: + raise ValueError("Scene end time precedes its start time.") + + start = FramePosition( + timecode=Timecode( + start_seconds.numerator, + Fraction(1, start_seconds.denominator), + ), + frame_number=start_frame, + ) + end = FramePosition( + timecode=Timecode( + end_seconds.numerator, + Fraction(1, end_seconds.denominator), + ), + frame_number=end_frame, + ) + scene_list.append((start, end)) + + if not scene_list: + return [], [] + + start_limit = ( + parse_frame_or_time(context.start_time) if context.start_time is not None else None + ) + stop_limit = parse_frame_or_time(context.end_time) if context.end_time is not None else None + length = parse_frame_or_time(context.duration) if context.duration is not None else None + + if length == 0: + return [], [] + + if length is not None: + if start_limit is None: + origin = ( + scene_list[0][0].frame_number + if isinstance(length, int) + else scene_list[0][0].timecode.seconds + ) + elif (isinstance(start_limit, int) and isinstance(length, int)) or ( + isinstance(start_limit, Fraction) and isinstance(length, Fraction) + ): + origin = start_limit + else: + matches = { + (position.frame_number, position.timecode.seconds) + for scene in scene_list + for position in scene + if ( + position.frame_number + if isinstance(start_limit, int) + else position.timecode.seconds + ) + == start_limit + } + if len(matches) != 1: + raise ValueError( + "Cannot convert the requested start to the duration's units: " + "the CSV has no unique saved position for it." + ) + + frame_number, seconds = next(iter(matches)) + origin = frame_number if isinstance(length, int) else seconds + + stop_limit = origin + length + + selected: SceneList = [] + for start, end in scene_list: + if start_limit is not None: + left = start.frame_number if isinstance(start_limit, int) else start.timecode.seconds + right = end.frame_number if isinstance(start_limit, int) else end.timecode.seconds + + # Retain a zero-elapsed row exactly at the requested start. + if right < start_limit or (right == start_limit and left < right): + continue + if left < start_limit < right: + raise ValueError( + "The requested range would split a saved scene. " + "The CSV does not contain the complete position for that cutoff." + ) + + if stop_limit is not None: + left = start.frame_number if isinstance(stop_limit, int) else start.timecode.seconds + right = end.frame_number if isinstance(stop_limit, int) else end.timecode.seconds + + if left >= stop_limit: + continue + if left < stop_limit < right: + raise ValueError( + "The requested range would split a saved scene. " + "The CSV does not contain the complete position for that cutoff." + ) + + selected.append((start, end)) + + cut_list = [start for start, _ in selected[1:]] + return selected, cut_list + + +def _parse_csv_seconds(value: str) -> Fraction: + """Parse a CSV time field whose unit is already known.""" + value = value.strip() + if ":" in value: + sign = -1 if value.startswith("-") else 1 + text = value[1:] if sign < 0 else value + return sign * Fraction(parse_frame_or_time(text)) + return Fraction(value.removesuffix("s")) diff --git a/scenedetect/_fan_out.py b/scenedetect/_fan_out.py index 0d8883a3..d1b9873d 100644 --- a/scenedetect/_fan_out.py +++ b/scenedetect/_fan_out.py @@ -14,8 +14,8 @@ Used by the benchmark sweep harness to amortize video decoding across multiple detector configurations running in parallel: one source decode feeds N consumer streams, each read by an independent detection thread. The source is paced by the slowest consumer -(blocking ``put`` into bounded per-consumer queues), so peak memory is bounded by -``n * prefetch`` frames. +(blocking ``put`` into bounded per-consumer queues). Each consumer can also retain one +queued frame for ``peek_timecode()`` without copying its image. Internal API (underscore-prefixed module). Not part of the public surface. """ @@ -29,7 +29,7 @@ import numpy as np -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, Timecode, TimecodeLike from scenedetect.video_stream import SeekError, VideoStream _EOF = object() @@ -63,9 +63,10 @@ def __init__(self, source: VideoStream, n: int, prefetch: int = 4): Arguments: source: Already-opened ``VideoStream`` to read from. n: Number of consumer streams to expose. Must be >= 1. - prefetch: Per-consumer queue depth. ``0`` is rendezvous (every frame waits - for every consumer to take it); 4-8 absorbs jitter between consumers - at the cost of up to ``n * prefetch`` resident frames. + prefetch: Per-consumer queue depth. ``0`` uses a one-item queue. + Values of 4-8 absorb jitter between consumers. Queue capacity is + ``n * max(1, prefetch)`` items in total. Each consumer may also hold + one pending item for peeking. """ if n < 1: raise ValueError("n must be at least 1") @@ -126,11 +127,14 @@ def _read_loop(self) -> None: frame = self._source.read() if frame is False: break + position = self._source.position + assert position is not None + item = (frame, position) # Block per-consumer; slowest consumer paces the source. for q in self._queues: while not self._stop.is_set(): try: - q.put(frame, timeout=0.1) + q.put(item, timeout=0.1) break except queue.Full: continue @@ -161,15 +165,19 @@ class _FanOutConsumer(VideoStream): Maintains its own ``frame_number`` / ``position`` -- both advance only when this consumer calls ``read()``, independent of the source's position or sibling consumers. + + Each consumer preserves the source's frame positions and numbering mode. """ BACKEND_NAME = "fan_out" def __init__(self, parent: FanOutVideoStream, index: int): + super().__init__(frame_numbering=parent._source.frame_numbering) + self._position = parent._source.position self._parent = parent self._index = index - self._frame_number = 0 self._eof = False + self._pending_item: tuple[np.ndarray, FramePosition] | None = None @property def path(self) -> str: @@ -188,9 +196,13 @@ def frame_rate(self) -> Fraction: return self._parent._source.frame_rate @property - def duration(self) -> FrameTimecode | None: + def duration(self) -> Fraction | None: return self._parent._source.duration + @property + def frame_count(self) -> int | None: + return self._parent._source.frame_count + @property def frame_size(self) -> tuple[int, int]: return self._parent._source.frame_size @@ -203,38 +215,39 @@ def aspect_ratio(self) -> float: def decode_failures(self) -> int: return self._parent._source.decode_failures - @property - def frame_number(self) -> int: - return self._frame_number - - @property - def position(self) -> FrameTimecode: - # Mirrors VideoStream contract: "frame 1 corresponds to presentation time 0; - # returns 0 even if frame_number is 1." - n = max(0, self._frame_number - 1) - return FrameTimecode(timecode=n, fps=self.frame_rate) - - @property - def position_ms(self) -> float: - if self._frame_number == 0: - return 0.0 - fps = self.frame_rate - return float(1000 * (self._frame_number - 1) * fps.denominator) / float(fps.numerator) - - def read(self, decode: bool = True) -> np.ndarray | bool: + def _next_item(self) -> tuple[np.ndarray, FramePosition] | None: + if self._pending_item: + item = self._pending_item + self._pending_item = None + return item if self._eof: - return False + return None item = self._parent._queues[self._index].get() if item is _EOF: self._eof = True if self._parent._reader_exc is not None: raise self._parent._reader_exc + return None + return item + + def read(self, decode: bool = True) -> np.ndarray | bool: + item = self._next_item() + if item is None: return False - self._frame_number += 1 + frame, position = item + self._position = position # The source already decoded the frame; decode=False just suppresses returning it. if not decode: return True - return item # type: ignore[return-value] + return frame # type: ignore[return-value] + + def peek_timecode(self) -> Timecode | None: + """Return the next queued frame's timestamp without advancing this consumer's position.""" + if self._pending_item is None: + self._pending_item = self._next_item() + if self._pending_item is None: + return None + return self._pending_item[1].timecode def reset(self) -> None: raise SeekError("FanOutVideoStream consumers are forward-only; reset the source instead.") diff --git a/scenedetect/backends/concat.py b/scenedetect/backends/concat.py index 386ed866..38565569 100644 --- a/scenedetect/backends/concat.py +++ b/scenedetect/backends/concat.py @@ -12,7 +12,7 @@ """``scenedetect.backends.concat`` Module :class:`VideoStreamConcat` presents multiple videos as a single, contiguous -:class:`VideoStream ` with a monotonic PTS-based +:class:`VideoStream ` with a global PTS-based timeline. Frames are decoded through any available backend, so the concatenation logic is backend-agnostic. The easiest way to construct one is by passing a list of paths to :func:`scenedetect.open_video`: @@ -24,8 +24,8 @@ The resulting stream can be used anywhere a single-video stream can, e.g. with a :class:`SceneManager `. All videos must have the same -resolution. Framerates may differ, in which case reported frame numbers may be inaccurate - -use `position` for accurate PTS-based timing. +resolution. Framerates may differ. Frame ordinals follow the decoded sequence across input +boundaries; `position` contains each frame's timestamp on the global timeline. :meth:`VideoStreamConcat.map_span` maps a span of the global timeline back to per-source local times (e.g. for use as ffmpeg `-ss`/`-t` arguments). @@ -40,15 +40,12 @@ import numpy as np -from scenedetect.common import FrameRate, FrameTimecode, Timecode, TimecodeLike +from scenedetect.common import FrameRate, Timecode, TimecodeLike, parse_frame_or_time from scenedetect.platform import StrPath -from scenedetect.video_stream import VideoOpenFailure, VideoStream +from scenedetect.video_stream import FrameNumbering, SeekError, VideoOpenFailure, VideoStream logger = logging.getLogger("pyscenedetect") -_GLOBAL_TIME_BASE = Fraction(1, 1000000) -"""Time base used for the global (concatenated) timeline.""" - FRAMERATE_DELTA_TOLERANCE: float = 0.1 """Tolerance in frames/sec above which a framerate mismatch between inputs is warned about.""" @@ -60,34 +57,30 @@ class _SourceMetadata: path: Path frame_size: tuple[int, int] frame_rate: Fraction - duration: Fraction - """Declared duration of the video in seconds (exact rational value). May be inaccurate; - the global timeline is corrected once the actual end of the source is reached.""" - frames: int - """Declared number of frames in the video. May be inaccurate.""" + duration: Fraction | None + """Declared duration of the video in seconds, or None if unavailable. May be inaccurate; + later source offsets may be extended when decoding reaches this source's end.""" + frame_count: int | None + """Reported total source frame count, or None if unavailable.""" aspect_ratio: float @dataclass(frozen=True) class SourceSpan: """Portion of a single input video covered by a time span on the global timeline of a - :class:`VideoStreamConcat`. Local times are relative to the start of that video, directly - usable as seek targets or ffmpeg `-ss`/`-t` values.""" + :class:`VideoStreamConcat`. The interval [local_start, local_end) is relative to that video's + start. Use local_start as a seek target or ffmpeg `-ss` value; the elapsed time between the + endpoints gives the `-t` value.""" source_index: int path: Path - local_start: FrameTimecode - local_end: FrameTimecode - - -def _exact_seconds(timecode: FrameTimecode) -> Fraction: - """Time represented by `timecode` as an exact rational number of seconds.""" - return Fraction(timecode.pts) * timecode.time_base + local_start: Timecode + local_end: Timecode class VideoStreamConcat(VideoStream): """Concatenates multiple videos into a single, contiguous video stream with a - monotonic PTS-based global timeline. + PTS-based global timeline. The concatenation logic is backend-agnostic: frames are read through any PySceneDetect `VideoStream` backend, selected by name (default `opencv`). For the most accurate seam @@ -104,6 +97,7 @@ def __init__( paths: ty.Sequence[StrPath], frame_rate: FrameRate | None = None, backend: str = "opencv", + frame_numbering: FrameNumbering = FrameNumbering.RELATIVE, **kwargs, ): """Open a list of videos as one continuous stream. @@ -114,6 +108,8 @@ def __init__( backend: Name of the backend to decode each input with (see :data:`scenedetect.backends.AVAILABLE_BACKENDS`). Falls back to OpenCV if unavailable. + frame_numbering: RELATIVE (default) restarts ordinals at 0 after seeking. + SOURCE counts frames from the beginning of the concatenated stream. kwargs: Optional named arguments to pass to every child backend constructor. Raises: @@ -121,7 +117,7 @@ def __init__( VideoOpenFailure: A video could not be opened, or resolutions don't match. """ assert paths - super().__init__() + super().__init__(frame_numbering=frame_numbering) # Import here to avoid a circular import (scenedetect.backends imports this module). from scenedetect.backends import AVAILABLE_BACKENDS @@ -143,15 +139,13 @@ def __init__( try: for index in range(len(self._paths)): cap = self._open_source(index) - duration = cap.duration - declared_seconds = _exact_seconds(duration) if duration is not None else Fraction(0) self._sources.append( _SourceMetadata( path=self._paths[index], frame_size=cap.frame_size, frame_rate=cap.frame_rate, - duration=declared_seconds, - frames=duration.frame_num if duration is not None else 0, + duration=cap.duration, + frame_count=cap.frame_count, aspect_ratio=cap.aspect_ratio, ) ) @@ -170,15 +164,17 @@ def __init__( # Global start time of each source in exact rational seconds. Has one extra entry at # the end holding the total (declared) duration. Values after the current source are - # estimates from declared durations, and are corrected once the actual end of each - # source is reached during decode. + # estimates from declared durations, and may be extended using an estimated end time + # when each source reaches EOF. self._offsets: list[Fraction] = [Fraction(0)] for source in self._sources: - self._offsets.append(self._offsets[-1] + source.duration) + # Preserve the existing zero placeholder for unknown source offsets. + duration = source.duration if source.duration is not None else Fraction(0) + self._offsets.append(self._offsets[-1] + duration) self._index: int = 0 - self._frames_prior: int = 0 self._decode_failures_prior: int = 0 + self._pending_frame: np.ndarray | None = None assert first_cap is not None self._cap: VideoStream = first_cap @@ -204,8 +200,8 @@ def _validate_sources(self): ) if abs(float(source.frame_rate) - float(first.frame_rate)) > FRAMERATE_DELTA_TOLERANCE: logger.warning( - "Framerate of %s does not match the first input. Timing is based on " - "presentation timestamps, but reported frame numbers may be inaccurate.", + "Framerate of %s does not match the first input. The reported frame rate " + "is taken from the first input; timestamps use each input backend's timing.", source.path.name, ) @@ -222,14 +218,19 @@ def _switch_source(self, index: int): def _child_position_seconds(self) -> Fraction: """Position of the current source as exact rational seconds (local timeline).""" - return _exact_seconds(self._cap.position) + position = self._cap.position + assert position is not None + timecode = position.timecode + return timecode.seconds def _finish_current_source(self): - """Correct the declared offset of the next source now that the actual end of the - current source is known, guaranteeing strictly monotonic PTS across the seam even - when the declared duration is inaccurate.""" + """Extend later source offsets when the estimated end exceeds the declared duration. + + Estimate the end from the last observed timestamp plus one frame at the child's rate. + """ self._decode_failures_prior += self._cap.decode_failures - self._frames_prior += self._cap.frame_number + if self._cap.position is None: + return actual_end = ( self._offsets[self._index] + self._child_position_seconds() @@ -241,46 +242,163 @@ def _finish_current_source(self): for i in range(self._index + 1, len(self._offsets)): self._offsets[i] += delta - def read(self, decode: bool = True) -> np.ndarray | bool: - """Read/decode the next frame. Returns False when all inputs have been processed.""" - self._check_open() + def _current_timecode(self) -> Timecode: + """Current position on the global timeline as a Timecode.""" + seconds = self._offsets[self._index] + self._child_position_seconds() + return Timecode(pts=seconds.numerator, time_base=Fraction(1, seconds.denominator)) + + def _open_next_source(self) -> bool: + if (self._index + 1) >= len(self._paths): + logger.debug("No more input to process.") + return False + self._finish_current_source() + self._index += 1 + logger.debug("Processing complete, opening next video: %s", self._paths[self._index]) + self._switch_source(self._index) + return True + + def _read_next_frame(self, decode: bool = True) -> np.ndarray | bool: + """Read/decode the next frame. Returns False when all inputs have been processed. + + Consume a pending seek image before reading from a child. Does not record a global + frame position. + """ + if self._pending_frame is not None: + frame = self._pending_frame + self._pending_frame = None + return frame if decode else True while True: result = self._cap.read(decode=decode) if result is not False: return result - if (self._index + 1) >= len(self._paths): - logger.debug("No more input to process.") + if not self._open_next_source(): return False - self._finish_current_source() - self._index += 1 - logger.debug("Processing complete, opening next video: %s", self._paths[self._index]) - self._switch_source(self._index) + + def read(self, decode: bool = True) -> np.ndarray | bool: + self._check_open() + result = self._read_next_frame(decode=decode) + if result is False: + return False + self._record_frame(self._current_timecode()) + return result + + def peek_timecode(self) -> Timecode | None: + """Return the next frame's global timecode without recording a position.""" + self._check_open() + if self._pending_frame is not None: + return self._current_timecode() + + while True: + timecode = self._cap.peek_timecode() + if timecode is not None: + seconds = self._offsets[self._index] + timecode.seconds + return Timecode( + pts=seconds.numerator, + time_base=Fraction(1, seconds.denominator), + ) + + if not self._open_next_source(): + return None def seek(self, target: TimecodeLike): """Seek to `target` on the global timeline. Supports seeking across sources in - either direction.""" + either direction. + + Integer targets are zero-based source ordinals reached by sequential reading. For + example, `seek(4)` followed by `read()` reads the fifth frame, with ordinal 0 in + RELATIVE mode or 4 in SOURCE mode. + + SOURCE time seeks count preceding frames sequentially. RELATIVE time seeks use native + child seeking and the currently known source offsets, which may depend on declared + durations. If the child raises SeekError and another source exists, replay the selected + child and continue across source boundaries. Preroll retains the first image encountered + at or after the requested time for the next read. Timestamp and seek accuracy depend on + the child backend. + A successful seek restarts RELATIVE numbering at 0 without resetting frame timestamps. + + Arguments: + target: A zero-based source ordinal (int or digit-only string), or a time + (float seconds, timecode string, or Timecode). + + Raises: + SeekError: Seeking is unsupported or the requested position cannot be reached. + OSError: A child backend fails to open, seek, or read an input. + TypeError: The target type is unsupported. + ValueError: The target is negative, non-finite, or malformed, or has an invalid + time base. + """ + self._check_open() - if not isinstance(target, FrameTimecode): - target = FrameTimecode(target, self.frame_rate) - if target < 0: + + if not self.is_seekable: + raise SeekError("Seeking is not supported for this video stream.") + + parsed = parse_frame_or_time(target) + if parsed < 0: raise ValueError("Target seek position cannot be negative!") - target_seconds = _exact_seconds(target) - # Find the last source which starts at or before the target. - index = bisect.bisect_right(self._offsets, target_seconds) - 1 - index = max(0, min(index, len(self._paths) - 1)) - if index != self._index: - self._decode_failures_prior += self._cap.decode_failures - self._frames_prior = sum(source.frames for source in self._sources[:index]) - self._index = index - self._switch_source(index) - local_seconds = target_seconds - self._offsets[index] - self._cap.seek(float(local_seconds)) + + if isinstance(parsed, Fraction): + if self._frame_numbering is FrameNumbering.SOURCE: + position = self.position + if position is not None and position.timecode.seconds >= parsed: + self.reset() + else: + self._pending_frame = None + target_seconds = parsed + # Find the last source which starts at or before the target. + index = bisect.bisect_right(self._offsets, target_seconds) - 1 + index = max(0, min(index, len(self._paths) - 1)) + if index != self._index: + self._decode_failures_prior += self._cap.decode_failures + self._index = index + self._switch_source(index) + local_seconds = target_seconds - self._offsets[index] + try: + self._cap.seek( + Timecode( + pts=local_seconds.numerator, + time_base=Fraction(1, local_seconds.denominator), + ) + ) + except SeekError: + if self._index + 1 >= len(self._paths): + raise + self._cap.reset() + else: + self._position = None + return + + while True: + result = self._read_next_frame() + if result is False: + raise SeekError("Could not reach the requested time.") + + timecode = self._current_timecode() + if timecode.seconds >= parsed: + assert isinstance(result, np.ndarray) + self._pending_frame = result + if self.frame_numbering is FrameNumbering.RELATIVE: + self._position = None + return + if self.frame_numbering is FrameNumbering.SOURCE: + self._record_frame(timecode) + else: + if self._frame_numbering is FrameNumbering.RELATIVE or parsed <= self.frame_number: + self.reset() + + for _ in range(self.frame_number + 1, parsed): + if self._read_next_frame(decode=False) is False: + raise SeekError("Could not reach the requested frame.") + if self.frame_numbering is FrameNumbering.SOURCE: + self._record_frame(self._current_timecode()) + return def reset(self): """Close and re-open the stream (equivalent to seeking back to the beginning).""" self._check_open() self._index = 0 - self._frames_prior = 0 + self._position = None + self._pending_frame = None self._decode_failures_prior = 0 self._switch_source(0) @@ -291,6 +409,7 @@ def close(self) -> None: if self._closed: return self._closed = True + self._pending_frame = None self._cap.close() # @@ -315,19 +434,24 @@ def is_seekable(self) -> bool: def frame_rate(self) -> Fraction: """Average framerate of the first input video. Individual sources may vary; use `position` for accurate timing.""" - if self._frame_rate_override is not None: - return Fraction(self._frame_rate_override) return self._sources[0].frame_rate @property - def duration(self) -> FrameTimecode: - """Total duration of all input videos combined. May be inaccurate.""" - return FrameTimecode( - timecode=Timecode( - pts=round(self._offsets[-1] / _GLOBAL_TIME_BASE), time_base=_GLOBAL_TIME_BASE - ), - fps=self.frame_rate, - ) + def duration(self) -> Fraction | None: + """Combined duration estimate in seconds, or None if an input duration is unavailable.""" + if any(source.duration is None for source in self._sources): + return None + return self._offsets[-1] + + @property + def frame_count(self) -> int | None: + """Combined reported frame count, or None if an input count is unavailable.""" + total = 0 + for source in self._sources: + if source.frame_count is None: + return None + total += source.frame_count + return total @property def frame_size(self) -> tuple[int, int]: @@ -338,28 +462,6 @@ def frame_size(self) -> tuple[int, int]: def aspect_ratio(self) -> float: return self._sources[0].aspect_ratio - @property - def position(self) -> FrameTimecode: - """Presentation time of the last-read frame on the global timeline (the first frame - of the first video has a presentation time of 0).""" - global_seconds = self._offsets[self._index] + self._child_position_seconds() - return FrameTimecode( - timecode=Timecode( - pts=round(global_seconds / _GLOBAL_TIME_BASE), time_base=_GLOBAL_TIME_BASE - ), - fps=self.frame_rate, - ) - - @property - def position_ms(self) -> float: - """Presentation time of the last-read frame in milliseconds on the global timeline.""" - return float((self._offsets[self._index] + self._child_position_seconds()) * 1000) - - @property - def frame_number(self) -> int: - """Number of frames read so far across all sources.""" - return self._frames_prior + self._cap.frame_number - @property def decode_failures(self) -> int: """Number of frames which failed to decode across all sources.""" @@ -379,11 +481,19 @@ def child_backend(self) -> str: """Name of the backend used to decode each input video.""" return self._cap.BACKEND_NAME - def map_span(self, start: FrameTimecode, end: FrameTimecode) -> list[SourceSpan]: + def map_span(self, start: Timecode, end: Timecode) -> list[SourceSpan]: """Map a time span on the global timeline to the input video(s) covering it. - A span which straddles one or more file boundaries yields multiple entries.""" - start_seconds = _exact_seconds(start) - end_seconds = _exact_seconds(end) + A span which straddles one or more file boundaries yields multiple entries. + + Treat [start, end) as a half-open interval and clip it to the currently known source + boundaries. Empty intervals return no spans. Raises ValueError if end precedes start. + """ + start_seconds = start.seconds + end_seconds = end.seconds + if end_seconds < start_seconds: + raise ValueError("Span end must not precede its start.") + if end_seconds == start_seconds: + return [] spans: list[SourceSpan] = [] for index, source in enumerate(self._sources): source_start, source_end = self._offsets[index], self._offsets[index + 1] @@ -393,23 +503,17 @@ def map_span(self, start: FrameTimecode, end: FrameTimecode) -> list[SourceSpan] continue local_start = max(Fraction(0), start_seconds - source_start) local_end = min(source_end - source_start, end_seconds - source_start) + if local_end <= local_start: + continue spans.append( SourceSpan( source_index=index, path=source.path, - local_start=FrameTimecode( - timecode=Timecode( - pts=round(local_start / _GLOBAL_TIME_BASE), - time_base=_GLOBAL_TIME_BASE, - ), - fps=source.frame_rate, + local_start=Timecode( + pts=local_start.numerator, time_base=Fraction(1, local_start.denominator) ), - local_end=FrameTimecode( - timecode=Timecode( - pts=round(local_end / _GLOBAL_TIME_BASE), - time_base=_GLOBAL_TIME_BASE, - ), - fps=source.frame_rate, + local_end=Timecode( + pts=local_end.numerator, time_base=Fraction(1, local_end.denominator) ), ) ) diff --git a/scenedetect/backends/moviepy.py b/scenedetect/backends/moviepy.py index 1718f6c2..89efcb76 100644 --- a/scenedetect/backends/moviepy.py +++ b/scenedetect/backends/moviepy.py @@ -16,6 +16,7 @@ image sequences or AviSynth scripts are supported as inputs. """ +import math import os import time import typing as ty @@ -30,13 +31,13 @@ from scenedetect.backends.opencv import VideoStreamCv2 from scenedetect.common import ( FrameRate, - FrameTimecode, Timecode, TimecodeLike, framerate_to_fraction, + parse_frame_or_time, ) from scenedetect.platform import StrPath, get_file_name -from scenedetect.video_stream import SeekError, VideoOpenFailure, VideoStream +from scenedetect.video_stream import FrameNumbering, SeekError, VideoOpenFailure, VideoStream logger = getLogger("pyscenedetect") @@ -77,6 +78,8 @@ def __init__( frame_rate: FrameRate | None = None, print_infos: bool = False, framerate: float | None = None, + *, + frame_numbering: FrameNumbering = FrameNumbering.RELATIVE, ): """Open a video or device. @@ -87,13 +90,15 @@ def __init__( print_infos: If True, prints information about the opened video to stdout. framerate: [DEPRECATED] Use `frame_rate` instead. Retained as a deprecated alias for backwards compatibility; ignored when `frame_rate` is provided. + frame_numbering: RELATIVE (default) restarts ordinals at 0 after seeking. + SOURCE counts frames from the source beginning. Raises: OSError: file could not be found, access was denied, or the video is corrupt VideoOpenFailure: video could not be opened (may be corrupted) ValueError: specified frame rate is invalid """ - super().__init__() + super().__init__(frame_numbering=frame_numbering) if framerate is not None: warnings.warn( @@ -122,14 +127,10 @@ def __init__( self._reader = _retry_on_oserror( "open", lambda: FFMPEG_VideoReader(self._path, print_infos=print_infos) ) - # This will always be one behind self._reader.lastread when we finally call read() - # as MoviePy caches the first frame when opening the video. Thus self._last_frame - # will always be the current frame, and self._reader.lastread will be the next. - self._last_frame: bool | np.ndarray = False - self._last_frame_rgb: np.ndarray | None = None - # Older versions don't track the video position when calling read_frame so we need - # to keep track of the current frame number. - self._frame_number = 0 + # TODO: Support native VFR timestamps. FFMPEG_VideoReader exposes no per-frame + # PTS, so this backend currently derives timestamps from the frame rate. + # Timestamp of the cached image that the next read will return. + self._next_timecode = Timecode(pts=0, time_base=1 / self.frame_rate) # We need to manually keep track of EOF as duration may not be accurate. self._eof = False self._aspect_ratio: float | None = None @@ -170,10 +171,15 @@ def frame_size(self) -> tuple[int, int]: return tuple(self._reader.infos["video_size"]) @property - def duration(self) -> FrameTimecode | None: - """Duration of the stream as a FrameTimecode, or None if non terminating.""" + def duration(self) -> Fraction | None: + """Reported source duration in seconds.""" assert isinstance(self._reader.infos["duration"], float) - return self.base_timecode + self._reader.infos["duration"] + return Fraction(str(self._reader.infos["duration"])) + + @property + def frame_count(self) -> int | None: + """Unavailable: MoviePy derives its frame count from duration and frame rate.""" + return None @property def aspect_ratio(self) -> float: @@ -189,100 +195,99 @@ def aspect_ratio(self) -> float: self._aspect_ratio = 1.0 return self._aspect_ratio - @property - def position(self) -> FrameTimecode: - """Current position within stream as FrameTimecode. - - This can be interpreted as presentation time stamp of the last frame which was decoded by - calling `read`. This will always return 0 (e.g. be equal to `base_timecode`) if no frames - have been `read` yet.""" - frame_number = max(self._frame_number - 1, 0) - # Synthesize a Timecode from the frame count and rational framerate. - # MoviePy assumes CFR, so this is equivalent to frame-based timing. - # Use the framerate denominator as the time_base denominator for exact timing. - fps = self.frame_rate - time_base = Fraction(1, fps.numerator) - pts = frame_number * fps.denominator - timecode = Timecode(pts=pts, time_base=time_base) - return FrameTimecode(timecode=timecode, fps=fps) - - @property - def position_ms(self) -> float: - """Current position within stream as a float of the presentation time in milliseconds. - The first frame has a time of 0.0 ms. - - This method will always return 0.0 if no frames have been `read`.""" - return self.position.seconds * 1000.0 - - @property - def frame_number(self) -> int: - """Current position within stream in frames as an int. - - 0 indicates that no frames have been `read`, 1 indicates the first frame was just read. - """ - return self._frame_number - def seek(self, target: TimecodeLike): - """Seek to the given timecode. If given as a frame number, represents the current seek - pointer (e.g. if seeking to 0, the next frame decoded will be the first frame of the video). + """Position the next read at a source frame ordinal or a time on the FPS-derived clock. + + Integer targets use sequential reading in both numbering modes. For example, `seek(4)` + followed by `read()` reads the fifth frame. Its ordinal is 0 in RELATIVE mode or 4 in + SOURCE mode. - For 1-based indices (first frame is frame #1), the target frame number needs to be converted - to 0-based by subtracting one. For example, if we want to seek to the first frame, we call - seek(0) followed by read(). If we want to seek to the 5th frame, we call seek(4) followed - by read(), at which point frame_number will be 5. + Time targets select the first frame at or after the requested time on the clock derived + from `frame_rate`. Native per-frame presentation timestamps are not available. RELATIVE + mode uses native MoviePy seeking; SOURCE mode counts the preceding frames sequentially. + A successful seek restarts RELATIVE numbering at 0 without resetting frame timestamps. Not supported if the VideoStream is a device/camera. Untested with web streams. Arguments: - target: Target position in video stream to seek to. - If float, interpreted as time in seconds. - If int, interpreted as frame number. + target: A zero-based source ordinal (int or digit-only string), or a time + (float seconds, timecode string, or Timecode). Raises: - SeekError: An error occurs while seeking, or seeking is not supported. - ValueError: `target` is not a valid value (i.e. it is negative), or the stream is - closed. + SeekError: The target cannot be reached, or seeking is not supported. + OSError: MoviePy fails while seeking. + TypeError: The target type is unsupported. + ValueError: The target is negative, non-finite, or malformed, or has an invalid + time base. """ + self._check_open() - success = False - if not isinstance(target, FrameTimecode): - target = FrameTimecode(target, self.frame_rate) - duration = self.duration - assert duration is not None - try: - self._last_frame = _retry_on_oserror( - "seek", lambda: self._reader.get_frame(target.seconds) - ) - if hasattr(self._reader, "last_read") and target >= duration: - raise SeekError("MoviePy > 2.0 does not have proper EOF semantics (#461).") - self._frame_number = min( - target.frame_num, - FrameTimecode(self._reader.infos["duration"], self.frame_rate).frame_num - 1, - ) - success = True - except OSError as ex: - # TODO(https://scenedetect.com/issues/380): Other backends do not currently throw an - # exception if attempting to seek past EOF. - # - # We need to ensure consistency for seeking past end of video with respect to errors and - # behaviour, and should probably gracefully stop at the last frame instead of throwing. - if target >= duration: - raise SeekError("Target frame is beyond end of video!") from ex - raise - finally: - # Leave the object in a valid state on any errors. - if not success: + + if not self.is_seekable: + raise SeekError("Seeking is not supported for this video stream!") + + parsed = parse_frame_or_time(target) + if parsed < 0: + raise ValueError(f"Target frame/timecode ({target}) is negative!") + + if isinstance(parsed, Fraction): + target_frame = math.ceil(parsed * self.frame_rate) + if self.frame_numbering is FrameNumbering.SOURCE: + self.seek(target_frame) + if self._eof: + raise SeekError("Could not seek to the requested frame") + return + + reader_time = target_frame / self._reader.fps + success = False + duration = self._reader.infos["duration"] + try: + # MoviePy 1.x does not update pos during direct read_frame() calls. + self._reader.pos = self._next_timecode.pts + 1 + _retry_on_oserror("seek", lambda: self._reader.get_frame(reader_time)) + if hasattr(self._reader, "last_read") and reader_time >= duration: + raise SeekError("MoviePy > 2.0 does not have proper EOF semantics (#461).") + self._next_timecode = Timecode(pts=target_frame, time_base=1 / self.frame_rate) + self._position = None + self._eof = False + success = True + except OSError as ex: + # TODO(https://scenedetect.com/issues/380): Other backends do not currently throw an + # exception if attempting to seek past EOF. + # + # We need to ensure consistency for seeking past end of video with respect to errors + # and behaviour, and should probably gracefully stop at the last frame instead of + # throwing. + if reader_time >= duration: + raise SeekError("Target frame is beyond end of video!") from ex + raise + finally: + # Leave the object in a valid state on any errors. + if not success: + self.reset() + + else: + if self.frame_numbering is FrameNumbering.RELATIVE or parsed <= self.frame_number: self.reset() + for _ in range(self.frame_number + 1, parsed): + item = self._read_next_frame() + if item is None: + raise SeekError("Could not seek to the requested frame") + if self._frame_numbering is FrameNumbering.SOURCE: + _, timecode = item + self._record_frame(timecode) + return + def reset(self, print_infos=False): """Close and re-open the VideoStream (should be equivalent to calling `seek(0)`).""" self._check_open() - self._last_frame = False - self._last_frame_rgb = None - self._frame_number = 0 + self._reader.close() + self._position = None self._eof = False self._reader = _retry_on_oserror( "reset", lambda: FFMPEG_VideoReader(self._path, print_infos=print_infos) ) + self._next_timecode = Timecode(pts=0, time_base=1 / self.frame_rate) def close(self) -> None: """Close the video, terminating the ffmpeg process used to decode it. Has no effect if @@ -295,20 +300,41 @@ def close(self) -> None: def read(self, decode: bool = True) -> np.ndarray | bool: self._check_open() - if not hasattr(self._reader, "lastread") or self._eof: + item = self._read_next_frame() + if item is None: return False - has_last_read = hasattr(self._reader, "last_read") - # In MoviePy 2.0 there is a separate property we need to read named differently (#461). - self._last_frame = self._reader.last_read if has_last_read else self._reader.lastread - # Read the *next* frame for the following call to read, and to check for EOF. - frame = self._reader.read_frame() - if frame is self._last_frame: - if self._eof: - return False + + frame, timecode = item + result = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if decode else True + self._record_frame(timecode) + return result + + def peek_timecode(self) -> Timecode | None: + """Return the cached frame's timestamp on the FPS-derived clock.""" + self._check_open() + if self._eof: + return None + return self._next_timecode + + def _read_next_frame(self) -> tuple[np.ndarray, Timecode] | None: + """Return the cached image and timestamp without recording a position. + + Prefetch the next image. If it reaches EOF, the current image is still returned; + the following call returns None. + """ + if self._eof: + return None + if hasattr(self._reader, "last_read"): + frame = self._reader.last_read + elif hasattr(self._reader, "lastread"): + frame = self._reader.lastread + else: + return None + + timecode = self._next_timecode + if self._reader.read_frame() is frame: self._eof = True - self._frame_number += 1 - if decode and isinstance(self._last_frame, np.ndarray): - self._last_frame_rgb = cv2.cvtColor(self._last_frame, cv2.COLOR_BGR2RGB) - assert self._last_frame_rgb is not None - return self._last_frame_rgb - return not self._eof + else: + self._next_timecode = Timecode(pts=timecode.pts + 1, time_base=timecode.time_base) + + return frame, timecode diff --git a/scenedetect/backends/opencv.py b/scenedetect/backends/opencv.py index 25b36044..9157766d 100644 --- a/scenedetect/backends/opencv.py +++ b/scenedetect/backends/opencv.py @@ -30,13 +30,14 @@ from scenedetect.common import ( MAX_FPS_DELTA, FrameRate, - FrameTimecode, Timecode, TimecodeLike, framerate_to_fraction, + parse_frame_or_time, ) from scenedetect.platform import StrPath, get_file_name from scenedetect.video_stream import ( + FrameNumbering, FrameRateUnavailable, SeekError, VideoOpenFailure, @@ -97,6 +98,8 @@ def __init__( max_decode_attempts: int = 5, path_or_device: StrPath | int | None = None, framerate: float | None = None, + *, + frame_numbering: FrameNumbering = FrameNumbering.RELATIVE, ): """Open a video file, image sequence, or network stream. @@ -108,19 +111,22 @@ def __init__( max_decode_attempts: Number of attempts to continue decoding the video after a frame fails to decode. This allows processing videos that have a few corrupted frames or metadata (in which case accuracy - of detection algorithms may be lower). Once this limit is passed, - decoding will stop and emit an error. + of detection algorithms may be lower). If all attempts fail, + `read()` returns False. path_or_device: [DEPRECATED] Specify `path` for files, image sequences, or network streams/URLs. Use `VideoCaptureAdapter` for devices/pipes. framerate: [DEPRECATED] Use `frame_rate` instead. Retained as a deprecated alias for backwards compatibility; ignored when `frame_rate` is provided. + frame_numbering: RELATIVE (default) numbers the first frame read after each + successful seek as 0. SOURCE counts from the source beginning, including + seek preroll. Neither mode resets presentation timestamps. Raises: OSError: file could not be found or access was denied VideoOpenFailure: video could not be opened (may be corrupted) ValueError: specified frame rate is invalid """ - super().__init__() + super().__init__(frame_numbering=frame_numbering) if framerate is not None: warnings.warn( "`framerate` is deprecated and scheduled for removal in v0.9; " @@ -153,7 +159,7 @@ def __init__( self._is_device = isinstance(self._path_or_device, int) # VideoCapture state - self._has_grabbed = False + self._pending_grab = False self._max_decode_attempts = max_decode_attempts self._decode_failures = 0 self._warning_displayed = False @@ -224,13 +230,26 @@ def frame_size(self) -> tuple[int, int]: ) @property - def duration(self) -> FrameTimecode | None: - """Duration of the stream as a FrameTimecode, or None if non terminating.""" + def duration(self) -> Fraction | None: + """Estimated source duration in seconds, or None if unavailable. + + Calculated from reported frame count and frame rate; may be inaccurate for VFR. + """ + frame_count = self.frame_count + if frame_count is None: + return None + return frame_count / self.frame_rate + + @property + def frame_count(self) -> int | None: + """Reported total source frame count, or None if unavailable.""" if self._is_device: return None if self._closed: - return self.base_timecode + math.trunc(self._closed_frame_count) - return self.base_timecode + math.trunc(self._cap.get(cv2.CAP_PROP_FRAME_COUNT)) + frame_count = math.trunc(self._closed_frame_count) + else: + frame_count = math.trunc(self._cap.get(cv2.CAP_PROP_FRAME_COUNT)) + return frame_count if frame_count > 0 else None @property def aspect_ratio(self) -> float: @@ -241,80 +260,90 @@ def aspect_ratio(self) -> float: @property def timecode(self) -> Timecode: - """Current position within stream as a Timecode.""" - # *NOTE*: Although OpenCV has `CAP_PROP_PTS`, it doesn't seem to be reliable. For now, we - # use `CAP_PROP_POS_MSEC` instead, converting to microseconds for sufficient precision to - # avoid frame-boundary rounding errors at common framerates like 24000/1001. + """Timestamp of the current capture frame. + + Video timestamps are rounded to integer microseconds from CAP_PROP_POS_MSEC. + Image-sequence timestamps use the source image index and configured frame rate. + """ if self._eof_timecode is not None: return self._eof_timecode + if self._cap.get(cv2.CAP_PROP_BACKEND) == cv2.CAP_IMAGES: + source_index = max(0, math.trunc(self._cap.get(cv2.CAP_PROP_POS_FRAMES)) - 1) + return Timecode( + pts=source_index, + time_base=1 / self.frame_rate, + ) + # *NOTE*: CAP_PROP_PTS can be unreliable, so use CAP_PROP_POS_MSEC instead. + # Its FPS-based units can discard VFR timestamp precision. ms = self._cap.get(cv2.CAP_PROP_POS_MSEC) time_base = Fraction(1, 1000000) return Timecode(pts=round(ms * 1000), time_base=time_base) - @property - def position(self) -> FrameTimecode: - timecode = self.timecode - # If PTS is non-positive but we've read frames, derive from frame number. This handles - # image sequences and cases where CAP_PROP_POS_MSEC is unreliable. OpenCV 5 reports - # CAP_PROP_POS_MSEC as -1 (rather than 0) for image sequences on Windows, so check <= 0. - if timecode.pts <= 0 and self.frame_number > 0: - fps = self.frame_rate - time_base = Fraction(1, fps.numerator) - pts = (self.frame_number - 1) * fps.denominator - timecode = Timecode(pts=pts, time_base=time_base) - return FrameTimecode(timecode=timecode, fps=self.frame_rate) + def seek(self, target: TimecodeLike): + """Position the next read at a source frame ordinal or presentation time. - @property - def position_ms(self) -> float: - return self._cap.get(cv2.CAP_PROP_POS_MSEC) + Integer targets use sequential grabbing in both numbering modes. RELATIVE numbering + restarts at 0; SOURCE numbering includes the skipped prefix. Image-sequence time + targets select the first image at or after the target using the configured frame rate. - @property - def frame_number(self) -> int: - return math.trunc(self._cap.get(cv2.CAP_PROP_POS_FRAMES)) + Other time targets use native seeking in RELATIVE mode and sequential grabbing in + SOURCE mode. Preroll retains the first qualifying frame for the next read. Comparisons + use microsecond precision. Native seeking can land late and skip eligible frames. - def seek(self, target: TimecodeLike): + Arguments: + target: A zero-based source ordinal (int or digit-only string), or a presentation + time (float seconds, time string, or Timecode). + + Raises: + SeekError: Seeking is unsupported or the required preroll cannot be completed. + TypeError: The target type is unsupported. + ValueError: The target is negative, non-finite, malformed, or has an invalid time base. + """ self._check_open() - if self._is_device: + if not self.is_seekable: raise SeekError("Cannot seek if input is a device!") - if not isinstance(target, FrameTimecode): - target = FrameTimecode(target, self.frame_rate) - if target < 0: + parsed = parse_frame_or_time(target) + if parsed < 0: raise ValueError("Target seek position cannot be negative!") - target_secs = (self.base_timecode + target).seconds - self._has_grabbed = False - self._eof_timecode = None - if target_secs > 0: - # Seek one frame before target so the next read() returns the frame at target. - one_frame_ms = 1000.0 / float(self._frame_rate) - seek_ms = max(0.0, target_secs * 1000.0 - one_frame_ms) - self._cap.set(cv2.CAP_PROP_POS_MSEC, seek_ms) - self._has_grabbed = self._cap.grab() - if self._has_grabbed: - # VFR correction: set(CAP_PROP_POS_MSEC) converts time using avg_fps internally, - # which can land ~1s too early for VFR video. Read forward until we reach the - # intended position. The threshold (2x one_frame_ms) never triggers for CFR. - actual_ms = self._cap.get(cv2.CAP_PROP_POS_MSEC) - corrections = 0 - while actual_ms < seek_ms - 2.0 * one_frame_ms and corrections < 100: - if not self._cap.grab(): - break - actual_ms = self._cap.get(cv2.CAP_PROP_POS_MSEC) - corrections += 1 - # If we seeked past the end, back up one frame. - if not self._has_grabbed: - pos = self._cap.get(cv2.CAP_PROP_POS_FRAMES) - # OpenCV 5 can report NaN here after a seek past EOF, which would crash - # round()/trunc and hang the CLI decode thread (#380). - if not math.isfinite(pos): - raise SeekError("Target frame is beyond end of video!") - seek_pos = round(pos - 1.0) - self._cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, seek_pos)) - self._has_grabbed = self._cap.grab() + + # TODO: Optimize seeking for CAP_IMAGES + if isinstance(parsed, Fraction) and self._cap.get(cv2.CAP_PROP_BACKEND) == cv2.CAP_IMAGES: + parsed = math.ceil(parsed * self.frame_rate) + if isinstance(parsed, Fraction): + # Compare the target at the same precision as the reported video timestamps. + target_time = Fraction(round(parsed * 1_000_000), 1_000_000) + if self.frame_numbering is FrameNumbering.RELATIVE: + self._pending_grab = False + self._eof_timecode = None + if not self._cap.set(cv2.CAP_PROP_POS_MSEC, float(parsed * 1000)): + raise SeekError("Could not seek to the requested time.") + elif self._position is not None and self._position.timecode.seconds >= target_time: + self.reset() + + while self._grab_next_frame(): + if self.timecode.seconds >= target_time: + self._pending_grab = True + if self.frame_numbering is FrameNumbering.RELATIVE: + self._position = None + return + if self.frame_numbering is FrameNumbering.SOURCE: + self._record_frame(self.timecode) + + raise SeekError("Could not seek to the requested time.") + else: - self._cap.set(cv2.CAP_PROP_POS_FRAMES, 0) + if self.frame_numbering is FrameNumbering.RELATIVE or self.frame_number >= parsed: + self.reset() + for _ in range(self.frame_number + 1, parsed): + if not self._grab_next_frame(): + raise SeekError("Could not seek to the requested frame.") + if self.frame_numbering is FrameNumbering.SOURCE: + self._record_frame(self.timecode) + + return def reset(self): - """Close and re-open the VideoStream (should be equivalent to calling `seek(0)`).""" + """Reopen at the source beginning and clear the recorded position and pending frame.""" self._check_open() self._cap.release() self._open_capture(float(self._frame_rate)) @@ -330,41 +359,19 @@ def close(self) -> None: self._closed_frame_count = self._cap.get(cv2.CAP_PROP_FRAME_COUNT) self._closed_aspect_ratio = self.aspect_ratio self._closed = True + self._pending_grab = False self._cap.release() def read(self, decode: bool = True) -> np.ndarray | bool: self._check_open() - if not self._cap.isOpened(): - return False - # At the end of some VFR streams OpenCV reports an earlier CAP_PROP_POS_MSEC once grab() - # fails, so keep `position` on the last frame read like the other backends do (#561). - last_timecode = self.timecode if self._has_grabbed else None - has_grabbed = self._cap.grab() - # If we failed to grab the frame, retry a few times if required. - if not has_grabbed: - duration = self.duration - if duration is not None and duration > 0 and self.position < (duration - 1): - for _ in range(self._max_decode_attempts): - has_grabbed = self._cap.grab() - if has_grabbed: - break - # Report previous failure in debug mode. - if has_grabbed: - self._decode_failures += 1 - logger.debug("Frame failed to decode.") - if not self._warning_displayed and self._decode_failures > 1: - logger.warning("Failed to decode some frames, results may be inaccurate.") - # We didn't manage to grab a frame even after retrying, so just return. - if not has_grabbed: - self._eof_timecode = last_timecode + if not self._grab_next_frame(): return False - self._has_grabbed = True - self._eof_timecode = None + self._record_frame(self.timecode) # Need to make sure we actually grabbed a frame before calling retrieve. - if decode and self._has_grabbed: - _, frame = self._cap.retrieve() - return frame - return self._has_grabbed + if decode: + success, frame = self._cap.retrieve() + return frame if success else False + return True # # Private Methods @@ -420,16 +427,63 @@ def _open_capture(self, frame_rate: FrameRate | None = None): raise FrameRateUnavailable() self._cap: cv2.VideoCapture = cap + self._position = None self._frame_rate: Fraction = framerate_to_fraction(frame_rate) - self._has_grabbed = False + self._pending_grab = False self._eof_timecode: Timecode | None = None cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 1.0) # https://github.com/opencv/opencv/issues/26795 + def _grab_next_frame(self) -> bool: + """Consume a pending seek frame or grab the next frame without recording a position.""" + if self._pending_grab: + self._pending_grab = False + return True + if not self._cap.isOpened(): + return False + last_timecode = self.timecode + has_grabbed = self._cap.grab() + # If we failed to grab the frame, retry a few times if required. + if not has_grabbed: + for _ in range(self._max_decode_attempts): + has_grabbed = self._cap.grab() + if has_grabbed: + break + # Report previous failure in debug mode. + if has_grabbed: + self._decode_failures += 1 + logger.debug("Frame failed to decode.") + if not self._warning_displayed and self._decode_failures > 1: + logger.warning("Failed to decode some frames, results may be inaccurate.") + + if has_grabbed: + self._eof_timecode = None + else: + self._eof_timecode = last_timecode + return has_grabbed + + def peek_timecode(self) -> Timecode | None: + """Return the presentation time of the next frame without advancing the stream. + + Returns: + Timecode of the next frame, or None if end of video. + """ + self._check_open() + if self._pending_grab: + return self.timecode + if not self._grab_next_frame(): + return None + self._pending_grab = True + return self.timecode + class VideoCaptureAdapter(VideoStream): """Adapter for existing VideoCapture objects. Unlike VideoStreamCv2, this class supports VideoCaptures which may not support seeking. + Ordinals and timestamps start at zero with the first frame read through this adapter, + even if the capture was already advanced. Timestamps use frame count and frame_rate, + not capture-provided timestamps, so variable frame intervals are not preserved. + The VideoCapture remains owned by the caller: closing the adapter (e.g. by leaving a `with` block) does not release it. """ @@ -452,8 +506,8 @@ def __init__( max_read_attempts: Number of attempts to continue decoding the video after a frame fails to decode. This allows processing videos that have a few corrupted frames or metadata (in which case accuracy - of detection algorithms may be lower). Once this limit is passed, - decoding will stop and emit an error. + of detection algorithms may be lower). If all attempts fail, + `read()` returns False. framerate: [DEPRECATED] Use `frame_rate` instead. Retained as a deprecated alias for backwards compatibility; ignored when `frame_rate` is provided. @@ -484,11 +538,10 @@ def __init__( self._cap = cap self._frame_rate: Fraction = framerate_to_fraction(frame_rate) - self._num_frames = 0 self._max_read_attempts = max_read_attempts self._decode_failures = 0 self._warning_displayed = False - self._time_base: float = 0.0 + self._pending_grab = False # # Backend-Specific Methods/Properties @@ -528,7 +581,7 @@ def name(self) -> str: @property def is_seekable(self) -> bool: - """Always False, as the underlying VideoCapture is assumed to not support seeking.""" + """Always False; this adapter does not expose seeking.""" return False @property @@ -540,48 +593,39 @@ def frame_size(self) -> tuple[int, int]: ) @property - def duration(self) -> FrameTimecode | None: - """Duration of the stream as a FrameTimecode, or None if non terminating.""" + def duration(self) -> Fraction | None: + """Estimated source duration in seconds, or None if unavailable. + + Calculated from reported frame count and frame rate; may be inaccurate for VFR. + """ + frame_count = self.frame_count + if frame_count is None: + return None + return frame_count / self.frame_rate + + @property + def frame_count(self) -> int | None: + """Reported total source frame count, or None if unavailable.""" frame_count = math.trunc(self._cap.get(cv2.CAP_PROP_FRAME_COUNT)) - if frame_count > 0: - return self.base_timecode + frame_count - return None + return frame_count if frame_count > 0 else None @property def aspect_ratio(self) -> float: """Display/pixel aspect ratio as a float (1.0 represents square pixels).""" return _get_aspect_ratio(self._cap) - @property - def position(self) -> FrameTimecode: - if self.frame_number < 1: - return self.base_timecode - # Synthesize a Timecode from frame count and rational framerate. - fps = self.frame_rate - time_base = Fraction(1, fps.numerator) - pts = (self.frame_number - 1) * fps.denominator - timecode = Timecode(pts=pts, time_base=time_base) - return FrameTimecode(timecode=timecode, fps=fps) - - @property - def position_ms(self) -> float: - if self._num_frames == 0: - return 0.0 - return self._cap.get(cv2.CAP_PROP_POS_MSEC) - self._time_base - - @property - def frame_number(self) -> int: - return self._num_frames - def seek(self, target: TimecodeLike): - """The underlying VideoCapture is assumed to not support seeking.""" + """Seeking is not supported by this adapter.""" raise NotImplementedError("Seeking is not supported.") def reset(self): """Not supported.""" raise NotImplementedError("Reset is not supported.") - def read(self, decode: bool = True) -> np.ndarray | bool: + def _grab_next_frame(self) -> bool: + if self._pending_grab: + self._pending_grab = False + return True if not self._cap.isOpened(): return False has_grabbed = self._cap.grab() @@ -597,14 +641,29 @@ def read(self, decode: bool = True) -> np.ndarray | bool: logger.debug("Frame failed to decode.") if not self._warning_displayed and self._decode_failures > 1: logger.warning("Failed to decode some frames, results may be inaccurate.") - # We didn't manage to grab a frame even after retrying, so just return. - if not has_grabbed: + return has_grabbed + + def read(self, decode: bool = True) -> np.ndarray | bool: + if not self._grab_next_frame(): return False - if self._num_frames == 0: - self._time_base = self._cap.get(cv2.CAP_PROP_POS_MSEC) - self._num_frames += 1 + # TODO: Define a timestamp policy for timed and untimed captures. + # The FPS-derived clock below does not preserve variable frame intervals. + self._record_frame(Timecode(pts=self.frame_number + 1, time_base=1 / self.frame_rate)) # Need to make sure we actually grabbed a frame before calling retrieve. - if decode and self._num_frames > 0: - _, frame = self._cap.retrieve() - return frame + if decode: + success, frame = self._cap.retrieve() + return frame if success else False return True + + def peek_timecode(self) -> Timecode | None: + """Return the next frame's timestamp on the FPS-derived clock.""" + self._check_open() + if not self._pending_grab: + if not self._grab_next_frame(): + return None + self._pending_grab = True + + return Timecode( + pts=self.frame_number + 1, + time_base=1 / self.frame_rate, + ) diff --git a/scenedetect/backends/pyav.py b/scenedetect/backends/pyav.py index d173869f..6fe44016 100644 --- a/scenedetect/backends/pyav.py +++ b/scenedetect/backends/pyav.py @@ -24,13 +24,14 @@ from scenedetect.common import ( MAX_FPS_DELTA, FrameRate, - FrameTimecode, Timecode, TimecodeLike, framerate_to_fraction, + parse_frame_or_time, ) from scenedetect.platform import StrPath, get_file_name from scenedetect.video_stream import ( + FrameNumbering, FrameRateUnavailable, SeekError, VideoOpenFailure, @@ -53,10 +54,12 @@ MAX_SEEK_PROBE_FRAMES = 32 -"""Number of frames `VideoStreamAv.seek()` decodes looking for a timestamp before concluding the -stream has none and cannot be seeked (e.g. raw Annex-B H.264). This also caps how many leading -frames without timestamps a file may have when `seek()` is the first call on the stream: a file -whose first timestamp is on frame 40 can be read sequentially, but not seeked before reading.""" +"""Number of frames `VideoStreamAv.seek()` probes for a timestamp before or after a native +RELATIVE timestamp seek. Streams without timestamps (e.g. raw Annex-B H.264) cannot use this path. +This also caps how many leading frames without timestamps can be probed before the first native +seek: a file whose first timestamp is on frame 40 can be read sequentially, but not seeked this way +before reading. Integer seeks and SOURCE timestamp seeks are not subject to this probe limit. +""" MAX_CONSECUTIVE_DECODE_FAILURES = 8 """Number of consecutive frame decode failures after which `VideoStreamAv.read()` gives up. @@ -84,8 +87,10 @@ def __init__( threading_mode: str | None = None, suppress_output: bool = False, framerate: FrameRate | None = None, + *, + frame_numbering: FrameNumbering = FrameNumbering.RELATIVE, ): - """Open a video by path. + """Open a video by path or from a binary file-like object. .. warning:: @@ -100,15 +105,19 @@ def __init__( name: Overrides the `name` property derived from the video path. Should be set if `path_or_io` is a file-like object. threading_mode: The PyAV video stream `thread_type`. See av.codec.context.ThreadType - for valid threading modes ('AUTO', 'FRAME', 'NONE', and 'SLICE'). If this mode is - 'AUTO' or 'FRAME' and not all frames have been decoded, the video will be reopened - if seekable, and the remaining frames decoded in single-threaded mode. + for valid threading modes ('AUTO', 'FRAME', 'NONE', and 'SLICE'). For seekable + sources in 'AUTO' or 'FRAME' mode, an EOF error triggers at most one recovery + attempt with codec threading disabled. Consumed frames are replayed before reading + resumes. suppress_output: If False, ffmpeg output will be sent to stdout/stderr by calling `av.logging.restore_default_callback()` before any other library calls. If True the application may deadlock if threading_mode is set. See the PyAV documentation for details: https://pyav.org/docs/stable/overview/caveats.html#sub-interpeters framerate: [DEPRECATED] Use `frame_rate` instead. Retained as a deprecated alias for backwards compatibility; ignored when `frame_rate` is provided. + frame_numbering: Origin for decoded frame ordinals. RELATIVE (default) numbers the + first frame read after each successful seek as 0. SOURCE counts decoded frames + from the source beginning, including seek preroll. Neither mode resets timestamps. Raises: OSError: file could not be found or access was denied @@ -118,7 +127,7 @@ def __init__( # NOTE(https://scenedetect.com/issues/258): `read()` skips over corrupt packets and # continues decoding. `self._container.discard_corrupt = True` may be a future # refinement for frames FFmpeg flags as corrupt but still decodes. - super().__init__() + super().__init__(frame_numbering=frame_numbering) if framerate is not None: warnings.warn( @@ -136,22 +145,24 @@ def __init__( self._name = "" if name is None else name self._path = "" self._frame: av.VideoFrame | None = None + self._pending_frame: av.VideoFrame | None = None + self._seek_origin: TimecodeLike = 0 self._decoder: ty.Generator | None = None self._reopened = True self._decode_failures = 0 self._warning_displayed = False - # Presentation time of `_frame` relative to the start of the stream. None until the first - # `read()` (and after `close()`/`reset()`). + # Timestamp of the latest decoded frame, including pending frames and seek preroll. + # Public position is stored separately in `_position`. self._timecode: Timecode | None = None - # Timestamp (and timebase) subtracted from every frame timestamp such that that frame 1 is - # at time 0. Decided based on the the first decoded frame with a valid timestamp. Only set + # Timestamp (and timebase) subtracted from every frame timestamp so the first frame is + # at time 0. Decided based on the first decoded frame with a valid timestamp. Only set # once, even after `reset()` or `seek()`. self._offset: int | None = None self._offset_time_base: Fraction | None = None # Ensures we only log a warning once per pass (until `reset()`) if positions go backwards. self._warned_non_monotonic = False - # 1-based count of frames decoded in the current stream pass, used to estimate the position - # of frames without timestamps and for diagnostic logging. + # 1-based count of frames decoded in the current native decoding pass, used to estimate + # the time of frames without timestamps and for diagnostic logging. self._frames_decoded = 0 # True if `_io` was opened by this object (from a path) and must be closed in `close()`. # Set before anything below can raise so a partially constructed object is safe to finalize. @@ -208,8 +219,15 @@ def __init__( assert frame_rate >= MAX_FPS_DELTA self._frame_rate: Fraction = framerate_to_fraction(frame_rate) - # Calculate duration after we have set the framerate. - self._duration_frames = self._get_duration() + # Cache source metadata so it remains available after closing. + self._duration = self._get_duration() + # TODO(https://scenedetect.com/issues/590): Some AVI files remuxed by ffmpeg set the stream + # rate to a high tick rate (e.g. 600/1), causing `stream.frames` to report tick count + # rather than actual frame count (e.g. 12012 instead of 480). OpenCV reports the same value + # via CAP_PROP_FRAME_COUNT, but `duration_sec * frame_rate` would be more accurate when + # `stream.frames` disagrees with the stream duration and codec frame rate. + frame_count = self._video_stream.frames + self._frame_count = frame_count if frame_count > 0 else None def __del__(self): # Finalizers must never raise - an exception here becomes an unraisable error. During @@ -249,6 +267,8 @@ def close(self) -> None: self._closed = True self._frame = None self._timecode = None + self._pending_frame = None + self._position = None # # VideoStream Methods/Properties @@ -280,43 +300,20 @@ def frame_size(self) -> tuple[int, int]: return (self._codec_context.width, self._codec_context.height) @property - def duration(self) -> FrameTimecode: - """Duration of the video as a FrameTimecode.""" - return self.base_timecode + self._duration_frames + def duration(self) -> Fraction | None: + """Duration of the video, or None if unavailable.""" + return self._duration + + @property + def frame_count(self) -> int | None: + """Reported total source frame count, or None if unavailable.""" + return self._frame_count @property def frame_rate(self) -> Fraction: """Frame rate in frames/sec as a rational Fraction.""" return self._frame_rate - @property - def position(self) -> FrameTimecode: - """Current position within stream as FrameTimecode. - - This can be interpreted as presentation time stamp, thus frame 1 corresponds - to the presentation time 0. Returns 0 even if `frame_number` is 1.""" - if self._timecode is None: - return self.base_timecode - return FrameTimecode(timecode=self._timecode, fps=self.frame_rate) - - @property - def position_ms(self) -> float: - """Current position within stream as a float of the presentation time in - milliseconds. The first frame has a PTS of 0.""" - if self._timecode is None: - return 0.0 - return float(self._timecode.seconds) * 1000.0 - - @property - def frame_number(self) -> int: - """Current position within stream as the frame number (CFR-equivalent). - - Will return 0 until the first frame is `read`. For VFR video this is an approximation - derived from PTS * framerate; use `position` for accurate PTS-based timing.""" - if self._timecode is None: - return 0 - return round(float(self._timecode.seconds) * float(self.frame_rate)) + 1 - @property def rate(self) -> Fraction | None: """Frame rate reported by the stream (PyAV `guessed_rate`), or None if unavailable.""" @@ -344,181 +341,178 @@ def aspect_ratio(self) -> float: return display_aspect_ratio / frame_aspect_ratio def seek(self, target: TimecodeLike) -> None: - """Seek to the given timecode. If given as a frame number, represents the current seek - pointer (e.g. if seeking to 0, the next frame decoded will be the first frame of the video). + """Position the next read at a source frame ordinal or presentation time. - For 1-based indices (first frame is frame #1), the target frame number needs to be converted - to 0-based by subtracting one. For example, if we want to seek to the first frame, we call - seek(0) followed by read(). If we want to seek to the 5th frame, we call seek(4) followed - by read(), at which point frame_number will be 5. + Integer targets are zero-based source ordinals in both numbering modes and are reached + by sequential decoding. For example, `seek(4)` followed by `read()` reads the fifth source + frame. Its ordinal is 4 in SOURCE mode and 0 in RELATIVE mode. - May not be supported on all input codecs (see `is_seekable`). Elementary streams usually - cannot be seeked, and may raise `SeekError`, after which the stream position is undefined - until `reset()` is called. + Time targets select the first frame at or after the target encountered during preroll. + RELATIVE mode uses a native timestamp seek; SOURCE mode counts frames while decoding from + the beginning or continuing forward. A successful seek restarts RELATIVE numbering at 0 + without changing the source-relative presentation timestamps. Arguments: - target: Target position in video stream to seek to. - If float, interpreted as time in seconds. - If int, interpreted as frame number. + target: A source frame ordinal (int or digit-only string), or a presentation time + (float seconds, timecode string, or Timecode). + Raises: - SeekError: Stream does not support seeking, target cannot be seeked to, or the video - could not be re-opened to read forward from the start. - ValueError: `target` is not a valid value (i.e. it is negative), or the stream is - closed. + SeekError: Seeking is unsupported or the target cannot be reached. + TypeError: The target type is unsupported. + ValueError: The stream is closed, or the target is negative, non-finite, malformed, + or has an invalid time base. """ self._check_open() - if not isinstance(target, FrameTimecode): - target = FrameTimecode(target, self.frame_rate) - if target < 0: - raise ValueError("Target cannot be negative!") - if not self.is_seekable: - raise SeekError("Stream is not seekable.") - beginning = target == 0 - target = self.base_timecode + target - if target >= 1: - target = target - 1 + if not self.is_seekable: + raise SeekError("This source does not support seeking.") + parsed = parse_frame_or_time(target) + if parsed < 0: + raise ValueError("Target cannot be negative!") + beginning = parsed == 0 # Seeking to the start always re-opens the stream. The demuxer can only seek to keyframes # that carry a timestamp, so if the first one does not (as in some MPEG-TS files), seeking # the container to time 0 lands on a later keyframe instead. if beginning: self._reset_for_seek() return - # The timestamp offset is anchored at the start of the stream (see `_update_timecode()`), - # so it must only ever be decided from frames decoded in order from the start: a seek can - # land on a later keyframe. While it is unknown, decode frames until one carries a - # timestamp. Streams without any timestamps (e.g. raw H.264) cannot be seeked, so give up - # after `MAX_SEEK_PROBE_FRAMES` frames. As with any failed seek, the stream position is - # then undefined until `reset()` is called. - stream_time_base = self._video_stream.time_base - if not stream_time_base: - raise SeekError("Unable to seek in stream: stream time_base is unset.") - if self._offset is None: - while self._offset is None and self._frames_decoded < MAX_SEEK_PROBE_FRAMES: - if self.read(decode=False) is False: - break - if self._offset is None: - raise SeekError("Unable to seek in stream without timestamps.") - # Positions are relative to `_offset`, so the seek target must be too. For streams whose - # first frame has a PTS, this is the stream's `start_time`. - stream_time_base = _to_fraction(stream_time_base) - assert self._offset is not None and self._offset_time_base is not None - offset = self._offset - if offset and self._offset_time_base != stream_time_base: - offset = int(offset * self._offset_time_base / stream_time_base) - target_pts = offset + int((self.base_timecode + target).seconds / stream_time_base) - # TODO(https://scenedetect.com/issues/590): For some containers (e.g. MPEG-TS) whose - # keyframes lack timestamps, the demuxer can land past the target, or somewhere the - # position cannot be established. Both fall back to reading from the start of the stream - # (see below), which is correct but slow for distant targets; we could seek to an earlier - # keyframe instead. - try: - self._container.seek(target_pts, stream=self._video_stream) - except av.error.FFmpegError as ex: # type: ignore[attr-defined] - raise SeekError(f"Unable to seek in stream: {ex}") from ex - self._frame = None - self._decoder = None - self._timecode = None - # Seed `_frames_decoded` with the target frame before walking forward from the keyframe, - # then sync it to `self.frame_number` once the walk completes. - self._frames_decoded = target.frame_num - # The demuxer normally lands on a keyframe at or before `target_pts`, but the frames - # decoded from there may lack timestamps, in which case their position is unknown. - # Read until a frame carries one to establish where we landed, leaving the position - # unset (rather than estimated) until then so the walk below cannot mistake an - # estimate for having reached the target. Frames consumed while probing cannot be - # given back, so if no timestamp is found within `MAX_SEEK_PROBE_FRAMES` frames, or the - # first one found is already past the target, read forward from the start instead. - # That gives the same result as a sequential read, and only happens on malformed - # inputs. If the end of the stream is reached before any frame is decoded, there is - # nothing to establish. - probe_limit = self._frames_decoded + MAX_SEEK_PROBE_FRAMES - landed = None - while self.read(decode=False) is not False: - if self._frame_has_timestamp(): - landed = self.position - break - if self._frames_decoded >= probe_limit: - break - self._timecode = None - if self._frame is not None and (landed is None or landed > target): - logger.debug( - "Seek landed at %s for target %s, reading from the start instead.", - "unknown position" if landed is None else landed, - target, - ) - self._reset_for_seek() - # Walk forward until the frame before the target has been read. `position` is 0 both - # before any frame is read and on the first frame, so after re-opening the stream a frame - # must be read before it can be compared, otherwise `seek(1)` would leave the next `read()` - # on the first frame. - while self._timecode is None or self.position < target: - if self.read(decode=False) is False: - break - self._frames_decoded = self.frame_number + + if isinstance(parsed, Fraction): + if self._frame_numbering is FrameNumbering.RELATIVE: + # Establish the timestamp offset before jumping away from the source prefix. + while self._offset is None and self._frames_decoded < MAX_SEEK_PROBE_FRAMES: + if self._next_frame() is None: + break + + if self._offset is None: + raise SeekError("Unable to seek in stream without timestamps.") + + stream = self._video_stream + time_base = stream.time_base + if not time_base or time_base <= 0: + raise SeekError("The stream has no usable time base.") + time_base = _to_fraction(time_base) + + assert self._offset_time_base is not None + target_pts = (parsed + self._offset * self._offset_time_base) // time_base + if self._decoder is not None: + self._decoder.close() + self._decoder = None + self._pending_frame = None + try: + self._container.seek(target_pts, stream=stream) + except (OSError, OverflowError, av.error.FFmpegError) as ex: # type: ignore[attr-defined] + raise SeekError("Could not seek to the requested time.") from ex + self._frame = None + self._timecode = None + self._frames_decoded = 0 + + landed = None + for _ in range(MAX_SEEK_PROBE_FRAMES): + try: + candidate = self._decode_next_frame() + except av.error.EOFError: # type: ignore[attr-defined] + break + + if candidate is None: + break + + if self._frame_has_timestamp(candidate): + landed = self._timecode + self._pending_frame = candidate + break + + # An estimate cannot establish where the container landed. + self._timecode = None + + if landed is None or landed.seconds > parsed: + self._reset_for_seek() + else: + if self.position and self.position.timecode.seconds >= parsed: + self._reset_for_seek() + + while True: + try: + next_frame = self._decode_next_frame() + except av.error.EOFError as ex: # type: ignore[attr-defined] + raise SeekError("Could not reach the requested time.") from ex + + if next_frame is None: + raise SeekError("Could not reach the requested time.") + + assert self._timecode is not None + + if self._timecode.seconds >= parsed: + self._pending_frame = next_frame + if self._frame_numbering is FrameNumbering.RELATIVE: + self._frame = None + self._position = None + self._seek_origin = target + return + if self._frame_numbering is FrameNumbering.SOURCE: + self._record_decoded_frame(next_frame) + + else: + if self._frame_numbering is FrameNumbering.RELATIVE or parsed <= self.frame_number: + self._reset_for_seek() + for _ in range(self.frame_number + 1, parsed): + try: + frame = self._decode_next_frame() + except av.error.EOFError as ex: # type: ignore[attr-defined] + raise SeekError("Could not reach the requested frame.") from ex + + if frame is None: + raise SeekError("Could not reach the requested frame.") + + if self._frame_numbering is FrameNumbering.SOURCE: + self._record_decoded_frame(frame) + + self._seek_origin = target def reset(self): - """Close and re-open the VideoStream (should be equivalent to calling `seek(0)`).""" + """Reopen at the source beginning and clear the frame position and seek origin. + + Preserve the current codec threading mode and the one-shot EOF recovery guard. + """ self._check_open() + thread_type = self._video_stream.thread_type + if self._decoder is not None: + self._decoder.close() self._container.close() self._frame = None self._decoder = None self._timecode = None self._frames_decoded = 0 self._warned_non_monotonic = False + self._pending_frame = None + self._position = None + self._seek_origin = 0 try: self._container = self._open_container(rewind=True) - if self._threading_mode is not None: - self._video_stream.thread_type = self._threading_mode - self._reopened = False + self._video_stream.thread_type = thread_type except Exception as ex: raise VideoOpenFailure() from ex def read(self, decode: bool = True) -> np.ndarray | bool: self._check_open() - consecutive_failures = 0 - while True: - # Reuse the same decode generator for the lifetime of the container. Creating a new - # generator on each call would flush the codec's internal buffer at EOF and drop the - # last buffered frame. - if self._decoder is None: - self._decoder = self._container.decode(video=0) - try: - last_frame = self._frame - assert self._decoder is not None - self._frame = next(self._decoder) - # EOFError subclasses FFmpegError, so this clause must come first. - except av.error.EOFError: # type: ignore[attr-defined] - self._frame = last_frame - if self._handle_eof(): - return self.read(decode) - return False - except StopIteration: - return False - except av.error.FFmpegError as ex: # type: ignore[attr-defined] - # `next()` raised before assignment, so `self._frame` and `self._timecode` still - # reflect the last valid frame. - self._decode_failures += 1 - consecutive_failures += 1 - # A generator cannot be resumed once an exception propagates out of it; recreating - # it on the next iteration continues demuxing after the corrupt packet. - self._decoder = None - if consecutive_failures >= MAX_CONSECUTIVE_DECODE_FAILURES: - logger.error( - "Failed to decode %d consecutive frames, stopping: %s", - consecutive_failures, - ex, - ) - return False - logger.debug("Frame failed to decode: %s", ex) - if not self._warning_displayed and self._decode_failures > 1: - self._warning_displayed = True - logger.warning("Failed to decode some frames, results may be inaccurate.") - continue - assert self._frame is not None - self._frames_decoded += 1 - self._update_timecode() - return self._frame.to_ndarray(format="bgr24") if decode else True + frame = self._next_frame() + if frame is None: + return False + + result = frame.to_ndarray(format="bgr24") if decode else True + self._record_decoded_frame(frame) + return result + + def peek_timecode(self) -> Timecode | None: + self._check_open() + if self._pending_frame is None: + self._pending_frame = self._next_frame() + + frame = self._pending_frame + if frame is None: + return None + assert self._timecode is not None + return self._timecode # # Private Methods/Properties @@ -561,17 +555,16 @@ def _reset_for_seek(self): except VideoOpenFailure as ex: raise SeekError("Unable to seek in stream: failed to re-open video.") from ex - def _frame_has_timestamp(self) -> bool: - """True if `_frame` carries a usable timestamp (a PTS or DTS, and a time base).""" - frame = self._frame + def _frame_has_timestamp(self, frame: av.VideoFrame) -> bool: + """True if `frame` carries a usable timestamp (a PTS or DTS, and a time base).""" return ( frame is not None and bool(frame.time_base) and (frame.pts is not None or frame.dts is not None) ) - def _update_timecode(self): - """Update `_timecode` with the presentation time of `_frame` relative to the first frame. + def _update_timecode(self, frame: av.VideoFrame): + """Update `_timecode` with the presentation time of `frame` relative to the first frame. Each frame is placed at its PTS, falling back to its DTS when the PTS is missing. This is the same rule as OpenCV's FFmpeg backend. With `genpts` off, FFmpeg's @@ -582,19 +575,19 @@ def _update_timecode(self): the previous frame's position, estimated or not. `_offset` is decided once, from the first frame that carries a timestamp. When that is - frame 1 and it has a PTS, the stream `start_time` is used so files with edit lists start - at time 0 like the other backends. Otherwise the offset anchors frame 1 at time 0 assuming - the frames before it were spaced at the nominal frame rate. This covers DTS-only streams - (e.g. AVI), whose first DTS is already past the stream start by the decoder's B-frame - reordering delay, and streams whose first frames carry no timestamps at all. + the first frame and it has a PTS, the stream `start_time` is used so files with edit lists + start at time 0 like the other backends. Otherwise the offset anchors the first frame at + time 0 assuming the frames before it were spaced at the nominal frame rate. This covers + DTS-only streams (e.g. AVI), whose first DTS is already past the stream start by the + decoder's B-frame reordering delay, and streams whose first frames carry no + timestamps at all. """ - frame = self._frame assert frame is not None timestamp = frame.pts if frame.pts is not None else frame.dts if timestamp is None or not frame.time_base: self._timecode = self._estimated_timecode() return - time_base = self._frame_time_base + time_base = _to_fraction(frame.time_base) if self._offset is None: stream_time_base = self._video_stream.time_base if self._frames_decoded == 1 and frame.pts is not None and stream_time_base: @@ -616,8 +609,7 @@ def _update_timecode(self): assert self._offset_time_base is not None offset = int(offset * self._offset_time_base / time_base) timecode = Timecode(pts=timestamp - offset, time_base=time_base) - # Compare against the last reported position, including estimated ones, since that is - # what callers see go backwards. + # Compare with the previous decoded timestamp, including estimates. previous = self._timecode if ( previous is not None @@ -652,72 +644,124 @@ def _frame_period(self, time_base: Fraction) -> int: """Duration of one frame at the nominal frame rate in `time_base` ticks (at least 1).""" return max(round(1 / (self.frame_rate * time_base)), 1) - def _get_duration(self) -> int: - """Get video duration as number of frames based on the video and set framerate. + def _next_frame(self) -> av.VideoFrame | None: + """Return the next frame, attempting EOF recovery when needed.""" + while True: + try: + return self._decode_next_frame() + except av.error.EOFError: # type: ignore[attr-defined] + if self._handle_eof(): + continue + return None + + def _get_duration(self) -> Fraction | None: + """Get reported video duration in seconds, or None if unavailable. See https://pyav.org/docs/develop/api/time.html for details on how ffmpeg/PyAV handle time calculations internally and which time base to use. """ - assert self.frame_rate is not None, "Frame rate must be set before calling _get_duration!" - # See if we can obtain the number of frames directly from the stream itself. - # TODO(https://scenedetect.com/issues/590): Some AVI files remuxed by ffmpeg set the stream - # rate to a high tick rate (e.g. 600/1), causing `stream.frames` to report tick count - # rather than actual frame count (e.g. 12012 instead of 480). OpenCV reports the same value - # via CAP_PROP_FRAME_COUNT, but `duration_sec * frame_rate` would be more accurate when - # `stream.frames` disagrees with the stream duration and codec frame rate. - if self._video_stream.frames > 0: - return self._video_stream.frames - # Calculate based on the reported container duration. - duration_sec = None - container = self._video_stream.container - if container.duration is not None and container.duration > 0: + stream = self._video_stream + if ( + stream.duration is not None + and stream.duration >= 0 + and stream.time_base is not None + and stream.time_base > 0 + ): + return stream.duration * _to_fraction(stream.time_base) + logger.debug("Video-stream duration unavailable; trying container duration.") + # Fall back to container duration, which may include other tracks. + container = stream.container + if container.duration is not None and container.duration >= 0: # Containers use AV_TIME_BASE as the time base. - duration_sec = float(self._video_stream.container.duration / av.time_base) - # Lastly, if that calculation fails, try to calculate it based on the stream duration. - if duration_sec is None or duration_sec < MAX_FPS_DELTA: - if self._video_stream.duration is None: - logger.warning("Video duration unavailable.") - return 0 - # Streams use stream `time_base` as the time base. Unset is None on PyAV < 19 and - # a falsy AVRational(0, 1) on PyAV 19+. - time_base = self._video_stream.time_base - if not time_base: - logger.warning("Unable to calculate video duration: stream time_base is unset.") - return 0 - # `duration` is in units of `time_base`, so seconds = duration * time_base. - duration_sec = float(self._video_stream.duration * _to_fraction(time_base)) - return round(duration_sec * self.frame_rate) + return Fraction(container.duration, av.time_base) + + logger.warning("Video duration unavailable.") + return None def _handle_eof(self): - """Fix for issue where if thread_type is 'AUTO' the whole video is not decoded. + """Attempt one recovery from an EOF error in AUTO/FRAME decoding. - Re-open video if the threading mode is AUTO and we didn't decode all of the frames.""" - # Don't re-open the video if we already did, or if we already decoded all the frames. - if self._reopened or self.frame_number >= self.duration: + For seekable sources, reopen with codec threading disabled and replay the consumed + prefix to restore frame ordinals. Leave the next frame unread. Replay assumes that + reopening reproduces the consumed frame sequence. + """ + # Don't re-open the video if we already did. + if self._reopened: return False - self._reopened = True # Don't re-open the video if we can't seek or aren't in AUTO/FRAME thread_type mode. - thread_type = getattr( - self._video_stream.thread_type, "name", self._video_stream.thread_type - ) - if not self.is_seekable or self._offset is None or thread_type not in ("AUTO", "FRAME"): + thread_type = self._video_stream.thread_type + thread_type = getattr(thread_type, "name", thread_type) + if not self.is_seekable or thread_type not in ("AUTO", "FRAME"): return False - last_pos = self.position if self._timecode is not None else None - orig_pos = self._io.tell() - try: - container = self._open_container(rewind=True) - except: - self._io.seek(orig_pos) - raise - self._container.close() - self._container = container - self._decoder = None - if last_pos is not None: - try: - # `seek(target)` positions the stream one frame before `target` so the next `read()` - # returns `target`. Pass `last_pos + 1` so the reopened stream lands on `last_pos` - # and the caller's subsequent `read()` advances to the next frame. - self.seek(last_pos + 1) - except SeekError: - return False + + # Replay reads must not start another recovery attempt. + self._reopened = True + expected_position = self.position + frames_read = self.frame_number + 1 + seek_origin = self._seek_origin + self.reset() + # reset() preserves the mode; use a non-threaded path for this compatibility retry. + self._video_stream.thread_type = "NONE" + + if self.frame_numbering is FrameNumbering.SOURCE: + self.seek(frames_read) + else: + self.seek(seek_origin) + for _ in range(frames_read): + if self.read(decode=False) is False: + raise SeekError("Could not replay the consumed frames during EOF recovery.") + + if self.position != expected_position: + raise SeekError("Could not restore the expected position during EOF recovery.") + # Internal recovery seeks must not replace the original public seek target. + self._seek_origin = seek_origin return True + + def _decode_next_frame(self) -> av.VideoFrame | None: + """Decode one frame without publishing a position.""" + if self._pending_frame is not None: + frame = self._pending_frame + self._pending_frame = None + return frame + consecutive_failures = 0 + while True: + # Reuse a persistent decoder generator so the codec's internal frame buffer (used for + # B-frame reordering) is never flushed prematurely. Creating a new generator each call + # caused the last buffered frame to be lost at EOF. + if self._decoder is None: + self._decoder = self._container.decode(video=0) + try: + assert self._decoder is not None + frame = next(self._decoder) + # NOTE: EOFError subclasses FFmpegError, so this clause must come first. + except av.error.EOFError: # type: ignore[attr-defined] + raise + except StopIteration: + return None + except av.error.FFmpegError as ex: # type: ignore[attr-defined] + # Failed decode attempts do not publish a frame or advance its ordinal. + self._decode_failures += 1 + consecutive_failures += 1 + # The decoder generator is closed once an exception propagates through it; + # recreating it (next loop iteration) resumes demuxing after the bad packet. + self._decoder = None + if consecutive_failures >= MAX_CONSECUTIVE_DECODE_FAILURES: + logger.error( + "Failed to decode %d consecutive frames, stopping: %s", + consecutive_failures, + ex, + ) + return None + logger.debug("Frame failed to decode: %s", ex) + if not self._warning_displayed and self._decode_failures > 1: + self._warning_displayed = True + logger.warning("Failed to decode some frames, results may be inaccurate.") + continue + self._frames_decoded += 1 + self._update_timecode(frame) + return frame + + def _record_decoded_frame(self, frame: av.VideoFrame) -> None: + assert self._timecode is not None + self._frame = frame + self._record_frame(self._timecode) diff --git a/scenedetect/common.py b/scenedetect/common.py index bcf6382c..2defc794 100644 --- a/scenedetect/common.py +++ b/scenedetect/common.py @@ -12,57 +12,11 @@ """``scenedetect.common`` Module This module contains common types and functions used throughout PySceneDetect. - -This includes :class:`FrameTimecode` which is used as a way for PySceneDetect to store -frame-accurate timestamps of each cut. This is done by also specifying the video framerate with the -timecode, allowing a frame number to be converted to/from a floating-point number of seconds, or -string in the form `"HH:MM:SS[.nnn]"` where the `[.nnn]` part is optional. - -A :class:`FrameTimecode` can be created by specifying a timecode (`int` for number of frames, -`float` for number of seconds, or `str` in the form "HH:MM:SS" or "HH:MM:SS.nnn") with a framerate: - -.. code:: python - - frames = FrameTimecode(29, 29.97) - seconds_float = FrameTimecode(10.0, 10.0) - timecode_str = FrameTimecode("00:00:10.000", 10.0) - - -Arithmetic/comparison operations with :class:`FrameTimecode` objects is also possible, and the -other operand can also be of the above types: - -.. code:: python - - x = FrameTimecode("00:01:00.000", 10.0) - # Can add int (frames), float (seconds), or str (timecode). - print(x + 10) - print(x + 10.0) - print(x + "00:10:00") - # Same for all comparison operators. - print((x + 10.0) == "00:01:10.000") - - -:class:`FrameTimecode` objects can be added and subtracted, however the current implementation -disallows negative values, and will clamp negative results to 0. - -.. warning:: - - Be careful when subtracting :class:`FrameTimecode` objects or adding negative - amounts of frames/seconds. In the example below, ``c`` will be at frame 0 since - ``b > a``, but ``d`` will be at frame 5: - - .. code:: python - - a = FrameTimecode(5, 10.0) - b = FrameTimecode(10, 10.0) - c = a - b # b > a, so c == 0 - d = b - a - assert(c == 0) - assert(d == 5) """ import math import numbers +import re import typing as ty import warnings from dataclasses import dataclass @@ -80,27 +34,26 @@ to source frame without downscaling. """ -CutList = list["FrameTimecode"] -"""Type hint for a list of cuts, where each timecode represents the first frame of a new shot.""" +CutList = list["FramePosition"] +"""Type hint for a list of cuts, where each position represents the first frame of a new shot.""" FrameRate = float | Fraction """Type hint for a video frame rate. ``Fraction`` is the canonical exact form and should be preferred (e.g. ``Fraction(30000, 1001)``), while ``float`` is accepted for convenience. Floats will be converted to rationals at runtime via :func:`framerate_to_fraction`.""" -SceneList = list[tuple["FrameTimecode", "FrameTimecode"]] -"""Type hint for a list of scenes in the form (start time, end time).""" +SceneList = list[tuple["FramePosition", "FramePosition"]] +"""Type hint for a list of scenes in the form (start position, end position).""" -# `Timecode` and `FrameTimecode` are defined later in this module; using `typing.Union` with +# `Timecode` is defined later in this module; using `typing.Union` with # string forward refs is the only form that both works at the top of the file (the PEP 604 `|` # syntax can't accept string forward refs) and supports `TimecodeLike | None` at use sites. -TimecodeLike: ty.TypeAlias = ty.Union[int, float, str, "Timecode", "FrameTimecode"] -"""Type hint for values that can be converted to a :class:`FrameTimecode`. Accepts a frame number -(`int`), number of seconds (`float`), timecode string (`str` of the form ``HH:MM:SS[.nnn]``), a -:class:`Timecode`, or an existing :class:`FrameTimecode`.""" +TimecodeLike: ty.TypeAlias = ty.Union[int, float, str, "Timecode"] +"""Frame-or-time input accepted by :func:`parse_frame_or_time`: a frame number (`int`), +seconds (`float`), a frame/seconds/clock string (`str`), or a :class:`Timecode`.""" -TimecodePair = tuple["FrameTimecode", "FrameTimecode"] -"""Type hint for timecode pairs, typically representing the start/end of a scene.""" +PositionPair = tuple["FramePosition", "FramePosition"] +"""Type hint for position pairs, typically representing the start/end of a scene.""" ## ## Constants @@ -110,23 +63,13 @@ """Maximum amount two framerates can differ by for equality testing. Currently 1 frame/nanosec.""" # `datetime.timedelta` does not expose seconds per minute/hour as constants, so we define our own. -_SECONDS_PER_MINUTE = 60.0 -_SECONDS_PER_HOUR = 60.0 * _SECONDS_PER_MINUTE -_MINUTES_PER_HOUR = 60.0 +_SECONDS_PER_MINUTE = 60 +_SECONDS_PER_HOUR = 60 * _SECONDS_PER_MINUTE # Tolerance for snapping a float value's framerate to an NTSC-derived rational (N * 1000/1001). # e.g. 23.976 should be detected as 24000/1001, 29.97 should be detected as 30000/1001, etc. _NTSC_DETECTION_TOLERANCE: float = 1e-3 -# Float error allowed, in units in the last place (ulps) of the scaled value, when truncating a -# time to a number of decimal places, e.g. 0.29 * 100 == 28.999999999999996 should truncate to 29, -# not 28. Converting a time to seconds and scaling it by a power of ten each add at most about one -# ulp of error, so a few ulps absorb it while staying far below the spacing of real timestamps. -# The limit is very long videos at high precision: at precision 9 with a 1/90000 time base, the -# tolerance passes the gap between timestamps after about 40 hours, and the last digit can come -# out one higher than it should. -_TRUNCATION_ULPS: int = 4 - ## ## Helpers @@ -193,699 +136,164 @@ def __post_init__(self): ) @property - def seconds(self) -> float: - return float(self.time_base * self.pts) + def seconds(self) -> Fraction: + return self.time_base * self.pts + def get_timecode(self, precision: int = 3, use_rounding: bool = True) -> str: + """Format the timestamp as HH:MM:SS[.nnn].""" + if precision < 0: + raise ValueError("precision must be non-negative") -@dataclass(frozen=True) -class _FrameNumber: - """Represents a time as a frame number.""" + seconds = self.seconds + scale = 10**precision + scaled = abs(seconds) * scale + units = round(scaled) if use_rounding else scaled.numerator // scaled.denominator - value: int + whole_seconds, fraction = divmod(units, scale) + hours, remainder = divmod(whole_seconds, _SECONDS_PER_HOUR) + minutes, seconds_part = divmod(remainder, _SECONDS_PER_MINUTE) + sign = "-" if seconds < 0 and units else "" + suffix = f".{fraction:0{precision}d}" if precision else "" + return f"{sign}{hours:02d}:{minutes:02d}:{seconds_part:02d}{suffix}" -@dataclass(frozen=True) -class _Seconds: - """Represents a time in seconds.""" - value: float +def parse_frame_or_time(value: TimecodeLike) -> int | Fraction: + """Parse a non-negative input, preserving frames (int) or seconds (Fraction). + Digit-only strings denote frames. Decimal strings, seconds suffixed with ``s``, + and ``MM:SS``/``HH:MM:SS`` strings denote seconds. A Timecode uses its exact + ``pts * time_base``; floats use their decimal string representation. No FPS + conversion or frame rounding is performed. -class FrameTimecode: - """Object for frame-based timecodes, using the video framerate to compute back and - forth between frame number and seconds/timecode. + Raises: + TypeError: Unsupported input type (including bool). + ValueError: Negative, non-finite, or malformed input, or invalid time base. + """ + result: int | Fraction + if isinstance(value, bool): + raise TypeError("Boolean values are not frame-or-time inputs.") + if isinstance(value, int): + result = value + elif isinstance(value, float): + if not math.isfinite(value): + raise ValueError("Time must be finite.") + result = Fraction(str(value)) + elif isinstance(value, Timecode): + if value.time_base <= 0: + raise ValueError("Time base must be positive.") + result = value.seconds + elif isinstance(value, str): + text = value.strip() + if re.fullmatch(r"[0-9]+", text): + return int(text) + parts = text.split(":") + if len(parts) not in (1, 2, 3): + raise ValueError("Invalid timecode format.") + hours = minutes = 0 + seconds_text = parts[-1] + if len(parts) == 1: + seconds_text = seconds_text.removesuffix("s") + else: + if not all(re.fullmatch(r"[0-9]+", part) for part in parts[:-1]): + raise ValueError("Invalid timecode format.") + hours = int(parts[0]) if len(parts) == 3 else 0 + minutes = int(parts[-2]) + if not re.fullmatch(r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)", seconds_text): + raise ValueError("Invalid timecode seconds.") + seconds = Fraction(seconds_text) + if len(parts) > 1 and (minutes >= 60 or seconds >= 60): + raise ValueError("Timecode minutes and seconds must be less than 60.") + result = hours * 3600 + minutes * 60 + seconds + else: + raise TypeError(f"Unsupported frame-or-time input: {type(value)}") + if result < 0: + raise ValueError("Frame-or-time input must be non-negative.") + return result - A timecode is valid only if it complies with one of the following three types/formats: - 1. Timecode as `str` in the form "HH:MM:SS[.nnn]" (`"01:23:45"` or `"01:23:45.678"`) - 2. Number of seconds as `float`, or `str` in form "SSSS.nnnn" (`"45.678"`) - 3. Exact number of frames as `int`, or `str` in form NNNNN (`456` or `"456"`) - Rate-related properties: - * :attr:`framerate` is a ``float`` (legacy / deprecated alias). - * :attr:`frame_rate` is a ``Fraction`` and is the canonical form. Both represent - the same rate. - * :attr:`time_base` equals ``1 / frame_rate`` for CFR sources. For VFR - (:class:`Timecode`-backed) instances, ``time_base`` is authoritative and - ``frame_rate`` is an approximation. +@dataclass(frozen=True) +class FramePosition: + """Represents a frame's position, including its timecode and frame number. - Comparisons between two :class:`Timecode`-backed instances with the same rate are performed - exactly using ``pts * time_base`` as rational numbers. All other comparisons between two - rated instances use frame numbers, which for VFR sources are approximations. + Ordering compares frame numbers within the same stream and numbering sequence. + Equality uses both fields. String conversion formats the presentation timestamp. """ - def __init__( - self, - timecode: "TimecodeLike", - fps: "float | FrameTimecode | Fraction | None" = None, - ): - """ - Arguments: - timecode: A frame number (`int`), number of seconds (`float`), timecode string in - the form `'HH:MM:SS'` or `'HH:MM:SS.nnn'`, or a `Timecode`. - fps: The framerate to use for distance between frames and to calculate frame numbers. - For a VFR video, this may just be the average framerate. - Raises: - TypeError: Thrown if either `timecode` or `fps` are unsupported types. - ValueError: Thrown when specifying a negative timecode or framerate. - """ - self._time: _FrameNumber | _Seconds | Timecode - """Internal time representation.""" - self._rate: Fraction | None = None - """Rate at which time passes between frames, measured in frames/sec.""" - - # Copy constructor. - if isinstance(timecode, FrameTimecode): - self._time = timecode._time - self._rate = timecode._rate if fps is None else self._ensure_fractional(fps) - return - - # Ensure args are consistent with API. - if fps is None: - raise TypeError("fps is a required argument.") - self._rate = self._ensure_fractional(fps) - - # Timecode with a time base. - if isinstance(timecode, Timecode): - self._time = timecode - return - - # Process the timecode value, storing it as an exact number of frames only if required. - if isinstance(timecode, str) and timecode.isdigit(): - timecode = int(timecode) - - if isinstance(timecode, str): - self._time = _Seconds(self._timecode_to_seconds(timecode)) - elif isinstance(timecode, float): - if timecode < 0.0: - raise ValueError("Timecode frame number must be positive and greater than zero.") - self._time = _Seconds(timecode) - else: - # Only `int` remains: `Timecode`/`FrameTimecode` returned earlier and `str`/`float` - # were just handled above. - if timecode < 0: - raise ValueError("Timecode frame number must be positive and greater than zero.") - self._time = _FrameNumber(timecode) + timecode: Timecode + frame_number: int - @property - def frame_num(self) -> int: - """The frame number. For VFR video or Timecode-backed objects, this is an approximation - based on the average framerate. Prefer using `pts` and `time_base` for precise timing.""" - if isinstance(self._time, Timecode): - # Calculate approximate frame number from seconds and framerate. - if self._rate is not None: - return round(self._time.seconds * float(self._rate)) - # No framerate available - return estimate based on time. - return round(self._time.seconds) - if isinstance(self._time, _Seconds): - return self._seconds_to_frames(self._time.value) - return self._time.value + def __sub__(self, other: "FramePosition") -> "FrameDuration": + if not isinstance(other, FramePosition): + raise TypeError(f"Cannot subtract {type(other)} from FramePosition") - @property - def frame_rate(self) -> Fraction | None: - """The frame rate as an exact rational :class:`fractions.Fraction`. + frames = self.frame_number - other.frame_number + elapsed = self.timecode.seconds - other.timecode.seconds - For CFR sources this equals ``1 / time_base``. For VFR sources the rate may be an - approximation (e.g. the average framerate); prefer :attr:`time_base` for exact PTS - arithmetic. Returns ``None`` for timecodes constructed without an associated rate - (i.e. pure :class:`Timecode` representations). - """ - return self._rate + if frames < 0 or elapsed < 0: + raise ValueError("Cannot subtract FramePosition objects with negative result") - @property - def framerate(self) -> float | None: - """[DEPRECATED] Use :attr:`frame_rate` instead. + return FrameDuration(frames=frames, elapsed=elapsed) - Returns the rate as a ``float`` for legacy compatibility. The new :attr:`frame_rate` - property returns an exact :class:`fractions.Fraction` and matches the naming used by - :attr:`scenedetect.video_stream.VideoStream.frame_rate`. - """ - warnings.warn( - "`framerate` is deprecated and scheduled for removal in v0.9; " - "use `frame_rate` instead.", - DeprecationWarning, - stacklevel=2, - ) - if self._rate is None: - return None - return float(self._rate) - - @property - def time_base(self) -> Fraction: - """The time base in which presentation time is calculated.""" - if isinstance(self._time, Timecode): - return self._time.time_base - # `_FrameNumber` / `_Seconds` are only assigned after `_rate` is set. - assert self._rate is not None - return 1 / self._rate + def get_timecode(self, precision: int = 3, use_rounding: bool = True) -> str: + """Return the timecode as a string in HH:MM:SS[.nnn] format.""" + return self.timecode.get_timecode(precision=precision, use_rounding=use_rounding) @property def pts(self) -> int: - """The presentation timestamp of the frame in units of `time_base`.""" - if isinstance(self._time, Timecode): - return self._time.pts - return self.frame_num - - def get_frames(self) -> int: - """[DEPRECATED] Get the current time/position in number of frames. - - Use the `frame_num` property instead. - - :meta private: - """ - warnings.warn( - "get_frames() is deprecated, use the `frame_num` property instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.frame_num + """Presentation timestamp in units of time_base.""" + return self.timecode.pts - def get_framerate(self) -> float | None: - """[DEPRECATED] Get Framerate: Returns the framerate used by the FrameTimecode object. - - Use the `frame_rate` property instead. + @property + def time_base(self) -> Fraction: + """Timestamp unit expressed in seconds.""" + return self.timecode.time_base - :meta private: - """ - warnings.warn( - "get_framerate() is deprecated, use the `frame_rate` property instead.", - DeprecationWarning, - stacklevel=2, - ) - if self.frame_rate is None: - return None - return float(self.frame_rate) - - def equal_frame_rate(self, other: "float | Fraction | FrameTimecode") -> bool: - """Determine whether the passed frame rate equals this object's frame rate. - - Arguments: - other: Frame rate to compare against within the precision constant defined in this - module (see :data:`MAX_FPS_DELTA`). May be a ``float``, ``Fraction``, or another - :class:`FrameTimecode`. - Returns: - bool: True if ``other`` matches this :class:`FrameTimecode`'s frame rate within - tolerance, False otherwise. - - """ - if self.frame_rate is None: - return False - if isinstance(other, FrameTimecode): - if other.frame_rate is None: - return False - other = other.frame_rate - return math.fabs(float(self.frame_rate) - float(other)) < MAX_FPS_DELTA - - def equal_framerate(self, fps) -> bool: - """[DEPRECATED] Use :meth:`equal_frame_rate` instead.""" - warnings.warn( - "`equal_framerate()` is deprecated and scheduled for removal in v0.9; " - "use `equal_frame_rate()` instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.equal_frame_rate(fps) + def __str__(self) -> str: + return self.timecode.get_timecode() @property def seconds(self) -> float: - """The frame's position in number of seconds.""" - if isinstance(self._time, Timecode): - return self._time.seconds - if isinstance(self._time, _Seconds): - return self._time.value - # `_FrameNumber` is only assigned after `_rate` is set. - assert self._rate is not None - return float(self._time.value / self._rate) - - def get_seconds(self) -> float: - """[DEPRECATED] Get the frame's position in number of seconds. - - Use the `seconds` property instead. - - If using to compare a :class:`FrameTimecode` with a frame number, - you can do so directly against the object (e.g. ``FrameTimecode(10, 10.0) <= 1.0``). - - Returns: - float: The current time/position in seconds. + """Return the timecode in seconds as a float. This is a convenience property for + compatibility with legacy code that expects a float value. Use `timecode.seconds` for + the underlying Fraction value.""" + return float(self.timecode.seconds) - :meta private: - """ + @property + def frame_num(self) -> int: + """Deprecated alias for frame_number""" warnings.warn( - "get_seconds() is deprecated, use the `seconds` property instead.", + "`frame_num` is deprecated; use `frame_number` instead.", DeprecationWarning, stacklevel=2, ) - return self.seconds - - # TODO(https://scenedetect.com/issue/168): We should remove `nearest_frame` if possible, it - # assumes constant framerate and causes more problems than it solves. Setting it to False makes - # test_cli_load_scenes_with_time_frames in test_cli.py fail due to differences in end time. - # We may also just need to clamp end time to the one specified by the user, this may not be - # happening in the code. - def get_timecode( - self, precision: int = 3, use_rounding: bool = True, nearest_frame: bool = True - ) -> str: - """Get a formatted timecode string of the form HH:MM:SS[.nnn]. - - Arguments: - precision: The number of decimal places to include in the output ``[.nnn]``. - use_rounding: Rounds the output to the desired precision. If False, the value - will be truncated to the specified precision. - nearest_frame: Ensures that the timecode is moved to the nearest frame boundary if this - object has a defined framerate, otherwise has no effect. - - Returns: - str: The current time in the form ``"HH:MM:SS[.nnn]"``. A negative time (e.g. from a - negative PTS) is shown as zero. - - Raises: - ValueError: `precision` is negative. - """ - if precision < 0: - raise ValueError("precision must not be negative") - # Compute hours and minutes based off of seconds, and update seconds. - # For PTS-backed timecodes, the PTS already represents an exact frame boundary, so we use - # `seconds` directly. For non-PTS timecodes, `nearest_frame` snaps to the nearest frame - # boundary using frame_num, which avoids floating point drift in CFR video display. - if nearest_frame and self.frame_rate and not isinstance(self._time, Timecode): - secs = self.frame_num / float(self.frame_rate) - else: - secs = self.seconds - # Negative times (e.g. from a negative PTS) are shown as zero on both paths below. - secs = max(0.0, secs) - if not use_rounding: - # Truncate in whole units of the output precision, allowing for float error (see - # _TRUNCATION_ULPS). The split into hours, minutes and seconds is done with integers so - # that no further float error can creep in. - scaled = secs * 10**precision - units = math.floor(scaled + _TRUNCATION_ULPS * math.ulp(scaled)) - whole_secs, fraction = divmod(units, 10**precision) - hrs, whole_secs = divmod(whole_secs, int(_SECONDS_PER_HOUR)) - mins, whole_secs = divmod(whole_secs, int(_SECONDS_PER_MINUTE)) - msec_str = f".{fraction:0{precision}d}" if precision else "" - return f"{hrs:02d}:{mins:02d}:{whole_secs:02d}{msec_str}" - hrs = int(secs / _SECONDS_PER_HOUR) - secs -= hrs * _SECONDS_PER_HOUR - mins = int(secs / _SECONDS_PER_MINUTE) - secs = max(0.0, secs - (mins * _SECONDS_PER_MINUTE)) - secs = round(secs, precision) - secs = min(_SECONDS_PER_MINUTE, secs) - # Guard against emitting timecodes with 60 seconds after rounding/floating point errors. - if int(secs) == _SECONDS_PER_MINUTE: - secs = 0.0 - mins += 1 - if mins >= _MINUTES_PER_HOUR: - mins = 0 - hrs += 1 - # We have to extend the precision by 1 here, since `format` will round up. - msec = format(secs, f".{precision + 1}f") if precision else "" - # Need to include decimal place in `msec_str`. - msec_str = msec[-(2 + precision) : -1] - secs_str = f"{int(secs):02d}{msec_str}" - # Return hours, minutes, and seconds as a formatted timecode string. - return f"{hrs:02d}:{mins:02d}:{secs_str}" - - @staticmethod - def _ensure_fractional(fps: "FrameRate | numbers.Rational | FrameTimecode") -> Fraction: - """Validate and convert an `fps` argument into a positive `Fraction`. NTSC-like frame rates - are handled via :func:`framerate_to_fraction`.""" - if isinstance(fps, FrameTimecode): - if fps._rate is None: - raise TypeError("FrameTimecode passed as fps must have a known rate.") - return fps._rate - # Accept floats and non-integral rationals (`Fraction`, PyAV 19's `av.AVRational`), but - # keep rejecting `int`/`bool` so an accidental frame count is not treated as a frame rate. - if isinstance(fps, (float, numbers.Rational)) and not isinstance(fps, numbers.Integral): - return framerate_to_fraction(fps) - raise TypeError( - f"Wrong type for fps: {type(fps)} - expected float, Fraction (or another non-integral" - " rational), or FrameTimecode" - ) + return self.frame_number - def _seconds_to_frames(self, seconds: float) -> int: - """Convert `seconds` to the nearest number of frames using the current framerate. - - *NOTE*: This will not be correct for variable framerate videos. - """ - assert self._rate is not None - return round(seconds * self._rate) - - def _timecode_to_seconds(self, input: str) -> float: - """Parses a string based on the three possible forms (in timecode format, as an integer - number of frames, or floating-point seconds, ending with 's'). Exact frame numbers (int) - requires the `framerate` property was set when the timecode was created. Assuming a - framerate of 30.0 FPS, the strings '00:05:00.000', '00:05:00', '9000', '300s', and - '300.0' are all possible valid values. These values represent periods of time equal to - 5 minutes, 300 seconds, or 9000 frames (at 30 FPS). - - Raises: - ValueError: Value could not be parsed correctly. - """ - assert self._rate is not None and self._rate > MAX_FPS_DELTA - input = input.strip() - # Exact number of frames N - if input.isdigit(): - timecode = int(input) - if timecode < 0: - raise ValueError("Timecode frame number must be positive.") - return timecode / float(self._rate) - # Timecode in string format 'HH:MM:SS[.nnn]' or 'MM:SS[.nnn]' - elif input.find(":") >= 0: - values = input.split(":") - if len(values) not in (2, 3): - raise ValueError("Invalid timecode (too many separators).") - # Case of 'HH:MM:SS[.nnn]' - if len(values) == 3: - hrs, mins = int(values[0]), int(values[1]) - secs = float(values[2]) if "." in values[2] else int(values[2]) - # Case of 'MM:SS[.nnn]' - elif len(values) == 2: - hrs = 0 - mins = int(values[0]) - secs = float(values[1]) if "." in values[1] else int(values[1]) - if not (hrs >= 0 and mins >= 0 and secs >= 0 and mins < 60 and secs < 60): - raise ValueError("Invalid timecode range (values outside allowed range).") - secs += (hrs * 60 * 60) + (mins * 60) - return secs - # Try to parse the number as seconds in the format 1234.5 or 1234s - if input.endswith("s"): - input = input[:-1] - if not input.replace(".", "").isdigit(): - raise ValueError("All characters in timecode seconds string must be digits.") - as_float = float(input) - if as_float < 0.0: - raise ValueError("Timecode seconds value must be positive.") - return as_float - - def _get_other_as_frames(self, other: "TimecodeLike") -> int: - """Get the frame number from `other` for arithmetic operations.""" - if isinstance(other, int): - return other - if isinstance(other, float): - return self._seconds_to_frames(other) - if isinstance(other, str): - return self._seconds_to_frames(self._timecode_to_seconds(other)) - if isinstance(other, Timecode): - return self._seconds_to_frames(other.seconds) - if isinstance(other, FrameTimecode): - # If comparing two FrameTimecodes, they must have the same framerate for frame-based - # operations. - if self._rate and other._rate and not self.equal_frame_rate(other._rate): - raise ValueError( - "FrameTimecode instances require equal frame rate for frame-based arithmetic." - ) - if isinstance(other._time, _FrameNumber): - return other._time.value - # If other has no frame_num, it must have a timecode. Convert to frames. - return self._seconds_to_frames(other.seconds) - raise TypeError("Cannot obtain frame number for this timecode.") - - def __eq__(self, other: "TimecodeLike") -> bool: - if other is None: - return False - exact = _compare_as_exact(other, self) - if exact is not None: - return exact[0] == exact[1] - if _compare_as_fixed(other, self): - return self.frame_num == other.frame_num - # For integer comparison, use frame numbers to avoid floating point precision issues. - if isinstance(other, int): - return self.frame_num == other - if isinstance(self._time, (Timecode, _Seconds)): - return self.seconds == self._get_other_as_seconds(other) - return self.frame_num == self._get_other_as_frames(other) - - def __ne__(self, other: "TimecodeLike") -> bool: - if other is None: - return True - exact = _compare_as_exact(other, self) - if exact is not None: - return exact[0] != exact[1] - if _compare_as_fixed(other, self): - return self.frame_num != other.frame_num - # For integer comparison, use frame numbers to avoid floating point precision issues. - if isinstance(other, int): - return self.frame_num != other - if isinstance(self._time, (Timecode, _Seconds)): - return self.seconds != self._get_other_as_seconds(other) - return self.frame_num != self._get_other_as_frames(other) - - def __lt__(self, other: "TimecodeLike") -> bool: - exact = _compare_as_exact(other, self) - if exact is not None: - return exact[0] < exact[1] - if _compare_as_fixed(other, self): - return self.frame_num < other.frame_num - # For integer comparison, use frame numbers to avoid floating point precision issues. - if isinstance(other, int): - return self.frame_num < other - if isinstance(self._time, (Timecode, _Seconds)): - return self.seconds < self._get_other_as_seconds(other) - return self.frame_num < self._get_other_as_frames(other) - - def __le__(self, other: "TimecodeLike") -> bool: - exact = _compare_as_exact(other, self) - if exact is not None: - return exact[0] <= exact[1] - if _compare_as_fixed(other, self): - return self.frame_num <= other.frame_num - # For integer comparison, use frame numbers to avoid floating point precision issues. - if isinstance(other, int): - return self.frame_num <= other - if isinstance(self._time, (Timecode, _Seconds)): - return self.seconds <= self._get_other_as_seconds(other) - return self.frame_num <= self._get_other_as_frames(other) - - def __gt__(self, other: "TimecodeLike") -> bool: - exact = _compare_as_exact(other, self) - if exact is not None: - return exact[0] > exact[1] - if _compare_as_fixed(other, self): - return self.frame_num > other.frame_num - # For integer comparison, use frame numbers to avoid floating point precision issues. - if isinstance(other, int): - return self.frame_num > other - if isinstance(self._time, (Timecode, _Seconds)): - return self.seconds > self._get_other_as_seconds(other) - return self.frame_num > self._get_other_as_frames(other) - - def __ge__(self, other: "TimecodeLike") -> bool: - exact = _compare_as_exact(other, self) - if exact is not None: - return exact[0] >= exact[1] - if _compare_as_fixed(other, self): - return self.frame_num >= other.frame_num - # For integer comparison, use frame numbers to avoid floating point precision issues. - if isinstance(other, int): - return self.frame_num >= other - if isinstance(self._time, (Timecode, _Seconds)): - return self.seconds >= self._get_other_as_seconds(other) - return self.frame_num >= self._get_other_as_frames(other) - - def __iadd__(self, other: "TimecodeLike") -> "FrameTimecode": - # Narrow `other`'s internal time once so pyright can track it through the dispatch below. - # A bare `Timecode` is treated as its own internal time. - if isinstance(other, FrameTimecode): - other_inner = other._time - elif isinstance(other, Timecode): - other_inner = other - else: - other_inner = None - - if isinstance(self._time, Timecode) and isinstance(other_inner, Timecode): - if self._time.time_base == other_inner.time_base: - self._time = Timecode( - pts=max(0, self._time.pts + other_inner.pts), - time_base=self._time.time_base, - ) - return self - # Different time bases: use the finer (smaller) one for better precision. - time_base = min(self._time.time_base, other_inner.time_base) - self_pts = round(Fraction(self._time.pts) * self._time.time_base / time_base) - other_pts = round(Fraction(other_inner.pts) * other_inner.time_base / time_base) - self._time = Timecode(pts=max(0, self_pts + other_pts), time_base=time_base) - return self - - # If either input is a timecode, the output shall also be one. The input which isn't a - # timecode is converted into seconds, after which the equivalent timecode is computed. - if isinstance(self._time, Timecode): - seconds = self._get_other_as_seconds(other) - self._time = Timecode( - pts=max(0, self._time.pts + round(seconds / self._time.time_base)), - time_base=self._time.time_base, - ) - if self._rate is None and isinstance(other, FrameTimecode): - self._rate = other._rate - return self - if isinstance(other_inner, Timecode): - self._time = Timecode( - pts=max(0, other_inner.pts + round(self.seconds / other_inner.time_base)), - time_base=other_inner.time_base, - ) - if self._rate is None and isinstance(other, FrameTimecode): - self._rate = other._rate - return self - - if isinstance(self._time, _Seconds) and isinstance(other_inner, _Seconds): - self._time = _Seconds(max(0.0, self._time.value + other_inner.value)) - return self - - if isinstance(self._time, _Seconds): - self._time = _Seconds(max(0.0, self._time.value + self._get_other_as_seconds(other))) - return self - - self._time = _FrameNumber(max(0, self._time.value + self._get_other_as_frames(other))) - return self - - def __add__(self, other: "TimecodeLike") -> "FrameTimecode": - to_return = FrameTimecode(timecode=self) - to_return += other - return to_return - - def __isub__(self, other: "TimecodeLike") -> "FrameTimecode": - # Narrow `other`'s internal time once so pyright can track it through the dispatch below. - # A bare `Timecode` is treated as its own internal time. - if isinstance(other, FrameTimecode): - other_inner = other._time - elif isinstance(other, Timecode): - other_inner = other - else: - other_inner = None - - if isinstance(self._time, Timecode) and isinstance(other_inner, Timecode): - if self._time.time_base == other_inner.time_base: - self._time = Timecode( - pts=max(0, self._time.pts - other_inner.pts), - time_base=self._time.time_base, - ) - return self - # Different time bases: use the finer (smaller) one for better precision. - time_base = min(self._time.time_base, other_inner.time_base) - self_pts = round(Fraction(self._time.pts) * self._time.time_base / time_base) - other_pts = round(Fraction(other_inner.pts) * other_inner.time_base / time_base) - self._time = Timecode(pts=max(0, self_pts - other_pts), time_base=time_base) - return self - - # If either input is a timecode, the output shall also be one. The input which isn't a - # timecode is converted into seconds, after which the equivalent timecode is computed. - if isinstance(self._time, Timecode): - seconds = self._get_other_as_seconds(other) - self._time = Timecode( - pts=max(0, self._time.pts - round(seconds / self._time.time_base)), - time_base=self._time.time_base, - ) - if self._rate is None and isinstance(other, FrameTimecode): - self._rate = other._rate - return self - if isinstance(other_inner, Timecode): - # Compute `self - other` in `other`'s time base. - self_pts_in_other_base = round(self.seconds / other_inner.time_base) - self._time = Timecode( - pts=max(0, self_pts_in_other_base - other_inner.pts), - time_base=other_inner.time_base, - ) - if self._rate is None and isinstance(other, FrameTimecode): - self._rate = other._rate - return self - - if isinstance(self._time, _Seconds) and isinstance(other_inner, _Seconds): - self._time = _Seconds(max(0.0, self._time.value - other_inner.value)) - return self - - if isinstance(self._time, _Seconds): - self._time = _Seconds(max(0.0, self._time.value - self._get_other_as_seconds(other))) - return self + def get_frames(self) -> int: + """Return the frame number. This is a convenience method for compatibility with legacy + code that expects a `get_frames()` method. Use `frame_number` for the underlying value.""" + return self.frame_number - self._time = _FrameNumber(max(0, self._time.value - self._get_other_as_frames(other))) - return self + def get_seconds(self) -> float: + """Return the timecode in seconds as a float. This is a convenience method for + compatibility with legacy code that expects a `get_seconds()` method. Use + `timecode.seconds` for the underlying Fraction value.""" + return float(self.timecode.seconds) - def __sub__(self, other: "TimecodeLike") -> "FrameTimecode": - to_return = FrameTimecode(timecode=self) - to_return -= other - return to_return + def __lt__(self, other: "FramePosition") -> bool: + if not isinstance(other, FramePosition): + return NotImplemented + return self.frame_number < other.frame_number - # TODO(v1.0): __int__ and __float__ should be removed. Mark as deprecated, and indicate - # need to use relevant property instead. + def __gt__(self, other: "FramePosition") -> bool: + if not isinstance(other, FramePosition): + return NotImplemented + return self.frame_number > other.frame_number - def __int__(self) -> int: - if isinstance(self._time, _FrameNumber): - return self._time.value - return self.frame_num - def __float__(self) -> float: - return self.seconds +@dataclass(frozen=True) +class FrameDuration: + """Represents a duration of time, including its length in frames and seconds.""" - def __str__(self) -> str: - return self.get_timecode() - - def __repr__(self) -> str: - if isinstance(self._time, Timecode): - return f"{self.get_timecode()} [pts={self._time.pts}, time_base={self._time.time_base}]" - if isinstance(self._time, _Seconds): - return f"{self.get_timecode()} [seconds={self._time.value}, fps={self._rate}]" - return f"{self.get_timecode()} [frame_num={self._time.value}, fps={self._rate}]" - - def __hash__(self) -> int: - # Use frame_num for consistent hashing regardless of internal representation. - # This ensures that FrameTimecodes representing the same frame have the same hash, - # enabling proper dictionary lookups in StatsManager (including int-key interop). - # Exact (PTS-based) equality requires equal rates (`_compare_as_exact`), and equal exact - # times with equal rates always derive the same frame_num, so a == b still implies - # hash(a) == hash(b). Distinct exact times which round to the same frame number compare - # unequal and coexist as a hash collision. - return self.frame_num - - def _get_other_as_seconds(self, other: "TimecodeLike") -> float: - """Get the time in seconds from `other` for arithmetic operations.""" - if isinstance(other, int): - # Convert frame number to seconds using framerate. - if self._rate is None: - raise NotImplementedError( - "Cannot convert frame number to seconds without framerate" - ) - return float(other) / float(self._rate) - if isinstance(other, float): - return other - if isinstance(other, str): - return self._timecode_to_seconds(other) - if isinstance(other, Timecode): - return other.seconds - if isinstance(other, FrameTimecode): - return other.seconds - raise TypeError("Unsupported type for performing arithmetic with FrameTimecode.") - - -def _compare_as_fixed(other: ty.Any, base: FrameTimecode) -> ty.TypeGuard[FrameTimecode]: - """Type guard: True (and narrows `other` to `FrameTimecode`) iff both timecodes have a known - framerate, in which case frame-based comparison is exact and preferred over float seconds. - - This is the fallback when `_compare_as_exact` does not apply (i.e. at least one operand - lacks an exact presentation time, or the rates differ).""" - return base._rate is not None and isinstance(other, FrameTimecode) and other._rate is not None - - -def _compare_as_exact(other: ty.Any, base: FrameTimecode) -> "tuple[Fraction, Fraction] | None": - """If both operands carry exact presentation times (are :class:`Timecode`-backed) and share - the same nominal rate, return both times as exact rational seconds (``pts * time_base``) for - comparison, otherwise return ``None``. - - For Timecode-backed instances (e.g. VFR video positions), `frame_num` is an approximation - derived from the average framerate, so distinct presentation times can round to the same - frame number; the rational times are exact. The same-rate requirement keeps cross-rate - comparisons on the frame-number path, which both preserves existing cross-rate semantics and - guarantees ``__eq__``/``__hash__`` consistency: ``__hash__`` is derived from ``frame_num`` - (rate-dependent), and for equal rates, equal exact times always produce equal frame numbers. - - Returns the extracted pair instead of acting as a type guard since a TypeGuard can only - narrow `other`, not `other._time` or `base._time`. - """ - if ( - isinstance(base._time, Timecode) - and isinstance(other, FrameTimecode) - and isinstance(other._time, Timecode) - and base._rate == other._rate - ): - return ( - base._time.pts * base._time.time_base, - other._time.pts * other._time.time_base, - ) - return None + frames: int + elapsed: Fraction diff --git a/scenedetect/detector.py b/scenedetect/detector.py index 954e9504..f498ada1 100644 --- a/scenedetect/detector.py +++ b/scenedetect/detector.py @@ -20,17 +20,23 @@ .. warning:: This API is still unstable, and changes and design improvements are planned for the v1.0 - release. Instead of just timecodes, detection algorithms will also provide a specific type of - event (in, out, cut, etc...). + release. Instead of just frame positions, detection algorithms will also provide a specific + type of event (in, out, cut, etc...). """ import math from abc import ABC, abstractmethod from enum import Enum +from fractions import Fraction import numpy -from scenedetect.common import FrameTimecode, Timecode, TimecodeLike +from scenedetect.common import ( + FrameDuration, + FramePosition, + TimecodeLike, + parse_frame_or_time, +) from scenedetect.stats_manager import StatsManager @@ -47,28 +53,28 @@ def __init__(self): @abstractmethod def process_frame( - self, timecode: FrameTimecode, frame_img: numpy.ndarray - ) -> list[FrameTimecode]: - """Process the next frame. `timecode` is assumed to be sequential. + self, position: FramePosition, frame_img: numpy.ndarray + ) -> list[FramePosition]: + """Process the next frame. `position.frame_number` is assumed to increase. Arguments: - timecode: Timecode corresponding to the frame being processed. + position: Frame position corresponding to the frame being processed. frame_img: Video frame as a 24-bit BGR image. Returns: - List of timecodes where scene cuts have been detected, if any. + List of frame positions where scene cuts have been detected, if any. """ # Optional Methods - def post_process(self, timecode: FrameTimecode) -> list[FrameTimecode]: + def post_process(self, position: FramePosition) -> list[FramePosition]: """Called after there are no more frames to process. Arguments: - timecode: The last position in the video which was read. + position: The last position in the video which was read. Returns: - List of timecodes where scene cuts have been detected, if any. + List of frame positions where scene cuts have been detected, if any. """ return [] @@ -102,6 +108,13 @@ def get_metrics(self) -> list[str]: """ return [] + def meets_minimum(self, duration: FrameDuration, minimum: int | Fraction) -> bool: + + if isinstance(minimum, (int)): + return duration.frames >= minimum + + return duration.elapsed >= minimum + class FlashFilter: """Filters fast-cuts to enforce minimum scene length.""" @@ -118,99 +131,81 @@ def __init__(self, mode: Mode, length: TimecodeLike): """ Arguments: mode: The mode to use when enforcing `length`. - length: Minimum scene length. Accepts any :data:`~scenedetect.common.TimecodeLike` value - (e.g. ``int`` frames, ``float`` seconds, ``str`` such as ``"0.6s"`` / - ``"00:00:00.600"``, or a :class:`~scenedetect.common.FrameTimecode` / - :class:`~scenedetect.common.Timecode`). + length: Minimum scene length. Accepts any :data:`TimecodeLike` value (e.g. + ``int`` frames, ``float`` seconds, ``str`` such as ``"0.6s"`` / + ``"00:00:00.600"``, or a :class:`~scenedetect.common.Timecode`). """ self._mode = mode - # Frame count (int) and seconds (float) representations of `length`. Exactly one is - # populated. Temporal inputs (float/non-digit str / Timecode / FrameTimecode) populate - # `_filter_secs`; integer inputs (int/digit str) populate `_filter_length`, which is - # compared as a frame count so no conversion to seconds is needed (#577). - self._filter_length: int = 0 - self._filter_secs: float | None = None - if isinstance(length, float): - self._filter_secs = length - elif isinstance(length, str) and not length.strip().isdigit(): - self._filter_secs = FrameTimecode(timecode=length, fps=100.0).seconds - elif isinstance(length, (Timecode, FrameTimecode)): - self._filter_secs = length.seconds - else: - self._filter_length = int(length) - self._last_above: FrameTimecode | None = None # Last frame above threshold. + self._filter_length: int | Fraction = parse_frame_or_time(length) + self._last_above: FramePosition | None = None # Reference for minimum-length checks. self._merge_enabled = False # Used to disable merging until at least one cut was found. self._merge_triggered = False # True when the merge filter is active. - self._merge_start: FrameTimecode | None = None # Frame where we started merging. + self._merge_start: FramePosition | None = None # Frame where we started merging. @property def max_behind(self) -> int: + """Image-buffer budget for delayed cuts, in frames. + + Time-based MERGE lengths use a 240 FPS estimate. This estimate does not affect + the minimum-length checks. + """ if self._mode == FlashFilter.Mode.SUPPRESS: return 0 - if self._filter_secs is not None: - # Estimate using 240fps so the event buffer is large enough for any reasonable input. - return math.ceil(self._filter_secs * 240.0) + if isinstance(self._filter_length, Fraction): + # TODO: Replace the fixed FPS estimate with duration-aware event buffering. + return math.ceil(self._filter_length * 240) return self._filter_length @property def _is_disabled(self) -> bool: - if self._filter_secs is not None: - return self._filter_secs <= 0.0 return self._filter_length <= 0 - def filter(self, timecode: FrameTimecode, above_threshold: bool) -> list[FrameTimecode]: + def _meets_minimum(self, duration: FrameDuration) -> bool: + if isinstance(self._filter_length, int): + return duration.frames >= self._filter_length + return duration.elapsed >= self._filter_length + + def filter(self, position: FramePosition, above_threshold: bool) -> list[FramePosition]: + """Process one frame's cut-candidate flag and return accepted cut positions. + + Call for every processed frame, including frames below the threshold. + MERGE can return a position saved from an earlier call. + """ if self._is_disabled: - return [timecode] if above_threshold else [] + return [position] if above_threshold else [] if self._last_above is None: - self._last_above = timecode + self._last_above = position if self._mode == FlashFilter.Mode.MERGE: - return self._filter_merge(timecode=timecode, above_threshold=above_threshold) + return self._filter_merge(position=position, above_threshold=above_threshold) elif self._mode == FlashFilter.Mode.SUPPRESS: - return self._filter_suppress(timecode=timecode, above_threshold=above_threshold) + return self._filter_suppress(position=position, above_threshold=above_threshold) raise RuntimeError("Unhandled FlashFilter mode.") - def _min_length_met(self, from_tc: FrameTimecode, to_tc: FrameTimecode) -> bool: - """Whether `to_tc` is at least the minimum scene length past `from_tc`. - - When the length was given in frames, compare frame counts directly so an - exact N-frame gap is not lost to float conversion at NTSC rates (#577). - `FrameTimecode.__ge__` compares an int against `frame_num` exactly, so - this avoids the one-ulp error of `length / float(frame_rate)`. - """ - if self._filter_length > 0: - return (to_tc - from_tc) >= self._filter_length - assert self._filter_secs is not None - return (to_tc - from_tc) >= self._filter_secs - def _filter_suppress( - self, timecode: FrameTimecode, above_threshold: bool - ) -> list[FrameTimecode]: - frame_rate = timecode.frame_rate - assert frame_rate is not None and frame_rate >= 0 + self, position: FramePosition, above_threshold: bool + ) -> list[FramePosition]: assert self._last_above is not None - min_length_met: bool = self._min_length_met(self._last_above, timecode) + min_length_met: bool = self._meets_minimum(position - self._last_above) if not (above_threshold and min_length_met): return [] # Both length and threshold requirements were satisfied. Emit the cut, and wait until both # requirements are met again. - self._last_above = timecode - return [timecode] + self._last_above = position + return [position] - def _filter_merge(self, timecode: FrameTimecode, above_threshold: bool) -> list[FrameTimecode]: - frame_rate = timecode.frame_rate - assert frame_rate is not None and frame_rate >= 0 + def _filter_merge(self, position: FramePosition, above_threshold: bool) -> list[FramePosition]: assert self._last_above is not None - min_length_met: bool = self._min_length_met(self._last_above, timecode) + min_length_met: bool = self._meets_minimum(position - self._last_above) # Ensure last frame is always advanced to the most recent one that was above the threshold. if above_threshold: - self._last_above = timecode + self._last_above = position if self._merge_triggered: - # This frame was under the threshold, see if enough frames passed to disable the filter. + # Finish merging when both the quiet gap and merged span meet the minimum. assert self._merge_start is not None if ( min_length_met and not above_threshold - and self._min_length_met(self._merge_start, self._last_above) + and self._meets_minimum(self._last_above - self._merge_start) ): self._merge_triggered = False return [self._last_above] @@ -223,9 +218,9 @@ def _filter_merge(self, timecode: FrameTimecode, above_threshold: bool) -> list[ if min_length_met: # Only allow the merge filter once the first cut is emitted. self._merge_enabled = True - return [timecode] + return [position] # Start merging cuts until the length requirement is met. if self._merge_enabled: self._merge_triggered = True - self._merge_start = timecode + self._merge_start = position return [] diff --git a/scenedetect/detectors/adaptive_detector.py b/scenedetect/detectors/adaptive_detector.py index 655cdf51..a22513f8 100644 --- a/scenedetect/detectors/adaptive_detector.py +++ b/scenedetect/detectors/adaptive_detector.py @@ -20,7 +20,7 @@ import numpy as np -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, TimecodeLike, parse_frame_or_time from scenedetect.detectors import ContentDetector logger = getLogger("pyscenedetect") @@ -79,7 +79,7 @@ def __init__( ) # TODO: Turn these public options into properties. - self.min_scene_len = min_scene_len + self.min_scene_len = parse_frame_or_time(min_scene_len) self.adaptive_threshold = adaptive_threshold self.min_content_val = min_content_val self.window_width = window_width @@ -87,10 +87,10 @@ def __init__( self._adaptive_ratio_key = AdaptiveDetector.ADAPTIVE_RATIO_KEY_TEMPLATE.format( window_width=window_width, luma_only="" if not luma_only else "_lum" ) - self._buffer: list[tuple[FrameTimecode, float]] = [] + self._buffer: list[tuple[FramePosition, float]] = [] # NOTE: The name of last cut is different from `self._last_scene_cut` from our base class, # and serves a different purpose! - self._last_cut: FrameTimecode | None = None + self._last_cut: FramePosition | None = None @property def event_buffer_length(self) -> int: @@ -99,8 +99,8 @@ def event_buffer_length(self) -> int: def get_metrics(self) -> list[str]: return [*super().get_metrics(), self._adaptive_ratio_key] - def process_frame(self, timecode: FrameTimecode, frame_img: np.ndarray) -> list[FrameTimecode]: - super().process_frame(timecode=timecode, frame_img=frame_img) + def process_frame(self, position: FramePosition, frame_img: np.ndarray) -> list[FramePosition]: + super().process_frame(position=position, frame_img=frame_img) # If the parent could not calculate a frame score, there's nothing to buffer. if self._frame_score is None: @@ -108,14 +108,14 @@ def process_frame(self, timecode: FrameTimecode, frame_img: np.ndarray) -> list[ # Initialize last scene cut point at the beginning of the frames of interest. if self._last_cut is None: - self._last_cut = timecode + self._last_cut = position required_frames = 1 + (2 * self.window_width) - self._buffer.append((timecode, self._frame_score)) + self._buffer.append((position, self._frame_score)) if not len(self._buffer) >= required_frames: return [] self._buffer = self._buffer[-required_frames:] - (target_timecode, target_score) = self._buffer[self.window_width] + (target_position, target_score) = self._buffer[self.window_width] average_window_score = sum( score for i, (_frame, score) in enumerate(self._buffer) if i != self.window_width ) / (2.0 * self.window_width) @@ -130,7 +130,7 @@ def process_frame(self, timecode: FrameTimecode, frame_img: np.ndarray) -> list[ adaptive_ratio = 255.0 if self.stats_manager is not None: self.stats_manager.set_metrics( - target_timecode, {self._adaptive_ratio_key: adaptive_ratio} + target_position, {self._adaptive_ratio_key: adaptive_ratio} ) # Check to see if adaptive_ratio exceeds the adaptive_threshold as well as there @@ -138,9 +138,12 @@ def process_frame(self, timecode: FrameTimecode, frame_img: np.ndarray) -> list[ threshold_met: bool = ( adaptive_ratio >= self.adaptive_threshold and target_score >= self.min_content_val ) - # Cuts are emitted at `target_timecode` (`window_width` behind `timecode`). - min_length_met: bool = (target_timecode - self._last_cut) >= self.min_scene_len + # Cuts are emitted at `target_position` (`window_width` behind `position`). + min_length_met: bool = self.meets_minimum( + target_position - self._last_cut, + self.min_scene_len, + ) if threshold_met and min_length_met: - self._last_cut = target_timecode - return [target_timecode] + self._last_cut = target_position + return [target_position] return [] diff --git a/scenedetect/detectors/content_detector.py b/scenedetect/detectors/content_detector.py index 6ad39045..9ce70157 100644 --- a/scenedetect/detectors/content_detector.py +++ b/scenedetect/detectors/content_detector.py @@ -22,7 +22,7 @@ import cv2 import numpy -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, TimecodeLike from scenedetect.detector import FlashFilter, SceneDetector @@ -150,7 +150,7 @@ def __init__( def get_metrics(self): return ContentDetector.METRIC_KEYS - def _calculate_frame_score(self, timecode: FrameTimecode, frame_img: numpy.ndarray) -> float: + def _calculate_frame_score(self, position: FramePosition, frame_img: numpy.ndarray) -> float: """Calculate score representing relative amount of motion in `frame_img` compared to the last time the function was called (returns 0.0 on the first call).""" # TODO: Add option to enable motion estimation before calculating score components. @@ -189,32 +189,32 @@ def _calculate_frame_score(self, timecode: FrameTimecode, frame_img: numpy.ndarr if self.stats_manager is not None: metrics = {self.FRAME_SCORE_KEY: frame_score} metrics.update(score_components._asdict()) - self.stats_manager.set_metrics(timecode, metrics) + self.stats_manager.set_metrics(position, metrics) # Store all data required to calculate the next frame's score. self._last_frame = ContentDetector._FrameData(hue, sat, lum, edges) return frame_score def process_frame( - self, timecode: FrameTimecode, frame_img: numpy.ndarray - ) -> list[FrameTimecode]: + self, position: FramePosition, frame_img: numpy.ndarray + ) -> list[FramePosition]: """Process the next frame. `frame_num` is assumed to be sequential. Arguments: - frame_num (int): Frame number of frame that is being passed. Can start from any value - but must remain sequential. + position (FramePosition): Position (frame_number, timecode) of frame that is + being passed. frame_img (numpy.ndarray or None): Video frame corresponding to `frame_img`. Returns: - ty.List[int]: List of frames where scene cuts have been detected. There may be 0 - or more frames in the list, and not necessarily the same as frame_num. + typing.List[FramePosition]: List of frames where scene cuts have been detected. + There may be 0 or more frames in the list, and not necessarily the same as frame_num. """ - self._frame_score = self._calculate_frame_score(timecode, frame_img) + self._frame_score = self._calculate_frame_score(position, frame_img) if self._frame_score is None: return [] above_threshold: bool = self._frame_score >= self._threshold - return self._flash_filter.filter(timecode=timecode, above_threshold=above_threshold) + return self._flash_filter.filter(position=position, above_threshold=above_threshold) def _detect_edges(self, lum: numpy.ndarray) -> numpy.ndarray: """Detect edges using the luma channel of a frame. diff --git a/scenedetect/detectors/hash_detector.py b/scenedetect/detectors/hash_detector.py index 395766c9..cc504a5a 100644 --- a/scenedetect/detectors/hash_detector.py +++ b/scenedetect/detectors/hash_detector.py @@ -19,7 +19,7 @@ import cv2 import numpy -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, TimecodeLike, parse_frame_or_time from scenedetect.detector import SceneDetector @@ -53,12 +53,12 @@ def __init__( ): super().__init__() self._threshold = threshold - self._min_scene_len = min_scene_len + self._min_scene_len = parse_frame_or_time(min_scene_len) self._size = size self._size_sq = float(size * size) self._factor = lowpass self._last_frame: numpy.ndarray | None = None - self._last_scene_cut: FrameTimecode | None = None + self._last_scene_cut: FramePosition | None = None self._last_hash = numpy.array([]) self._metric_key = f"hash_dist [size={self._size} lowpass={self._factor}]" @@ -66,8 +66,8 @@ def get_metrics(self): return [self._metric_key] def process_frame( - self, timecode: FrameTimecode, frame_img: numpy.ndarray - ) -> list[FrameTimecode]: + self, position: FramePosition, frame_img: numpy.ndarray + ) -> list[FramePosition]: """Similar to ContentDetector, but using a perceptual hashing algorithm to calculate a hash for each frame and then calculate a hash difference frame to frame.""" @@ -76,7 +76,7 @@ def process_frame( # Initialize last scene cut point at the beginning of the frames of interest. if self._last_scene_cut is None: - self._last_scene_cut = timecode + self._last_scene_cut = position # We can only start detecting once we have a frame to compare with. if self._last_frame is not None: @@ -100,17 +100,17 @@ def process_frame( hash_dist_norm = hash_dist / self._size_sq if self.stats_manager is not None: - self.stats_manager.set_metrics(timecode, {self._metric_key: hash_dist_norm}) + self.stats_manager.set_metrics(position, {self._metric_key: hash_dist_norm}) self._last_hash = curr_hash # We consider any frame over the threshold a new scene, but only if # the minimum scene length has been reached (otherwise it is ignored). if hash_dist_norm >= self._threshold and ( - (timecode - self._last_scene_cut) >= self._min_scene_len + self.meets_minimum(position - self._last_scene_cut, self._min_scene_len) ): - cut_list.append(timecode) - self._last_scene_cut = timecode + cut_list.append(position) + self._last_scene_cut = position self._last_frame = frame_img.copy() diff --git a/scenedetect/detectors/histogram_detector.py b/scenedetect/detectors/histogram_detector.py index aba17b55..bf184adb 100644 --- a/scenedetect/detectors/histogram_detector.py +++ b/scenedetect/detectors/histogram_detector.py @@ -20,7 +20,7 @@ import cv2 import numpy -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, TimecodeLike, parse_frame_or_time from scenedetect.detector import SceneDetector @@ -52,27 +52,27 @@ def __init__( # between -1.0 and 1.0. self._threshold = max(0.0, min(1.0, 1.0 - threshold)) self._bins = bins - self._min_scene_len = min_scene_len + self._min_scene_len = parse_frame_or_time(min_scene_len) self._last_hist = None self._last_cut = None self._metric_key = f"hist_diff [bins={self._bins}]" def process_frame( - self, timecode: FrameTimecode, frame_img: numpy.ndarray - ) -> list[FrameTimecode]: + self, position: FramePosition, frame_img: numpy.ndarray + ) -> list[FramePosition]: """Computes the histogram of the luma channel of the frame image and compares it with the histogram of the luma channel of the previous frame. If the difference between the histograms exceeds the threshold, a scene cut is detected. Histogram difference is computed using the correlation metric. Arguments: - timecode: Timecode of the frame that is being passed. + position: FramePosition of the frame that is being passed. frame_img: Decoded frame image (numpy.ndarray) to perform scene detection on. Returns: - List of timecodes where scene cuts have been detected. There may be 0 - or more timecodes in the list, and not necessarily the same as `timecode`. + List of FramePositions where scene cuts have been detected. There may be 0 + or more FramePositions in the list, and not necessarily the same as `position`. """ cut_list = [] @@ -86,7 +86,7 @@ def process_frame( # Initialize last scene cut point at the beginning of the frames of interest. if not self._last_cut: - self._last_cut = timecode + self._last_cut = position hist = self.calculate_histogram(frame_img, bins=self._bins) @@ -107,14 +107,14 @@ def process_frame( # correlation less than 0.8 between histograms will be considered significant enough to # denote a scene change. if hist_diff <= self._threshold and ( - (timecode - self._last_cut) >= self._min_scene_len + self.meets_minimum(position - self._last_cut, self._min_scene_len) ): - cut_list.append(timecode) - self._last_cut = timecode + cut_list.append(position) + self._last_cut = position # Save stats to a StatsManager if it is being used if self.stats_manager is not None: - self.stats_manager.set_metrics(timecode, {self._metric_key: hist_diff}) + self.stats_manager.set_metrics(position, {self._metric_key: hist_diff}) self._last_hist = hist diff --git a/scenedetect/detectors/threshold_detector.py b/scenedetect/detectors/threshold_detector.py index 3747db98..d2d01d9d 100644 --- a/scenedetect/detectors/threshold_detector.py +++ b/scenedetect/detectors/threshold_detector.py @@ -17,12 +17,20 @@ import typing as ty import warnings +from bisect import bisect_left from enum import Enum +from fractions import Fraction from logging import getLogger import numpy -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import ( + FrameDuration, + FramePosition, + Timecode, + TimecodeLike, + parse_frame_or_time, +) from scenedetect.detector import SceneDetector logger = getLogger("pyscenedetect") @@ -91,53 +99,52 @@ def __init__( self.threshold = int(threshold) self.method = ThresholdDetector.Method(method) self.fade_bias = fade_bias - self.min_scene_len = min_scene_len - self.min_out_length = min_out_length + self.min_scene_len = parse_frame_or_time(min_scene_len) + self.min_out_length = parse_frame_or_time(min_out_length) self.processed_frame = False - self.last_scene_cut: FrameTimecode | None = None + self.last_scene_cut: FramePosition | None = None # Whether to add an additional scene or not when ending on a fade out # (as cuts are only added on fade ins; see post_process() for details). self.add_final_scene = add_final_scene # Where the last fade (threshold crossing) was detected. self.last_fade: dict[str, ty.Any] = { - "frame": None, # FrameTimecode where the last detected fade is + "frame": None, # FramePosition where the last detected fade is "type": None, # type of fade, can be either 'in' or 'out' } self._metric_keys = [ThresholdDetector.THRESHOLD_VALUE_KEY] + self._fade_positions: list[FramePosition] = [] def get_metrics(self) -> list[str]: return self._metric_keys - def process_frame( - self, timecode: FrameTimecode, frame_img: numpy.ndarray - ) -> list[FrameTimecode]: + def process_frame(self, frame: FramePosition, frame_img: numpy.ndarray) -> list[FramePosition]: """Process the next frame. Arguments: - timecode: FrameTimecode of the current frame position. - frame_img (numpy.ndarray or None): Video frame corresponding to `timecode`. + frame: FramePosition of the current frame position. + frame_img (numpy.ndarray or None): Video frame corresponding to `frame`. Returns: - List of FrameTimecodes where scene cuts have been detected. + List of FramePosition where scene cuts have been detected. """ # Initialize last scene cut point at the beginning of the frames of interest. if self.last_scene_cut is None: - self.last_scene_cut = timecode + self.last_scene_cut = frame - cuts: list[FrameTimecode] = [] + cuts: list[FramePosition] = [] # The metric used here to detect scene breaks is the percent of pixels # less than or equal to the threshold; however, since this differs on # user-supplied values, we supply the average pixel intensity as this # frame metric instead (to assist with manually selecting a threshold) if (self.stats_manager is not None) and ( - self.stats_manager.metrics_exist(timecode, self._metric_keys) + self.stats_manager.metrics_exist(frame, self._metric_keys) ): - frame_avg = self.stats_manager.get_metrics(timecode, self._metric_keys)[0] + frame_avg = self.stats_manager.get_metrics(frame, self._metric_keys)[0] else: frame_avg = numpy.mean(frame_img) if self.stats_manager is not None: - self.stats_manager.set_metrics(timecode, {self._metric_keys[0]: frame_avg}) + self.stats_manager.set_metrics(frame, {self._metric_keys[0]: frame_avg}) if self.processed_frame: if self.last_fade["type"] == "in" and ( @@ -146,16 +153,17 @@ def process_frame( ): # Just faded out of a scene, wait for next fade in. self.last_fade["type"] = "out" - self.last_fade["frame"] = timecode + self.last_fade["frame"] = frame + self._fade_positions = [] elif self.last_fade["type"] == "out" and ( (self.method == ThresholdDetector.Method.FLOOR and frame_avg >= self.threshold) or (self.method == ThresholdDetector.Method.CEILING and frame_avg < self.threshold) ): # Both the scene and the fade-out must meet their minimum durations. - if (timecode - self.last_scene_cut) >= self.min_scene_len and ( - timecode - self.last_fade["frame"] - ) >= self.min_out_length: + if self.meets_minimum( + frame - self.last_scene_cut, self.min_scene_len + ) and self.meets_minimum(frame - self.last_fade["frame"], self.min_out_length): # Just faded into a new scene, compute timecode for the scene # split based on the fade bias. Use frame-number arithmetic so the # result is identical across backends - float seconds + framerate @@ -163,26 +171,52 @@ def process_frame( # frame number by 1 between PyAV (sub-microsecond PTS) and OpenCV # (millisecond-truncated CAP_PROP_POS_MSEC). f_out = self.last_fade["frame"] - duration_frames = timecode.frame_num - f_out.frame_num - split_frame_num = f_out.frame_num + round( + duration_frames = frame.frame_number - f_out.frame_number + split_frame_num = f_out.frame_number + round( duration_frames * (1.0 + self.fade_bias) / 2.0 ) - cuts.append(FrameTimecode(split_frame_num, fps=timecode)) - self.last_scene_cut = timecode + if frame.frame_number == split_frame_num: + split_frame = frame + else: + index = bisect_left( + self._fade_positions, + split_frame_num, + key=lambda position: position.frame_number, + ) + earlier = self._fade_positions[index - 1] if index else None + later = ( + self._fade_positions[index] + if index < len(self._fade_positions) + else frame + ) + + split_frame = later + if earlier is not None and ( + split_frame_num - earlier.frame_number + <= later.frame_number - split_frame_num + ): + split_frame = earlier + + cuts.append(split_frame) + self.last_scene_cut = frame + self._fade_positions = [] + self.last_fade["type"] = "in" - self.last_fade["frame"] = timecode + self.last_fade["frame"] = frame else: # Initial state: faded out if the first frame is past the threshold for `method`. - self.last_fade["frame"] = timecode + self.last_fade["frame"] = frame if self.method == ThresholdDetector.Method.FLOOR: faded_out = frame_avg < self.threshold else: faded_out = frame_avg >= self.threshold self.last_fade["type"] = "out" if faded_out else "in" self.processed_frame = True + if self.last_fade["type"] == "out": + self._fade_positions.append(frame) return cuts - def post_process(self, timecode: FrameTimecode) -> list[FrameTimecode]: + def post_process(self, frame: FramePosition) -> list[FramePosition]: """Writes a final scene cut if the last detected fade was a fade-out. Only writes the scene cut if add_final_scene is true, and the last fade @@ -195,15 +229,21 @@ def post_process(self, timecode: FrameTimecode) -> list[FrameTimecode]: # If the last fade detected was a fade out, we add a corresponding new # scene break to indicate the end of the scene. This is only done for # fade-outs, as a scene cut is already added when a fade-in is found. - cuts: list[FrameTimecode] = [] - elapsed = timecode if self.last_scene_cut is None else timecode - self.last_scene_cut + last_scene_cut = self.last_scene_cut + if last_scene_cut is None: + return [] + cuts: list[FramePosition] = [] + duration = frame - self.last_fade["frame"] + # TODO: Define the last frame's duration and exclusive end time across backends. + # The fade duration includes the last frame in its count, but not in elapsed time. + fade_duration = FrameDuration(frames=duration.frames + 1, elapsed=duration.elapsed) if ( self.last_fade["type"] == "out" and self.add_final_scene and self.last_fade["frame"] is not None - and elapsed >= self.min_scene_len - # timecode is the last processed frame, so include it in the fade duration. - and (timecode + 1 - self.last_fade["frame"]) >= self.min_out_length + and self.meets_minimum(frame - last_scene_cut, self.min_scene_len) + # frame is the last processed frame, so include it in the fade duration. + and self.meets_minimum(fade_duration, self.min_out_length) ): cuts.append(self.last_fade["frame"]) return cuts diff --git a/scenedetect/detectors/transnet_v2.py b/scenedetect/detectors/transnet_v2.py index 726b4d2d..6c39248d 100644 --- a/scenedetect/detectors/transnet_v2.py +++ b/scenedetect/detectors/transnet_v2.py @@ -20,7 +20,7 @@ import cv2 import numpy as np -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, TimecodeLike from scenedetect.detector import FlashFilter, SceneDetector logger = getLogger("pyscenedetect") @@ -33,13 +33,16 @@ def __init__(self, threshold: float, flash_filter: FlashFilter): self.threshold = threshold self.flash_filter = flash_filter - def push(self, ys: np.ndarray, ts: np.ndarray): + def push(self, ys: np.ndarray, positions: np.ndarray) -> list[FramePosition]: predictions = (ys > self.threshold).astype(np.uint8) cuts = [] - for y, t in zip(predictions, ts, strict=True): - if self.y_prev == 0 and y == 1 and self.i > 0: - cuts.append(t) + for y, position in zip(predictions, positions, strict=True): + if position is None: + continue + + is_cut = self.y_prev == 0 and y == 1 and self.i > 0 + cuts.extend(self.flash_filter.filter(position, is_cut)) self.y_prev = y self.i += 1 @@ -67,22 +70,22 @@ def __init__( self.session = ort.InferenceSession(model_path, sess_opt=sess_opt, providers=onnx_providers) self.pixels = None - self.time = None + self.positions: np.ndarray | None = None self.det = Detector(threshold, flash_filter) - def _inference(self, pixels: np.ndarray, time: np.ndarray): + def _inference(self, pixels: np.ndarray, positions: np.ndarray) -> list[FramePosition]: pred = np.array(self.session.run(["output"], {"input": pixels}))[0] cuts = [] for i in range(pred.shape[0]): - cuts.extend(self.det.push(pred[i, 25:75, 0], time[i, 25:75])) + cuts.extend(self.det.push(pred[i, 25:75, 0], positions[i, 25:75])) return cuts - def push(self, pixels: np.ndarray, time: np.ndarray): + def push(self, pixels: np.ndarray, positions: np.ndarray) -> list[FramePosition]: if self.pixels is None: self.pixels = pixels - self.time = time + self.positions = positions return self._inference( np.stack( @@ -99,31 +102,29 @@ def push(self, pixels: np.ndarray, time: np.ndarray): ), np.stack( ( - np.tile(np.expand_dims(time[0], axis=0), (100,)), - np.concatenate( - (np.tile(np.expand_dims(time[0], axis=0), (25,)), time[:75]), 0 - ), + np.full(100, None, dtype=object), + np.concatenate((np.full(25, None, dtype=object), positions[:75]), 0), ) ), ) else: - # `self.time` is set in lockstep with `self.pixels` above, so it is non-None here. - assert self.time is not None + # `self.positions` is set in lockstep with `self.pixels` above, so it is non-None here. + assert self.positions is not None c1 = self.pixels c2 = pixels - t1 = self.time - t2 = time + p1 = self.positions + p2 = positions self.pixels = pixels - self.time = time + self.positions = positions return self._inference( np.stack( (np.concatenate((c1[25:], c2[:25]), 0), np.concatenate((c1[75:], c2[:75]), 0)) ), np.stack( - (np.concatenate((t1[25:], t2[:25]), 0), np.concatenate((t1[75:], t2[:75]), 0)) + (np.concatenate((p1[25:], p2[:25]), 0), np.concatenate((p1[75:], p2[:75]), 0)) ), ) @@ -140,7 +141,7 @@ def __init__( super().__init__() self.px = np.zeros((2, 100, 27, 48, 3), dtype=np.uint8) - self.time = np.zeros((2, 100), dtype=np.int64) + self.positions = np.full((2, 100), None, dtype=object) self.blank = np.zeros(self.px.shape[2:], dtype=np.uint8) @@ -155,56 +156,39 @@ def __init__( ) # TODO(https://scenedetect.com/issue/168): Figure out a better long term plan for handling # `min_scene_len` which should be specified in seconds, not frames. - self._flash_filter = FlashFilter(mode=filter_mode, length=min_scene_len) - - def mk_ft(self, pts: int): - # t = Timecode(pts=pts, time_base=self.time_base) - t = float(pts * self.time_base) - return FrameTimecode(t, fps=self._fps) - def process_frame(self, timecode: FrameTimecode, frame_img: np.ndarray) -> list[FrameTimecode]: + def process_frame(self, position: FramePosition, frame_img: np.ndarray) -> list[FramePosition]: """Process the next frame.""" - self.time_base = timecode.time_base - self._fps = timecode._rate - pixels = cv2.resize(frame_img, (48, 27), interpolation=cv2.INTER_AREA) self.px[self.j, self.i] = pixels - self.time[self.j, self.i] = timecode.pts + self.positions[self.j, self.i] = position self.i += 1 if self.i >= 100: - cuts = self.predictor.push(self.px[self.j], self.time[self.j]) + cuts = self.predictor.push(self.px[self.j], self.positions[self.j]) self.j = 1 - self.j self.i = 0 - filtered_cuts = [] - for cut in cuts: - filtered_cuts += self._flash_filter.filter(self.mk_ft(cut), True) - return filtered_cuts + return cuts else: return [] - def post_process(self, timecode: FrameTimecode) -> list[FrameTimecode]: - """Writes a final scene cut if the last detected fade was a fade-out.""" + def post_process(self, position: FramePosition) -> list[FramePosition]: + """Flush buffered model predictions.""" cuts = [] - - last_time = timecode.pts blank_frame = self.blank[:] self.px[self.j, self.i :] = blank_frame - self.time[self.j, self.i :] = last_time - cuts.extend(self.predictor.push(self.px[self.j], self.time[self.j])) + self.positions[self.j, self.i :] = None + cuts.extend(self.predictor.push(self.px[self.j], self.positions[self.j])) self.j = 1 - self.j self.px[self.j, :] = blank_frame - self.time[self.j, :] = last_time - cuts.extend(self.predictor.push(self.px[self.j], self.time[self.j])) + self.positions[self.j, :] = None + cuts.extend(self.predictor.push(self.px[self.j], self.positions[self.j])) - filtered_cuts = [] - for cut in cuts: - filtered_cuts += self._flash_filter.filter(self.mk_ft(cut), True) - return filtered_cuts + return cuts diff --git a/scenedetect/frame_timecode.py b/scenedetect/frame_timecode.py deleted file mode 100644 index 8fcb5e15..00000000 --- a/scenedetect/frame_timecode.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# PySceneDetect: Python-Based Video Scene Detector -# ------------------------------------------------------------------- -# [ Site: https://scenedetect.com ] -# [ Docs: https://scenedetect.com/docs/ ] -# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] -# -# Copyright (C) 2018 Brandon Castellano . -# PySceneDetect is licensed under the BSD 3-Clause License; see the -# included LICENSE file, or visit one of the above pages for details. -# -"""DEPRECATED""" - -import warnings - -warnings.warn( - "The `frame_timecode` submodule is deprecated, import from the base package instead.", - DeprecationWarning, - stacklevel=2, -) - -from scenedetect.common import * # noqa: E402, F403 diff --git a/scenedetect/output/__init__.py b/scenedetect/output/__init__.py index 9e12a74d..e9bdc1c2 100644 --- a/scenedetect/output/__init__.py +++ b/scenedetect/output/__init__.py @@ -39,8 +39,9 @@ ) from scenedetect.common import ( CutList, - FrameTimecode, + FrameRate, SceneList, + Timecode, framerate_to_fraction, ) @@ -141,6 +142,14 @@ def wrapper(*args: ty.Any, **kwargs: ty.Any) -> ty.Any: return decorator +def _format_seconds(seconds: Fraction) -> str: + """Format seconds to three decimal places using exact rounding.""" + milliseconds = round(seconds * 1000) + whole_seconds, millis = divmod(abs(milliseconds), 1000) + sign = "-" if milliseconds < 0 else "" + return f"{sign}{whole_seconds}.{millis:03d}" + + @_open_output_file("CSV") def write_scene_list( output_csv_file: StrPath | BytePath | ty.TextIO, @@ -155,10 +164,10 @@ def write_scene_list( Arguments: output_csv_file: Handle to open file in write mode, or a filesystem path. A path is opened with a context manager so the file is closed after writing. - scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. + scene_list: List of pairs of FramePosition denoting each scene's start/end FramePosition. include_cut_list: Bool indicating if the first row should include the timecodes where each scene starts. Should be set to False if RFC 4180 compliant CSV output is required. - cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames + cut_list: Optional list of FramePosition objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not specified, the cut list is generated using the start times of each scene following the first one. col_separator: Delimiter to use between values. Must be single character. @@ -173,10 +182,11 @@ def write_scene_list( csv_writer = csv.writer(output_file, delimiter=col_separator, lineterminator=row_separator) # If required, output the cutting list as the first row (i.e. before the header row). if include_cut_list: + cuts = cut_list or [start for start, _ in scene_list[1:]] csv_writer.writerow( [ "Timecode List:", - *(cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]]), + *(cut.timecode.get_timecode() for cut in cuts), ] ) csv_writer.writerow( @@ -195,18 +205,22 @@ def write_scene_list( ) for i, (start, end) in enumerate(scene_list): duration = end - start + duration_timecode = Timecode( + pts=duration.elapsed.numerator, + time_base=Fraction(1, duration.elapsed.denominator), + ) csv_writer.writerow( [ f"{i + 1:d}", - f"{start.frame_num + 1:d}", - start.get_timecode(), - f"{start.seconds:.3f}", - f"{end.frame_num:d}", - end.get_timecode(), - f"{end.seconds:.3f}", - f"{duration.frame_num:d}", - duration.get_timecode(), - f"{duration.seconds:.3f}", + f"{start.frame_number + 1:d}", + start.timecode.get_timecode(), + _format_seconds(start.timecode.seconds), + f"{end.frame_number:d}", + end.timecode.get_timecode(), + _format_seconds(end.timecode.seconds), + f"{duration.frames:d}", + duration_timecode.get_timecode(), + _format_seconds(duration.elapsed), ] ) @@ -221,12 +235,12 @@ def write_scene_list_html( image_width: int | None = None, image_height: int | None = None, ): - """Writes the given list of scenes to an output file handle in html format. + """Writes the given list of scenes to an html file. Arguments: output_html_filename: filename of output html file - scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. - cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames + scene_list: List of pairs of FramePosition denoting each scene's start/end FramePosition. + cut_list: Optional list of FramePosition objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not passed, the start times of each scene (besides the 0th scene) is used instead. css: String containing all the css information for the resulting html page. @@ -277,11 +291,9 @@ def write_scene_list_html( """ # Output Timecode list + cuts = cut_list or [start for start, _ in scene_list[1:]] timecode_table = SimpleTable( - [ - ["Timecode List:"] - + (cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]]) - ], + [["Timecode List:"] + [cut.timecode.get_timecode() for cut in cuts]], css_class=css_class, ) @@ -300,19 +312,22 @@ def write_scene_list_html( ] for i, (start, end) in enumerate(scene_list): duration = end - start + duration_timecode = Timecode( + pts=duration.elapsed.numerator, time_base=Fraction(1, duration.elapsed.denominator) + ) row = SimpleTableRow( [ f"{i + 1:d}", - f"{start.frame_num + 1:d}", - start.get_timecode(), - f"{start.seconds:.3f}", - f"{end.frame_num:d}", - end.get_timecode(), - f"{end.seconds:.3f}", - f"{duration.frame_num:d}", - duration.get_timecode(), - f"{duration.seconds:.3f}", + f"{start.frame_number + 1:d}", + start.timecode.get_timecode(), + _format_seconds(start.timecode.seconds), + f"{end.frame_number:d}", + end.timecode.get_timecode(), + _format_seconds(end.timecode.seconds), + f"{duration.frames:d}", + duration_timecode.get_timecode(), + _format_seconds(duration.elapsed), ] ) @@ -330,7 +345,8 @@ def write_scene_list_html( # Write html file page = HTMLPage() page.add_table(timecode_table) - page.add_table(scene_table) + if scene_list: + page.add_table(scene_table) page.css = css page.save(output_html_filename) @@ -352,7 +368,7 @@ def _edl_nominal_rate(frame_rate: Fraction | float) -> int | None: return None -def _edl_timecode(timecode: FrameTimecode) -> str: +def _edl_timecode(timecode: Timecode, frame_rate: Fraction, offset_frames: int = 0) -> str: """Format `timecode` as non-drop-frame ``HH:MM:SS:FF`` for a CMX 3600 EDL entry. Non-drop-frame timecode counts frames at the nominal rate: a timecode second is 24 frames at @@ -360,11 +376,9 @@ def _edl_timecode(timecode: FrameTimecode) -> str: (about 3.6 seconds per hour). Rates that are neither whole numbers nor ``N * 1000/1001`` have no nominal rate; for those, the timecode is derived from wall-clock seconds instead. """ - frame_rate = timecode.frame_rate - assert frame_rate is not None nominal_rate = _edl_nominal_rate(frame_rate) if nominal_rate is not None: - frames = timecode.frame_num + frames = round(timecode.seconds * frame_rate) + offset_frames frames_part = frames % nominal_rate total_seconds = frames // nominal_rate hours, minutes, seconds = ( @@ -373,7 +387,7 @@ def _edl_timecode(timecode: FrameTimecode) -> str: total_seconds % 60, ) else: - wall_seconds = timecode.seconds + wall_seconds = timecode.seconds + offset_frames / frame_rate hours = int(wall_seconds // 3600) minutes = int((wall_seconds % 3600) // 60) seconds = int(wall_seconds % 60) @@ -421,18 +435,22 @@ def write_scene_list_edl( title: str = "PySceneDetect", reel: str = "AX", start_timecode: str | None = None, + *, + frame_rate: FrameRate, ): """Writes the given list of scenes to `output_path` in CMX 3600 EDL format. Arguments: output_path: Open text file or path to write the EDL file to. Parent directories must exist. When a path is provided, the file is closed after writing. - scene_list: List of scenes as pairs of FrameTimecodes denoting each scene's start/end. + scene_list: List of scenes as pairs of FramePositions denoting each scene's start/end. title: Title header written as ``TITLE:`` in the EDL. reel: Reel name used for each event. Typically 2-8 uppercase characters. start_timecode: Optional SMPTE timecode (``HH:MM:SS:FF`` or 8-digit ``HHMMSSFF``) added to every event so the EDL aligns with the source media's on-screen timecode. Applied to both source and record columns. + frame_rate: Rate used to interpret/export EDL timecodes. Must match the editor's + EDL import rate. VFR boundaries may be rounded to this rate's frame grid. Timecodes are written as non-drop-frame (``FCM: NON-DROP FRAME``), counting frames at the nominal rate: 24 per timecode second at 23.976 fps, 30 at 29.97 fps, and so on. Rates with no @@ -440,16 +458,15 @@ def write_scene_list_edl( """ # `_open_output_file` replaces filesystem paths with writable text streams. assert isinstance(output_path, _SupportsWrite) + frame_rate = framerate_to_fraction(frame_rate) output_file = output_path offset_frames = 0 if start_timecode is not None and start_timecode.strip() and scene_list: - frame_rate = scene_list[0][0].frame_rate - assert frame_rate is not None offset_frames = _parse_edl_start_timecode(start_timecode, frame_rate) lines = [f"TITLE: {title}", "FCM: NON-DROP FRAME", ""] for i, (start, end) in enumerate(scene_list): - in_tc = _edl_timecode(start + offset_frames) - out_tc = _edl_timecode(end + offset_frames) + in_tc = _edl_timecode(start.timecode, frame_rate, offset_frames) + out_tc = _edl_timecode(end.timecode, frame_rate, offset_frames) lines.append(f"{(i + 1):03d} {reel} V C {in_tc} {out_tc} {in_tc} {out_tc}") # `scenedetect` is imported lazily to avoid a circular import at module load. import scenedetect @@ -470,11 +487,6 @@ def _rational_seconds(value: Fraction) -> str: return f"{value.numerator}/{value.denominator}s" -def _frame_timecode_seconds(tc: FrameTimecode) -> Fraction: - """Exact seconds for `tc` as a `Fraction`, derived from PTS * time base.""" - return Fraction(tc.pts) * tc.time_base - - def _escape_ffmetadata(value: str) -> str: """Escape `value` for use in an FFmetadata file. @@ -506,7 +518,7 @@ def write_scene_list_ffmetadata( Arguments: output_path: Open text file or path to write the FFmetadata file to. Parent directories must exist. When a path is provided, the file is closed after writing. - scene_list: List of scenes as pairs of FrameTimecodes denoting each scene's start/end. + scene_list: List of scenes as pairs of FramePositions denoting each scene's start/end. title_format_template: Template for each chapter's title. ``$SCENE_NUMBER`` is replaced with the 1-based scene number, and ``$VIDEO_NAME`` with `video_name` if provided. video_name: Name of the video to substitute for ``$VIDEO_NAME`` in the chapter titles. If @@ -526,8 +538,8 @@ def write_scene_list_ffmetadata( # Chapter times are written in milliseconds from exact (PTS-based) seconds, so they don't # drift on fractional frame rates like 23.976 or 29.97. Rounding up ensures a chapter never # starts before the first frame of its scene (e.g. 500.5 ms is written as 501). - start_ms = math.ceil(_frame_timecode_seconds(start) * 1000) - end_ms = math.ceil(_frame_timecode_seconds(end) * 1000) + start_ms = math.ceil(start.timecode.seconds * 1000) + end_ms = math.ceil(end.timecode.seconds * 1000) title = title_template.safe_substitute(substitutions, SCENE_NUMBER=i + 1) lines += [ "[CHAPTER]", @@ -558,7 +570,7 @@ def write_scene_list_fcpx( Arguments: output_path: Open text file or path to write the FCPXML file to. Parent directories must exist. When a path is provided, the file is closed after writing. - scene_list: List of scenes as pairs of FrameTimecodes. Must not be empty. + scene_list: List of scenes as pairs of FramePositions. Must not be empty. video_path: Path to the source video file; written into the output as a ``file://`` URI. frame_rate: Source frame rate as a rational `Fraction` (e.g. ``Fraction(24000, 1001)``). frame_size: Source resolution as a ``(width, height)`` tuple in pixels. @@ -579,9 +591,7 @@ def write_scene_list_fcpx( width, height = frame_size frame_duration = _rational_seconds(Fraction(frame_rate.denominator, frame_rate.numerator)) src_uri = video_path.absolute().as_uri() - total_duration = _rational_seconds( - _frame_timecode_seconds(scene_list[-1][1] - scene_list[0][0]) - ) + total_duration = _rational_seconds((scene_list[-1][1] - scene_list[0][0]).elapsed) root = ElementTree.Element("fcpxml", version="1.9") resources = ElementTree.SubElement(root, "resources") @@ -623,8 +633,8 @@ def write_scene_list_fcpx( spine = ElementTree.SubElement(sequence, "spine") for i, (start, end) in enumerate(scene_list): - scene_start = _rational_seconds(_frame_timecode_seconds(start)) - scene_duration = _rational_seconds(_frame_timecode_seconds(end - start)) + scene_start = _rational_seconds(start.timecode.seconds) + scene_duration = _rational_seconds((end - start).elapsed) ElementTree.SubElement( spine, "asset-clip", @@ -649,7 +659,7 @@ def write_scene_list_fcp7( frame_rate: Fraction, frame_size: tuple[int, int], video_name: str | None = None, - source_duration: FrameTimecode | None = None, + source_duration: Fraction | None = None, ): """Writes the given list of scenes to `output_path` in Final Cut Pro 7 XML (xmeml) format. @@ -660,15 +670,15 @@ def write_scene_list_fcp7( Arguments: output_path: Open text file or path to write the xmeml file to. Parent directories must exist. When a path is provided, the file is closed after writing. - scene_list: List of scenes as pairs of FrameTimecodes. Must not be empty. + scene_list: List of scenes as pairs of FramePositions. Must not be empty. video_path: Path to the source video file; written into the output as a ``file://`` URI. frame_rate: Source frame rate as a rational `Fraction`. frame_size: Source resolution as a ``(width, height)`` tuple in pixels. video_name: Display name used for project and sequence. Defaults to the stem of `video_path`. - source_duration: Total duration of the source media. Required on ```` so NLEs - (DaVinci Resolve, Premiere) can seek into the source - without it the clip plays - frozen. If None, falls back to the last scene's end time. + source_duration: Total duration of the source media in seconds. Required on ```` + so NLEs (DaVinci Resolve, Premiere) can seek into the source - without it the + clip plays frozen. If None, falls back to the last scene's end time. """ assert scene_list # `_open_output_file` replaces filesystem paths with writable text streams. @@ -687,7 +697,7 @@ def write_scene_list_fcp7( fps = float(frame_rate) ntsc = "True" if frame_rate.denominator != 1 else "False" duration = scene_list[-1][1] - scene_list[0][0] - ElementTree.SubElement(sequence, "duration").text = str(round(duration.seconds * fps)) + ElementTree.SubElement(sequence, "duration").text = str(round(duration.elapsed * frame_rate)) rate = ElementTree.SubElement(sequence, "rate") ElementTree.SubElement(rate, "timebase").text = str(round(fps)) @@ -712,8 +722,8 @@ def write_scene_list_fcp7( path_uri = video_path.absolute().as_uri() source_duration_frames = str( round( - (source_duration.seconds if source_duration is not None else scene_list[-1][1].seconds) - * fps + (source_duration if source_duration is not None else scene_list[-1][1].timecode.seconds) + * frame_rate ) ) FILE_ID = "file1" @@ -727,10 +737,10 @@ def write_scene_list_fcp7( ElementTree.SubElement(clip_rate, "timebase").text = str(round(fps)) ElementTree.SubElement(clip_rate, "ntsc").text = ntsc # Frame numbers relative to the declared fps, computed from PTS seconds. - ElementTree.SubElement(clip, "start").text = str(round(start.seconds * fps)) - ElementTree.SubElement(clip, "end").text = str(round(end.seconds * fps)) - ElementTree.SubElement(clip, "in").text = str(round(start.seconds * fps)) - ElementTree.SubElement(clip, "out").text = str(round(end.seconds * fps)) + ElementTree.SubElement(clip, "start").text = str(round(start.timecode.seconds * frame_rate)) + ElementTree.SubElement(clip, "end").text = str(round(end.timecode.seconds * frame_rate)) + ElementTree.SubElement(clip, "in").text = str(round(start.timecode.seconds * frame_rate)) + ElementTree.SubElement(clip, "out").text = str(round(end.timecode.seconds * frame_rate)) # xmeml allows a single full `` declaration reused via `` on # subsequent clipitems. Emit full details on the first, then self-close on the rest. @@ -771,7 +781,7 @@ def write_scene_list_otio( frame_rate: Fraction, name: str | None = None, audio: bool = True, - source_duration: FrameTimecode | None = None, + source_duration: Fraction | None = None, ): """Writes the given list of scenes to `output_path` as an OTIO Timeline.1 JSON document. @@ -780,15 +790,15 @@ def write_scene_list_otio( Arguments: output_path: Open text file or path to write the OTIO file to. Parent directories must exist. When a path is provided, the file is closed after writing. - scene_list: List of scenes as pairs of FrameTimecodes. + scene_list: List of scenes as pairs of FramePositions. video_path: Path to the source video file; written into the output as an absolute path. frame_rate: Source frame rate as a rational `Fraction`. Exported as a float, as the current OTIO format does not support rational timings. name: Timeline name. Defaults to the stem of `video_path`. audio: If True (default), include an audio track alongside the video track. - source_duration: Total duration of the source media. Written as the media reference's - available range so NLEs can seek into the source. If None, the available range is - left unspecified rather than inferred from the selected scenes. + source_duration: Total duration of the source media in seconds. Written as the media + reference's available range so NLEs can seek into the source. If None, the available + range is left unspecified rather than inferred from the selected scenes. """ # `_open_output_file` replaces filesystem paths with writable text streams. assert isinstance(output_path, _SupportsWrite) @@ -807,7 +817,7 @@ def write_scene_list_otio( "duration": { "OTIO_SCHEMA": "RationalTime.1", "rate": fps, - "value": round(source_duration.seconds * fps, 6), + "value": float(round(source_duration * fps, 6)), }, "start_time": { "OTIO_SCHEMA": "RationalTime.1", @@ -847,12 +857,12 @@ def write_scene_list_otio( "duration": { "OTIO_SCHEMA": "RationalTime.1", "rate": fps, - "value": round((end - start).seconds * fps, 6), + "value": float(round((end - start).elapsed * frame_rate, 6)), }, "start_time": { "OTIO_SCHEMA": "RationalTime.1", "rate": fps, - "value": round(start.seconds * fps, 6), + "value": float(round(start.timecode.seconds * frame_rate, 6)), }, }, "enabled": True, diff --git a/scenedetect/output/image.py b/scenedetect/output/image.py index b4bdbbb2..8c4bcc95 100644 --- a/scenedetect/output/image.py +++ b/scenedetect/output/image.py @@ -17,6 +17,7 @@ import sys import threading import typing as ty +from fractions import Fraction from pathlib import Path from string import Template @@ -24,21 +25,18 @@ import numpy as np from scenedetect.common import ( - FrameTimecode, + FramePosition, Interpolation, SceneList, + Timecode, TimecodeLike, + parse_frame_or_time, ) from scenedetect.platform import StrPath, get_and_create_path, get_cv2_imwrite_params, tqdm from scenedetect.video_stream import VideoStream logger = logging.getLogger("pyscenedetect") -# Added to the ratio of scene length to interval (a number of intervals, so it has no unit) before -# rounding down, so floating point error doesn't drop an image from a scene that is a whole number -# of intervals long (e.g. 0.3 / 0.1 gives 2.9999999999999996). -_INTERVAL_COUNT_TOLERANCE: float = 1e-9 - def _get_num_images( scene_list: SceneList, @@ -55,13 +53,12 @@ def _get_num_images( if interval is None: assert num_images is not None return [num_images] * len(scene_list) - frame_rate = scene_list[0][0].frame_rate - assert frame_rate is not None - interval_secs = FrameTimecode(timecode=interval, fps=frame_rate).seconds + parsed_interval = parse_frame_or_time(interval) result = [] for start, end in scene_list: - duration_secs = max((end - start).seconds, 0.0) - num_intervals = math.floor(duration_secs / interval_secs + _INTERVAL_COUNT_TOLERANCE) + duration = end - start + scene_length = duration.frames if isinstance(parsed_interval, int) else duration.elapsed + num_intervals = scene_length // parsed_interval scene_images = max(num_intervals + 1, min_images) if max_images is not None: scene_images = min(scene_images, max_images) @@ -73,40 +70,44 @@ def _generate_timecode_list( scene_list: SceneList, num_images_per_scene: list[int], frame_margin: TimecodeLike, -) -> list[list[FrameTimecode]]: - """Generate per-scene image timecodes using PTS-accurate seconds-based timing. + frame_rate: Fraction, +) -> list[list[Timecode]]: + """Generate per-scene image targets using timestamps and frame-rate estimates. `num_images_per_scene` is the number of images to generate for each scene in `scene_list`. `frame_margin` accepts any :data:`TimecodeLike` value (e.g. ``int`` frames, ``float`` seconds, or ``str`` such as ``"0.1s"``). + Frame-count margins and the final-frame clamp use ``frame_rate`` and are + approximate for VFR sources. """ - frame_rate = scene_list[0][0].frame_rate - assert frame_rate is not None - margin_secs = FrameTimecode(timecode=frame_margin, fps=frame_rate).seconds - frame_secs = float(1 / frame_rate) + # TODO: Define VFR sampling and padding semantics. Handle any frame-count + # margins during extraction without FPS conversion. + parsed_margin = parse_frame_or_time(frame_margin) + margin_secs = parsed_margin / frame_rate if isinstance(parsed_margin, int) else parsed_margin + frame_secs = 1 / frame_rate result = [] for (start, end), num_images in zip(scene_list, num_images_per_scene, strict=True): - duration_secs = (end - start).seconds + duration_secs = (end - start).elapsed if duration_secs <= 0: - result.append([start] * num_images) + result.append([start.timecode] * num_images) continue segment_secs = duration_secs / num_images - # `end` is exclusive, so the last frame of the scene is one frame before it. Scenes can be - # shorter than one frame (e.g. VFR), so never go before the start of the scene. - last_frame_secs = max(end.seconds - frame_secs, start.seconds) + # Estimate the final frame time using the frame rate, without going before scene start. + last_frame_secs = max(end.timecode.seconds - frame_secs, start.timecode.seconds) timecodes = [] for j in range(num_images): - seg_start = start.seconds + j * segment_secs - seg_end = start.seconds + (j + 1) * segment_secs + seg_start = start.timecode.seconds + j * segment_secs + seg_end = start.timecode.seconds + (j + 1) * segment_secs if num_images == 1: - t = start.seconds + duration_secs / 2.0 + t = start.timecode.seconds + duration_secs / 2 elif j == 0: t = min(seg_start + margin_secs, seg_end) elif j == num_images - 1: t = max(last_frame_secs - margin_secs, seg_start) else: - t = (seg_start + seg_end) / 2.0 - timecodes.append(FrameTimecode(min(t, last_frame_secs), fps=frame_rate)) + t = (seg_start + seg_end) / 2 + t = min(t, last_frame_secs) + timecodes.append(Timecode(pts=t.numerator, time_base=Fraction(1, t.denominator))) result.append(timecodes) return result @@ -180,6 +181,7 @@ def __init__( selecting which frames to extract. Accepts an int (frames), float (seconds), or str (e.g. ``"0.1s"``, ``"00:00:00.100"``). Can be 0, but some video files may then fail to extract the very last frame. + Frame-count margins use the video's frame rate and are approximate for VFR. image_extension: Type of image to save (must be one of 'jpg', 'png', or 'webp'). encoder_param: Quality/compression efficiency, based on type of image: 'jpg' / 'webp': Quality 0-100, higher is better quality. 100 is lossless for webp. @@ -233,7 +235,7 @@ def run( output_dir: Directory to write files to. show_progress: If `true` and tqdm is available, shows a progress bar. """ - timecode_list = self.generate_timecode_list(scene_list) + timecode_list = self.generate_timecode_list(scene_list, video.frame_rate) total_images = sum(len(timecodes) for timecodes in timecode_list) max_scene_images = max(len(timecodes) for timecodes in timecode_list) @@ -256,15 +258,15 @@ def run( image_num_format = "%0" image_num_format += str(math.floor(math.log(max_scene_images, 10)) + 2) + "d" - def format_filename(scene_number: int, image_number: int, image_timecode: FrameTimecode): + def format_filename(scene_number: int, image_number: int, position: FramePosition): return "{}.{}".format( filename_template.safe_substitute( VIDEO_NAME=video.name, SCENE_NUMBER=scene_num_format % (scene_number + 1), IMAGE_NUMBER=image_num_format % (image_number + 1), - FRAME_NUMBER=image_timecode.frame_num, - TIMESTAMP_MS=int(image_timecode.seconds * 1000), - TIMECODE=image_timecode.get_timecode().replace(":", ";"), + FRAME_NUMBER=position.frame_number, + TIMESTAMP_MS=int(position.timecode.seconds * 1000), + TIMECODE=position.timecode.get_timecode().replace(":", ";"), ), self._image_extension, ) @@ -328,8 +330,10 @@ def checked_put(work_queue: queue.Queue, item: ty.Any): for j, timecode in enumerate(scene_timecodes): video.seek(timecode) frame_im = video.read() - if frame_im is not None and frame_im is not False: - file_path = format_filename(i, j, timecode) + if isinstance(frame_im, np.ndarray): + position = video.position + assert position is not None + file_path = format_filename(i, j, position) image_filenames[i].append(file_path) checked_put( encode_queue, (frame_im, get_and_create_path(file_path, output_dir)) @@ -390,16 +394,20 @@ def image_save_thread(self, save_queue: queue.Queue, progress_bar: tqdm): if progress_bar is not None: progress_bar.update(1) - def generate_timecode_list(self, scene_list: SceneList) -> list[list[FrameTimecode]]: + def generate_timecode_list( + self, scene_list: SceneList, frame_rate: Fraction + ) -> list[list[Timecode]]: """Generates a list of timecodes for each scene in `scene_list` based on the current config parameters. - Uses PTS-accurate seconds-based timing so results are correct for both CFR and VFR video. + Uses scene timestamps to calculate image extraction targets. """ num_images_per_scene = _get_num_images( scene_list, self._num_images, self._interval, self._min_images, self._max_images ) - return _generate_timecode_list(scene_list, num_images_per_scene, self._frame_margin) + return _generate_timecode_list( + scene_list, num_images_per_scene, self._frame_margin, frame_rate + ) def resize_image( self, @@ -434,7 +442,7 @@ def save_images( and the associated video/frame source. Arguments: - scene_list: A list of scenes (pairs of FrameTimecode objects) returned + scene_list: A list of scenes (pairs of FramePosition objects) returned from calling a SceneManager's detect_scenes() method. video: A VideoStream object corresponding to the scene list. Note that the video will be closed/re-opened and seeked through. @@ -444,6 +452,7 @@ def save_images( selecting which frames to extract. Accepts an int (frames), float (seconds), or str (e.g. ``"0.1s"``, ``"00:00:00.100"``). Can be 0, but some video files may then fail to extract the very last frame. + Frame-count margins use the video's frame rate and are approximate for VFR. image_extension: Type of image to save (must be one of 'jpg', 'png', or 'webp'). encoder_param: Quality/compression efficiency, based on type of image: 'jpg' / 'webp': Quality 0-100, higher is better quality. 100 is lossless for webp. @@ -492,9 +501,7 @@ def save_images( if interval is not None: if num_images is not None: raise ValueError("num_images and interval cannot both be set") - frame_rate = scene_list[0][0].frame_rate - assert frame_rate is not None - if FrameTimecode(timecode=interval, fps=frame_rate).seconds <= 0: + if parse_frame_or_time(interval) <= 0: raise ValueError("interval must be greater than 0") if min_images <= 0: raise ValueError("min_images must be greater than 0") @@ -540,6 +547,7 @@ def save_images( scene_list, _get_num_images(scene_list, num_images, interval, min_images, max_images), frame_margin, + video.frame_rate, ) total_images = sum(len(timecodes) for timecodes in timecode_list) max_scene_images = max(len(timecodes) for timecodes in timecode_list) @@ -572,6 +580,8 @@ def save_images( video.seek(image_timecode) frame_im = video.read() if isinstance(frame_im, np.ndarray): + position = video.position + assert position is not None # TODO: Add extension to template. # TODO: Allow NUM to be a valid suffix in addition to NUMBER. file_path = "{}.{}".format( @@ -579,9 +589,9 @@ def save_images( VIDEO_NAME=video.name, SCENE_NUMBER=scene_num_format % (i + 1), IMAGE_NUMBER=image_num_format % (j + 1), - FRAME_NUMBER=image_timecode.frame_num, - TIMESTAMP_MS=int(image_timecode.seconds * 1000), - TIMECODE=image_timecode.get_timecode().replace(":", ";"), + FRAME_NUMBER=position.frame_number, + TIMESTAMP_MS=int(position.timecode.seconds * 1000), + TIMECODE=position.timecode.get_timecode().replace(":", ";"), ), image_extension, ) diff --git a/scenedetect/output/video.py b/scenedetect/output/video.py index c375aeea..82151f55 100644 --- a/scenedetect/output/video.py +++ b/scenedetect/output/video.py @@ -36,9 +36,10 @@ import typing as ty from collections.abc import Sequence from dataclasses import dataclass +from fractions import Fraction from pathlib import Path -from scenedetect.common import FrameTimecode, TimecodePair +from scenedetect.common import FramePosition, PositionPair, Timecode from scenedetect.platform import ( CommandTooLong, Template, @@ -111,24 +112,30 @@ class VideoMetadata: @dataclass class SceneMetadata: - """Information about the scene being extracted.""" + """Detected scene metadata used to name an output clip. + + Expansion may include additional footage; these positions identify the supplied scene. + """ index: int """0-based index of this scene.""" - start: FrameTimecode + start: FramePosition """First frame.""" - end: FrameTimecode - """Last frame.""" + end: FramePosition + """Exclusive end position.""" PathFormatter = ty.Callable[[VideoMetadata, SceneMetadata], str] -def default_formatter(template: str) -> PathFormatter: +def default_formatter(template: str, *, expand: bool = False) -> PathFormatter: """Formats filenames using a template string which allows the following variables: `$VIDEO_NAME`, `$SCENE_NUMBER`, `$START_TIME`, `$END_TIME`, `$START_FRAME`, `$END_FRAME`, `$START_PTS`, `$END_PTS` (presentation timestamp in milliseconds, accurate for VFR video) + + With `expand=True`, the first clip's start variables use "0" and the last clip's + end variables use an empty string. Other boundaries keep their supplied values. """ MIN_DIGITS = 3 @@ -137,15 +144,31 @@ def format_scene_number(video: VideoMetadata, scene: SceneMetadata) -> str: return ("%0" + str(width) + "d") % (scene.index + 1) def formatter(video: VideoMetadata, scene: SceneMetadata) -> str: + start_time = scene.start.timecode.get_timecode().replace(":", ";") + end_time = scene.end.timecode.get_timecode().replace(":", ";") + start_frame = str(scene.start.frame_number) + end_frame = str(scene.end.frame_number) + start_pts = str(round(scene.start.timecode.seconds * 1000)) + end_pts = str(round(scene.end.timecode.seconds * 1000)) + + if expand and scene.index == 0: + start_time = "0" + start_frame = "0" + start_pts = "0" + if expand and scene.index == video.total_scenes - 1: + end_time = "" + end_frame = "" + end_pts = "" + return Template(template).safe_substitute( VIDEO_NAME=video.name, SCENE_NUMBER=format_scene_number(video, scene), - START_TIME=str(scene.start.get_timecode().replace(":", ";")), - END_TIME=str(scene.end.get_timecode().replace(":", ";")), - START_FRAME=str(scene.start.frame_num), - END_FRAME=str(scene.end.frame_num), - START_PTS=str(round(scene.start.seconds * 1000)), - END_PTS=str(round(scene.end.seconds * 1000)), + START_TIME=str(start_time), + END_TIME=str(end_time), + START_FRAME=str(start_frame), + END_FRAME=str(end_frame), + START_PTS=str(start_pts), + END_PTS=str(end_pts), ) return formatter @@ -158,18 +181,20 @@ def formatter(video: VideoMetadata, scene: SceneMetadata) -> str: def split_video_mkvmerge( input_video_path: str, - scene_list: Sequence[TimecodePair], + scene_list: Sequence[PositionPair], output_dir: str | Path | None = None, output_file_template: str = "$VIDEO_NAME.mkv", video_name: str | None = None, show_output: bool = False, suppress_output=None, + *, + expand: bool = False, ) -> int: """Split `input_video_path` using `mkvmerge` based on the scenes in `scene_list`. Arguments: input_video_path: Path to the video to be split. - scene_list : List of scenes as pairs of FrameTimecodes denoting the start/end times. + scene_list : List of scenes as pairs of FramePositions denoting the start/end times. output_dir: Directory to output videos. If not set, output will be in working directory. output_file_template: Template to use for generating output files. Note that mkvmerge always adds the suffix "-$SCENE_NUMBER" to the output paths. Only the $VIDEO_NAME variable @@ -178,6 +203,7 @@ def split_video_mkvmerge( $VIDEO_NAME. If not specified, will be obtained from the filename. show_output: If False, adds the --quiet flag when invoking `mkvmerge`. suppress_output: [DEPRECATED] DO NOT USE. For backwards compatibility only. + expand: Extend the first output to time zero and the last output to source EOF. Returns: Return code of invoking mkvmerge (0 on success). If scene_list is empty, will still return 0, but no commands will be invoked. @@ -212,6 +238,11 @@ def split_video_mkvmerge( output_path = output_path.with_stem(output_path.stem + "-001") output_path.parent.mkdir(parents=True, exist_ok=True) + parts = [] + for i, (start_time, end_time) in enumerate(scene_list): + start = "00:00:00.000" if expand and i == 0 else start_time.timecode.get_timecode() + end = "" if expand and i == len(scene_list) - 1 else end_time.timecode.get_timecode() + parts.append(f"{start}-{end}") call_list = ["mkvmerge"] if not show_output: call_list.append("--quiet") @@ -219,23 +250,16 @@ def split_video_mkvmerge( "-o", str(output_path), "--split", - "parts:{}".format( - ",".join( - [ - f"{start_time.get_timecode()}-{end_time.get_timecode()}" - for start_time, end_time in scene_list - ] - ) - ), + f"parts:{','.join(parts)}", input_video_path, ] - total_frames = scene_list[-1][1].frame_num - scene_list[0][0].frame_num + total_frames = scene_list[-1][1].frame_number - scene_list[0][0].frame_number processing_start_time = time.time() ret_val = 0 try: # TODO: Capture stdout/stderr and show that if the command fails. ret_val = invoke_command(call_list) - if show_output: + if show_output and not expand: logger.info( "Average processing speed %.2f frames/sec.", float(total_frames) / (time.time() - processing_start_time), @@ -254,7 +278,7 @@ def split_video_mkvmerge( def split_video_ffmpeg( input_video_path: str, - scene_list: Sequence[TimecodePair], + scene_list: Sequence[PositionPair], output_dir: str | Path | None = None, output_file_template: str = "$VIDEO_NAME-Scene-$SCENE_NUMBER.mp4", video_name: str | None = None, @@ -264,12 +288,14 @@ def split_video_ffmpeg( suppress_output=None, hide_progress=None, formatter: PathFormatter | None = None, + *, + expand: bool = False, ) -> int: """Split `input_video_path` using `ffmpeg` based on the scenes in `scene_list`. Arguments: input_video_path: Path to the video to be split. - scene_list: List of scenes (pairs of FrameTimecodes) denoting the start/end of each scene. + scene_list: List of scenes (pairs of FramePositions) denoting the start/end of each scene. output_dir: Directory to output videos. If not set, output will be in working directory. output_file_template: Template to use for generating output filenames. The following variables will be replaced in the template for each scene: @@ -282,6 +308,9 @@ def split_video_ffmpeg( suppress_output: [DEPRECATED] DO NOT USE. For backwards compatibility only. hide_progress: [DEPRECATED] DO NOT USE. For backwards compatibility only. formatter: Custom formatter callback. Overrides `output_file_template`. + expand: Extend the first output to time zero and the last output to source EOF. + Built-in filename boundary variables use zero for the first start and a blank + last end. Custom formatter metadata retains the supplied scene positions. Returns: Return code of invoking ffmpeg (0 on success). If scene_list is empty, will @@ -318,19 +347,35 @@ def split_video_ffmpeg( scene_num_format += str(max(3, math.floor(math.log(len(scene_list), 10)) + 1)) + "d" if formatter is None: - formatter = default_formatter(output_file_template) + formatter = default_formatter(output_file_template, expand=expand) video_metadata = VideoMetadata( name=video_name, path=Path(input_video_path), total_scenes=len(scene_list) ) try: progress_bar = None - total_frames = scene_list[-1][1].frame_num - scene_list[0][0].frame_num + total_frames = scene_list[-1][1].frame_number - scene_list[0][0].frame_number if show_progress: - progress_bar = tqdm(total=total_frames, unit="frame", miniters=1, dynamic_ncols=True) + progress_bar = tqdm( + total=len(scene_list) if expand else total_frames, + unit="scene" if expand else "frame", + miniters=1, + dynamic_ncols=True, + ) processing_start_time = time.time() for i, (start_time, end_time) in enumerate(scene_list): duration = end_time - start_time + start_timecode = start_time.timecode + if expand and i == 0: + start_timecode = Timecode(pts=0, time_base=Fraction(1)) + + duration_timecode = None + if not (expand and i == len(scene_list) - 1): + elapsed = end_time.timecode.seconds - start_timecode.seconds + duration_timecode = Timecode( + pts=elapsed.numerator, + time_base=Fraction(1, elapsed.denominator), + ) scene_metadata = SceneMetadata(index=i, start=start_time, end=end_time) output_path = Path(formatter(video_metadata, scene_metadata)) if output_dir: @@ -350,12 +395,12 @@ def split_video_ffmpeg( "-nostdin", "-y", "-ss", - str(start_time.seconds), + start_timecode.get_timecode(precision=6), "-i", input_video_path, - "-t", - str(duration.seconds), ] + if duration_timecode is not None: + call_list += ["-t", duration_timecode.get_timecode(precision=6)] call_list += ffmpeg_args call_list += ["-sn"] call_list += [str(output_path)] @@ -369,11 +414,11 @@ def split_video_ffmpeg( logger.error("Error splitting video (ffmpeg returned %d).", ret_val) break if progress_bar: - progress_bar.update(duration.frame_num) + progress_bar.update(1 if expand else duration.frames) if progress_bar: progress_bar.close() - if show_output: + if show_output and not expand: logger.info( "Average processing speed %.2f frames/sec.", float(total_frames) / (time.time() - processing_start_time), diff --git a/scenedetect/scene_manager.py b/scenedetect/scene_manager.py index aaec6a2d..e191b21a 100644 --- a/scenedetect/scene_manager.py +++ b/scenedetect/scene_manager.py @@ -29,7 +29,7 @@ scene_manager.add_detector(ContentDetector()) # Detect all scenes in video from current position to end. scene_manager.detect_scenes(video) - # `get_scene_list` returns a list of start/end timecode pairs + # `get_scene_list` returns a list of start/end position pairs # for each scene that was found. scenes = scene_manager.get_scene_list() @@ -37,11 +37,13 @@ .. code:: python + import numpy from scenedetect import open_video, SceneManager, ContentDetector + from scenedetect.common import FramePosition # Callback to invoke on the first frame of every new scene detection. - def on_new_scene(frame_img: numpy.ndarray, frame_num: int): - print("New scene found at frame %d." % frame_num) + def on_new_scene(frame_img: numpy.ndarray, position: FramePosition): + print("New scene found at frame %d." % position.frame_number) video = open_video(test_video_file) scene_manager = SceneManager() @@ -80,6 +82,7 @@ def on_new_scene(frame_img: numpy.ndarray, frame_num: int): import threading import typing as ty import warnings +from fractions import Fraction import cv2 import numpy as np @@ -87,10 +90,11 @@ def on_new_scene(frame_img: numpy.ndarray, frame_num: int): from scenedetect.common import ( CropRegion, CutList, - FrameTimecode, + FramePosition, Interpolation, SceneList, TimecodeLike, + parse_frame_or_time, ) from scenedetect.detector import SceneDetector @@ -98,7 +102,7 @@ def on_new_scene(frame_img: numpy.ndarray, frame_num: int): from scenedetect.output import * # noqa: F403 from scenedetect.platform import tqdm from scenedetect.stats_manager import StatsManager -from scenedetect.video_stream import VideoStream +from scenedetect.video_stream import FrameNumbering, VideoStream logger = logging.getLogger("pyscenedetect") @@ -140,8 +144,8 @@ def compute_downscale_factor(frame_width: int, effective_width: int = DEFAULT_MI def expand_scenes_to_bounds( scenes: SceneList, - start: FrameTimecode, - end: FrameTimecode, + start: FramePosition, + end: FramePosition, ) -> SceneList: """Return a new scene list whose first scene starts at `start` and last scene ends at `end`. @@ -150,7 +154,7 @@ def expand_scenes_to_bounds( outside that analysis window. Arguments: - scenes: List of (start, end) FrameTimecode pairs. + scenes: List of (start, end) FramePosition pairs. start: Desired start of the first scene. end: Desired end of the last scene. @@ -168,36 +172,33 @@ def expand_scenes_to_bounds( def get_scenes_from_cuts( cut_list: CutList, - start_pos: int | FrameTimecode, - end_pos: int | FrameTimecode, + start_pos: FramePosition, + end_pos: FramePosition, ) -> SceneList: - """Returns a list of tuples of start/end FrameTimecodes for each scene based on a + """Returns a list of tuples of start/end FramePositions for each scene based on a list of detected scene cuts/breaks. This function is called when using the :meth:`SceneManager.get_scene_list` method. The scene list is generated from a cutting list (:meth:`SceneManager.get_cut_list`), - noting that each scene is contiguous, starting from the first to last frame of the input. + noting that scenes are contiguous from `start_pos` to the exclusive `end_pos`. If `cut_list` is empty, the resulting scene will span from `start_pos` to `end_pos`. Arguments: - cut_list: List of FrameTimecode objects where scene cuts/breaks occur. - num_frames: The number of frames, or FrameTimecode representing duration, of the video that - was processed (used to generate last scene's end time). - start_frame: The start frame or FrameTimecode of the cut list. Used to generate the first - scene's start time. + cut_list: List of FramePosition objects where scene cuts/breaks occur. + start_pos: Start position of the first scene. + end_pos: Exclusive end position of the last scene. Returns: - List of tuples in the form (start_time, end_time), where both start_time and - end_time are FrameTimecode objects representing the exact time/frame where each - scene occupies based on the input cut_list. + List of (start_pos, end_pos) FramePosition pairs. Each scene includes its start + position and excludes its end position. """ - # Scene list, where scenes are tuples of (Start FrameTimecode, End FrameTimecode). + # Scene list, where scenes are tuples of (start FramePosition, end FramePosition). scene_list = [] if not cut_list: scene_list.append((start_pos, end_pos)) return scene_list - # Initialize last_cut to the first frame we processed,as it will be - # the start timecode for the first scene in the list. + # Initialize last_cut to the first frame we processed, as it will be + # the start position for the first scene in the list. last_cut = start_pos for cut in cut_list: scene_list.append((last_cut, cut)) @@ -228,7 +229,7 @@ def __init__( stats_manager: :class:`~scenedetect.stats_manager.StatsManager` to bind to this `SceneManager`. Can be accessed via the `stats_manager` property to save to disk. """ - self._cutting_list: list[FrameTimecode] = [] + self._cutting_list: list[FramePosition] = [] self._detector_list: list[SceneDetector] = [] # TODO(v1.0): This class should own a StatsManager instead of taking an optional one. # Expose a new `stats_manager` @property from the SceneManager, and either change the @@ -239,14 +240,13 @@ def __init__( # (scenedetect.backends.concat). self._stats_manager: StatsManager | None = stats_manager - # Position of video that was first passed to detect_scenes. - self._start_pos: FrameTimecode | None = None - # Position of video on the last frame processed by detect_scenes. - self._last_pos: FrameTimecode | None = None + # Position of the first frame accepted for detection. + self._start_pos: FramePosition | None = None + # Position of the last frame read by detect_scenes, including skipped frames. + self._last_pos: FramePosition | None = None # Size of the decoded frames. self._frame_size: tuple[int, int] | None = None self._frame_size_errors: int = 0 - self._base_timecode: FrameTimecode | None = None self._downscale: int = 1 self._auto_downscale: bool = True # Interpolation method to use when downscaling. Defaults to linear interpolation @@ -256,7 +256,7 @@ def __init__( self._exception_info = None self._stop = threading.Event() - self._frame_buffer: list[tuple[FrameTimecode, np.ndarray]] = [] + self._frame_buffer: list[tuple[FramePosition, np.ndarray]] = [] self._frame_buffer_size = 0 self._crop = None @@ -372,54 +372,56 @@ def clear_detectors(self) -> None: self._detector_list.clear() def get_scene_list(self, start_in_scene: bool = False) -> SceneList: - """Return a list of tuples of start/end FrameTimecodes for each detected scene. + """Return a list of tuples of start/end FramePositions for each detected scene. Arguments: start_in_scene: Assume the video begins in a scene. This means that when detecting fast cuts with `ContentDetector`, if no cuts are found, the resulting scene list - will contain a single scene spanning the entire video (instead of no scenes). + will contain a single scene spanning the processed range (instead of no scenes). When detecting fades with `ThresholdDetector`, the beginning portion of the video will always be included until the first fade-out event is detected. Returns: - List of tuples in the form (start_time, end_time), where both start_time and - end_time are FrameTimecode objects representing the exact time/frame where each - detected scene in the video begins and ends. + List of (start_pos, end_pos) FramePosition pairs with exclusive end positions. + The final end position advances the frame number but uses the last frame's timestamp. """ - if self._base_timecode is None or self._start_pos is None or self._last_pos is None: + if self._start_pos is None or self._last_pos is None: return [] cut_list = self._get_cutting_list() - scene_list = get_scenes_from_cuts( - cut_list=cut_list, start_pos=self._start_pos, end_pos=self._last_pos + 1 - ) # If we didn't actually detect any cuts, make sure the resulting scene_list is empty # unless start_in_scene is True. if not cut_list and not start_in_scene: - scene_list = [] - return sorted(scene_list) + return [] + # TODO: Account for the last frame's duration across backends. + end_pos = FramePosition( + timecode=self._last_pos.timecode, + frame_number=self._last_pos.frame_number + 1, + ) + scene_list = get_scenes_from_cuts( + cut_list=cut_list, start_pos=self._start_pos, end_pos=end_pos + ) + return scene_list - def _get_cutting_list(self) -> list[FrameTimecode]: - """Return a sorted list of unique frame numbers of any detected scene cuts.""" + def _get_cutting_list(self) -> list[FramePosition]: + """Return unique cut positions sorted by frame number.""" if not self._cutting_list: return [] # Ensure all cuts are unique by using a set to remove all duplicates. - return [cut for cut in sorted(set(self._cutting_list))] + return sorted(set(self._cutting_list), key=lambda position: position.frame_number) def _process_frame( self, - position: FrameTimecode, + position: FramePosition, frame_im: np.ndarray, - callback: ty.Callable[[np.ndarray, FrameTimecode], None] | None = None, + callback: ty.Callable[[np.ndarray, FramePosition], None] | None = None, ) -> bool: """Add any cuts detected with the current frame to the cutting list. Returns True if any new cuts were detected, False otherwise.""" new_cuts = False - # TODO(https://scenedetect.com/issues/283): This breaks with AdaptiveDetector as cuts differ - # from the frame number being processed. Allow detectors to specify the max frame lookahead - # they require (i.e. any event will never be more than N frames behind the current one). + # TODO(https://scenedetect.com/issues/283): Ensure the buffer covers delayed cuts from + # every detector. self._frame_buffer.append((position, frame_im)) - # frame_buffer[-1] is current frame, -2 is one behind, etc - # so index based on cut frame should be [event_frame - (frame_num + 1)] + # Keep recent processed images so callbacks can match them to cut positions. self._frame_buffer = self._frame_buffer[-(self._frame_buffer_size + 1) :] for detector in self._detector_list: cuts = detector.process_frame(position, frame_im) @@ -432,10 +434,10 @@ def _process_frame( callback(frame, position) return new_cuts - def _post_process(self, timecode: FrameTimecode) -> None: + def _post_process(self, position: FramePosition) -> None: """Add remaining cuts to the cutting list, after processing the last frame.""" for detector in self._detector_list: - self._cutting_list += detector.post_process(timecode) + self._cutting_list += detector.post_process(position) def stop(self) -> None: """Stop the current :meth:`detect_scenes` call, if any. Thread-safe.""" @@ -448,11 +450,11 @@ def detect_scenes( end_time: TimecodeLike | None = None, frame_skip: int = 0, show_progress: bool = False, - callback: ty.Callable[[np.ndarray, FrameTimecode], None] | None = None, + callback: ty.Callable[[np.ndarray, FramePosition], None] | None = None, frame_source: VideoStream | None = None, ) -> int: """Perform scene detection on the given video using the added SceneDetectors, returning the - number of frames processed. Results can be obtained by calling :meth:`get_scene_list` or + number of frames read. Results can be obtained by calling :meth:`get_scene_list` or :meth:`get_cut_list`. Video decoding is performed in a background thread to allow scene detection and frame @@ -462,22 +464,25 @@ def detect_scenes( Arguments: video: VideoStream obtained from either `scenedetect.open_video`, or by creating one directly (e.g. `scenedetect.backends.opencv.VideoStreamCv2`). - duration: Amount of time to detect from current video position. Cannot be - specified if `end_time` is set. - end_time: Time to stop processing at. Cannot be specified if `duration` is set. + duration: Number of frames or elapsed time to process from the next unread frame. + Elapsed time is measured from that frame's timestamp. Cannot be specified if + `end_time` is set. + end_time: Exclusive frame ordinal or timestamp cutoff. Frame ordinals use the video's + `frame_numbering`; timestamps use its timeline. Cannot be specified if `duration` + is set. frame_skip: Not recommended except for extremely high framerate videos. Number of frames to skip (i.e. process every 1 in N+1 frames, - where N is frame_skip, processing only 1/N+1 percent of the video, - speeding up the detection time at the expense of accuracy). + where N is frame_skip), speeding up detection at the expense of accuracy. `frame_skip` **must** be 0 (the default) when using a StatsManager. show_progress: If True, and the ``tqdm`` module is available, displays - a progress bar with the progress, framerate, and expected time to - complete processing the video frame source. - callback: If set, called after each scene/event detected. + progress in frames or seconds, with an estimated time remaining when + a suitable total is known. + callback: If set, called with (image, FramePosition) for cuts reported during frame + processing whose images remain buffered. frame_source: [DEPRECATED] DO NOT USE. For compatibility with previous version. :meta private: Returns: - int: Number of frames read and processed from the frame source. + int: Number of frames read, including frames skipped for detection. Raises: ValueError: `frame_skip` **must** be 0 (the default) if the SceneManager was constructed with a StatsManager object. @@ -497,11 +502,15 @@ def detect_scenes( raise ValueError("frame_skip must be 0 when using a StatsManager.") if duration is not None and end_time is not None: raise ValueError("duration and end_time cannot be set at the same time!") - # TODO: These checks should be handled by the FrameTimecode constructor. - if duration is not None and isinstance(duration, (int, float)) and duration < 0: - raise ValueError("duration must be greater than or equal to 0!") - if end_time is not None and isinstance(end_time, (int, float)) and end_time < 0: - raise ValueError("end_time must be greater than or equal to 0!") + start_frame_num: int = video.frame_number + stop_at = parse_frame_or_time(end_time) if end_time is not None else None + length = parse_frame_or_time(duration) if duration is not None else None + + if length == 0: + return 0 + if isinstance(length, int): + stop_at = start_frame_num + 1 + length + duration_seconds = length if isinstance(length, Fraction) else None effective_frame_size = video.frame_size if self._crop: @@ -532,30 +541,40 @@ def detect_scenes( downscale_factor, ) - self._base_timecode = video.base_timecode - - # TODO: Figure out a better solution for communicating framerate to StatsManager. - if self._stats_manager is not None: - self._stats_manager._base_timecode = self._base_timecode - - start_frame_num: int = video.frame_number - if end_time is not None: - end_time = self._base_timecode + end_time - elif duration is not None: - end_time = (self._base_timecode + duration) + start_frame_num - - total_frames = 0 - if video.duration is not None: - if end_time is not None and end_time < video.duration: - total_frames = end_time - start_frame_num + total: int | Fraction | None = None + start_seconds: Fraction | None = None + + if isinstance(stop_at, Fraction) or duration_seconds is not None: + next_timecode = video.peek_timecode() + if next_timecode is None: + return 0 + + start_seconds = next_timecode.seconds + if duration_seconds is not None: + stop_at = start_seconds + duration_seconds + + assert isinstance(stop_at, Fraction) + total = max(0, stop_at - start_seconds) + elif isinstance(stop_at, int): + total = max(0, stop_at - start_frame_num - 1) + elif show_progress: + frame_count = video.frame_count + if frame_count is not None and video.frame_numbering is FrameNumbering.SOURCE: + total = max(0, frame_count - start_frame_num - 1) else: - total_frames = video.duration.frame_num - start_frame_num + video_duration = video.duration + if video_duration is not None: + next_timecode = video.peek_timecode() + if next_timecode is None: + return 0 + start_seconds = next_timecode.seconds + total = max(0, video_duration - start_seconds) progress_bar = None if show_progress: progress_bar = tqdm( - total=int(total_frames), - unit="frames", + total=float(total) if isinstance(total, Fraction) else total, + unit="s" if start_seconds is not None else "frames", desc=PROGRESS_BAR_DESCRIPTION % 0, dynamic_ncols=True, ) @@ -564,12 +583,12 @@ def detect_scenes( self._stop.clear() decode_thread = threading.Thread( target=SceneManager._decode_thread, - args=(self, video, frame_skip, downscale_factor, end_time, frame_queue), + args=(self, video, frame_skip, downscale_factor, stop_at, frame_queue), daemon=True, ) decode_thread.start() frame_im = None - prev_position = None + progress = 0 logger.info("Detecting scenes...") try: @@ -586,13 +605,14 @@ def detect_scenes( progress_bar.set_description( PROGRESS_BAR_DESCRIPTION % len(self._cutting_list), refresh=False ) - # Increment progress bar by delta of position.frame_num instead of 1 - # to handle VFR video where frame count is an approximation. - delta = ( - 1 if prev_position is None else position.frame_num - prev_position.frame_num - ) - progress_bar.update(delta) - prev_position = position + if start_seconds is None: + completed = position.frame_number - start_frame_num + else: + completed = float(position.timecode.seconds - start_seconds) + + completed = max(progress, completed) + progress_bar.update(completed - progress) + progress = completed finally: if progress_bar is not None: progress_bar.set_description( @@ -615,8 +635,10 @@ def detect_scenes( assert exc is not None raise exc.with_traceback(self._exception_info[2]) - self._last_pos = video.position - self._post_process(video.position) + last_pos = video.position + if last_pos is not None and frame_im is not None: + self._last_pos = last_pos + self._post_process(last_pos) return video.frame_number - start_frame_num @@ -625,18 +647,30 @@ def _decode_thread( video: VideoStream, frame_skip: int, downscale_factor: float, - end_time: FrameTimecode, + stop_at: int | Fraction | None, out_queue: queue.Queue, ): + frames_to_skip = 0 try: while not self._stop.is_set(): + if isinstance(stop_at, int) and video.frame_number + 1 >= stop_at: + break + if isinstance(stop_at, Fraction): + next_timecode = video.peek_timecode() + if next_timecode is None or next_timecode.seconds >= stop_at: + break + + skipping = frames_to_skip > 0 frame_im = None # We don't do any kind of locking here since the worst-case of this being wrong # is that we do some extra work, and this function should never mutate any data # (all of which should be modified under the GIL). - frame_im = video.read() + frame_im = video.read(decode=not skipping) if frame_im is False: break + if skipping: + frames_to_skip -= 1 + continue assert isinstance(frame_im, np.ndarray) # Verify the decoded frame size against the video container's reported # resolution, and also verify that consecutive frames have the correct size. @@ -644,7 +678,7 @@ def _decode_thread( if self._frame_size is None: self._frame_size = decoded_size if video.frame_size != decoded_size: - logger.warn( + logger.warning( f"WARNING: Decoded frame size ({decoded_size}) does not match " f" video resolution {video.frame_size}, possible corrupt input." ) @@ -657,7 +691,9 @@ def _decode_thread( f"expected = {self._frame_size}. Video may be corrupt." ) if self._frame_size_errors == MAX_FRAME_SIZE_ERRORS: - logger.warn("WARNING: Too many errors emitted, skipping future messages.") + logger.warning( + "WARNING: Too many errors emitted, skipping future messages." + ) # Skip processing frames that have an incorrect size. continue @@ -680,15 +716,7 @@ def _decode_thread( self._start_pos = video.position out_queue.put((frame_im, video.position)) - - if frame_skip > 0: - for _ in range(frame_skip): - if not video.read(decode=False): - break - # End time includes the presentation time of the frame, but the `position` - # property of a VideoStream references the beginning of the frame in time. - if end_time is not None and not (video.position + 1) < end_time: - break + frames_to_skip = frame_skip # If *any* exceptions occur, we re-raise them in the main thread so that the caller of # detect_scenes can handle it. @@ -701,9 +729,6 @@ def _decode_thread( self._stop.set() finally: - # Handle case where start position was never set if we did not decode any frames. - if self._start_pos is None: - self._start_pos = video.position # Make sure main thread stops processing loop. out_queue.put((None, None)) @@ -715,20 +740,19 @@ def get_cut_list( self, show_warning: bool = True, ) -> CutList: - """[DEPRECATED] Return a list of FrameTimecodes of the detected scene changes/cuts. + """[DEPRECATED] Return a list of FramePositions of the detected scene changes/cuts. - Unlike get_scene_list, the cutting list returns a list of FrameTimecodes representing + Unlike get_scene_list, the cutting list returns a list of FramePositions representing the point in the input video where a new scene was detected, and thus the frame where the input should be cut/split. The cutting list, in turn, is used to generate the scene list, noting that each scene is contiguous starting from the first frame and ending at the last frame detected. Arguments: - show_warning: If set to False, suppresses the error from being warned. In v0.7, - this will have no effect and the error will become a Python warning. + show_warning: If False, suppresses the deprecation warning. Returns: - List of FrameTimecode objects denoting the points in time where a scene change + List of FramePosition objects denoting the positions where a scene change was detected in the input video, which can also be passed to external tools for automated splitting of the input into individual scenes. diff --git a/scenedetect/stats_manager.py b/scenedetect/stats_manager.py index dc415f3c..ea0ef2ad 100644 --- a/scenedetect/stats_manager.py +++ b/scenedetect/stats_manager.py @@ -25,10 +25,11 @@ import os import os.path import typing as ty +from dataclasses import dataclass from logging import getLogger from pathlib import Path -from scenedetect.common import FrameTimecode +from scenedetect.common import FramePosition, Timecode from scenedetect.platform import StrPath logger = getLogger("pyscenedetect") @@ -48,6 +49,12 @@ ## +@dataclass(slots=True) +class _FrameStats: + metrics: dict[str, float] + timecode: Timecode | None = None + + class FrameMetricRegistered(Exception): """[DEPRECATED - DO NOT USE] No longer used. @@ -96,22 +103,12 @@ class StatsManager: Only metrics consisting of `float` or `int` should be used currently. """ - def __init__(self, base_timecode: int | FrameTimecode | None = None): - """Initialize a new StatsManager. - - Arguments: - base_timecode: Timecode associated with this object. Must not be None (default value - will be removed in a future release). - """ - # Frame metrics keyed by either an `int` frame number or a `FrameTimecode`. Both forms - # hash/compare to the same dict slot (`FrameTimecode.__hash__` returns `frame_num`), so - # public methods accept both interchangeably for the same frame. - self._frame_metrics: dict[int | FrameTimecode, dict[str, float]] = dict() + def __init__(self): + """Initialize a new StatsManager.""" + # Frame metrics keyed by either an `int` frame number. + self._frame_metrics: dict[int, _FrameStats] = dict() self._metric_keys: set[str] = set() self._metrics_updated: bool = False # Flag indicating if metrics require saving. - self._base_timecode: int | FrameTimecode | None = ( - base_timecode # Used for timing calculations. - ) @property def metric_keys(self) -> ty.Iterable[str]: @@ -124,7 +121,7 @@ def register_metrics(self, metric_keys: ty.Iterable[str]) -> None: # TODO(https://scenedetect.com/issues/507): We should support the dictionary protocol instead # of using this bespoke interface. It would be useful for Pandas compatibility as well. def get_metrics( - self, timecode: int | FrameTimecode, metric_keys: ty.Iterable[str] + self, frame: int | FramePosition, metric_keys: ty.Iterable[str] ) -> list[ty.Any]: """Return the requested statistics/metrics for a given timecode. @@ -132,25 +129,45 @@ def get_metrics( A list containing the requested frame metrics for the given frame number, ordered as they are in `metric_keys`. """ - return [self._get_metric(timecode, metric_key) for metric_key in metric_keys] + frame_number = frame.frame_number if isinstance(frame, FramePosition) else frame + stats = self._frame_metrics.get(frame_number) + metrics = stats.metrics if stats is not None else dict() + return [metrics.get(metric_key) for metric_key in metric_keys] - def set_metrics(self, timecode: int | FrameTimecode, metric_kv_dict: dict[str, ty.Any]) -> None: + def set_metrics(self, frame: int | FramePosition, metric_kv_dict: dict[str, ty.Any]) -> None: """Set Metrics: Sets the provided statistics/metrics for a given frame. Arguments: - timecode: Timecode to set metrics for. - metric_kv_dict: Key value mapping of metrics to their values for `timecode`. + frame: Frame to set metrics for. + metric_kv_dict: Key value mapping of metrics to their values for `frame`. """ - for metric_key in metric_kv_dict: - self._set_metric(timecode, metric_key, metric_kv_dict[metric_key]) + frame_number = frame.frame_number if isinstance(frame, FramePosition) else frame + stats = self._frame_metrics.get(frame_number) + if stats is None: + stats = _FrameStats(metrics=dict()) + self._metrics_updated = True + + if stats.timecode is None and isinstance(frame, FramePosition): + stats.timecode = frame.timecode + self._metrics_updated = True + + for key, value in metric_kv_dict.items(): + if key not in stats.metrics or stats.metrics[key] != value: + stats.metrics[key] = value + self._metrics_updated = True + + self._frame_metrics[frame_number] = stats - def metrics_exist(self, timecode: int | FrameTimecode, metric_keys: ty.Iterable[str]) -> bool: + def metrics_exist(self, frame: int | FramePosition, metric_keys: ty.Iterable[str]) -> bool: """Metrics Exist: Checks if the given metrics/stats exist for the given frame. Returns: bool: True if the given metric keys exist for the frame, False otherwise. """ - return all([self._metric_exists(timecode, metric_key) for metric_key in metric_keys]) + frame_number = frame.frame_number if isinstance(frame, FramePosition) else frame + stats = self._frame_metrics.get(frame_number) + metrics = stats.metrics if stats is not None else dict() + return all(metric_key in metrics for metric_key in metric_keys) def is_save_required(self) -> bool: """Is Save Required: Checks if the stats have been updated since loading. @@ -190,16 +207,16 @@ def save_to_csv( csv_writer = csv.writer(csv_file, lineterminator="\n") metric_keys = sorted(list(self._metric_keys)) csv_writer.writerow([COLUMN_NAME_FRAME_NUMBER, COLUMN_NAME_TIMECODE, *metric_keys]) - frame_keys = sorted(self._frame_metrics.keys()) + frame_keys = sorted(self._frame_metrics) logger.info("Writing %d frames to CSV...", len(frame_keys)) - for frame_key in frame_keys: - # `frame_key` may be a bare `int` if the deprecated `load_from_csv` populated the dict. - # Skip such rows since we cannot recover a timecode without a base framerate. - if not isinstance(frame_key, FrameTimecode): - continue + for frame_number in frame_keys: + stats = self._frame_metrics[frame_number] csv_writer.writerow( - [frame_key.frame_num + 1, frame_key.get_timecode()] - + [str(metric) for metric in self.get_metrics(frame_key, metric_keys)] + [ + frame_number + 1, + stats.timecode.get_timecode() if stats.timecode is not None else "", + *self.get_metrics(frame_number, metric_keys), + ] ) @staticmethod @@ -280,35 +297,18 @@ def load_from_csv(self, csv_file: StrPath | bytes | ty.TextIO) -> int | None: # Switch from 1-based to 0-based frame numbers. if frame_number > 0: frame_number -= 1 - self.set_metrics(frame_number, metric_dict) + for i, metric in enumerate(row[2:]): if metric and metric != "None": try: - self._set_metric(frame_number, loaded_metrics[i], float(metric)) + metric_dict[loaded_metrics[i]] = float(metric) except ValueError: raise StatsFileCorrupt( f"Corrupted value in stats file: {metric}" ) from ValueError + self.set_metrics(frame_number, metric_dict) num_frames += 1 self._metric_keys = self._metric_keys.union(set(loaded_metrics)) logger.info("Loaded %d metrics for %d frames.", num_metrics, num_frames) self._metrics_updated = False return num_frames - - # TODO: Get rid of these functions and simplify the implementation of this class. - - def _get_metric(self, timecode: int | FrameTimecode, metric_key: str) -> ty.Any | None: - if self._metric_exists(timecode, metric_key): - return self._frame_metrics[timecode][metric_key] - return None - - def _set_metric( - self, timecode: int | FrameTimecode, metric_key: str, metric_value: ty.Any - ) -> None: - self._metrics_updated = True - if timecode not in self._frame_metrics: - self._frame_metrics[timecode] = dict() - self._frame_metrics[timecode][metric_key] = metric_value - - def _metric_exists(self, timecode: int | FrameTimecode, metric_key: str) -> bool: - return timecode in self._frame_metrics and metric_key in self._frame_metrics[timecode] diff --git a/scenedetect/video_stream.py b/scenedetect/video_stream.py index 1d55cd4b..e7e0fdb0 100644 --- a/scenedetect/video_stream.py +++ b/scenedetect/video_stream.py @@ -22,7 +22,7 @@ frame = video.read() if frame is False: break - print("Read %d frames" % video.frame_number) + print("Read %d frames" % (video.frame_number + 1)) Leaving the ``with`` block closes the video, releasing resources such as file handles and decoders. A stream can also be closed explicitly by calling :meth:`VideoStream.close`. @@ -36,12 +36,18 @@ import typing as ty from abc import ABC, abstractmethod +from enum import Enum from fractions import Fraction from types import TracebackType import numpy as np -from scenedetect.common import FrameTimecode, TimecodeLike +from scenedetect.common import FramePosition, Timecode, TimecodeLike + + +class FrameNumbering(Enum): + RELATIVE = "relative" + SOURCE = "source" class SeekError(Exception): @@ -89,6 +95,43 @@ class VideoStream(ABC): # Default Implementations # + def __init__(self, frame_numbering: FrameNumbering = FrameNumbering.RELATIVE): + """ + Arguments: + frame_numbering: The frame numbering scheme to use. + """ + self._frame_numbering: FrameNumbering = frame_numbering + self._position: FramePosition | None = None + + @property + def frame_numbering(self) -> FrameNumbering: + """Returns the frame numbering scheme used by this VideoStream.""" + return self._frame_numbering + + @property + def position(self) -> FramePosition | None: + """Most recently recorded frame position, or None before a frame has been recorded. + + SOURCE-mode seeks may record preroll frames without returning their images. + """ + return self._position + + @property + def position_ms(self) -> float: + """Presentation time of the recorded position in milliseconds, or 0.0 if there is none. + + Restarting relative frame numbering does not reset presentation time. + """ + return self.position.timecode.seconds * 1000.0 if self.position is not None else 0.0 + + @property + def frame_number(self) -> int: + """Zero-based ordinal of the most recently recorded frame, or -1 if there is none. + + The ordinal's origin is determined by `frame_numbering`. + """ + return self._position.frame_number if self._position is not None else -1 + _decode_failures: int = 0 """Cumulative count of frames which failed to decode. Backends which can detect and skip corrupt frames increment this as an instance attribute.""" @@ -97,11 +140,6 @@ class VideoStream(ABC): """True once the stream has been closed. Backends which implement `close()` set this as an instance attribute, and call `_check_open()` from methods which require an open stream.""" - @property - def base_timecode(self) -> FrameTimecode: - """FrameTimecode object to use as a time base.""" - return FrameTimecode(timecode=0, fps=self.frame_rate) - @property def decode_failures(self) -> int: """Number of frames that failed to decode and were skipped (may indicate video @@ -145,6 +183,10 @@ def _check_open(self) -> None: if self._closed: raise ValueError("I/O operation on closed video stream.") + def _record_frame(self, timecode: Timecode) -> FramePosition: + self._position = FramePosition(timecode=timecode, frame_number=self.frame_number + 1) + return self._position + # # Backend Identification # @@ -182,44 +224,32 @@ def frame_rate(self) -> Fraction: @property @abstractmethod - def duration(self) -> FrameTimecode | None: - """Duration of the stream as a FrameTimecode, or None if non terminating.""" - ... + def duration(self) -> Fraction | None: + """Reported source duration in seconds, or None if unavailable. - @property - @abstractmethod - def frame_size(self) -> tuple[int, int]: - """Size of each video frame in pixels as a tuple of (width, height).""" - ... - - @property - @abstractmethod - def aspect_ratio(self) -> float: - """Pixel aspect ratio as a float (1.0 represents square pixels).""" + This is metadata and may be inaccurate. Estimates may be revised during decoding. + """ ... @property @abstractmethod - def position(self) -> FrameTimecode: - """Current position within stream as FrameTimecode. + def frame_count(self) -> int | None: + """Reported total source frame count, or None if unavailable. - This can be interpreted as presentation time stamp, thus frame 1 corresponds - to the presentation time 0. Returns 0 even if `frame_number` is 1.""" + This is metadata and may be inaccurate. Seeking and frame numbering does not change it. + """ ... @property @abstractmethod - def position_ms(self) -> float: - """Current position within stream as a float of the presentation time in - milliseconds. The first frame has a PTS of 0.""" + def frame_size(self) -> tuple[int, int]: + """Size of each video frame in pixels as a tuple of (width, height).""" ... @property @abstractmethod - def frame_number(self) -> int: - """Current position within stream as the frame number. - - Will return 0 until the first frame is `read`.""" + def aspect_ratio(self) -> float: + """Pixel aspect ratio as a float (1.0 represents square pixels).""" ... # @@ -243,6 +273,15 @@ def read(self, decode: bool = True) -> np.ndarray | bool: """ ... + @abstractmethod + def peek_timecode(self) -> Timecode | None: + """Return the presentation time of the next frame without advancing the stream. + + Returns: + Timecode of the next frame, or None if end of video. + """ + ... + @abstractmethod def reset(self) -> None: """Close and re-open the VideoStream (equivalent to seeking back to beginning). @@ -254,13 +293,12 @@ def reset(self) -> None: @abstractmethod def seek(self, target: TimecodeLike) -> None: - """Seek to the given timecode. If given as a frame number, represents the current seek - pointer (e.g. if seeking to 0, the next frame decoded will be the first frame of the video). + """Position the next read at a source frame ordinal or presentation time. - For 1-based indices (first frame is frame #1), the target frame number needs to be converted - to 0-based by subtracting one. For example, if we want to seek to the first frame, we call - seek(0) followed by read(). If we want to seek to the 5th frame, we call seek(4) followed - by read(), at which point frame_number will be 5. + Frame targets are zero-based source ordinals regardless of the numbering mode. For + example, `seek(4)` followed by `read()` reads the fifth source frame. Its ordinal is 4 in + SOURCE mode and 0 in RELATIVE mode. A successful seek restarts RELATIVE numbering at 0 + without changing source-relative presentation timestamps. May not be supported on all backend types or inputs (e.g. cameras). If `SeekError` is raised, the stream position is undefined. `reset()` can be called to restore the stream. diff --git a/scripts/generate_goldens.py b/scripts/generate_goldens.py index 26bdf107..154ab34e 100644 --- a/scripts/generate_goldens.py +++ b/scripts/generate_goldens.py @@ -53,7 +53,7 @@ def generate_golden(video_path: str, detector_class, params: dict) -> list[int]: scene_manager.detect_scenes(video) scene_list = scene_manager.get_scene_list() # Return start frame of each scene except the first one (which is 0) - return [scene[0].get_frames() for scene in scene_list[1:]] + return [scene[0].frame_number for scene in scene_list[1:]] def main(): diff --git a/tests/test_frame_position.py b/tests/test_frame_position.py new file mode 100644 index 00000000..663cae62 --- /dev/null +++ b/tests/test_frame_position.py @@ -0,0 +1,148 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# Copyright (C) 2025 Brandon Castellano . +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +# + +"""Tests for frame-position helpers, ordering and duration arithmetic.""" + +from dataclasses import FrozenInstanceError, dataclass +from fractions import Fraction + +import pytest + +from scenedetect.common import FrameDuration, FramePosition, Timecode + + +def test_frame_position_helpers_keep_frames_and_time_separate(): + position = FramePosition(Timecode(2, Fraction(1, 3)), 17) + + assert position.frame_number == position.get_frames() == 17 + assert position.pts == 2 + assert position.time_base == Fraction(1, 3) + assert position.timecode.seconds == Fraction(2, 3) + assert isinstance(position.timecode.seconds, Fraction) + + seconds = position.seconds + legacy_seconds = position.get_seconds() + assert isinstance(seconds, float) + assert isinstance(legacy_seconds, float) + assert seconds == legacy_seconds == pytest.approx(2 / 3) + assert position.get_timecode() == "00:00:00.667" + assert str(position) == "00:00:00.667" + expected = position.timecode.get_timecode(precision=4, use_rounding=False) + actual = position.get_timecode(precision=4, use_rounding=False) + assert actual == expected + + with pytest.warns(DeprecationWarning, match="frame_number") as caught: + assert position.frame_num == position.frame_number == position.get_frames() == 17 + assert len(caught) == 1 + assert caught[0].filename == __file__ + + +def test_frame_position_ordering_uses_ordinals(): + first = FramePosition(Timecode(1000, Fraction(1, 1000)), 10) + second = FramePosition(Timecode(1000, Fraction(1, 1000)), 11) + third = FramePosition(Timecode(900, Fraction(1, 1000)), 12) + + assert sorted([third, second, first]) == [first, second, third] + assert first < second < third + assert third > second > first + + +def test_frame_position_equality_and_hashing_use_both_fields(): + original = FramePosition(Timecode(1000, Fraction(1, 1000)), 10) + same = FramePosition(Timecode(1000, Fraction(1, 1000)), 10) + different_frame = FramePosition(original.timecode, 11) + different_time = FramePosition(Timecode(1001, Fraction(1, 1000)), 10) + + assert original == same + assert hash(original) == hash(same) + assert original != different_frame + assert original != different_time + assert {original: "saved"}[same] == "saved" + assert len({original, same, different_frame, different_time}) == 3 + + assert not original < different_time + assert not original > different_time + assert not different_time < original + assert not different_time > original + + +def test_frame_position_equality_distinguishes_subclasses(): + @dataclass(frozen=True) + class TaggedPosition(FramePosition): + tag: str + + original = FramePosition(Timecode(1000, Fraction(1, 1000)), 10) + tagged = TaggedPosition(original.timecode, original.frame_number, "tag") + assert original != tagged + assert tagged != original + + +def test_frame_position_subtraction_uses_exact_time_bases(): + start = FramePosition(Timecode(1, Fraction(1, 3)), 10) + end = FramePosition(Timecode(7, Fraction(1, 10)), 13) + + duration = end - start + assert duration == FrameDuration(frames=3, elapsed=Fraction(11, 30)) + assert isinstance(duration.elapsed, Fraction) + + +def test_frame_position_subtraction_allows_equal_timestamps(): + start = FramePosition(Timecode(500, Fraction(1, 1000)), 10) + end = FramePosition(Timecode(1000, Fraction(1, 2000)), 12) + + duration = end - start + assert duration == FrameDuration(frames=2, elapsed=Fraction(0)) + assert isinstance(duration.elapsed, Fraction) + + +def test_frame_position_subtraction_from_itself_is_zero(): + position = FramePosition(Timecode(1, Fraction(1, 3)), 10) + + duration = position - position + assert duration == FrameDuration(frames=0, elapsed=Fraction(0)) + assert isinstance(duration.elapsed, Fraction) + + +@pytest.mark.parametrize( + ("end_frame", "end_pts"), + [(9, 2000), (11, 500)], + ids=["negative-frames", "negative-time"], +) +def test_frame_position_subtraction_rejects_negative_results(end_frame, end_pts): + start = FramePosition(Timecode(1000, Fraction(1, 1000)), 10) + end = FramePosition(Timecode(end_pts, Fraction(1, 1000)), end_frame) + + with pytest.raises(ValueError, match="negative"): + end - start + + +@pytest.mark.parametrize( + "other", + [1, Timecode(1, Fraction(1, 1000)), FrameDuration(1, Fraction(1, 1000))], +) +def test_frame_position_subtraction_requires_another_position(other): + position = FramePosition(Timecode(1000, Fraction(1, 1000)), 10) + + with pytest.raises(TypeError): + position - other + + +@pytest.mark.parametrize( + ("value", "attribute", "replacement"), + [ + (FramePosition(Timecode(2, Fraction(1, 3)), 17), "frame_number", 18), + (FrameDuration(3, Fraction(11, 30)), "elapsed", Fraction(2, 3)), + ], +) +def test_positions_and_durations_are_immutable(value, attribute, replacement): + with pytest.raises(FrozenInstanceError): + setattr(value, attribute, replacement) diff --git a/tests/test_timecode.py b/tests/test_timecode.py index 51b0ee46..1df98607 100644 --- a/tests/test_timecode.py +++ b/tests/test_timecode.py @@ -9,16 +9,7 @@ # PySceneDetect is licensed under the BSD 3-Clause License; see the # included LICENSE file, or visit one of the above pages for details. # -"""PySceneDetect scenedetect.timecode Tests - -This file includes unit tests for the scenedetect.timecode module (specifically, the -FrameTimecode object, used for representing frame-accurate timestamps and time values). - -These unit tests test the FrameTimecode object with respect to object construction, -testing argument format/limits, operators (addition/subtraction), and conversion -to and from various time formats like integer frame number, float number of seconds, -or string HH:MM:SS[.nnn]. timecode format. -""" +"""Tests for timecodes, frame-rate conversion and NTSC filter regressions.""" # Third-Party Library Imports import math @@ -29,379 +20,66 @@ import pytest # Standard Library Imports -from scenedetect.common import MAX_FPS_DELTA, FrameTimecode, Timecode, framerate_to_fraction +from scenedetect.common import ( + MAX_FPS_DELTA, + FrameDuration, + FramePosition, + Timecode, + framerate_to_fraction, +) from scenedetect.detector import FlashFilter -def test_framerate(): - """Test FrameTimecode constructor argument "fps".""" - # Not passing fps results in TypeError. - with pytest.raises(TypeError): - FrameTimecode() # type: ignore[call-arg] - with pytest.raises(TypeError): - FrameTimecode(timecode=0, fps=None) - with pytest.raises(TypeError): - FrameTimecode( - timecode=None, # type: ignore[arg-type] - fps=FrameTimecode(timecode=0, fps=None), - ) +def test_framerate_to_fraction_rejects_invalid_rates(): + """Reject rates at or below the minimum supported threshold.""" # Test zero FPS/negative. with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=0.0) + framerate_to_fraction(fps=0.0) with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=-1.0) + framerate_to_fraction(fps=-1.0) with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=-100.0) + framerate_to_fraction(fps=-100.0) with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=0.0) + framerate_to_fraction(fps=0.0) with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=-1.0) + framerate_to_fraction(fps=-1.0) with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=-1000.0) + framerate_to_fraction(fps=-1000.0) with pytest.raises(ValueError): - FrameTimecode(timecode=0, fps=MAX_FPS_DELTA / 2) - # Test positive framerates. - assert FrameTimecode(timecode=0, fps=1.0).frame_num == 0 - assert FrameTimecode(timecode=0, fps=10.0).frame_num == 0 - assert FrameTimecode(timecode=0, fps=MAX_FPS_DELTA * 2).frame_num == 0 - assert FrameTimecode(timecode=0, fps=1000.0).frame_num == 0 - assert FrameTimecode(timecode=0, fps=1000.0).frame_num == 0 + framerate_to_fraction(fps=MAX_FPS_DELTA / 2) # Reject framerates too small for equality testing or potential divide by zero situations. with pytest.raises(ValueError): - assert FrameTimecode(timecode=0, fps=MAX_FPS_DELTA).frame_num == 0 - - -def test_frame_rate_property(): - """`frame_rate` returns an exact Fraction; `framerate` returns the float equivalent.""" - # Integer rate. - tc = FrameTimecode(timecode=0, fps=30.0) - assert tc.frame_rate == Fraction(30, 1) - assert isinstance(tc.frame_rate, Fraction) - with pytest.warns(DeprecationWarning, match="frame_rate"): - legacy_frame_rate = tc.framerate - - assert legacy_frame_rate == 30.0 - assert isinstance(legacy_frame_rate, float) - # Constructed directly from a Fraction (the exact form for NTSC rates). - tc = FrameTimecode(timecode=0, fps=Fraction(30000, 1001)) - assert tc.frame_rate == Fraction(30000, 1001) - with pytest.warns(DeprecationWarning, match="frame_rate"): - assert tc.framerate == pytest.approx(float(Fraction(30000, 1001))) - tc = FrameTimecode(timecode=0, fps=Fraction(24000, 1001)) - assert tc.frame_rate == Fraction(24000, 1001) - # time_base equals 1 / frame_rate for CFR sources. - assert tc.frame_rate is not None - assert tc.time_base == 1 / tc.frame_rate - - -def test_frame_rate_for_vfr(): - """For Timecode-backed instances, frame_rate is the approximation passed via fps.""" - fps = Fraction(24000, 1001) - tc = FrameTimecode(timecode=Timecode(pts=1001, time_base=Fraction(1, 24000)), fps=fps) - # frame_rate exposes the rate carried by the FrameTimecode (an approximation for VFR). - assert tc.frame_rate == fps - # time_base is authoritative for VFR and need not equal 1 / frame_rate. - assert tc.time_base == Fraction(1, 24000) - assert tc.frame_rate is not None - assert tc.time_base != 1 / tc.frame_rate - - -def test_frame_num_and_frame_rate_are_read_only(): - """Per migration guide, `frame_num`, `frame_rate`, and the legacy `framerate` alias are - read-only properties; callers must construct a new FrameTimecode to change them.""" - tc = FrameTimecode(timecode=0, fps=30.0) - for attr in ("frame_num", "frame_rate", "framerate"): - with pytest.raises(AttributeError): - setattr(tc, attr, 99) - - -def test_equal_frame_rate_legacy_alias(): - """`equal_framerate()` is the deprecated alias for `equal_frame_rate()` (issue #548). - Both forms should produce identical results for every accepted operand type.""" - tc = FrameTimecode(timecode=0, fps=30.0) - # float, Fraction, FrameTimecode operands. - other_tc = FrameTimecode(timecode=0, fps=30.0) - for other in (30.0, Fraction(30, 1), other_tc): - expected = tc.equal_frame_rate(other) - with pytest.warns(DeprecationWarning, match="equal_frame_rate"): - actual = tc.equal_framerate(other) - assert actual == expected - assert actual is True - # Mismatched rate. - assert tc.equal_frame_rate(24.0) is False - with pytest.warns(DeprecationWarning, match="equal_frame_rate"): - assert tc.equal_framerate(24.0) is False - - -def test_timecode_numeric(): - """Test FrameTimecode constructor argument "timecode" with numeric arguments.""" - with pytest.raises(ValueError): - FrameTimecode(timecode=-1, fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode=-1.0, fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode=-0.1, fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode=-1.0 / 1000, fps=1.0) - assert FrameTimecode(timecode=0, fps=1.0).frame_num == 0 - assert FrameTimecode(timecode=1, fps=1.0).frame_num == 1 - assert FrameTimecode(timecode=0.0, fps=1.0).frame_num == 0 - assert FrameTimecode(timecode=1.0, fps=1.0).frame_num == 1 - - -def test_timecode_string(): - """Test FrameTimecode constructor argument "timecode" with string arguments.""" - # Invalid strings: - with pytest.raises(ValueError): - FrameTimecode(timecode="-1", fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode="-1.0", fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode="-0.1", fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode="1.9x", fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode="1x", fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode="1.9.9", fps=1.0) - with pytest.raises(ValueError): - FrameTimecode(timecode="1.0-", fps=1.0) - - # Frame number integer [int->str] ('%d', integer number as string) - assert FrameTimecode(timecode="0", fps=1.0).frame_num == 0 - assert FrameTimecode(timecode="1", fps=1.0).frame_num == 1 - assert FrameTimecode(timecode="10", fps=1.0).frame_num == 10 - - # Seconds format [float->str] ('%f', number as string) - assert FrameTimecode(timecode="0.0", fps=1.0).frame_num == 0 - assert FrameTimecode(timecode="1.0", fps=1.0).frame_num == 1 - assert FrameTimecode(timecode="10.0", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="10.0000000000", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="10.100", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="1.100", fps=10.0).frame_num == 11 - - # Seconds format [float->str] ('%fs', number as string followed by 's' for seconds) - assert FrameTimecode(timecode="0s", fps=1.0).frame_num == 0 - assert FrameTimecode(timecode="1s", fps=1.0).frame_num == 1 - assert FrameTimecode(timecode="10s", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="10.0s", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="10.0000000000s", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="10.100s", fps=1.0).frame_num == 10 - assert FrameTimecode(timecode="1.100s", fps=10.0).frame_num == 11 - - # Standard timecode format [timecode->str] ('HH:MM:SS[.nnn]', where [.nnn] is optional) - assert FrameTimecode(timecode="00:00:01", fps=1.0).frame_num == 1 - assert FrameTimecode(timecode="00:00:01.9999", fps=1.0).frame_num == 2 - assert FrameTimecode(timecode="00:00:02.0000", fps=1.0).frame_num == 2 - assert FrameTimecode(timecode="00:00:02.0001", fps=1.0).frame_num == 2 - - # MM:SS[.nnn] is also allowed - assert FrameTimecode(timecode="00:01", fps=1.0).frame_num == 1 - assert FrameTimecode(timecode="00:01.9999", fps=1.0).frame_num == 2 - assert FrameTimecode(timecode="00:02.0000", fps=1.0).frame_num == 2 - assert FrameTimecode(timecode="00:02.0001", fps=1.0).frame_num == 2 - - # Conversion edge cases - assert FrameTimecode(timecode="00:00:01", fps=10.0).frame_num == 10 - assert FrameTimecode(timecode="00:00:00.5", fps=10.0).frame_num == 5 - assert FrameTimecode(timecode="00:00:00.100", fps=10.0).frame_num == 1 - assert FrameTimecode(timecode="00:00:00.001", fps=1000.0).frame_num == 1 - - assert FrameTimecode(timecode="00:00:59.999", fps=1.0).frame_num == 60 - assert FrameTimecode(timecode="00:01:00.000", fps=1.0).frame_num == 60 - assert FrameTimecode(timecode="00:01:00.001", fps=1.0).frame_num == 60 - - assert FrameTimecode(timecode="00:59:59.999", fps=1.0).frame_num == 3600 - assert FrameTimecode(timecode="01:00:00.000", fps=1.0).frame_num == 3600 - assert FrameTimecode(timecode="01:00:00.001", fps=1.0).frame_num == 3600 - - # Check too many ":" characters (https://github.com/Breakthrough/PySceneDetect/issues/476) - with pytest.raises(ValueError): - FrameTimecode(timecode="01:01:00:00.001", fps=1.0) - - -def test_get_frames(): - """Test FrameTimecode get_frames() method.""" - assert FrameTimecode(timecode=1, fps=1.0).frame_num == 1 - assert FrameTimecode(timecode=1000, fps=60.0).frame_num == 1000 - assert FrameTimecode(timecode=1000000000, fps=29.97).frame_num == 1000000000 - - assert FrameTimecode(timecode=1.0, fps=1.0).frame_num == int(1.0 / 1.0) - assert FrameTimecode(timecode=1000.0, fps=60.0).frame_num == int(1000.0 * 60.0) - # 29.97 snaps to exact NTSC Fraction(30000, 1001), so expected is computed from that - # rational rather than the lossy float multiplication. - assert FrameTimecode(timecode=1000000000.0, fps=29.97).frame_num == round( - 1000000000.0 * 30000 / 1001 - ) - - assert FrameTimecode(timecode="00:00:02.0000", fps=1.0).frame_num == 2 - assert FrameTimecode(timecode="00:00:00.5", fps=10.0).frame_num == 5 - assert FrameTimecode(timecode="00:00:01", fps=10.0).frame_num == 10 - assert FrameTimecode(timecode="00:01:00.000", fps=1.0).frame_num == 60 - - -def test_get_seconds(): - """Test FrameTimecode get_seconds() method.""" - assert FrameTimecode(timecode=1, fps=1.0).seconds, pytest.approx(1.0 / 1.0) - assert FrameTimecode(timecode=1000, fps=60.0).seconds, pytest.approx(1000 / 60.0) - assert FrameTimecode(timecode=1000000000, fps=29.97).seconds, pytest.approx(1000000000 / 29.97) - - assert FrameTimecode(timecode=1.0, fps=1.0).seconds, pytest.approx(1.0) - assert FrameTimecode(timecode=1000.0, fps=60.0).seconds, pytest.approx(1000.0) - assert FrameTimecode(timecode=1000000000.0, fps=29.97).seconds, pytest.approx(1000000000.0) - - assert FrameTimecode(timecode="00:00:02.0000", fps=1.0).seconds, pytest.approx(2.0) - assert FrameTimecode(timecode="00:00:00.5", fps=10.0).seconds, pytest.approx(0.5) - assert FrameTimecode(timecode="00:00:01", fps=10.0).seconds, pytest.approx(1.0) - assert FrameTimecode(timecode="00:01:00.000", fps=1.0).seconds, pytest.approx(60.0) - - -def test_get_timecode(): - """Test FrameTimecode get_timecode() method.""" - assert FrameTimecode(timecode=1.0, fps=1.0).get_timecode() == "00:00:01.000" - assert FrameTimecode(timecode=60.117, fps=60.0).get_timecode() == "00:01:00.117" - # 29.97 snaps to exact NTSC Fraction(30000, 1001); 3600.234s lands on the nearest - # NTSC frame at ~01:00:00.230 rather than the lossy-float result of "01:00:00.234". - assert FrameTimecode(timecode=3600.234, fps=29.97).get_timecode() == "01:00:00.230" - - assert FrameTimecode(timecode="00:00:02.0000", fps=1.0).get_timecode() == "00:00:02.000" - assert FrameTimecode(timecode="00:00:00.5", fps=10.0).get_timecode() == "00:00:00.500" - # If a value is provided in seconds, we store that value internally now. - assert ( - FrameTimecode(timecode="00:00:01.501", fps=10.0).get_timecode(nearest_frame=False) - == "00:00:01.501" - ) - assert ( - FrameTimecode(timecode="00:00:01.501", fps=10.0).get_timecode(nearest_frame=True) - == "00:00:01.500" - ) - - -def test_equality(): - """Test FrameTimecode equality (==, __eq__) operator.""" - x = FrameTimecode(timecode=1.0, fps=10.0) - assert x == x - assert x == FrameTimecode(timecode=1.0, fps=10.0) - assert x == FrameTimecode(timecode=1.0, fps=10.0) - assert x == FrameTimecode(timecode=1.0, fps=Fraction(10, 1)) - assert x != FrameTimecode(timecode=10.0, fps=10.0) - assert x != FrameTimecode(timecode=10.0, fps=10.0) - assert x != FrameTimecode(timecode=10.0, fps=Fraction(100, 10)) - assert x == FrameTimecode(x) - assert x == FrameTimecode(1.0, x) - assert x == FrameTimecode(10, x) - assert x == "00:00:01" - assert x == "00:00:01.0" - assert x == "00:00:01.00" - assert x == "00:00:01.000" - assert x == "00:00:01.0000" - assert x == "00:00:01.00000" - assert x == 10 - assert x == 1.0 - - with pytest.raises(ValueError): - assert x == "0x" - with pytest.raises(ValueError): - assert x == "x00:00:00.000" - with pytest.raises(TypeError): - assert x == [0] - with pytest.raises(TypeError): - assert x == (0,) - with pytest.raises(TypeError): - assert x == [0, 1, 2, 3] - with pytest.raises(TypeError): - assert x == {0: 0} - - assert FrameTimecode(timecode="00:00:00.5", fps=10.0) == "00:00:00.500" - assert FrameTimecode(timecode="00:00:01.500", fps=10.0) == "00:00:01.500" - - -def test_addition(): - """Test FrameTimecode addition (+/+=, __add__/__iadd__) operator.""" - x = FrameTimecode(timecode=1.0, fps=10.0) - assert x + 1 == FrameTimecode(timecode=1.1, fps=10.0) - assert x + 1 == FrameTimecode(1.1, x) - assert x + 10 == "00:00:02.000", str(x + 10) - assert x + 10 == 20 - assert x + 10 == 2.0 - assert x + 10 == "00:00:02.000" - - -def test_subtraction(): - """Test FrameTimecode subtraction (-/-=, __sub__) operator.""" - x = FrameTimecode(timecode=1.0, fps=10.0) - assert (x - 1) == FrameTimecode(timecode=0.9, fps=10.0) - assert x - 2 == FrameTimecode(0.8, x) - assert x - 10 == FrameTimecode(0.0, x) - # TODO(v1.0): Allow negative values. For now we clamp. - assert x - 11 == FrameTimecode(0.0, x) - assert x - 100 == FrameTimecode(0.0, x) - assert x - 1.0 == FrameTimecode(0.0, x) - assert x - 100.0 == FrameTimecode(0.0, x) - assert x - 1 == FrameTimecode(timecode=0.9, fps=10.0) - assert FrameTimecode("00:00:00.000", fps=20.0) == x - 10 - - -@pytest.mark.parametrize( - "frame_num,fps", [(1, 1.0), (61, 14.0), (29, 25.0), (126, Fraction(24000, 1001))] -) -def test_identity(frame_num, fps): - """Test FrameTimecode values, when used in init return the same values""" - frame_time_code = FrameTimecode(frame_num, fps=fps) - assert FrameTimecode(frame_time_code) == frame_time_code - assert FrameTimecode(frame_time_code.frame_num, fps=fps) == frame_time_code - assert FrameTimecode(frame_time_code.seconds, fps=fps) == frame_time_code - assert FrameTimecode(frame_time_code.get_timecode(), fps=fps) == frame_time_code - - -def test_precision(): - """Test rounding and precision, which has implications for rounding behavior.""" - - fps = 1000.0 - - assert FrameTimecode(110, fps).get_timecode(precision=2, use_rounding=True) == "00:00:00.11" - assert FrameTimecode(110, fps).get_timecode(precision=2, use_rounding=False) == "00:00:00.11" - assert FrameTimecode(110, fps).get_timecode(precision=1, use_rounding=True) == "00:00:00.1" - assert FrameTimecode(110, fps).get_timecode(precision=1, use_rounding=False) == "00:00:00.1" - assert FrameTimecode(110, fps).get_timecode(precision=0, use_rounding=True) == "00:00:00" - assert FrameTimecode(110, fps).get_timecode(precision=0, use_rounding=False) == "00:00:00" - - assert FrameTimecode(990, fps).get_timecode(precision=2, use_rounding=True) == "00:00:00.99" - assert FrameTimecode(990, fps).get_timecode(precision=2, use_rounding=False) == "00:00:00.99" - assert FrameTimecode(990, fps).get_timecode(precision=1, use_rounding=True) == "00:00:01.0" - assert FrameTimecode(990, fps).get_timecode(precision=1, use_rounding=False) == "00:00:00.9" - assert FrameTimecode(990, fps).get_timecode(precision=0, use_rounding=True) == "00:00:01" - assert FrameTimecode(990, fps).get_timecode(precision=0, use_rounding=False) == "00:00:00" + assert framerate_to_fraction(fps=MAX_FPS_DELTA) def test_precision_truncation(): """Truncating must drop the extra digits, never round up into the last digit that is kept.""" # 1.99996667s, e.g. a frame position from a 90 kHz time base. - tc = FrameTimecode(Timecode(pts=179997, time_base=Fraction(1, 90000)), Fraction(30000, 1001)) + tc = Timecode(pts=179997, time_base=Fraction(1, 90000)) assert tc.get_timecode(precision=3, use_rounding=False) == "00:00:01.999" assert tc.get_timecode(precision=2, use_rounding=False) == "00:00:01.99" assert tc.get_timecode(precision=0, use_rounding=False) == "00:00:01" assert tc.get_timecode(precision=3, use_rounding=True) == "00:00:02.000" # Frame 911 is at 37.996s. - tc = FrameTimecode(911, Fraction(24000, 1001)) + tc = Timecode(911, Fraction(1001, 24000)) assert tc.get_timecode(precision=1, use_rounding=False) == "00:00:37.9" assert tc.get_timecode(precision=1, use_rounding=True) == "00:00:38.0" - tc = FrameTimecode(59.99996, 24.0) - assert tc.get_timecode(use_rounding=False, nearest_frame=False) == "00:00:59.999" + tc = Timecode(pts=5999996, time_base=Fraction(1, 100000)) + assert tc.get_timecode(use_rounding=False) == "00:00:59.999" # Float error must not truncate exact values down, e.g. 504 / (24000 / 1001) == 21.021. - tc = FrameTimecode(504, Fraction(24000, 1001)) + tc = Timecode(pts=504, time_base=Fraction(1001, 24000)) assert tc.get_timecode(precision=3, use_rounding=False) == "00:00:21.021" - tc = FrameTimecode(61.29, 24.0) - assert tc.get_timecode(precision=2, use_rounding=False, nearest_frame=False) == "00:01:01.29" + tc = Timecode(pts=6129, time_base=Fraction(1, 100)) + assert tc.get_timecode(precision=2, use_rounding=False) == "00:01:01.29" def test_precision_truncation_matches_exact_arithmetic(): """Truncation must give the exact answer at any precision, including large timestamps.""" # Float error is larger for big values at high precision: 8192.826s at 1/1000 time base. - tc = FrameTimecode(Timecode(pts=8192826, time_base=Fraction(1, 1000)), Fraction(30000, 1001)) + tc = Timecode(pts=8192826, time_base=Fraction(1, 1000)) assert tc.get_timecode(precision=3, use_rounding=False) == "02:16:32.826" assert tc.get_timecode(precision=6, use_rounding=False) == "02:16:32.826000" @@ -424,48 +102,110 @@ def exact(secs: Fraction, precision: int) -> str: ): for _ in range(500): pts = rng.randrange(0, 400_000_000) - tc = FrameTimecode(Timecode(pts=pts, time_base=time_base), Fraction(30000, 1001)) + tc = Timecode(pts=pts, time_base=time_base) for precision in precisions: assert tc.get_timecode(precision=precision, use_rounding=False) == exact( pts * time_base, precision ), (pts, time_base, precision) - # Frame number timecodes. + # CFR fixtures use the exact frame period as their timestamp unit. for fps in (Fraction(24000, 1001), Fraction(30000, 1001), Fraction(25)): for _ in range(500): frame = rng.randrange(0, 10_000_000) - tc = FrameTimecode(frame, fps) + tc = Timecode(pts=frame, time_base=1 / fps) for precision in precisions: assert tc.get_timecode(precision=precision, use_rounding=False) == exact( Fraction(frame) / fps, precision ), (frame, fps, precision) -def test_negative_time_is_shown_as_zero(): - """A negative PTS gives a zero timecode, whether rounding or truncating.""" - tc = FrameTimecode(Timecode(pts=-1, time_base=Fraction(1, 1000)), Fraction(30000, 1001)) - assert tc.get_timecode(use_rounding=False) == "00:00:00.000" - assert tc.get_timecode(use_rounding=True) == "00:00:00.000" - tc = FrameTimecode(Timecode(pts=-4_000_000, time_base=Fraction(1, 1000)), Fraction(30000, 1001)) - assert tc.get_timecode(use_rounding=False) == "00:00:00.000" - assert tc.get_timecode(use_rounding=True) == "00:00:00.000" +@pytest.mark.parametrize( + "pts,time_base,expected", + [ + (0, Fraction(1, 1000), "00:00:00.000"), + (125, Fraction(1, 100), "00:00:01.250"), + (45296789, Fraction(1, 1000), "12:34:56.789"), + (1, Fraction(1001, 24000), "00:00:00.042"), + (360000, Fraction(1), "100:00:00.000"), + ], +) +def test_timecode_get_timecode(pts, time_base, expected): + """Format observed timestamps directly, including rational bases and long runtimes.""" + assert Timecode(pts, time_base).get_timecode() == expected -@pytest.mark.parametrize("use_rounding", [True, False]) -def test_negative_precision_is_rejected(use_rounding: bool): - """A negative precision gives a clear error, whether rounding or truncating.""" - tc = FrameTimecode(10, 24.0) - with pytest.raises(ValueError, match="precision must not be negative"): - tc.get_timecode(precision=-1, use_rounding=use_rounding) +@pytest.mark.parametrize( + "seconds,precision,use_rounding,expected", + [ + ("0.11", 2, True, "00:00:00.11"), + ("0.99", 1, True, "00:00:01.0"), + ("0.99", 1, False, "00:00:00.9"), + ("0.99", 0, True, "00:00:01"), + ("0.99", 0, False, "00:00:00"), + ("1.5", 0, True, "00:00:02"), + ("2.5", 0, True, "00:00:02"), + ("0.0005", 3, True, "00:00:00.000"), + ("0.0015", 3, True, "00:00:00.002"), + ("0.0025", 3, True, "00:00:00.002"), + ("0.9995", 3, True, "00:00:01.000"), + ("59.9995", 3, True, "00:01:00.000"), + ("3599.9995", 3, True, "01:00:00.000"), + ("1/3", 6, True, "00:00:00.333333"), + ("2/3", 6, True, "00:00:00.666667"), + ("2/3", 6, False, "00:00:00.666666"), + ("1.000000000000000001", 18, True, "00:00:01.000000000000000001"), + ("1.000000000000000001", 18, False, "00:00:01.000000000000000001"), + ], +) +def test_timecode_get_timecode_precision(seconds, precision, use_rounding, expected): + """Round exact ties to even and carry through boundaries without float conversion.""" + value = Fraction(seconds) + timecode = Timecode(value.numerator, Fraction(1, value.denominator)) + assert timecode.get_timecode(precision=precision, use_rounding=use_rounding) == expected + + +@pytest.mark.parametrize( + "seconds,expected", + [ + ("1.23499", "00:00:01.234"), + ("0.99996", "00:00:00.999"), + ("59.99996", "00:00:59.999"), + ("3599.99996", "00:59:59.999"), + ], +) +def test_timecode_get_timecode_truncation_regression(seconds, expected): + """Truncation must not round an extra decimal place before discarding it.""" + value = Fraction(seconds) + timecode = Timecode(value.numerator, Fraction(1, value.denominator)) + assert timecode.get_timecode(use_rounding=False) == expected -def test_rational_framerate_precision(): - """Rational framerates should round-trip frame/second conversions without drift.""" - fps = Fraction(24000, 1001) - # Verify that frame_num round-trips through seconds without drift over many frames. - for frame in [0, 1, 100, 1000, 10000, 100000]: - tc = FrameTimecode(frame, fps) - assert tc.frame_num == frame, f"Frame {frame} drifted to {tc.frame_num}" +@pytest.mark.parametrize( + "seconds,use_rounding,expected", + [ + ("-1.23499", True, "-00:00:01.235"), + ("-1.23499", False, "-00:00:01.234"), + ("-59.9995", True, "-00:01:00.000"), + ("-0.0001", True, "00:00:00.000"), + ("-0.0001", False, "00:00:00.000"), + ("-0.001", True, "-00:00:00.001"), + ("-0.001", False, "-00:00:00.001"), + ("-4000", True, "-01:06:40.000"), + ("-4000", False, "-01:06:40.000"), + ], +) +def test_timecode_get_timecode_negative_timestamps(seconds, use_rounding, expected): + """Preserve negative timestamp signs, but do not emit negative zero.""" + value = Fraction(seconds) + timecode = Timecode(value.numerator, Fraction(1, value.denominator)) + assert timecode.get_timecode(use_rounding=use_rounding) == expected + + +@pytest.mark.parametrize("precision", [-1, -3]) +@pytest.mark.parametrize("use_rounding", [True, False]) +def test_timecode_get_timecode_rejects_negative_precision(precision, use_rounding): + with pytest.raises(ValueError, match="precision must be non-negative"): + Timecode(0, Fraction(1, 1000)).get_timecode(precision=precision, use_rounding=use_rounding) def test_ntsc_framerate_detection(): @@ -474,29 +214,13 @@ def test_ntsc_framerate_detection(): assert framerate_to_fraction(29.97002997002997) == Fraction(30000, 1001) assert framerate_to_fraction(59.94005994005994) == Fraction(60000, 1001) assert framerate_to_fraction(119.88011988011988) == Fraction(120000, 1001) + assert framerate_to_fraction(59.94) == Fraction(60000, 1001) assert framerate_to_fraction(24.0) == Fraction(24, 1) assert framerate_to_fraction(30.0) == Fraction(30, 1) assert framerate_to_fraction(60.0) == Fraction(60, 1) assert framerate_to_fraction(25.0) == Fraction(25, 1) -def test_frame_timecode_converts_ntsc_float_fps(): - """End-to-end: passing a float NTSC rate into the FrameTimecode constructor must yield - the exact Fraction representation, not the lossy float. This is the user-facing entry - point most users hit (e.g. when a backend hands them `cap.get(CAP_PROP_FPS)`).""" - expected = { - 23.976: Fraction(24000, 1001), - 29.97: Fraction(30000, 1001), - 59.94: Fraction(60000, 1001), - } - for fps_float, fps_exact in expected.items(): - tc = FrameTimecode(0, fps_float) - assert tc.frame_rate == fps_exact, ( - f"FrameTimecode(0, {fps_float}) produced {tc.frame_rate}, expected {fps_exact}" - ) - assert isinstance(tc.frame_rate, Fraction) - - def test_ntsc_framerate_detection_arbitrary_base(): """NTSC detection should work for any base rate, not a hardcoded list (e.g. 48000/1001 for HFR cinema).""" @@ -541,161 +265,31 @@ def test_framerate_to_fraction_accepts_rational(): framerate_to_fraction(_StubRational(0, 1)) # type: ignore[arg-type] -def test_frame_timecode_accepts_rational_fps(): - tc = FrameTimecode(0, _StubRational(24000, 1001)) # type: ignore[arg-type] - assert isinstance(tc.frame_rate, Fraction) - assert tc.frame_rate == Fraction(24000, 1001) - - -def test_frame_timecode_rejects_integral_fps(): - """`int`/`bool` are also `numbers.Rational` - these must raise TypeError so a misplaced - frame *count* is never silently used as a frame *rate*.""" - with pytest.raises(TypeError): - FrameTimecode(0, 30) # type: ignore[arg-type] - with pytest.raises(TypeError): - FrameTimecode(0, True) # type: ignore[arg-type] - - def test_timecode_normalizes_rational_time_base(): tc = Timecode(pts=1001, time_base=_StubRational(1, 30000)) # type: ignore[arg-type] assert isinstance(tc.time_base, Fraction) assert tc.time_base == Fraction(1, 30000) - assert tc.seconds == pytest.approx(1001 / 30000) - - -def test_timecode_arithmetic_mixed_time_base(): - """Arithmetic with FrameTimecodes using different time_bases should work.""" - fps = Fraction(24000, 1001) - # Timecode with time_base 1/24000 (from PyAV) - tc_pyav = FrameTimecode(timecode=Timecode(pts=1001, time_base=Fraction(1, 24000)), fps=fps) - # Timecode with time_base 1/1000000 (from OpenCV microseconds) - tc_cv2 = FrameTimecode(timecode=Timecode(pts=41708, time_base=Fraction(1, 1000000)), fps=fps) - # Both represent approximately 1 frame duration. Addition/subtraction shouldn't raise. - result = tc_pyav + tc_cv2 - assert result.seconds > 0 - result = tc_pyav - tc_cv2 - assert result.seconds >= 0 # Clamped to 0 if negative - - -def test_timecode_frame_num_for_vfr(): - """frame_num should return approximate values for Timecode-backed objects without warning.""" - fps = Fraction(24000, 1001) - tc = FrameTimecode(timecode=Timecode(pts=1001, time_base=Fraction(1, 24000)), fps=fps) - # Should not raise or warn - just return the approximate frame number. - assert tc.frame_num == 1 - - -def test_arithmetic_with_bare_timecode(): - """`FrameTimecode` arithmetic should accept a bare :class:`Timecode` operand by treating - it as an absolute time in seconds.""" - fps = 30.0 - base = FrameTimecode(timecode=10, fps=fps) # 10 frames @ 30fps == ~0.333s - # 1/30s expressed in a 1/1000 time base is pts=33 (rounded). - one_frame_at_30 = Timecode(pts=33, time_base=Fraction(1, 1000)) - - plus = base + one_frame_at_30 - assert plus.frame_num == 11 - - minus = base - one_frame_at_30 - assert minus.frame_num == 9 - - # Reverse direction: a Timecode-backed FrameTimecode plus a bare Timecode. - pts_base = FrameTimecode(timecode=Timecode(pts=1, time_base=Fraction(1, 1000)), fps=fps) - pts_plus = pts_base + Timecode(pts=2, time_base=Fraction(1, 1000)) - assert pts_plus.seconds == pytest.approx(0.003) - - -def test_comparisons_with_bare_timecode(): - """`FrameTimecode` comparison operators should accept a bare :class:`Timecode` operand.""" - fps = 30.0 - half_second_frame = FrameTimecode(timecode=15, fps=fps) - half_second_tc = Timecode(pts=500, time_base=Fraction(1, 1000)) - one_second_tc = Timecode(pts=1000, time_base=Fraction(1, 1000)) - - assert half_second_frame == half_second_tc - assert half_second_frame != one_second_tc - assert half_second_frame < one_second_tc - assert half_second_frame <= half_second_tc - assert one_second_tc != half_second_frame # reflected via __ne__ - assert FrameTimecode(timecode=30, fps=fps) > half_second_tc - assert FrameTimecode(timecode=15, fps=fps) >= half_second_tc - - -def test_exact_comparison_same_rate(): - """Timecode-backed instances with the same rate compare by exact PTS, not rounded frame - numbers. pts=999 and pts=1001 @ time_base 1/1000 both round to frame 30 @ 30fps, but - represent different presentation times.""" - fps = Fraction(30, 1) - a = FrameTimecode(timecode=Timecode(pts=999, time_base=Fraction(1, 1000)), fps=fps) - b = FrameTimecode(timecode=Timecode(pts=1001, time_base=Fraction(1, 1000)), fps=fps) - assert a.frame_num == b.frame_num == 30 # Rounding collides... - assert a != b # ...but exact times differ. - assert not (a == b) # noqa: SIM201 - deliberately exercises __eq__, not just __ne__. - assert a < b and a <= b - assert b > a and b >= a - assert not (a > b) and not (a >= b) - # Hash may still collide (frame_num-based); that is legal since a != b. - assert hash(a) == hash(b) - # Sets/sorting now distinguish and correctly order the two times. - assert len({a, b}) == 2 - assert sorted([b, a]) == [a, b] - - -def test_exact_equality_across_time_base_representations(): - """Equal exact times expressed in different time bases are equal, and hashes agree.""" - fps = Fraction(30, 1) - a = FrameTimecode(timecode=Timecode(pts=500, time_base=Fraction(1, 1000)), fps=fps) - b = FrameTimecode(timecode=Timecode(pts=1000, time_base=Fraction(1, 2000)), fps=fps) - assert a == b and not (a != b) # noqa: SIM202 - deliberately exercises both operators. - assert a <= b and a >= b - assert not (a < b) and not (a > b) - assert hash(a) == hash(b) - assert len({a, b}) == 1 - - -def test_exact_comparison_requires_same_rate(): - """Timecode-backed instances with DIFFERENT rates keep legacy frame-number comparison.""" - a = FrameTimecode(timecode=Timecode(pts=999, time_base=Fraction(1, 1000)), fps=30.0) - b = FrameTimecode(timecode=Timecode(pts=1001, time_base=Fraction(1, 1000)), fps=30.0) - c = FrameTimecode(b, fps=Fraction(30000, 1001)) # Same time as b, different rate. - # Cross-rate falls back to frame_num comparison: - assert (a == c) == (a.frame_num == c.frame_num) - # Same-rate pair still compares exactly: - assert a != b - - -def test_cross_rate_frame_number_equality_unchanged(): - """Legacy behavior pinned: rated, non-Timecode-backed instances with different rates still - compare by frame number.""" - assert FrameTimecode(timecode=100, fps=25.0) == FrameTimecode(timecode=100, fps=30.0) - - -def test_mixed_representation_comparison_unchanged(): - """Timecode-backed vs frame-backed comparison still uses frame numbers.""" - fps = Fraction(24000, 1001) - vfr = FrameTimecode(timecode=Timecode(pts=1001, time_base=Fraction(1, 24000)), fps=fps) - assert vfr.frame_num == 1 - assert vfr == FrameTimecode(timecode=1, fps=fps) + assert tc.seconds == Fraction(1001, 30000) def test_min_scene_len_accepts_timecode_like(): - """Detector ``min_scene_len`` and FlashFilter ``length`` should accept any TimecodeLike, - including :class:`FrameTimecode` / :class:`Timecode`.""" + """Detector minima and FlashFilter lengths accept frame and time inputs.""" from scenedetect.detector import FlashFilter from scenedetect.detectors import ContentDetector - # FlashFilter: int, float, str, FrameTimecode, Timecode all valid. + # FlashFilter: integer frames, seconds, strings and Timecode are valid. FlashFilter(mode=FlashFilter.Mode.MERGE, length=15) FlashFilter(mode=FlashFilter.Mode.MERGE, length=0.5) FlashFilter(mode=FlashFilter.Mode.MERGE, length="00:00:00.500") - FlashFilter(mode=FlashFilter.Mode.MERGE, length=FrameTimecode(timecode=15, fps=30.0)) FlashFilter( mode=FlashFilter.Mode.MERGE, length=Timecode(pts=500, time_base=Fraction(1, 1000)), ) # ContentDetector: same. - ContentDetector(min_scene_len=FrameTimecode(timecode=15, fps=30.0)) + ContentDetector(min_scene_len=15) + ContentDetector(min_scene_len=0.5) + ContentDetector(min_scene_len="00:00:00.500") ContentDetector(min_scene_len=Timecode(pts=500, time_base=Fraction(1, 1000))) @@ -709,19 +303,25 @@ def test_min_scene_len_accepts_timecode_like(): ) -def _ntsc_pts_position(frame: int, fps: Fraction) -> FrameTimecode: +def _ntsc_pts_position(frame: int, fps: Fraction) -> FramePosition: """Position of `frame` as a PTS-exact backend (e.g. PyAV) reports it. For an NTSC rate ``num/1001`` with ``time_base = 1/num`` each frame advances exactly ``1001`` PTS units. """ - return FrameTimecode(Timecode(pts=frame * 1001, time_base=Fraction(1, fps.numerator)), fps) + return FramePosition( + timecode=Timecode(pts=frame * 1001, time_base=Fraction(1, fps.numerator)), + frame_number=frame, + ) -def _ntsc_microsecond_position(frame: int, fps: Fraction) -> FrameTimecode: +def _ntsc_microsecond_position(frame: int, fps: Fraction) -> FramePosition: """Position of `frame` as the OpenCV backend reports it, rounded to whole microseconds.""" us = round(frame * 1_000_000 / fps) - return FrameTimecode(Timecode(pts=us, time_base=Fraction(1, 1_000_000)), fps) + return FramePosition( + timecode=Timecode(pts=us, time_base=Fraction(1, 1_000_000)), + frame_number=frame, + ) @pytest.mark.parametrize("fps", NTSC_RATES) @@ -734,15 +334,14 @@ def test_flashfilter_emits_cut_every_n_frames_at_ntsc(fps: Fraction, mode: Flash emitted += flash_filter.filter( _ntsc_pts_position(frame, fps), above_threshold=frame > 0 and frame % 15 == 0 ) - assert [t.frame_num for t in emitted] == list(range(15, 300, 15)) + assert [t.frame_number for t in emitted] == list(range(15, 300, 15)) @pytest.mark.parametrize("fps", NTSC_RATES) -def test_flashfilter_keeps_exact_gap_at_ntsc(fps: Fraction): - """The exact N-frame gap must satisfy the minimum-length check at NTSC rates.""" +def test_frame_position_subtraction_preserves_ntsc_gap(fps: Fraction): + """Subtracting NTSC positions preserves the exact frame count and elapsed time.""" gap = _ntsc_pts_position(115, fps) - _ntsc_pts_position(100, fps) - assert gap.frame_num == 15 - assert gap >= 15 + assert gap == FrameDuration(frames=15, elapsed=Fraction(15) / fps) @pytest.mark.parametrize("fps", NTSC_RATES) @@ -758,16 +357,4 @@ def test_flashfilter_keeps_cuts_on_microsecond_positions(fps: Fraction, mode: Fl emitted += flash_filter.filter( _ntsc_microsecond_position(frame, fps), above_threshold=frame > 0 and frame % 17 == 0 ) - assert [t.frame_num for t in emitted] == list(range(17, 17 * 20, 17)) - - -def test_get_framerate(): - """`get_framerate()` emits one warning and preserves its legacy float return value.""" - tc = FrameTimecode(timecode=0, fps=30.0) - - with pytest.warns(DeprecationWarning, match="frame_rate") as warning_info: - frame_rate = tc.get_framerate() - - assert len(warning_info) == 1 - assert frame_rate == 30.0 - assert isinstance(frame_rate, float) + assert [t.frame_number for t in emitted] == list(range(17, 17 * 20, 17)) diff --git a/tests/test_timecode_input.py b/tests/test_timecode_input.py new file mode 100644 index 00000000..c5c39931 --- /dev/null +++ b/tests/test_timecode_input.py @@ -0,0 +1,103 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# Copyright (C) 2025 Brandon Castellano . +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +# +"""Unit-preserving frame-or-time input parsing.""" + +from fractions import Fraction + +import numpy +import pytest + +from scenedetect.common import FramePosition, Timecode, parse_frame_or_time +from scenedetect.detectors.threshold_detector import ThresholdDetector + + +@pytest.mark.parametrize( + "value, expected", + [ + (0, 0), + (15, 15), + ("15", 15), + (" 15 ", 15), + (0.0, Fraction(0)), + (15.0, Fraction(15)), + (0.6, Fraction(3, 5)), + ("15.0", Fraction(15)), + ("15s", Fraction(15)), + (" 0.6s ", Fraction(3, 5)), + (".5", Fraction(1, 2)), + ("1.", Fraction(1)), + ("00:00:00.600", Fraction(3, 5)), + ("01:02.500", Fraction(125, 2)), + ("01:23:45.678", Fraction(5025678, 1000)), + ("0.000000000000000001s", Fraction(1, 10**18)), + (Timecode(1001, Fraction(1, 24000)), Fraction(1001, 24000)), + (Timecode(1, Fraction(1)), Fraction(1)), + ], +) +def test_parse_preserves_units(value, expected): + result = parse_frame_or_time(value) + assert result == expected + assert type(result) is type(expected) + + +@pytest.mark.parametrize( + "value", + [ + -1, + -0.5, + float("inf"), + float("-inf"), + float("nan"), + "", + " ", + "-1", + "-0.5s", + "nan", + "inf", + "1/2", + "1e3", + "1.2.3", + "s", + "00:60:00", + "60:00", + "00:00:60", + "00:00:60.001", + "00::01", + "00:00:01:00", + "00:00:01s", + Timecode(-1, Fraction(1, 10)), + Timecode(1, Fraction(0)), + Timecode(1, Fraction(-1, 10)), + ], +) +def test_parse_rejects_invalid_values(value): + with pytest.raises(ValueError): + parse_frame_or_time(value) + + +@pytest.mark.parametrize("value", [True, False, None, [], Fraction(1, 2)]) +def test_parse_rejects_unsupported_types(value): + with pytest.raises(TypeError): + parse_frame_or_time(value) + + +def test_threshold_initializes_last_scene_cut(): + position = FramePosition(Timecode(0, Fraction(1, 25)), 0) + detector = ThresholdDetector() + assert detector.process_frame(position, numpy.full((2, 2, 3), 100)) == [] + assert detector.last_scene_cut == position + + +def test_threshold_post_process_without_frames(): + detector = ThresholdDetector(add_final_scene=True) + position = FramePosition(Timecode(0, Fraction(1, 25)), 0) + assert detector.post_process(position) == [] diff --git a/tests/test_video_stream.py b/tests/test_video_stream.py index fba7e966..2fb89825 100644 --- a/tests/test_video_stream.py +++ b/tests/test_video_stream.py @@ -16,9 +16,11 @@ all supported backends, and verify that they are functionally equivalent where possible. """ +import math import os.path import typing as ty from dataclasses import dataclass +from fractions import Fraction import numpy import pytest @@ -26,7 +28,8 @@ from scenedetect import open_video from scenedetect.backends import VideoStreamAv, VideoStreamMoviePy from scenedetect.backends.opencv import VideoStreamCv2 -from scenedetect.video_stream import SeekError, VideoStream +from scenedetect.common import FramePosition, Timecode +from scenedetect.video_stream import FrameNumbering, SeekError, VideoStream # Accuracy a framerate is checked to for testing purposes. FRAMERATE_TOLERANCE = 0.001 @@ -87,6 +90,7 @@ class VideoParameters: frame_rate: float total_frames: int aspect_ratio: float + duration: float # TODO: Save two "golden" frames from each video on a shot boundary, and use that to validate @@ -101,6 +105,7 @@ def get_test_video_params() -> list[VideoParameters]: frame_rate=29.97, total_frames=720, aspect_ratio=1.0, + duration=24.024, ), VideoParameters( path=get_absolute_path("resources/goldeneye.mp4"), @@ -109,6 +114,7 @@ def get_test_video_params() -> list[VideoParameters]: frame_rate=23.976, total_frames=1980, aspect_ratio=1.0, + duration=82.5825, ), VideoParameters( path=get_absolute_path("resources/issue-195-aspect-ratio.mp4"), @@ -117,6 +123,7 @@ def get_test_video_params() -> list[VideoParameters]: frame_rate=25.0, total_frames=628, aspect_ratio=1.4545454545, + duration=25.12, ), ] @@ -147,8 +154,12 @@ def test_properties( stream = auto_close(vs_type(test_video.path)) assert stream.frame_size == (test_video.width, test_video.height) assert stream.frame_rate == pytest.approx(test_video.frame_rate, FRAMERATE_TOLERANCE) - assert stream.duration is not None - assert stream.duration.frame_num == test_video.total_frames + assert isinstance(stream.duration, Fraction) + assert stream.duration == pytest.approx(test_video.duration, abs=0.01) + if vs_type is VideoStreamMoviePy: + assert stream.frame_count is None + else: + assert stream.frame_count == test_video.total_frames file_name = os.path.basename(test_video.path) last_dot_pos = file_name.rfind(".") assert stream.name == file_name[:last_dot_pos] @@ -165,7 +176,7 @@ def test_read( assert isinstance(frame, numpy.ndarray) # For now hard-code 3 channels/pixel for each test video assert frame.shape == (test_video.height, test_video.width, 3) - assert stream.frame_number == 1 + assert stream.frame_number == 0 def test_read_no_decode( self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close @@ -173,31 +184,37 @@ def test_read_no_decode( """Validate invoking `read` with `decode` set to False.""" stream = auto_close(vs_type(test_video.path)) assert stream.read(decode=False) is True - assert stream.frame_number == 1 + assert stream.frame_number == 0 def test_time_invariants( self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close ): """Validate the `frame_number`, `position`, and `position_ms` properties.""" stream = auto_close(vs_type(test_video.path)) - # The video starts "before" the first frame, with everything set to zero. - assert stream.frame_number == 0 - assert stream.position == stream.base_timecode + # No frame has been recorded yet. + assert stream.frame_number == -1 + assert stream.position is None assert stream.position_ms == pytest.approx(0.0, abs=TIME_TOLERANCE_MS) - # Read the first frame (frame number 1). + # Read the first frame (frame number 0). assert stream.read() is not False - assert stream.frame_number == 1 + assert stream.frame_number == 0 # The `position`/`position_ms` properties represent the presentation time, so they # should still be zero for the first frame. - assert stream.position == stream.base_timecode + assert isinstance(stream.position, FramePosition) + assert stream.position.frame_number == 0 + assert stream.position.timecode.seconds == 0 assert stream.position_ms == pytest.approx(0.0, abs=TIME_TOLERANCE_MS) - # Test that the invariants hold for the first few frames. - for i in range(2, 10): + # These fixtures are CFR, so their expected timestamps follow their frame rates. + for i in range(1, 10): assert stream.read() is not False assert stream.frame_number == i - assert stream.position == stream.base_timecode + (i - 1) + assert isinstance(stream.position, FramePosition) + assert stream.position.frame_number == i + assert stream.position.timecode.seconds == pytest.approx( + float(i / stream.frame_rate), abs=TIME_TOLERANCE_MS / 1000 + ) assert stream.position_ms == pytest.approx( - 1000.0 * (i - 1) / float(stream.frame_rate), abs=TIME_TOLERANCE_MS + 1000.0 * i / float(stream.frame_rate), abs=TIME_TOLERANCE_MS ) def test_reset( @@ -208,117 +225,159 @@ def test_reset( # Decode some frames, then reset the VideoStream and validate the time invariants. for _ in range(10): stream.read() - assert stream.frame_number == 10 + assert stream.frame_number == 9 + assert stream.peek_timecode() is not None stream.reset() - assert stream.frame_number == 0 - assert stream.position == 0 + assert stream.frame_number == -1 + assert stream.position is None assert stream.position_ms == pytest.approx(0, abs=TIME_TOLERANCE_MS) + assert stream.read() is not False + assert stream.frame_number == 0 + assert isinstance(stream.position, FramePosition) + assert stream.position.timecode.seconds == 0 + @pytest.mark.parametrize("frame_numbering", list(FrameNumbering)) def test_seek( - self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close + self, + vs_type: ty.Callable[..., VideoStream], + test_video: VideoParameters, + auto_close, + frame_numbering: FrameNumbering, ): """Validate `seek()` functionality with different offset types.""" - stream = auto_close(vs_type(test_video.path)) + stream = auto_close(vs_type(test_video.path, frame_numbering=frame_numbering)) + assert stream.frame_numbering is frame_numbering # Seek to a given frame number (int). stream.seek(200) - assert stream.frame_number == 200 - assert stream.position == stream.base_timecode + 199 - assert stream.position_ms == pytest.approx( - 1000.0 * (199.0 / float(stream.frame_rate)), abs=TIME_TOLERANCE_MS - ) + if frame_numbering is FrameNumbering.SOURCE: + assert stream.frame_number == 199 + assert isinstance(stream.position, FramePosition) + assert stream.position_ms == pytest.approx( + float(1000 * 199.0 / float(stream.frame_rate)), abs=TIME_TOLERANCE_MS + ) + else: + assert stream.frame_number == -1 + assert stream.position is None + assert stream.position_ms == 0.0 stream.read() - assert stream.frame_number == 201 - assert stream.position == stream.base_timecode + 200 + assert stream.frame_number == (200 if frame_numbering is FrameNumbering.SOURCE else 0) + assert isinstance(stream.position, FramePosition) + assert stream.position.timecode.seconds == pytest.approx( + float(200 / stream.frame_rate), abs=TIME_TOLERANCE_MS / 1000 + ) assert stream.position_ms == pytest.approx( 1000.0 * (200.0 / float(stream.frame_rate)), abs=TIME_TOLERANCE_MS ) - # Seek to a time in seconds (float). - stream.seek(2.0) - assert stream.frame_number == round(stream.frame_rate * 2.0) - # FrameTimecode is currently one "behind" the frame_number since it - # starts counting from zero. This should eventually be changed. - assert stream.position == (stream.base_timecode + 2.0) - 1 - assert stream.position_ms == pytest.approx( - 2000.0 - (1000.0 / stream.frame_rate), abs=1000.0 / stream.frame_rate - ) - stream.read() - assert stream.frame_number == 1 + round(stream.frame_rate * 2.0) - assert stream.position == stream.base_timecode + 2.0 - assert stream.position_ms == pytest.approx(2000.0, abs=1000.0 / stream.frame_rate) - - # Seek to a FrameTimecode. - stream.seek(stream.base_timecode + 2.0) - assert stream.frame_number == round(stream.frame_rate * 2.0) - # FrameTimecode is currently one "behind" the frame_number since it - # starts counting from zero. This should eventually be changed. - assert stream.position == (stream.base_timecode + 2.0) - 1 - assert stream.position_ms == pytest.approx( - 2000.0 - (1000.0 / stream.frame_rate), abs=1000.0 / stream.frame_rate - ) - stream.read() - assert stream.frame_number == 1 + round(stream.frame_rate * 2.0) - assert stream.position == stream.base_timecode + 2.0 - assert stream.position_ms == pytest.approx(2000.0, abs=1000.0 / stream.frame_rate) + # These CFR fixtures select the first frame at or after 2 seconds. + target_frame = math.ceil(2 * stream.frame_rate) + for target in (2.0, Timecode(pts=2, time_base=Fraction(1))): + stream.seek(target) + + if frame_numbering is FrameNumbering.SOURCE: + assert stream.frame_number == target_frame - 1 + assert isinstance(stream.position, FramePosition) + assert stream.position.timecode.seconds == pytest.approx( + float((target_frame - 1) / stream.frame_rate), + abs=TIME_TOLERANCE_MS / 1000, + ) + else: + assert stream.frame_number == -1 + assert stream.position is None + assert stream.position_ms == 0.0 + assert stream.read() is not False + assert stream.frame_number == ( + target_frame if frame_numbering is FrameNumbering.SOURCE else 0 + ) + assert isinstance(stream.position, FramePosition) + assert stream.position.timecode.seconds == pytest.approx( + float(target_frame / stream.frame_rate), + abs=TIME_TOLERANCE_MS / 1000, + ) + assert stream.position_ms == pytest.approx( + float(1000 * target_frame / stream.frame_rate), + abs=TIME_TOLERANCE_MS, + ) + + @pytest.mark.parametrize("frame_numbering", list(FrameNumbering)) def test_seek_start( - self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close + self, + vs_type: ty.Callable[..., VideoStream], + test_video: VideoParameters, + auto_close, + frame_numbering: FrameNumbering, ): """Validate behaviour of `seek()` at the start of a video.""" - stream = auto_close(vs_type(test_video.path)) + stream = auto_close(vs_type(test_video.path, frame_numbering=frame_numbering)) # Here we check similar invariants to test_time_invariants, but using seek(). - assert stream.frame_number == 0 - assert stream.position == stream.base_timecode - assert stream.position_ms == pytest.approx(0.0, abs=TIME_TOLERANCE_MS) + assert stream.frame_number == -1 + assert stream.position is None + assert stream.position_ms == 0.0 # Seeking to frame 0 (or time 0) is equivalent to seeking "before" the first frame. stream.seek(0) - assert stream.frame_number == 0 - assert stream.position == stream.base_timecode - assert stream.position_ms == pytest.approx(0.0, abs=TIME_TOLERANCE_MS) + assert stream.frame_number == -1 + assert stream.position is None + assert stream.position_ms == 0.0 # Ensure invariants hold for the first few frames. - for i in range(1, 10): + for i in range(10): assert stream.read() is not False + assert isinstance(stream.position, FramePosition) assert stream.frame_number == i - assert stream.position == stream.base_timecode + (i - 1) + assert stream.position.timecode.seconds == pytest.approx( + i / float(stream.frame_rate), abs=TIME_TOLERANCE_MS / 1000 + ) assert stream.position_ms == pytest.approx( - 1000.0 * (i - 1) / float(stream.frame_rate), abs=TIME_TOLERANCE_MS + 1000.0 * i / float(stream.frame_rate), abs=TIME_TOLERANCE_MS ) stream.seek(0) - assert stream.frame_number == 0 - assert stream.position == stream.base_timecode - assert stream.position_ms == pytest.approx(0.0, abs=TIME_TOLERANCE_MS) + assert stream.frame_number == -1 + assert stream.position is None + assert stream.position_ms == 0.0 - # Seek to the first frame (1) instead of the start (0) and verify the invariants. + # Seek to the second source frame (ordinal 1). stream.seek(1) - assert stream.frame_number == 1 - # Position and position_ms represent the presentation time, and thus are still zero. - assert stream.position == stream.base_timecode - assert stream.position_ms == pytest.approx(0.0, abs=TIME_TOLERANCE_MS) - stream.read() - assert stream.frame_number == 2 - stream = auto_close(vs_type(test_video.path)) + # SOURCE has recorded frame 0; RELATIVE has no recorded position yet. + if frame_numbering is FrameNumbering.SOURCE: + assert isinstance(stream.position, FramePosition) + assert stream.frame_number == 0 + assert stream.position.timecode.seconds == 0 + else: + assert stream.frame_number == -1 + assert stream.position is None + assert stream.read() is not False + assert isinstance(stream.position, FramePosition) + assert stream.frame_number == (1 if stream.frame_numbering is FrameNumbering.SOURCE else 0) + assert stream.position.timecode.seconds == pytest.approx( + float(1 / stream.frame_rate), abs=TIME_TOLERANCE_MS / 1000 + ) def test_read_eof( self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close ): """Ensure calling `read()` handles the end of the video correctly.""" - stream = auto_close(vs_type(test_video.path)) - # To make the test faster, we seek to the second last frame. + stream = auto_close(vs_type(test_video.path, frame_numbering=FrameNumbering.SOURCE)) + # Seek to the final expected source frame. stream.seek(test_video.total_frames - 1) while stream.read() is not False: pass # TODO: On some videos, the PyAV backend seems to drop a frame. See where this occurs. if vs_type == VideoStreamAv: - assert stream.frame_number in (test_video.total_frames, test_video.total_frames - 1) + assert stream.frame_number in (test_video.total_frames - 1, test_video.total_frames - 2) else: - assert stream.frame_number == test_video.total_frames + assert stream.frame_number == test_video.total_frames - 1 + + last_position = stream.position + assert stream.peek_timecode() is None + assert stream.read() is False + assert stream.position == last_position def test_seek_past_eof( self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close ): """Validate calling `seek()` to offset past end of video.""" - stream = auto_close(vs_type(test_video.path)) + stream = auto_close(vs_type(test_video.path, frame_numbering=FrameNumbering.SOURCE)) # Seek to a large seek offset past the end of the video. Some backends only support 32-bit # frame numbers so that's our max offset. Certain backends disallow seek offsets past EOF, # in which case they should raise a SeekError (and the test is considered a pass). @@ -331,9 +390,9 @@ def test_seek_past_eof( assert stream.read() is False # TODO: On some videos, the PyAV backend seems to drop a frame. See where this occurs. if vs_type == VideoStreamAv: - assert stream.frame_number in (test_video.total_frames, test_video.total_frames - 1) + assert stream.frame_number in (test_video.total_frames - 1, test_video.total_frames - 2) else: - assert stream.frame_number == test_video.total_frames + assert stream.frame_number == test_video.total_frames - 1 def test_seek_invalid( self, vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close @@ -411,8 +470,9 @@ def test_delayed_start_normalized( backend (the fixture has a start time of 1.075s).""" stream = auto_close(vs_type(delayed_start_video)) assert stream.read(decode=False) is not False - assert stream.position.seconds < 0.1 - assert stream.frame_number == 1 + assert stream.position is not None + assert 0 <= stream.position.timecode.seconds < Fraction(1, 10) + assert stream.frame_number == 0 # @@ -429,6 +489,7 @@ def _video_properties(stream: VideoStream) -> tuple: stream.duration, stream.frame_size, stream.aspect_ratio, + stream.frame_count, ) @@ -443,13 +504,15 @@ def test_close_is_idempotent(vs_type: ty.Callable[..., VideoStream], auto_close) def test_use_after_close(vs_type: ty.Callable[..., VideoStream], auto_close): - """`read()`, `seek()`, and `reset()` must raise `ValueError` once a stream is closed.""" + """`read()`, `peek_timecode()`, `seek()`, and `reset()` must raise after closing.""" stream = auto_close(vs_type(get_absolute_path("resources/testvideo.mp4"))) stream.close() with pytest.raises(ValueError): stream.read() with pytest.raises(ValueError): stream.read(decode=False) + with pytest.raises(ValueError): + stream.peek_timecode() with pytest.raises(ValueError): stream.seek(10) with pytest.raises(ValueError): @@ -484,3 +547,25 @@ def test_context_manager_closes_on_error(vs_type: ty.Callable[..., VideoStream], raise RuntimeError("raised in with block") with pytest.raises(ValueError): stream.read() + + +@pytest.mark.parametrize("test_video", get_test_video_params()) +def test_peek_timecode( + vs_type: ty.Callable[..., VideoStream], test_video: VideoParameters, auto_close +): + """Peeking retains the next frame without changing the recorded position.""" + stream = auto_close(vs_type(test_video.path)) + + for frame_number in range(3): + previous_position = stream.position + timecode = stream.peek_timecode() + + assert isinstance(timecode, Timecode) + assert stream.peek_timecode() == timecode + assert stream.position == previous_position + assert stream.frame_number == frame_number - 1 + + assert stream.read(decode=False) is True + assert stream.frame_number == frame_number + assert stream.position is not None + assert stream.position.timecode == timecode