nnilayy commited on
Commit
d604241
·
verified ·
1 Parent(s): 1d21f43

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. lib/python3.10/site-packages/arrow/_version.py +1 -0
  3. lib/python3.10/site-packages/arrow/constants.py +177 -0
  4. lib/python3.10/site-packages/arrow/util.py +117 -0
  5. lib/python3.10/site-packages/av/attachments/__init__.py +0 -0
  6. lib/python3.10/site-packages/av/attachments/stream.pxd +5 -0
  7. lib/python3.10/site-packages/av/attachments/stream.pyi +8 -0
  8. lib/python3.10/site-packages/av/attachments/stream.pyx +26 -0
  9. lib/python3.10/site-packages/av/audio/__init__.pxd +0 -0
  10. lib/python3.10/site-packages/av/audio/__init__.py +2 -0
  11. lib/python3.10/site-packages/av/audio/__init__.pyi +4 -0
  12. lib/python3.10/site-packages/av/audio/codeccontext.pxd +11 -0
  13. lib/python3.10/site-packages/av/audio/codeccontext.pyi +29 -0
  14. lib/python3.10/site-packages/av/audio/codeccontext.pyx +106 -0
  15. lib/python3.10/site-packages/av/audio/fifo.pxd +19 -0
  16. lib/python3.10/site-packages/av/audio/fifo.pyi +22 -0
  17. lib/python3.10/site-packages/av/audio/format.pxd +11 -0
  18. lib/python3.10/site-packages/av/audio/format.pyi +11 -0
  19. lib/python3.10/site-packages/av/audio/frame.pxd +31 -0
  20. lib/python3.10/site-packages/av/audio/frame.pyi +47 -0
  21. lib/python3.10/site-packages/av/audio/frame.pyx +187 -0
  22. lib/python3.10/site-packages/av/audio/layout.pxd +8 -0
  23. lib/python3.10/site-packages/av/audio/layout.pyi +12 -0
  24. lib/python3.10/site-packages/av/audio/layout.pyx +84 -0
  25. lib/python3.10/site-packages/av/audio/plane.pxd +8 -0
  26. lib/python3.10/site-packages/av/audio/plane.pyi +4 -0
  27. lib/python3.10/site-packages/av/audio/plane.pyx +11 -0
  28. lib/python3.10/site-packages/av/audio/resampler.pxd +21 -0
  29. lib/python3.10/site-packages/av/audio/resampler.pyi +20 -0
  30. lib/python3.10/site-packages/av/audio/resampler.pyx +119 -0
  31. lib/python3.10/site-packages/av/audio/stream.pyx +43 -0
  32. lib/python3.10/site-packages/av/codec/__init__.pxd +0 -0
  33. lib/python3.10/site-packages/av/codec/codec.pyi +115 -0
  34. lib/python3.10/site-packages/av/codec/context.pxd +64 -0
  35. lib/python3.10/site-packages/av/codec/context.pyx +672 -0
  36. lib/python3.10/site-packages/av/codec/hwaccel.pyx +156 -0
  37. lib/python3.10/site-packages/av/filter/__init__.py +3 -0
  38. lib/python3.10/site-packages/av/filter/__init__.pyi +4 -0
  39. lib/python3.10/site-packages/av/filter/context.pyi +18 -0
  40. lib/python3.10/site-packages/av/filter/context.pyx +134 -0
  41. lib/python3.10/site-packages/av/filter/filter.pxd +15 -0
  42. lib/python3.10/site-packages/av/filter/filter.pyi +23 -0
  43. lib/python3.10/site-packages/av/filter/filter.pyx +106 -0
  44. lib/python3.10/site-packages/av/filter/graph.pxd +22 -0
  45. lib/python3.10/site-packages/av/filter/graph.pyi +47 -0
  46. lib/python3.10/site-packages/av/filter/graph.pyx +224 -0
  47. lib/python3.10/site-packages/av/filter/link.pxd +16 -0
  48. lib/python3.10/site-packages/av/filter/link.pyi +5 -0
  49. lib/python3.10/site-packages/av/filter/link.pyx +53 -0
  50. lib/python3.10/site-packages/av/filter/loudnorm.pxd +4 -0
.gitattributes CHANGED
@@ -66,3 +66,5 @@ lib/python3.10/site-packages/propcache/_helpers_c.cpython-310-x86_64-linux-gnu.s
66
  lib/python3.10/site-packages/rpds/rpds.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
67
  lib/python3.10/site-packages/grpc/_cython/cygrpc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
68
  lib/python3.10/site-packages/fugashi.libs/libmecab-eada4a80.so.2.0.0 filter=lfs diff=lfs merge=lfs -text
 
 
 
66
  lib/python3.10/site-packages/rpds/rpds.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
67
  lib/python3.10/site-packages/grpc/_cython/cygrpc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
68
  lib/python3.10/site-packages/fugashi.libs/libmecab-eada4a80.so.2.0.0 filter=lfs diff=lfs merge=lfs -text
69
+ lib/python3.10/site-packages/av/utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
70
+ lib/python3.10/site-packages/av/plane.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
lib/python3.10/site-packages/arrow/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "1.3.0"
lib/python3.10/site-packages/arrow/constants.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constants used internally in arrow."""
2
+
3
+ import sys
4
+ from datetime import datetime
5
+
6
+ if sys.version_info < (3, 8): # pragma: no cover
7
+ from typing_extensions import Final
8
+ else:
9
+ from typing import Final # pragma: no cover
10
+
11
+ # datetime.max.timestamp() errors on Windows, so we must hardcode
12
+ # the highest possible datetime value that can output a timestamp.
13
+ # tl;dr platform-independent max timestamps are hard to form
14
+ # See: https://stackoverflow.com/q/46133223
15
+ try:
16
+ # Get max timestamp. Works on POSIX-based systems like Linux and macOS,
17
+ # but will trigger an OverflowError, ValueError, or OSError on Windows
18
+ _MAX_TIMESTAMP = datetime.max.timestamp()
19
+ except (OverflowError, ValueError, OSError): # pragma: no cover
20
+ # Fallback for Windows and 32-bit systems if initial max timestamp call fails
21
+ # Must get max value of ctime on Windows based on architecture (x32 vs x64)
22
+ # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/ctime-ctime32-ctime64-wctime-wctime32-wctime64
23
+ # Note: this may occur on both 32-bit Linux systems (issue #930) along with Windows systems
24
+ is_64bits = sys.maxsize > 2**32
25
+ _MAX_TIMESTAMP = (
26
+ datetime(3000, 1, 1, 23, 59, 59, 999999).timestamp()
27
+ if is_64bits
28
+ else datetime(2038, 1, 1, 23, 59, 59, 999999).timestamp()
29
+ )
30
+
31
+ MAX_TIMESTAMP: Final[float] = _MAX_TIMESTAMP
32
+ MAX_TIMESTAMP_MS: Final[float] = MAX_TIMESTAMP * 1000
33
+ MAX_TIMESTAMP_US: Final[float] = MAX_TIMESTAMP * 1_000_000
34
+
35
+ MAX_ORDINAL: Final[int] = datetime.max.toordinal()
36
+ MIN_ORDINAL: Final[int] = 1
37
+
38
+ DEFAULT_LOCALE: Final[str] = "en-us"
39
+
40
+ # Supported dehumanize locales
41
+ DEHUMANIZE_LOCALES = {
42
+ "en",
43
+ "en-us",
44
+ "en-gb",
45
+ "en-au",
46
+ "en-be",
47
+ "en-jp",
48
+ "en-za",
49
+ "en-ca",
50
+ "en-ph",
51
+ "fr",
52
+ "fr-fr",
53
+ "fr-ca",
54
+ "it",
55
+ "it-it",
56
+ "es",
57
+ "es-es",
58
+ "el",
59
+ "el-gr",
60
+ "ja",
61
+ "ja-jp",
62
+ "se",
63
+ "se-fi",
64
+ "se-no",
65
+ "se-se",
66
+ "sv",
67
+ "sv-se",
68
+ "fi",
69
+ "fi-fi",
70
+ "zh",
71
+ "zh-cn",
72
+ "zh-tw",
73
+ "zh-hk",
74
+ "nl",
75
+ "nl-nl",
76
+ "be",
77
+ "be-by",
78
+ "pl",
79
+ "pl-pl",
80
+ "ru",
81
+ "ru-ru",
82
+ "af",
83
+ "bg",
84
+ "bg-bg",
85
+ "ua",
86
+ "uk",
87
+ "uk-ua",
88
+ "mk",
89
+ "mk-mk",
90
+ "de",
91
+ "de-de",
92
+ "de-ch",
93
+ "de-at",
94
+ "nb",
95
+ "nb-no",
96
+ "nn",
97
+ "nn-no",
98
+ "pt",
99
+ "pt-pt",
100
+ "pt-br",
101
+ "tl",
102
+ "tl-ph",
103
+ "vi",
104
+ "vi-vn",
105
+ "tr",
106
+ "tr-tr",
107
+ "az",
108
+ "az-az",
109
+ "da",
110
+ "da-dk",
111
+ "ml",
112
+ "hi",
113
+ "cs",
114
+ "cs-cz",
115
+ "sk",
116
+ "sk-sk",
117
+ "fa",
118
+ "fa-ir",
119
+ "mr",
120
+ "ca",
121
+ "ca-es",
122
+ "ca-ad",
123
+ "ca-fr",
124
+ "ca-it",
125
+ "eo",
126
+ "eo-xx",
127
+ "bn",
128
+ "bn-bd",
129
+ "bn-in",
130
+ "rm",
131
+ "rm-ch",
132
+ "ro",
133
+ "ro-ro",
134
+ "sl",
135
+ "sl-si",
136
+ "id",
137
+ "id-id",
138
+ "ne",
139
+ "ne-np",
140
+ "ee",
141
+ "et",
142
+ "sw",
143
+ "sw-ke",
144
+ "sw-tz",
145
+ "la",
146
+ "la-va",
147
+ "lt",
148
+ "lt-lt",
149
+ "ms",
150
+ "ms-my",
151
+ "ms-bn",
152
+ "or",
153
+ "or-in",
154
+ "lb",
155
+ "lb-lu",
156
+ "zu",
157
+ "zu-za",
158
+ "sq",
159
+ "sq-al",
160
+ "ta",
161
+ "ta-in",
162
+ "ta-lk",
163
+ "ur",
164
+ "ur-pk",
165
+ "ka",
166
+ "ka-ge",
167
+ "kk",
168
+ "kk-kz",
169
+ # "lo",
170
+ # "lo-la",
171
+ "am",
172
+ "am-et",
173
+ "hy-am",
174
+ "hy",
175
+ "uz",
176
+ "uz-uz",
177
+ }
lib/python3.10/site-packages/arrow/util.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpful functions used internally within arrow."""
2
+
3
+ import datetime
4
+ from typing import Any, Optional, cast
5
+
6
+ from dateutil.rrule import WEEKLY, rrule
7
+
8
+ from arrow.constants import (
9
+ MAX_ORDINAL,
10
+ MAX_TIMESTAMP,
11
+ MAX_TIMESTAMP_MS,
12
+ MAX_TIMESTAMP_US,
13
+ MIN_ORDINAL,
14
+ )
15
+
16
+
17
+ def next_weekday(
18
+ start_date: Optional[datetime.date], weekday: int
19
+ ) -> datetime.datetime:
20
+ """Get next weekday from the specified start date.
21
+
22
+ :param start_date: Datetime object representing the start date.
23
+ :param weekday: Next weekday to obtain. Can be a value between 0 (Monday) and 6 (Sunday).
24
+ :return: Datetime object corresponding to the next weekday after start_date.
25
+
26
+ Usage::
27
+
28
+ # Get first Monday after epoch
29
+ >>> next_weekday(datetime(1970, 1, 1), 0)
30
+ 1970-01-05 00:00:00
31
+
32
+ # Get first Thursday after epoch
33
+ >>> next_weekday(datetime(1970, 1, 1), 3)
34
+ 1970-01-01 00:00:00
35
+
36
+ # Get first Sunday after epoch
37
+ >>> next_weekday(datetime(1970, 1, 1), 6)
38
+ 1970-01-04 00:00:00
39
+ """
40
+ if weekday < 0 or weekday > 6:
41
+ raise ValueError("Weekday must be between 0 (Monday) and 6 (Sunday).")
42
+ return cast(
43
+ datetime.datetime,
44
+ rrule(freq=WEEKLY, dtstart=start_date, byweekday=weekday, count=1)[0],
45
+ )
46
+
47
+
48
+ def is_timestamp(value: Any) -> bool:
49
+ """Check if value is a valid timestamp."""
50
+ if isinstance(value, bool):
51
+ return False
52
+ if not isinstance(value, (int, float, str)):
53
+ return False
54
+ try:
55
+ float(value)
56
+ return True
57
+ except ValueError:
58
+ return False
59
+
60
+
61
+ def validate_ordinal(value: Any) -> None:
62
+ """Raise an exception if value is an invalid Gregorian ordinal.
63
+
64
+ :param value: the input to be checked
65
+
66
+ """
67
+ if isinstance(value, bool) or not isinstance(value, int):
68
+ raise TypeError(f"Ordinal must be an integer (got type {type(value)}).")
69
+ if not (MIN_ORDINAL <= value <= MAX_ORDINAL):
70
+ raise ValueError(f"Ordinal {value} is out of range.")
71
+
72
+
73
+ def normalize_timestamp(timestamp: float) -> float:
74
+ """Normalize millisecond and microsecond timestamps into normal timestamps."""
75
+ if timestamp > MAX_TIMESTAMP:
76
+ if timestamp < MAX_TIMESTAMP_MS:
77
+ timestamp /= 1000
78
+ elif timestamp < MAX_TIMESTAMP_US:
79
+ timestamp /= 1_000_000
80
+ else:
81
+ raise ValueError(f"The specified timestamp {timestamp!r} is too large.")
82
+ return timestamp
83
+
84
+
85
+ # Credit to https://stackoverflow.com/a/1700069
86
+ def iso_to_gregorian(iso_year: int, iso_week: int, iso_day: int) -> datetime.date:
87
+ """Converts an ISO week date into a datetime object.
88
+
89
+ :param iso_year: the year
90
+ :param iso_week: the week number, each year has either 52 or 53 weeks
91
+ :param iso_day: the day numbered 1 through 7, beginning with Monday
92
+
93
+ """
94
+
95
+ if not 1 <= iso_week <= 53:
96
+ raise ValueError("ISO Calendar week value must be between 1-53.")
97
+
98
+ if not 1 <= iso_day <= 7:
99
+ raise ValueError("ISO Calendar day value must be between 1-7")
100
+
101
+ # The first week of the year always contains 4 Jan.
102
+ fourth_jan = datetime.date(iso_year, 1, 4)
103
+ delta = datetime.timedelta(fourth_jan.isoweekday() - 1)
104
+ year_start = fourth_jan - delta
105
+ gregorian = year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1)
106
+
107
+ return gregorian
108
+
109
+
110
+ def validate_bounds(bounds: str) -> None:
111
+ if bounds != "()" and bounds != "(]" and bounds != "[)" and bounds != "[]":
112
+ raise ValueError(
113
+ "Invalid bounds. Please select between '()', '(]', '[)', or '[]'."
114
+ )
115
+
116
+
117
+ __all__ = ["next_weekday", "is_timestamp", "validate_ordinal", "iso_to_gregorian"]
lib/python3.10/site-packages/av/attachments/__init__.py ADDED
File without changes
lib/python3.10/site-packages/av/attachments/stream.pxd ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from av.stream cimport Stream
2
+
3
+
4
+ cdef class AttachmentStream(Stream):
5
+ pass
lib/python3.10/site-packages/av/attachments/stream.pyi ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ from av.stream import Stream
4
+
5
+ class AttachmentStream(Stream):
6
+ type: Literal["attachment"]
7
+ @property
8
+ def mimetype(self) -> str | None: ...
lib/python3.10/site-packages/av/attachments/stream.pyx ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.stream cimport Stream
2
+
3
+
4
+ cdef class AttachmentStream(Stream):
5
+ """
6
+ An :class:`AttachmentStream` represents a stream of attachment data within a media container.
7
+ Typically used to attach font files that are referenced in ASS/SSA Subtitle Streams.
8
+ """
9
+
10
+ @property
11
+ def name(self):
12
+ """
13
+ Returns the file name of the attachment.
14
+
15
+ :rtype: str | None
16
+ """
17
+ return self.metadata.get("filename")
18
+
19
+ @property
20
+ def mimetype(self):
21
+ """
22
+ Returns the MIME type of the attachment.
23
+
24
+ :rtype: str | None
25
+ """
26
+ return self.metadata.get("mimetype")
lib/python3.10/site-packages/av/audio/__init__.pxd ADDED
File without changes
lib/python3.10/site-packages/av/audio/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .frame import AudioFrame
2
+ from .stream import AudioStream
lib/python3.10/site-packages/av/audio/__init__.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .frame import AudioFrame
2
+ from .stream import AudioStream
3
+
4
+ __all__ = ("AudioFrame", "AudioStream")
lib/python3.10/site-packages/av/audio/codeccontext.pxd ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from av.audio.frame cimport AudioFrame
3
+ from av.audio.resampler cimport AudioResampler
4
+ from av.codec.context cimport CodecContext
5
+
6
+
7
+ cdef class AudioCodecContext(CodecContext):
8
+ # Hold onto the frames that we will decode until we have a full one.
9
+ cdef AudioFrame next_frame
10
+ # For encoding.
11
+ cdef AudioResampler resampler
lib/python3.10/site-packages/av/audio/codeccontext.pyi ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterator, Literal
2
+
3
+ from av.codec.context import CodecContext
4
+ from av.packet import Packet
5
+
6
+ from .format import AudioFormat
7
+ from .frame import AudioFrame
8
+ from .layout import AudioLayout
9
+
10
+ class _Format:
11
+ def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ...
12
+ def __set__(self, instance: object, value: AudioFormat | str) -> None: ...
13
+
14
+ class _Layout:
15
+ def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ...
16
+ def __set__(self, instance: object, value: AudioLayout | str) -> None: ...
17
+
18
+ class AudioCodecContext(CodecContext):
19
+ frame_size: int
20
+ sample_rate: int
21
+ rate: int
22
+ type: Literal["audio"]
23
+ format: _Format
24
+ layout: _Layout
25
+ @property
26
+ def channels(self) -> int: ...
27
+ def encode(self, frame: AudioFrame | None = None) -> list[Packet]: ...
28
+ def encode_lazy(self, frame: AudioFrame | None = None) -> Iterator[Packet]: ...
29
+ def decode(self, packet: Packet | None = None) -> list[AudioFrame]: ...
lib/python3.10/site-packages/av/audio/codeccontext.pyx ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+ from av.audio.format cimport AudioFormat, get_audio_format
4
+ from av.audio.frame cimport AudioFrame, alloc_audio_frame
5
+ from av.audio.layout cimport AudioLayout, get_audio_layout
6
+ from av.codec.hwaccel cimport HWAccel
7
+ from av.frame cimport Frame
8
+ from av.packet cimport Packet
9
+
10
+
11
+ cdef class AudioCodecContext(CodecContext):
12
+ cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel):
13
+ CodecContext._init(self, ptr, codec, hwaccel)
14
+
15
+ cdef _prepare_frames_for_encode(self, Frame input_frame):
16
+
17
+ cdef AudioFrame frame = input_frame
18
+ cdef bint allow_var_frame_size = self.ptr.codec.capabilities & lib.AV_CODEC_CAP_VARIABLE_FRAME_SIZE
19
+
20
+ # Note that the resampler will simply return an input frame if there is
21
+ # no resampling to be done. The control flow was just a little easier this way.
22
+ if not self.resampler:
23
+ self.resampler = AudioResampler(
24
+ format=self.format,
25
+ layout=self.layout,
26
+ rate=self.ptr.sample_rate,
27
+ frame_size=None if allow_var_frame_size else self.ptr.frame_size
28
+ )
29
+ frames = self.resampler.resample(frame)
30
+
31
+ # flush if input frame is None
32
+ if input_frame is None:
33
+ frames.append(None)
34
+
35
+ return frames
36
+
37
+ cdef Frame _alloc_next_frame(self):
38
+ return alloc_audio_frame()
39
+
40
+ cdef _setup_decoded_frame(self, Frame frame, Packet packet):
41
+ CodecContext._setup_decoded_frame(self, frame, packet)
42
+ cdef AudioFrame aframe = frame
43
+ aframe._init_user_attributes()
44
+
45
+ @property
46
+ def frame_size(self):
47
+ """
48
+ Number of samples per channel in an audio frame.
49
+
50
+ :type: int
51
+ """
52
+ return self.ptr.frame_size
53
+
54
+ @property
55
+ def sample_rate(self):
56
+ """
57
+ Sample rate of the audio data, in samples per second.
58
+
59
+ :type: int
60
+ """
61
+ return self.ptr.sample_rate
62
+
63
+ @sample_rate.setter
64
+ def sample_rate(self, int value):
65
+ self.ptr.sample_rate = value
66
+
67
+ @property
68
+ def rate(self):
69
+ """Another name for :attr:`sample_rate`."""
70
+ return self.sample_rate
71
+
72
+ @rate.setter
73
+ def rate(self, value):
74
+ self.sample_rate = value
75
+
76
+ @property
77
+ def channels(self):
78
+ return self.layout.nb_channels
79
+
80
+ @property
81
+ def layout(self):
82
+ """
83
+ The audio channel layout.
84
+
85
+ :type: AudioLayout
86
+ """
87
+ return get_audio_layout(self.ptr.ch_layout)
88
+
89
+ @layout.setter
90
+ def layout(self, value):
91
+ cdef AudioLayout layout = AudioLayout(value)
92
+ self.ptr.ch_layout = layout.layout
93
+
94
+ @property
95
+ def format(self):
96
+ """
97
+ The audio sample format.
98
+
99
+ :type: AudioFormat
100
+ """
101
+ return get_audio_format(self.ptr.sample_fmt)
102
+
103
+ @format.setter
104
+ def format(self, value):
105
+ cdef AudioFormat format = AudioFormat(value)
106
+ self.ptr.sample_fmt = format.sample_fmt
lib/python3.10/site-packages/av/audio/fifo.pxd ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+ from libc.stdint cimport int64_t, uint64_t
3
+
4
+ from av.audio.frame cimport AudioFrame
5
+
6
+
7
+ cdef class AudioFifo:
8
+
9
+ cdef lib.AVAudioFifo *ptr
10
+
11
+ cdef AudioFrame template
12
+
13
+ cdef readonly uint64_t samples_written
14
+ cdef readonly uint64_t samples_read
15
+ cdef readonly double pts_per_sample
16
+
17
+ cpdef write(self, AudioFrame frame)
18
+ cpdef read(self, int samples=*, bint partial=*)
19
+ cpdef read_many(self, int samples, bint partial=*)
lib/python3.10/site-packages/av/audio/fifo.pyi ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .format import AudioFormat
2
+ from .frame import AudioFrame
3
+ from .layout import AudioLayout
4
+
5
+ class AudioFifo:
6
+ def write(self, frame: AudioFrame) -> None: ...
7
+ def read(self, samples: int = 0, partial: bool = False) -> AudioFrame | None: ...
8
+ def read_many(self, samples: int, partial: bool = False) -> list[AudioFrame]: ...
9
+ @property
10
+ def format(self) -> AudioFormat: ...
11
+ @property
12
+ def layout(self) -> AudioLayout: ...
13
+ @property
14
+ def sample_rate(self) -> int: ...
15
+ @property
16
+ def samples(self) -> int: ...
17
+ @property
18
+ def samples_written(self) -> int: ...
19
+ @property
20
+ def samples_read(self) -> int: ...
21
+ @property
22
+ def pts_per_sample(self) -> float: ...
lib/python3.10/site-packages/av/audio/format.pxd ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+
4
+ cdef class AudioFormat:
5
+
6
+ cdef lib.AVSampleFormat sample_fmt
7
+
8
+ cdef _init(self, lib.AVSampleFormat sample_fmt)
9
+
10
+
11
+ cdef AudioFormat get_audio_format(lib.AVSampleFormat format)
lib/python3.10/site-packages/av/audio/format.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class AudioFormat:
2
+ name: str
3
+ bytes: int
4
+ bits: int
5
+ is_planar: bool
6
+ is_packed: bool
7
+ planar: AudioFormat
8
+ packed: AudioFormat
9
+ container_name: str
10
+
11
+ def __init__(self, name: str | AudioFormat) -> None: ...
lib/python3.10/site-packages/av/audio/frame.pxd ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+ from libc.stdint cimport uint8_t, uint64_t
3
+
4
+ from av.audio.format cimport AudioFormat
5
+ from av.audio.layout cimport AudioLayout
6
+ from av.frame cimport Frame
7
+
8
+
9
+ cdef class AudioFrame(Frame):
10
+ # For raw storage of the frame's data; don't ever touch this.
11
+ cdef uint8_t *_buffer
12
+ cdef size_t _buffer_size
13
+
14
+ cdef readonly AudioLayout layout
15
+ """
16
+ The audio channel layout.
17
+
18
+ :type: AudioLayout
19
+ """
20
+
21
+ cdef readonly AudioFormat format
22
+ """
23
+ The audio sample format.
24
+
25
+ :type: AudioFormat
26
+ """
27
+
28
+ cdef _init(self, lib.AVSampleFormat format, lib.AVChannelLayout layout, unsigned int nb_samples, unsigned int align)
29
+ cdef _init_user_attributes(self)
30
+
31
+ cdef AudioFrame alloc_audio_frame()
lib/python3.10/site-packages/av/audio/frame.pyi ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Union
2
+
3
+ import numpy as np
4
+
5
+ from av.frame import Frame
6
+
7
+ from .format import AudioFormat
8
+ from .layout import AudioLayout
9
+ from .plane import AudioPlane
10
+
11
+ format_dtypes: dict[str, str]
12
+ _SupportedNDarray = Union[
13
+ np.ndarray[Any, np.dtype[np.float64]], # f8
14
+ np.ndarray[Any, np.dtype[np.float32]], # f4
15
+ np.ndarray[Any, np.dtype[np.int32]], # i4
16
+ np.ndarray[Any, np.dtype[np.int16]], # i2
17
+ np.ndarray[Any, np.dtype[np.uint8]], # u1
18
+ ]
19
+
20
+ class _Format:
21
+ def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ...
22
+ def __set__(self, instance: object, value: AudioFormat | str) -> None: ...
23
+
24
+ class _Layout:
25
+ def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ...
26
+ def __set__(self, instance: object, value: AudioLayout | str) -> None: ...
27
+
28
+ class AudioFrame(Frame):
29
+ planes: tuple[AudioPlane, ...]
30
+ samples: int
31
+ sample_rate: int
32
+ rate: int
33
+ format: _Format
34
+ layout: _Layout
35
+
36
+ def __init__(
37
+ self,
38
+ format: str = "s16",
39
+ layout: str = "stereo",
40
+ samples: int = 0,
41
+ align: int = 1,
42
+ ) -> None: ...
43
+ @staticmethod
44
+ def from_ndarray(
45
+ array: _SupportedNDarray, format: str = "s16", layout: str = "stereo"
46
+ ) -> AudioFrame: ...
47
+ def to_ndarray(self) -> _SupportedNDarray: ...
lib/python3.10/site-packages/av/audio/frame.pyx ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.audio.format cimport get_audio_format
2
+ from av.audio.layout cimport get_audio_layout
3
+ from av.audio.plane cimport AudioPlane
4
+ from av.error cimport err_check
5
+ from av.utils cimport check_ndarray
6
+
7
+
8
+ cdef object _cinit_bypass_sentinel
9
+
10
+
11
+ format_dtypes = {
12
+ "dbl": "f8",
13
+ "dblp": "f8",
14
+ "flt": "f4",
15
+ "fltp": "f4",
16
+ "s16": "i2",
17
+ "s16p": "i2",
18
+ "s32": "i4",
19
+ "s32p": "i4",
20
+ "u8": "u1",
21
+ "u8p": "u1",
22
+ }
23
+
24
+
25
+ cdef AudioFrame alloc_audio_frame():
26
+ """Get a mostly uninitialized AudioFrame.
27
+
28
+ You MUST call AudioFrame._init(...) or AudioFrame._init_user_attributes()
29
+ before exposing to the user.
30
+
31
+ """
32
+ return AudioFrame.__new__(AudioFrame, _cinit_bypass_sentinel)
33
+
34
+
35
+ cdef class AudioFrame(Frame):
36
+ """A frame of audio."""
37
+
38
+ def __cinit__(self, format="s16", layout="stereo", samples=0, align=1):
39
+ if format is _cinit_bypass_sentinel:
40
+ return
41
+
42
+ cdef AudioFormat cy_format = AudioFormat(format)
43
+ cdef AudioLayout cy_layout = AudioLayout(layout)
44
+ self._init(cy_format.sample_fmt, cy_layout.layout, samples, align)
45
+
46
+ cdef _init(self, lib.AVSampleFormat format, lib.AVChannelLayout layout, unsigned int nb_samples, unsigned int align):
47
+ self.ptr.nb_samples = nb_samples
48
+ self.ptr.format = <int>format
49
+ self.ptr.ch_layout = layout
50
+
51
+ # Sometimes this is called twice. Oh well.
52
+ self._init_user_attributes()
53
+
54
+ if self.layout.nb_channels != 0 and nb_samples:
55
+ # Cleanup the old buffer.
56
+ lib.av_freep(&self._buffer)
57
+
58
+ # Get a new one.
59
+ self._buffer_size = err_check(lib.av_samples_get_buffer_size(
60
+ NULL,
61
+ self.layout.nb_channels,
62
+ nb_samples,
63
+ format,
64
+ align
65
+ ))
66
+ self._buffer = <uint8_t *>lib.av_malloc(self._buffer_size)
67
+ if not self._buffer:
68
+ raise MemoryError("cannot allocate AudioFrame buffer")
69
+
70
+ # Connect the data pointers to the buffer.
71
+ err_check(lib.avcodec_fill_audio_frame(
72
+ self.ptr,
73
+ self.layout.nb_channels,
74
+ <lib.AVSampleFormat>self.ptr.format,
75
+ self._buffer,
76
+ self._buffer_size,
77
+ align
78
+ ))
79
+
80
+ def __dealloc__(self):
81
+ lib.av_freep(&self._buffer)
82
+
83
+ cdef _init_user_attributes(self):
84
+ self.layout = get_audio_layout(self.ptr.ch_layout)
85
+ self.format = get_audio_format(<lib.AVSampleFormat>self.ptr.format)
86
+
87
+ def __repr__(self):
88
+ return (
89
+ f"<av.{self.__class__.__name__} pts={self.pts}, {self.samples} "
90
+ f"samples at {self.rate}Hz, {self.layout.name}, {self.format.name} at 0x{id(self):x}"
91
+ )
92
+
93
+ @staticmethod
94
+ def from_ndarray(array, format="s16", layout="stereo"):
95
+ """
96
+ Construct a frame from a numpy array.
97
+ """
98
+ import numpy as np
99
+
100
+ # map avcodec type to numpy type
101
+ try:
102
+ dtype = np.dtype(format_dtypes[format])
103
+ except KeyError:
104
+ raise ValueError(
105
+ f"Conversion from numpy array with format `{format}` is not yet supported"
106
+ )
107
+
108
+ # check input format
109
+ nb_channels = AudioLayout(layout).nb_channels
110
+ check_ndarray(array, dtype, 2)
111
+ if AudioFormat(format).is_planar:
112
+ if array.shape[0] != nb_channels:
113
+ raise ValueError(f"Expected planar `array.shape[0]` to equal `{nb_channels}` but got `{array.shape[0]}`")
114
+ samples = array.shape[1]
115
+ else:
116
+ if array.shape[0] != 1:
117
+ raise ValueError(f"Expected packed `array.shape[0]` to equal `1` but got `{array.shape[0]}`")
118
+ samples = array.shape[1] // nb_channels
119
+
120
+ frame = AudioFrame(format=format, layout=layout, samples=samples)
121
+ for i, plane in enumerate(frame.planes):
122
+ plane.update(array[i, :])
123
+ return frame
124
+
125
+ @property
126
+ def planes(self):
127
+ """
128
+ A tuple of :class:`~av.audio.plane.AudioPlane`.
129
+
130
+ :type: tuple
131
+ """
132
+ cdef int plane_count = 0
133
+ while self.ptr.extended_data[plane_count]:
134
+ plane_count += 1
135
+
136
+ return tuple([AudioPlane(self, i) for i in range(plane_count)])
137
+
138
+ @property
139
+ def samples(self):
140
+ """
141
+ Number of audio samples (per channel).
142
+
143
+ :type: int
144
+ """
145
+ return self.ptr.nb_samples
146
+
147
+ @property
148
+ def sample_rate(self):
149
+ """
150
+ Sample rate of the audio data, in samples per second.
151
+
152
+ :type: int
153
+ """
154
+ return self.ptr.sample_rate
155
+
156
+ @sample_rate.setter
157
+ def sample_rate(self, value):
158
+ self.ptr.sample_rate = value
159
+
160
+ @property
161
+ def rate(self):
162
+ """Another name for :attr:`sample_rate`."""
163
+ return self.ptr.sample_rate
164
+
165
+ @rate.setter
166
+ def rate(self, value):
167
+ self.ptr.sample_rate = value
168
+
169
+ def to_ndarray(self):
170
+ """Get a numpy array of this frame.
171
+
172
+ .. note:: Numpy must be installed.
173
+
174
+ """
175
+ import numpy as np
176
+
177
+ try:
178
+ dtype = np.dtype(format_dtypes[self.format.name])
179
+ except KeyError:
180
+ raise ValueError(f"Conversion from {self.format.name!r} format to numpy array is not supported.")
181
+
182
+ if self.format.is_planar:
183
+ count = self.samples
184
+ else:
185
+ count = self.samples * self.layout.nb_channels
186
+
187
+ return np.vstack([np.frombuffer(x, dtype=dtype, count=count) for x in self.planes])
lib/python3.10/site-packages/av/audio/layout.pxd ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+
4
+ cdef class AudioLayout:
5
+ cdef lib.AVChannelLayout layout
6
+ cdef _init(self, lib.AVChannelLayout layout)
7
+
8
+ cdef AudioLayout get_audio_layout(lib.AVChannelLayout c_layout)
lib/python3.10/site-packages/av/audio/layout.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ class AudioLayout:
4
+ name: str
5
+ nb_channels: int
6
+ channels: tuple[AudioChannel, ...]
7
+ def __init__(self, layout: str | AudioLayout): ...
8
+
9
+ @dataclass
10
+ class AudioChannel:
11
+ name: str
12
+ description: str
lib/python3.10/site-packages/av/audio/layout.pyx ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+ from cpython.bytes cimport PyBytes_FromStringAndSize
3
+
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass
8
+ class AudioChannel:
9
+ name: str
10
+ description: str
11
+
12
+ def __repr__(self):
13
+ return f"<av.AudioChannel '{self.name}' ({self.description})>"
14
+
15
+ cdef object _cinit_bypass_sentinel
16
+
17
+ cdef AudioLayout get_audio_layout(lib.AVChannelLayout c_layout):
18
+ """Get an AudioLayout from Cython land."""
19
+ cdef AudioLayout layout = AudioLayout.__new__(AudioLayout, _cinit_bypass_sentinel)
20
+ layout._init(c_layout)
21
+ return layout
22
+
23
+
24
+ cdef class AudioLayout:
25
+ def __init__(self, layout):
26
+ if layout is _cinit_bypass_sentinel:
27
+ return
28
+
29
+ if type(layout) is str:
30
+ ret = lib.av_channel_layout_from_string(&c_layout, layout)
31
+ if ret != 0:
32
+ raise ValueError(f"Invalid layout: {layout}")
33
+ elif isinstance(layout, AudioLayout):
34
+ c_layout = (<AudioLayout>layout).layout
35
+ else:
36
+ raise TypeError(f"layout must be of type: string | av.AudioLayout, got {type(layout)}")
37
+
38
+ self._init(c_layout)
39
+
40
+ cdef _init(self, lib.AVChannelLayout layout):
41
+ self.layout = layout
42
+
43
+ def __repr__(self):
44
+ return f"<av.{self.__class__.__name__} {self.name!r}>"
45
+
46
+ def __eq__(self, other):
47
+ return isinstance(other, AudioLayout) and self.name == other.name and self.nb_channels == other.nb_channels
48
+
49
+ @property
50
+ def nb_channels(self):
51
+ return self.layout.nb_channels
52
+
53
+ @property
54
+ def channels(self):
55
+ cdef lib.AVChannel channel
56
+ cdef char buf[16]
57
+ cdef char buf2[128]
58
+
59
+ results = []
60
+
61
+ for index in range(self.layout.nb_channels):
62
+ channel = lib.av_channel_layout_channel_from_index(&self.layout, index);
63
+ size = lib.av_channel_name(buf, sizeof(buf), channel) - 1
64
+ size2 = lib.av_channel_description(buf2, sizeof(buf2), channel) - 1
65
+ results.append(
66
+ AudioChannel(
67
+ PyBytes_FromStringAndSize(buf, size).decode("utf-8"),
68
+ PyBytes_FromStringAndSize(buf2, size2).decode("utf-8"),
69
+ )
70
+ )
71
+
72
+ return tuple(results)
73
+
74
+ @property
75
+ def name(self) -> str:
76
+ """The canonical name of the audio layout."""
77
+ cdef char layout_name[128]
78
+ cdef int ret
79
+
80
+ ret = lib.av_channel_layout_describe(&self.layout, layout_name, sizeof(layout_name))
81
+ if ret < 0:
82
+ raise RuntimeError(f"Failed to get layout name: {ret}")
83
+
84
+ return layout_name
lib/python3.10/site-packages/av/audio/plane.pxd ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from av.plane cimport Plane
2
+
3
+
4
+ cdef class AudioPlane(Plane):
5
+
6
+ cdef readonly size_t buffer_size
7
+
8
+ cdef size_t _buffer_size(self)
lib/python3.10/site-packages/av/audio/plane.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from av.plane import Plane
2
+
3
+ class AudioPlane(Plane):
4
+ buffer_size: int
lib/python3.10/site-packages/av/audio/plane.pyx ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.audio.frame cimport AudioFrame
2
+
3
+
4
+ cdef class AudioPlane(Plane):
5
+
6
+ def __cinit__(self, AudioFrame frame, int index):
7
+ # Only the first linesize is ever populated, but it applies to every plane.
8
+ self.buffer_size = self.frame.ptr.linesize[0]
9
+
10
+ cdef size_t _buffer_size(self):
11
+ return self.buffer_size
lib/python3.10/site-packages/av/audio/resampler.pxd ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.audio.format cimport AudioFormat
2
+ from av.audio.frame cimport AudioFrame
3
+ from av.audio.layout cimport AudioLayout
4
+ from av.filter.graph cimport Graph
5
+
6
+
7
+ cdef class AudioResampler:
8
+
9
+ cdef readonly bint is_passthrough
10
+
11
+ cdef AudioFrame template
12
+
13
+ # Destination descriptors
14
+ cdef readonly AudioFormat format
15
+ cdef readonly AudioLayout layout
16
+ cdef readonly int rate
17
+ cdef readonly unsigned int frame_size
18
+
19
+ cdef Graph graph
20
+
21
+ cpdef resample(self, AudioFrame)
lib/python3.10/site-packages/av/audio/resampler.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.filter.graph import Graph
2
+
3
+ from .format import AudioFormat
4
+ from .frame import AudioFrame
5
+ from .layout import AudioLayout
6
+
7
+ class AudioResampler:
8
+ rate: int
9
+ frame_size: int
10
+ format: AudioFormat
11
+ graph: Graph | None
12
+
13
+ def __init__(
14
+ self,
15
+ format: str | int | AudioFormat | None = None,
16
+ layout: str | int | AudioLayout | None = None,
17
+ rate: int | None = None,
18
+ frame_size: int | None = None,
19
+ ) -> None: ...
20
+ def resample(self, frame: AudioFrame | None) -> list[AudioFrame]: ...
lib/python3.10/site-packages/av/audio/resampler.pyx ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.filter.context cimport FilterContext
2
+
3
+ import errno
4
+
5
+ import av.filter
6
+
7
+
8
+ cdef class AudioResampler:
9
+
10
+ """AudioResampler(format=None, layout=None, rate=None)
11
+
12
+ :param AudioFormat format: The target format, or string that parses to one
13
+ (e.g. ``"s16"``).
14
+ :param AudioLayout layout: The target layout, or an int/string that parses
15
+ to one (e.g. ``"stereo"``).
16
+ :param int rate: The target sample rate.
17
+
18
+
19
+ """
20
+
21
+ def __cinit__(self, format=None, layout=None, rate=None, frame_size=None):
22
+ if format is not None:
23
+ self.format = format if isinstance(format, AudioFormat) else AudioFormat(format)
24
+
25
+ if layout is not None:
26
+ self.layout = AudioLayout(layout)
27
+ self.rate = int(rate) if rate else 0
28
+
29
+ self.frame_size = int(frame_size) if frame_size else 0
30
+
31
+ self.graph = None
32
+
33
+ cpdef resample(self, AudioFrame frame):
34
+ """resample(frame)
35
+
36
+ Convert the ``sample_rate``, ``channel_layout`` and/or ``format`` of
37
+ a :class:`~.AudioFrame`.
38
+
39
+ :param AudioFrame frame: The frame to convert or `None` to flush.
40
+ :returns: A list of :class:`AudioFrame` in new parameters. If the nothing is to be done return the same frame
41
+ as a single element list.
42
+
43
+ """
44
+ # We don't have any input, so don't bother even setting up.
45
+ if not self.graph and frame is None:
46
+ return []
47
+
48
+ # Shortcut for passthrough.
49
+ if self.is_passthrough:
50
+ return [frame]
51
+
52
+ # Take source settings from the first frame.
53
+ if not self.graph:
54
+ self.template = frame
55
+
56
+ # Set some default descriptors.
57
+ self.format = self.format or frame.format
58
+ self.layout = self.layout or frame.layout
59
+ self.rate = self.rate or frame.sample_rate
60
+
61
+ # Check if we can passthrough or if there is actually work to do.
62
+ if (
63
+ frame.format.sample_fmt == self.format.sample_fmt and
64
+ frame.layout == self.layout and
65
+ frame.sample_rate == self.rate and
66
+ self.frame_size == 0
67
+ ):
68
+ self.is_passthrough = True
69
+ return [frame]
70
+
71
+ # handle resampling with aformat filter
72
+ # (similar to configure_output_audio_filter from ffmpeg)
73
+ self.graph = av.filter.Graph()
74
+ extra_args = {}
75
+ if frame.time_base is not None:
76
+ extra_args["time_base"] = str(frame.time_base)
77
+ abuffer = self.graph.add(
78
+ "abuffer",
79
+ sample_rate=str(frame.sample_rate),
80
+ sample_fmt=AudioFormat(frame.format).name,
81
+ channel_layout=frame.layout.name,
82
+ **extra_args,
83
+ )
84
+ aformat = self.graph.add(
85
+ "aformat",
86
+ sample_rates=str(self.rate),
87
+ sample_fmts=self.format.name,
88
+ channel_layouts=self.layout.name,
89
+ )
90
+ abuffersink = self.graph.add("abuffersink")
91
+ abuffer.link_to(aformat)
92
+ aformat.link_to(abuffersink)
93
+ self.graph.configure()
94
+
95
+ if self.frame_size > 0:
96
+ self.graph.set_audio_frame_size(self.frame_size)
97
+
98
+ if frame is not None:
99
+ if (
100
+ frame.format.sample_fmt != self.template.format.sample_fmt or
101
+ frame.layout != self.template.layout or
102
+ frame.sample_rate != self.template.rate
103
+ ):
104
+ raise ValueError("Frame does not match AudioResampler setup.")
105
+
106
+ self.graph.push(frame)
107
+
108
+ output = []
109
+ while True:
110
+ try:
111
+ output.append(self.graph.pull())
112
+ except EOFError:
113
+ break
114
+ except av.FFmpegError as e:
115
+ if e.errno != errno.EAGAIN:
116
+ raise
117
+ break
118
+
119
+ return output
lib/python3.10/site-packages/av/audio/stream.pyx ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.packet cimport Packet
2
+
3
+ from .frame cimport AudioFrame
4
+
5
+
6
+ cdef class AudioStream(Stream):
7
+ def __repr__(self):
8
+ form = self.format.name if self.format else None
9
+ return (
10
+ f"<av.AudioStream #{self.index} {self.name} at {self.rate}Hz,"
11
+ f" {self.layout.name}, {form} at 0x{id(self):x}>"
12
+ )
13
+
14
+ def __getattr__(self, name):
15
+ return getattr(self.codec_context, name)
16
+
17
+ cpdef encode(self, AudioFrame frame=None):
18
+ """
19
+ Encode an :class:`.AudioFrame` and return a list of :class:`.Packet`.
20
+
21
+ :rtype: list[Packet]
22
+
23
+ .. seealso:: This is mostly a passthrough to :meth:`.CodecContext.encode`.
24
+ """
25
+
26
+ packets = self.codec_context.encode(frame)
27
+ cdef Packet packet
28
+ for packet in packets:
29
+ packet._stream = self
30
+ packet.ptr.stream_index = self.ptr.index
31
+
32
+ return packets
33
+
34
+ cpdef decode(self, Packet packet=None):
35
+ """
36
+ Decode a :class:`.Packet` and return a list of :class:`.AudioFrame`.
37
+
38
+ :rtype: list[AudioFrame]
39
+
40
+ .. seealso:: This is a passthrough to :meth:`.CodecContext.decode`.
41
+ """
42
+
43
+ return self.codec_context.decode(packet)
lib/python3.10/site-packages/av/codec/__init__.pxd ADDED
File without changes
lib/python3.10/site-packages/av/codec/codec.pyi ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Flag, IntEnum
2
+ from fractions import Fraction
3
+ from typing import ClassVar, Literal, cast, overload
4
+
5
+ from av.audio.codeccontext import AudioCodecContext
6
+ from av.audio.format import AudioFormat
7
+ from av.descriptor import Descriptor
8
+ from av.subtitles.codeccontext import SubtitleCodecContext
9
+ from av.video.codeccontext import VideoCodecContext
10
+ from av.video.format import VideoFormat
11
+
12
+ from .context import CodecContext
13
+
14
+ class Properties(Flag):
15
+ NONE = cast(ClassVar[Properties], ...)
16
+ INTRA_ONLY = cast(ClassVar[Properties], ...)
17
+ LOSSY = cast(ClassVar[Properties], ...)
18
+ LOSSLESS = cast(ClassVar[Properties], ...)
19
+ REORDER = cast(ClassVar[Properties], ...)
20
+ BITMAP_SUB = cast(ClassVar[Properties], ...)
21
+ TEXT_SUB = cast(ClassVar[Properties], ...)
22
+
23
+ class Capabilities(IntEnum):
24
+ none = cast(int, ...)
25
+ draw_horiz_band = cast(int, ...)
26
+ dr1 = cast(int, ...)
27
+ hwaccel = cast(int, ...)
28
+ delay = cast(int, ...)
29
+ small_last_frame = cast(int, ...)
30
+ hwaccel_vdpau = cast(int, ...)
31
+ subframes = cast(int, ...)
32
+ experimental = cast(int, ...)
33
+ channel_conf = cast(int, ...)
34
+ neg_linesizes = cast(int, ...)
35
+ frame_threads = cast(int, ...)
36
+ slice_threads = cast(int, ...)
37
+ param_change = cast(int, ...)
38
+ auto_threads = cast(int, ...)
39
+ variable_frame_size = cast(int, ...)
40
+ avoid_probing = cast(int, ...)
41
+ hardware = cast(int, ...)
42
+ hybrid = cast(int, ...)
43
+ encoder_reordered_opaque = cast(int, ...)
44
+ encoder_flush = cast(int, ...)
45
+ encoder_recon_frame = cast(int, ...)
46
+
47
+ class UnknownCodecError(ValueError): ...
48
+
49
+ class Codec:
50
+ @property
51
+ def is_encoder(self) -> bool: ...
52
+ @property
53
+ def is_decoder(self) -> bool: ...
54
+ @property
55
+ def mode(self) -> Literal["r", "w"]: ...
56
+ descriptor: Descriptor
57
+ @property
58
+ def name(self) -> str: ...
59
+ @property
60
+ def canonical_name(self) -> str: ...
61
+ @property
62
+ def long_name(self) -> str: ...
63
+ @property
64
+ def type(self) -> Literal["video", "audio", "data", "subtitle", "attachment"]: ...
65
+ @property
66
+ def id(self) -> int: ...
67
+ frame_rates: list[Fraction] | None
68
+ audio_rates: list[int] | None
69
+ video_formats: list[VideoFormat] | None
70
+ audio_formats: list[AudioFormat] | None
71
+
72
+ @property
73
+ def properties(self) -> int: ...
74
+ @property
75
+ def intra_only(self) -> bool: ...
76
+ @property
77
+ def lossy(self) -> bool: ...
78
+ @property
79
+ def lossless(self) -> bool: ...
80
+ @property
81
+ def reorder(self) -> bool: ...
82
+ @property
83
+ def bitmap_sub(self) -> bool: ...
84
+ @property
85
+ def text_sub(self) -> bool: ...
86
+ @property
87
+ def capabilities(self) -> int: ...
88
+ @property
89
+ def experimental(self) -> bool: ...
90
+ @property
91
+ def delay(self) -> bool: ...
92
+ def __init__(self, name: str, mode: Literal["r", "w"] = "r") -> None: ...
93
+ @overload
94
+ def create(self, kind: Literal["video"]) -> VideoCodecContext: ...
95
+ @overload
96
+ def create(self, kind: Literal["audio"]) -> AudioCodecContext: ...
97
+ @overload
98
+ def create(self, kind: Literal["subtitle"]) -> SubtitleCodecContext: ...
99
+ @overload
100
+ def create(self, kind: None = None) -> CodecContext: ...
101
+ @overload
102
+ def create(
103
+ self, kind: Literal["video", "audio", "subtitle"] | None = None
104
+ ) -> (
105
+ VideoCodecContext | AudioCodecContext | SubtitleCodecContext | CodecContext
106
+ ): ...
107
+
108
+ class codec_descriptor:
109
+ name: str
110
+ options: tuple[int, ...]
111
+
112
+ codecs_available: set[str]
113
+
114
+ def dump_codecs() -> None: ...
115
+ def dump_hwconfigs() -> None: ...
lib/python3.10/site-packages/av/codec/context.pxd ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+ from libc.stdint cimport int64_t
3
+
4
+ from av.bytesource cimport ByteSource
5
+ from av.codec.codec cimport Codec
6
+ from av.codec.hwaccel cimport HWAccel
7
+ from av.frame cimport Frame
8
+ from av.packet cimport Packet
9
+
10
+
11
+ cdef class CodecContext:
12
+ cdef lib.AVCodecContext *ptr
13
+
14
+ # Whether AVCodecContext.extradata should be de-allocated upon destruction.
15
+ cdef bint extradata_set
16
+
17
+ # Used as a signal that this is within a stream, and also for us to access that
18
+ # stream. This is set "manually" by the stream after constructing this object.
19
+ cdef int stream_index
20
+
21
+ cdef lib.AVCodecParserContext *parser
22
+ cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel)
23
+
24
+ # Public API.
25
+ cdef readonly bint is_open
26
+ cdef readonly Codec codec
27
+ cdef readonly HWAccel hwaccel
28
+ cdef public dict options
29
+ cpdef open(self, bint strict=?)
30
+
31
+ # Wraps both versions of the transcode API, returning lists.
32
+ cpdef encode(self, Frame frame=?)
33
+ cpdef decode(self, Packet packet=?)
34
+ cpdef flush_buffers(self)
35
+
36
+ # Used by hardware-accelerated decode.
37
+ cdef HWAccel hwaccel_ctx
38
+
39
+ # Used by both transcode APIs to setup user-land objects.
40
+ # TODO: Remove the `Packet` from `_setup_decoded_frame` (because flushing packets
41
+ # are bogus). It should take all info it needs from the context and/or stream.
42
+ cdef _prepare_and_time_rebase_frames_for_encode(self, Frame frame)
43
+ cdef _prepare_frames_for_encode(self, Frame frame)
44
+ cdef _setup_encoded_packet(self, Packet)
45
+ cdef _setup_decoded_frame(self, Frame, Packet)
46
+
47
+ # Implemented by base for the generic send/recv API.
48
+ # Note that the user cannot send without receiving. This is because
49
+ # `_prepare_frames_for_encode` may expand a frame into multiple (e.g. when
50
+ # resampling audio to a higher rate but with fixed size frames), and the
51
+ # send/recv buffer may be limited to a single frame. Ergo, we need to flush
52
+ # the buffer as often as possible.
53
+ cdef _recv_packet(self)
54
+ cdef _send_packet_and_recv(self, Packet packet)
55
+ cdef _recv_frame(self)
56
+
57
+ cdef _transfer_hwframe(self, Frame frame)
58
+
59
+ # Implemented by children for the generic send/recv API, so we have the
60
+ # correct subclass of Frame.
61
+ cdef Frame _next_frame
62
+ cdef Frame _alloc_next_frame(self)
63
+
64
+ cdef CodecContext wrap_codec_context(lib.AVCodecContext*, const lib.AVCodec*, HWAccel hwaccel)
lib/python3.10/site-packages/av/codec/context.pyx ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+ from libc.errno cimport EAGAIN
3
+ from libc.stdint cimport uint8_t
4
+ from libc.string cimport memcpy
5
+
6
+ from av.bytesource cimport ByteSource, bytesource
7
+ from av.codec.codec cimport Codec, wrap_codec
8
+ from av.dictionary cimport _Dictionary
9
+ from av.error cimport err_check
10
+ from av.packet cimport Packet
11
+ from av.utils cimport avrational_to_fraction, to_avrational
12
+
13
+ from enum import Flag, IntEnum
14
+
15
+ from av.dictionary import Dictionary
16
+
17
+
18
+ cdef object _cinit_sentinel = object()
19
+
20
+
21
+ cdef CodecContext wrap_codec_context(lib.AVCodecContext *c_ctx, const lib.AVCodec *c_codec, HWAccel hwaccel):
22
+ """Build an av.CodecContext for an existing AVCodecContext."""
23
+
24
+ cdef CodecContext py_ctx
25
+
26
+ if c_ctx.codec_type == lib.AVMEDIA_TYPE_VIDEO:
27
+ from av.video.codeccontext import VideoCodecContext
28
+ py_ctx = VideoCodecContext(_cinit_sentinel)
29
+ elif c_ctx.codec_type == lib.AVMEDIA_TYPE_AUDIO:
30
+ from av.audio.codeccontext import AudioCodecContext
31
+ py_ctx = AudioCodecContext(_cinit_sentinel)
32
+ elif c_ctx.codec_type == lib.AVMEDIA_TYPE_SUBTITLE:
33
+ from av.subtitles.codeccontext import SubtitleCodecContext
34
+ py_ctx = SubtitleCodecContext(_cinit_sentinel)
35
+ else:
36
+ py_ctx = CodecContext(_cinit_sentinel)
37
+
38
+ py_ctx._init(c_ctx, c_codec, hwaccel)
39
+
40
+ return py_ctx
41
+
42
+
43
+ class ThreadType(Flag):
44
+ NONE = 0
45
+ FRAME: "Decode more than one frame at once" = lib.FF_THREAD_FRAME
46
+ SLICE: "Decode more than one part of a single frame at once" = lib.FF_THREAD_SLICE
47
+ AUTO: "Decode using both FRAME and SLICE methods." = lib.FF_THREAD_SLICE | lib.FF_THREAD_FRAME
48
+
49
+ class Flags(IntEnum):
50
+ unaligned = lib.AV_CODEC_FLAG_UNALIGNED
51
+ qscale = lib.AV_CODEC_FLAG_QSCALE
52
+ four_mv = lib.AV_CODEC_FLAG_4MV
53
+ output_corrupt = lib.AV_CODEC_FLAG_OUTPUT_CORRUPT
54
+ qpel = lib.AV_CODEC_FLAG_QPEL
55
+ drop_changed = 1 << 5
56
+ recon_frame = lib.AV_CODEC_FLAG_RECON_FRAME
57
+ copy_opaque = lib.AV_CODEC_FLAG_COPY_OPAQUE
58
+ frame_duration = lib.AV_CODEC_FLAG_FRAME_DURATION
59
+ pass1 = lib.AV_CODEC_FLAG_PASS1
60
+ pass2 = lib.AV_CODEC_FLAG_PASS2
61
+ loop_filter = lib.AV_CODEC_FLAG_LOOP_FILTER
62
+ gray = lib.AV_CODEC_FLAG_GRAY
63
+ psnr = lib.AV_CODEC_FLAG_PSNR
64
+ interlaced_dct = lib.AV_CODEC_FLAG_INTERLACED_DCT
65
+ low_delay = lib.AV_CODEC_FLAG_LOW_DELAY
66
+ global_header = lib.AV_CODEC_FLAG_GLOBAL_HEADER
67
+ bitexact = lib.AV_CODEC_FLAG_BITEXACT
68
+ ac_pred = lib.AV_CODEC_FLAG_AC_PRED
69
+ interlaced_me = lib.AV_CODEC_FLAG_INTERLACED_ME
70
+ closed_gop = lib.AV_CODEC_FLAG_CLOSED_GOP
71
+
72
+ class Flags2(IntEnum):
73
+ fast = lib.AV_CODEC_FLAG2_FAST
74
+ no_output = lib.AV_CODEC_FLAG2_NO_OUTPUT
75
+ local_header = lib.AV_CODEC_FLAG2_LOCAL_HEADER
76
+ chunks = lib.AV_CODEC_FLAG2_CHUNKS
77
+ ignore_crop = lib.AV_CODEC_FLAG2_IGNORE_CROP
78
+ show_all = lib.AV_CODEC_FLAG2_SHOW_ALL
79
+ export_mvs = lib.AV_CODEC_FLAG2_EXPORT_MVS
80
+ skip_manual = lib.AV_CODEC_FLAG2_SKIP_MANUAL
81
+ ro_flush_noop = lib.AV_CODEC_FLAG2_RO_FLUSH_NOOP
82
+
83
+
84
+ cdef class CodecContext:
85
+ @staticmethod
86
+ def create(codec, mode=None, hwaccel=None):
87
+ cdef Codec cy_codec = codec if isinstance(codec, Codec) else Codec(codec, mode)
88
+ cdef lib.AVCodecContext *c_ctx = lib.avcodec_alloc_context3(cy_codec.ptr)
89
+ return wrap_codec_context(c_ctx, cy_codec.ptr, hwaccel)
90
+
91
+ def __cinit__(self, sentinel=None, *args, **kwargs):
92
+ if sentinel is not _cinit_sentinel:
93
+ raise RuntimeError("Cannot instantiate CodecContext")
94
+
95
+ self.options = {}
96
+ self.stream_index = -1 # This is set by the container immediately.
97
+ self.is_open = False
98
+
99
+ cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel):
100
+ self.ptr = ptr
101
+ if self.ptr.codec and codec and self.ptr.codec != codec:
102
+ raise RuntimeError("Wrapping CodecContext with mismatched codec.")
103
+ self.codec = wrap_codec(codec if codec != NULL else self.ptr.codec)
104
+ self.hwaccel = hwaccel
105
+
106
+ # Set reasonable threading defaults.
107
+ self.ptr.thread_count = 0 # use as many threads as there are CPUs.
108
+ self.ptr.thread_type = 0x02 # thread within a frame. Does not change the API.
109
+
110
+ @property
111
+ def flags(self):
112
+ """
113
+ Get and set the flags bitmask of CodecContext.
114
+
115
+ :rtype: int
116
+ """
117
+ return self.ptr.flags
118
+
119
+ @flags.setter
120
+ def flags(self, int value):
121
+ self.ptr.flags = value
122
+
123
+ @property
124
+ def qscale(self):
125
+ """
126
+ Use fixed qscale.
127
+
128
+ :rtype: bool
129
+ """
130
+ return bool(self.ptr.flags & lib.AV_CODEC_FLAG_QSCALE)
131
+
132
+ @qscale.setter
133
+ def qscale(self, value):
134
+ if value:
135
+ self.ptr.flags |= lib.AV_CODEC_FLAG_QSCALE
136
+ else:
137
+ self.ptr.flags &= ~lib.AV_CODEC_FLAG_QSCALE
138
+
139
+ @property
140
+ def copy_opaque(self):
141
+ return bool(self.ptr.flags & lib.AV_CODEC_FLAG_COPY_OPAQUE)
142
+
143
+ @copy_opaque.setter
144
+ def copy_opaque(self, value):
145
+ if value:
146
+ self.ptr.flags |= lib.AV_CODEC_FLAG_COPY_OPAQUE
147
+ else:
148
+ self.ptr.flags &= ~lib.AV_CODEC_FLAG_COPY_OPAQUE
149
+
150
+ @property
151
+ def flags2(self):
152
+ """
153
+ Get and set the flags2 bitmask of CodecContext.
154
+
155
+ :rtype: int
156
+ """
157
+ return self.ptr.flags2
158
+
159
+ @flags2.setter
160
+ def flags2(self, int value):
161
+ self.ptr.flags2 = value
162
+
163
+ @property
164
+ def extradata(self):
165
+ if self.ptr is NULL:
166
+ return None
167
+ if self.ptr.extradata_size > 0:
168
+ return <bytes>(<uint8_t*>self.ptr.extradata)[:self.ptr.extradata_size]
169
+ return None
170
+
171
+ @extradata.setter
172
+ def extradata(self, data):
173
+ if data is None:
174
+ lib.av_freep(&self.ptr.extradata)
175
+ self.ptr.extradata_size = 0
176
+ else:
177
+ source = bytesource(data)
178
+ self.ptr.extradata = <uint8_t*>lib.av_realloc(self.ptr.extradata, source.length + lib.AV_INPUT_BUFFER_PADDING_SIZE)
179
+ if not self.ptr.extradata:
180
+ raise MemoryError("Cannot allocate extradata")
181
+ memcpy(self.ptr.extradata, source.ptr, source.length)
182
+ self.ptr.extradata_size = source.length
183
+ self.extradata_set = True
184
+
185
+ @property
186
+ def extradata_size(self):
187
+ return self.ptr.extradata_size
188
+
189
+ @property
190
+ def is_encoder(self):
191
+ if self.ptr is NULL:
192
+ return False
193
+ return lib.av_codec_is_encoder(self.ptr.codec)
194
+
195
+ @property
196
+ def is_decoder(self):
197
+ if self.ptr is NULL:
198
+ return False
199
+ return lib.av_codec_is_decoder(self.ptr.codec)
200
+
201
+ cpdef open(self, bint strict=True):
202
+ if self.is_open:
203
+ if strict:
204
+ raise ValueError("CodecContext is already open.")
205
+ return
206
+
207
+ cdef _Dictionary options = Dictionary()
208
+ options.update(self.options or {})
209
+
210
+ if not self.ptr.time_base.num and self.is_encoder:
211
+ if self.type == "video":
212
+ self.ptr.time_base.num = self.ptr.framerate.den or 1
213
+ self.ptr.time_base.den = self.ptr.framerate.num or lib.AV_TIME_BASE
214
+ elif self.type == "audio":
215
+ self.ptr.time_base.num = 1
216
+ self.ptr.time_base.den = self.ptr.sample_rate
217
+ else:
218
+ self.ptr.time_base.num = 1
219
+ self.ptr.time_base.den = lib.AV_TIME_BASE
220
+
221
+ err_check(lib.avcodec_open2(self.ptr, self.codec.ptr, &options.ptr), "avcodec_open2(" + self.codec.name + ")")
222
+ self.is_open = True
223
+ self.options = dict(options)
224
+
225
+ def __dealloc__(self):
226
+ if self.ptr and self.extradata_set:
227
+ lib.av_freep(&self.ptr.extradata)
228
+ if self.ptr:
229
+ lib.avcodec_free_context(&self.ptr)
230
+ if self.parser:
231
+ lib.av_parser_close(self.parser)
232
+
233
+ def __repr__(self):
234
+ _type = self.type or "<notype>"
235
+ name = self.name or "<nocodec>"
236
+ return f"<av.{self.__class__.__name__} {_type}/{name} at 0x{id(self):x}>"
237
+
238
+ def parse(self, raw_input=None):
239
+ """Split up a byte stream into list of :class:`.Packet`.
240
+
241
+ This is only effectively splitting up a byte stream, and does no
242
+ actual interpretation of the data.
243
+
244
+ It will return all packets that are fully contained within the given
245
+ input, and will buffer partial packets until they are complete.
246
+
247
+ :param ByteSource raw_input: A chunk of a byte-stream to process.
248
+ Anything that can be turned into a :class:`.ByteSource` is fine.
249
+ ``None`` or empty inputs will flush the parser's buffers.
250
+
251
+ :return: ``list`` of :class:`.Packet` newly available.
252
+
253
+ """
254
+
255
+ if not self.parser:
256
+ self.parser = lib.av_parser_init(self.codec.ptr.id)
257
+ if not self.parser:
258
+ raise ValueError(f"No parser for {self.codec.name}")
259
+
260
+ cdef ByteSource source = bytesource(raw_input, allow_none=True)
261
+
262
+ cdef unsigned char *in_data = source.ptr if source is not None else NULL
263
+ cdef int in_size = source.length if source is not None else 0
264
+
265
+ cdef unsigned char *out_data
266
+ cdef int out_size
267
+ cdef int consumed
268
+ cdef Packet packet = None
269
+
270
+ packets = []
271
+
272
+ while True:
273
+ with nogil:
274
+ consumed = lib.av_parser_parse2(
275
+ self.parser,
276
+ self.ptr,
277
+ &out_data, &out_size,
278
+ in_data, in_size,
279
+ lib.AV_NOPTS_VALUE, lib.AV_NOPTS_VALUE,
280
+ 0
281
+ )
282
+ err_check(consumed)
283
+
284
+ if out_size:
285
+ # We copy the data immediately, as we have yet to figure out
286
+ # the expected lifetime of the buffer we get back. All of the
287
+ # examples decode it immediately.
288
+ #
289
+ # We've also tried:
290
+ # packet = Packet()
291
+ # packet.data = out_data
292
+ # packet.size = out_size
293
+ # packet.source = source
294
+ #
295
+ # ... but this results in corruption.
296
+
297
+ packet = Packet(out_size)
298
+ memcpy(packet.ptr.data, out_data, out_size)
299
+
300
+ packets.append(packet)
301
+
302
+ if not in_size:
303
+ # This was a flush. Only one packet should ever be returned.
304
+ break
305
+
306
+ in_data += consumed
307
+ in_size -= consumed
308
+
309
+ if not in_size:
310
+ break
311
+
312
+ return packets
313
+
314
+ @property
315
+ def is_hwaccel(self):
316
+ """
317
+ Returns ``True`` if this codec context is hardware accelerated, ``False`` otherwise.
318
+ """
319
+ return self.hwaccel_ctx is not None
320
+
321
+ def _send_frame_and_recv(self, Frame frame):
322
+ cdef Packet packet
323
+
324
+ cdef int res
325
+ with nogil:
326
+ res = lib.avcodec_send_frame(self.ptr, frame.ptr if frame is not None else NULL)
327
+ err_check(res, "avcodec_send_frame()")
328
+
329
+ packet = self._recv_packet()
330
+ while packet:
331
+ yield packet
332
+ packet = self._recv_packet()
333
+
334
+ cdef _send_packet_and_recv(self, Packet packet):
335
+ cdef Frame frame
336
+
337
+ cdef int res
338
+ with nogil:
339
+ res = lib.avcodec_send_packet(self.ptr, packet.ptr if packet is not None else NULL)
340
+ err_check(res, "avcodec_send_packet()")
341
+
342
+ out = []
343
+ while True:
344
+ frame = self._recv_frame()
345
+ if frame:
346
+ out.append(frame)
347
+ else:
348
+ break
349
+ return out
350
+
351
+ cdef _prepare_frames_for_encode(self, Frame frame):
352
+ return [frame]
353
+
354
+ cdef Frame _alloc_next_frame(self):
355
+ raise NotImplementedError("Base CodecContext cannot decode.")
356
+
357
+ cdef _recv_frame(self):
358
+ if not self._next_frame:
359
+ self._next_frame = self._alloc_next_frame()
360
+ cdef Frame frame = self._next_frame
361
+
362
+ cdef int res
363
+ with nogil:
364
+ res = lib.avcodec_receive_frame(self.ptr, frame.ptr)
365
+
366
+ if res == -EAGAIN or res == lib.AVERROR_EOF:
367
+ return
368
+ err_check(res, "avcodec_receive_frame()")
369
+
370
+ frame = self._transfer_hwframe(frame)
371
+
372
+ if not res:
373
+ self._next_frame = None
374
+ return frame
375
+
376
+ cdef _transfer_hwframe(self, Frame frame):
377
+ return frame
378
+
379
+ cdef _recv_packet(self):
380
+ cdef Packet packet = Packet()
381
+
382
+ cdef int res
383
+ with nogil:
384
+ res = lib.avcodec_receive_packet(self.ptr, packet.ptr)
385
+ if res == -EAGAIN or res == lib.AVERROR_EOF:
386
+ return
387
+ err_check(res, "avcodec_receive_packet()")
388
+
389
+ if not res:
390
+ return packet
391
+
392
+ cdef _prepare_and_time_rebase_frames_for_encode(self, Frame frame):
393
+ if self.ptr.codec_type not in [lib.AVMEDIA_TYPE_VIDEO, lib.AVMEDIA_TYPE_AUDIO]:
394
+ raise NotImplementedError("Encoding is only supported for audio and video.")
395
+
396
+ self.open(strict=False)
397
+
398
+ frames = self._prepare_frames_for_encode(frame)
399
+
400
+ # Assert the frames are in our time base.
401
+ # TODO: Don't mutate time.
402
+ for frame in frames:
403
+ if frame is not None:
404
+ frame._rebase_time(self.ptr.time_base)
405
+
406
+ return frames
407
+
408
+ cpdef encode(self, Frame frame=None):
409
+ """Encode a list of :class:`.Packet` from the given :class:`.Frame`."""
410
+ res = []
411
+ for frame in self._prepare_and_time_rebase_frames_for_encode(frame):
412
+ for packet in self._send_frame_and_recv(frame):
413
+ self._setup_encoded_packet(packet)
414
+ res.append(packet)
415
+ return res
416
+
417
+ def encode_lazy(self, Frame frame=None):
418
+ for frame in self._prepare_and_time_rebase_frames_for_encode(frame):
419
+ for packet in self._send_frame_and_recv(frame):
420
+ self._setup_encoded_packet(packet)
421
+ yield packet
422
+
423
+ cdef _setup_encoded_packet(self, Packet packet):
424
+ # We coerced the frame's time_base into the CodecContext's during encoding,
425
+ # and FFmpeg copied the frame's pts/dts to the packet, so keep track of
426
+ # this time_base in case the frame needs to be muxed to a container with
427
+ # a different time_base.
428
+ #
429
+ # NOTE: if the CodecContext's time_base is altered during encoding, all bets
430
+ # are off!
431
+ packet._time_base = self.ptr.time_base
432
+
433
+ cpdef decode(self, Packet packet=None):
434
+ """Decode a list of :class:`.Frame` from the given :class:`.Packet`.
435
+
436
+ If the packet is None, the buffers will be flushed. This is useful if
437
+ you do not want the library to automatically re-order frames for you
438
+ (if they are encoded with a codec that has B-frames).
439
+
440
+ """
441
+
442
+ if not self.codec.ptr:
443
+ raise ValueError("cannot decode unknown codec")
444
+
445
+ self.open(strict=False)
446
+
447
+ res = []
448
+ for frame in self._send_packet_and_recv(packet):
449
+ if isinstance(frame, Frame):
450
+ self._setup_decoded_frame(frame, packet)
451
+ res.append(frame)
452
+ return res
453
+
454
+ cpdef flush_buffers(self):
455
+ """Reset the internal codec state and discard all internal buffers.
456
+
457
+ Should be called before you start decoding from a new position e.g.
458
+ when seeking or when switching to a different stream.
459
+
460
+ """
461
+ if self.is_open:
462
+ with nogil:
463
+ lib.avcodec_flush_buffers(self.ptr)
464
+
465
+ cdef _setup_decoded_frame(self, Frame frame, Packet packet):
466
+ # Propagate our manual times.
467
+ # While decoding, frame times are in stream time_base, which PyAV
468
+ # is carrying around.
469
+ # TODO: Somehow get this from the stream so we can not pass the
470
+ # packet here (because flushing packets are bogus).
471
+ if packet is not None:
472
+ frame._time_base = packet._time_base
473
+
474
+ @property
475
+ def name(self):
476
+ return self.codec.name
477
+
478
+ @property
479
+ def type(self):
480
+ return self.codec.type
481
+
482
+ @property
483
+ def profiles(self):
484
+ """
485
+ List the available profiles for this stream.
486
+
487
+ :type: list[str]
488
+ """
489
+ ret = []
490
+ if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles:
491
+ return ret
492
+
493
+ # Profiles are always listed in the codec descriptor, but not necessarily in
494
+ # the codec itself. So use the descriptor here.
495
+ desc = self.codec.desc
496
+ cdef int i = 0
497
+ while desc.profiles[i].profile != lib.FF_PROFILE_UNKNOWN:
498
+ ret.append(desc.profiles[i].name)
499
+ i += 1
500
+
501
+ return ret
502
+
503
+ @property
504
+ def profile(self):
505
+ if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles:
506
+ return
507
+
508
+ # Profiles are always listed in the codec descriptor, but not necessarily in
509
+ # the codec itself. So use the descriptor here.
510
+ desc = self.codec.desc
511
+ cdef int i = 0
512
+ while desc.profiles[i].profile != lib.FF_PROFILE_UNKNOWN:
513
+ if desc.profiles[i].profile == self.ptr.profile:
514
+ return desc.profiles[i].name
515
+ i += 1
516
+
517
+ @profile.setter
518
+ def profile(self, value):
519
+ if not self.codec or not self.codec.desc or not self.codec.desc.profiles:
520
+ return
521
+
522
+ # Profiles are always listed in the codec descriptor, but not necessarily in
523
+ # the codec itself. So use the descriptor here.
524
+ desc = self.codec.desc
525
+ cdef int i = 0
526
+ while desc.profiles[i].profile != lib.FF_PROFILE_UNKNOWN:
527
+ if desc.profiles[i].name == value:
528
+ self.ptr.profile = desc.profiles[i].profile
529
+ return
530
+ i += 1
531
+
532
+ @property
533
+ def time_base(self):
534
+ if self.is_decoder:
535
+ raise RuntimeError("Cannot access 'time_base' as a decoder")
536
+ return avrational_to_fraction(&self.ptr.time_base)
537
+
538
+ @time_base.setter
539
+ def time_base(self, value):
540
+ if self.is_decoder:
541
+ raise RuntimeError("Cannot access 'time_base' as a decoder")
542
+ to_avrational(value, &self.ptr.time_base)
543
+
544
+ @property
545
+ def codec_tag(self):
546
+ return self.ptr.codec_tag.to_bytes(4, byteorder="little", signed=False).decode(
547
+ encoding="ascii")
548
+
549
+ @codec_tag.setter
550
+ def codec_tag(self, value):
551
+ if isinstance(value, str) and len(value) == 4:
552
+ self.ptr.codec_tag = int.from_bytes(value.encode(encoding="ascii"),
553
+ byteorder="little", signed=False)
554
+ else:
555
+ raise ValueError("Codec tag should be a 4 character string.")
556
+
557
+ @property
558
+ def bit_rate(self):
559
+ return self.ptr.bit_rate if self.ptr.bit_rate > 0 else None
560
+
561
+ @bit_rate.setter
562
+ def bit_rate(self, int value):
563
+ self.ptr.bit_rate = value
564
+
565
+ @property
566
+ def max_bit_rate(self):
567
+ if self.ptr.rc_max_rate > 0:
568
+ return self.ptr.rc_max_rate
569
+ else:
570
+ return None
571
+
572
+ @property
573
+ def bit_rate_tolerance(self):
574
+ self.ptr.bit_rate_tolerance
575
+
576
+ @bit_rate_tolerance.setter
577
+ def bit_rate_tolerance(self, int value):
578
+ self.ptr.bit_rate_tolerance = value
579
+
580
+ @property
581
+ def thread_count(self):
582
+ """How many threads to use; 0 means auto.
583
+
584
+ Wraps :ffmpeg:`AVCodecContext.thread_count`.
585
+
586
+ """
587
+ return self.ptr.thread_count
588
+
589
+ @thread_count.setter
590
+ def thread_count(self, int value):
591
+ if self.is_open:
592
+ raise RuntimeError("Cannot change thread_count after codec is open.")
593
+ self.ptr.thread_count = value
594
+
595
+ @property
596
+ def thread_type(self):
597
+ """One of :class:`.ThreadType`.
598
+
599
+ Wraps :ffmpeg:`AVCodecContext.thread_type`.
600
+
601
+ """
602
+ return ThreadType(self.ptr.thread_type)
603
+
604
+ @thread_type.setter
605
+ def thread_type(self, value):
606
+ if self.is_open:
607
+ raise RuntimeError("Cannot change thread_type after codec is open.")
608
+ if type(value) is int:
609
+ self.ptr.thread_type = value
610
+ elif type(value) is str:
611
+ self.ptr.thread_type = ThreadType[value].value
612
+ else:
613
+ self.ptr.thread_type = value.value
614
+
615
+ @property
616
+ def skip_frame(self):
617
+ """Returns one of the following str literals:
618
+
619
+ "NONE" Discard nothing
620
+ "DEFAULT" Discard useless packets like 0 size packets in AVI
621
+ "NONREF" Discard all non reference
622
+ "BIDIR" Discard all bidirectional frames
623
+ "NONINTRA" Discard all non intra frames
624
+ "NONKEY Discard all frames except keyframes
625
+ "ALL" Discard all
626
+
627
+ Wraps :ffmpeg:`AVCodecContext.skip_frame`.
628
+ """
629
+ value = self.ptr.skip_frame
630
+ if value == lib.AVDISCARD_NONE:
631
+ return "NONE"
632
+ if value == lib.AVDISCARD_DEFAULT:
633
+ return "DEFAULT"
634
+ if value == lib.AVDISCARD_NONREF:
635
+ return "NONREF"
636
+ if value == lib.AVDISCARD_BIDIR:
637
+ return "BIDIR"
638
+ if value == lib.AVDISCARD_NONINTRA:
639
+ return "NONINTRA"
640
+ if value == lib.AVDISCARD_NONKEY:
641
+ return "NONKEY"
642
+ if value == lib.AVDISCARD_ALL:
643
+ return "ALL"
644
+ return f"{value}"
645
+
646
+ @skip_frame.setter
647
+ def skip_frame(self, value):
648
+ if value == "NONE":
649
+ self.ptr.skip_frame = lib.AVDISCARD_NONE
650
+ elif value == "DEFAULT":
651
+ self.ptr.skip_frame = lib.AVDISCARD_DEFAULT
652
+ elif value == "NONREF":
653
+ self.ptr.skip_frame = lib.AVDISCARD_NONREF
654
+ elif value == "BIDIR":
655
+ self.ptr.skip_frame = lib.AVDISCARD_BIDIR
656
+ elif value == "NONINTRA":
657
+ self.ptr.skip_frame = lib.AVDISCARD_NONINTRA
658
+ elif value == "NONKEY":
659
+ self.ptr.skip_frame = lib.AVDISCARD_NONKEY
660
+ elif value == "ALL":
661
+ self.ptr.skip_frame = lib.AVDISCARD_ALL
662
+ else:
663
+ raise ValueError("Invalid skip_frame type")
664
+
665
+ @property
666
+ def delay(self):
667
+ """Codec delay.
668
+
669
+ Wraps :ffmpeg:`AVCodecContext.delay`.
670
+
671
+ """
672
+ return self.ptr.delay
lib/python3.10/site-packages/av/codec/hwaccel.pyx ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import weakref
2
+ from enum import IntEnum
3
+
4
+ cimport libav as lib
5
+
6
+ from av.codec.codec cimport Codec
7
+ from av.dictionary cimport _Dictionary
8
+ from av.error cimport err_check
9
+ from av.video.format cimport get_video_format
10
+
11
+ from av.dictionary import Dictionary
12
+
13
+
14
+ class HWDeviceType(IntEnum):
15
+ none = lib.AV_HWDEVICE_TYPE_NONE
16
+ vdpau = lib.AV_HWDEVICE_TYPE_VDPAU
17
+ cuda = lib.AV_HWDEVICE_TYPE_CUDA
18
+ vaapi = lib.AV_HWDEVICE_TYPE_VAAPI
19
+ dxva2 = lib.AV_HWDEVICE_TYPE_DXVA2
20
+ qsv = lib.AV_HWDEVICE_TYPE_QSV
21
+ videotoolbox = lib.AV_HWDEVICE_TYPE_VIDEOTOOLBOX
22
+ d3d11va = lib.AV_HWDEVICE_TYPE_D3D11VA
23
+ drm = lib.AV_HWDEVICE_TYPE_DRM
24
+ opencl = lib.AV_HWDEVICE_TYPE_OPENCL
25
+ mediacodec = lib.AV_HWDEVICE_TYPE_MEDIACODEC
26
+ vulkan = lib.AV_HWDEVICE_TYPE_VULKAN
27
+ d3d12va = lib.AV_HWDEVICE_TYPE_D3D12VA
28
+
29
+ class HWConfigMethod(IntEnum):
30
+ none = 0
31
+ hw_device_ctx = lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX # This is the only one we support.
32
+ hw_frame_ctx = lib.AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX
33
+ internal = lib.AV_CODEC_HW_CONFIG_METHOD_INTERNAL
34
+ ad_hoc = lib.AV_CODEC_HW_CONFIG_METHOD_AD_HOC
35
+
36
+
37
+ cdef object _cinit_sentinel = object()
38
+ cdef object _singletons = weakref.WeakValueDictionary()
39
+
40
+ cdef HWConfig wrap_hwconfig(lib.AVCodecHWConfig *ptr):
41
+ try:
42
+ return _singletons[<int>ptr]
43
+ except KeyError:
44
+ pass
45
+ cdef HWConfig config = HWConfig(_cinit_sentinel)
46
+ config._init(ptr)
47
+ _singletons[<int>ptr] = config
48
+ return config
49
+
50
+
51
+ cdef class HWConfig:
52
+ def __init__(self, sentinel):
53
+ if sentinel is not _cinit_sentinel:
54
+ raise RuntimeError("Cannot instantiate CodecContext")
55
+
56
+ cdef void _init(self, lib.AVCodecHWConfig *ptr):
57
+ self.ptr = ptr
58
+
59
+ def __repr__(self):
60
+ return (
61
+ f"<av.{self.__class__.__name__} "
62
+ f"device_type={lib.av_hwdevice_get_type_name(self.device_type)} "
63
+ f"format={self.format.name if self.format else None} "
64
+ f"is_supported={self.is_supported} at 0x{<int>self.ptr:x}>"
65
+ )
66
+
67
+ @property
68
+ def device_type(self):
69
+ return HWDeviceType(self.ptr.device_type)
70
+
71
+ @property
72
+ def format(self):
73
+ return get_video_format(self.ptr.pix_fmt, 0, 0)
74
+
75
+ @property
76
+ def methods(self):
77
+ return HWConfigMethod(self.ptr.methods)
78
+
79
+ @property
80
+ def is_supported(self):
81
+ return bool(self.ptr.methods & lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX)
82
+
83
+
84
+ cpdef hwdevices_available():
85
+ result = []
86
+
87
+ cdef lib.AVHWDeviceType x = lib.AV_HWDEVICE_TYPE_NONE
88
+ while True:
89
+ x = lib.av_hwdevice_iterate_types(x)
90
+ if x == lib.AV_HWDEVICE_TYPE_NONE:
91
+ break
92
+ result.append(lib.av_hwdevice_get_type_name(HWDeviceType(x)))
93
+
94
+ return result
95
+
96
+
97
+ cdef class HWAccel:
98
+ def __init__(self, device_type, device=None, allow_software_fallback=True, options=None, flags=None):
99
+ if isinstance(device_type, HWDeviceType):
100
+ self._device_type = device_type
101
+ elif isinstance(device_type, str):
102
+ self._device_type = int(lib.av_hwdevice_find_type_by_name(device_type))
103
+ elif isinstance(device_type, int):
104
+ self._device_type = device_type
105
+ else:
106
+ raise ValueError("Unknown type for device_type")
107
+
108
+ self._device = device
109
+ self.allow_software_fallback = allow_software_fallback
110
+ self.options = {} if not options else dict(options)
111
+ self.flags = 0 if not flags else flags
112
+ self.ptr = NULL
113
+ self.config = None
114
+
115
+ def _initialize_hw_context(self, Codec codec not None):
116
+ cdef HWConfig config
117
+ for config in codec.hardware_configs:
118
+ if not (config.ptr.methods & lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX):
119
+ continue
120
+ if self._device_type and config.device_type != self._device_type:
121
+ continue
122
+ break
123
+ else:
124
+ raise NotImplementedError(f"No supported hardware config for {codec}")
125
+
126
+ self.config = config
127
+
128
+ cdef char *c_device = NULL
129
+ if self._device:
130
+ device_bytes = self._device.encode()
131
+ c_device = device_bytes
132
+ cdef _Dictionary c_options = Dictionary(self.options)
133
+
134
+ err_check(
135
+ lib.av_hwdevice_ctx_create(
136
+ &self.ptr, config.ptr.device_type, c_device, c_options.ptr, self.flags
137
+ )
138
+ )
139
+
140
+ def create(self, Codec codec not None):
141
+ """Create a new hardware accelerator context with the given codec"""
142
+ if self.ptr:
143
+ raise RuntimeError("Hardware context already initialized")
144
+
145
+ ret = HWAccel(
146
+ device_type=self._device_type,
147
+ device=self._device,
148
+ allow_software_fallback=self.allow_software_fallback,
149
+ options=self.options
150
+ )
151
+ ret._initialize_hw_context(codec)
152
+ return ret
153
+
154
+ def __dealloc__(self):
155
+ if self.ptr:
156
+ lib.av_buffer_unref(&self.ptr)
lib/python3.10/site-packages/av/filter/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .filter import Filter, FilterFlags, filter_descriptor, filters_available
2
+ from .graph import Graph
3
+ from .loudnorm import stats
lib/python3.10/site-packages/av/filter/__init__.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .context import *
2
+ from .filter import *
3
+ from .graph import *
4
+ from .loudnorm import *
lib/python3.10/site-packages/av/filter/context.pyi ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.filter import Graph
2
+ from av.frame import Frame
3
+
4
+ from .pad import FilterContextPad
5
+
6
+ class FilterContext:
7
+ name: str | None
8
+ inputs: tuple[FilterContextPad, ...]
9
+ outputs: tuple[FilterContextPad, ...]
10
+
11
+ def init(self, args: str | None = None, **kwargs: str | None) -> None: ...
12
+ def link_to(
13
+ self, input_: FilterContext, output_idx: int = 0, input_idx: int = 0
14
+ ) -> None: ...
15
+ @property
16
+ def graph(self) -> Graph: ...
17
+ def push(self, frame: Frame) -> None: ...
18
+ def pull(self) -> Frame: ...
lib/python3.10/site-packages/av/filter/context.pyx ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import weakref
2
+
3
+ from av.audio.frame cimport alloc_audio_frame
4
+ from av.dictionary cimport _Dictionary
5
+ from av.dictionary import Dictionary
6
+ from av.error cimport err_check
7
+ from av.filter.pad cimport alloc_filter_pads
8
+ from av.frame cimport Frame
9
+ from av.utils cimport avrational_to_fraction
10
+ from av.video.frame cimport alloc_video_frame
11
+
12
+
13
+ cdef object _cinit_sentinel = object()
14
+
15
+
16
+ cdef FilterContext wrap_filter_context(Graph graph, Filter filter, lib.AVFilterContext *ptr):
17
+ cdef FilterContext self = FilterContext(_cinit_sentinel)
18
+ self._graph = weakref.ref(graph)
19
+ self.filter = filter
20
+ self.ptr = ptr
21
+ return self
22
+
23
+
24
+ cdef class FilterContext:
25
+ def __cinit__(self, sentinel):
26
+ if sentinel is not _cinit_sentinel:
27
+ raise RuntimeError("cannot construct FilterContext")
28
+
29
+ def __repr__(self):
30
+ if self.ptr != NULL:
31
+ name = repr(self.ptr.name) if self.ptr.name != NULL else "<NULL>"
32
+ else:
33
+ name = "None"
34
+
35
+ parent = self.filter.ptr.name if self.filter and self.filter.ptr != NULL else None
36
+ return f"<av.FilterContext {name} of {parent!r} at 0x{id(self):x}>"
37
+
38
+ @property
39
+ def name(self):
40
+ if self.ptr.name != NULL:
41
+ return self.ptr.name
42
+
43
+ @property
44
+ def inputs(self):
45
+ if self._inputs is None:
46
+ self._inputs = alloc_filter_pads(self.filter, self.ptr.input_pads, True, self)
47
+ return self._inputs
48
+
49
+ @property
50
+ def outputs(self):
51
+ if self._outputs is None:
52
+ self._outputs = alloc_filter_pads(self.filter, self.ptr.output_pads, False, self)
53
+ return self._outputs
54
+
55
+ def init(self, args=None, **kwargs):
56
+ if self.inited:
57
+ raise ValueError("already inited")
58
+ if args and kwargs:
59
+ raise ValueError("cannot init from args and kwargs")
60
+
61
+ cdef _Dictionary dict_ = None
62
+ cdef char *c_args = NULL
63
+ if args or not kwargs:
64
+ if args:
65
+ c_args = args
66
+ err_check(lib.avfilter_init_str(self.ptr, c_args))
67
+ else:
68
+ dict_ = Dictionary(kwargs)
69
+ err_check(lib.avfilter_init_dict(self.ptr, &dict_.ptr))
70
+
71
+ self.inited = True
72
+ if dict_:
73
+ raise ValueError(f"unused config: {', '.join(sorted(dict_))}")
74
+
75
+ def link_to(self, FilterContext input_, int output_idx=0, int input_idx=0):
76
+ err_check(lib.avfilter_link(self.ptr, output_idx, input_.ptr, input_idx))
77
+
78
+ @property
79
+ def graph(self):
80
+ if (graph := self._graph()):
81
+ return graph
82
+ else:
83
+ raise RuntimeError("graph is unallocated")
84
+
85
+ def push(self, Frame frame):
86
+ cdef int res
87
+
88
+ if frame is None:
89
+ with nogil:
90
+ res = lib.av_buffersrc_write_frame(self.ptr, NULL)
91
+ err_check(res)
92
+ return
93
+ elif self.filter.name in ("abuffer", "buffer"):
94
+ with nogil:
95
+ res = lib.av_buffersrc_write_frame(self.ptr, frame.ptr)
96
+ err_check(res)
97
+ return
98
+
99
+ # Delegate to the input.
100
+ if len(self.inputs) != 1:
101
+ raise ValueError(
102
+ f"cannot delegate push without single input; found {len(self.inputs)}"
103
+ )
104
+ if not self.inputs[0].link:
105
+ raise ValueError("cannot delegate push without linked input")
106
+ self.inputs[0].linked.context.push(frame)
107
+
108
+ def pull(self):
109
+ cdef Frame frame
110
+ cdef int res
111
+
112
+ if self.filter.name == "buffersink":
113
+ frame = alloc_video_frame()
114
+ elif self.filter.name == "abuffersink":
115
+ frame = alloc_audio_frame()
116
+ else:
117
+ # Delegate to the output.
118
+ if len(self.outputs) != 1:
119
+ raise ValueError(
120
+ f"cannot delegate pull without single output; found {len(self.outputs)}"
121
+ )
122
+ if not self.outputs[0].link:
123
+ raise ValueError("cannot delegate pull without linked output")
124
+ return self.outputs[0].linked.context.pull()
125
+
126
+ self.graph.configure()
127
+
128
+ with nogil:
129
+ res = lib.av_buffersink_get_frame(self.ptr, frame.ptr)
130
+ err_check(res)
131
+
132
+ frame._init_user_attributes()
133
+ frame.time_base = avrational_to_fraction(&self.ptr.inputs[0].time_base)
134
+ return frame
lib/python3.10/site-packages/av/filter/filter.pxd ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+ from av.descriptor cimport Descriptor
4
+
5
+
6
+ cdef class Filter:
7
+
8
+ cdef const lib.AVFilter *ptr
9
+
10
+ cdef object _inputs
11
+ cdef object _outputs
12
+ cdef Descriptor _descriptor
13
+
14
+
15
+ cdef Filter wrap_filter(const lib.AVFilter *ptr)
lib/python3.10/site-packages/av/filter/filter.pyi ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from av.descriptor import Descriptor
2
+ from av.option import Option
3
+
4
+ from .pad import FilterPad
5
+
6
+ class Filter:
7
+ name: str
8
+ description: str
9
+
10
+ descriptor: Descriptor
11
+ options: tuple[Option, ...] | None
12
+ flags: int
13
+ dynamic_inputs: bool
14
+ dynamic_outputs: bool
15
+ timeline_support: bool
16
+ slice_threads: bool
17
+ command_support: bool
18
+ inputs: tuple[FilterPad, ...]
19
+ outputs: tuple[FilterPad, ...]
20
+
21
+ def __init__(self, name: str) -> None: ...
22
+
23
+ filters_available: set[str]
lib/python3.10/site-packages/av/filter/filter.pyx ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+ from av.descriptor cimport wrap_avclass
4
+ from av.filter.pad cimport alloc_filter_pads
5
+
6
+
7
+ cdef object _cinit_sentinel = object()
8
+
9
+
10
+ cdef Filter wrap_filter(const lib.AVFilter *ptr):
11
+ cdef Filter filter_ = Filter(_cinit_sentinel)
12
+ filter_.ptr = ptr
13
+ return filter_
14
+
15
+
16
+ cpdef enum FilterFlags:
17
+ DYNAMIC_INPUTS = lib.AVFILTER_FLAG_DYNAMIC_INPUTS
18
+ DYNAMIC_OUTPUTS = lib.AVFILTER_FLAG_DYNAMIC_OUTPUTS
19
+ SLICE_THREADS = lib.AVFILTER_FLAG_SLICE_THREADS
20
+ SUPPORT_TIMELINE_GENERIC = lib.AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC
21
+ SUPPORT_TIMELINE_INTERNAL = lib.AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL
22
+
23
+
24
+ cdef class Filter:
25
+ def __cinit__(self, name):
26
+ if name is _cinit_sentinel:
27
+ return
28
+ if not isinstance(name, str):
29
+ raise TypeError("takes a filter name as a string")
30
+ self.ptr = lib.avfilter_get_by_name(name)
31
+ if not self.ptr:
32
+ raise ValueError(f"no filter {name}")
33
+
34
+ @property
35
+ def descriptor(self):
36
+ if self._descriptor is None:
37
+ self._descriptor = wrap_avclass(self.ptr.priv_class)
38
+ return self._descriptor
39
+
40
+ @property
41
+ def options(self):
42
+ if self.descriptor is None:
43
+ return
44
+ return self.descriptor.options
45
+
46
+ @property
47
+ def name(self):
48
+ return self.ptr.name
49
+
50
+ @property
51
+ def description(self):
52
+ return self.ptr.description
53
+
54
+ @property
55
+ def flags(self):
56
+ return self.ptr.flags
57
+
58
+ @property
59
+ def dynamic_inputs(self):
60
+ return bool(self.ptr.flags & lib.AVFILTER_FLAG_DYNAMIC_INPUTS)
61
+
62
+ @property
63
+ def dynamic_outputs(self):
64
+ return bool(self.ptr.flags & lib.AVFILTER_FLAG_DYNAMIC_OUTPUTS)
65
+
66
+ @property
67
+ def timeline_support(self):
68
+ return bool(self.ptr.flags & lib.AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC)
69
+
70
+ @property
71
+ def slice_threads(self):
72
+ return bool(self.ptr.flags & lib.AVFILTER_FLAG_SLICE_THREADS)
73
+
74
+ @property
75
+ def command_support(self):
76
+ return self.ptr.process_command != NULL
77
+
78
+ @property
79
+ def inputs(self):
80
+ if self._inputs is None:
81
+ self._inputs = alloc_filter_pads(self, self.ptr.inputs, True)
82
+ return self._inputs
83
+
84
+ @property
85
+ def outputs(self):
86
+ if self._outputs is None:
87
+ self._outputs = alloc_filter_pads(self, self.ptr.outputs, False)
88
+ return self._outputs
89
+
90
+
91
+ cdef get_filter_names():
92
+ names = set()
93
+ cdef const lib.AVFilter *ptr
94
+ cdef void *opaque = NULL
95
+ while True:
96
+ ptr = lib.av_filter_iterate(&opaque)
97
+ if ptr:
98
+ names.add(ptr.name)
99
+ else:
100
+ break
101
+ return names
102
+
103
+ filters_available = get_filter_names()
104
+
105
+
106
+ filter_descriptor = wrap_avclass(lib.avfilter_get_class())
lib/python3.10/site-packages/av/filter/graph.pxd ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+ from av.filter.context cimport FilterContext
4
+
5
+
6
+ cdef class Graph:
7
+ cdef object __weakref__
8
+
9
+ cdef lib.AVFilterGraph *ptr
10
+
11
+ cdef readonly bint configured
12
+ cpdef configure(self, bint auto_buffer=*, bint force=*)
13
+
14
+ cdef dict _name_counts
15
+ cdef str _get_unique_name(self, str name)
16
+
17
+ cdef _register_context(self, FilterContext)
18
+ cdef _auto_register(self)
19
+ cdef int _nb_filters_seen
20
+ cdef dict _context_by_ptr
21
+ cdef dict _context_by_name
22
+ cdef dict _context_by_type
lib/python3.10/site-packages/av/filter/graph.pyi ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fractions import Fraction
2
+ from typing import Any
3
+
4
+ from av.audio.format import AudioFormat
5
+ from av.audio.frame import AudioFrame
6
+ from av.audio.layout import AudioLayout
7
+ from av.audio.stream import AudioStream
8
+ from av.video.format import VideoFormat
9
+ from av.video.frame import VideoFrame
10
+ from av.video.stream import VideoStream
11
+
12
+ from .context import FilterContext
13
+ from .filter import Filter
14
+
15
+ class Graph:
16
+ configured: bool
17
+
18
+ def __init__(self) -> None: ...
19
+ def configure(self, auto_buffer: bool = True, force: bool = False) -> None: ...
20
+ def link_nodes(self, *nodes: FilterContext) -> Graph: ...
21
+ def add(
22
+ self, filter: str | Filter, args: Any = None, **kwargs: str
23
+ ) -> FilterContext: ...
24
+ def add_buffer(
25
+ self,
26
+ template: VideoStream | None = None,
27
+ width: int | None = None,
28
+ height: int | None = None,
29
+ format: VideoFormat | None = None,
30
+ name: str | None = None,
31
+ time_base: Fraction | None = None,
32
+ ) -> FilterContext: ...
33
+ def add_abuffer(
34
+ self,
35
+ template: AudioStream | None = None,
36
+ sample_rate: int | None = None,
37
+ format: AudioFormat | str | None = None,
38
+ layout: AudioLayout | str | None = None,
39
+ channels: int | None = None,
40
+ name: str | None = None,
41
+ time_base: Fraction | None = None,
42
+ ) -> FilterContext: ...
43
+ def set_audio_frame_size(self, frame_size: int) -> None: ...
44
+ def push(self, frame: None | AudioFrame | VideoFrame) -> None: ...
45
+ def pull(self) -> VideoFrame | AudioFrame: ...
46
+ def vpush(self, frame: VideoFrame | None) -> None: ...
47
+ def vpull(self) -> VideoFrame: ...
lib/python3.10/site-packages/av/filter/graph.pyx ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from fractions import Fraction
3
+
4
+ from av.audio.format cimport AudioFormat
5
+ from av.audio.frame cimport AudioFrame
6
+ from av.audio.layout cimport AudioLayout
7
+ from av.error cimport err_check
8
+ from av.filter.context cimport FilterContext, wrap_filter_context
9
+ from av.filter.filter cimport Filter, wrap_filter
10
+ from av.video.format cimport VideoFormat
11
+ from av.video.frame cimport VideoFrame
12
+
13
+
14
+ cdef class Graph:
15
+ def __cinit__(self):
16
+ self.ptr = lib.avfilter_graph_alloc()
17
+ self.configured = False
18
+ self._name_counts = {}
19
+
20
+ self._nb_filters_seen = 0
21
+ self._context_by_ptr = {}
22
+ self._context_by_name = {}
23
+ self._context_by_type = {}
24
+
25
+ def __dealloc__(self):
26
+ if self.ptr:
27
+ # This frees the graph, filter contexts, links, etc..
28
+ lib.avfilter_graph_free(&self.ptr)
29
+
30
+ cdef str _get_unique_name(self, str name):
31
+ count = self._name_counts.get(name, 0)
32
+ self._name_counts[name] = count + 1
33
+ if count:
34
+ return "%s_%s" % (name, count)
35
+ else:
36
+ return name
37
+
38
+ cpdef configure(self, bint auto_buffer=True, bint force=False):
39
+ if self.configured and not force:
40
+ return
41
+
42
+ err_check(lib.avfilter_graph_config(self.ptr, NULL))
43
+ self.configured = True
44
+
45
+ # We get auto-inserted stuff here.
46
+ self._auto_register()
47
+
48
+ def link_nodes(self, *nodes):
49
+ """
50
+ Links nodes together for simple filter graphs.
51
+ """
52
+ for c, n in zip(nodes, nodes[1:]):
53
+ c.link_to(n)
54
+ return self
55
+
56
+ def add(self, filter, args=None, **kwargs):
57
+ cdef Filter cy_filter
58
+ if isinstance(filter, str):
59
+ cy_filter = Filter(filter)
60
+ elif isinstance(filter, Filter):
61
+ cy_filter = filter
62
+ else:
63
+ raise TypeError("filter must be a string or Filter")
64
+
65
+ cdef str name = self._get_unique_name(kwargs.pop("name", None) or cy_filter.name)
66
+
67
+ cdef lib.AVFilterContext *ptr = lib.avfilter_graph_alloc_filter(self.ptr, cy_filter.ptr, name)
68
+ if not ptr:
69
+ raise RuntimeError("Could not allocate AVFilterContext")
70
+
71
+ # Manually construct this context (so we can return it).
72
+ cdef FilterContext ctx = wrap_filter_context(self, cy_filter, ptr)
73
+ ctx.init(args, **kwargs)
74
+ self._register_context(ctx)
75
+
76
+ # There might have been automatic contexts added (e.g. resamplers,
77
+ # fifos, and scalers). It is more likely to see them after the graph
78
+ # is configured, but we want to be safe.
79
+ self._auto_register()
80
+
81
+ return ctx
82
+
83
+ cdef _register_context(self, FilterContext ctx):
84
+ self._context_by_ptr[<long>ctx.ptr] = ctx
85
+ self._context_by_name[ctx.ptr.name] = ctx
86
+ self._context_by_type.setdefault(ctx.filter.ptr.name, []).append(ctx)
87
+
88
+ cdef _auto_register(self):
89
+ cdef int i
90
+ cdef lib.AVFilterContext *c_ctx
91
+ cdef Filter filter_
92
+ cdef FilterContext py_ctx
93
+ # We assume that filters are never removed from the graph. At this
94
+ # point we don't expose that in the API, so we should be okay...
95
+ for i in range(self._nb_filters_seen, self.ptr.nb_filters):
96
+ c_ctx = self.ptr.filters[i]
97
+ if <long>c_ctx in self._context_by_ptr:
98
+ continue
99
+ filter_ = wrap_filter(c_ctx.filter)
100
+ py_ctx = wrap_filter_context(self, filter_, c_ctx)
101
+ self._register_context(py_ctx)
102
+ self._nb_filters_seen = self.ptr.nb_filters
103
+
104
+ def add_buffer(self, template=None, width=None, height=None, format=None, name=None, time_base=None):
105
+ if template is not None:
106
+ if width is None:
107
+ width = template.width
108
+ if height is None:
109
+ height = template.height
110
+ if format is None:
111
+ format = template.format
112
+ if time_base is None:
113
+ time_base = template.time_base
114
+
115
+ if width is None:
116
+ raise ValueError("missing width")
117
+ if height is None:
118
+ raise ValueError("missing height")
119
+ if format is None:
120
+ raise ValueError("missing format")
121
+ if time_base is None:
122
+ warnings.warn("missing time_base. Guessing 1/1000 time base. "
123
+ "This is deprecated and may be removed in future releases.",
124
+ DeprecationWarning)
125
+ time_base = Fraction(1, 1000)
126
+
127
+ return self.add(
128
+ "buffer",
129
+ name=name,
130
+ video_size=f"{width}x{height}",
131
+ pix_fmt=str(int(VideoFormat(format))),
132
+ time_base=str(time_base),
133
+ pixel_aspect="1/1",
134
+ )
135
+
136
+ def add_abuffer(self, template=None, sample_rate=None, format=None, layout=None, channels=None, name=None, time_base=None):
137
+ """
138
+ Convenience method for adding `abuffer <https://ffmpeg.org/ffmpeg-filters.html#abuffer>`_.
139
+ """
140
+
141
+ if template is not None:
142
+ if sample_rate is None:
143
+ sample_rate = template.sample_rate
144
+ if format is None:
145
+ format = template.format
146
+ if layout is None:
147
+ layout = template.layout.name
148
+ if channels is None:
149
+ channels = template.channels
150
+ if time_base is None:
151
+ time_base = template.time_base
152
+
153
+ if sample_rate is None:
154
+ raise ValueError("missing sample_rate")
155
+ if format is None:
156
+ raise ValueError("missing format")
157
+ if layout is None and channels is None:
158
+ raise ValueError("missing layout or channels")
159
+ if time_base is None:
160
+ time_base = Fraction(1, sample_rate)
161
+
162
+ kwargs = dict(
163
+ sample_rate=str(sample_rate),
164
+ sample_fmt=AudioFormat(format).name,
165
+ time_base=str(time_base),
166
+ )
167
+ if layout:
168
+ kwargs["channel_layout"] = AudioLayout(layout).name
169
+ if channels:
170
+ kwargs["channels"] = str(channels)
171
+
172
+ return self.add("abuffer", name=name, **kwargs)
173
+
174
+ def set_audio_frame_size(self, frame_size):
175
+ """
176
+ Set the audio frame size for the graphs `abuffersink`.
177
+ See `av_buffersink_set_frame_size <https://ffmpeg.org/doxygen/trunk/group__lavfi__buffersink.html#ga359d7d1e42c27ca14c07559d4e9adba7>`_.
178
+ """
179
+ if not self.configured:
180
+ raise ValueError("graph not configured")
181
+ sinks = self._context_by_type.get("abuffersink", [])
182
+ if not sinks:
183
+ raise ValueError("missing abuffersink filter")
184
+ for sink in sinks:
185
+ lib.av_buffersink_set_frame_size((<FilterContext>sink).ptr, frame_size)
186
+
187
+ def push(self, frame):
188
+ if frame is None:
189
+ contexts = self._context_by_type.get("buffer", []) + self._context_by_type.get("abuffer", [])
190
+ elif isinstance(frame, VideoFrame):
191
+ contexts = self._context_by_type.get("buffer", [])
192
+ elif isinstance(frame, AudioFrame):
193
+ contexts = self._context_by_type.get("abuffer", [])
194
+ else:
195
+ raise ValueError(f"can only AudioFrame, VideoFrame or None; got {type(frame)}")
196
+
197
+ for ctx in contexts:
198
+ ctx.push(frame)
199
+
200
+ def vpush(self, VideoFrame frame):
201
+ """Like `push`, but only for VideoFrames."""
202
+ for ctx in self._context_by_type.get("buffer", []):
203
+ ctx.push(frame)
204
+
205
+
206
+ # TODO: Test complex filter graphs, add `at: int = 0` arg to pull() and vpull().
207
+ def pull(self):
208
+ vsinks = self._context_by_type.get("buffersink", [])
209
+ asinks = self._context_by_type.get("abuffersink", [])
210
+
211
+ nsinks = len(vsinks) + len(asinks)
212
+ if nsinks != 1:
213
+ raise ValueError(f"can only auto-pull with single sink; found {nsinks}")
214
+
215
+ return (vsinks or asinks)[0].pull()
216
+
217
+ def vpull(self):
218
+ """Like `pull`, but only for VideoFrames."""
219
+ vsinks = self._context_by_type.get("buffersink", [])
220
+ nsinks = len(vsinks)
221
+ if nsinks != 1:
222
+ raise ValueError(f"can only auto-pull with single sink; found {nsinks}")
223
+
224
+ return vsinks[0].pull()
lib/python3.10/site-packages/av/filter/link.pxd ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+ from av.filter.graph cimport Graph
4
+ from av.filter.pad cimport FilterContextPad
5
+
6
+
7
+ cdef class FilterLink:
8
+
9
+ cdef readonly Graph graph
10
+ cdef lib.AVFilterLink *ptr
11
+
12
+ cdef FilterContextPad _input
13
+ cdef FilterContextPad _output
14
+
15
+
16
+ cdef FilterLink wrap_filter_link(Graph graph, lib.AVFilterLink *ptr)
lib/python3.10/site-packages/av/filter/link.pyi ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .pad import FilterContextPad
2
+
3
+ class FilterLink:
4
+ input: FilterContextPad
5
+ output: FilterContextPad
lib/python3.10/site-packages/av/filter/link.pyx ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport libav as lib
2
+
3
+ from av.filter.graph cimport Graph
4
+
5
+
6
+ cdef _cinit_sentinel = object()
7
+
8
+
9
+ cdef class FilterLink:
10
+
11
+ def __cinit__(self, sentinel):
12
+ if sentinel is not _cinit_sentinel:
13
+ raise RuntimeError("cannot instantiate FilterLink")
14
+
15
+ @property
16
+ def input(self):
17
+ if self._input:
18
+ return self._input
19
+ cdef lib.AVFilterContext *cctx = self.ptr.src
20
+ cdef unsigned int i
21
+ for i in range(cctx.nb_outputs):
22
+ if self.ptr == cctx.outputs[i]:
23
+ break
24
+ else:
25
+ raise RuntimeError("could not find link in context")
26
+ ctx = self.graph._context_by_ptr[<long>cctx]
27
+ self._input = ctx.outputs[i]
28
+ return self._input
29
+
30
+ @property
31
+ def output(self):
32
+ if self._output:
33
+ return self._output
34
+ cdef lib.AVFilterContext *cctx = self.ptr.dst
35
+ cdef unsigned int i
36
+ for i in range(cctx.nb_inputs):
37
+ if self.ptr == cctx.inputs[i]:
38
+ break
39
+ else:
40
+ raise RuntimeError("could not find link in context")
41
+ try:
42
+ ctx = self.graph._context_by_ptr[<long>cctx]
43
+ except KeyError:
44
+ raise RuntimeError("could not find context in graph", (cctx.name, cctx.filter.name))
45
+ self._output = ctx.inputs[i]
46
+ return self._output
47
+
48
+
49
+ cdef FilterLink wrap_filter_link(Graph graph, lib.AVFilterLink *ptr):
50
+ cdef FilterLink link = FilterLink(_cinit_sentinel)
51
+ link.graph = graph
52
+ link.ptr = ptr
53
+ return link
lib/python3.10/site-packages/av/filter/loudnorm.pxd ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from av.audio.stream cimport AudioStream
2
+
3
+
4
+ cpdef bytes stats(str loudnorm_args, AudioStream stream)