Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ Options

[REQUIRED] Input video file. Image sequences and URLs are supported.

.. option:: --stdin

Read the input video from standard input instead of :option:`-i/--input <-i>`. Requires the pyav backend. An MP4 needs its index at the start of the file (ffmpeg -movflags +faststart), otherwise remux to MKV or MPEG-TS. Commands that need to seek in the video are not supported.

.. option:: -o DIR, --output DIR

Output directory for created files. If unset, working directory will be used. May be overridden by command options.
Expand Down Expand Up @@ -132,6 +136,9 @@ Global options, their config file keys, and their Python API counterparts.
* - :option:`-i/--input <scenedetect -i>`
-
- :func:`~scenedetect.open_video`, :func:`~scenedetect.detect`
* - :option:`--stdin <scenedetect --stdin>`
-
- :class:`~scenedetect.backends.pyav.VideoStreamAv` (``path_or_io``)
* - :option:`-o/--output <scenedetect -o>`
- :ref:`[global] output <config-global>`
- ``output_dir`` argument of :func:`~scenedetect.output.save_images` and :func:`~scenedetect.output.split_video_ffmpeg`; output path argument of each ``write_scene_list*`` function
Expand Down
5 changes: 5 additions & 0 deletions docs/generate_cli_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ class Counterpart:
option="input",
api=(":func:`~scenedetect.open_video`", ":func:`~scenedetect.detect`"),
),
Counterpart(
"Input video from a pipe",
option="stdin",
api=(f":class:`~{_BE}.pyav.VideoStreamAv` (``path_or_io``)",),
),
Counterpart(
"Start, end, or duration",
command="time",
Expand Down
4 changes: 3 additions & 1 deletion scenedetect/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def main():

with log_redirect:
try:
run_scenedetect(context)
success = run_scenedetect(context)
except KeyboardInterrupt:
logger.info("Stopped.")
if DEBUG_MODE:
Expand All @@ -54,6 +54,8 @@ def main():
raise
logger.critical("ERROR: Unhandled exception:", exc_info=ex)
raise SystemExit(1) from ex
if not success:
raise SystemExit(1)


if __name__ == "__main__":
Expand Down
29 changes: 27 additions & 2 deletions scenedetect/_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ def print_command_help(ctx: click.Context, command: click.Command):
type=click.STRING,
help="[REQUIRED] Input video file. Image sequences and URLs are supported.",
)
@click.option(
"--stdin",
is_flag=True,
default=False,
help="Read the input video from standard input instead of -i/--input. Requires the pyav backend. An MP4 needs its index at the start of the file (ffmpeg -movflags +faststart), otherwise remux to MKV or MPEG-TS. Commands that need to seek in the video are not supported.",
)
@click.option(
"--output",
"-o",
Expand Down Expand Up @@ -336,6 +342,7 @@ def print_command_help(ctx: click.Context, command: click.Command):
def scenedetect(
ctx: click.Context,
input: str | None,
stdin: bool,
output: str | None,
stats: str | None,
config: str | None,
Expand All @@ -356,6 +363,7 @@ def scenedetect(

ctx.handle_options(
input_path=input,
use_stdin=stdin,
output=output,
frame_rate=frame_rate,
stats_file=stats,
Expand All @@ -374,6 +382,12 @@ def scenedetect(
)


def check_not_stdin(ctx: CliContext, command: str) -> None:
"""Rejects `command` if the input is read from stdin, which cannot seek and has no path."""
if ctx.use_stdin:
raise click.UsageError(f"{command} is incompatible with --stdin.")


def add_hidden_alias(command: click.Command, alias: str):
"""Adds a copy of `command` that can be invoked under the name `alias`."""
# Shallow copy: deepcopy fails on Python 3.10 + click >=8.3 because click's internal
Expand Down Expand Up @@ -492,6 +506,8 @@ def time_command(
"Only one of --duration/-d or --end/-e can be specified, not both.",
param_hint="time",
)
if start is not None:
check_not_stdin(ctx, "time -s/--start")
logger.debug("Setting video time:\n start: %s, duration: %s, end: %s", start, duration, end)
# *NOTE*: The Python API uses 0-based frame indices, but the CLI uses 1-based indices to
# match the default start number used by `ffmpeg` when saving frames as images. As such,
Expand Down Expand Up @@ -1005,6 +1021,7 @@ def load_scenes_command(ctx: click.Context, input: str | None, start_col_name: s
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)
assert ctx.scene_manager is not None
if ctx.scene_manager.get_num_detectors() > 0:
Expand Down Expand Up @@ -1093,15 +1110,19 @@ def save_html_command(
assert isinstance(ctx, CliContext)
# Make sure a save-images command is in the pipeline for us to use the results from if we need
# to include images.
include_images = not ctx.config.get_value("save-html", "no-images", no_images)
no_images = ctx.config.get_value("save-html", "no-images", no_images)
if ctx.use_stdin and not no_images:
logger.warning("WARNING: save-html will not include images when reading from --stdin.")
no_images = True
include_images = not no_images
if include_images and not ctx.save_images:
assert save_images_command.callback is not None
save_images_command.callback()
save_html_args = {
"filename": ctx.config.get_value("save-html", "filename", filename),
"image_width": ctx.config.get_value("save-html", "image-width", image_width),
"image_height": ctx.config.get_value("save-html", "image-height", image_height),
"no_images": ctx.config.get_value("save-html", "no-images", no_images),
"no_images": no_images,
"show": ctx.config.get_value("save-html", "show", show),
}
ctx.add_command(cli_commands.save_html, save_html_args)
Expand Down Expand Up @@ -1330,6 +1351,7 @@ def split_video_command(
ctx = ctx.obj
assert isinstance(ctx, CliContext)

check_not_stdin(ctx, "split-video")
check_split_video_requirements(use_mkvmerge=mkvmerge)
assert ctx.video_stream is not None
if "%" in ctx.video_stream.path or "://" in ctx.video_stream.path:
Expand Down Expand Up @@ -1575,6 +1597,7 @@ def save_images_command(
assert isinstance(ctx, CliContext)
assert ctx.video_stream is not None

check_not_stdin(ctx, "save-images")
if "://" in ctx.video_stream.path:
error_str = "\nThe save-images command is incompatible with URLs."
logger.error(error_str)
Expand Down Expand Up @@ -1958,6 +1981,7 @@ def save_fcp_command(
ctx = ctx.obj
assert isinstance(ctx, CliContext)

check_not_stdin(ctx, "save-fcp")
save_fcp_args = {
"filename": ctx.config.get_value("save-fcp", "filename", filename),
"format": ctx.config.get_value("save-fcp", "format", format),
Expand Down Expand Up @@ -2021,6 +2045,7 @@ def save_otio_command(
ctx = ctx.obj
assert isinstance(ctx, CliContext)

check_not_stdin(ctx, "save-otio")
if audio and no_audio:
raise click.BadArgumentUsage("Only one of --audio or --no-audio can be specified.")

Expand Down
68 changes: 58 additions & 10 deletions scenedetect/_cli/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"""Context of which command-line options and config settings the user provided."""

import logging
import sys
import typing as ty

import click
Expand All @@ -24,6 +25,7 @@
ConfigRegistry,
CropValue,
)
from scenedetect.backends import VideoStreamAv
from scenedetect.common import MAX_FPS_DELTA, FrameTimecode
from scenedetect.detector import SceneDetector
from scenedetect.detectors import (
Expand All @@ -45,6 +47,20 @@
"""The user config, which can be overriden by command-line. If not found, will be default config."""


class _PipeReader:
"""Read-only view of a pipe. Windows reports pipes as seekable, but seeking on one fails or
returns bogus positions, so this keeps PyAV from trying."""

def __init__(self, pipe: ty.BinaryIO):
self._pipe = pipe

def read(self, size: int = -1) -> bytes:
return self._pipe.read(size)

def seekable(self) -> bool:
return False


def check_split_video_requirements(use_mkvmerge: bool) -> None:
"""Validates that the proper tool is available on the system to perform the
`split-video` command.
Expand Down Expand Up @@ -90,6 +106,7 @@ def __init__(self):

# 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
Expand Down Expand Up @@ -177,6 +194,7 @@ def parse_timecode(self, value: str | None, correct_pts: bool = False) -> FrameT
def handle_options(
self,
input_path: str | None,
use_stdin: bool,
output: str | None,
frame_rate: float | None,
stats_file: str | None,
Expand Down Expand Up @@ -256,12 +274,20 @@ def handle_options(
param_hint="frame skip + stats file",
)

if use_stdin and input_path is not None:
raise click.BadParameter(
"-i/--input cannot be used with --stdin.", param_hint="--stdin"
)

# Handle case where -i/--input was not specified (e.g. for the `help` command).
if input_path is None:
if input_path is None and not use_stdin:
return

# Load the input video to obtain a time base for parsing timecodes.
self._open_video_stream(input_path, frame_rate, backend)
if use_stdin:
self._open_stdin_stream(frame_rate, backend)
else:
self._open_video_stream(input_path, frame_rate, backend)

self.output = self.config.get_value("global", "output", output)
if self.output:
Expand Down Expand Up @@ -492,13 +518,28 @@ 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):
if backend not in (None, "pyav") or VideoStreamAv is None:
raise click.BadParameter(
"--stdin requires the pyav backend. Install it with `pip install av`.",
param_hint="--stdin",
)
# sys.stdin is None if there is no console, e.g. under pythonw.exe on Windows.
if sys.stdin is None or sys.stdin.isatty():
raise click.BadParameter(
"--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")

def _open_video_stream(
self,
input_path: str,
input_path: str | None,
frame_rate: float | None,
backend: str | None,
):
if "%" in input_path and backend != "opencv":
input_hint = "--stdin" if self.use_stdin else "-i/--input"
if input_path is not None and "%" in input_path and backend != "opencv":
raise click.BadParameter(
"The OpenCV backend (`--backend opencv`) must be used to process image sequences.",
param_hint="-i/--input",
Expand All @@ -514,7 +555,16 @@ def _open_video_stream(
)

# Open the video with the specified backend, loading any required config settings.
if backend == "pyav":
if input_path is None: # --stdin
self.video_stream = VideoStreamAv(
# _PipeReader only implements the part of BinaryIO that PyAV uses.
ty.cast(ty.BinaryIO, _PipeReader(sys.stdin.buffer)),
frame_rate=frame_rate,
name="stdin",
threading_mode=self.config.get_value("backend-pyav", "threading-mode"),
suppress_output=self.config.get_value("backend-pyav", "suppress-output"),
)
elif backend == "pyav":
self.video_stream = open_video(
path=input_path,
frame_rate=frame_rate,
Expand Down Expand Up @@ -558,7 +608,7 @@ def _open_video_stream(
raise click.BadParameter(
"Failed to obtain frame rate for input video. Manually specify frame rate with the"
" -f/--frame-rate option, or try re-encoding the file.",
param_hint="-i/--input",
param_hint=input_hint,
) from ex
except VideoOpenFailure as ex:
if DEBUG_MODE:
Expand All @@ -567,11 +617,9 @@ def _open_video_stream(
"Failed to open input video{}: {}".format(
f" using {backend} backend" if backend else "", str(ex)
),
param_hint="-i/--input",
param_hint=input_hint,
) from ex
except OSError as ex:
if DEBUG_MODE:
raise
raise click.BadParameter(
f"Input error:\n\n\t{ex!s}\n", param_hint="-i/--input"
) from None
raise click.BadParameter(f"Input error:\n\n\t{ex!s}\n", param_hint=input_hint) from None
19 changes: 16 additions & 3 deletions scenedetect/_cli/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,21 @@
logger = logging.getLogger("pyscenedetect")


def run_scenedetect(context: CliContext):
def run_scenedetect(context: CliContext) -> bool:
"""Perform main CLI application control logic. Run once all command-line options and
configuration file options have been validated.

Arguments:
context: Prevalidated command-line option context to use for processing.

Returns:
False if scene detection failed, True otherwise.
"""
# No input may have been specified depending on the commands/args that were used.
logger.debug("Running controller.")
if context.scene_manager is None:
logger.debug("No input specified.")
return
return True

# Suppress warnings when reading past EOF in MoviePy (#461).
if VideoStreamMoviePy and isinstance(context.video_stream, VideoStreamMoviePy):
Expand All @@ -58,7 +61,7 @@ def run_scenedetect(context: CliContext):
# Perform scene detection on input.
result = _detect(context)
if result is None:
return
return False
scenes, cuts = result
scenes = _postprocess_scene_list(context, scenes)
# Handle -s/--stats option.
Expand All @@ -76,6 +79,7 @@ def run_scenedetect(context: CliContext):
# Handle post-processing commands the user wants to run (see scenedetect._cli.commands).
for handler, kwargs in context.commands:
handler(context=context, scenes=scenes, cuts=cuts, **kwargs)
return True


def _postprocess_scene_list(context: CliContext, scene_list: SceneList) -> SceneList:
Expand Down Expand Up @@ -143,6 +147,15 @@ def _detect(context: CliContext) -> tuple[SceneList, CutList] | None:
)
return None

if num_frames <= 0 and context.use_stdin:
logger.critical(
"Failed to read any frames from stdin. An MP4 needs its index at the start of the file"
" to be read from a pipe (ffmpeg -movflags +faststart). Otherwise, try remuxing to MKV"
" or MPEG-TS:\n"
" ffmpeg -i input.mp4 -c copy -f matroska -\n"
)
return None

perf_duration = time.time() - perf_start_time
logger.info(
"Processed %d frames in %.1f seconds (average %.2f FPS).",
Expand Down
Loading
Loading