-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcaps.py
More file actions
1232 lines (1001 loc) · 40.2 KB
/
caps.py
File metadata and controls
1232 lines (1001 loc) · 40.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
# TODO add function to guess media type given extension
import logging
logger = logging.getLogger("ffmpegio")
import re, fractions, subprocess as sp
from collections import namedtuple
from fractions import Fraction
from functools import partial
from .path import ffmpeg as _ffmpeg
from .errors import FFmpegError
# fmt:off
__all__ = ["options", "filters", "codecs", "coders", "formats", "devices",
"muxers", "demuxers", "bsfilters", "protocols", "pix_fmts", "sample_fmts",
"layouts", "colors", "demuxer_info", "muxer_info", "encoder_info",
"decoder_info", "filter_info", "bsfilter_info", "frame_rate_presets",
"video_size_presets"]
# fmt:on
_ffCodecRegexp = re.compile(
r"([D.])([E.])([VAS])([I.])([L.])([S.])\s+([^=\s][\S]*)\s+(.*)"
) # g
_ffEncodersRegexp = re.compile(r"\s+\(encoders:([^\)]+)\)")
_ffDecodersRegexp = re.compile(r"\s+\(decoders:([^\)]+)\)")
_coderRegexp = re.compile(
r"([VAS])([F.])([S.])([X.])([B.])([D.])\s+([^=\s]\S*)\s+(.*)"
) # g
_formatRegexp = re.compile(r"([D ]) *([E ]) +(\S+) +(.*)") # g
_filterRegexp = re.compile(
r"([T.])([S.])([C.])\s+(\S+)\s+(A+|V+|N|\|)->(A+|V+|N|\|)\s+(.*)"
) # g
_cache = dict()
def ffmpeg(gopts):
out = _ffmpeg(["-hide_banner", *gopts], stdout=sp.PIPE, encoding="utf-8")
if out.returncode or out.stdout.count("\n") == 1:
raise FFmpegError(out.stdout)
return out.stdout
def _(cap):
return (None, _cache[cap]) if (cap in _cache) else (ffmpeg([f"-{cap}"]), None)
def __(type, name):
return (
(None, _cache[type][name])
if (type in _cache and name in _cache[type])
else (ffmpeg(["-help", f"{type}={name}"]), None)
)
def options(type=None, name_only=False, return_desc=False):
"""get FFmpeg command options
:param type: specify option type to return, defaults to None
:type type: "per-file"\|"video"\|"audio"\|"subtitle"\|"general"\|"global"\|None, optional
:param name_only: True to only return option names, defaults to False
:type name_only: bool, optional
:param return_desc: True to also return option description, defaults to False
:type return_desc: bool, optional
:return: dict of types of options
:rtype: dict(dict or tuple) if type not specified
"""
try:
opts = _cache["options"]
except:
lines = ffmpeg(["-help", "long"]).split("\n")
ginds = [
(i + 1, l[:-1].lower())
for i, l in enumerate(lines)
if len(l) and l[0] not in "- \t" and l[-1] == ":"
]
ginds.append((len(lines) + 1, None))
def parse_line(s):
m = re.match(r"\s*-(.+?) ([^ ]+?)? {2,}(.*)$", s)
return (m[1], m[2], m[3]) if m else None
raw_opts = (
(
l,
{
o[0]: o[1:]
for o in (parse_line(s) for s in lines[i0 : i1 - 1])
if o is not None
},
)
for (i0, l), (i1, _) in zip(ginds[:-1], ginds[1:])
)
opts = {
"video": {},
"audio": {},
"subtitle": {},
"general": {},
"global": {"overwrite": ("bool", "[ffmpegio] combining -y/-n options")},
}
for gname, gopts in raw_opts:
if "video" in gname:
opts["video"].update(gopts)
elif "audio" in gname:
opts["audio"].update(gopts)
elif "subtitle" in gname:
opts["subtitle"].update(gopts)
elif "per-file" in gname:
opts["general"].update(gopts)
else:
opts["global"].update(gopts)
_cache["options"] = opts
if type == "per-file":
opts = {
"per-file": {
k: v for t, o in opts.items() if t != "global" for k, v in o.items()
}
}
return (
({t: tuple(o) for t, o in opts.items()} if type is None else tuple(opts[type]))
if name_only
else (
(
opts
if return_desc
else {t: {k: v[0] for k, v in o.items()} for t, o in opts.items()}
)
if type is None
else (
opts[type] if return_desc else {k: v[0] for k, v in opts[type].items()}
)
)
)
# fmt:off
FilterSummary = namedtuple(
"FilterSummary",
["description", "input", "num_inputs", "output", "num_outputs",
"timeline_support", "slice_threading", "command_support"],
)
# fmt:on
def filters(type=None):
"""get FFmpeg filters
:param type: specify input or output stream type, defaults to None
:type type: 'audio'|'video'|'dynamic', optional
:return: dict of summary of the filters
:rtype: dict(key,FilterSummary)
Each key of the returned dict is a name of a filter and its value is a
FilterSummary namedtuple with the following items:
================ ======== ===============================================
Key type description
================ ======== ===============================================
description str Short description of the filter
input str Input stream type: 'audio'|'video'|'dynamic'
num_inputs int|None Number of inputs or None if 'dynamic'
output str Output stream type: 'audio'|'video'|'dynamic'
num_outputs int|None Number of outputs or None if 'dynamic'
timeline_support bool True if supports timeline editing
slice_threading bool True if supports threading
command_support bool True if supports command input from stdin
================ ======== ===============================================
"""
stdout, data = _("filters")
if not data:
types = {"A": "audio", "V": "video", "N": "dynamic", "|": "none"}
data = {}
for match in _filterRegexp.finditer(stdout):
intype = types[match[5][0]]
outtype = types[match[6][0]]
data[match[4]] = FilterSummary(
description=match[7],
input=intype,
num_inputs=0
if intype == "none"
else len(match[5])
if intype != "dynamic"
else None,
output=outtype,
num_outputs=0
if outtype == "none"
else len(match[6])
if outtype != "dynamic"
else None,
timeline_support=match[1] == "T",
slice_threading=match[2] == "S",
command_support=match[3] == "C",
)
_cache["filters"] = data
if type is not None:
data = {k: v for k, v in data.items() if v.input == type or v.output == type}
return data
def codecs(type=None, stream_type=None):
"""get FFmpeg codecs
:param type: Specify to list only decoder or encoder, defaults to None
:type type: 'decoder'|'encoder', optional
:param stream_type: Specify to stream type, defaults to None
:type stream_type: 'audio'|'video'|'subtitle', optional
:return: summary of FFmpeg codecs
:rtype: dict
Each key of the returned dict is a name of a codec and its value is a dict
with the following items:
================ ========= ===============================================
Key type description
================ ========= ===============================================
type str Stream type: 'audio'|'video'|'subtitle'
description str Short description of the codec
can_decode bool True if FFmpeg can decode
decoders list(str) List of compatible decoders
can_encode bool True if FFmpeg can encode
encoders list(str) List of compatible encoders
intra_frame_only bool True if codec only uses intra-frame coding
is_lossy bool True if codec can do lossy compression
is_lossless bool True if codec can do lossless compression
================ ========= ===============================================
"""
stdout, data = _("codecs")
if not data:
data = {}
for match in _ffCodecRegexp.finditer(stdout):
stype = {"V": "video", "A": "audio", "S": "subtitle"}[match[3]]
desc = match[8]
encoders = _ffEncodersRegexp.match(desc)
if encoders:
desc = desc.slice(0, encoders.index) + desc.slice(
encoders.index + encoders[0].length
)
encoders = encoders[1].trim().split(" ") if encoders else None
decoders = _ffDecodersRegexp.match(desc)
if decoders:
desc = desc.slice(0, decoders.index) + desc.slice(
decoders.index + decoders[0].length
)
decoders = decoders[1].trim().split(" ") if decoders else None
data[match[7]] = {
"type": stype,
"description": desc,
"can_decode": match[1] == "D",
"decoders": decoders,
"can_encode": match[2] == "E",
"encoders": encoders,
"intra_frame_only": match[4] == "I",
"is_lossy": match[5] == "L",
"is_lossless": match[6] == "S",
}
if not encoders:
del data[match[7]]["encoders"]
if not decoders:
del data[match[7]]["decoders"]
_cache["codecs"] = data
# return all if no argument specified
if type is None and stream_type is None:
return data
decoder = type is not None and type == "decoder"
encoder = type is not None and type == "encoder"
stype = stream_type is not None
def pick(entry):
return (
(decoder and entry["can_decode"]) or (encoder and entry["can_encode"])
) and (stype and stream_type == entry["type"])
return {k: v for k, v in data.items() if pick(v)}
def encoders(type=None):
"""get summary of FFmpeg encoders
:param type: specify stream type, defaults to None
:type type: 'audio'|'video'|'subtitle', optional
:return: list of encoders
:rtype: dict
Each key of the returned dict is a name of a decoder or encoder and its
value is a dict with the following items:
================ ==== ===============================================
Key type description
================ ==== ===============================================
type str Stream type: 'audio'|'video'|'subtitle'
description str Short description of the coder
frame_mt bool True if employs frame-level multithreading
slice_mt bool True if employs slice-level multithreading
experimental bool True if experimental encoder
draw_horiz_band bool True if supports draw_horiz_band
directRendering bool True if supports direct encoding method 1
================ ==== ===============================================
"""
return _coders("encoders", type)
def decoders(type=None):
"""get summary of FFmpeg decoders
:param stream_type: specify stream type, defaults to None
:type stream_type: 'audio'|'video'|'subtitle', optional
:return: list of decoders or encoders
:rtype: dict
Each key of the returned dict is a name of a decoder and its
value is a dict with the following items:
================ ==== ===============================================
Key type description
================ ==== ===============================================
type str Stream type: 'audio'|'video'|'subtitle'
description str Short description of the coder
frame_mt bool True if employs frame-level multithreading
slice_mt bool True if employs slice-level multithreading
experimental bool True if experimental encoder
draw_horiz_band bool True if supports draw_horiz_band
directRendering bool True if supports direct encoding method 1
================ ==== ===============================================
"""
return _coders("decoders", type)
def _coders(type, stream_type=None):
# reversed fftools/comdutils.c show_encoders()
stdout, data = _(type)
if not data:
data = {}
for match in _coderRegexp.finditer(stdout):
stype = {"V": "video", "A": "audio", "S": "subtitle"}[match[1]]
data[match[7]] = {
"type": stype,
"description": match[8],
"frame_mt": match[2] == "F",
"slice_mt": match[3] == "S",
"experimental": match[4] == "X",
"draw_horiz_band": match[5] == "B",
"directRendering": match[6] == "D",
}
_cache[type] = data
if stream_type is not None:
data = {k: v for k, v in data.items() if v["type"] == stream_type}
return data
# / **
# * reversed fftools/comdutils.c show_formats()
# * /
def formats():
"""get FFmpeg formats
:return: list of formats
:rtype: dict
Each key of the returned dict is a name of a format and its value is a dict
with the following items:
================ ==== ===============================================
Key type description
================ ==== ===============================================
description str Short description of the format
can_demux bool True if supports inputs of this format
can_mux bool True if support outputs of this format
================ ==== ===============================================
"""
return _getFormats("formats", True)
def devices(type=None):
"""get FFmpeg devices
:param type: specify source or sink type, defaults to None
:type type: 'source'|'sink', optional
:return: list of devices
:rtype: dict
Each key of the returned dict is a name of a device and its value is a dict
with the following items:
================ ==== ===============================================
Key type description
================ ==== ===============================================
description str Short description of the device
can_demux bool True if supports inputs of this format
can_mux bool True if support outputs of this format
================ ==== ===============================================
"""
devs = _getFormats("devices", True)
if type:
try:
key = {"source": "can_demux", "sink": "can_mux"}[type]
except:
raise ValueError(f'type must be either "source" or "sink"')
return {k: v for k, v in devs.items() if v[key]}
return devs
def muxers():
"""get FFmpeg muxers
:return: list of muxers
:rtype: dict
Each key of the returned dict is a name of a muxer and its value is a dict
with the following items:
================ ==== ===============================================
Key type description
================ ==== ===============================================
description str Short description of the muxer
================ ==== ===============================================
"""
return _getFormats("muxers", False)
def demuxers():
"""get FFmpeg demuxers
:return: list of demuxers
:rtype: dict
Each key of the returned dict is a name of a demuxer and its value is a dict
with the following items:
================ ==== ===============================================
Key type description
================ ==== ===============================================
description str Short description of the demuxer
================ ==== ===============================================
"""
return _getFormats("demuxers", False)
def _getFormats(type, doCan):
stdout, data = _(type)
if data:
return data
data = {}
for match in _formatRegexp.finditer(stdout):
for format in match[3].split(","):
if not (format in data):
data[format] = {"description": match[4]}
if doCan:
data[format]["can_demux"] = match[1] == "D"
data[format]["can_mux"] = match[2] == "E"
_cache[type] = data
return data
# // reversed fftools/comdutils.c show_bsfs()
def bsfilters():
"""get list of FFmpeg bitstream filters
:return: list of bistream filters
:rtype: list(str)
"""
stdout, data = _("bsfs")
if data:
return data
m = re.match(r"\s*Bitstream filters:\s+([\s\S]+)\s*", stdout)
_cache["bsfs"] = re.split(r"\s*\n\s*", m[1].strip())
return _cache["bsfs"]
# // reversed fftools/comdutils.c show_protocols()
def protocols():
"""get list of supported protocols
:return: list of protocols
:rtype: dict
Returned dict has 'input' and 'output' keys and each contains a list of
supported protocol names.
"""
stdout, data = _("protocols")
if data:
return data
match = re.search(r"Input:\s+([\s\S]+)Output:\s+([\s\S]+)", stdout)
_cache["protocols"] = dict(
input=re.split(r"\s*\n\s*", match[1]), output=re.split(r"\s*\n\s*", match[1])
)
return _cache["protocols"]
# // according to fftools/comdutils.c show_pix_fmts()
def pix_fmts():
"""get supported pixel formats
:return: list of supported pixel formats
:rtype: dict
Each key of the returned dict is a name of a pix_fmt and its value is a dict
with the following items:
============== ==== ===============================================
Key type description
============== ==== ===============================================
nb_components int Number of color components
bits_per_pixel int Number of bits per pixel
input bool True if can be used as an input option
output bool True if can be used as an output option
hw_accel bool True if supported by hardware accelerators
paletted bool True if uses paletted colors
bitstream bool True if can be used with bistreams
============== ==== ===============================================
"""
stdout, data = _("pix_fmts")
if data:
return data
data = {
match[6]: dict(
nb_components=int(match[7]),
bits_per_pixel=int(match[8]),
input=match[1] == "I",
output=match[2] == "O",
hw_accel=match[3] == "H",
paletted=match[4] == "P",
bitstream=match[5] == "B",
)
for match in re.finditer(
r"([I.])([O.])([H.])([P.])([B.])\s+(\S+)\s+(\d+)\s+(\d+)", stdout
)
}
_cache["pix_fmts"] = data
return data
def sample_fmts():
"""get supported audio sample formats
:return: list of supported audio sample formats
:rtype: dict
Each key of the returned dict is a name of a sample_fmt and its value
is the number of bits per sample.
"""
# // according to fftools/comdutils.c show_sample_fmts()
stdout, data = _("sample_fmts")
if not data:
_cache["sample_fmts"] = data = {
match[1]: int(match[2]) for match in re.finditer(r"(\S+)\s+(\d+)", stdout)
}
return data
def layouts():
"""get supported audio channel layouts
:return: list of supported audio channel layouts
:rtype: dict
Returned dict has two keys "channels" and "layouts". The value of "channels"
is a dict of possible channel names as keys and their descriptions as values.
The value of "layouts" is also a dict, which keys specifies the names and
their value strs indicate the combinations of channels (their names are
"+"ed).
"""
# // according to fftools/comdutils.c show_layouts()
stdout, data = _("layouts")
if data:
return data
match = re.match(
r"\s*Individual channels:\s+NAME\s+DESCRIPTION\s+(\S[\s\S]+)Standard channel layouts:\s+NAME\s+DECOMPOSITION\s+(\S[\s\S]+)",
stdout,
)
data = dict(
channels={
m[1]: m[2] for m in re.finditer(r"(\S+)\s+\s([\s\S]+?)\s*\n", match[1])
},
layouts={
m[1]: m[2] for m in re.finditer(r"(\S+)\s+(\S[\s\S]+?)\s*\n", match[2])
},
)
_cache["layouts"] = data
return data
def colors():
"""get recognized color names
:return: list of color names
:rtype: dict
The keys of the returned dict are the name of the colors and their values
are the RGB hex strs.
"""
# // according to fftools/comdutils.c show_colors()
stdout, data = _("colors")
if data:
return data
data = {
match[1]: match[2]
for match in re.finditer(r"(\S+)\s+(\#[0-9a-f]{6})\s*?\n", stdout)
}
_cache["colors"] = data
return data
def demuxer_info(name):
"""get detailed info of a media demuxer
:return: list of features
:rtype: dict
The returned dict has following entries:
============== ========= ================================================
Key type description
============== ========= ================================================
names list(str) List of compatible short names
long_name str Common long name
extensions list(str) List of associated common extensions (w/out '.')
options str Unparsed string, listing supported options
============== ========= ================================================
"""
# // according to fftools/comdutils.c show_help_demuxer()
stdout, data = __("demuxer", name)
if data:
return data
m = re.match(
r"Demuxer (\S+) \[([^\]]+)\]:\s*?\n(?: Common extensions: ([^.]+)\.\s*\n)?([\s\S]*)",
stdout,
)
data = dict(
names=m[1].split(","),
long_name=m[2],
extensions=m[3].split(",") if m[3] else [],
options=m[4],
)
if not "demuxer" in _cache:
_cache["demuxer"] = {}
_cache["demuxer"][name] = data
return data
def muxer_info(name):
"""get detailed info of a media muxer
:return: list of features
:rtype: dict
The returned dict has following entries:
=============== ========= ================================================
Key type description
=============== ========= ================================================
names list(str) List of compatible short names
long_name str Common long name
extensions list(str) List of associated common extensions (w/out '.')
mime_types list(str) List of associated MIME types
video_codecs list(str) List of supported video codecs
audio_codecs list(str) List of supported audio codecs
subtitle_codecs list(str) List of supported subtitle codecs
options str Unparsed string, listing supported options
=============== ========= ================================================
"""
# // according to fftools/comdutils.c show_help_muxer()
stdout, data = __("muxer", name)
if data:
return data
m = re.match(
r"Muxer (\S+) \[([^\]]+)\]:\s*?\n(?: Common extensions: ([^.]+)\.\s*?\n)?(?: Mime type: ([^.]+)\.\s*?\n)?(?: Default video codec: ([^.]+)\.\s*?\n)?(?: Default audio codec: ([^.]+)\.\s*?\n)?(?: Default subtitle codec: ([^.]+).\s*?\n)?([\s\S]*)",
stdout,
)
data = {
"names": m[1].split(","),
"long_name": m[2],
"extensions": m[3].split(",") if m[3] else [],
"mime_types": m[4].split(",") if m[4] else [],
"video_codecs": m[5].split(",") if m[5] else [],
"audio_codecs": m[6].split(",") if m[6] else [],
"subtitle_codecs": m[7].split(",") if m[7] else [],
"options": m[8],
}
if not "muxer" in _cache:
_cache["muxer"] = {}
_cache["muxer"][name] = data
return data
def encoder_info(name):
"""get detailed info of an encoder
:return: list of features
:rtype: dict
The returned dict has following entries:
====================== ============== ================================================
Key type description
====================== ============== ================================================
name list(str) Short names
long_name str Long name
capabilities list(str) List of supported capabilities
threading list(str) List of threading capabilities
supported_hwdevices list(str) List of supported hardware accelerators
supported_framerates list(Fraction) List of supported video frame rates
supported_pix_fmts list(str) List of supported video pixel formats
supported_sample_rates list(int) List of supported audio sample rates
supported_sample_fmts list(str) List of supported audio sample formats
supported_layouts list(str) List of supported audio channel layouts
options str Unparsed string, listing supported options
====================== ============== ================================================
"""
return _getCodecInfo(name, True)
def decoder_info(name):
"""get detailed info of a decoder
:return: list of features
:rtype: dict
The returned dict has following entries:
====================== ============== ================================================
Key type description
====================== ============== ================================================
name list(str) Short names
long_name str Long name
capabilities list(str) List of supported capabilities
threading list(str) List of threading capabilities
supported_hwdevices list(str) List of supported hardware accelerators
supported_framerates list(Fraction) List of supported video frame rates
supported_pix_fmts list(str) List of supported video pixel formats
supported_sample_rates list(int) List of supported audio sample rates
supported_sample_fmts list(str) List of supported audio sample formats
supported_layouts list(str) List of supported audio channel layouts
options str Unparsed string, listing supported options
====================== ============== ================================================
"""
return _getCodecInfo(name, False)
def _getCodecInfo(name, encoder):
# // according to fftools/comdutils.c show_help_codec()
stdout, data = __("encoder" if encoder else "decoder", name)
if data:
return data
type = "Encoder" if encoder else "Decoder"
m = re.search(
type
+ r" (\S+) \[([^\]]*)\]:\s*?\n"
+ r" General capabilities: ([^\r\n]+?)\s*?\n"
+ r"(?: Threading capabilities: ([^\r\n]+?)\s*?\n)?"
+ r"(?: Supported hardware devices: ([^\r\n]*?)\s*?\n)?"
+ r"(?: Supported framerates: ([^\r\n]+?)\s*?\n)?"
+ r"(?: Supported pixel formats: ([^\r\n]+?)\s*?\n)?"
+ r"(?: Supported sample rates: ([^\r\n]+?)\s*?\n)?"
+ r"(?: Supported sample formats: ([^\r\n]+?)\s*?\n)?"
+ r"(?: Supported channel layouts: ([^\r\n]+?)\s*?\n)?"
+ r"([\s\S]*)",
stdout,
)
def resolveFs(s):
m = re.match(r"(\d+)\/(\d+)", s)
return fractions.Fraction(int(m[1]), int(m[2]))
_re_layouts = re.compile(
re.sub(r"([().])", r"\\\1", "|".join(layouts()["layouts"]))
+ r"|\d+ channels \(.+?\)"
)
data = {
"name": m[1],
"long_name": m[2],
"capabilities": m[3].split(" ") if m[3] and m[3] != "none" else [],
"threading": m[4].split(" and ") if m[4] and m[4] != "none" else [],
"supported_hwdevices": m[5].split(" ") if m[5] else [],
"supported_framerates": [resolveFs(s) for s in m[6].split(" ")] if m[6] else [],
"supported_pix_fmts": m[7].split(" ") if m[7] else [],
"supported_sample_rates": [int(v) for v in m[8].split(" ")] if m[8] else [],
"supported_sample_fmts": m[9].split(" ") if m[9] else [],
"supported_layouts": _re_layouts.findall(m[10]) if m[10] else [],
"options": m[11],
}
if not "muxer" in _cache:
_cache["muxer"] = {}
_cache["muxer"][name] = data
return data
# fmt: off
FilterInfo = namedtuple(
"FilterInfo",
[ "name", "description", "threading", "inputs", "outputs",
"options", "extra_options", "timeline_support",
],
)
FilterOption = namedtuple(
"FilterOption",
["name", "aliases", "type", "help", "ranges", "constants", "default",
"video", "audio", "runtime"],
)
# fmt:on
def _get_filter_pad_info(str):
if str.startswith(" dynamic"):
return None
elif str.startswith(" none"):
return []
matches = re.finditer(r" #\d+: (\S+)(?= \() \((\S+)\)\s*?(?:\n|$)", str)
if not matches:
raise Exception("Failed to parse filter port info: %s" % str)
return [{"name": m[1], "type": m[2]} for m in matches]
def _conv_func(type, s):
try:
return type(s)
except:
return s
def _get_filter_option_constant(str):
m = re.match(
r" ([^ \n]+) {1,16}(?:([^ ]+) {1,12}| {13})"
r"[.E][.D][.F][.V][.A][.S][.X][.R][.B][.T][.P]"
r"(?: (.+))?\n?",
str,
)
return m[1], (m[2] and int(m[2]), m[3] or "")
def _get_filter_option(str, name):
# libavutil/opt.c/opt_list
lines = str.splitlines()
# first line is the main option definition
m0 = re.match(
r" (?: |-)?([^ \n]+) {1,17}(?:\<([^ >]+)\> {1,12}| {13})"
r"[.E][.D][.F]([.V])([.A])[.S][.X][.R][.B]([.T])[.P]",
lines[0],
)
if not m0:
# likely deprecated
logger.info(
f"_get_filter_option(): invalid option line found for {name} filter. Likely deprecated:\n{lines[0]}"
)
return None
name, type, *flags = m0.groups()
m1 = re.search(r"( \(from \S+? to \S+?\))*(?: \(default (.+)\))?$", lines[0])
ranges_str, default = m1.groups()
help = lines[0][m0.end() + 1 : m1.start()]
if default:
if type == "string":
# remove quotes
default = default[1:-1]
elif type == "boolean":
default = {"true": True, "false": False}.get(default, default)
conv = (
partial(_conv_func, int)
if type in ("int", "int64", "uint64")
else partial(_conv_func, float)
if type in ("float", "double")
else partial(_conv_func, Fraction)
if type == "rational"
else (lambda s: s)
)
ranges = (
None
if ranges_str is None
else [
(conv(m[1]), conv(m[2]))
for m in re.finditer(r"\(from (\S+?) to (\S+?)\)", ranges_str)
]
)
constants = [_get_filter_option_constant(l) for l in lines[1:] if l]
if len(constants):
# combines aliases
def chk_is_alias(i, o):
other = constants[i]
return other[1] == o[1]
has_alias = [chk_is_alias(i, o) for i, o in enumerate(constants[1:])]
has_alias.append(False)
for i, has in enumerate(has_alias):
k, v = constants[i]
constants[i] = (k, (constants[i + 1][0] if has else None, *v))
has_alias.insert(0, False)
constants = [o for o, isa in zip(constants, has_alias[:-1]) if not isa]
return FilterOption(
name,
[],
type,
help,
ranges,
dict(constants),
conv(default),
*(fl != "." for fl in flags),
)
def _get_filter_options(str):
m = re.match(r"(.+)? AVOptions:\n", str)
name = m[1]
blocks = re.split(r"\n(?! |\n|$)", str[m.end() :])
opts = [_get_filter_option(line, name) for line in blocks if line]
# combines aliases
def is_alias(i, o):
other = opts[i]
return other.type == o.type and other.help == o.help
n = len(opts)
i = 0
alias_of = [-1] * n
for j, o in enumerate(opts[1:]):
if is_alias(i, o):
alias_of[j + 1] = i
else:
i = j + 1
im = [*[i for i, j in enumerate(alias_of) if j < 0], n]
for i0, i1 in zip(im[:-1], im[1:]):
if i1 - i0 > 1:
v = list(opts[i0])
v[1] = [o.name for o in opts[i0 + 1 : i1]]
opts[i0] = FilterOption(*v)
opts = [o for o, isa in zip(opts, alias_of) if isa < 0]
return name, opts