Debian Codegraph @

av/container/output.py

raw
1 import os
2
3 import cython
4 from cython.cimports import libav as lib
5 from cython.cimports.av.codec.codec import Codec
6 from cython.cimports.av.codec.context import CodecContext, wrap_codec_context
7 from cython.cimports.av.container.streams import StreamContainer
8 from cython.cimports.av.dictionary import Dictionary
9 from cython.cimports.av.error import err_check
10 from cython.cimports.av.packet import Packet
11 from cython.cimports.av.stream import Stream, wrap_stream
12 from cython.cimports.av.utils import dict_to_avdict, to_avrational
13
14
15 @cython.cfunc
16 def close_output(self: OutputContainer):
17 self.streams = StreamContainer()
18 if self._myflag & 12 == 4: # enum.started and not enum.done
19 # If the underlying Python IO file was already closed (e.g. during GC
20 # finalization where cycle ordering is undefined), skip the trailer.
21 if self.file is not None and getattr(self.file.file, "closed", False):
22 self._myflag |= 8 # enum.done = True
23 return
24 # We must only ever call av_write_trailer *once*, otherwise we get a
25 # segmentation fault. Therefore no matter whether it succeeds or not
26 # we must absolutely set enum.done.
27 try:
28 self.err_check(lib.av_write_trailer(self.ptr))
29 finally:
30 if self.file is None and not (self.ptr.oformat.flags & lib.AVFMT_NOFILE):
31 lib.avio_closep(cython.address(self.ptr.pb))
32 self._myflag |= 8 # enum.done = True
33
34
35 @cython.final
36 @cython.cclass
37 class OutputContainer(Container):
38 def __cinit__(self, *args, **kwargs):
39 self.streams = StreamContainer()
40 self.metadata = {}
41 with cython.nogil:
42 self.packet_ptr = lib.av_packet_alloc()
43
44 def __del__(self):
45 close_output(self)
46
47 def __dealloc__(self):
48 with cython.nogil:
49 lib.av_packet_free(cython.address(self.packet_ptr))
50
51 def add_stream(self, codec_name, rate=None, options: dict | None = None, **kwargs):
52 """add_stream(codec_name, rate=None)
53
54 Creates a new stream from a codec name and returns it.
55 Supports video, audio, and subtitle streams.
56
57 :param codec_name: The name of a codec.
58 :type codec_name: str
59 :param dict options: Stream options.
60 :param \\**kwargs: Set attributes for the stream.
61 :rtype: The new :class:`~av.stream.Stream`.
62
63 """
64
65 codec_obj: Codec = Codec(codec_name, "w")
66 codec: cython.pointer[cython.const[lib.AVCodec]] = codec_obj.ptr
67
68 # Assert that this format supports the requested codec.
69 if not lib.avformat_query_codec(
70 self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL
71 ):
72 raise ValueError(
73 f"{self.format.name!r} format does not support {codec_obj.name!r} codec"
74 )
75
76 # Create new stream in the AVFormatContext, set AVCodecContext values.
77 stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
78 ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3(codec)
79
80 # Now lets set some more sane video defaults
81 if codec.type == lib.AVMEDIA_TYPE_VIDEO:
82 ctx.pix_fmt = lib.AV_PIX_FMT_YUV420P
83 ctx.width = kwargs.pop("width", 640)
84 ctx.height = kwargs.pop("height", 480)
85 ctx.bit_rate = kwargs.pop("bit_rate", 0)
86 ctx.bit_rate_tolerance = kwargs.pop("bit_rate_tolerance", 128000)
87 try:
88 to_avrational(kwargs.pop("time_base"), cython.address(ctx.time_base))
89 except KeyError:
90 pass
91 to_avrational(rate or 24, cython.address(ctx.framerate))
92
93 stream.avg_frame_rate = ctx.framerate
94 stream.time_base = ctx.time_base
95
96 # Some sane audio defaults
97 elif codec.type == lib.AVMEDIA_TYPE_AUDIO:
98 out: cython.pointer[cython.const[cython.void]] = cython.NULL
99 lib.avcodec_get_supported_config(
100 cython.NULL,
101 codec,
102 lib.AV_CODEC_CONFIG_SAMPLE_FORMAT,
103 0,
104 cython.address(out),
105 cython.NULL,
106 )
107 if out:
108 ctx.sample_fmt = cython.cast(cython.pointer[lib.AVSampleFormat], out)[0]
109 ctx.bit_rate = kwargs.pop("bit_rate", 0)
110 ctx.bit_rate_tolerance = kwargs.pop("bit_rate_tolerance", 32000)
111 try:
112 to_avrational(kwargs.pop("time_base"), cython.address(ctx.time_base))
113 except KeyError:
114 pass
115
116 if rate is None:
117 ctx.sample_rate = 48000
118 elif type(rate) is int:
119 ctx.sample_rate = rate
120 else:
121 raise TypeError("audio stream `rate` must be: int | None")
122 stream.time_base = ctx.time_base
123 lib.av_channel_layout_default(cython.address(ctx.ch_layout), 2)
124
125 # Some formats want stream headers to be separate
126 if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER:
127 ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER
128
129 # Initialise stream codec parameters to populate the codec type.
130 #
131 # Subsequent changes to the codec context will be applied just before
132 # encoding starts in `start_encoding()`.
133 err_check(lib.avcodec_parameters_from_context(stream.codecpar, ctx))
134
135 # Construct the user-land stream
136 py_codec_context: CodecContext = wrap_codec_context(ctx, codec, None)
137 py_stream: Stream = wrap_stream(self, stream, py_codec_context)
138 self.streams.add_stream(py_stream)
139
140 if options:
141 py_stream.options.update(options)
142
143 for k, v in kwargs.items():
144 setattr(py_stream, k, v)
145
146 return py_stream
147
148 def add_mux_stream(self, codec_name: str, rate=None, **kwargs) -> Stream:
149 """add_mux_stream(codec_name, rate=None)
150
151 Creates a new stream for muxing pre-encoded data without creating a
152 :class:`.CodecContext`. Use this when you want to mux packets that were
153 already encoded externally and no encoding/decoding is needed.
154
155 :param codec_name: The name of a codec.
156 :type codec_name: str
157 :param \\**kwargs: Set attributes for the stream (e.g. ``width``, ``height``,
158 ``time_base``).
159 :rtype: The new :class:`~av.stream.Stream`.
160
161 """
162 # Find the codec to get its id and type (try encoder first, then decoder).
163 codec_name_bytes: bytes = codec_name.encode()
164 codec: cython.pointer[cython.const[lib.AVCodec]] = (
165 lib.avcodec_find_encoder_by_name(codec_name_bytes)
166 )
167 codec_descriptor: cython.pointer[cython.const[lib.AVCodecDescriptor]] = (
168 cython.NULL
169 )
170 if codec == cython.NULL:
171 codec = lib.avcodec_find_decoder_by_name(codec_name_bytes)
172 if codec == cython.NULL:
173 codec_descriptor = lib.avcodec_descriptor_get_by_name(codec_name_bytes)
174 if codec_descriptor == cython.NULL:
175 raise ValueError(f"Unknown codec: {codec_name!r}")
176
177 codec_id: lib.AVCodecID
178 codec_type: lib.AVMediaType
179 if codec != cython.NULL:
180 codec_id = codec.id
181 codec_type = codec.type
182 else:
183 codec_id = codec_descriptor.id
184 codec_type = codec_descriptor.type
185
186 # Assert that this format supports the requested codec.
187 if not lib.avformat_query_codec(
188 self.ptr.oformat, codec_id, lib.FF_COMPLIANCE_NORMAL
189 ):
190 raise ValueError(
191 f"{self.format.name!r} format does not support {codec_name!r} codec"
192 )
193
194 # Create stream with no codec context.
195 stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(
196 self.ptr, cython.NULL
197 )
198 if stream == cython.NULL:
199 raise MemoryError("Could not allocate stream")
200
201 stream.codecpar.codec_id = codec_id
202 stream.codecpar.codec_type = codec_type
203
204 if codec_type == lib.AVMEDIA_TYPE_VIDEO:
205 stream.codecpar.width = kwargs.pop("width", 0)
206 stream.codecpar.height = kwargs.pop("height", 0)
207 if rate is not None:
208 to_avrational(rate, cython.address(stream.avg_frame_rate))
209 elif codec_type == lib.AVMEDIA_TYPE_AUDIO:
210 if rate is not None:
211 if type(rate) is int:
212 stream.codecpar.sample_rate = rate
213 else:
214 raise TypeError("audio stream `rate` must be: int | None")
215
216 # Construct the user-land stream (no codec context).
217 py_stream: Stream = wrap_stream(self, stream, None)
218 self.streams.add_stream(py_stream)
219
220 for k, v in kwargs.items():
221 setattr(py_stream, k, v)
222
223 return py_stream
224
225 def add_stream_from_template(
226 self, template: Stream, opaque: bool | None = None, **kwargs
227 ):
228 """
229 Creates a new stream from a template. Supports video, audio, subtitle, data and attachment streams.
230
231 :param template: Copy codec from another :class:`~av.stream.Stream` instance.
232 :param opaque: If True, copy opaque data from the template's codec context.
233 :param \\**kwargs: Set attributes for the stream.
234 :rtype: The new :class:`~av.stream.Stream`.
235 """
236 if opaque is None:
237 opaque = template.type != "video"
238
239 if template.codec_context is None:
240 return self._add_stream_without_codec_from_template(template, **kwargs)
241
242 codec_obj: Codec
243 if opaque: # Copy ctx from template.
244 codec_obj = template.codec_context.codec
245 else: # Construct new codec object.
246 codec_obj = Codec(template.codec_context.codec.name, "w")
247
248 codec: cython.pointer[cython.const[lib.AVCodec]] = codec_obj.ptr
249
250 # Assert that this format supports the requested codec.
251 if not lib.avformat_query_codec(
252 self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL
253 ):
254 raise ValueError(
255 f"{self.format.name!r} format does not support {codec_obj.name!r} codec"
256 )
257
258 # Create new stream in the AVFormatContext, set AVCodecContext values.
259 stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
260 ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3(codec)
261
262 err_check(lib.avcodec_parameters_to_context(ctx, template.ptr.codecpar))
263 # Reset the codec tag assuming we are remuxing.
264 ctx.codec_tag = 0
265
266 # Copy the template's stream time_base
267 stream.time_base = template.ptr.time_base
268 ctx.time_base = template.ptr.time_base
269
270 # Some formats want stream headers to be separate
271 if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER:
272 ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER
273
274 # Copy flags If we're creating a new codec object. This fixes some muxing issues.
275 # Overwriting `ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER` is intentional.
276 if not opaque:
277 ctx.flags = template.codec_context.flags
278
279 # Initialize stream codec parameters to populate the codec type. Subsequent changes to
280 # the codec context will be applied just before encoding starts in `start_encoding()`.
281 err_check(lib.avcodec_parameters_from_context(stream.codecpar, ctx))
282
283 # Construct the user-land stream
284 py_codec_context: CodecContext = wrap_codec_context(ctx, codec, None)
285 py_codec_context._ctxflags |= 1 # _template_initialized = True
286 py_stream: Stream = wrap_stream(self, stream, py_codec_context)
287 self.streams.add_stream(py_stream)
288
289 for k, v in kwargs.items():
290 setattr(py_stream, k, v)
291
292 return py_stream
293
294 def _add_stream_without_codec_from_template(
295 self, template: Stream, **kwargs
296 ) -> Stream:
297 codec_type: cython.int = template.ptr.codecpar.codec_type
298 if codec_type not in {lib.AVMEDIA_TYPE_ATTACHMENT, lib.AVMEDIA_TYPE_DATA}:
299 raise ValueError(
300 f"template stream of type {template.type} has no codec context"
301 )
302
303 stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(
304 self.ptr, cython.NULL
305 )
306 if stream == cython.NULL:
307 raise MemoryError("Could not allocate stream")
308
309 err_check(lib.avcodec_parameters_copy(stream.codecpar, template.ptr.codecpar))
310
311 # Mirror basic properties that are not derived from a codec context.
312 stream.time_base = template.ptr.time_base
313 stream.start_time = template.ptr.start_time
314 stream.duration = template.ptr.duration
315 stream.disposition = template.ptr.disposition
316
317 py_stream: Stream = wrap_stream(self, stream, None)
318 self.streams.add_stream(py_stream)
319
320 py_stream.metadata = dict(template.metadata)
321
322 for k, v in kwargs.items():
323 setattr(py_stream, k, v)
324
325 return py_stream
326
327 def add_attachment(self, name: str, mimetype: str, data: bytes):
328 """
329 Create an attachment stream and embed its payload into the container header.
330
331 - Only supported by formats that support attachments (e.g. Matroska).
332 - No per-packet muxing is required; attachments are written at header time.
333 """
334 # Create stream with no codec (attachments are codec-less).
335 stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(
336 self.ptr, cython.NULL
337 )
338 if stream == cython.NULL:
339 raise MemoryError("Could not allocate stream")
340
341 stream.codecpar.codec_type = lib.AVMEDIA_TYPE_ATTACHMENT
342 stream.codecpar.codec_id = lib.AV_CODEC_ID_NONE
343
344 # Allocate and copy payload into codecpar.extradata.
345 payload_size: cython.size_t = len(data)
346 if payload_size:
347 buf = cython.cast(cython.p_uchar, lib.av_malloc(payload_size + 1))
348 if buf == cython.NULL:
349 raise MemoryError("Could not allocate attachment data")
350 # Copy bytes.
351 for i in range(payload_size):
352 buf[i] = data[i]
353 buf[payload_size] = 0
354 stream.codecpar.extradata = cython.cast(cython.p_uchar, buf)
355 stream.codecpar.extradata_size = payload_size
356
357 # Wrap as user-land stream.
358 meta_ptr = cython.address(stream.metadata)
359 err_check(lib.av_dict_set(meta_ptr, b"filename", name.encode(), 0))
360 mime_bytes = mimetype.encode()
361 err_check(lib.av_dict_set(meta_ptr, b"mimetype", mime_bytes, 0))
362
363 py_stream: Stream = wrap_stream(self, stream, None)
364 self.streams.add_stream(py_stream)
365 return py_stream
366
367 def add_data_stream(self, codec_name=None, options: dict | None = None):
368 """add_data_stream(codec_name=None)
369
370 Creates a new data stream and returns it.
371
372 :param codec_name: Optional name of the data codec (e.g. 'klv')
373 :type codec_name: str | None
374 :param dict options: Stream options.
375 :rtype: The new :class:`~av.data.stream.DataStream`.
376 """
377 codec: cython.pointer[cython.const[lib.AVCodec]] = cython.NULL
378 codec_descriptor: cython.pointer[cython.const[lib.AVCodecDescriptor]] = (
379 cython.NULL
380 )
381
382 if codec_name is not None:
383 codec_name_bytes: bytes = codec_name.encode()
384 codec = lib.avcodec_find_encoder_by_name(codec_name_bytes)
385 if codec == cython.NULL:
386 codec = lib.avcodec_find_decoder_by_name(codec_name_bytes)
387 if codec == cython.NULL:
388 codec_descriptor = lib.avcodec_descriptor_get_by_name(codec_name_bytes)
389 if codec_descriptor == cython.NULL:
390 raise ValueError(f"Unknown data codec: {codec_name}")
391
392 # Verify format supports this codec
393 codec_id = codec.id if codec != cython.NULL else codec_descriptor.id
394 if not lib.avformat_query_codec(
395 self.ptr.oformat, codec_id, lib.FF_COMPLIANCE_NORMAL
396 ):
397 raise ValueError(
398 f"{self.format.name!r} format does not support {codec_name!r} codec"
399 )
400
401 # Create new stream in the AVFormatContext
402 stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
403 if stream == cython.NULL:
404 raise MemoryError("Could not allocate stream")
405
406 # Set up codec context and parameters
407 ctx: cython.pointer[lib.AVCodecContext] = cython.NULL
408 if codec != cython.NULL:
409 ctx = lib.avcodec_alloc_context3(codec)
410 if ctx == cython.NULL:
411 raise MemoryError("Could not allocate codec context")
412
413 # Some formats want stream headers to be separate
414 if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER:
415 ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER
416
417 # Initialize stream codec parameters
418 err_check(lib.avcodec_parameters_from_context(stream.codecpar, ctx))
419 else:
420 # No codec available - set basic parameters for data stream
421 stream.codecpar.codec_type = lib.AVMEDIA_TYPE_DATA
422 if codec_descriptor != cython.NULL:
423 stream.codecpar.codec_id = codec_descriptor.id
424
425 # Construct the user-land stream
426 py_codec_context: CodecContext | None = None
427 if ctx != cython.NULL:
428 py_codec_context = wrap_codec_context(ctx, codec, None)
429
430 py_stream: Stream = wrap_stream(self, stream, py_codec_context)
431 self.streams.add_stream(py_stream)
432
433 if options:
434 py_stream.options.update(options)
435
436 return py_stream
437
438 @cython.ccall
439 def start_encoding(self):
440 """Write the file header! Called automatically."""
441 if self._myflag & 4: # started
442 return
443
444 # TODO: This does NOT handle options coming from 3 sources.
445 # This is only a rough approximation of what would be cool to do.
446 used_options: set = set()
447 stream: Stream
448
449 # Finalize and open all streams.
450 for stream in self.streams:
451 ctx = stream.codec_context
452 if ctx is not None and not ctx.is_open:
453 for k, v in self.options.items():
454 ctx.options.setdefault(k, v)
455
456 if not (ctx._ctxflags & 1): # template_initialized
457 ctx.open()
458
459 # Track option consumption.
460 for k in self.options:
461 if k not in ctx.options:
462 used_options.add(k)
463
464 stream._finalize_for_output()
465
466 # Open the output file, if needed.
467 name_obj: bytes = os.fsencode(self.name if self.file is None else "")
468 name: cython.p_char = name_obj
469 if self.ptr.pb == cython.NULL and not self.ptr.oformat.flags & lib.AVFMT_NOFILE:
470 err_check(
471 lib.avio_open(cython.address(self.ptr.pb), name, lib.AVIO_FLAG_WRITE)
472 )
473
474 # Copy the metadata dict.
475 dict_to_avdict(
476 cython.address(self.ptr.metadata),
477 self.metadata,
478 encoding=self.metadata_encoding,
479 errors=self.metadata_errors,
480 )
481
482 all_options: Dictionary = Dictionary(self.options, self.container_options)
483 options: Dictionary = all_options.copy()
484 self.err_check(lib.avformat_write_header(self.ptr, cython.address(options.ptr)))
485
486 # Track option usage...
487 for k in all_options:
488 if k not in options:
489 used_options.add(k)
490
491 # ... and warn if any weren't used.
492 unused_options = {
493 k: v for k, v in self.options.items() if k not in used_options
494 }
495 if unused_options:
496 import logging
497
498 log = logging.getLogger(__name__)
499 log.warning("Some options were not used: %s" % unused_options)
500
501 self._myflag |= 4
502
503 @property
504 def supported_codecs(self):
505 """
506 Returns a set of all codecs this format supports.
507 """
508 result: set = set()
509 codec: cython.pointer[cython.const[lib.AVCodec]] = cython.NULL
510 opaque: cython.p_void = cython.NULL
511
512 while True:
513 codec = lib.av_codec_iterate(cython.address(opaque))
514 if codec == cython.NULL:
515 break
516
517 if (
518 lib.avformat_query_codec(
519 self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL
520 )
521 == 1
522 ):
523 result.add(codec.name)
524
525 return result
526
527 @property
528 def default_video_codec(self):
529 """
530 Returns the default video codec this container recommends.
531 """
532 return lib.avcodec_get_name(self.format.optr.video_codec)
533
534 @property
535 def default_audio_codec(self):
536 """
537 Returns the default audio codec this container recommends.
538 """
539 return lib.avcodec_get_name(self.format.optr.audio_codec)
540
541 @property
542 def default_subtitle_codec(self):
543 """
544 Returns the default subtitle codec this container recommends.
545 """
546 return lib.avcodec_get_name(self.format.optr.subtitle_codec)
547
548 def close(self):
549 close_output(self)
550
551 def mux(self, packets):
552 # We accept either a Packet, or a sequence of packets. This should smooth out
553 # the transition to the new encode API which returns a sequence of packets.
554 if isinstance(packets, Packet):
555 self.mux_one(packets)
556 else:
557 for packet in packets:
558 self.mux_one(packet)
559
560 def mux_one(self, packet: Packet):
561 self.start_encoding()
562
563 # Assert the packet is in stream time.
564 if (
565 packet.ptr.stream_index < 0
566 or cython.cast(cython.uint, packet.ptr.stream_index) >= self.ptr.nb_streams
567 ):
568 raise ValueError("Bad Packet stream_index.")
569
570 stream: cython.pointer[lib.AVStream] = self.ptr.streams[packet.ptr.stream_index]
571 packet._rebase_time(stream.time_base)
572
573 # Make another reference to the packet, as `av_interleaved_write_frame()`
574 # takes ownership of the reference.
575 self.err_check(lib.av_packet_ref(self.packet_ptr, packet.ptr))
576
577 with cython.nogil:
578 ret: cython.int = lib.av_interleaved_write_frame(self.ptr, self.packet_ptr)
579 self.err_check(ret)