| 1 |
import warnings |
| 2 |
from fractions import Fraction |
| 3 |
|
| 4 |
import cython |
| 5 |
from cython.cimports.av.audio.format import AudioFormat |
| 6 |
from cython.cimports.av.audio.frame import AudioFrame |
| 7 |
from cython.cimports.av.audio.layout import AudioLayout |
| 8 |
from cython.cimports.av.error import err_check |
| 9 |
from cython.cimports.av.filter.context import FilterContext, wrap_filter_context |
| 10 |
from cython.cimports.av.filter.filter import Filter, wrap_filter |
| 11 |
from cython.cimports.av.video.format import VideoFormat |
| 12 |
from cython.cimports.av.video.frame import VideoFrame |
| 13 |
|
| 14 |
|
| 15 |
@cython.final |
| 16 |
@cython.cclass |
| 17 |
class Graph: |
| 18 |
def __cinit__(self): |
| 19 |
self.ptr = lib.avfilter_graph_alloc() |
| 20 |
self.configured = False |
| 21 |
self._name_counts = {} |
| 22 |
self._nb_filters_seen = 0 |
| 23 |
self._context_by_ptr = {} |
| 24 |
self._context_by_type = {} |
| 25 |
|
| 26 |
def __dealloc__(self): |
| 27 |
if self.ptr: |
| 28 |
# This frees the graph, filter contexts, links, etc.. |
| 29 |
lib.avfilter_graph_free(cython.address(self.ptr)) |
| 30 |
|
| 31 |
@property |
| 32 |
def threads(self): |
| 33 |
"""Maximum number of threads used by filters in this graph. |
| 34 |
|
| 35 |
Set to 0 for automatic thread count. Must be set before adding any |
| 36 |
filters to the graph. |
| 37 |
|
| 38 |
Wraps :ffmpeg:`AVFilterGraph.nb_threads`. |
| 39 |
""" |
| 40 |
return self.ptr.nb_threads |
| 41 |
|
| 42 |
@threads.setter |
| 43 |
def threads(self, value: cython.int): |
| 44 |
if self.ptr.nb_filters: |
| 45 |
raise RuntimeError("Cannot change threads after filters have been added.") |
| 46 |
self.ptr.nb_threads = value |
| 47 |
|
| 48 |
@cython.cfunc |
| 49 |
def _get_unique_name(self, name: str) -> str: |
| 50 |
count = self._name_counts.get(name, 0) |
| 51 |
self._name_counts[name] = count + 1 |
| 52 |
if count: |
| 53 |
return "%s_%s" % (name, count) |
| 54 |
else: |
| 55 |
return name |
| 56 |
|
| 57 |
@cython.cfunc |
| 58 |
@cython.inline |
| 59 |
def _get_context_by_type(self, type_: str) -> list[FilterContext]: |
| 60 |
return self._context_by_type.get(type_, []) |
| 61 |
|
| 62 |
@cython.ccall |
| 63 |
def configure(self, auto_buffer: cython.bint = True, force: cython.bint = False): |
| 64 |
if self.configured and not force: |
| 65 |
return |
| 66 |
|
| 67 |
err_check(lib.avfilter_graph_config(self.ptr, cython.NULL)) |
| 68 |
self.configured = True |
| 69 |
|
| 70 |
# We get auto-inserted stuff here. |
| 71 |
self._auto_register() |
| 72 |
|
| 73 |
def link_nodes(self, *nodes): |
| 74 |
""" |
| 75 |
Links nodes together for simple filter graphs. |
| 76 |
""" |
| 77 |
for c, n in zip(nodes, nodes[1:]): |
| 78 |
c.link_to(n) |
| 79 |
return self |
| 80 |
|
| 81 |
def add(self, filter, args=None, **kwargs): |
| 82 |
cy_filter: Filter |
| 83 |
if isinstance(filter, str): |
| 84 |
cy_filter = Filter(filter) |
| 85 |
elif isinstance(filter, Filter): |
| 86 |
cy_filter = filter |
| 87 |
else: |
| 88 |
raise TypeError("filter must be a string or Filter") |
| 89 |
|
| 90 |
name: str = self._get_unique_name(kwargs.pop("name", None) or cy_filter.name) |
| 91 |
ptr: cython.pointer[lib.AVFilterContext] = lib.avfilter_graph_alloc_filter( |
| 92 |
self.ptr, cy_filter.ptr, name |
| 93 |
) |
| 94 |
if not ptr: |
| 95 |
raise RuntimeError("Could not allocate AVFilterContext") |
| 96 |
|
| 97 |
# Manually construct this context (so we can return it). |
| 98 |
ctx: FilterContext = wrap_filter_context(self, cy_filter, ptr) |
| 99 |
ctx.init(args, **kwargs) |
| 100 |
self._register_context(ctx) |
| 101 |
|
| 102 |
# There might have been automatic contexts added (e.g. resamplers, |
| 103 |
# fifos, and scalers). It is more likely to see them after the graph |
| 104 |
# is configured, but we want to be safe. |
| 105 |
self._auto_register() |
| 106 |
|
| 107 |
return ctx |
| 108 |
|
| 109 |
@cython.cfunc |
| 110 |
def _register_context(self, ctx: FilterContext): |
| 111 |
self._context_by_ptr[cython.cast(cython.long, ctx.ptr)] = ctx |
| 112 |
self._context_by_type.setdefault(ctx.filter.ptr.name, []).append(ctx) |
| 113 |
|
| 114 |
@cython.cfunc |
| 115 |
def _auto_register(self): |
| 116 |
i: cython.int |
| 117 |
c_ctx: cython.pointer[lib.AVFilterContext] |
| 118 |
filter_: Filter |
| 119 |
py_ctx: FilterContext |
| 120 |
# We assume that filters are never removed from the graph. At this |
| 121 |
# point we don't expose that in the API, so we should be okay... |
| 122 |
for i in range(self._nb_filters_seen, self.ptr.nb_filters): |
| 123 |
c_ctx = self.ptr.filters[i] |
| 124 |
if cython.cast(cython.long, c_ctx) in self._context_by_ptr: |
| 125 |
continue |
| 126 |
filter_ = wrap_filter(c_ctx.filter) |
| 127 |
py_ctx = wrap_filter_context(self, filter_, c_ctx) |
| 128 |
self._register_context(py_ctx) |
| 129 |
self._nb_filters_seen = self.ptr.nb_filters |
| 130 |
|
| 131 |
def add_buffer( |
| 132 |
self, |
| 133 |
template=None, |
| 134 |
width=None, |
| 135 |
height=None, |
| 136 |
format=None, |
| 137 |
name=None, |
| 138 |
time_base=None, |
| 139 |
): |
| 140 |
if template is not None: |
| 141 |
if width is None: |
| 142 |
width = template.width |
| 143 |
if height is None: |
| 144 |
height = template.height |
| 145 |
if format is None: |
| 146 |
format = template.format |
| 147 |
if time_base is None: |
| 148 |
time_base = template.time_base |
| 149 |
|
| 150 |
if width is None: |
| 151 |
raise ValueError("missing width") |
| 152 |
if height is None: |
| 153 |
raise ValueError("missing height") |
| 154 |
if format is None: |
| 155 |
raise ValueError("missing format") |
| 156 |
if time_base is None: |
| 157 |
warnings.warn( |
| 158 |
"missing time_base. Guessing 1/1000 time base. " |
| 159 |
"This is deprecated and may be removed in future releases.", |
| 160 |
DeprecationWarning, |
| 161 |
) |
| 162 |
time_base = Fraction(1, 1000) |
| 163 |
|
| 164 |
return self.add( |
| 165 |
"buffer", |
| 166 |
name=name, |
| 167 |
video_size=f"{width}x{height}", |
| 168 |
pix_fmt=str(int(VideoFormat(format))), |
| 169 |
time_base=str(time_base), |
| 170 |
pixel_aspect="1/1", |
| 171 |
) |
| 172 |
|
| 173 |
def add_abuffer( |
| 174 |
self, |
| 175 |
template=None, |
| 176 |
sample_rate=None, |
| 177 |
format=None, |
| 178 |
layout=None, |
| 179 |
channels=None, |
| 180 |
name=None, |
| 181 |
time_base=None, |
| 182 |
): |
| 183 |
""" |
| 184 |
Convenience method for adding `abuffer <https://ffmpeg.org/ffmpeg-filters.html#abuffer>`_. |
| 185 |
""" |
| 186 |
|
| 187 |
if template is not None: |
| 188 |
if sample_rate is None: |
| 189 |
sample_rate = template.sample_rate |
| 190 |
if format is None: |
| 191 |
format = template.format |
| 192 |
if layout is None: |
| 193 |
layout = template.layout.name |
| 194 |
if channels is None: |
| 195 |
channels = template.channels |
| 196 |
if time_base is None: |
| 197 |
time_base = template.time_base |
| 198 |
|
| 199 |
if sample_rate is None: |
| 200 |
raise ValueError("missing sample_rate") |
| 201 |
if format is None: |
| 202 |
raise ValueError("missing format") |
| 203 |
if layout is None and channels is None: |
| 204 |
raise ValueError("missing layout or channels") |
| 205 |
if time_base is None: |
| 206 |
time_base = Fraction(1, sample_rate) |
| 207 |
|
| 208 |
kwargs = { |
| 209 |
"sample_rate": f"{sample_rate}", |
| 210 |
"sample_fmt": AudioFormat(format).name, |
| 211 |
"time_base": f"{time_base}", |
| 212 |
} |
| 213 |
if layout: |
| 214 |
kwargs["channel_layout"] = AudioLayout(layout).name |
| 215 |
if channels: |
| 216 |
kwargs["channels"] = f"{channels}" |
| 217 |
|
| 218 |
return self.add("abuffer", name=name, **kwargs) |
| 219 |
|
| 220 |
def set_audio_frame_size(self, frame_size): |
| 221 |
""" |
| 222 |
Set the audio frame size for the graphs `abuffersink`. |
| 223 |
See `av_buffersink_set_frame_size <https://ffmpeg.org/doxygen/trunk/group__lavfi__buffersink.html#ga359d7d1e42c27ca14c07559d4e9adba7>`_. |
| 224 |
""" |
| 225 |
if not self.configured: |
| 226 |
raise ValueError("graph not configured") |
| 227 |
sinks = self._get_context_by_type("abuffersink") |
| 228 |
if not sinks: |
| 229 |
raise ValueError("missing abuffersink filter") |
| 230 |
for sink in sinks: |
| 231 |
lib.av_buffersink_set_frame_size( |
| 232 |
cython.cast(FilterContext, sink).ptr, frame_size |
| 233 |
) |
| 234 |
|
| 235 |
def push(self, frame): |
| 236 |
if frame is None: |
| 237 |
contexts = self._get_context_by_type("buffer") + self._get_context_by_type( |
| 238 |
"abuffer" |
| 239 |
) |
| 240 |
elif isinstance(frame, VideoFrame): |
| 241 |
contexts = self._get_context_by_type("buffer") |
| 242 |
elif isinstance(frame, AudioFrame): |
| 243 |
contexts = self._get_context_by_type("abuffer") |
| 244 |
else: |
| 245 |
raise ValueError( |
| 246 |
f"can only AudioFrame, VideoFrame or None; got {type(frame)}" |
| 247 |
) |
| 248 |
|
| 249 |
for ctx in contexts: |
| 250 |
ctx.push(frame) |
| 251 |
|
| 252 |
def vpush(self, frame: VideoFrame | None): |
| 253 |
"""Like `push`, but only for VideoFrames.""" |
| 254 |
for ctx in self._get_context_by_type("buffer"): |
| 255 |
ctx.push(frame) |
| 256 |
|
| 257 |
# TODO: Test complex filter graphs, add `at: int = 0` arg to pull() and vpull(). |
| 258 |
def pull(self): |
| 259 |
vsinks = self._get_context_by_type("buffersink") |
| 260 |
asinks = self._get_context_by_type("abuffersink") |
| 261 |
|
| 262 |
nsinks = len(vsinks) + len(asinks) |
| 263 |
if nsinks != 1: |
| 264 |
raise ValueError(f"can only auto-pull with single sink; found {nsinks}") |
| 265 |
|
| 266 |
return (vsinks or asinks)[0].pull() |
| 267 |
|
| 268 |
def vpull(self): |
| 269 |
"""Like `pull`, but only for VideoFrames.""" |
| 270 |
vsinks = self._get_context_by_type("buffersink") |
| 271 |
nsinks = len(vsinks) |
| 272 |
if nsinks != 1: |
| 273 |
raise ValueError(f"can only auto-pull with single sink; found {nsinks}") |
| 274 |
|
| 275 |
return vsinks[0].pull() |