{{ message }}
Repository navigation
Expand file tree
/
Copy pathtest_cli.py
More file actions
1672 lines (1528 loc) · 62.2 KB
/
Copy pathtest_cli.py
File metadata and controls
1672 lines (1528 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# PySceneDetect: Python-Based Video Scene Detector
# -------------------------------------------------------------------
# [ Site: https://scenedetect.com ]
# [ Docs: https://scenedetect.com/docs/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
#
# Copyright (C) 2022 Brandon Castellano <http://www.bcastell.com>.
# PySceneDetect is licensed under the BSD 3-Clause License; see the
# included LICENSE file, or visit one of the above pages for details.
#
import os
import subprocess
# These tests validate that the CLI itself functions correctly, mainly based on the return
# return code from the process. We do not yet check for correctness of the output, just a
# successful invocation of the command (i.e. no exceptions/errors).
# TODO: Add some basic correctness tests to validate the output (just look for the
# last expected log message or extract # of scenes). Might need to refactor the test cases
# since we need to calculate the output file names for commands that write to disk.
# TODO: Define error/exit codes explicitly. Right now these tests only verify that the
# exit code is zero or nonzero.
# TODO: These tests are very expensive since they spin up new Python interpreters.
# Move most of these test cases (e.g. argument validation) to ones that interface directly
# with the scenedetect._cli module. Click also supports unit testing directly, so we should
# probably use that instead of spinning up new subprocesses for each run of the controller.
# That will also allow splitting up the validation of argument parsing logic from the controller
# logic by creating a CLI context with the desired parameters.
# TODO: Missing tests for --min-scene-len and --drop-short-scenes.
import sys
from pathlib import Path
import cv2
import numpy as np
import pytest
import scenedetect
from scenedetect._cli.config import ConfigLoadFailure, ConfigRegistry
from scenedetect.output import is_ffmpeg_available, is_mkvmerge_available
from scenedetect.platform import StrPath
from tests.helpers import invoke_cli
SCENEDETECT_CMD = sys.executable + " -m scenedetect"
ALL_DETECTORS = [
"detect-content",
"detect-threshold",
"detect-adaptive",
"detect-hist",
"detect-hash",
]
ALL_BACKENDS = ["opencv", "pyav"]
DEFAULT_VIDEO_PATH = "tests/resources/goldeneye.mp4"
DEFAULT_VIDEO_NAME = Path(DEFAULT_VIDEO_PATH).stem
DEFAULT_BACKEND = "opencv"
DEFAULT_STATSFILE = "statsfile.csv"
DEFAULT_TIME = "-s 2s -d 4s" # Seek forward a bit but limit the amount we process.
DEFAULT_DETECTOR = "detect-content"
DEFAULT_CONFIG_FILE = "scenedetect.cfg" # Ensure we default to a "blank" config file.
DEFAULT_NUM_SCENES = 2 # Number of scenes we expect to detect given above params.
DEFAULT_FFMPEG_ARGS = (
"-vf crop=128:128:0:0 -map 0:v:0 -c:v libx264 -preset ultrafast -qp 0 -tune zerolatency"
)
"""Only encodes a small crop of the frame and tuned for performance to speed up tests."""
def invoke_scenedetect(
args: str = "",
output_dir: StrPath | None = None,
config_file: str | None = DEFAULT_CONFIG_FILE,
**kwargs,
):
"""Invokes the scenedetect CLI with the specified arguments and returns the exit code.
The kwargs are passed to the args format method, for example:
invoke_scenedetect('-i {VIDEO} {DETECTOR}', VIDEO='file.mp4', DETECTOR='detect-content')
Providing `output_dir` and `config_file` set -o/--output and -c/--config, respectively.
Default values are set for any arguments found in the command:
VIDEO -> VIDEO_PATH
VIDEO_NAME -> VIDEO_NAME
DETECTOR -> DEFAULT_DETECTOR
TIME -> DEFAULT_TIME
STATS -> DEFAULT_STATSFILE
BACKEND -> DEFAULT_BACKEND
CONFIG_FILE -> DEFAULT_CONFIG_FILE
"""
value_dict = dict(
VIDEO=DEFAULT_VIDEO_PATH,
VIDEO_NAME=DEFAULT_VIDEO_NAME,
TIME=DEFAULT_TIME,
DETECTOR=DEFAULT_DETECTOR,
STATS=DEFAULT_STATSFILE,
BACKEND=DEFAULT_BACKEND,
)
value_dict.update(**kwargs)
command = SCENEDETECT_CMD
if output_dir:
command += f" -o {output_dir}"
if config_file:
command += f" -c {config_file}"
command += " " + args.format(**value_dict)
return subprocess.call(command.strip().split(" "))
def test_cli_no_args():
"""Test `scenedetect` command invoked without any arguments."""
assert invoke_scenedetect(config_file=None) == 0
def test_cli_default_detector():
"""Test `scenedetect` command invoked without a detector."""
assert invoke_scenedetect("-i {VIDEO} time {TIME}", config_file=None) == 0
def test_cli_crop():
"""Test --crop functionality."""
assert invoke_scenedetect("-i {VIDEO} --crop 0 0 256 256 time {TIME}", config_file=None) == 0
def test_cli_crop_rejects_invalid():
"""Test --crop rejects invalid options."""
# Outside of video bounds
assert (
invoke_scenedetect("-i {VIDEO} --crop 4000 0 8000 100 time {TIME}", config_file=None) != 1
)
assert (
invoke_scenedetect("-i {VIDEO} --crop 0 4000 100 8000 time {TIME}", config_file=None) != 1
)
# Negative numbers
assert invoke_scenedetect("-i {VIDEO} --crop 0 0 -256 -256 time {TIME}", config_file=None) != 1
@pytest.mark.parametrize("info_command", ["help", "about", "version"])
def test_cli_info_command(info_command):
"""Test `scenedetect` info commands (e.g. help, about)."""
assert invoke_scenedetect(info_command) == 0
def test_cli_time_validate_options():
"""Validate behavior of setting parameters via the `time` command."""
base_command = "-i {VIDEO} time {TIME} {DETECTOR}"
# Ensure cannot set end and duration together.
assert invoke_scenedetect(base_command, TIME="-s 2.0 -d 6.0 -e 8.0") != 0
assert invoke_scenedetect(base_command, TIME="-s 2.0 -e 8.0 -d 6.0 ") != 0
def test_cli_time_end():
"""Validate processed frames without start time being set. End time is the end frame to stop at,
but with duration, we stop at start + duration - 1."""
EXPECTED = """[PySceneDetect] Scene List:
-----------------------------------------------------------------------
| Scene # | Start Frame | Start Time | End Frame | End Time |
-----------------------------------------------------------------------
| 1 | 1 | 00:00:00.000 | 10 | 00:00:00.417 |
-----------------------------------------------------------------------
"""
TEST_CASES = [
"time --end 10",
"time --end 00:00:00.417",
"time --end 0.417",
"time --duration 10",
"time --duration 00:00:00.417",
"time --duration 0.417",
]
for test_case in TEST_CASES:
output = subprocess.check_output(
[
*SCENEDETECT_CMD.split(" "),
"-i",
DEFAULT_VIDEO_PATH,
"-m",
"0",
"detect-content",
"list-scenes",
"-n",
*test_case.split(),
],
text=True,
)
assert EXPECTED in output, test_case
def test_cli_time_start():
"""Validate processed frames with both start and end/duration set. End time is the end frame to
stop at, but with duration, we stop at start + duration - 1."""
EXPECTED = """[PySceneDetect] Scene List:
-----------------------------------------------------------------------
| Scene # | Start Frame | Start Time | End Frame | End Time |
-----------------------------------------------------------------------
| 1 | 4 | 00:00:00.125 | 10 | 00:00:00.417 |
-----------------------------------------------------------------------
"""
TEST_CASES = [
"time --start 4 --end 10",
"time --start 4 --end 00:00:00.417",
"time --start 4 --end 0.417",
"time --start 4 --duration 7",
"time --start 4 --duration 0.292",
"time --start 4 --duration 00:00:00.292",
]
for test_case in TEST_CASES:
output = subprocess.check_output(
[
*SCENEDETECT_CMD.split(" "),
"-i",
DEFAULT_VIDEO_PATH,
"-m",
"0",
"detect-content",
"list-scenes",
"-n",
*test_case.split(),
],
text=True,
)
assert EXPECTED in output, test_case
def test_cli_time_scene_boundary():
"""Validate frames that are processed when crossing a scene boundary. End time is the end frame
to stop at, but with duration, we stop at start + duration - 1."""
# -------------------------------------------------------------------------------------
# | Scene | Frame | PTS | PTS + Duration | Annotation |
# -------------------------------------------------------------------------------------
# | 1 | 86 | 00:00:03.545 | 00:00:03.587 | Start Frame |
# | 1 | 87 | 00:00:03.587 | 00:00:03.629 | |
# | 1 | 88 | 00:00:03.629 | 00:00:03.670 | |
# | 1 | 89 | 00:00:03.670 | 00:00:03.712 | |
# | 1 | 90 | 00:00:03.712 | 00:00:03.754 | Scene 1 End |
# | 2 | 91 | 00:00:03.754 | 00:00:03.795 | Scene 2 Start |
# | 2 | 92 | 00:00:03.795 | 00:00:03.837 | |
# | 2 | 93 | 00:00:03.837 | 00:00:03.879 | |
# | 2 | 94 | 00:00:03.879 | 00:00:03.921 | |
# | 2 | 95 | 00:00:03.921 | 00:00:03.962 | |
# | 2 | 96 | 00:00:03.962 | 00:00:04.004 | End Frame |
# -------------------------------------------------------------------------------------
EXPECTED = """
-----------------------------------------------------------------------
| Scene # | Start Frame | Start Time | End Frame | End Time |
-----------------------------------------------------------------------
| 1 | 86 | 00:00:03.545 | 90 | 00:00:03.754 |
| 2 | 91 | 00:00:03.754 | 96 | 00:00:04.004 |
-----------------------------------------------------------------------
"""
# End time is the end frame to stop at, but with duration, we stop at start + duration - 1.
TEST_CASES = [
"time --start 86 --end 96",
"time --start 00:00:03.545 --end 00:00:04.004",
"time --start 3.545 --end 4.004",
"time --start 86 --duration 11",
"time --start 00:00:03.545 --duration 00:00:00.459",
"time --start 3.545 --duration 0.459",
]
for test_case in TEST_CASES:
output = subprocess.check_output(
[
*SCENEDETECT_CMD.split(" "),
"-i",
DEFAULT_VIDEO_PATH,
"-m",
"0",
"detect-content",
"list-scenes",
"-n",
*test_case.split(),
],
text=True,
)
assert EXPECTED in output, test_case
@pytest.mark.parametrize("backend", ["opencv", "pyav", "moviepy"])
def test_cli_time_start_past_end_of_video(backend: str):
"""Start time past EOF must fail the same way on every backend (issue #380)."""
exit_code, output = invoke_cli(["-i", DEFAULT_VIDEO_PATH, "-b", backend, "time", "-s", "10000"])
assert exit_code != 0, output
assert "beyond the end of the video" in output
assert "multiple audio tracks" not in output
assert "Detected 1 scenes" not in output
def test_cli_time_end_of_video():
"""Validate frame number/timecode alignment at the end of the video. The end timecode includes
presentation time and therefore should represent the full length of the video."""
output = subprocess.check_output(
[
*SCENEDETECT_CMD.split(" "),
"-i",
DEFAULT_VIDEO_PATH,
"detect-content",
"list-scenes",
"-n",
"time",
"-s",
"1872",
],
text=True,
)
assert (
"""
-----------------------------------------------------------------------
| Scene # | Start Frame | Start Time | End Frame | End Time |
-----------------------------------------------------------------------
| 1 | 1872 | 00:01:18.036 | 1916 | 00:01:19.913 |
| 2 | 1917 | 00:01:19.913 | 1966 | 00:01:21.999 |
| 3 | 1967 | 00:01:21.999 | 1980 | 00:01:22.582 |
-----------------------------------------------------------------------
"""
in output
)
assert "00:01:19.913,00:01:21.999" in output
@pytest.mark.parametrize("detector_command", ALL_DETECTORS)
def test_cli_detector(detector_command: str):
"""Test each detection algorithm."""
# Ensure all detectors work without a statsfile.
assert invoke_scenedetect("-i {VIDEO} time {TIME} {DETECTOR}", DETECTOR=detector_command) == 0
@pytest.mark.parametrize("detector_command", ALL_DETECTORS)
def test_cli_detector_with_stats(tmp_path, detector_command: str):
"""Test each detection algorithm with a statsfile."""
# Run with a statsfile twice to ensure the file is populated with those metrics and reloaded.
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR}",
output_dir=tmp_path,
DETECTOR=detector_command,
)
== 0
)
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR}",
output_dir=tmp_path,
DETECTOR=detector_command,
)
== 0
)
# TODO: Check for existence of statsfile by trying to load it with the library,
# and ensuring that we got some frames.
@pytest.mark.parametrize(
"option",
["--frame-rate", "--framerate", "-f"],
)
def test_cli_frame_rate_aliases(option: str):
"""All frame-rate aliases are accepted by the CLI."""
exit_code, _ = invoke_cli(
["-i", DEFAULT_VIDEO_PATH, option, "30.0", "time", "-s", "2s", "-d", "4s"]
)
assert exit_code == 0
@pytest.mark.parametrize(
("options", "succeeds"),
[
(["--frame-rate", "30.0", "--framerate", "0"], False),
(["--framerate", "0", "--frame-rate", "30.0"], True),
],
)
def test_cli_frame_rate_aliases_last_value_wins(options: list[str], succeeds: bool):
"""When a frame-rate option is repeated, only the last value is validated and used."""
exit_code, _ = invoke_cli(["-i", DEFAULT_VIDEO_PATH, *options, "time", "-s", "2s", "-d", "4s"])
assert (exit_code == 0) is succeeds
def test_cli_framerate_alias_is_visible():
"""Help shows all frame-rate aliases as one option."""
exit_code, output = invoke_cli(["--help"])
assert exit_code == 0
assert "-f, --frame-rate, --framerate FPS" in output
def test_cli_min_scene_len_accepts_all_timecode_forms(tmp_path: Path):
"""`--min-scene-len` (and equivalent options) must accept frames, seconds, and timecodes
in v0.7 per the changelog. The four forms below all resolve to ~20 frames at 23.976 fps
and must produce byte-identical scene lists."""
# 20 frames @ 23.976 fps = 0.8341... s, which rounds to the same nearest frame regardless
# of which form is parsed.
forms = ["20", "0.834", "0.834s", "00:00:00.834"]
outputs = []
for form in forms:
out = tmp_path / f"scenes_{form.replace(':', '_')}.csv"
exit_code, _ = invoke_cli(
[
"-i",
DEFAULT_VIDEO_PATH,
"-o",
str(tmp_path),
"time",
"-s",
"2s",
"-d",
"4s",
"detect-content",
"--min-scene-len",
form,
"list-scenes",
"-f",
out.name,
"-q", # suppress stdout printing
],
)
assert exit_code == 0, f"--min-scene-len {form!r} rejected"
assert out.exists(), f"--min-scene-len {form!r} did not produce {out}"
outputs.append((form, out.read_text()))
# All forms must produce the same scene list.
base_form, base_csv = outputs[0]
for form, csv in outputs[1:]:
assert csv == base_csv, (
f"Scene list differs between --min-scene-len {base_form!r} and {form!r}"
)
def test_cli_list_scenes(tmp_path: Path):
"""Test `list-scenes` command."""
exit_code, _ = invoke_cli(
[
"-i",
DEFAULT_VIDEO_PATH,
"-o",
str(tmp_path),
"time",
"-s",
"2s",
"-d",
"4s",
"detect-content",
"list-scenes",
]
)
assert exit_code == 0
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}-Scenes.csv")
assert os.path.exists(output_path)
EXPECTED_CSV_OUTPUT = """Timecode List:,00:00:03.754
Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds)
1,49,00:00:02.002,2.002,90,00:00:03.754,3.754,42,00:00:01.752,1.752
2,91,00:00:03.754,3.754,144,00:00:06.006,6.006,54,00:00:02.252,2.252
"""
assert output_path.read_text() == EXPECTED_CSV_OUTPUT
def test_cli_list_scenes_skip_cuts(tmp_path: Path):
"""Test `list-scenes` command with the -s/--skip-cuts option for RFC 4180 compliance."""
# Regular invocation
assert (
invoke_scenedetect(
"-i {VIDEO} time {TIME} {DETECTOR} list-scenes -s",
output_dir=tmp_path,
)
== 0
)
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}-Scenes.csv")
assert os.path.exists(output_path)
EXPECTED_CSV_OUTPUT = """Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds)
1,49,00:00:02.002,2.002,90,00:00:03.754,3.754,42,00:00:01.752,1.752
2,91,00:00:03.754,3.754,144,00:00:06.006,6.006,54,00:00:02.252,2.252
"""
assert output_path.read_text() == EXPECTED_CSV_OUTPUT
def test_cli_list_scenes_no_output(tmp_path: Path):
"""Test `list-scenes` command with the -n flag."""
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}-Scenes.csv")
assert (
invoke_scenedetect(
"-i {VIDEO} time {TIME} {DETECTOR} list-scenes -n",
output_dir=tmp_path,
)
== 0
)
assert not os.path.exists(output_path)
def test_cli_list_scenes_custom_delimiter(tmp_path: Path):
"""Test `list-scenes` command with custom delimiters set in a config file."""
config_path = tmp_path.joinpath("config.cfg")
config_path.write_text("""
[list-scenes]
col-separator = |
row-separator = \\t
""")
assert (
invoke_scenedetect(
f"-i {{VIDEO}} -c {config_path} time {{TIME}} {{DETECTOR}} list-scenes",
output_dir=tmp_path,
)
== 0
)
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}-Scenes.csv")
assert os.path.exists(output_path)
EXPECTED_CSV_OUTPUT = """Timecode List:,00:00:03.754
Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds)
1,49,00:00:02.002,2.002,90,00:00:03.754,3.754,42,00:00:01.752,1.752
2,91,00:00:03.754,3.754,144,00:00:06.006,6.006,54,00:00:02.252,2.252
"""
EXPECTED_CSV_OUTPUT = EXPECTED_CSV_OUTPUT.replace(",", "|").replace("\n", "\t")
assert output_path.read_text() == EXPECTED_CSV_OUTPUT
def test_cli_list_scenes_rejects_multichar_col_separator(tmp_path: Path):
"""Test `list-scenes` command with custom delimiters set in a config file."""
config_path = tmp_path.joinpath("config.cfg")
config_path.write_text("""
[list-scenes]
col-separator = ||
""")
assert (
invoke_scenedetect(
f"-i {{VIDEO}} -c {config_path} time {{TIME}} {{DETECTOR}} list-scenes",
output_dir=tmp_path,
)
!= 0
)
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}-Scenes.csv")
assert not os.path.exists(output_path)
@pytest.mark.skipif(condition=not is_ffmpeg_available(), reason="ffmpeg is not available")
def test_cli_split_video_ffmpeg(tmp_path: Path):
"""Test `split-video` command using ffmpeg."""
# Assumption: The default filename format is VIDEO_NAME-Scene-SCENE_NUMBER.
command = f"{SCENEDETECT_CMD} -i {DEFAULT_VIDEO_PATH} -o {tmp_path} time {DEFAULT_TIME} {DEFAULT_DETECTOR} split-video -a".split(
" "
)
command.append(DEFAULT_FFMPEG_ARGS)
assert subprocess.call(command) == 0
entries = sorted(tmp_path.glob(f"{DEFAULT_VIDEO_NAME}-Scene-*"))
assert len(entries) == DEFAULT_NUM_SCENES, entries
[entry.unlink() for entry in entries]
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} split-video -c", output_dir=tmp_path
)
== 0
)
entries = sorted(tmp_path.glob(f"{DEFAULT_VIDEO_NAME}-Scene-*"))
assert len(entries) == DEFAULT_NUM_SCENES
[entry.unlink() for entry in entries]
command += ["-f", "abc$VIDEO_NAME-123$SCENE_NUMBER"]
assert subprocess.call(command) == 0
entries = sorted(tmp_path.glob(f"abc{DEFAULT_VIDEO_NAME}-123*"))
assert len(entries) == DEFAULT_NUM_SCENES, entries
[entry.unlink() for entry in entries]
# -a/--args and -c/--copy are mutually exclusive, so this command should fail (return nonzero)
assert invoke_scenedetect(
'-i {VIDEO} {DETECTOR} split-video -c -a "-c:v libx264"',
output_dir=tmp_path,
)
@pytest.mark.skipif(condition=not is_mkvmerge_available(), reason="mkvmerge is not available")
def test_cli_split_video_mkvmerge(tmp_path: Path):
"""Test `split-video` command using mkvmerge."""
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} split-video -m", output_dir=tmp_path
)
== 0
)
for scene in range(DEFAULT_NUM_SCENES):
path = tmp_path / (Path(DEFAULT_VIDEO_PATH).stem + f"-Scene-{1 + scene:03d}.mkv")
path.unlink(missing_ok=False)
# If only one scene (just using a few frames), should keep same output template.
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time -e 3 {DETECTOR} split-video -m", output_dir=tmp_path
)
== 0
)
path = tmp_path / (Path(DEFAULT_VIDEO_PATH).stem + "-Scene-001.mkv")
path.unlink(missing_ok=False)
# -m takes precedence over -c
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} split-video -m -c", output_dir=tmp_path
)
== 0
)
# Custom filename format
for scene in range(DEFAULT_NUM_SCENES):
path = tmp_path / (Path(DEFAULT_VIDEO_PATH).stem + f"-Scene-{1 + scene:03d}.mkv")
path.unlink(missing_ok=False)
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} split-video -m -f test$VIDEO_NAME",
output_dir=tmp_path,
)
== 0
)
for scene in range(DEFAULT_NUM_SCENES):
path = tmp_path / ("test" + Path(DEFAULT_VIDEO_PATH).stem + f"-{1 + scene:03d}.mkv")
path.unlink(missing_ok=False)
# -a/--args and -m/--mkvmerge are mutually exclusive
assert invoke_scenedetect(
'-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} split-video -m -a "-c:v libx264"',
output_dir=tmp_path,
)
def test_cli_save_images(tmp_path: Path):
"""Test `save-images` command."""
assert (
invoke_scenedetect(
"-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} save-images", output_dir=tmp_path
)
== 0
)
images = [image for image in tmp_path.glob("*.jpg")]
# Should detect two scenes and generate 3 images per scene with above params.
assert len(images) == 6
# Open one of the created images and make sure it has the correct resolution.
image = cv2.imread(str(images[0]))
assert image is not None
assert image.shape == (544, 1280, 3)
def test_cli_save_images_path_handling(tmp_path: Path):
"""Test `save-images` ability to handle UTF-8 paths."""
assert (
invoke_scenedetect(
"-i {{VIDEO}} -s {{STATS}} time {{TIME}} {{DETECTOR}} save-images -f {}".format(
"電腦檔案-$SCENE_NUMBER-$IMAGE_NUMBER"
),
output_dir=tmp_path,
)
== 0
)
images = [image for image in tmp_path.glob("電腦檔案-*.jpg")]
# Should detect two scenes and generate 3 images per scene with above params.
assert len(images) == 6
# Check the created images can be read and have the correct size.
# We can't use `cv2.imread` here since it doesn't seem to work correctly with UTF-8 paths.
image = cv2.imdecode(np.fromfile(images[0], dtype=np.uint8), cv2.IMREAD_UNCHANGED)
assert image is not None
assert image.shape == (544, 1280, 3)
# TODO(https://scenedetect.com/issues/134): This works fine with OpenCV currently, but needs to be
# supported for PyAV and MoviePy.
def test_cli_save_images_rotation(rotated_video_file, tmp_path: Path):
"""Test that `save-images` command rotates images correctly with the default backend."""
assert (
invoke_scenedetect(
"-i {VIDEO} {DETECTOR} time {TIME} save-images",
VIDEO=rotated_video_file,
output_dir=tmp_path,
)
== 0
)
images = [image for image in tmp_path.glob("*.jpg")]
# Should detect two scenes and generate 3 images per scene with above params.
assert len(images) == 6
image = cv2.imread(str(images[0]))
assert image is not None
# Note same resolution as in test_cli_save_images but rotated 90 degrees.
assert image.shape == (1280, 544, 3)
_TIME_AND_DETECTOR = ["time", *DEFAULT_TIME.split(), DEFAULT_DETECTOR]
def _count_images_per_scene(path: Path) -> list[int]:
return [
len(list(path.glob(f"{DEFAULT_VIDEO_NAME}-Scene-{scene + 1:03d}-*.jpg")))
for scene in range(DEFAULT_NUM_SCENES)
]
def _invoke_save_images(
tmp_path: Path, args: list[str], config: str | None = None
) -> tuple[int, str]:
"""Run `save-images` with `args` in-process, using `config` as the [save-images] section of
the config file."""
config_path = tmp_path / "config.cfg"
config_path.write_text(f"[save-images]\n{config or ''}\n")
return invoke_cli(
[
"-c",
str(config_path),
"-i",
DEFAULT_VIDEO_PATH,
"-o",
str(tmp_path),
*_TIME_AND_DETECTOR,
"save-images",
*args,
]
)
@pytest.mark.parametrize(
"args,expected",
[
# The two scenes are 1.752s and 2.252s long: floor(length / 1s) + 1 images each.
(["-i", "1s"], [2, 3]),
(["-i", "1.5s"], [2, 2]),
(["--interval", "00:00:01.000"], [2, 3]),
# DURATION in frames (24 frames is about 1s here).
(["-i", "24"], [2, 3]),
# --min-images and --max-images limit the number of images per scene.
(["-i", "1s", "--min-images", "3"], [3, 3]),
(["-i", "0.5s", "--max-images", "4"], [4, 4]),
(["-i", "0.2s", "--min-images", "10", "--max-images", "11"], [10, 11]),
(["-i", "0.5s", "--max-images", "0"], [4, 5]),
],
)
def test_cli_save_images_interval(tmp_path: Path, args: list[str], expected: list[int]):
"""Test `save-images -i/--interval` with --min-images/--max-images."""
exit_code, _ = _invoke_save_images(tmp_path, args)
assert exit_code == 0
assert _count_images_per_scene(tmp_path) == expected
@pytest.mark.parametrize(
"args,error",
[
(["-n", "3", "-i", "1s"], "Only one of -n/--num-images or -i/--interval can be set."),
(
["--min-images", "2"],
"--min-images and --max-images can only be used with -i/--interval.",
),
(
["-n", "3", "--max-images", "2"],
"--min-images and --max-images can only be used with -i/--interval.",
),
(
["-i", "1s", "--min-images", "3", "--max-images", "2"],
"max-images must be 0 (no limit) or at least min-images.",
),
(["-i", "1s", "--min-images", "0"], "0 is not in the range x>=1."),
(["-i", "1s", "--max-images", "-1"], "-1 is not in the range x>=0."),
(
["-i", "abc"],
"Invalid value for -i/--interval: Interval must be in frames (24), seconds (1.5s), or HH:MM:SS.",
),
(["-i", "0"], "Invalid value for -i/--interval: Interval must be greater than 0."),
(["-i", "0s"], "Invalid value for -i/--interval: Interval must be greater than 0."),
],
)
def test_cli_save_images_interval_rejects_invalid_values(
tmp_path: Path, args: list[str], error: str
):
exit_code, output = _invoke_save_images(tmp_path, args)
assert exit_code != 0
assert error in output
assert not list(tmp_path.glob("*.jpg"))
@pytest.mark.parametrize(
"config,args,expected",
[
("interval = 1s", [], [2, 3]),
("interval = 1s\nmin-images = 3", [], [3, 3]),
("interval = 0.5s\nmax-images = 4", [], [4, 4]),
# Options on the command line take precedence over the config file.
("interval = 2s\nmax-images = 2", ["-i", "0.5s"], [2, 2]),
("interval = 0.5s\nmax-images = 4", ["--max-images", "2"], [2, 2]),
("interval = 0.5s\nmax-images = 4", ["--max-images", "0"], [4, 5]),
("interval = 2s", ["--min-images", "3"], [3, 3]),
("num-images = 5", ["-i", "1s"], [2, 3]),
# Without an interval in effect, min-images and max-images in the config file are ignored.
("interval = 1s\nmin-images = 5\nmax-images = 5", ["-n", "2"], [2, 2]),
("num-images = 2\nmin-images = 5", [], [2, 2]),
],
)
def test_cli_save_images_interval_config_file(
tmp_path: Path, config: str, args: list[str], expected: list[int]
):
"""Test the `interval`, `min-images` and `max-images` options of `[save-images]`."""
exit_code, _ = _invoke_save_images(tmp_path, args, config=config)
assert exit_code == 0
assert _count_images_per_scene(tmp_path) == expected
@pytest.mark.parametrize(
"config,args,error",
[
(
"num-images = 3\ninterval = 1s",
[],
"Only one of num-images or interval can be set in the config file.",
),
(
"num-images = 3",
["--max-images", "2"],
"--min-images and --max-images can only be used with -i/--interval.",
),
(
"interval = 1s\nmin-images = 3\nmax-images = 2",
[],
"max-images must be 0 (no limit) or at least min-images.",
),
("interval = 0", [], "interval in the config file must be greater than 0."),
("interval = 0s", [], "interval in the config file must be greater than 0."),
],
)
def test_cli_save_images_interval_config_file_rejects_invalid_values(
tmp_path: Path, config: str, args: list[str], error: str
):
exit_code, output = _invoke_save_images(tmp_path, args, config=config)
assert exit_code != 0
assert error in output
assert not list(tmp_path.glob("*.jpg"))
@pytest.mark.parametrize(
"config,error",
[
("interval = abc", "Timecodes must be in seconds (100.0), frames (100), or HH:MM:SS."),
("min-images = 0", "Value must be an integer of at least 1."),
("min-images = 1.5", "Value must be an integer of at least 1."),
("min-images = x", "Value must be an integer of at least 1."),
("max-images = -1", "Value must be an integer of at least 0."),
],
)
def test_cli_save_images_interval_config_file_load_errors(tmp_path: Path, config: str, error: str):
config_path = tmp_path.joinpath("config.cfg")
config_path.write_text(f"[save-images]\n{config}\n")
with pytest.raises(ConfigLoadFailure) as ex:
ConfigRegistry(str(config_path))
assert any(error in message for _, message in ex.value.init_log)
def test_cli_save_html(tmp_path: Path):
"""Test `save-html` command."""
base_command = "-i {VIDEO} -s {STATS} time {TIME} {DETECTOR} {COMMAND}"
assert invoke_scenedetect(base_command, COMMAND="save-html", output_dir=tmp_path) == 0
# The global -o option should also apply when no images are saved.
assert (
invoke_scenedetect(
base_command,
COMMAND="save-html --no-images --filename no-images.html",
output_dir=tmp_path,
)
== 0
)
assert (tmp_path / "no-images.html").exists()
# Ensure we can still call the now deprecated export-html command.
assert invoke_scenedetect(base_command, COMMAND="export-html", output_dir=tmp_path) == 0
# TODO: Check for existence of HTML & image files.
def test_cli_moviepy_accepts_frame_rate_override():
"""The MoviePy backend supports the -f/--frame-rate override in v0.7. The CLI must run
end-to-end without raising NotImplementedError, and the override must be reflected in the
resulting frame rate."""
from fractions import Fraction
from scenedetect.backends.moviepy import VideoStreamMoviePy
# Direct backend invocation: confirm the frame_rate property reports the override.
vs = VideoStreamMoviePy("tests/resources/testvideo.mp4", frame_rate=15.0)
assert vs.frame_rate == Fraction(15, 1), (
f"MoviePy frame_rate override not honored: got {vs.frame_rate}"
)
# CLI invocation must run cleanly with `-b moviepy -f 30`.
exit_code, output = invoke_cli(
[
"-i",
DEFAULT_VIDEO_PATH,
"-b",
"moviepy",
"--frame-rate",
"30",
"time",
"--end",
"1s",
"detect-content",
],
)
assert exit_code == 0, f"CLI failed:\n{output}"
assert "NotImplementedError" not in output, (
f"Backend NotImplementedError leaked to user output:\n{output}"
)
def test_cli_legacy_v06_config_file(tmp_path: Path):
"""A v0.6-era scenedetect.cfg using the deprecated `[export-html]` section must still load
in v0.7. The parser maps `[export-html]` -> `[save-html]` (via DEPRECATED_COMMANDS in
scenedetect/_cli/config.py) and emits a deprecation warning on load. This is the most
likely silent break for users upgrading config files; the option set under both sections
is identical."""
legacy_cfg = tmp_path / "scenedetect.cfg"
legacy_cfg.write_text(
# Mix of unchanged sections and the renamed `[export-html]` section.
"[global]\nmin-scene-len = 0.6s\n\n"
"[detect-content]\nthreshold = 27\n\n"
"[export-html]\nfilename = $VIDEO_NAME-Scenes.html\nno-images = yes\n"
)
exit_code, output = invoke_cli(
["-c", str(legacy_cfg), "-i", DEFAULT_VIDEO_PATH, "time", "-s", "2s", "-d", "1s"],
)
assert exit_code == 0, f"v0.6-style config rejected:\n{output}"
def test_cli_save_qp(tmp_path: Path):
"""Test `save-qp` command with and without a custom filename format."""
EXPECTED_QP_CONTENTS = """
0 I -1
90 I -1
"""
for filename in (None, "custom.txt"):
filename_format = f"--filename {filename}" if filename else ""
assert (
invoke_scenedetect(
f"-i {{VIDEO}} time -e 95 {{DETECTOR}} save-qp {filename_format}",
output_dir=tmp_path,
)
== 0
)
output_path = tmp_path.joinpath(filename if filename else f"{DEFAULT_VIDEO_NAME}.qp")
assert os.path.exists(output_path)
assert output_path.read_text() == EXPECTED_QP_CONTENTS[1:]
def test_cli_save_qp_start_offset(tmp_path: Path):
"""Test `save-qp` command but using a shifted start time."""
# The QP file should always start from frame 0, so we expect a similar result to the above, but
# with the frame numbers shifted by the start frame. Note that on the command-line, the first
# frame is frame 1, but the first frame in a QP file is indexed by 0.
#
# Since we are starting at frame 51, we must shift all cuts by 50 frames.
EXPECTED_QP_CONTENTS = """
0 I -1
40 I -1
"""
assert (
invoke_scenedetect(
"-i {VIDEO} time -s 51 -e 95 {DETECTOR} save-qp",
output_dir=tmp_path,
)
== 0
)
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}.qp")
assert os.path.exists(output_path)
assert output_path.read_text() == EXPECTED_QP_CONTENTS[1:]
def test_cli_save_qp_no_shift(tmp_path: Path):
"""Test `save-qp` command with start time shifting disabled."""
EXPECTED_QP_CONTENTS = """
50 I -1
90 I -1
"""
assert (
invoke_scenedetect(
"-i {VIDEO} time -s 51 -e 95 {DETECTOR} save-qp --disable-shift",
output_dir=tmp_path,
)
== 0
)
output_path = tmp_path.joinpath(f"{DEFAULT_VIDEO_NAME}.qp")
assert os.path.exists(output_path)
assert output_path.read_text() == EXPECTED_QP_CONTENTS[1:]
def test_cli_save_keyframes(tmp_path: Path):
"""Test `save-keyframes` command."""
EXPECTED_KEYFRAMES_CONTENTS = """# keyframe format v1
fps 0
0
90
"""
assert (
invoke_scenedetect(
"-i {VIDEO} time -e 95 {DETECTOR} save-keyframes",
output_dir=tmp_path,
)
== 0
)
output_path = tmp_path / f"{DEFAULT_VIDEO_NAME}-keyframes.txt"
assert output_path.exists()
assert output_path.read_text() == EXPECTED_KEYFRAMES_CONTENTS
def test_cli_save_keyframes_start_offset(tmp_path: Path):
"""Test `save-keyframes` command"""
EXPECTED_KEYFRAMES_CONTENTS = """# keyframe format v1
fps 0
0
90
"""
assert (
invoke_scenedetect(
"-i {VIDEO} time -s 51 -e 95 {DETECTOR} save-keyframes",
output_dir=tmp_path,
You can’t perform that action at this time.
