Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
713ac1e
Introduce frame position and duration types for VFR support
MuhammadBilalKhan267 Oct 25, 2026
3d8c695
Port FlashFilter to frame positions and durations
MuhammadBilalKhan267 Oct 26, 2026
005c1d0
[api] Port ContentDetector to FramePosition
MuhammadBilalKhan267 Oct 27, 2026
75efbc4
[style] Fix ContentDetector formatting
MuhammadBilalKhan267 Oct 27, 2026
a964060
[api] Port AdaptiveDetector to FramePosition
MuhammadBilalKhan267 Oct 27, 2026
0bc3f7c
[api] Port HashDetector to FramePosition
MuhammadBilalKhan267 Oct 27, 2026
7843d4b
[api] Port HistogramDetector to FramePosition
MuhammadBilalKhan267 Oct 27, 2026
d3282b9
[refactor] Remove duplicate minimum check from ThresholdDetector
MuhammadBilalKhan267 Oct 27, 2026
9704a20
[api] Port TransNet V2 to FramePosition
MuhammadBilalKhan267 Oct 27, 2026
a2fc7c0
[style] Format files
MuhammadBilalKhan267 Oct 27, 2026
ed6d674
[api] Port scene management and add timestamp peeking
MuhammadBilalKhan267 Nov 14, 2026
0b6e3c1
Merge main' into fix/569-vfr-inaccurate-frame-nums
MuhammadBilalKhan267 Nov 15, 2026
d1e4404
[api] Port scene exports to FramePosition [skip ci]
MuhammadBilalKhan267 Nov 15, 2026
d9ab513
[api] Port image extraction to FramePosition [skip ci]
MuhammadBilalKhan267 Nov 17, 2026
a38d67a
Merge main into fix/569-vfr-inaccurate-frame-nums. Port FFMETADATA to…
MuhammadBilalKhan267 Nov 17, 2026
ccbd50e
[api] Port CLI to frame positions [skip ci]
MuhammadBilalKhan267 Nov 21, 2026
42911b7
[api] Separate stream metadata and support expanded splits [skip ci]
MuhammadBilalKhan267 Nov 21, 2026
c315b63
[api] Port benchmark and golden cut extraction [skip ci]
MuhammadBilalKhan267 Nov 21, 2026
26e1352
[api] Remove FrameTimecode and its legacy module [skip ci]
MuhammadBilalKhan267 Nov 21, 2026
de3c7e0
[api] Add FramePosition compatibility helpers [skip ci]
MuhammadBilalKhan267 Nov 22, 2026
b10d5e5
Merge upstream/main into VFR branch [skip ci]
MuhammadBilalKhan267 Nov 22, 2026
21a72bc
[tests] Port timecode and NTSC regressions to the new types [skip ci]
MuhammadBilalKhan267 Nov 22, 2026
a8757a4
[tests] Cover FramePosition and FrameDuration contracts [skip ci]
MuhammadBilalKhan267 Nov 22, 2026
9ca4019
[tests] Port video stream tests to FramePosition [skip ci]
MuhammadBilalKhan267 Nov 23, 2026
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
2 changes: 1 addition & 1 deletion benchmark/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down
2 changes: 1 addition & 1 deletion benchmark/sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 19 additions & 13 deletions scenedetect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -203,16 +210,15 @@ 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)
scene_manager.add_detector(detector)
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)
Expand Down
110 changes: 75 additions & 35 deletions scenedetect/_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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"
"""


Expand All @@ -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.")
Expand All @@ -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.
Expand Down Expand Up @@ -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")
),
)
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand All @@ -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",
Expand Down Expand Up @@ -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.
"""


Expand Down
Loading