diff --git a/docs/api.rst b/docs/api.rst index 2e199af4..f8cfc5a3 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -19,6 +19,8 @@ The ``scenedetect`` API integrates into Python applications and supports custom * :class:`HistogramDetector `: finds fast cuts using Y-channel (brightness) histogram changes in YUV + * :class:`SolidColorDetector `: reports the start and end of solid-color intervals + * :class:`ThresholdDetector `: finds fades in and out using average RGB pixel brightness * :doc:`api/output`: output helpers: diff --git a/docs/api/detectors.rst b/docs/api/detectors.rst index cf6bd10d..1c551e55 100644 --- a/docs/api/detectors.rst +++ b/docs/api/detectors.rst @@ -7,7 +7,7 @@ Detectors .. automodule:: scenedetect.detectors -.. seealso:: Each detector is also available as a ``detect-*`` command; see the ``detect-*`` commands in the :ref:`CLI reference `. The :option:`-m/--min-scene-len ` option sets ``min_scene_len`` for every detector. +.. seealso:: Scene cut detectors are available as ``detect-*`` commands in the :ref:`CLI reference `. The :option:`-m/--min-scene-len ` option sets their minimum scene length. Use :ref:`list-solid ` to locate runs of solid-color frames. .. note:: @@ -72,6 +72,37 @@ HistogramDetector .. autoclass:: scenedetect.detectors.histogram_detector.HistogramDetector :members: +SolidColorDetector +------------------ + +.. seealso:: **Command Line:** :ref:`list-solid ` | **Config File:** :ref:`[list-solid] ` + +For example, to find solid-color sections lasting at least five frames: + +.. code-block:: python + + from scenedetect import SceneManager, open_video + from scenedetect.detectors import SolidColorDetector + + detector = SolidColorDetector(min_frames=5) + manager = SceneManager() + manager.add_detector(detector) + with open_video("recording.mp4") as video: + manager.detect_scenes(video=video) + for start, end in detector.get_intervals(): + print(start.get_timecode(), end.get_timecode(), (end - start).seconds) + +The end time is exclusive. Adjacent solid frames belong to the same interval even +if their colors differ. Use a lower threshold to distinguish low-contrast detail +from a blank screen. To preserve fine detail during analysis, set +``manager.auto_downscale = False`` and ``manager.downscale = 1`` before detection. +On variable-frame-rate input, use timecodes for boundaries. The scene CSV's frame +numbers use the nominal frame rate. A run ending at the last observed frame uses +one nominal frame duration to estimate its exclusive end. + +.. autoclass:: scenedetect.detectors.solid_color_detector.SolidColorDetector + :members: + ThresholdDetector ----------------- diff --git a/docs/cli.rst b/docs/cli.rst index 73906e30..fd22e155 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -552,6 +552,53 @@ Options Skip cutting list as first row in the CSV file. Set for RFC 4180 compliant output. +.. _command-list-solid: + +.. program:: scenedetect list-solid + + +``list-solid`` +------------------------------------------------------------------------ + + +.. seealso:: **Python API:** :class:`~scenedetect.detectors.solid_color_detector.SolidColorDetector` | **Config File:** :ref:`[list-solid] ` + +Save solid-color frame intervals to CSV without changing scene cuts. + + ``Intervals use the standard scene CSV columns and source-video timecodes. Combine with`` + ``scene output commands to generate both reports in one detection pass.`` + + ``Classification uses frames after global cropping and resizing. Use --downscale 1 before`` + ``this command to preserve small image details that downscaling can remove.`` + + +Options +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + +.. option:: -f NAME, --filename NAME + + Filename format to use. Supports $VIDEO_NAME. + + Default: ``$VIDEO_NAME-Solid.csv`` + +.. option:: -o DIR, --output DIR + + Output directory. Overrides global :option:`-o/--output <-o>`. + +.. option:: --threshold + + Maximum per-channel spatial standard deviation for a solid-color frame. + + Default: ``2.0`` + +.. option:: --min-frames + + Minimum number of consecutive solid-color frames to report. + + Default: ``2`` + + .. _command-load-scenes: .. program:: scenedetect load-scenes diff --git a/docs/cli/config_sections.inc b/docs/cli/config_sections.inc index b8b4710e..87b3eb5b 100644 --- a/docs/cli/config_sections.inc +++ b/docs/cli/config_sections.inc @@ -439,6 +439,47 @@ Options of :ref:`list-scenes ` (Python API: :func:`~scenede # Overrides `display-scenes` and `display-cuts`. #quiet = no +.. _config-list-solid: + +[list-solid] +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Options of :ref:`list-solid ` (Python API: :class:`~scenedetect.detectors.solid_color_detector.SolidColorDetector`). + +.. list-table:: + :class: config-keys + :header-rows: 1 + :widths: 28 32 40 + + * - Key + - Default + - CLI option + * - ``threshold`` + - ``2.0`` + - :option:`--threshold ` + * - ``min-frames`` + - ``2`` + - :option:`--min-frames ` + * - ``filename`` + - ``$VIDEO_NAME-Solid.csv`` + - :option:`-f/--filename ` + * - ``output`` + - *none* + - :option:`-o/--output ` + +.. code-block:: ini + + [list-solid] + # Maximum standard deviation in each color channel, in 8-bit pixel values. + #threshold = 2.0 + + # Ignore runs shorter than this many consecutive frames. + #min-frames = 2 + + # CSV filename and folder. The folder defaults to the global output directory. + #filename = $VIDEO_NAME-Solid.csv + #output = /usr/tmp/reports + .. _config-load-scenes: [load-scenes] diff --git a/docs/cli_index.inc b/docs/cli_index.inc index 07dee69b..559cb38f 100644 --- a/docs/cli_index.inc +++ b/docs/cli_index.inc @@ -27,6 +27,7 @@ - **Scene Lists & Exports** - :ref:`list-scenes ` + - :ref:`list-solid ` - :ref:`save-html ` - :ref:`save-edl ` - :ref:`save-fcp ` diff --git a/docs/generate_cli_docs.py b/docs/generate_cli_docs.py index 4e512530..1bedcb0c 100644 --- a/docs/generate_cli_docs.py +++ b/docs/generate_cli_docs.py @@ -193,6 +193,11 @@ class Counterpart: command="list-scenes", api=(f":func:`~{_OUT}.write_scene_list`",), ), + Counterpart( + "Solid-color intervals (CSV)", + command="list-solid", + api=(f":class:`~{_DET}.solid_color_detector.SolidColorDetector`",), + ), Counterpart( "Scene list (HTML)", command="save-html", @@ -824,6 +829,7 @@ def create_help(ctx: click.Context, commands: list[str]) -> str: "Scene Lists & Exports", ( "list-scenes", + "list-solid", "save-html", "save-edl", "save-fcp", diff --git a/scenedetect.cfg b/scenedetect.cfg index 58d2b3cc..11569072 100644 --- a/scenedetect.cfg +++ b/scenedetect.cfg @@ -312,6 +312,18 @@ #quiet = no +[list-solid] +# Maximum standard deviation in each color channel, in 8-bit pixel values. +#threshold = 2.0 + +# Ignore runs shorter than this many consecutive frames. +#min-frames = 2 + +# CSV filename and folder. The folder defaults to the global output directory. +#filename = $VIDEO_NAME-Solid.csv +#output = /usr/tmp/reports + + [load-scenes] # Name of column used to mark scene cut points. #start-col-name = Start Frame diff --git a/scenedetect/_cli/__init__.py b/scenedetect/_cli/__init__.py index ee29c9f2..44061b4b 100644 --- a/scenedetect/_cli/__init__.py +++ b/scenedetect/_cli/__init__.py @@ -45,6 +45,7 @@ ContentDetector, HashDetector, HistogramDetector, + SolidColorDetector, ThresholdDetector, ) from scenedetect.platform import get_cv2_imwrite_params, get_system_version_info @@ -1022,6 +1023,8 @@ def load_scenes_command(ctx: click.Context, input: str | None, start_col_name: s assert isinstance(ctx, CliContext) check_not_stdin(ctx, "load-scenes") + if ctx.solid_detector is not None: + raise click.ClickException("The list-solid command cannot be used with load-scenes.") logger.debug("Will load scenes from %s (start_col_name = %s)", input, start_col_name) assert ctx.scene_manager is not None if ctx.scene_manager.get_num_detectors() > 0: @@ -1142,6 +1145,85 @@ def save_html_command( """ +@click.command("list-solid", cls=Command) +@click.option( + "--filename", + "-f", + metavar="NAME", + type=click.STRING, + default=None, + help="Filename format to use. Supports $VIDEO_NAME.{}".format( + USER_CONFIG.get_help_string("list-solid", "filename") + ), +) +@click.option( + "--output", + "-o", + metavar="DIR", + type=click.Path(exists=False, dir_okay=True, writable=True, resolve_path=False), + help="Output directory. Overrides global -o/--output.{}".format( + USER_CONFIG.get_help_string("list-solid", "output", show_default=False) + ), +) +@click.option( + "--threshold", + type=_click_range("list-solid", "threshold"), + default=None, + help="Maximum per-channel spatial standard deviation for a solid-color frame.{}".format( + USER_CONFIG.get_help_string("list-solid", "threshold") + ), +) +@click.option( + "--min-frames", + type=_click_range("list-solid", "min-frames"), + default=None, + help="Minimum number of consecutive solid-color frames to report.{}".format( + USER_CONFIG.get_help_string("list-solid", "min-frames") + ), +) +@click.pass_context +def list_solid_command( + ctx: click.Context, + filename: str | None, + output: str | None, + threshold: float | None, + min_frames: int | None, +): + """Save solid-color frame intervals to CSV without changing scene cuts. + + Intervals use the standard scene CSV columns and source-video timecodes. Combine with + scene output commands to generate both reports in one detection pass. + + Classification uses frames after global cropping and resizing. Use --downscale 1 before + this command to preserve small image details that downscaling can remove. + """ + ctx = ctx.obj + assert isinstance(ctx, CliContext) + if ctx.solid_detector is not None: + raise click.ClickException("The list-solid command must only be specified once.") + if ctx.load_scenes_input: + raise click.ClickException("The list-solid command cannot be used with load-scenes.") + if ctx.frame_skip: + raise click.ClickException("The list-solid command cannot be used with --frame-skip.") + assert ctx.scene_manager is not None + try: + ctx.solid_detector = SolidColorDetector( + threshold=ctx.config.get_value("list-solid", "threshold", threshold), + min_frames=ctx.config.get_value("list-solid", "min-frames", min_frames), + ) + except ValueError as ex: + raise click.BadParameter(str(ex), param_hint="list-solid") from ex + ctx.scene_manager.add_detector(ctx.solid_detector) + ctx.add_command( + cli_commands.list_solid, + { + "filename": ctx.config.get_value("list-solid", "filename", filename), + "output": ctx.config.get_value("list-solid", "output", output), + }, + requires_scenes=False, + ) + + @click.command("list-scenes", cls=Command, help=LIST_SCENES_HELP) @click.option( "--output", @@ -2082,6 +2164,7 @@ def save_otio_command( # Output scenedetect.add_command(list_scenes_command) +scenedetect.add_command(list_solid_command) scenedetect.add_command(save_chapters_command) scenedetect.add_command(save_edl_command) scenedetect.add_command(save_html_command) diff --git a/scenedetect/_cli/commands.py b/scenedetect/_cli/commands.py index 1576b4cd..3b8ad676 100644 --- a/scenedetect/_cli/commands.py +++ b/scenedetect/_cli/commands.py @@ -126,6 +126,30 @@ def save_keyframes( logger.info(f"Keyframes written to: {keyframes_path}") +def list_solid( + context: CliContext, + scenes: SceneList, + cuts: CutList, + filename: str, + output: str | None, +): + """Write solid-color intervals using the standard scene CSV columns.""" + del scenes, cuts + assert context.video_stream is not None + assert context.solid_detector is not None + filename = Template(filename).safe_substitute(VIDEO_NAME=context.video_stream.name) + if not filename.lower().endswith(".csv"): + filename += ".csv" + path = get_and_create_path(filename, output) + logger.info("Writing solid-color intervals to CSV file:\n %s", path) + with open(path, "w", newline="") as report: + write_scene_list( + output_csv_file=report, + scene_list=context.solid_detector.get_intervals(), + include_cut_list=False, + ) + + def list_scenes( context: CliContext, scenes: SceneList, diff --git a/scenedetect/_cli/config.py b/scenedetect/_cli/config.py index 6dea3251..2d4da759 100644 --- a/scenedetect/_cli/config.py +++ b/scenedetect/_cli/config.py @@ -427,6 +427,12 @@ def default_to_str(value: ConfigValue) -> str: "load-scenes": { "start-col-name": "Start Frame", }, + "list-solid": { + "filename": "$VIDEO_NAME-Solid.csv", + "output": None, + "threshold": RangeValue(2.0, min_val=0.0, max_val=127.5), + "min-frames": RangeValue(2, min_val=1, max_val=None), + }, "list-scenes": { "cut-format": TimecodeFormat.TIMECODE, "col-separator": EscapedChar(","), diff --git a/scenedetect/_cli/context.py b/scenedetect/_cli/context.py index 266f3658..a166cdfd 100644 --- a/scenedetect/_cli/context.py +++ b/scenedetect/_cli/context.py @@ -35,6 +35,7 @@ ContentDetector, HashDetector, HistogramDetector, + SolidColorDetector, ThresholdDetector, ) from scenedetect.output import is_ffmpeg_available, is_mkvmerge_available @@ -105,6 +106,8 @@ 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 + self.solid_detector: SolidColorDetector | None = None + self.requires_scene_detection: bool = False # Input: self.video_stream: VideoStream | None = None @@ -129,12 +132,18 @@ def __init__(self): # the results of the detection pipeline by the controller. self.commands: list[tuple[ty.Callable, dict[str, ty.Any]]] = [] - def add_command(self, command: ty.Callable, command_args: dict[str, ty.Any]): + def add_command( + self, + command: ty.Callable, + command_args: dict[str, ty.Any], + requires_scenes: bool = True, + ): """Add `command` to the processing pipeline. Will be called after processing the input.""" if "output" in command_args and command_args["output"] is None: command_args["output"] = self.output logger.debug("Adding command: %s(%s)", command.__name__, command_args) self.commands.append((command, command_args)) + self.requires_scene_detection |= requires_scenes def add_detector(self, detector: type[SceneDetector], detector_args: dict[str, ty.Any]): """Instantiate and add `detector` to the processing pipeline.""" @@ -145,10 +154,17 @@ def add_detector(self, detector: type[SceneDetector], detector_args: dict[str, t self.scene_manager.add_detector(detector(**detector_args)) def ensure_detector(self): - """Ensures at least one detector has been instantiated, otherwise adds a default one.""" + """Add the default cut detector when scene detection is required.""" assert self.scene_manager is not None assert self.default_detector is not None - if self.scene_manager.get_num_detectors() == 0: + # The solid-color observer never emits cuts and must not suppress implicit scene + # detection for other commands. Resolve this after all commands have been registered. + num_cut_detectors = self.scene_manager.get_num_detectors() - int( + self.solid_detector is not None + ) + if num_cut_detectors == 0 and ( + self.solid_detector is None or self.requires_scene_detection or self.stats_file_path + ): logger.debug("No detector specified, adding default detector.") (detector_type, detector_args) = self.default_detector self.add_detector(detector_type, detector_args) diff --git a/scenedetect/_cli/controller.py b/scenedetect/_cli/controller.py index 329d5685..97664695 100644 --- a/scenedetect/_cli/controller.py +++ b/scenedetect/_cli/controller.py @@ -66,7 +66,11 @@ def run_scenedetect(context: CliContext) -> bool: scenes = _postprocess_scene_list(context, scenes) # Handle -s/--stats option. _save_stats(context) - if scenes: + if context.solid_detector is not None and context.scene_manager.get_num_detectors() == 1: + logger.info( + "Solid-color intervals found: %d", len(context.solid_detector.get_intervals()) + ) + elif scenes: logger.info( "Detected %d scenes, average shot length %.1f seconds.", len(scenes), diff --git a/scenedetect/detectors/__init__.py b/scenedetect/detectors/__init__.py index 16238025..fd60d8ec 100644 --- a/scenedetect/detectors/__init__.py +++ b/scenedetect/detectors/__init__.py @@ -29,6 +29,9 @@ * :mod:`HashDetector `: Uses perceptual hashing to calculate similarity between adjacent frames. + * :mod:`SolidColorDetector `: + Observes intervals of solid-color frames without emitting scene cuts. + Detection algorithms are created by implementing the :class:`SceneDetector ` interface. Detectors are typically attached to a :class:`SceneManager ` when @@ -40,6 +43,7 @@ from scenedetect.detectors.adaptive_detector import AdaptiveDetector as AdaptiveDetector from scenedetect.detectors.hash_detector import HashDetector as HashDetector from scenedetect.detectors.histogram_detector import HistogramDetector as HistogramDetector +from scenedetect.detectors.solid_color_detector import SolidColorDetector as SolidColorDetector # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # diff --git a/scenedetect/detectors/solid_color_detector.py b/scenedetect/detectors/solid_color_detector.py new file mode 100644 index 00000000..4a52ff2b --- /dev/null +++ b/scenedetect/detectors/solid_color_detector.py @@ -0,0 +1,116 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +# +"""Observe intervals of spatially uniform frames without emitting scene cuts.""" + +from numbers import Integral, Real + +import cv2 +import numpy + +from scenedetect.common import FrameTimecode +from scenedetect.detector import SceneDetector + + +class SolidColorDetector(SceneDetector): + """Collect intervals in which every frame is approximately a solid color. + + Each BGR channel's spatial standard deviation is calculated independently. A frame is solid + when the largest deviation is at most ``threshold``; the color itself can change between + frames within an interval. This detector never emits scene cuts, so it can observe the same + frames as another detector attached to a :class:`~scenedetect.scene_manager.SceneManager`. + Retrieve completed intervals with :meth:`get_intervals` after processing finishes. + """ + + def __init__(self, threshold: float = 2.0, min_frames: int = 2): + """ + Arguments: + threshold: Maximum spatial standard deviation allowed in each 8-bit BGR channel, + inclusive. Must be finite and between 0 and 127.5. Zero requires exact uniformity. + min_frames: Minimum number of observed solid frames required for an interval. Must + be a positive integer. Counts processed frames, even when frame skipping is used. + + Raises: + ValueError: An argument is outside its allowed range or has an invalid type. + """ + super().__init__() + if ( + isinstance(threshold, bool) + or not isinstance(threshold, Real) + or not 0 <= threshold <= 127.5 + ): + raise ValueError("threshold must be a finite number between 0 and 127.5.") + if isinstance(min_frames, bool) or not isinstance(min_frames, Integral) or min_frames < 1: + raise ValueError("min_frames must be a positive integer.") + self._threshold = float(threshold) + self._min_frames = int(min_frames) + self._intervals: list[tuple[FrameTimecode, FrameTimecode]] = [] + self._start: FrameTimecode | None = None + self._last_solid: FrameTimecode | None = None + self._solid_frames = 0 + + def process_frame( + self, timecode: FrameTimecode, frame_img: numpy.ndarray + ) -> list[FrameTimecode]: + """Observe a sequential BGR frame. + + Arguments: + timecode: Timecode corresponding to the frame being processed. + frame_img: Video frame as a 24-bit BGR image. + + Returns: + An empty list; this detector never emits scene cuts. + """ + if self._threshold == 0.0: + # meanStdDev can report tiny nonzero deviations for exactly uniform images. + is_solid = bool((frame_img == frame_img[0, 0]).all()) + else: + _, deviation = cv2.meanStdDev(frame_img) + is_solid = float(deviation.max()) <= self._threshold + if is_solid: + if self._start is None: + self._start = FrameTimecode(timecode) + self._last_solid = FrameTimecode(timecode) + self._solid_frames += 1 + else: + self._finish_interval(timecode) + return [] + + def post_process(self, timecode: FrameTimecode) -> list[FrameTimecode]: + """Close a trailing interval one frame after the last processed frame. + + Arguments: + timecode: Timecode of the last frame processed. + + Returns: + An empty list; this detector never emits scene cuts. + """ + # If detection stops early, the decoder can be ahead of the last observed frame. + if self._last_solid is not None: + self._finish_interval(self._last_solid + 1) + return [] + + def get_intervals(self) -> list[tuple[FrameTimecode, FrameTimecode]]: + """Return completed intervals in chronological order as ``(start, exclusive_end)`` pairs. + + A pending trailing interval is included only after :meth:`post_process` is called. + Returned lists and timecodes can be modified without changing detector state. + + Returns: + Completed ``(start, exclusive_end)`` timecode pairs in chronological order. + """ + return [(FrameTimecode(start), FrameTimecode(end)) for start, end in self._intervals] + + def _finish_interval(self, end: FrameTimecode) -> None: + if self._start is not None and self._solid_frames >= self._min_frames: + self._intervals.append((self._start, FrameTimecode(end))) + self._start = None + self._last_solid = None + self._solid_frames = 0 diff --git a/scenedetect/scene_manager.py b/scenedetect/scene_manager.py index aaec6a2d..330f7141 100644 --- a/scenedetect/scene_manager.py +++ b/scenedetect/scene_manager.py @@ -424,7 +424,7 @@ def _process_frame( for detector in self._detector_list: cuts = detector.process_frame(position, frame_im) self._cutting_list += cuts - new_cuts = bool(cuts) + new_cuts |= bool(cuts) if callback: for cut in cuts: for position, frame in self._frame_buffer: diff --git a/tests/test_cli_list_solid.py b/tests/test_cli_list_solid.py new file mode 100644 index 00000000..9b594aa0 --- /dev/null +++ b/tests/test_cli_list_solid.py @@ -0,0 +1,228 @@ +"""CLI regression tests for the solid-color interval report.""" + +import csv +from pathlib import Path + +import cv2 +import numpy as np +import pytest +from click.testing import CliRunner + +import scenedetect._cli as cli +from scenedetect._cli import commands +from scenedetect._cli.context import CliContext +from scenedetect._cli.controller import run_scenedetect +from tests.helpers import invoke_cli + + +@pytest.fixture +def solid_video(tmp_path: Path) -> Path: + path = tmp_path / "solid.avi" + writer = cv2.VideoWriter(str(path), cv2.VideoWriter.fourcc(*"MJPG"), 10.0, (32, 32)) + assert writer.isOpened() + texture = np.zeros((32, 32, 3), dtype=np.uint8) + texture[:, 16:] = 255 + try: + # Two solid runs, including a color change within one run and a trailing run. + for frame, count in [ + (np.zeros_like(texture), 3), + (np.full_like(texture, 255), 2), + (texture, 15), + (255 - texture, 15), + (np.full_like(texture, 64), 4), + ]: + for _ in range(count): + writer.write(frame) + finally: + writer.release() + return path + + +def _args(video: Path, output: Path) -> list[str]: + return ["-c", "scenedetect.cfg", "-i", str(video), "-o", str(output), "-q"] + + +def _rows(path: Path) -> list[dict[str, str]]: + with path.open(newline="") as report: + return list(csv.DictReader(report)) + + +def test_list_solid_csv(solid_video: Path, tmp_path: Path): + exit_code, output = invoke_cli([*_args(solid_video, tmp_path), "list-solid"]) + assert exit_code == 0, output + path = tmp_path / "solid-Solid.csv" + assert path.read_text().splitlines()[0].startswith("Scene Number,Start Frame,") + assert [(r["Start Frame"], r["End Frame"], r["Length (frames)"]) for r in _rows(path)] == [ + ("1", "5", "5"), + ("36", "39", "4"), + ] + + +def test_list_solid_empty_and_output_override(solid_video: Path, tmp_path: Path): + destination = tmp_path / "report" + exit_code, output = invoke_cli( + [ + *_args(solid_video, tmp_path), + "list-solid", + "--min-frames", + "100", + "-o", + str(destination), + "-f", + "$VIDEO_NAME-empty", + ] + ) + assert exit_code == 0, output + path = destination / "solid-empty.csv" + assert len(path.read_text().splitlines()) == 1 + assert _rows(path) == [] + + +def test_list_solid_uses_config_and_source_timecodes(solid_video: Path, tmp_path: Path): + config = tmp_path / "custom.cfg" + config.write_text("[list-solid]\nfilename = configured\nmin-frames = 3\nthreshold = 0\n") + exit_code, output = invoke_cli( + [ + "-c", + str(config), + "-i", + str(solid_video), + "-o", + str(tmp_path), + "-q", + "time", + "--start", + "2", + "--end", + "38", + "list-solid", + ] + ) + assert exit_code == 0, output + assert [(r["Start Frame"], r["End Frame"]) for r in _rows(tmp_path / "configured.csv")] == [ + ("2", "5"), + ("36", "38"), + ] + + +@pytest.mark.parametrize("report_first", [False, True]) +def test_list_solid_preserves_implicit_scenes( + solid_video: Path, tmp_path: Path, report_first: bool +): + baseline = tmp_path / "baseline" + assert invoke_cli([*_args(solid_video, baseline), "list-scenes"])[0] == 0 + scene_command = ["list-scenes"] + report_command = ["list-solid"] + command = report_command + scene_command if report_first else scene_command + report_command + exit_code, output = invoke_cli([*_args(solid_video, tmp_path), *command]) + assert exit_code == 0, output + expected = (baseline / "solid-Scenes.csv").read_text() + assert len(expected.splitlines()) > 3 # The baseline actually contains a cut. + assert (tmp_path / "solid-Scenes.csv").read_text() == expected + + +@pytest.mark.parametrize("scene_command", [None, "list-scenes", "split-video"]) +@pytest.mark.parametrize("report_first", [False, True]) +def test_list_solid_detector_selection_and_single_pass( + solid_video: Path, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + scene_command: str | None, + report_first: bool, +): + # Avoid invoking an external encoder while checking split-video's implicit detector. + monkeypatch.setattr(cli, "check_split_video_requirements", lambda **kwargs: None) + split_scenes = [] + monkeypatch.setattr( + commands, "split_video", lambda **kwargs: split_scenes.extend(kwargs["scenes"]) + ) + context = CliContext() + command = ["list-solid"] + if scene_command: + command = [*command, scene_command] if report_first else [scene_command, *command] + try: + result = CliRunner().invoke( + cli.scenedetect, [*_args(solid_video, tmp_path), *command], obj=context + ) + assert result.exit_code == 0, result.output + manager = context.scene_manager + assert manager is not None + original_detect = manager.detect_scenes + calls = [] + + def detect_once(**kwargs): + calls.append(kwargs) + return original_detect(**kwargs) + + monkeypatch.setattr(manager, "detect_scenes", detect_once) + assert run_scenedetect(context) + assert len(calls) == 1 + assert manager.get_num_detectors() == (2 if scene_command else 1) + if scene_command == "split-video": + assert len(split_scenes) > 1 + finally: + if context.video_stream: + context.video_stream.close() + + +@pytest.mark.parametrize("report_first", [False, True]) +def test_list_solid_rejects_load_scenes(solid_video: Path, tmp_path: Path, report_first: bool): + loaded = tmp_path / "scenes.csv" + loaded.write_text("Start Frame\n1\n") + load_command = ["load-scenes", "-i", str(loaded)] + command = ["list-solid", *load_command] if report_first else [*load_command, "list-solid"] + exit_code, output = invoke_cli([*_args(solid_video, tmp_path), *command]) + assert exit_code != 0 + assert "list-solid" in output and "load-scenes" in output + + +@pytest.mark.parametrize("report_first", [False, True]) +def test_list_solid_rejects_frame_skip(solid_video: Path, tmp_path: Path, report_first: bool): + command = ["list-solid", "list-scenes"] if report_first else ["list-scenes", "list-solid"] + exit_code, output = invoke_cli([*_args(solid_video, tmp_path), "--frame-skip", "1", *command]) + assert exit_code != 0 + assert "list-solid" in output and "--frame-skip" in output + + +@pytest.mark.parametrize( + "option,value", + [("--threshold", "-1"), ("--threshold", "128"), ("--threshold", "nan"), ("--min-frames", "0")], +) +def test_list_solid_rejects_invalid_options( + solid_video: Path, tmp_path: Path, option: str, value: str +): + exit_code, output = invoke_cli([*_args(solid_video, tmp_path), "list-solid", option, value]) + assert exit_code != 0 + assert "Invalid value" in output + + +@pytest.mark.parametrize( + "config,expected_error", + [ + ("[list-solid]\nthreshold = nan\n", "finite"), + ("[global]\nframe-skip = 1\n", "--frame-skip"), + ], +) +def test_list_solid_rejects_invalid_config( + solid_video: Path, tmp_path: Path, config: str, expected_error: str +): + config_path = tmp_path / "invalid.cfg" + config_path.write_text(config) + exit_code, output = invoke_cli( + ["-c", str(config_path), "-i", str(solid_video), "-q", "list-solid"] + ) + assert exit_code != 0 + assert expected_error in output + + +def test_list_solid_preserves_implicit_stats(solid_video: Path, tmp_path: Path): + baseline = tmp_path / "baseline" + baseline.mkdir() + baseline_stats = baseline / "stats.csv" + report_stats = tmp_path / "stats.csv" + assert invoke_cli([*_args(solid_video, baseline), "-s", str(baseline_stats)])[0] == 0 + exit_code, output = invoke_cli( + [*_args(solid_video, tmp_path), "-s", str(report_stats), "list-solid"] + ) + assert exit_code == 0, output + assert report_stats.read_text() == baseline_stats.read_text() diff --git a/tests/test_solid_color_detector.py b/tests/test_solid_color_detector.py new file mode 100644 index 00000000..1fa6d8b2 --- /dev/null +++ b/tests/test_solid_color_detector.py @@ -0,0 +1,144 @@ +# +# PySceneDetect: Python-Based Video Scene Detector +# ------------------------------------------------------------------- +# [ Site: https://scenedetect.com ] +# [ Docs: https://scenedetect.com/docs/ ] +# [ Github: https://github.com/Breakthrough/PySceneDetect/ ] +# +# PySceneDetect is licensed under the BSD 3-Clause License; see the +# included LICENSE file, or visit one of the above pages for details. +# +"""Solid-color interval detection using synthetic BGR frames.""" + +import numpy as np +import pytest + +from scenedetect import FrameTimecode +from scenedetect.detector import SceneDetector +from scenedetect.detectors import SolidColorDetector + + +def _solid(color=(0, 0, 0)): + return np.full((4, 4, 3), color, dtype=np.uint8) + + +def _detail(): + image = _solid() + image[::2] = 255 + return image + + +def _intervals(detector): + intervals = detector.get_intervals() + assert all(isinstance(tc, FrameTimecode) for pair in intervals for tc in pair) + return [(start.frame_num, end.frame_num) for start, end in intervals] + + +def _detect(frames, *, start=0, step=1, **kwargs): + detector = SolidColorDetector(**kwargs) + assert isinstance(detector, SceneDetector) + timecode = FrameTimecode(start, fps=24.0) + for index, frame in enumerate(frames): + timecode = FrameTimecode(start + index * step, fps=24.0) + assert detector.process_frame(timecode, frame) == [] + assert detector.post_process(timecode) == [] + return detector + + +@pytest.mark.parametrize( + "solid_flags, expected", + [ + ([], []), + ([False] * 4, []), + ([True] * 4, [(0, 4)]), + ([True, True, False, False], [(0, 2)]), + ([False, False, True, True], [(2, 4)]), + ([False, True, True, False], [(1, 3)]), + ([True, True, False, True, True, False, True, True], [(0, 2), (3, 5), (6, 8)]), + ([True, False, True], []), + ], +) +def test_interval_boundaries(solid_flags, expected): + assert ( + _intervals(_detect([_solid() if solid else _detail() for solid in solid_flags])) == expected + ) + + +def test_any_color_and_color_changes_form_one_run(): + colors = [(0, 0, 0), (255, 255, 255), (0, 0, 255), (0, 255, 0), (255, 0, 0), (23, 81, 170)] + assert _intervals(_detect([_solid(color) for color in colors], threshold=0)) == [(0, 6)] + + +@pytest.mark.parametrize("channel", [0, 1, 2]) +def test_zero_threshold_requires_exact_uniformity_on_large_odd_size_frame(channel): + frame = np.full((1919, 1079, 3), (21, 123, 253), dtype=np.uint8) + assert _intervals(_detect([frame, frame], threshold=0)) == [(0, 2)] + frame[-1, -1, channel] += 1 + assert _intervals(_detect([frame, frame], threshold=0)) == [] + + +@pytest.mark.parametrize("length, expected", [(1, []), (2, [(0, 2)]), (3, [(0, 3)])]) +@pytest.mark.parametrize("trailing", [False, True]) +def test_min_frames_boundary(length, expected, trailing): + frames = [_solid()] * length + if not trailing: + frames.append(_detail()) + assert _intervals(_detect(frames)) == expected + + +def test_minimum_one_keeps_single_frame_runs(): + assert _intervals(_detect([_solid(), _detail(), _solid()], min_frames=1)) == [(0, 1), (2, 3)] + + +def test_min_frames_counts_observations_instead_of_elapsed_frames(): + assert _intervals(_detect([_solid(), _solid()], step=5, min_frames=3)) == [] + assert _intervals(_detect([_solid(), _solid()], start=10, step=5)) == [(10, 16)] + + +@pytest.mark.parametrize("channel", [0, 1, 2]) +@pytest.mark.parametrize("threshold, expected", [(0.0, []), (1.999, []), (2.0, [(0, 2)])]) +def test_inclusive_threshold_uses_maximum_channel_deviation(channel, threshold, expected): + # Half the pixels differ by four in just one channel: its population stddev is exactly two. + frame = _solid((100, 100, 100)) + frame[::2, :, channel] = 104 + assert _intervals(_detect([frame, frame], threshold=threshold)) == expected + + +def test_upper_threshold_boundary(): + assert _intervals(_detect([_detail(), _detail()], threshold=127.5)) == [(0, 2)] + + +@pytest.mark.parametrize( + "threshold", + [-0.01, 127.51, 10**400, float("nan"), float("inf"), -float("inf"), None, "2", True], +) +def test_invalid_threshold_rejected(threshold): + with pytest.raises(ValueError, match="threshold"): + SolidColorDetector(threshold=threshold) + + +@pytest.mark.parametrize("minimum", [0, -1, 1.5, 2.0, True, None, "2", float("inf")]) +def test_invalid_min_frames_rejected(minimum): + with pytest.raises(ValueError, match="min_frames"): + SolidColorDetector(min_frames=minimum) + + +def test_pending_interval_and_repeated_flush(): + detector = SolidColorDetector() + for index in (10, 11): + assert detector.process_frame(FrameTimecode(index, fps=24.0), _solid()) == [] + assert detector.get_intervals() == [] + # On an early stop, the decoder can have read ahead of the detector. + assert detector.post_process(FrameTimecode(15, fps=24.0)) == [] + assert _intervals(detector) == [(10, 12)] + assert detector.post_process(FrameTimecode(11, fps=24.0)) == [] + assert _intervals(detector) == [(10, 12)] + + +def test_intervals_are_independent_snapshots(): + detector = _detect([_solid(), _solid()]) + result = detector.get_intervals() + start = result[0][0] + start += 1 + result.clear() + assert _intervals(detector) == [(0, 2)]