-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo
More file actions
executable file
·2053 lines (1824 loc) · 83.6 KB
/
Copy pathvideo
File metadata and controls
executable file
·2053 lines (1824 loc) · 83.6 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
#!/usr/bin/env python3
"""
video - unified video tool backed by ffmpeg
Subcommands:
catalog [-o OUTPUT] DIR
scan a directory tree and write an HTML report
clamp [-s START] [-e END] [-o OUTPUT] FILE
cut to a time range; start and end are optional
(omit -s to start from the beginning, omit -e to
go to the end of the video)
concat [-o OUTPUT] FILE...
join videos of the same format and resolution
convert [-f FORMAT] [-o OUTPUT] FILE
transcode to a target format (default: H.264/AAC MP4)
formats [--all] explain supported container formats and codecs,
check availability in the installed ffmpeg,
and show current config defaults
info [--json] FILE print detailed file, container and stream info
(codec, profile, resolution, aspect ratio, fps,
colour space, bit depth, bitrate, channels,
tags, and more; --json for raw ffprobe output)
normalise [-n] [-l N] [-f] DIR
batch-normalise a directory tree to a web-friendly
format (H.264/AAC MP4 at 720p); deinterlaces CRT
footage and upscales low-res content via lanczos;
-n dry-run: writes a full HTML assessment report
(green/red per criterion) without converting;
-l N stop after converting N files (re-run to continue)
thumb [-t TIME] [-H PX] [-o OUTPUT] FILE
extract a single frame as a PNG image
Run `video <subcommand> -h` for per-command help.
"""
import argparse
import configparser
import datetime
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
LOG = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING)
# ---------------------------------------------------------------------------
# Config schema
# Each entry: (key, default, description).
# Consumed by `bcconfig --init` to generate a .bcconfig template.
# Defaults here must match the fallbacks used in _vcfg() / gcfg() calls below.
#
# Default encoding rationale
# --------------------------
# Goal: quality archive of mixed-source footage (480p–1080p) that won't be
# played on 4K screens. Priority is good quality at reasonable file size;
# encode time is secondary since files are encoded once.
#
# video_codec = libx264 (H.264)
# Universal hardware decode support on every GPU, phone, and browser.
# VP9/WebM and H.265 have patchier hardware decoders, which matters when
# playing multiple streams simultaneously. H.264 is the safe archive choice.
#
# video_crf = 20
# CRF 23 is the ffmpeg default but is tuned for web delivery (acceptable
# quality, small files). CRF 20 is noticeably better quality (~50% larger
# than CRF 23) while still compressing bloated/inefficient sources hard.
# CRF 18 would be near-lossless but produces unnecessarily large files.
#
# video_preset = slow
# At the same CRF, a slower preset finds more efficient ways to encode,
# producing smaller files at identical quality. Since we encode once and
# play back many times, the extra encode time is worth it. `slow` gives
# most of the benefit of `slower`/`veryslow` without extreme encode times.
#
# audio_codec = aac / audio_bitrate = 160k
# AAC has universal container and device support. 160k is a meaningful step
# up from 128k for archive quality with negligible extra storage cost.
# 192k+ offers diminishing returns for typical speech/mixed audio.
#
# target_height = 720 (normalise default)
# Acts as a ceiling, not a target. Videos taller than 720p are scaled down
# to 720p (width auto-calculated from source aspect ratio, scale=-2:720,
# lanczos). Videos at or below 720p are left at their original resolution.
# This preserves 480p sources at 480p — upscaling would add no real quality
# and wastes storage. AI upscaling (e.g. Real-ESRGAN) is a known future
# improvement for 480p content but requires a separate tool.
# ---------------------------------------------------------------------------
BCCONFIG_SCHEMA = {
"video": [
("default_format", "mp4", "Default container format: mp4, mkv, mov, webm"),
],
"video.convert": [
("video_codec", "libx264", "Video codec: libx264, libx265, libvpx-vp9"),
("video_preset", "slow", "Encoding speed/compression: ultrafast … veryslow"),
("video_crf", "20", "Quality (lower = better): libx264 18–28, libx265 24–28"),
("audio_codec", "aac", "Audio codec: aac, libmp3lame, libopus"),
("audio_bitrate", "160k", "Audio bitrate (e.g. 128k, 192k, 256k)"),
],
"video.thumb": [
("time", "00:00:01", "Default timestamp for frame extraction (HH:MM:SS or seconds)"),
],
"video.normalise": [
("format", "mp4", "Target container format: mp4, mkv, mov, webm"),
("target_height", "720", "Maximum height in pixels; taller videos are scaled down (aspect preserved), shorter videos are left as-is"),
("video_codec", "libx264", "Video codec: libx264, libx265, libvpx-vp9"),
("audio_codec", "aac", "Audio codec: aac, libmp3lame, libopus"),
("video_preset", "slow", "Encoding speed/compression: ultrafast … veryslow"),
("video_crf", "20", "Quality (lower = better): libx264 18–28, libx265 24–28"),
("audio_bitrate", "160k", "Audio bitrate (e.g. 128k, 192k, 256k)"),
("original_dir", "/tmp/video-originals", "Where to move originals before transcoding"),
("deinterlace", "auto", "Deinterlace: auto (detect), yes, no"),
],
}
def _schema_for_metadata():
sections = {}
for section, entries in BCCONFIG_SCHEMA.items():
sections[section] = [
{"key": key, "default": default, "description": desc}
for key, default, desc in entries
]
return sections
def bc_metadata():
"""Return machine-readable command metadata for bcui/bcconfig discovery."""
return {
"schema_version": 1,
"name": "video",
"summary": "ffmpeg-backed video tools",
"command_style": "subcommands",
"config_sections": _schema_for_metadata(),
"subcommands": [
{
"name": "formats",
"summary": "Explain supported formats and codecs",
"safety": "read",
"args": [],
"options": [
{"name": "all", "flag": "--all", "kind": "boolean",
"label": "List all ffmpeg encoders"},
],
"artifacts": [],
},
{
"name": "info",
"summary": "Print detailed file, container, and stream information",
"safety": "read",
"args": [
{"name": "file", "label": "Video file", "kind": "path",
"required": True, "exists": True},
],
"options": [
{"name": "json", "flag": "--json", "kind": "boolean",
"label": "Raw ffprobe JSON"},
],
"artifacts": [
{"kind": "json", "source": "stdout", "when_option": "json"},
],
},
{
"name": "convert",
"summary": "Transcode a file using config defaults",
"safety": "write",
"args": [
{"name": "file", "label": "Video file", "kind": "path",
"required": True, "exists": True},
],
"options": [
{"name": "format", "flag": "--format", "short_flag": "-f",
"kind": "choice", "choices": ["mp4", "mkv", "mov", "webm"],
"config": "video.default_format"},
{"name": "height", "flag": "--height", "short_flag": "-H",
"kind": "integer", "label": "Height"},
{"name": "vcodec", "flag": "--vcodec", "kind": "string",
"label": "Video codec", "config": "video.convert.video_codec"},
{"name": "acodec", "flag": "--acodec", "kind": "string",
"label": "Audio codec", "config": "video.convert.audio_codec"},
{"name": "crf", "flag": "--crf", "kind": "integer",
"label": "CRF", "config": "video.convert.video_crf"},
{"name": "preset", "flag": "--preset", "kind": "string",
"config": "video.convert.video_preset"},
{"name": "abitrate", "flag": "--abitrate", "kind": "string",
"label": "Audio bitrate", "config": "video.convert.audio_bitrate"},
{"name": "output", "flag": "--output", "short_flag": "-o",
"kind": "path", "label": "Output file", "artifact": "video"},
],
"artifacts": [
{"kind": "video", "path_option": "output"},
],
},
{
"name": "concat",
"summary": "Join videos of the same format and resolution",
"safety": "write",
"args": [
{"name": "files", "label": "Video files", "kind": "path-list",
"required": True, "exists": True},
],
"options": [
{"name": "output", "flag": "--output", "short_flag": "-o",
"kind": "path", "label": "Output file", "artifact": "video"},
],
"artifacts": [
{"kind": "video", "path_option": "output"},
],
},
{
"name": "clamp",
"summary": "Cut a video to a time range",
"safety": "write",
"args": [
{"name": "file", "label": "Video file", "kind": "path",
"required": True, "exists": True},
],
"options": [
{"name": "start", "flag": "--start", "short_flag": "-s",
"kind": "string", "label": "Start time"},
{"name": "end", "flag": "--end", "short_flag": "-e",
"kind": "string", "label": "End time"},
{"name": "output", "flag": "--output", "short_flag": "-o",
"kind": "path", "label": "Output file", "artifact": "video"},
],
"artifacts": [
{"kind": "video", "path_option": "output"},
],
},
{
"name": "thumb",
"summary": "Extract a single frame as a PNG image",
"safety": "write",
"args": [
{"name": "file", "label": "Video file", "kind": "path",
"required": True, "exists": True},
],
"options": [
{"name": "time", "flag": "--time", "short_flag": "-t",
"kind": "string", "config": "video.thumb.time"},
{"name": "height", "flag": "--height", "short_flag": "-H",
"kind": "integer", "label": "Height"},
{"name": "output", "flag": "--output", "short_flag": "-o",
"kind": "path", "label": "Output PNG", "artifact": "image/png"},
],
"artifacts": [
{"kind": "image", "path_option": "output"},
],
},
{
"name": "catalog",
"summary": "Scan a directory tree and write an HTML report",
"safety": "write",
"args": [
{"name": "directory", "label": "Directory", "kind": "directory",
"required": True, "exists": True},
],
"options": [
{"name": "output", "flag": "--output", "short_flag": "-o",
"kind": "path", "label": "Output HTML", "artifact": "text/html"},
],
"artifacts": [
{"kind": "html", "path_option": "output"},
],
},
{
"name": "normalise",
"summary": "Batch-normalise a directory tree to a web-friendly format",
"safety": "write",
"args": [
{"name": "directory", "label": "Directory", "kind": "directory",
"required": True, "exists": True},
],
"options": [
{"name": "dry_run", "flag": "--dry-run", "short_flag": "-n",
"kind": "boolean", "label": "Dry run"},
{"name": "limit", "flag": "--limit", "short_flag": "-l",
"kind": "integer", "label": "Limit"},
{"name": "force", "flag": "--force", "short_flag": "-f",
"kind": "boolean", "label": "Force"},
{"name": "output", "flag": "--output", "short_flag": "-o",
"kind": "path", "label": "Output HTML", "artifact": "text/html"},
],
"artifacts": [
{"kind": "html", "path_option": "output"},
],
},
],
}
_BCCONFIG_NAME = ".bcconfig"
def _find_bcconfig_files(cwd=None):
"""Return list of .bcconfig file paths from ~ down to cwd (root first)."""
home = os.path.expanduser("~")
cwd = os.path.abspath(cwd or os.getcwd())
paths = []
home_cfg = os.path.join(home, _BCCONFIG_NAME)
if os.path.isfile(home_cfg):
paths.append(home_cfg)
try:
rel = os.path.relpath(cwd, home)
except ValueError:
return paths # different drive on Windows
if rel.startswith(".."):
return paths # cwd is outside home; only home config applies
parts = [p for p in rel.split(os.sep) if p and p != "."]
current = home
for part in parts:
current = os.path.join(current, part)
candidate = os.path.join(current, _BCCONFIG_NAME)
if os.path.isfile(candidate):
paths.append(candidate)
return paths
def _load_config(local_dir=None):
"""Load .bcconfig configuration via configparser.
Reads .bcconfig files from ~ down to local_dir (or cwd), merging them
so that closer-to-pwd values override parent values.
Returns a RawConfigParser instance; missing keys fall back gracefully.
"""
cfg = configparser.RawConfigParser()
files = _find_bcconfig_files(local_dir or os.getcwd())
cfg.read(files, encoding="utf-8")
return cfg
# Global config loaded once at import time.
# Subcommands that accept a directory load their own merged config at runtime.
_VIDEO_CFG = _load_config()
def _vcfg(section, key, fallback, cfg=None):
"""Return a value from [section]/key, falling back to *fallback*.
Uses the module-level global config unless *cfg* is supplied.
"""
return (cfg or _VIDEO_CFG).get(section, key, fallback=fallback)
# ---------------------------------------------------------------------------
# Dependency check
# ---------------------------------------------------------------------------
def _require(*tools):
missing = [t for t in tools if not _on_path(t)]
if missing:
sys.exit(
f"Error: required tool(s) not found on PATH: {', '.join(missing)}\n"
"Run 'bcinit' to install missing dependencies."
)
def _on_path(tool):
return shutil.which(tool) is not None
# ---------------------------------------------------------------------------
# ffmpeg / ffprobe helpers
# ---------------------------------------------------------------------------
def _run(cmd, check=True):
"""Run a command, streaming output to the terminal."""
LOG.debug("run: %s", " ".join(str(c) for c in cmd))
result = subprocess.run([str(c) for c in cmd], check=check)
return result.returncode
def _probe(path):
"""Return ffprobe JSON for *path*."""
cmd = [
"ffprobe", "-v", "quiet",
"-print_format", "json",
"-show_format", "-show_streams",
path,
]
out = subprocess.check_output([str(c) for c in cmd], stderr=subprocess.DEVNULL)
return json.loads(out)
def _default_output(path, suffix):
"""Derive an output filename from *path* with *suffix* appended before the extension."""
base, _ = os.path.splitext(os.path.basename(path))
return f"{base}{suffix}"
# Covers the major Unicode emoji blocks: misc symbols, pictographs, emoticons,
# transport, flags (regional indicators), variation selectors, ZWJ.
_EMOJI_RE = re.compile(
"["
"\U0001F300-\U0001F9FF" # Misc Symbols & Pictographs, Emoticons, Transport, Supplemental
"\U0001FA00-\U0001FAFF" # Symbols & Pictographs Extended-A
"\U00002600-\U000027BF" # Misc Symbols, Dingbats
"\U0001F1E0-\U0001F1FF" # Regional Indicator letters (flags)
"\uFE00-\uFE0F" # Variation Selectors
"\u200D" # Zero Width Joiner
"]+",
flags=re.UNICODE,
)
def _strip_emoji(s):
"""Remove emoji characters from *s* and normalise any resulting whitespace."""
cleaned = _EMOJI_RE.sub("", s)
# Collapse runs of whitespace left after removal; strip leading/trailing
return re.sub(r"[ \t]+", " ", cleaned).strip()
# ---------------------------------------------------------------------------
# Subcommands
# ---------------------------------------------------------------------------
def cmd_info(args):
_require("ffprobe")
if args.json:
data = _probe(args.file)
print(json.dumps(data, indent=2))
return
path = args.file
stat = os.stat(path)
data = _probe(path)
fmt = data.get("format", {})
streams = data.get("streams", [])
tags = fmt.get("tags", {})
# ---- helpers ----
W = 18 # label column width
HR = "─" * 54
def section(title):
print(f"\n\033[1m{title}\033[0m")
print(HR)
def field(label, value, note=""):
if value in (None, "", "unknown", "0", 0):
return
note_str = f" \033[2m({note})\033[0m" if note else ""
print(f" {label:<{W}} {value}{note_str}")
def ratio(raw):
"""'16:9' or fraction string → reduce and return, e.g. '16:9'."""
try:
a, b = (int(x) for x in raw.replace(":", "/").split("/"))
from math import gcd
g = gcd(a, b)
return f"{a//g}:{b//g}"
except Exception:
return raw
# ---- File ----
section("File")
field("Path", os.path.abspath(path))
field("Size", _fmt_size(stat.st_size),
f"{stat.st_size:,} bytes")
field("Modified", datetime.datetime.fromtimestamp(stat.st_mtime)
.strftime("%Y-%m-%d %H:%M:%S"))
# ---- Container ----
section("Container")
field("Format", fmt.get("format_long_name") or fmt.get("format_name"))
duration = float(fmt.get("duration") or 0)
if duration:
h, rem = divmod(int(duration), 3600)
m, s = divmod(rem, 60)
field("Duration", f"{h:02d}:{m:02d}:{s:02d}", f"{duration:.3f}s")
br = int(fmt.get("bit_rate") or 0)
field("Overall bitrate", f"{br // 1000} kb/s")
field("Streams", fmt.get("nb_streams"))
if tags:
for k in ("title", "comment", "artist", "album", "copyright",
"creation_time", "encoder", "major_brand"):
v = tags.get(k) or tags.get(k.upper())
if v:
field(k.replace("_", " ").title(), v)
# ---- Streams ----
vs_count = as_count = ss_count = 0
for s in streams:
ctype = s.get("codec_type", "data")
idx = s.get("index", "?")
codec = s.get("codec_name", "?")
stags = s.get("tags", {})
lang = stags.get("language") or stags.get("LANGUAGE") or ""
if ctype == "video":
vs_count += 1
section(f"Video stream #{idx}"
+ (f" [{lang}]" if lang else ""))
field("Codec", codec)
field("Profile", s.get("profile"))
field("Level", s.get("level"))
w, h = s.get("width", 0), s.get("height", 0)
if w and h:
field("Resolution", f"{w}×{h}")
dar = s.get("display_aspect_ratio", "")
if dar and dar != "0:1":
field("Aspect ratio", ratio(dar))
field("Pixel format", s.get("pix_fmt"))
field("Color space", s.get("color_space"))
field("Color range", s.get("color_range"))
field("Color primaries",s.get("color_primaries"))
field("Transfer", s.get("color_transfer"))
field("Bit depth", s.get("bits_per_raw_sample"),
"per channel")
avg = _fmt_fps(s.get("avg_frame_rate", ""))
r = _fmt_fps(s.get("r_frame_rate", ""))
fps_note = f"real base: {r}" if r and r != avg else ""
field("Frame rate", f"{avg} fps", fps_note)
fo = s.get("field_order", "")
field("Field order", fo if fo and fo != "unknown" else None)
if _is_interlaced(s):
field("Interlaced", "yes")
sbr = int(s.get("bit_rate") or 0)
field("Bitrate", f"{sbr // 1000} kb/s" if sbr else None)
frames = s.get("nb_frames") or s.get("nb_read_frames")
field("Frames", frames)
for k in ("title", "handler_name", "encoder"):
v = stags.get(k) or stags.get(k.upper())
if v:
field(k.replace("_", " ").title(), v)
elif ctype == "audio":
as_count += 1
section(f"Audio stream #{idx}"
+ (f" [{lang}]" if lang else ""))
field("Codec", codec)
field("Profile", s.get("profile"))
field("Sample rate", f"{s.get('sample_rate')} Hz"
if s.get("sample_rate") else None)
ch = s.get("channels")
layout = s.get("channel_layout", "")
field("Channels", f"{ch}"
+ (f" ({layout})" if layout else ""))
field("Bit depth", s.get("bits_per_sample") or
s.get("bits_per_raw_sample"),
"per sample")
abr = int(s.get("bit_rate") or 0)
field("Bitrate", f"{abr // 1000} kb/s" if abr else None)
for k in ("title", "handler_name"):
v = stags.get(k) or stags.get(k.upper())
if v:
field(k.replace("_", " ").title(), v)
elif ctype == "subtitle":
ss_count += 1
section(f"Subtitle stream #{idx}"
+ (f" [{lang}]" if lang else ""))
field("Codec", codec)
t = stags.get("title") or stags.get("TITLE")
field("Title", t)
else:
section(f"Stream #{idx} [{ctype}]")
field("Codec", codec)
print()
def cmd_convert(args):
_require("ffmpeg")
# All settings: explicit args win, then config, then hardcoded fallbacks
fmt = args.format.lower()
vcodec = args.vcodec or _vcfg("video.convert", "video_codec", "libx264")
acodec = args.acodec or _vcfg("video.convert", "audio_codec", "aac")
crf = str(args.crf if args.crf is not None else _vcfg("video.convert", "video_crf", "20"))
preset = args.preset or _vcfg("video.convert", "video_preset", "slow")
abitrate= args.abitrate or _vcfg("video.convert", "audio_bitrate", "160k")
SUPPORTED = {"mp4", "mkv", "mov", "webm"}
if fmt not in SUPPORTED:
sys.exit(f"Error: unsupported format '{fmt}'. Supported: {', '.join(sorted(SUPPORTED))}")
# webm needs its own codecs regardless of config/args
if fmt == "webm":
vcodec = "libvpx-vp9"
acodec = "libopus"
output = args.output or _default_output(args.file, f"_.{fmt}")
cmd = ["ffmpeg", "-i", args.file]
if args.height:
cmd += ["-vf", f"scale=-2:{args.height}"]
cmd += ["-vcodec", vcodec]
if vcodec in ("libx264", "libx265"):
cmd += ["-crf", crf, "-preset", preset]
cmd += ["-acodec", acodec, "-b:a", abitrate, output]
_run(cmd)
print(f"Converted: {output}")
# ---------------------------------------------------------------------------
# Formats reference data
# ---------------------------------------------------------------------------
_CONTAINER_INFO = {
"mp4": {
"full_name": "MPEG-4 Part 14",
"muxer": "mp4",
"browser": "Excellent — supported by every modern browser and device",
"use_cases": "Web delivery, general distribution, streaming, archival",
"notes": "Default choice. Requires moov atom at start for streaming; "
"ffmpeg adds -movflags +faststart automatically when writing to .mp4",
"vcodecs": "H.264 (libx264), H.265 (libx265), AV1",
"acodecs": "AAC, MP3, AC-3",
},
"mkv": {
"full_name": "Matroska",
"muxer": "matroska",
"browser": "Good — Chrome/Firefox; not Safari without plugin",
"use_cases": "Archival, multiple audio/subtitle tracks, any codec combination",
"notes": "Open container with no codec restrictions. Ideal when you need "
"multiple audio tracks or soft subtitles.",
"vcodecs": "Any (H.264, H.265, AV1, VP9, …)",
"acodecs": "Any (AAC, Opus, FLAC, …)",
},
"mov": {
"full_name": "QuickTime Movie",
"muxer": "mov",
"browser": "Good on macOS/Safari; limited elsewhere without codec support",
"use_cases": "Apple ecosystem, Final Cut Pro / DaVinci Resolve interchange, ProRes",
"notes": "Apple's native container. Shares most of the MP4 spec (both are "
"ISO Base Media File Format). Prefer MP4 for distribution.",
"vcodecs": "H.264, H.265, ProRes, DNxHD",
"acodecs": "AAC, PCM, ALAC",
},
"webm": {
"full_name": "WebM",
"muxer": "webm",
"browser": "Excellent in Chrome/Firefox; limited in Safari",
"use_cases": "Web video, open-source pipelines, smaller files at equivalent quality",
"notes": "Royalty-free container designed for the web. VP9+Opus gives "
"competitive quality to H.264+AAC at smaller sizes.",
"vcodecs": "VP8, VP9 (libvpx-vp9), AV1",
"acodecs": "Vorbis, Opus (libopus)",
},
}
_VCODEC_INFO = {
"libx264": {
"codec": "H.264 / AVC",
"standard": "ITU-T H.264, ISO/IEC 14496-10",
"quality": "CRF 18–28 (lower = better; 23 is default)",
"preset": "ultrafast → veryslow (speed vs compression; medium is default)",
"use_cases": "Universal default. Best compatibility across all devices and browsers.",
"notes": "Mature, fast encoder. Use CRF 18–20 for near-lossless archival, "
"23 for good web quality, 26–28 for small-but-acceptable files.",
},
"libx265": {
"codec": "H.265 / HEVC",
"standard": "ITU-T H.265, ISO/IEC 23008-2",
"quality": "CRF 24–28 (default 28; roughly equivalent quality to H.264 at half the bitrate)",
"preset": "ultrafast → veryslow (slower presets give significantly better compression)",
"use_cases": "4K/HDR archival, bandwidth-constrained delivery, future-proofing",
"notes": "~50% smaller than H.264 at the same quality, but slower to encode "
"and decode. Not universally supported (no Safari < macOS 10.13).",
},
"libvpx-vp9": {
"codec": "VP9",
"standard": "Google VP9 (open, royalty-free)",
"quality": "CRF 15–35; also supports -b:v 0 -crf N for constrained quality",
"preset": "Use -cpu-used 0–5 (0 = slowest/best, 4 = fast/default for web)",
"use_cases": "WebM/web delivery, YouTube, open-source pipelines",
"notes": "Royalty-free alternative to H.265. Good quality but slower to encode. "
"Pair with Opus audio for best results.",
},
}
_ACODEC_INFO = {
"aac": {
"codec": "Advanced Audio Coding",
"standard": "ISO/IEC 13818-7",
"bitrates": "96–320 kb/s stereo; 128 kb/s is a solid default",
"use_cases": "Universal — pairs with H.264/H.265 in MP4/MOV/MKV",
"notes": "The most compatible audio codec. AAC-LC is the standard profile; "
"ffmpeg uses the built-in aac encoder unless libfdk_aac is available.",
},
"libopus": {
"codec": "Opus",
"standard": "IETF RFC 6716 (open, royalty-free)",
"bitrates": "32–320 kb/s; transparent quality at ~128 kb/s stereo",
"use_cases": "WebM, open-source pipelines, low-bitrate speech/music",
"notes": "Best audio codec at low-to-medium bitrates. Royalty-free. "
"Required for WebM; also works in MKV.",
},
"libmp3lame": {
"codec": "MP3 / MPEG-1 Audio Layer III",
"standard": "ISO/IEC 11172-3",
"bitrates": "128–320 kb/s; 192 kb/s is the common quality threshold",
"use_cases": "Legacy compatibility, standalone audio files",
"notes": "Widely supported but technically inferior to AAC at the same bitrate. "
"Use AAC unless MP3 compatibility is specifically required.",
},
}
def _get_available_encoders():
"""Return a set of encoder names available in the installed ffmpeg."""
try:
out = subprocess.check_output(
["ffmpeg", "-encoders", "-v", "quiet"],
stderr=subprocess.DEVNULL,
).decode(errors="replace")
encoders = set()
for line in out.splitlines():
parts = line.split()
# Encoder lines: " V..... libx264 H.264 / AVC ..."
if len(parts) >= 2 and len(parts[0]) == 6 and parts[0][0] in "VAS":
encoders.add(parts[1])
return encoders
except Exception:
return set()
def _get_available_muxers():
"""Return a set of muxer names available in the installed ffmpeg."""
try:
out = subprocess.check_output(
["ffmpeg", "-muxers", "-v", "quiet"],
stderr=subprocess.DEVNULL,
).decode(errors="replace")
muxers = set()
for line in out.splitlines():
parts = line.split()
if len(parts) >= 2 and len(parts[0]) == 2 and "E" in parts[0]:
muxers.add(parts[1])
return muxers
except Exception:
return set()
def cmd_formats(args):
_require("ffmpeg")
GREEN = "\033[32m"
RED = "\033[31m"
YELLOW = "\033[33m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
HR = "─" * 60
W = 16
def section(title):
print(f"\n{BOLD}{title}{RESET}")
print(HR)
def field(label, value):
if value:
print(f" {label:<{W}} {value}")
def avail(name, available):
mark = f"{GREEN}✓ available{RESET}" if name in available \
else f"{RED}✗ not in this build{RESET}"
return mark
encoders = _get_available_encoders()
muxers = _get_available_muxers()
# ---- Tool versions ----
section("Tools")
field("ffmpeg", _tool_version("ffmpeg"))
field("ffprobe", _tool_version("ffprobe"))
# ---- Current config ----
section("Current config (~/.bcconfig)")
field("Default format", _vcfg("video", "default_format", "mp4"))
field("Video codec", _vcfg("video.convert", "video_codec", "libx264"))
field("Audio codec", _vcfg("video.convert", "audio_codec", "aac"))
field("CRF", _vcfg("video.convert", "video_crf", "20"))
field("Preset", _vcfg("video.convert", "video_preset", "slow"))
field("Audio bitrate", _vcfg("video.convert", "audio_bitrate", "160k"))
# ---- Container formats ----
section("Container formats")
for ext, info in _CONTAINER_INFO.items():
mark = f"{GREEN}✓{RESET}" if info["muxer"] in muxers else f"{RED}✗{RESET}"
print(f"\n {BOLD}.{ext}{RESET} {DIM}{info['full_name']}{RESET} {mark}")
print(f" {'Browser':<{W}} {info['browser']}")
print(f" {'Use cases':<{W}} {info['use_cases']}")
print(f" {'Video codecs':<{W}} {info['vcodecs']}")
print(f" {'Audio codecs':<{W}} {info['acodecs']}")
print(f" {'Notes':<{W}} {info['notes']}")
# ---- Video codecs ----
section("Video codecs")
for enc, info in _VCODEC_INFO.items():
mark = avail(enc, encoders)
print(f"\n {BOLD}{enc}{RESET} {DIM}{info['codec']}{RESET} {mark}")
print(f" {'Standard':<{W}} {info['standard']}")
print(f" {'Quality':<{W}} {info['quality']}")
print(f" {'Preset':<{W}} {info['preset']}")
print(f" {'Use cases':<{W}} {info['use_cases']}")
print(f" {'Notes':<{W}} {info['notes']}")
# ---- Audio codecs ----
section("Audio codecs")
for enc, info in _ACODEC_INFO.items():
mark = avail(enc, encoders)
print(f"\n {BOLD}{enc}{RESET} {DIM}{info['codec']}{RESET} {mark}")
print(f" {'Standard':<{W}} {info['standard']}")
print(f" {'Bitrates':<{W}} {info['bitrates']}")
print(f" {'Use cases':<{W}} {info['use_cases']}")
print(f" {'Notes':<{W}} {info['notes']}")
if args.all:
# ---- Full ffmpeg encoder list ----
section("All available encoders (ffmpeg -encoders)")
try:
out = subprocess.check_output(
["ffmpeg", "-encoders", "-v", "quiet"],
stderr=subprocess.DEVNULL,
).decode(errors="replace")
# Print from the "------" divider onwards
printing = False
for line in out.splitlines():
if line.startswith(" ---"):
printing = True
continue
if printing:
print(" ", line)
except Exception as e:
print(f" (error: {e})")
print()
def cmd_concat(args):
_require("ffmpeg")
output = args.output or "output.mp4"
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as flist:
for f in args.files:
flist.write(f"file '{os.path.abspath(f)}'\n")
flist_path = flist.name
try:
_run([
"ffmpeg", "-f", "concat", "-safe", "0",
"-i", flist_path,
"-vcodec", "libx264", "-acodec", "aac",
output,
])
print(f"Concatenated: {output}")
finally:
os.unlink(flist_path)
def cmd_clamp(args):
_require("ffmpeg")
output = args.output or _default_output(args.file, "_clamp.mp4")
cmd = ["ffmpeg", "-i", args.file]
if args.start:
cmd += ["-ss", args.start]
if args.end:
cmd += ["-to", args.end]
cmd += ["-vcodec", "libx264", "-acodec", "aac", output]
_run(cmd)
print(f"Clamped: {output}")
def cmd_thumb(args):
_require("ffmpeg")
output = args.output or _default_output(args.file, "_thumb.png")
timestamp = args.time or _vcfg("video.thumb", "time", "00:00:01")
cmd = ["ffmpeg", "-i", args.file, "-ss", timestamp, "-vframes", "1"]
if args.height:
# -2 keeps width even and maintains aspect ratio
cmd += ["-vf", f"scale=-2:{args.height}"]
cmd.append(output)
_run(cmd)
print(f"Thumbnail: {output}")
# ---------------------------------------------------------------------------
# Catalog helpers
# ---------------------------------------------------------------------------
VIDEO_EXTENSIONS = {
".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v", ".wmv",
".flv", ".mpg", ".mpeg", ".ts", ".mts", ".m2ts", ".3gp", ".ogv",
}
def _fmt_duration(secs):
secs = int(secs)
h, rem = divmod(secs, 3600)
m, s = divmod(rem, 60)
return f"{h:02d}:{m:02d}:{s:02d}"
def _fmt_size(nbytes):
for unit in ("B", "KB", "MB", "GB"):
if nbytes < 1024:
return f"{nbytes:.1f} {unit}"
nbytes /= 1024
return f"{nbytes:.1f} TB"
def _fmt_fps(raw):
"""Convert '30000/1001' style fraction to a clean decimal string."""
try:
num, den = raw.split("/")
fps = int(num) / int(den)
return f"{fps:.2f}".rstrip("0").rstrip(".")
except Exception:
return raw
def _catalog_probe(full_path, rel_path):
"""Probe one file and return a summary dict. Never raises."""
entry = {
"path": rel_path,
"size": os.path.getsize(full_path),
"error": None,
"format": "",
"duration": 0.0,
"bitrate": 0,
"video_codec": "",
"width": "",
"height": "",
"fps": "",
"audio_codec": "",
"channels": "",
"sample_rate": "",
}
try:
data = _probe(full_path)
fmt = data.get("format", {})
entry["format"] = fmt.get("format_name", "").split(",")[0]
entry["duration"] = float(fmt.get("duration") or 0)
entry["bitrate"] = int(fmt.get("bit_rate") or 0)
for stream in data.get("streams", []):
ctype = stream.get("codec_type")
if ctype == "video" and not entry["video_codec"]:
entry["video_codec"] = stream.get("codec_name", "")
entry["width"] = stream.get("width", "")
entry["height"] = stream.get("height", "")
entry["fps"] = _fmt_fps(stream.get("avg_frame_rate", ""))
elif ctype == "audio" and not entry["audio_codec"]:
entry["audio_codec"] = stream.get("codec_name", "")
entry["channels"] = stream.get("channels", "")
entry["sample_rate"] = stream.get("sample_rate", "")
except Exception as exc:
entry["error"] = str(exc)
return entry
def _catalog_html(directory, entries):
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
abs_dir = os.path.abspath(directory)
total_size = sum(e["size"] for e in entries)
total_duration = sum(e["duration"] for e in entries)
errors = sum(1 for e in entries if e["error"])
rows = []
for e in entries:
err_cell = f'<td class="err" title="{e["error"]}">error</td>' if e["error"] else ""
resolution = f'{e["width"]}×{e["height"]}' if e["width"] else "—"
fps = e["fps"] or "—"
audio = f'{e["audio_codec"]} {e["channels"]}ch' if e["audio_codec"] else "—"
bitrate = f'{e["bitrate"] // 1000} kb/s' if e["bitrate"] else "—"
duration = _fmt_duration(e["duration"]) if e["duration"] else "—"
size = _fmt_size(e["size"])
video_cell = f'{e["video_codec"]}<br><span class="sub">{resolution} · {fps} fps</span>' if e["video_codec"] else "—"
cells = [
f'<td class="path" title="{e["path"]}">{e["path"]}</td>',
f'<td class="r">{size}</td>',
f'<td class="r">{duration}</td>',
f'<td>{e["format"]}</td>',
f'<td>{video_cell}</td>',
f'<td>{audio}</td>',
f'<td class="r">{bitrate}</td>',
]
if e["error"]:
cells = [f'<td class="path err" colspan="7" title="{e["error"]}">{e["path"]} — probe error</td>']
rows.append(f'<tr>{"".join(cells)}</tr>')