Debian Codegraph @

av/container/core.py

raw
1 import os
2 import time
3 from enum import Flag, IntEnum
4 from pathlib import Path
5
6 import cython
7 import cython.cimports.libav as lib
8 from cython.cimports.av.container.core import timeout_info
9 from cython.cimports.av.container.input import InputContainer
10 from cython.cimports.av.container.output import OutputContainer
11 from cython.cimports.av.container.pyio import pyio_close_custom_gil, pyio_close_gil
12 from cython.cimports.av.error import err_check, stash_exception
13 from cython.cimports.av.format import build_container_format
14 from cython.cimports.av.utils import (
15 avdict_to_dict,
16 avrational_to_fraction,
17 dict_to_avdict,
18 to_avrational,
19 )
20 from cython.cimports.libc.stdint import int64_t
21 from cython.operator import dereference
22
23 from av.logging import Capture as LogCapture
24
25 _cinit_sentinel = cython.declare(object, object())
26
27 AVChapterPtrPtr = cython.typedef(cython.pointer[cython.pointer[lib.AVChapter]])
28
29
30 @cython.cfunc
31 @cython.nogil
32 @cython.exceptval(check=False)
33 def interrupt_cb(p: cython.p_void) -> cython.int:
34 info: timeout_info = dereference(cython.cast(cython.pointer[timeout_info], p))
35 if info.timeout < 0: # timeout < 0 means no timeout
36 return 0
37
38 current_time: cython.double
39 with cython.gil:
40 current_time = time.monotonic()
41 if current_time < info.start_time:
42 # Raise this when we get back to Python.
43 stash_exception(
44 (
45 RuntimeError,
46 RuntimeError("Clock has been changed to before timeout start"),
47 None,
48 )
49 )
50 return 1
51
52 if current_time > info.start_time + info.timeout:
53 return 1
54 return 0
55
56
57 @cython.cfunc
58 @cython.nogil
59 @cython.exceptval(check=False)
60 def pyav_io_open(
61 s: cython.pointer[lib.AVFormatContext],
62 pb: cython.pointer[cython.pointer[lib.AVIOContext]],
63 url: cython.p_const_char,
64 flags: cython.int,
65 options: cython.pointer[cython.pointer[lib.AVDictionary]],
66 ) -> cython.int:
67 with cython.gil:
68 return pyav_io_open_gil(s, pb, url, flags, options)
69
70
71 @cython.cfunc
72 @cython.exceptval(check=False)
73 def pyav_io_open_gil(
74 s: cython.pointer[lib.AVFormatContext],
75 pb: cython.pointer[cython.pointer[lib.AVIOContext]],
76 url: cython.p_const_char,
77 flags: cython.int,
78 options: cython.pointer[cython.pointer[lib.AVDictionary]],
79 ) -> cython.int:
80 container: Container
81 file: object
82 pyio_file: PyIOFile
83 try:
84 container = cython.cast(Container, dereference(s).opaque)
85
86 if options is not cython.NULL:
87 options_dict = avdict_to_dict(
88 dereference(
89 cython.cast(
90 cython.pointer[cython.pointer[lib.AVDictionary]], options
91 )
92 ),
93 encoding=container.metadata_encoding,
94 errors=container.metadata_errors,
95 )
96 else:
97 options_dict = {}
98
99 file = container.io_open(
100 cython.cast(str, url) if url is not cython.NULL else "", flags, options_dict
101 )
102
103 pyio_file = PyIOFile(
104 file, container.buffer_size, (flags & lib.AVIO_FLAG_WRITE) != 0
105 )
106
107 # Add it to the container to avoid it being deallocated
108 container.open_files[cython.cast(int64_t, pyio_file.iocontext.opaque)] = (
109 pyio_file
110 )
111 pb[0] = pyio_file.iocontext
112 return 0
113 except Exception:
114 return stash_exception()
115
116
117 @cython.cfunc
118 @cython.nogil
119 @cython.exceptval(check=False)
120 def pyav_io_close(
121 s: cython.pointer[lib.AVFormatContext], pb: cython.pointer[lib.AVIOContext]
122 ) -> cython.int:
123 with cython.gil:
124 return pyav_io_close_gil(s, pb)
125
126
127 @cython.cfunc
128 @cython.exceptval(check=False)
129 def pyav_io_close_gil(
130 s: cython.pointer[lib.AVFormatContext], pb: cython.pointer[lib.AVIOContext]
131 ) -> cython.int:
132 container: Container
133 result: cython.int = 0
134 try:
135 container = cython.cast(Container, dereference(s).opaque)
136 if (
137 container.open_files is not None
138 and cython.cast(int64_t, pb.opaque) in container.open_files
139 ):
140 result = pyio_close_custom_gil(pb)
141
142 # Remove it from the container so that it can be deallocated
143 del container.open_files[cython.cast(int64_t, pb.opaque)]
144 else:
145 result = pyio_close_gil(pb)
146
147 except Exception:
148 stash_exception()
149 result = lib.AVERROR_UNKNOWN # Or another appropriate error code
150
151 return result
152
153
154 @cython.cfunc
155 @cython.nogil
156 @cython.exceptval(check=False)
157 def _free_chapters(ctx: cython.pointer[lib.AVFormatContext]) -> cython.void:
158 i: cython.Py_ssize_t
159 if ctx.chapters != cython.NULL:
160 for i in range(ctx.nb_chapters):
161 if ctx.chapters[i] != cython.NULL:
162 if ctx.chapters[i].metadata != cython.NULL:
163 lib.av_dict_free(cython.address(ctx.chapters[i].metadata))
164 lib.av_freep(
165 cython.cast(cython.pp_void, cython.address(ctx.chapters[i]))
166 )
167 lib.av_freep(cython.cast(cython.pp_void, cython.address(ctx.chapters)))
168 ctx.nb_chapters = 0
169
170
171 # fmt: off
172 class Flags(Flag):
173 gen_pts: "Generate missing pts even if it requires parsing future frames." = lib.AVFMT_FLAG_GENPTS
174 ign_idx: "Ignore index." = lib.AVFMT_FLAG_IGNIDX
175 non_block: "Do not block when reading packets from input." = lib.AVFMT_FLAG_NONBLOCK
176 ign_dts: "Ignore DTS on frames that contain both DTS & PTS." = lib.AVFMT_FLAG_IGNDTS
177 no_fillin: "Do not infer any values from other values, just return what is stored in the container." = lib.AVFMT_FLAG_NOFILLIN
178 no_parse: "Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fill in code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled." = lib.AVFMT_FLAG_NOPARSE
179 no_buffer: "Do not buffer frames when possible." = lib.AVFMT_FLAG_NOBUFFER
180 custom_io: "The caller has supplied a custom AVIOContext, don't avio_close() it." = lib.AVFMT_FLAG_CUSTOM_IO
181 discard_corrupt: "Discard frames marked corrupted." = lib.AVFMT_FLAG_DISCARD_CORRUPT
182 flush_packets: "Flush the AVIOContext every packet." = lib.AVFMT_FLAG_FLUSH_PACKETS
183 bitexact: "When muxing, try to avoid writing any random/volatile data to the output. This includes any random IDs, real-time timestamps/dates, muxer version, etc. This flag is mainly intended for testing." = lib.AVFMT_FLAG_BITEXACT
184 sort_dts: "Try to interleave outputted packets by dts (using this flag can slow demuxing down)." = lib.AVFMT_FLAG_SORT_DTS
185 fast_seek: "Enable fast, but inaccurate seeks for some formats." = lib.AVFMT_FLAG_FAST_SEEK
186 auto_bsf: "Add bitstream filters as requested by the muxer." = lib.AVFMT_FLAG_AUTO_BSF
187
188 class AudioCodec(IntEnum):
189 """Enumeration for audio codec IDs."""
190 none = lib.AV_CODEC_ID_NONE # No codec.
191 pcm_alaw = lib.AV_CODEC_ID_PCM_ALAW # PCM A-law.
192 pcm_bluray = lib.AV_CODEC_ID_PCM_BLURAY # PCM Blu-ray.
193 pcm_dvd = lib.AV_CODEC_ID_PCM_DVD # PCM DVD.
194 pcm_f16le = lib.AV_CODEC_ID_PCM_F16LE # PCM F16 little-endian.
195 pcm_f24le = lib.AV_CODEC_ID_PCM_F24LE # PCM F24 little-endian.
196 pcm_f32be = lib.AV_CODEC_ID_PCM_F32BE # PCM F32 big-endian.
197 pcm_f32le = lib.AV_CODEC_ID_PCM_F32LE # PCM F32 little-endian.
198 pcm_f64be = lib.AV_CODEC_ID_PCM_F64BE # PCM F64 big-endian.
199 pcm_f64le = lib.AV_CODEC_ID_PCM_F64LE # PCM F64 little-endian.
200 pcm_lxf = lib.AV_CODEC_ID_PCM_LXF # PCM LXF.
201 pcm_mulaw = lib.AV_CODEC_ID_PCM_MULAW # PCM μ-law.
202 pcm_s16be = lib.AV_CODEC_ID_PCM_S16BE # PCM signed 16-bit big-endian.
203 pcm_s16be_planar = lib.AV_CODEC_ID_PCM_S16BE_PLANAR # PCM signed 16-bit big-endian planar.
204 pcm_s16le = lib.AV_CODEC_ID_PCM_S16LE # PCM signed 16-bit little-endian.
205 pcm_s16le_planar = lib.AV_CODEC_ID_PCM_S16LE_PLANAR # PCM signed 16-bit little-endian planar.
206 pcm_s24be = lib.AV_CODEC_ID_PCM_S24BE # PCM signed 24-bit big-endian.
207 pcm_s24daud = lib.AV_CODEC_ID_PCM_S24DAUD # PCM signed 24-bit D-Cinema audio.
208 pcm_s24le = lib.AV_CODEC_ID_PCM_S24LE # PCM signed 24-bit little-endian.
209 pcm_s24le_planar = lib.AV_CODEC_ID_PCM_S24LE_PLANAR # PCM signed 24-bit little-endian planar.
210 pcm_s32be = lib.AV_CODEC_ID_PCM_S32BE # PCM signed 32-bit big-endian.
211 pcm_s32le = lib.AV_CODEC_ID_PCM_S32LE # PCM signed 32-bit little-endian.
212 pcm_s32le_planar = lib.AV_CODEC_ID_PCM_S32LE_PLANAR # PCM signed 32-bit little-endian planar.
213 pcm_s64be = lib.AV_CODEC_ID_PCM_S64BE # PCM signed 64-bit big-endian.
214 pcm_s64le = lib.AV_CODEC_ID_PCM_S64LE # PCM signed 64-bit little-endian.
215 pcm_s8 = lib.AV_CODEC_ID_PCM_S8 # PCM signed 8-bit.
216 pcm_s8_planar = lib.AV_CODEC_ID_PCM_S8_PLANAR # PCM signed 8-bit planar.
217 pcm_u16be = lib.AV_CODEC_ID_PCM_U16BE # PCM unsigned 16-bit big-endian.
218 pcm_u16le = lib.AV_CODEC_ID_PCM_U16LE # PCM unsigned 16-bit little-endian.
219 pcm_u24be = lib.AV_CODEC_ID_PCM_U24BE # PCM unsigned 24-bit big-endian.
220 pcm_u24le = lib.AV_CODEC_ID_PCM_U24LE # PCM unsigned 24-bit little-endian.
221 pcm_u32be = lib.AV_CODEC_ID_PCM_U32BE # PCM unsigned 32-bit big-endian.
222 pcm_u32le = lib.AV_CODEC_ID_PCM_U32LE # PCM unsigned 32-bit little-endian.
223 pcm_u8 = lib.AV_CODEC_ID_PCM_U8 # PCM unsigned 8-bit.
224 pcm_vidc = lib.AV_CODEC_ID_PCM_VIDC # PCM VIDC.
225 # fmt: on
226
227
228 @cython.cclass
229 class Container:
230 def __cinit__(
231 self,
232 sentinel,
233 file_,
234 format_name,
235 options,
236 container_options,
237 stream_options,
238 hwaccel,
239 metadata_encoding,
240 metadata_errors,
241 buffer_size,
242 open_timeout,
243 read_timeout,
244 io_open,
245 ):
246 if sentinel is not _cinit_sentinel:
247 raise RuntimeError("cannot construct base Container")
248
249 writeable: cython.bint = isinstance(self, OutputContainer)
250 if not writeable and not isinstance(self, InputContainer):
251 raise RuntimeError("Container cannot be directly extended.")
252
253 if isinstance(file_, str):
254 self.name = file_
255 else:
256 self.name = str(getattr(file_, "name", "<none>"))
257
258 self.options = dict(options or ())
259 self.container_options = dict(container_options or ())
260 self.stream_options = [dict(x) for x in stream_options or ()]
261
262 self.hwaccel = hwaccel
263
264 self.metadata_encoding = metadata_encoding
265 self.metadata_errors = metadata_errors
266
267 self.open_timeout = open_timeout
268 self.read_timeout = read_timeout
269
270 self.buffer_size = buffer_size
271 self.io_open = io_open
272
273 acodec = None # no audio codec specified
274 if format_name is not None:
275 if ":" in format_name:
276 format_name, acodec = format_name.split(":")
277 self.format = ContainerFormat(format_name)
278
279 res: cython.int
280 name_obj: bytes = os.fsencode(self.name)
281 name: cython.p_char = name_obj
282 ofmt: cython.pointer[cython.const[lib.AVOutputFormat]]
283
284 if writeable:
285 self._myflag |= 1 # enum.writeable = True
286 ofmt = (
287 self.format.optr
288 if self.format
289 else lib.av_guess_format(cython.NULL, name, cython.NULL)
290 )
291 if ofmt == cython.NULL:
292 raise ValueError("Could not determine output format")
293
294 with cython.nogil:
295 # This does not actually open the file.
296 res = lib.avformat_alloc_output_context2(
297 cython.address(self.ptr),
298 ofmt,
299 cython.NULL,
300 name,
301 )
302 self.err_check(res)
303 else:
304 # We need the context before we open the input AND setup Python IO.
305 self.ptr = lib.avformat_alloc_context()
306
307 # Setup interrupt callback
308 if self.open_timeout is not None or self.read_timeout is not None:
309 self.ptr.interrupt_callback.callback = interrupt_cb
310 self.ptr.interrupt_callback.opaque = cython.address(
311 self.interrupt_callback_info
312 )
313
314 if acodec is not None:
315 self.ptr.audio_codec_id = getattr(AudioCodec, acodec)
316
317 self.ptr.flags |= lib.AVFMT_FLAG_GENPTS
318 self.ptr.opaque = cython.cast(cython.p_void, self)
319
320 # Setup Python IO.
321 self.open_files = {}
322 if not isinstance(file_, basestring):
323 self.file = PyIOFile(file_, buffer_size, writeable)
324 self.ptr.pb = self.file.iocontext
325
326 if io_open is not None:
327 self.ptr.io_open = pyav_io_open
328 self.ptr.io_close2 = pyav_io_close
329 self.ptr.flags |= lib.AVFMT_FLAG_CUSTOM_IO
330
331 ifmt: cython.pointer[cython.const[lib.AVInputFormat]]
332 c_options: Dictionary
333 if not writeable:
334 ifmt = self.format.iptr if self.format else cython.NULL
335 c_options = Dictionary(self.options, self.container_options)
336
337 self.set_timeout(self.open_timeout)
338 self.start_timeout()
339 with cython.nogil:
340 res = lib.avformat_open_input(
341 cython.address(self.ptr), name, ifmt, cython.address(c_options.ptr)
342 )
343 self.set_timeout(None)
344 self.err_check(res)
345 self._myflag |= 2 # enum.input_was_opened = True
346
347 if format_name is None:
348 self.format = build_container_format(self.ptr.iformat, self.ptr.oformat)
349
350 def __dealloc__(self):
351 with cython.nogil:
352 lib.avformat_free_context(self.ptr)
353
354 def __enter__(self):
355 return self
356
357 def __exit__(self, exc_type, exc_val, exc_tb):
358 self.close()
359
360 def close(self):
361 raise NotImplementedError
362
363 def __repr__(self):
364 return f"<av.{self.__class__.__name__} {self.file or self.name!r}>"
365
366 @cython.cfunc
367 @cython.exceptval(-1, check=False)
368 def err_check(self, value: cython.int) -> cython.int:
369 return err_check(value, filename=self.name)
370
371 def dumps_format(self):
372 self._assert_open()
373 with LogCapture() as logs:
374 lib.av_dump_format(self.ptr, 0, "", isinstance(self, OutputContainer))
375 return "".join(log[2] for log in logs)
376
377 @cython.cfunc
378 def set_timeout(self, timeout):
379 if timeout is None:
380 self.interrupt_callback_info.timeout = -1.0
381 else:
382 self.interrupt_callback_info.timeout = timeout
383
384 @cython.cfunc
385 def start_timeout(self):
386 self.interrupt_callback_info.start_time = time.monotonic()
387
388 @cython.cfunc
389 def _assert_open(self):
390 if self.ptr == cython.NULL:
391 raise AssertionError("Container is not open")
392
393 @property
394 def video_codec_id(self):
395 self._assert_open()
396 return self.ptr.video_codec_id
397
398 @video_codec_id.setter
399 def video_codec_id(self, value: lib.AVCodecID):
400 self._assert_open()
401 self.ptr.video_codec_id = value
402
403 @property
404 def flags(self):
405 self._assert_open()
406 return self.ptr.flags
407
408 @flags.setter
409 def flags(self, value: cython.int):
410 self._assert_open()
411 self.ptr.flags = value
412
413 @property
414 def input_was_opened(self):
415 return self._myflag & 2
416
417 def chapters(self):
418 self._assert_open()
419 result: list = []
420 i: cython.Py_ssize_t
421 for i in range(self.ptr.nb_chapters):
422 ch = self.ptr.chapters[i]
423 result.append(
424 {
425 "id": ch.id,
426 "start": ch.start,
427 "end": ch.end,
428 "time_base": avrational_to_fraction(cython.address(ch.time_base)),
429 "metadata": avdict_to_dict(
430 ch.metadata, self.metadata_encoding, self.metadata_errors
431 ),
432 }
433 )
434 return result
435
436 def set_chapters(self, chapters):
437 self._assert_open()
438
439 count: cython.Py_ssize_t = len(chapters)
440 i: cython.Py_ssize_t
441 ch_array: AVChapterPtrPtr
442 ch: cython.pointer[lib.AVChapter]
443 entry: dict
444
445 with cython.nogil:
446 _free_chapters(self.ptr)
447
448 if count == 0:
449 self.ptr.nb_chapters = 0
450 self.ptr.chapters = cython.NULL
451 return
452
453 ch_array = cython.cast(
454 AVChapterPtrPtr,
455 lib.av_malloc(count * cython.sizeof(cython.pointer[lib.AVChapter])),
456 )
457 if ch_array == cython.NULL:
458 raise MemoryError("av_malloc failed for chapters")
459
460 for i in range(count):
461 entry = chapters[i]
462 ch = cython.cast(
463 cython.pointer[lib.AVChapter],
464 lib.av_malloc(cython.sizeof(lib.AVChapter)),
465 )
466 if ch == cython.NULL:
467 raise MemoryError("av_malloc failed for chapter")
468 ch.id = entry["id"]
469 ch.start = cython.cast(int64_t, entry["start"])
470 ch.end = cython.cast(int64_t, entry["end"])
471 to_avrational(entry["time_base"], cython.address(ch.time_base))
472 ch.metadata = cython.NULL
473 if "metadata" in entry:
474 dict_to_avdict(
475 cython.address(ch.metadata),
476 entry["metadata"],
477 self.metadata_encoding,
478 self.metadata_errors,
479 )
480 ch_array[i] = ch
481
482 self.ptr.nb_chapters = count
483 self.ptr.chapters = ch_array
484
485
486 def open(
487 file,
488 mode=None,
489 format=None,
490 options=None,
491 container_options=None,
492 stream_options=None,
493 metadata_encoding="utf-8",
494 metadata_errors="strict",
495 buffer_size=32768,
496 timeout=None,
497 io_open=None,
498 hwaccel=None,
499 ):
500 """open(file, mode='r', **kwargs)
501
502 Main entrypoint to opening files/streams.
503
504 :param str file: The file to open, which can be either a string or a file-like object.
505 :param str mode: ``"r"`` for reading and ``"w"`` for writing.
506 :param str format: Specific format to use. Defaults to autodect.
507 :param dict options: Options to pass to the container and all streams.
508 :param dict container_options: Options to pass to the container.
509 :param list stream_options: Options to pass to each stream.
510 :param str metadata_encoding: Encoding to use when reading or writing file metadata.
511 Defaults to ``"utf-8"``.
512 :param str metadata_errors: Specifies how to handle encoding errors; behaves like
513 ``str.encode`` parameter. Defaults to ``"strict"``.
514 :param int buffer_size: Size of buffer for Python input/output operations in bytes.
515 Honored only when ``file`` is a file-like object. Defaults to 32768 (32k).
516 :param timeout: How many seconds to wait for data before giving up, as a float, or a
517 ``(open timeout, read timeout)`` tuple.
518 :param callable io_open: Custom I/O callable for opening files/streams.
519 This option is intended for formats that need to open additional
520 file-like objects to ``file`` using custom I/O.
521 The callable signature is ``io_open(url: str, flags: int, options: dict)``, where
522 ``url`` is the url to open, ``flags`` is a combination of AVIO_FLAG_* and
523 ``options`` is a dictionary of additional options. The callable should return a
524 file-like object.
525 :param HWAccel hwaccel: Optional settings for hardware-accelerated decoding.
526 :rtype: Container
527
528 For devices (via ``libavdevice``), pass the name of the device to ``format``,
529 e.g.::
530
531 >>> # Open webcam on MacOS.
532 >>> av.open('0', format='avfoundation') # doctest: +SKIP
533
534 For DASH and custom I/O using ``io_open``, add a protocol prefix to the ``file`` to
535 prevent the DASH encoder defaulting to the file protocol and using temporary files.
536 The custom I/O callable can be used to remove the protocol prefix to reveal the actual
537 name for creating the file-like object. E.g.::
538
539 >>> av.open("customprotocol://manifest.mpd", "w", io_open=custom_io) # doctest: +SKIP
540
541 .. seealso:: :ref:`garbage_collection`
542
543 More information on using input and output devices is available on the
544 `FFmpeg website <https://www.ffmpeg.org/ffmpeg-devices.html>`_.
545 """
546
547 if not (mode is None or (isinstance(mode, str) and mode == "r" or mode == "w")):
548 raise ValueError(f"mode must be 'r', 'w', or None, got: {mode}")
549
550 if isinstance(file, str):
551 pass
552 elif isinstance(file, Path):
553 file = f"{file}"
554 elif mode is None:
555 mode = getattr(file, "mode", None)
556
557 if mode is None:
558 mode = "r"
559
560 if isinstance(timeout, tuple):
561 if not len(timeout) == 2:
562 raise ValueError("timeout must be `float` or `tuple[float, float]`")
563
564 open_timeout, read_timeout = timeout
565 else:
566 open_timeout = timeout
567 read_timeout = timeout
568
569 if mode.startswith("r"):
570 return InputContainer(
571 _cinit_sentinel,
572 file,
573 format,
574 options,
575 container_options,
576 stream_options,
577 hwaccel,
578 metadata_encoding,
579 metadata_errors,
580 buffer_size,
581 open_timeout,
582 read_timeout,
583 io_open,
584 )
585
586 if stream_options:
587 raise ValueError(
588 "Provide stream options via Container.add_stream(..., options={})."
589 )
590 return OutputContainer(
591 _cinit_sentinel,
592 file,
593 format,
594 options,
595 container_options,
596 stream_options,
597 None,
598 metadata_encoding,
599 metadata_errors,
600 buffer_size,
601 open_timeout,
602 read_timeout,
603 io_open,
604 )