diff --git a/.gitattributes b/.gitattributes index a137d05242eb416d965afd01b79e73110f606033..e6fc0d689570f61ba43c745378a58893bfd365df 100644 --- a/.gitattributes +++ b/.gitattributes @@ -66,3 +66,5 @@ lib/python3.10/site-packages/propcache/_helpers_c.cpython-310-x86_64-linux-gnu.s lib/python3.10/site-packages/rpds/rpds.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text lib/python3.10/site-packages/grpc/_cython/cygrpc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text lib/python3.10/site-packages/fugashi.libs/libmecab-eada4a80.so.2.0.0 filter=lfs diff=lfs merge=lfs -text +lib/python3.10/site-packages/av/utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +lib/python3.10/site-packages/av/plane.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/lib/python3.10/site-packages/arrow/_version.py b/lib/python3.10/site-packages/arrow/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..67bc602abf06e9bcea675fe21c56a2f3c76bc331 --- /dev/null +++ b/lib/python3.10/site-packages/arrow/_version.py @@ -0,0 +1 @@ +__version__ = "1.3.0" diff --git a/lib/python3.10/site-packages/arrow/constants.py b/lib/python3.10/site-packages/arrow/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..53d163b999e3cf796df0fff20723394c3c899f0c --- /dev/null +++ b/lib/python3.10/site-packages/arrow/constants.py @@ -0,0 +1,177 @@ +"""Constants used internally in arrow.""" + +import sys +from datetime import datetime + +if sys.version_info < (3, 8): # pragma: no cover + from typing_extensions import Final +else: + from typing import Final # pragma: no cover + +# datetime.max.timestamp() errors on Windows, so we must hardcode +# the highest possible datetime value that can output a timestamp. +# tl;dr platform-independent max timestamps are hard to form +# See: https://stackoverflow.com/q/46133223 +try: + # Get max timestamp. Works on POSIX-based systems like Linux and macOS, + # but will trigger an OverflowError, ValueError, or OSError on Windows + _MAX_TIMESTAMP = datetime.max.timestamp() +except (OverflowError, ValueError, OSError): # pragma: no cover + # Fallback for Windows and 32-bit systems if initial max timestamp call fails + # Must get max value of ctime on Windows based on architecture (x32 vs x64) + # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/ctime-ctime32-ctime64-wctime-wctime32-wctime64 + # Note: this may occur on both 32-bit Linux systems (issue #930) along with Windows systems + is_64bits = sys.maxsize > 2**32 + _MAX_TIMESTAMP = ( + datetime(3000, 1, 1, 23, 59, 59, 999999).timestamp() + if is_64bits + else datetime(2038, 1, 1, 23, 59, 59, 999999).timestamp() + ) + +MAX_TIMESTAMP: Final[float] = _MAX_TIMESTAMP +MAX_TIMESTAMP_MS: Final[float] = MAX_TIMESTAMP * 1000 +MAX_TIMESTAMP_US: Final[float] = MAX_TIMESTAMP * 1_000_000 + +MAX_ORDINAL: Final[int] = datetime.max.toordinal() +MIN_ORDINAL: Final[int] = 1 + +DEFAULT_LOCALE: Final[str] = "en-us" + +# Supported dehumanize locales +DEHUMANIZE_LOCALES = { + "en", + "en-us", + "en-gb", + "en-au", + "en-be", + "en-jp", + "en-za", + "en-ca", + "en-ph", + "fr", + "fr-fr", + "fr-ca", + "it", + "it-it", + "es", + "es-es", + "el", + "el-gr", + "ja", + "ja-jp", + "se", + "se-fi", + "se-no", + "se-se", + "sv", + "sv-se", + "fi", + "fi-fi", + "zh", + "zh-cn", + "zh-tw", + "zh-hk", + "nl", + "nl-nl", + "be", + "be-by", + "pl", + "pl-pl", + "ru", + "ru-ru", + "af", + "bg", + "bg-bg", + "ua", + "uk", + "uk-ua", + "mk", + "mk-mk", + "de", + "de-de", + "de-ch", + "de-at", + "nb", + "nb-no", + "nn", + "nn-no", + "pt", + "pt-pt", + "pt-br", + "tl", + "tl-ph", + "vi", + "vi-vn", + "tr", + "tr-tr", + "az", + "az-az", + "da", + "da-dk", + "ml", + "hi", + "cs", + "cs-cz", + "sk", + "sk-sk", + "fa", + "fa-ir", + "mr", + "ca", + "ca-es", + "ca-ad", + "ca-fr", + "ca-it", + "eo", + "eo-xx", + "bn", + "bn-bd", + "bn-in", + "rm", + "rm-ch", + "ro", + "ro-ro", + "sl", + "sl-si", + "id", + "id-id", + "ne", + "ne-np", + "ee", + "et", + "sw", + "sw-ke", + "sw-tz", + "la", + "la-va", + "lt", + "lt-lt", + "ms", + "ms-my", + "ms-bn", + "or", + "or-in", + "lb", + "lb-lu", + "zu", + "zu-za", + "sq", + "sq-al", + "ta", + "ta-in", + "ta-lk", + "ur", + "ur-pk", + "ka", + "ka-ge", + "kk", + "kk-kz", + # "lo", + # "lo-la", + "am", + "am-et", + "hy-am", + "hy", + "uz", + "uz-uz", +} diff --git a/lib/python3.10/site-packages/arrow/util.py b/lib/python3.10/site-packages/arrow/util.py new file mode 100644 index 0000000000000000000000000000000000000000..f3eaa21c9b46c00ae011261c8e51c07273a16c43 --- /dev/null +++ b/lib/python3.10/site-packages/arrow/util.py @@ -0,0 +1,117 @@ +"""Helpful functions used internally within arrow.""" + +import datetime +from typing import Any, Optional, cast + +from dateutil.rrule import WEEKLY, rrule + +from arrow.constants import ( + MAX_ORDINAL, + MAX_TIMESTAMP, + MAX_TIMESTAMP_MS, + MAX_TIMESTAMP_US, + MIN_ORDINAL, +) + + +def next_weekday( + start_date: Optional[datetime.date], weekday: int +) -> datetime.datetime: + """Get next weekday from the specified start date. + + :param start_date: Datetime object representing the start date. + :param weekday: Next weekday to obtain. Can be a value between 0 (Monday) and 6 (Sunday). + :return: Datetime object corresponding to the next weekday after start_date. + + Usage:: + + # Get first Monday after epoch + >>> next_weekday(datetime(1970, 1, 1), 0) + 1970-01-05 00:00:00 + + # Get first Thursday after epoch + >>> next_weekday(datetime(1970, 1, 1), 3) + 1970-01-01 00:00:00 + + # Get first Sunday after epoch + >>> next_weekday(datetime(1970, 1, 1), 6) + 1970-01-04 00:00:00 + """ + if weekday < 0 or weekday > 6: + raise ValueError("Weekday must be between 0 (Monday) and 6 (Sunday).") + return cast( + datetime.datetime, + rrule(freq=WEEKLY, dtstart=start_date, byweekday=weekday, count=1)[0], + ) + + +def is_timestamp(value: Any) -> bool: + """Check if value is a valid timestamp.""" + if isinstance(value, bool): + return False + if not isinstance(value, (int, float, str)): + return False + try: + float(value) + return True + except ValueError: + return False + + +def validate_ordinal(value: Any) -> None: + """Raise an exception if value is an invalid Gregorian ordinal. + + :param value: the input to be checked + + """ + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"Ordinal must be an integer (got type {type(value)}).") + if not (MIN_ORDINAL <= value <= MAX_ORDINAL): + raise ValueError(f"Ordinal {value} is out of range.") + + +def normalize_timestamp(timestamp: float) -> float: + """Normalize millisecond and microsecond timestamps into normal timestamps.""" + if timestamp > MAX_TIMESTAMP: + if timestamp < MAX_TIMESTAMP_MS: + timestamp /= 1000 + elif timestamp < MAX_TIMESTAMP_US: + timestamp /= 1_000_000 + else: + raise ValueError(f"The specified timestamp {timestamp!r} is too large.") + return timestamp + + +# Credit to https://stackoverflow.com/a/1700069 +def iso_to_gregorian(iso_year: int, iso_week: int, iso_day: int) -> datetime.date: + """Converts an ISO week date into a datetime object. + + :param iso_year: the year + :param iso_week: the week number, each year has either 52 or 53 weeks + :param iso_day: the day numbered 1 through 7, beginning with Monday + + """ + + if not 1 <= iso_week <= 53: + raise ValueError("ISO Calendar week value must be between 1-53.") + + if not 1 <= iso_day <= 7: + raise ValueError("ISO Calendar day value must be between 1-7") + + # The first week of the year always contains 4 Jan. + fourth_jan = datetime.date(iso_year, 1, 4) + delta = datetime.timedelta(fourth_jan.isoweekday() - 1) + year_start = fourth_jan - delta + gregorian = year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1) + + return gregorian + + +def validate_bounds(bounds: str) -> None: + if bounds != "()" and bounds != "(]" and bounds != "[)" and bounds != "[]": + raise ValueError( + "Invalid bounds. Please select between '()', '(]', '[)', or '[]'." + ) + + +__all__ = ["next_weekday", "is_timestamp", "validate_ordinal", "iso_to_gregorian"] diff --git a/lib/python3.10/site-packages/av/attachments/__init__.py b/lib/python3.10/site-packages/av/attachments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.10/site-packages/av/attachments/stream.pxd b/lib/python3.10/site-packages/av/attachments/stream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..81f788b7741fc3d148f2d55e3d33aead5bcc9f62 --- /dev/null +++ b/lib/python3.10/site-packages/av/attachments/stream.pxd @@ -0,0 +1,5 @@ +from av.stream cimport Stream + + +cdef class AttachmentStream(Stream): + pass diff --git a/lib/python3.10/site-packages/av/attachments/stream.pyi b/lib/python3.10/site-packages/av/attachments/stream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3d660e4a0eb6afbe9be9d912082893d9c8973b16 --- /dev/null +++ b/lib/python3.10/site-packages/av/attachments/stream.pyi @@ -0,0 +1,8 @@ +from typing import Literal + +from av.stream import Stream + +class AttachmentStream(Stream): + type: Literal["attachment"] + @property + def mimetype(self) -> str | None: ... diff --git a/lib/python3.10/site-packages/av/attachments/stream.pyx b/lib/python3.10/site-packages/av/attachments/stream.pyx new file mode 100644 index 0000000000000000000000000000000000000000..de7d101196f4fe58015b4ec47fbcc9f45953c42a --- /dev/null +++ b/lib/python3.10/site-packages/av/attachments/stream.pyx @@ -0,0 +1,26 @@ +from av.stream cimport Stream + + +cdef class AttachmentStream(Stream): + """ + An :class:`AttachmentStream` represents a stream of attachment data within a media container. + Typically used to attach font files that are referenced in ASS/SSA Subtitle Streams. + """ + + @property + def name(self): + """ + Returns the file name of the attachment. + + :rtype: str | None + """ + return self.metadata.get("filename") + + @property + def mimetype(self): + """ + Returns the MIME type of the attachment. + + :rtype: str | None + """ + return self.metadata.get("mimetype") diff --git a/lib/python3.10/site-packages/av/audio/__init__.pxd b/lib/python3.10/site-packages/av/audio/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.10/site-packages/av/audio/__init__.py b/lib/python3.10/site-packages/av/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74ddf696497af9293024c39df458c9b03dd0cf0a --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/__init__.py @@ -0,0 +1,2 @@ +from .frame import AudioFrame +from .stream import AudioStream diff --git a/lib/python3.10/site-packages/av/audio/__init__.pyi b/lib/python3.10/site-packages/av/audio/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..73f2eebddf52ed45cdb7cd819e75b3ea7d735f4a --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/__init__.pyi @@ -0,0 +1,4 @@ +from .frame import AudioFrame +from .stream import AudioStream + +__all__ = ("AudioFrame", "AudioStream") diff --git a/lib/python3.10/site-packages/av/audio/codeccontext.pxd b/lib/python3.10/site-packages/av/audio/codeccontext.pxd new file mode 100644 index 0000000000000000000000000000000000000000..55ad15e9f0404d2b77810682774fd25ab434fadb --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/codeccontext.pxd @@ -0,0 +1,11 @@ + +from av.audio.frame cimport AudioFrame +from av.audio.resampler cimport AudioResampler +from av.codec.context cimport CodecContext + + +cdef class AudioCodecContext(CodecContext): + # Hold onto the frames that we will decode until we have a full one. + cdef AudioFrame next_frame + # For encoding. + cdef AudioResampler resampler diff --git a/lib/python3.10/site-packages/av/audio/codeccontext.pyi b/lib/python3.10/site-packages/av/audio/codeccontext.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b3ec3ce6e877a88a9fcf7661c9aded27201fc8fb --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/codeccontext.pyi @@ -0,0 +1,29 @@ +from typing import Iterator, Literal + +from av.codec.context import CodecContext +from av.packet import Packet + +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class _Format: + def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ... + def __set__(self, instance: object, value: AudioFormat | str) -> None: ... + +class _Layout: + def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ... + def __set__(self, instance: object, value: AudioLayout | str) -> None: ... + +class AudioCodecContext(CodecContext): + frame_size: int + sample_rate: int + rate: int + type: Literal["audio"] + format: _Format + layout: _Layout + @property + def channels(self) -> int: ... + def encode(self, frame: AudioFrame | None = None) -> list[Packet]: ... + def encode_lazy(self, frame: AudioFrame | None = None) -> Iterator[Packet]: ... + def decode(self, packet: Packet | None = None) -> list[AudioFrame]: ... diff --git a/lib/python3.10/site-packages/av/audio/codeccontext.pyx b/lib/python3.10/site-packages/av/audio/codeccontext.pyx new file mode 100644 index 0000000000000000000000000000000000000000..856af555c72a5d7acf0db30bb21ff561f09c169b --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/codeccontext.pyx @@ -0,0 +1,106 @@ +cimport libav as lib + +from av.audio.format cimport AudioFormat, get_audio_format +from av.audio.frame cimport AudioFrame, alloc_audio_frame +from av.audio.layout cimport AudioLayout, get_audio_layout +from av.codec.hwaccel cimport HWAccel +from av.frame cimport Frame +from av.packet cimport Packet + + +cdef class AudioCodecContext(CodecContext): + cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel): + CodecContext._init(self, ptr, codec, hwaccel) + + cdef _prepare_frames_for_encode(self, Frame input_frame): + + cdef AudioFrame frame = input_frame + cdef bint allow_var_frame_size = self.ptr.codec.capabilities & lib.AV_CODEC_CAP_VARIABLE_FRAME_SIZE + + # Note that the resampler will simply return an input frame if there is + # no resampling to be done. The control flow was just a little easier this way. + if not self.resampler: + self.resampler = AudioResampler( + format=self.format, + layout=self.layout, + rate=self.ptr.sample_rate, + frame_size=None if allow_var_frame_size else self.ptr.frame_size + ) + frames = self.resampler.resample(frame) + + # flush if input frame is None + if input_frame is None: + frames.append(None) + + return frames + + cdef Frame _alloc_next_frame(self): + return alloc_audio_frame() + + cdef _setup_decoded_frame(self, Frame frame, Packet packet): + CodecContext._setup_decoded_frame(self, frame, packet) + cdef AudioFrame aframe = frame + aframe._init_user_attributes() + + @property + def frame_size(self): + """ + Number of samples per channel in an audio frame. + + :type: int + """ + return self.ptr.frame_size + + @property + def sample_rate(self): + """ + Sample rate of the audio data, in samples per second. + + :type: int + """ + return self.ptr.sample_rate + + @sample_rate.setter + def sample_rate(self, int value): + self.ptr.sample_rate = value + + @property + def rate(self): + """Another name for :attr:`sample_rate`.""" + return self.sample_rate + + @rate.setter + def rate(self, value): + self.sample_rate = value + + @property + def channels(self): + return self.layout.nb_channels + + @property + def layout(self): + """ + The audio channel layout. + + :type: AudioLayout + """ + return get_audio_layout(self.ptr.ch_layout) + + @layout.setter + def layout(self, value): + cdef AudioLayout layout = AudioLayout(value) + self.ptr.ch_layout = layout.layout + + @property + def format(self): + """ + The audio sample format. + + :type: AudioFormat + """ + return get_audio_format(self.ptr.sample_fmt) + + @format.setter + def format(self, value): + cdef AudioFormat format = AudioFormat(value) + self.ptr.sample_fmt = format.sample_fmt diff --git a/lib/python3.10/site-packages/av/audio/fifo.pxd b/lib/python3.10/site-packages/av/audio/fifo.pxd new file mode 100644 index 0000000000000000000000000000000000000000..0ace5e4b1ec84daaeb09f27f6f9689a56d026912 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/fifo.pxd @@ -0,0 +1,19 @@ +cimport libav as lib +from libc.stdint cimport int64_t, uint64_t + +from av.audio.frame cimport AudioFrame + + +cdef class AudioFifo: + + cdef lib.AVAudioFifo *ptr + + cdef AudioFrame template + + cdef readonly uint64_t samples_written + cdef readonly uint64_t samples_read + cdef readonly double pts_per_sample + + cpdef write(self, AudioFrame frame) + cpdef read(self, int samples=*, bint partial=*) + cpdef read_many(self, int samples, bint partial=*) diff --git a/lib/python3.10/site-packages/av/audio/fifo.pyi b/lib/python3.10/site-packages/av/audio/fifo.pyi new file mode 100644 index 0000000000000000000000000000000000000000..085ed4bba1039b77675da29e26ef9ccbd539c8e1 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/fifo.pyi @@ -0,0 +1,22 @@ +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class AudioFifo: + def write(self, frame: AudioFrame) -> None: ... + def read(self, samples: int = 0, partial: bool = False) -> AudioFrame | None: ... + def read_many(self, samples: int, partial: bool = False) -> list[AudioFrame]: ... + @property + def format(self) -> AudioFormat: ... + @property + def layout(self) -> AudioLayout: ... + @property + def sample_rate(self) -> int: ... + @property + def samples(self) -> int: ... + @property + def samples_written(self) -> int: ... + @property + def samples_read(self) -> int: ... + @property + def pts_per_sample(self) -> float: ... diff --git a/lib/python3.10/site-packages/av/audio/format.pxd b/lib/python3.10/site-packages/av/audio/format.pxd new file mode 100644 index 0000000000000000000000000000000000000000..4160aa85b000714890d8a1d341becc0689d4091a --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/format.pxd @@ -0,0 +1,11 @@ +cimport libav as lib + + +cdef class AudioFormat: + + cdef lib.AVSampleFormat sample_fmt + + cdef _init(self, lib.AVSampleFormat sample_fmt) + + +cdef AudioFormat get_audio_format(lib.AVSampleFormat format) diff --git a/lib/python3.10/site-packages/av/audio/format.pyi b/lib/python3.10/site-packages/av/audio/format.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5f7e322edc85d831b5b6cc9979fd4dfca4b994c1 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/format.pyi @@ -0,0 +1,11 @@ +class AudioFormat: + name: str + bytes: int + bits: int + is_planar: bool + is_packed: bool + planar: AudioFormat + packed: AudioFormat + container_name: str + + def __init__(self, name: str | AudioFormat) -> None: ... diff --git a/lib/python3.10/site-packages/av/audio/frame.pxd b/lib/python3.10/site-packages/av/audio/frame.pxd new file mode 100644 index 0000000000000000000000000000000000000000..398d76d33ea1173e31a5e13809ba3910385572b3 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/frame.pxd @@ -0,0 +1,31 @@ +cimport libav as lib +from libc.stdint cimport uint8_t, uint64_t + +from av.audio.format cimport AudioFormat +from av.audio.layout cimport AudioLayout +from av.frame cimport Frame + + +cdef class AudioFrame(Frame): + # For raw storage of the frame's data; don't ever touch this. + cdef uint8_t *_buffer + cdef size_t _buffer_size + + cdef readonly AudioLayout layout + """ + The audio channel layout. + + :type: AudioLayout + """ + + cdef readonly AudioFormat format + """ + The audio sample format. + + :type: AudioFormat + """ + + cdef _init(self, lib.AVSampleFormat format, lib.AVChannelLayout layout, unsigned int nb_samples, unsigned int align) + cdef _init_user_attributes(self) + +cdef AudioFrame alloc_audio_frame() diff --git a/lib/python3.10/site-packages/av/audio/frame.pyi b/lib/python3.10/site-packages/av/audio/frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7f61e4e6dcccb5ae54aa27269c6adddf172a52a8 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/frame.pyi @@ -0,0 +1,47 @@ +from typing import Any, Union + +import numpy as np + +from av.frame import Frame + +from .format import AudioFormat +from .layout import AudioLayout +from .plane import AudioPlane + +format_dtypes: dict[str, str] +_SupportedNDarray = Union[ + np.ndarray[Any, np.dtype[np.float64]], # f8 + np.ndarray[Any, np.dtype[np.float32]], # f4 + np.ndarray[Any, np.dtype[np.int32]], # i4 + np.ndarray[Any, np.dtype[np.int16]], # i2 + np.ndarray[Any, np.dtype[np.uint8]], # u1 +] + +class _Format: + def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ... + def __set__(self, instance: object, value: AudioFormat | str) -> None: ... + +class _Layout: + def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ... + def __set__(self, instance: object, value: AudioLayout | str) -> None: ... + +class AudioFrame(Frame): + planes: tuple[AudioPlane, ...] + samples: int + sample_rate: int + rate: int + format: _Format + layout: _Layout + + def __init__( + self, + format: str = "s16", + layout: str = "stereo", + samples: int = 0, + align: int = 1, + ) -> None: ... + @staticmethod + def from_ndarray( + array: _SupportedNDarray, format: str = "s16", layout: str = "stereo" + ) -> AudioFrame: ... + def to_ndarray(self) -> _SupportedNDarray: ... diff --git a/lib/python3.10/site-packages/av/audio/frame.pyx b/lib/python3.10/site-packages/av/audio/frame.pyx new file mode 100644 index 0000000000000000000000000000000000000000..14356cb4e5d1427fb4e557d0f910fe1c5b7e2c03 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/frame.pyx @@ -0,0 +1,187 @@ +from av.audio.format cimport get_audio_format +from av.audio.layout cimport get_audio_layout +from av.audio.plane cimport AudioPlane +from av.error cimport err_check +from av.utils cimport check_ndarray + + +cdef object _cinit_bypass_sentinel + + +format_dtypes = { + "dbl": "f8", + "dblp": "f8", + "flt": "f4", + "fltp": "f4", + "s16": "i2", + "s16p": "i2", + "s32": "i4", + "s32p": "i4", + "u8": "u1", + "u8p": "u1", +} + + +cdef AudioFrame alloc_audio_frame(): + """Get a mostly uninitialized AudioFrame. + + You MUST call AudioFrame._init(...) or AudioFrame._init_user_attributes() + before exposing to the user. + + """ + return AudioFrame.__new__(AudioFrame, _cinit_bypass_sentinel) + + +cdef class AudioFrame(Frame): + """A frame of audio.""" + + def __cinit__(self, format="s16", layout="stereo", samples=0, align=1): + if format is _cinit_bypass_sentinel: + return + + cdef AudioFormat cy_format = AudioFormat(format) + cdef AudioLayout cy_layout = AudioLayout(layout) + self._init(cy_format.sample_fmt, cy_layout.layout, samples, align) + + cdef _init(self, lib.AVSampleFormat format, lib.AVChannelLayout layout, unsigned int nb_samples, unsigned int align): + self.ptr.nb_samples = nb_samples + self.ptr.format = format + self.ptr.ch_layout = layout + + # Sometimes this is called twice. Oh well. + self._init_user_attributes() + + if self.layout.nb_channels != 0 and nb_samples: + # Cleanup the old buffer. + lib.av_freep(&self._buffer) + + # Get a new one. + self._buffer_size = err_check(lib.av_samples_get_buffer_size( + NULL, + self.layout.nb_channels, + nb_samples, + format, + align + )) + self._buffer = lib.av_malloc(self._buffer_size) + if not self._buffer: + raise MemoryError("cannot allocate AudioFrame buffer") + + # Connect the data pointers to the buffer. + err_check(lib.avcodec_fill_audio_frame( + self.ptr, + self.layout.nb_channels, + self.ptr.format, + self._buffer, + self._buffer_size, + align + )) + + def __dealloc__(self): + lib.av_freep(&self._buffer) + + cdef _init_user_attributes(self): + self.layout = get_audio_layout(self.ptr.ch_layout) + self.format = get_audio_format(self.ptr.format) + + def __repr__(self): + return ( + f"" + +cdef object _cinit_bypass_sentinel + +cdef AudioLayout get_audio_layout(lib.AVChannelLayout c_layout): + """Get an AudioLayout from Cython land.""" + cdef AudioLayout layout = AudioLayout.__new__(AudioLayout, _cinit_bypass_sentinel) + layout._init(c_layout) + return layout + + +cdef class AudioLayout: + def __init__(self, layout): + if layout is _cinit_bypass_sentinel: + return + + if type(layout) is str: + ret = lib.av_channel_layout_from_string(&c_layout, layout) + if ret != 0: + raise ValueError(f"Invalid layout: {layout}") + elif isinstance(layout, AudioLayout): + c_layout = (layout).layout + else: + raise TypeError(f"layout must be of type: string | av.AudioLayout, got {type(layout)}") + + self._init(c_layout) + + cdef _init(self, lib.AVChannelLayout layout): + self.layout = layout + + def __repr__(self): + return f"" + + def __eq__(self, other): + return isinstance(other, AudioLayout) and self.name == other.name and self.nb_channels == other.nb_channels + + @property + def nb_channels(self): + return self.layout.nb_channels + + @property + def channels(self): + cdef lib.AVChannel channel + cdef char buf[16] + cdef char buf2[128] + + results = [] + + for index in range(self.layout.nb_channels): + channel = lib.av_channel_layout_channel_from_index(&self.layout, index); + size = lib.av_channel_name(buf, sizeof(buf), channel) - 1 + size2 = lib.av_channel_description(buf2, sizeof(buf2), channel) - 1 + results.append( + AudioChannel( + PyBytes_FromStringAndSize(buf, size).decode("utf-8"), + PyBytes_FromStringAndSize(buf2, size2).decode("utf-8"), + ) + ) + + return tuple(results) + + @property + def name(self) -> str: + """The canonical name of the audio layout.""" + cdef char layout_name[128] + cdef int ret + + ret = lib.av_channel_layout_describe(&self.layout, layout_name, sizeof(layout_name)) + if ret < 0: + raise RuntimeError(f"Failed to get layout name: {ret}") + + return layout_name \ No newline at end of file diff --git a/lib/python3.10/site-packages/av/audio/plane.pxd b/lib/python3.10/site-packages/av/audio/plane.pxd new file mode 100644 index 0000000000000000000000000000000000000000..316c84031c3da5b35135132227133b9ee5694bab --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/plane.pxd @@ -0,0 +1,8 @@ +from av.plane cimport Plane + + +cdef class AudioPlane(Plane): + + cdef readonly size_t buffer_size + + cdef size_t _buffer_size(self) diff --git a/lib/python3.10/site-packages/av/audio/plane.pyi b/lib/python3.10/site-packages/av/audio/plane.pyi new file mode 100644 index 0000000000000000000000000000000000000000..64524dcdb5170ebfbee5aaafff86f37f9a476444 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/plane.pyi @@ -0,0 +1,4 @@ +from av.plane import Plane + +class AudioPlane(Plane): + buffer_size: int diff --git a/lib/python3.10/site-packages/av/audio/plane.pyx b/lib/python3.10/site-packages/av/audio/plane.pyx new file mode 100644 index 0000000000000000000000000000000000000000..92c508cbd83f94e1458d877151899478bf9e2224 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/plane.pyx @@ -0,0 +1,11 @@ +from av.audio.frame cimport AudioFrame + + +cdef class AudioPlane(Plane): + + def __cinit__(self, AudioFrame frame, int index): + # Only the first linesize is ever populated, but it applies to every plane. + self.buffer_size = self.frame.ptr.linesize[0] + + cdef size_t _buffer_size(self): + return self.buffer_size diff --git a/lib/python3.10/site-packages/av/audio/resampler.pxd b/lib/python3.10/site-packages/av/audio/resampler.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d3601403d96bcc8774e993979109b3ff94495889 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/resampler.pxd @@ -0,0 +1,21 @@ +from av.audio.format cimport AudioFormat +from av.audio.frame cimport AudioFrame +from av.audio.layout cimport AudioLayout +from av.filter.graph cimport Graph + + +cdef class AudioResampler: + + cdef readonly bint is_passthrough + + cdef AudioFrame template + + # Destination descriptors + cdef readonly AudioFormat format + cdef readonly AudioLayout layout + cdef readonly int rate + cdef readonly unsigned int frame_size + + cdef Graph graph + + cpdef resample(self, AudioFrame) diff --git a/lib/python3.10/site-packages/av/audio/resampler.pyi b/lib/python3.10/site-packages/av/audio/resampler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cbf2134aa13911ebf13c7e2e676fadb96230f530 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/resampler.pyi @@ -0,0 +1,20 @@ +from av.filter.graph import Graph + +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class AudioResampler: + rate: int + frame_size: int + format: AudioFormat + graph: Graph | None + + def __init__( + self, + format: str | int | AudioFormat | None = None, + layout: str | int | AudioLayout | None = None, + rate: int | None = None, + frame_size: int | None = None, + ) -> None: ... + def resample(self, frame: AudioFrame | None) -> list[AudioFrame]: ... diff --git a/lib/python3.10/site-packages/av/audio/resampler.pyx b/lib/python3.10/site-packages/av/audio/resampler.pyx new file mode 100644 index 0000000000000000000000000000000000000000..69d790badd1eaa65614f955d78f3496096213014 --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/resampler.pyx @@ -0,0 +1,119 @@ +from av.filter.context cimport FilterContext + +import errno + +import av.filter + + +cdef class AudioResampler: + + """AudioResampler(format=None, layout=None, rate=None) + + :param AudioFormat format: The target format, or string that parses to one + (e.g. ``"s16"``). + :param AudioLayout layout: The target layout, or an int/string that parses + to one (e.g. ``"stereo"``). + :param int rate: The target sample rate. + + + """ + + def __cinit__(self, format=None, layout=None, rate=None, frame_size=None): + if format is not None: + self.format = format if isinstance(format, AudioFormat) else AudioFormat(format) + + if layout is not None: + self.layout = AudioLayout(layout) + self.rate = int(rate) if rate else 0 + + self.frame_size = int(frame_size) if frame_size else 0 + + self.graph = None + + cpdef resample(self, AudioFrame frame): + """resample(frame) + + Convert the ``sample_rate``, ``channel_layout`` and/or ``format`` of + a :class:`~.AudioFrame`. + + :param AudioFrame frame: The frame to convert or `None` to flush. + :returns: A list of :class:`AudioFrame` in new parameters. If the nothing is to be done return the same frame + as a single element list. + + """ + # We don't have any input, so don't bother even setting up. + if not self.graph and frame is None: + return [] + + # Shortcut for passthrough. + if self.is_passthrough: + return [frame] + + # Take source settings from the first frame. + if not self.graph: + self.template = frame + + # Set some default descriptors. + self.format = self.format or frame.format + self.layout = self.layout or frame.layout + self.rate = self.rate or frame.sample_rate + + # Check if we can passthrough or if there is actually work to do. + if ( + frame.format.sample_fmt == self.format.sample_fmt and + frame.layout == self.layout and + frame.sample_rate == self.rate and + self.frame_size == 0 + ): + self.is_passthrough = True + return [frame] + + # handle resampling with aformat filter + # (similar to configure_output_audio_filter from ffmpeg) + self.graph = av.filter.Graph() + extra_args = {} + if frame.time_base is not None: + extra_args["time_base"] = str(frame.time_base) + abuffer = self.graph.add( + "abuffer", + sample_rate=str(frame.sample_rate), + sample_fmt=AudioFormat(frame.format).name, + channel_layout=frame.layout.name, + **extra_args, + ) + aformat = self.graph.add( + "aformat", + sample_rates=str(self.rate), + sample_fmts=self.format.name, + channel_layouts=self.layout.name, + ) + abuffersink = self.graph.add("abuffersink") + abuffer.link_to(aformat) + aformat.link_to(abuffersink) + self.graph.configure() + + if self.frame_size > 0: + self.graph.set_audio_frame_size(self.frame_size) + + if frame is not None: + if ( + frame.format.sample_fmt != self.template.format.sample_fmt or + frame.layout != self.template.layout or + frame.sample_rate != self.template.rate + ): + raise ValueError("Frame does not match AudioResampler setup.") + + self.graph.push(frame) + + output = [] + while True: + try: + output.append(self.graph.pull()) + except EOFError: + break + except av.FFmpegError as e: + if e.errno != errno.EAGAIN: + raise + break + + return output diff --git a/lib/python3.10/site-packages/av/audio/stream.pyx b/lib/python3.10/site-packages/av/audio/stream.pyx new file mode 100644 index 0000000000000000000000000000000000000000..4d633edce6ef68b00e6f526e022f0c7aa894568f --- /dev/null +++ b/lib/python3.10/site-packages/av/audio/stream.pyx @@ -0,0 +1,43 @@ +from av.packet cimport Packet + +from .frame cimport AudioFrame + + +cdef class AudioStream(Stream): + def __repr__(self): + form = self.format.name if self.format else None + return ( + f"" + ) + + def __getattr__(self, name): + return getattr(self.codec_context, name) + + cpdef encode(self, AudioFrame frame=None): + """ + Encode an :class:`.AudioFrame` and return a list of :class:`.Packet`. + + :rtype: list[Packet] + + .. seealso:: This is mostly a passthrough to :meth:`.CodecContext.encode`. + """ + + packets = self.codec_context.encode(frame) + cdef Packet packet + for packet in packets: + packet._stream = self + packet.ptr.stream_index = self.ptr.index + + return packets + + cpdef decode(self, Packet packet=None): + """ + Decode a :class:`.Packet` and return a list of :class:`.AudioFrame`. + + :rtype: list[AudioFrame] + + .. seealso:: This is a passthrough to :meth:`.CodecContext.decode`. + """ + + return self.codec_context.decode(packet) diff --git a/lib/python3.10/site-packages/av/codec/__init__.pxd b/lib/python3.10/site-packages/av/codec/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.10/site-packages/av/codec/codec.pyi b/lib/python3.10/site-packages/av/codec/codec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4270c641f83a132ff0bcc99117ac891066cd3c7b --- /dev/null +++ b/lib/python3.10/site-packages/av/codec/codec.pyi @@ -0,0 +1,115 @@ +from enum import Flag, IntEnum +from fractions import Fraction +from typing import ClassVar, Literal, cast, overload + +from av.audio.codeccontext import AudioCodecContext +from av.audio.format import AudioFormat +from av.descriptor import Descriptor +from av.subtitles.codeccontext import SubtitleCodecContext +from av.video.codeccontext import VideoCodecContext +from av.video.format import VideoFormat + +from .context import CodecContext + +class Properties(Flag): + NONE = cast(ClassVar[Properties], ...) + INTRA_ONLY = cast(ClassVar[Properties], ...) + LOSSY = cast(ClassVar[Properties], ...) + LOSSLESS = cast(ClassVar[Properties], ...) + REORDER = cast(ClassVar[Properties], ...) + BITMAP_SUB = cast(ClassVar[Properties], ...) + TEXT_SUB = cast(ClassVar[Properties], ...) + +class Capabilities(IntEnum): + none = cast(int, ...) + draw_horiz_band = cast(int, ...) + dr1 = cast(int, ...) + hwaccel = cast(int, ...) + delay = cast(int, ...) + small_last_frame = cast(int, ...) + hwaccel_vdpau = cast(int, ...) + subframes = cast(int, ...) + experimental = cast(int, ...) + channel_conf = cast(int, ...) + neg_linesizes = cast(int, ...) + frame_threads = cast(int, ...) + slice_threads = cast(int, ...) + param_change = cast(int, ...) + auto_threads = cast(int, ...) + variable_frame_size = cast(int, ...) + avoid_probing = cast(int, ...) + hardware = cast(int, ...) + hybrid = cast(int, ...) + encoder_reordered_opaque = cast(int, ...) + encoder_flush = cast(int, ...) + encoder_recon_frame = cast(int, ...) + +class UnknownCodecError(ValueError): ... + +class Codec: + @property + def is_encoder(self) -> bool: ... + @property + def is_decoder(self) -> bool: ... + @property + def mode(self) -> Literal["r", "w"]: ... + descriptor: Descriptor + @property + def name(self) -> str: ... + @property + def canonical_name(self) -> str: ... + @property + def long_name(self) -> str: ... + @property + def type(self) -> Literal["video", "audio", "data", "subtitle", "attachment"]: ... + @property + def id(self) -> int: ... + frame_rates: list[Fraction] | None + audio_rates: list[int] | None + video_formats: list[VideoFormat] | None + audio_formats: list[AudioFormat] | None + + @property + def properties(self) -> int: ... + @property + def intra_only(self) -> bool: ... + @property + def lossy(self) -> bool: ... + @property + def lossless(self) -> bool: ... + @property + def reorder(self) -> bool: ... + @property + def bitmap_sub(self) -> bool: ... + @property + def text_sub(self) -> bool: ... + @property + def capabilities(self) -> int: ... + @property + def experimental(self) -> bool: ... + @property + def delay(self) -> bool: ... + def __init__(self, name: str, mode: Literal["r", "w"] = "r") -> None: ... + @overload + def create(self, kind: Literal["video"]) -> VideoCodecContext: ... + @overload + def create(self, kind: Literal["audio"]) -> AudioCodecContext: ... + @overload + def create(self, kind: Literal["subtitle"]) -> SubtitleCodecContext: ... + @overload + def create(self, kind: None = None) -> CodecContext: ... + @overload + def create( + self, kind: Literal["video", "audio", "subtitle"] | None = None + ) -> ( + VideoCodecContext | AudioCodecContext | SubtitleCodecContext | CodecContext + ): ... + +class codec_descriptor: + name: str + options: tuple[int, ...] + +codecs_available: set[str] + +def dump_codecs() -> None: ... +def dump_hwconfigs() -> None: ... diff --git a/lib/python3.10/site-packages/av/codec/context.pxd b/lib/python3.10/site-packages/av/codec/context.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7ba89dab75a619221ace0169cbe119aac7dea48d --- /dev/null +++ b/lib/python3.10/site-packages/av/codec/context.pxd @@ -0,0 +1,64 @@ +cimport libav as lib +from libc.stdint cimport int64_t + +from av.bytesource cimport ByteSource +from av.codec.codec cimport Codec +from av.codec.hwaccel cimport HWAccel +from av.frame cimport Frame +from av.packet cimport Packet + + +cdef class CodecContext: + cdef lib.AVCodecContext *ptr + + # Whether AVCodecContext.extradata should be de-allocated upon destruction. + cdef bint extradata_set + + # Used as a signal that this is within a stream, and also for us to access that + # stream. This is set "manually" by the stream after constructing this object. + cdef int stream_index + + cdef lib.AVCodecParserContext *parser + cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel) + + # Public API. + cdef readonly bint is_open + cdef readonly Codec codec + cdef readonly HWAccel hwaccel + cdef public dict options + cpdef open(self, bint strict=?) + + # Wraps both versions of the transcode API, returning lists. + cpdef encode(self, Frame frame=?) + cpdef decode(self, Packet packet=?) + cpdef flush_buffers(self) + + # Used by hardware-accelerated decode. + cdef HWAccel hwaccel_ctx + + # Used by both transcode APIs to setup user-land objects. + # TODO: Remove the `Packet` from `_setup_decoded_frame` (because flushing packets + # are bogus). It should take all info it needs from the context and/or stream. + cdef _prepare_and_time_rebase_frames_for_encode(self, Frame frame) + cdef _prepare_frames_for_encode(self, Frame frame) + cdef _setup_encoded_packet(self, Packet) + cdef _setup_decoded_frame(self, Frame, Packet) + + # Implemented by base for the generic send/recv API. + # Note that the user cannot send without receiving. This is because + # `_prepare_frames_for_encode` may expand a frame into multiple (e.g. when + # resampling audio to a higher rate but with fixed size frames), and the + # send/recv buffer may be limited to a single frame. Ergo, we need to flush + # the buffer as often as possible. + cdef _recv_packet(self) + cdef _send_packet_and_recv(self, Packet packet) + cdef _recv_frame(self) + + cdef _transfer_hwframe(self, Frame frame) + + # Implemented by children for the generic send/recv API, so we have the + # correct subclass of Frame. + cdef Frame _next_frame + cdef Frame _alloc_next_frame(self) + +cdef CodecContext wrap_codec_context(lib.AVCodecContext*, const lib.AVCodec*, HWAccel hwaccel) diff --git a/lib/python3.10/site-packages/av/codec/context.pyx b/lib/python3.10/site-packages/av/codec/context.pyx new file mode 100644 index 0000000000000000000000000000000000000000..5ca8f24a43204f9f74b439b7deab5b34cc90c6cc --- /dev/null +++ b/lib/python3.10/site-packages/av/codec/context.pyx @@ -0,0 +1,672 @@ +cimport libav as lib +from libc.errno cimport EAGAIN +from libc.stdint cimport uint8_t +from libc.string cimport memcpy + +from av.bytesource cimport ByteSource, bytesource +from av.codec.codec cimport Codec, wrap_codec +from av.dictionary cimport _Dictionary +from av.error cimport err_check +from av.packet cimport Packet +from av.utils cimport avrational_to_fraction, to_avrational + +from enum import Flag, IntEnum + +from av.dictionary import Dictionary + + +cdef object _cinit_sentinel = object() + + +cdef CodecContext wrap_codec_context(lib.AVCodecContext *c_ctx, const lib.AVCodec *c_codec, HWAccel hwaccel): + """Build an av.CodecContext for an existing AVCodecContext.""" + + cdef CodecContext py_ctx + + if c_ctx.codec_type == lib.AVMEDIA_TYPE_VIDEO: + from av.video.codeccontext import VideoCodecContext + py_ctx = VideoCodecContext(_cinit_sentinel) + elif c_ctx.codec_type == lib.AVMEDIA_TYPE_AUDIO: + from av.audio.codeccontext import AudioCodecContext + py_ctx = AudioCodecContext(_cinit_sentinel) + elif c_ctx.codec_type == lib.AVMEDIA_TYPE_SUBTITLE: + from av.subtitles.codeccontext import SubtitleCodecContext + py_ctx = SubtitleCodecContext(_cinit_sentinel) + else: + py_ctx = CodecContext(_cinit_sentinel) + + py_ctx._init(c_ctx, c_codec, hwaccel) + + return py_ctx + + +class ThreadType(Flag): + NONE = 0 + FRAME: "Decode more than one frame at once" = lib.FF_THREAD_FRAME + SLICE: "Decode more than one part of a single frame at once" = lib.FF_THREAD_SLICE + AUTO: "Decode using both FRAME and SLICE methods." = lib.FF_THREAD_SLICE | lib.FF_THREAD_FRAME + +class Flags(IntEnum): + unaligned = lib.AV_CODEC_FLAG_UNALIGNED + qscale = lib.AV_CODEC_FLAG_QSCALE + four_mv = lib.AV_CODEC_FLAG_4MV + output_corrupt = lib.AV_CODEC_FLAG_OUTPUT_CORRUPT + qpel = lib.AV_CODEC_FLAG_QPEL + drop_changed = 1 << 5 + recon_frame = lib.AV_CODEC_FLAG_RECON_FRAME + copy_opaque = lib.AV_CODEC_FLAG_COPY_OPAQUE + frame_duration = lib.AV_CODEC_FLAG_FRAME_DURATION + pass1 = lib.AV_CODEC_FLAG_PASS1 + pass2 = lib.AV_CODEC_FLAG_PASS2 + loop_filter = lib.AV_CODEC_FLAG_LOOP_FILTER + gray = lib.AV_CODEC_FLAG_GRAY + psnr = lib.AV_CODEC_FLAG_PSNR + interlaced_dct = lib.AV_CODEC_FLAG_INTERLACED_DCT + low_delay = lib.AV_CODEC_FLAG_LOW_DELAY + global_header = lib.AV_CODEC_FLAG_GLOBAL_HEADER + bitexact = lib.AV_CODEC_FLAG_BITEXACT + ac_pred = lib.AV_CODEC_FLAG_AC_PRED + interlaced_me = lib.AV_CODEC_FLAG_INTERLACED_ME + closed_gop = lib.AV_CODEC_FLAG_CLOSED_GOP + +class Flags2(IntEnum): + fast = lib.AV_CODEC_FLAG2_FAST + no_output = lib.AV_CODEC_FLAG2_NO_OUTPUT + local_header = lib.AV_CODEC_FLAG2_LOCAL_HEADER + chunks = lib.AV_CODEC_FLAG2_CHUNKS + ignore_crop = lib.AV_CODEC_FLAG2_IGNORE_CROP + show_all = lib.AV_CODEC_FLAG2_SHOW_ALL + export_mvs = lib.AV_CODEC_FLAG2_EXPORT_MVS + skip_manual = lib.AV_CODEC_FLAG2_SKIP_MANUAL + ro_flush_noop = lib.AV_CODEC_FLAG2_RO_FLUSH_NOOP + + +cdef class CodecContext: + @staticmethod + def create(codec, mode=None, hwaccel=None): + cdef Codec cy_codec = codec if isinstance(codec, Codec) else Codec(codec, mode) + cdef lib.AVCodecContext *c_ctx = lib.avcodec_alloc_context3(cy_codec.ptr) + return wrap_codec_context(c_ctx, cy_codec.ptr, hwaccel) + + def __cinit__(self, sentinel=None, *args, **kwargs): + if sentinel is not _cinit_sentinel: + raise RuntimeError("Cannot instantiate CodecContext") + + self.options = {} + self.stream_index = -1 # This is set by the container immediately. + self.is_open = False + + cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel): + self.ptr = ptr + if self.ptr.codec and codec and self.ptr.codec != codec: + raise RuntimeError("Wrapping CodecContext with mismatched codec.") + self.codec = wrap_codec(codec if codec != NULL else self.ptr.codec) + self.hwaccel = hwaccel + + # Set reasonable threading defaults. + self.ptr.thread_count = 0 # use as many threads as there are CPUs. + self.ptr.thread_type = 0x02 # thread within a frame. Does not change the API. + + @property + def flags(self): + """ + Get and set the flags bitmask of CodecContext. + + :rtype: int + """ + return self.ptr.flags + + @flags.setter + def flags(self, int value): + self.ptr.flags = value + + @property + def qscale(self): + """ + Use fixed qscale. + + :rtype: bool + """ + return bool(self.ptr.flags & lib.AV_CODEC_FLAG_QSCALE) + + @qscale.setter + def qscale(self, value): + if value: + self.ptr.flags |= lib.AV_CODEC_FLAG_QSCALE + else: + self.ptr.flags &= ~lib.AV_CODEC_FLAG_QSCALE + + @property + def copy_opaque(self): + return bool(self.ptr.flags & lib.AV_CODEC_FLAG_COPY_OPAQUE) + + @copy_opaque.setter + def copy_opaque(self, value): + if value: + self.ptr.flags |= lib.AV_CODEC_FLAG_COPY_OPAQUE + else: + self.ptr.flags &= ~lib.AV_CODEC_FLAG_COPY_OPAQUE + + @property + def flags2(self): + """ + Get and set the flags2 bitmask of CodecContext. + + :rtype: int + """ + return self.ptr.flags2 + + @flags2.setter + def flags2(self, int value): + self.ptr.flags2 = value + + @property + def extradata(self): + if self.ptr is NULL: + return None + if self.ptr.extradata_size > 0: + return (self.ptr.extradata)[:self.ptr.extradata_size] + return None + + @extradata.setter + def extradata(self, data): + if data is None: + lib.av_freep(&self.ptr.extradata) + self.ptr.extradata_size = 0 + else: + source = bytesource(data) + self.ptr.extradata = lib.av_realloc(self.ptr.extradata, source.length + lib.AV_INPUT_BUFFER_PADDING_SIZE) + if not self.ptr.extradata: + raise MemoryError("Cannot allocate extradata") + memcpy(self.ptr.extradata, source.ptr, source.length) + self.ptr.extradata_size = source.length + self.extradata_set = True + + @property + def extradata_size(self): + return self.ptr.extradata_size + + @property + def is_encoder(self): + if self.ptr is NULL: + return False + return lib.av_codec_is_encoder(self.ptr.codec) + + @property + def is_decoder(self): + if self.ptr is NULL: + return False + return lib.av_codec_is_decoder(self.ptr.codec) + + cpdef open(self, bint strict=True): + if self.is_open: + if strict: + raise ValueError("CodecContext is already open.") + return + + cdef _Dictionary options = Dictionary() + options.update(self.options or {}) + + if not self.ptr.time_base.num and self.is_encoder: + if self.type == "video": + self.ptr.time_base.num = self.ptr.framerate.den or 1 + self.ptr.time_base.den = self.ptr.framerate.num or lib.AV_TIME_BASE + elif self.type == "audio": + self.ptr.time_base.num = 1 + self.ptr.time_base.den = self.ptr.sample_rate + else: + self.ptr.time_base.num = 1 + self.ptr.time_base.den = lib.AV_TIME_BASE + + err_check(lib.avcodec_open2(self.ptr, self.codec.ptr, &options.ptr), "avcodec_open2(" + self.codec.name + ")") + self.is_open = True + self.options = dict(options) + + def __dealloc__(self): + if self.ptr and self.extradata_set: + lib.av_freep(&self.ptr.extradata) + if self.ptr: + lib.avcodec_free_context(&self.ptr) + if self.parser: + lib.av_parser_close(self.parser) + + def __repr__(self): + _type = self.type or "" + name = self.name or "" + return f"" + + def parse(self, raw_input=None): + """Split up a byte stream into list of :class:`.Packet`. + + This is only effectively splitting up a byte stream, and does no + actual interpretation of the data. + + It will return all packets that are fully contained within the given + input, and will buffer partial packets until they are complete. + + :param ByteSource raw_input: A chunk of a byte-stream to process. + Anything that can be turned into a :class:`.ByteSource` is fine. + ``None`` or empty inputs will flush the parser's buffers. + + :return: ``list`` of :class:`.Packet` newly available. + + """ + + if not self.parser: + self.parser = lib.av_parser_init(self.codec.ptr.id) + if not self.parser: + raise ValueError(f"No parser for {self.codec.name}") + + cdef ByteSource source = bytesource(raw_input, allow_none=True) + + cdef unsigned char *in_data = source.ptr if source is not None else NULL + cdef int in_size = source.length if source is not None else 0 + + cdef unsigned char *out_data + cdef int out_size + cdef int consumed + cdef Packet packet = None + + packets = [] + + while True: + with nogil: + consumed = lib.av_parser_parse2( + self.parser, + self.ptr, + &out_data, &out_size, + in_data, in_size, + lib.AV_NOPTS_VALUE, lib.AV_NOPTS_VALUE, + 0 + ) + err_check(consumed) + + if out_size: + # We copy the data immediately, as we have yet to figure out + # the expected lifetime of the buffer we get back. All of the + # examples decode it immediately. + # + # We've also tried: + # packet = Packet() + # packet.data = out_data + # packet.size = out_size + # packet.source = source + # + # ... but this results in corruption. + + packet = Packet(out_size) + memcpy(packet.ptr.data, out_data, out_size) + + packets.append(packet) + + if not in_size: + # This was a flush. Only one packet should ever be returned. + break + + in_data += consumed + in_size -= consumed + + if not in_size: + break + + return packets + + @property + def is_hwaccel(self): + """ + Returns ``True`` if this codec context is hardware accelerated, ``False`` otherwise. + """ + return self.hwaccel_ctx is not None + + def _send_frame_and_recv(self, Frame frame): + cdef Packet packet + + cdef int res + with nogil: + res = lib.avcodec_send_frame(self.ptr, frame.ptr if frame is not None else NULL) + err_check(res, "avcodec_send_frame()") + + packet = self._recv_packet() + while packet: + yield packet + packet = self._recv_packet() + + cdef _send_packet_and_recv(self, Packet packet): + cdef Frame frame + + cdef int res + with nogil: + res = lib.avcodec_send_packet(self.ptr, packet.ptr if packet is not None else NULL) + err_check(res, "avcodec_send_packet()") + + out = [] + while True: + frame = self._recv_frame() + if frame: + out.append(frame) + else: + break + return out + + cdef _prepare_frames_for_encode(self, Frame frame): + return [frame] + + cdef Frame _alloc_next_frame(self): + raise NotImplementedError("Base CodecContext cannot decode.") + + cdef _recv_frame(self): + if not self._next_frame: + self._next_frame = self._alloc_next_frame() + cdef Frame frame = self._next_frame + + cdef int res + with nogil: + res = lib.avcodec_receive_frame(self.ptr, frame.ptr) + + if res == -EAGAIN or res == lib.AVERROR_EOF: + return + err_check(res, "avcodec_receive_frame()") + + frame = self._transfer_hwframe(frame) + + if not res: + self._next_frame = None + return frame + + cdef _transfer_hwframe(self, Frame frame): + return frame + + cdef _recv_packet(self): + cdef Packet packet = Packet() + + cdef int res + with nogil: + res = lib.avcodec_receive_packet(self.ptr, packet.ptr) + if res == -EAGAIN or res == lib.AVERROR_EOF: + return + err_check(res, "avcodec_receive_packet()") + + if not res: + return packet + + cdef _prepare_and_time_rebase_frames_for_encode(self, Frame frame): + if self.ptr.codec_type not in [lib.AVMEDIA_TYPE_VIDEO, lib.AVMEDIA_TYPE_AUDIO]: + raise NotImplementedError("Encoding is only supported for audio and video.") + + self.open(strict=False) + + frames = self._prepare_frames_for_encode(frame) + + # Assert the frames are in our time base. + # TODO: Don't mutate time. + for frame in frames: + if frame is not None: + frame._rebase_time(self.ptr.time_base) + + return frames + + cpdef encode(self, Frame frame=None): + """Encode a list of :class:`.Packet` from the given :class:`.Frame`.""" + res = [] + for frame in self._prepare_and_time_rebase_frames_for_encode(frame): + for packet in self._send_frame_and_recv(frame): + self._setup_encoded_packet(packet) + res.append(packet) + return res + + def encode_lazy(self, Frame frame=None): + for frame in self._prepare_and_time_rebase_frames_for_encode(frame): + for packet in self._send_frame_and_recv(frame): + self._setup_encoded_packet(packet) + yield packet + + cdef _setup_encoded_packet(self, Packet packet): + # We coerced the frame's time_base into the CodecContext's during encoding, + # and FFmpeg copied the frame's pts/dts to the packet, so keep track of + # this time_base in case the frame needs to be muxed to a container with + # a different time_base. + # + # NOTE: if the CodecContext's time_base is altered during encoding, all bets + # are off! + packet._time_base = self.ptr.time_base + + cpdef decode(self, Packet packet=None): + """Decode a list of :class:`.Frame` from the given :class:`.Packet`. + + If the packet is None, the buffers will be flushed. This is useful if + you do not want the library to automatically re-order frames for you + (if they are encoded with a codec that has B-frames). + + """ + + if not self.codec.ptr: + raise ValueError("cannot decode unknown codec") + + self.open(strict=False) + + res = [] + for frame in self._send_packet_and_recv(packet): + if isinstance(frame, Frame): + self._setup_decoded_frame(frame, packet) + res.append(frame) + return res + + cpdef flush_buffers(self): + """Reset the internal codec state and discard all internal buffers. + + Should be called before you start decoding from a new position e.g. + when seeking or when switching to a different stream. + + """ + if self.is_open: + with nogil: + lib.avcodec_flush_buffers(self.ptr) + + cdef _setup_decoded_frame(self, Frame frame, Packet packet): + # Propagate our manual times. + # While decoding, frame times are in stream time_base, which PyAV + # is carrying around. + # TODO: Somehow get this from the stream so we can not pass the + # packet here (because flushing packets are bogus). + if packet is not None: + frame._time_base = packet._time_base + + @property + def name(self): + return self.codec.name + + @property + def type(self): + return self.codec.type + + @property + def profiles(self): + """ + List the available profiles for this stream. + + :type: list[str] + """ + ret = [] + if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles: + return ret + + # Profiles are always listed in the codec descriptor, but not necessarily in + # the codec itself. So use the descriptor here. + desc = self.codec.desc + cdef int i = 0 + while desc.profiles[i].profile != lib.FF_PROFILE_UNKNOWN: + ret.append(desc.profiles[i].name) + i += 1 + + return ret + + @property + def profile(self): + if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles: + return + + # Profiles are always listed in the codec descriptor, but not necessarily in + # the codec itself. So use the descriptor here. + desc = self.codec.desc + cdef int i = 0 + while desc.profiles[i].profile != lib.FF_PROFILE_UNKNOWN: + if desc.profiles[i].profile == self.ptr.profile: + return desc.profiles[i].name + i += 1 + + @profile.setter + def profile(self, value): + if not self.codec or not self.codec.desc or not self.codec.desc.profiles: + return + + # Profiles are always listed in the codec descriptor, but not necessarily in + # the codec itself. So use the descriptor here. + desc = self.codec.desc + cdef int i = 0 + while desc.profiles[i].profile != lib.FF_PROFILE_UNKNOWN: + if desc.profiles[i].name == value: + self.ptr.profile = desc.profiles[i].profile + return + i += 1 + + @property + def time_base(self): + if self.is_decoder: + raise RuntimeError("Cannot access 'time_base' as a decoder") + return avrational_to_fraction(&self.ptr.time_base) + + @time_base.setter + def time_base(self, value): + if self.is_decoder: + raise RuntimeError("Cannot access 'time_base' as a decoder") + to_avrational(value, &self.ptr.time_base) + + @property + def codec_tag(self): + return self.ptr.codec_tag.to_bytes(4, byteorder="little", signed=False).decode( + encoding="ascii") + + @codec_tag.setter + def codec_tag(self, value): + if isinstance(value, str) and len(value) == 4: + self.ptr.codec_tag = int.from_bytes(value.encode(encoding="ascii"), + byteorder="little", signed=False) + else: + raise ValueError("Codec tag should be a 4 character string.") + + @property + def bit_rate(self): + return self.ptr.bit_rate if self.ptr.bit_rate > 0 else None + + @bit_rate.setter + def bit_rate(self, int value): + self.ptr.bit_rate = value + + @property + def max_bit_rate(self): + if self.ptr.rc_max_rate > 0: + return self.ptr.rc_max_rate + else: + return None + + @property + def bit_rate_tolerance(self): + self.ptr.bit_rate_tolerance + + @bit_rate_tolerance.setter + def bit_rate_tolerance(self, int value): + self.ptr.bit_rate_tolerance = value + + @property + def thread_count(self): + """How many threads to use; 0 means auto. + + Wraps :ffmpeg:`AVCodecContext.thread_count`. + + """ + return self.ptr.thread_count + + @thread_count.setter + def thread_count(self, int value): + if self.is_open: + raise RuntimeError("Cannot change thread_count after codec is open.") + self.ptr.thread_count = value + + @property + def thread_type(self): + """One of :class:`.ThreadType`. + + Wraps :ffmpeg:`AVCodecContext.thread_type`. + + """ + return ThreadType(self.ptr.thread_type) + + @thread_type.setter + def thread_type(self, value): + if self.is_open: + raise RuntimeError("Cannot change thread_type after codec is open.") + if type(value) is int: + self.ptr.thread_type = value + elif type(value) is str: + self.ptr.thread_type = ThreadType[value].value + else: + self.ptr.thread_type = value.value + + @property + def skip_frame(self): + """Returns one of the following str literals: + + "NONE" Discard nothing + "DEFAULT" Discard useless packets like 0 size packets in AVI + "NONREF" Discard all non reference + "BIDIR" Discard all bidirectional frames + "NONINTRA" Discard all non intra frames + "NONKEY Discard all frames except keyframes + "ALL" Discard all + + Wraps :ffmpeg:`AVCodecContext.skip_frame`. + """ + value = self.ptr.skip_frame + if value == lib.AVDISCARD_NONE: + return "NONE" + if value == lib.AVDISCARD_DEFAULT: + return "DEFAULT" + if value == lib.AVDISCARD_NONREF: + return "NONREF" + if value == lib.AVDISCARD_BIDIR: + return "BIDIR" + if value == lib.AVDISCARD_NONINTRA: + return "NONINTRA" + if value == lib.AVDISCARD_NONKEY: + return "NONKEY" + if value == lib.AVDISCARD_ALL: + return "ALL" + return f"{value}" + + @skip_frame.setter + def skip_frame(self, value): + if value == "NONE": + self.ptr.skip_frame = lib.AVDISCARD_NONE + elif value == "DEFAULT": + self.ptr.skip_frame = lib.AVDISCARD_DEFAULT + elif value == "NONREF": + self.ptr.skip_frame = lib.AVDISCARD_NONREF + elif value == "BIDIR": + self.ptr.skip_frame = lib.AVDISCARD_BIDIR + elif value == "NONINTRA": + self.ptr.skip_frame = lib.AVDISCARD_NONINTRA + elif value == "NONKEY": + self.ptr.skip_frame = lib.AVDISCARD_NONKEY + elif value == "ALL": + self.ptr.skip_frame = lib.AVDISCARD_ALL + else: + raise ValueError("Invalid skip_frame type") + + @property + def delay(self): + """Codec delay. + + Wraps :ffmpeg:`AVCodecContext.delay`. + + """ + return self.ptr.delay diff --git a/lib/python3.10/site-packages/av/codec/hwaccel.pyx b/lib/python3.10/site-packages/av/codec/hwaccel.pyx new file mode 100644 index 0000000000000000000000000000000000000000..257e6e7b2d07d1d1358f418ee843e8329291b4b6 --- /dev/null +++ b/lib/python3.10/site-packages/av/codec/hwaccel.pyx @@ -0,0 +1,156 @@ +import weakref +from enum import IntEnum + +cimport libav as lib + +from av.codec.codec cimport Codec +from av.dictionary cimport _Dictionary +from av.error cimport err_check +from av.video.format cimport get_video_format + +from av.dictionary import Dictionary + + +class HWDeviceType(IntEnum): + none = lib.AV_HWDEVICE_TYPE_NONE + vdpau = lib.AV_HWDEVICE_TYPE_VDPAU + cuda = lib.AV_HWDEVICE_TYPE_CUDA + vaapi = lib.AV_HWDEVICE_TYPE_VAAPI + dxva2 = lib.AV_HWDEVICE_TYPE_DXVA2 + qsv = lib.AV_HWDEVICE_TYPE_QSV + videotoolbox = lib.AV_HWDEVICE_TYPE_VIDEOTOOLBOX + d3d11va = lib.AV_HWDEVICE_TYPE_D3D11VA + drm = lib.AV_HWDEVICE_TYPE_DRM + opencl = lib.AV_HWDEVICE_TYPE_OPENCL + mediacodec = lib.AV_HWDEVICE_TYPE_MEDIACODEC + vulkan = lib.AV_HWDEVICE_TYPE_VULKAN + d3d12va = lib.AV_HWDEVICE_TYPE_D3D12VA + +class HWConfigMethod(IntEnum): + none = 0 + hw_device_ctx = lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX # This is the only one we support. + hw_frame_ctx = lib.AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX + internal = lib.AV_CODEC_HW_CONFIG_METHOD_INTERNAL + ad_hoc = lib.AV_CODEC_HW_CONFIG_METHOD_AD_HOC + + +cdef object _cinit_sentinel = object() +cdef object _singletons = weakref.WeakValueDictionary() + +cdef HWConfig wrap_hwconfig(lib.AVCodecHWConfig *ptr): + try: + return _singletons[ptr] + except KeyError: + pass + cdef HWConfig config = HWConfig(_cinit_sentinel) + config._init(ptr) + _singletons[ptr] = config + return config + + +cdef class HWConfig: + def __init__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("Cannot instantiate CodecContext") + + cdef void _init(self, lib.AVCodecHWConfig *ptr): + self.ptr = ptr + + def __repr__(self): + return ( + f"self.ptr:x}>" + ) + + @property + def device_type(self): + return HWDeviceType(self.ptr.device_type) + + @property + def format(self): + return get_video_format(self.ptr.pix_fmt, 0, 0) + + @property + def methods(self): + return HWConfigMethod(self.ptr.methods) + + @property + def is_supported(self): + return bool(self.ptr.methods & lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) + + +cpdef hwdevices_available(): + result = [] + + cdef lib.AVHWDeviceType x = lib.AV_HWDEVICE_TYPE_NONE + while True: + x = lib.av_hwdevice_iterate_types(x) + if x == lib.AV_HWDEVICE_TYPE_NONE: + break + result.append(lib.av_hwdevice_get_type_name(HWDeviceType(x))) + + return result + + +cdef class HWAccel: + def __init__(self, device_type, device=None, allow_software_fallback=True, options=None, flags=None): + if isinstance(device_type, HWDeviceType): + self._device_type = device_type + elif isinstance(device_type, str): + self._device_type = int(lib.av_hwdevice_find_type_by_name(device_type)) + elif isinstance(device_type, int): + self._device_type = device_type + else: + raise ValueError("Unknown type for device_type") + + self._device = device + self.allow_software_fallback = allow_software_fallback + self.options = {} if not options else dict(options) + self.flags = 0 if not flags else flags + self.ptr = NULL + self.config = None + + def _initialize_hw_context(self, Codec codec not None): + cdef HWConfig config + for config in codec.hardware_configs: + if not (config.ptr.methods & lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX): + continue + if self._device_type and config.device_type != self._device_type: + continue + break + else: + raise NotImplementedError(f"No supported hardware config for {codec}") + + self.config = config + + cdef char *c_device = NULL + if self._device: + device_bytes = self._device.encode() + c_device = device_bytes + cdef _Dictionary c_options = Dictionary(self.options) + + err_check( + lib.av_hwdevice_ctx_create( + &self.ptr, config.ptr.device_type, c_device, c_options.ptr, self.flags + ) + ) + + def create(self, Codec codec not None): + """Create a new hardware accelerator context with the given codec""" + if self.ptr: + raise RuntimeError("Hardware context already initialized") + + ret = HWAccel( + device_type=self._device_type, + device=self._device, + allow_software_fallback=self.allow_software_fallback, + options=self.options + ) + ret._initialize_hw_context(codec) + return ret + + def __dealloc__(self): + if self.ptr: + lib.av_buffer_unref(&self.ptr) diff --git a/lib/python3.10/site-packages/av/filter/__init__.py b/lib/python3.10/site-packages/av/filter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd4430d474e27d1714b54a0f218709993def47c --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/__init__.py @@ -0,0 +1,3 @@ +from .filter import Filter, FilterFlags, filter_descriptor, filters_available +from .graph import Graph +from .loudnorm import stats diff --git a/lib/python3.10/site-packages/av/filter/__init__.pyi b/lib/python3.10/site-packages/av/filter/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5be1326c99efab97108a8dba6887cda669b6996a --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/__init__.pyi @@ -0,0 +1,4 @@ +from .context import * +from .filter import * +from .graph import * +from .loudnorm import * diff --git a/lib/python3.10/site-packages/av/filter/context.pyi b/lib/python3.10/site-packages/av/filter/context.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7c00087a928d37033f1e20a3692c0ede9276dfaa --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/context.pyi @@ -0,0 +1,18 @@ +from av.filter import Graph +from av.frame import Frame + +from .pad import FilterContextPad + +class FilterContext: + name: str | None + inputs: tuple[FilterContextPad, ...] + outputs: tuple[FilterContextPad, ...] + + def init(self, args: str | None = None, **kwargs: str | None) -> None: ... + def link_to( + self, input_: FilterContext, output_idx: int = 0, input_idx: int = 0 + ) -> None: ... + @property + def graph(self) -> Graph: ... + def push(self, frame: Frame) -> None: ... + def pull(self) -> Frame: ... diff --git a/lib/python3.10/site-packages/av/filter/context.pyx b/lib/python3.10/site-packages/av/filter/context.pyx new file mode 100644 index 0000000000000000000000000000000000000000..b820d3d1829ac4c8edb2b1b468d3b1dc76c16eeb --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/context.pyx @@ -0,0 +1,134 @@ +import weakref + +from av.audio.frame cimport alloc_audio_frame +from av.dictionary cimport _Dictionary +from av.dictionary import Dictionary +from av.error cimport err_check +from av.filter.pad cimport alloc_filter_pads +from av.frame cimport Frame +from av.utils cimport avrational_to_fraction +from av.video.frame cimport alloc_video_frame + + +cdef object _cinit_sentinel = object() + + +cdef FilterContext wrap_filter_context(Graph graph, Filter filter, lib.AVFilterContext *ptr): + cdef FilterContext self = FilterContext(_cinit_sentinel) + self._graph = weakref.ref(graph) + self.filter = filter + self.ptr = ptr + return self + + +cdef class FilterContext: + def __cinit__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot construct FilterContext") + + def __repr__(self): + if self.ptr != NULL: + name = repr(self.ptr.name) if self.ptr.name != NULL else "" + else: + name = "None" + + parent = self.filter.ptr.name if self.filter and self.filter.ptr != NULL else None + return f"" + + @property + def name(self): + if self.ptr.name != NULL: + return self.ptr.name + + @property + def inputs(self): + if self._inputs is None: + self._inputs = alloc_filter_pads(self.filter, self.ptr.input_pads, True, self) + return self._inputs + + @property + def outputs(self): + if self._outputs is None: + self._outputs = alloc_filter_pads(self.filter, self.ptr.output_pads, False, self) + return self._outputs + + def init(self, args=None, **kwargs): + if self.inited: + raise ValueError("already inited") + if args and kwargs: + raise ValueError("cannot init from args and kwargs") + + cdef _Dictionary dict_ = None + cdef char *c_args = NULL + if args or not kwargs: + if args: + c_args = args + err_check(lib.avfilter_init_str(self.ptr, c_args)) + else: + dict_ = Dictionary(kwargs) + err_check(lib.avfilter_init_dict(self.ptr, &dict_.ptr)) + + self.inited = True + if dict_: + raise ValueError(f"unused config: {', '.join(sorted(dict_))}") + + def link_to(self, FilterContext input_, int output_idx=0, int input_idx=0): + err_check(lib.avfilter_link(self.ptr, output_idx, input_.ptr, input_idx)) + + @property + def graph(self): + if (graph := self._graph()): + return graph + else: + raise RuntimeError("graph is unallocated") + + def push(self, Frame frame): + cdef int res + + if frame is None: + with nogil: + res = lib.av_buffersrc_write_frame(self.ptr, NULL) + err_check(res) + return + elif self.filter.name in ("abuffer", "buffer"): + with nogil: + res = lib.av_buffersrc_write_frame(self.ptr, frame.ptr) + err_check(res) + return + + # Delegate to the input. + if len(self.inputs) != 1: + raise ValueError( + f"cannot delegate push without single input; found {len(self.inputs)}" + ) + if not self.inputs[0].link: + raise ValueError("cannot delegate push without linked input") + self.inputs[0].linked.context.push(frame) + + def pull(self): + cdef Frame frame + cdef int res + + if self.filter.name == "buffersink": + frame = alloc_video_frame() + elif self.filter.name == "abuffersink": + frame = alloc_audio_frame() + else: + # Delegate to the output. + if len(self.outputs) != 1: + raise ValueError( + f"cannot delegate pull without single output; found {len(self.outputs)}" + ) + if not self.outputs[0].link: + raise ValueError("cannot delegate pull without linked output") + return self.outputs[0].linked.context.pull() + + self.graph.configure() + + with nogil: + res = lib.av_buffersink_get_frame(self.ptr, frame.ptr) + err_check(res) + + frame._init_user_attributes() + frame.time_base = avrational_to_fraction(&self.ptr.inputs[0].time_base) + return frame diff --git a/lib/python3.10/site-packages/av/filter/filter.pxd b/lib/python3.10/site-packages/av/filter/filter.pxd new file mode 100644 index 0000000000000000000000000000000000000000..27501ae575f7ed16741cee1ab497eb8a7c4a5bb7 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/filter.pxd @@ -0,0 +1,15 @@ +cimport libav as lib + +from av.descriptor cimport Descriptor + + +cdef class Filter: + + cdef const lib.AVFilter *ptr + + cdef object _inputs + cdef object _outputs + cdef Descriptor _descriptor + + +cdef Filter wrap_filter(const lib.AVFilter *ptr) diff --git a/lib/python3.10/site-packages/av/filter/filter.pyi b/lib/python3.10/site-packages/av/filter/filter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2751e973cf5a8350a5f266604b65270ab6045324 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/filter.pyi @@ -0,0 +1,23 @@ +from av.descriptor import Descriptor +from av.option import Option + +from .pad import FilterPad + +class Filter: + name: str + description: str + + descriptor: Descriptor + options: tuple[Option, ...] | None + flags: int + dynamic_inputs: bool + dynamic_outputs: bool + timeline_support: bool + slice_threads: bool + command_support: bool + inputs: tuple[FilterPad, ...] + outputs: tuple[FilterPad, ...] + + def __init__(self, name: str) -> None: ... + +filters_available: set[str] diff --git a/lib/python3.10/site-packages/av/filter/filter.pyx b/lib/python3.10/site-packages/av/filter/filter.pyx new file mode 100644 index 0000000000000000000000000000000000000000..d4880dc156e40bd8200ab2e54dd6be72d940106f --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/filter.pyx @@ -0,0 +1,106 @@ +cimport libav as lib + +from av.descriptor cimport wrap_avclass +from av.filter.pad cimport alloc_filter_pads + + +cdef object _cinit_sentinel = object() + + +cdef Filter wrap_filter(const lib.AVFilter *ptr): + cdef Filter filter_ = Filter(_cinit_sentinel) + filter_.ptr = ptr + return filter_ + + +cpdef enum FilterFlags: + DYNAMIC_INPUTS = lib.AVFILTER_FLAG_DYNAMIC_INPUTS + DYNAMIC_OUTPUTS = lib.AVFILTER_FLAG_DYNAMIC_OUTPUTS + SLICE_THREADS = lib.AVFILTER_FLAG_SLICE_THREADS + SUPPORT_TIMELINE_GENERIC = lib.AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC + SUPPORT_TIMELINE_INTERNAL = lib.AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL + + +cdef class Filter: + def __cinit__(self, name): + if name is _cinit_sentinel: + return + if not isinstance(name, str): + raise TypeError("takes a filter name as a string") + self.ptr = lib.avfilter_get_by_name(name) + if not self.ptr: + raise ValueError(f"no filter {name}") + + @property + def descriptor(self): + if self._descriptor is None: + self._descriptor = wrap_avclass(self.ptr.priv_class) + return self._descriptor + + @property + def options(self): + if self.descriptor is None: + return + return self.descriptor.options + + @property + def name(self): + return self.ptr.name + + @property + def description(self): + return self.ptr.description + + @property + def flags(self): + return self.ptr.flags + + @property + def dynamic_inputs(self): + return bool(self.ptr.flags & lib.AVFILTER_FLAG_DYNAMIC_INPUTS) + + @property + def dynamic_outputs(self): + return bool(self.ptr.flags & lib.AVFILTER_FLAG_DYNAMIC_OUTPUTS) + + @property + def timeline_support(self): + return bool(self.ptr.flags & lib.AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC) + + @property + def slice_threads(self): + return bool(self.ptr.flags & lib.AVFILTER_FLAG_SLICE_THREADS) + + @property + def command_support(self): + return self.ptr.process_command != NULL + + @property + def inputs(self): + if self._inputs is None: + self._inputs = alloc_filter_pads(self, self.ptr.inputs, True) + return self._inputs + + @property + def outputs(self): + if self._outputs is None: + self._outputs = alloc_filter_pads(self, self.ptr.outputs, False) + return self._outputs + + +cdef get_filter_names(): + names = set() + cdef const lib.AVFilter *ptr + cdef void *opaque = NULL + while True: + ptr = lib.av_filter_iterate(&opaque) + if ptr: + names.add(ptr.name) + else: + break + return names + +filters_available = get_filter_names() + + +filter_descriptor = wrap_avclass(lib.avfilter_get_class()) diff --git a/lib/python3.10/site-packages/av/filter/graph.pxd b/lib/python3.10/site-packages/av/filter/graph.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2e52bd6ec3a67992dc0f2a40bbd5da8e5ed41fda --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/graph.pxd @@ -0,0 +1,22 @@ +cimport libav as lib + +from av.filter.context cimport FilterContext + + +cdef class Graph: + cdef object __weakref__ + + cdef lib.AVFilterGraph *ptr + + cdef readonly bint configured + cpdef configure(self, bint auto_buffer=*, bint force=*) + + cdef dict _name_counts + cdef str _get_unique_name(self, str name) + + cdef _register_context(self, FilterContext) + cdef _auto_register(self) + cdef int _nb_filters_seen + cdef dict _context_by_ptr + cdef dict _context_by_name + cdef dict _context_by_type diff --git a/lib/python3.10/site-packages/av/filter/graph.pyi b/lib/python3.10/site-packages/av/filter/graph.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e170c2ce77da8ba8fa81561c24285886200d3d0d --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/graph.pyi @@ -0,0 +1,47 @@ +from fractions import Fraction +from typing import Any + +from av.audio.format import AudioFormat +from av.audio.frame import AudioFrame +from av.audio.layout import AudioLayout +from av.audio.stream import AudioStream +from av.video.format import VideoFormat +from av.video.frame import VideoFrame +from av.video.stream import VideoStream + +from .context import FilterContext +from .filter import Filter + +class Graph: + configured: bool + + def __init__(self) -> None: ... + def configure(self, auto_buffer: bool = True, force: bool = False) -> None: ... + def link_nodes(self, *nodes: FilterContext) -> Graph: ... + def add( + self, filter: str | Filter, args: Any = None, **kwargs: str + ) -> FilterContext: ... + def add_buffer( + self, + template: VideoStream | None = None, + width: int | None = None, + height: int | None = None, + format: VideoFormat | None = None, + name: str | None = None, + time_base: Fraction | None = None, + ) -> FilterContext: ... + def add_abuffer( + self, + template: AudioStream | None = None, + sample_rate: int | None = None, + format: AudioFormat | str | None = None, + layout: AudioLayout | str | None = None, + channels: int | None = None, + name: str | None = None, + time_base: Fraction | None = None, + ) -> FilterContext: ... + def set_audio_frame_size(self, frame_size: int) -> None: ... + def push(self, frame: None | AudioFrame | VideoFrame) -> None: ... + def pull(self) -> VideoFrame | AudioFrame: ... + def vpush(self, frame: VideoFrame | None) -> None: ... + def vpull(self) -> VideoFrame: ... diff --git a/lib/python3.10/site-packages/av/filter/graph.pyx b/lib/python3.10/site-packages/av/filter/graph.pyx new file mode 100644 index 0000000000000000000000000000000000000000..c1a2d7a0646146a8fe9300d5a779792d42658fc9 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/graph.pyx @@ -0,0 +1,224 @@ +import warnings +from fractions import Fraction + +from av.audio.format cimport AudioFormat +from av.audio.frame cimport AudioFrame +from av.audio.layout cimport AudioLayout +from av.error cimport err_check +from av.filter.context cimport FilterContext, wrap_filter_context +from av.filter.filter cimport Filter, wrap_filter +from av.video.format cimport VideoFormat +from av.video.frame cimport VideoFrame + + +cdef class Graph: + def __cinit__(self): + self.ptr = lib.avfilter_graph_alloc() + self.configured = False + self._name_counts = {} + + self._nb_filters_seen = 0 + self._context_by_ptr = {} + self._context_by_name = {} + self._context_by_type = {} + + def __dealloc__(self): + if self.ptr: + # This frees the graph, filter contexts, links, etc.. + lib.avfilter_graph_free(&self.ptr) + + cdef str _get_unique_name(self, str name): + count = self._name_counts.get(name, 0) + self._name_counts[name] = count + 1 + if count: + return "%s_%s" % (name, count) + else: + return name + + cpdef configure(self, bint auto_buffer=True, bint force=False): + if self.configured and not force: + return + + err_check(lib.avfilter_graph_config(self.ptr, NULL)) + self.configured = True + + # We get auto-inserted stuff here. + self._auto_register() + + def link_nodes(self, *nodes): + """ + Links nodes together for simple filter graphs. + """ + for c, n in zip(nodes, nodes[1:]): + c.link_to(n) + return self + + def add(self, filter, args=None, **kwargs): + cdef Filter cy_filter + if isinstance(filter, str): + cy_filter = Filter(filter) + elif isinstance(filter, Filter): + cy_filter = filter + else: + raise TypeError("filter must be a string or Filter") + + cdef str name = self._get_unique_name(kwargs.pop("name", None) or cy_filter.name) + + cdef lib.AVFilterContext *ptr = lib.avfilter_graph_alloc_filter(self.ptr, cy_filter.ptr, name) + if not ptr: + raise RuntimeError("Could not allocate AVFilterContext") + + # Manually construct this context (so we can return it). + cdef FilterContext ctx = wrap_filter_context(self, cy_filter, ptr) + ctx.init(args, **kwargs) + self._register_context(ctx) + + # There might have been automatic contexts added (e.g. resamplers, + # fifos, and scalers). It is more likely to see them after the graph + # is configured, but we want to be safe. + self._auto_register() + + return ctx + + cdef _register_context(self, FilterContext ctx): + self._context_by_ptr[ctx.ptr] = ctx + self._context_by_name[ctx.ptr.name] = ctx + self._context_by_type.setdefault(ctx.filter.ptr.name, []).append(ctx) + + cdef _auto_register(self): + cdef int i + cdef lib.AVFilterContext *c_ctx + cdef Filter filter_ + cdef FilterContext py_ctx + # We assume that filters are never removed from the graph. At this + # point we don't expose that in the API, so we should be okay... + for i in range(self._nb_filters_seen, self.ptr.nb_filters): + c_ctx = self.ptr.filters[i] + if c_ctx in self._context_by_ptr: + continue + filter_ = wrap_filter(c_ctx.filter) + py_ctx = wrap_filter_context(self, filter_, c_ctx) + self._register_context(py_ctx) + self._nb_filters_seen = self.ptr.nb_filters + + def add_buffer(self, template=None, width=None, height=None, format=None, name=None, time_base=None): + if template is not None: + if width is None: + width = template.width + if height is None: + height = template.height + if format is None: + format = template.format + if time_base is None: + time_base = template.time_base + + if width is None: + raise ValueError("missing width") + if height is None: + raise ValueError("missing height") + if format is None: + raise ValueError("missing format") + if time_base is None: + warnings.warn("missing time_base. Guessing 1/1000 time base. " + "This is deprecated and may be removed in future releases.", + DeprecationWarning) + time_base = Fraction(1, 1000) + + return self.add( + "buffer", + name=name, + video_size=f"{width}x{height}", + pix_fmt=str(int(VideoFormat(format))), + time_base=str(time_base), + pixel_aspect="1/1", + ) + + def add_abuffer(self, template=None, sample_rate=None, format=None, layout=None, channels=None, name=None, time_base=None): + """ + Convenience method for adding `abuffer `_. + """ + + if template is not None: + if sample_rate is None: + sample_rate = template.sample_rate + if format is None: + format = template.format + if layout is None: + layout = template.layout.name + if channels is None: + channels = template.channels + if time_base is None: + time_base = template.time_base + + if sample_rate is None: + raise ValueError("missing sample_rate") + if format is None: + raise ValueError("missing format") + if layout is None and channels is None: + raise ValueError("missing layout or channels") + if time_base is None: + time_base = Fraction(1, sample_rate) + + kwargs = dict( + sample_rate=str(sample_rate), + sample_fmt=AudioFormat(format).name, + time_base=str(time_base), + ) + if layout: + kwargs["channel_layout"] = AudioLayout(layout).name + if channels: + kwargs["channels"] = str(channels) + + return self.add("abuffer", name=name, **kwargs) + + def set_audio_frame_size(self, frame_size): + """ + Set the audio frame size for the graphs `abuffersink`. + See `av_buffersink_set_frame_size `_. + """ + if not self.configured: + raise ValueError("graph not configured") + sinks = self._context_by_type.get("abuffersink", []) + if not sinks: + raise ValueError("missing abuffersink filter") + for sink in sinks: + lib.av_buffersink_set_frame_size((sink).ptr, frame_size) + + def push(self, frame): + if frame is None: + contexts = self._context_by_type.get("buffer", []) + self._context_by_type.get("abuffer", []) + elif isinstance(frame, VideoFrame): + contexts = self._context_by_type.get("buffer", []) + elif isinstance(frame, AudioFrame): + contexts = self._context_by_type.get("abuffer", []) + else: + raise ValueError(f"can only AudioFrame, VideoFrame or None; got {type(frame)}") + + for ctx in contexts: + ctx.push(frame) + + def vpush(self, VideoFrame frame): + """Like `push`, but only for VideoFrames.""" + for ctx in self._context_by_type.get("buffer", []): + ctx.push(frame) + + + # TODO: Test complex filter graphs, add `at: int = 0` arg to pull() and vpull(). + def pull(self): + vsinks = self._context_by_type.get("buffersink", []) + asinks = self._context_by_type.get("abuffersink", []) + + nsinks = len(vsinks) + len(asinks) + if nsinks != 1: + raise ValueError(f"can only auto-pull with single sink; found {nsinks}") + + return (vsinks or asinks)[0].pull() + + def vpull(self): + """Like `pull`, but only for VideoFrames.""" + vsinks = self._context_by_type.get("buffersink", []) + nsinks = len(vsinks) + if nsinks != 1: + raise ValueError(f"can only auto-pull with single sink; found {nsinks}") + + return vsinks[0].pull() diff --git a/lib/python3.10/site-packages/av/filter/link.pxd b/lib/python3.10/site-packages/av/filter/link.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a6a4b1c092163e4739735026b6c26502003daa24 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/link.pxd @@ -0,0 +1,16 @@ +cimport libav as lib + +from av.filter.graph cimport Graph +from av.filter.pad cimport FilterContextPad + + +cdef class FilterLink: + + cdef readonly Graph graph + cdef lib.AVFilterLink *ptr + + cdef FilterContextPad _input + cdef FilterContextPad _output + + +cdef FilterLink wrap_filter_link(Graph graph, lib.AVFilterLink *ptr) diff --git a/lib/python3.10/site-packages/av/filter/link.pyi b/lib/python3.10/site-packages/av/filter/link.pyi new file mode 100644 index 0000000000000000000000000000000000000000..dd420ad91e94856492769f1efea588d2ee9e30ff --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/link.pyi @@ -0,0 +1,5 @@ +from .pad import FilterContextPad + +class FilterLink: + input: FilterContextPad + output: FilterContextPad diff --git a/lib/python3.10/site-packages/av/filter/link.pyx b/lib/python3.10/site-packages/av/filter/link.pyx new file mode 100644 index 0000000000000000000000000000000000000000..78b7da30f718227cce3a96bdc27177b9443106c9 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/link.pyx @@ -0,0 +1,53 @@ +cimport libav as lib + +from av.filter.graph cimport Graph + + +cdef _cinit_sentinel = object() + + +cdef class FilterLink: + + def __cinit__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot instantiate FilterLink") + + @property + def input(self): + if self._input: + return self._input + cdef lib.AVFilterContext *cctx = self.ptr.src + cdef unsigned int i + for i in range(cctx.nb_outputs): + if self.ptr == cctx.outputs[i]: + break + else: + raise RuntimeError("could not find link in context") + ctx = self.graph._context_by_ptr[cctx] + self._input = ctx.outputs[i] + return self._input + + @property + def output(self): + if self._output: + return self._output + cdef lib.AVFilterContext *cctx = self.ptr.dst + cdef unsigned int i + for i in range(cctx.nb_inputs): + if self.ptr == cctx.inputs[i]: + break + else: + raise RuntimeError("could not find link in context") + try: + ctx = self.graph._context_by_ptr[cctx] + except KeyError: + raise RuntimeError("could not find context in graph", (cctx.name, cctx.filter.name)) + self._output = ctx.inputs[i] + return self._output + + +cdef FilterLink wrap_filter_link(Graph graph, lib.AVFilterLink *ptr): + cdef FilterLink link = FilterLink(_cinit_sentinel) + link.graph = graph + link.ptr = ptr + return link diff --git a/lib/python3.10/site-packages/av/filter/loudnorm.pxd b/lib/python3.10/site-packages/av/filter/loudnorm.pxd new file mode 100644 index 0000000000000000000000000000000000000000..b08d3502fc9a3e39fd3273fb474fd8e974d65568 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/loudnorm.pxd @@ -0,0 +1,4 @@ +from av.audio.stream cimport AudioStream + + +cpdef bytes stats(str loudnorm_args, AudioStream stream) diff --git a/lib/python3.10/site-packages/av/filter/loudnorm.pyi b/lib/python3.10/site-packages/av/filter/loudnorm.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c680f638d43a8908438d81c56c07387524488412 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/loudnorm.pyi @@ -0,0 +1,3 @@ +from av.audio.stream import AudioStream + +def stats(loudnorm_args: str, stream: AudioStream) -> bytes: ... diff --git a/lib/python3.10/site-packages/av/filter/loudnorm.pyx b/lib/python3.10/site-packages/av/filter/loudnorm.pyx new file mode 100644 index 0000000000000000000000000000000000000000..78f320a9ecb77fa913f070e145fdfa79830015b1 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/loudnorm.pyx @@ -0,0 +1,69 @@ +# av/filter/loudnorm.pyx + +cimport libav as lib +from cpython.bytes cimport PyBytes_FromString +from libc.stdlib cimport free + +from av.audio.codeccontext cimport AudioCodecContext +from av.audio.stream cimport AudioStream +from av.container.core cimport Container +from av.stream cimport Stream +from av.logging import get_level, set_level + + +cdef extern from "libavcodec/avcodec.h": + ctypedef struct AVCodecContext: + pass + +cdef extern from "libavformat/avformat.h": + ctypedef struct AVFormatContext: + pass + +cdef extern from "loudnorm_impl.h": + char* loudnorm_get_stats( + AVFormatContext* fmt_ctx, + int audio_stream_index, + const char* loudnorm_args + ) nogil + + +cpdef bytes stats(str loudnorm_args, AudioStream stream): + """ + Get loudnorm statistics for an audio stream. + + Args: + loudnorm_args (str): Arguments for the loudnorm filter (e.g. "i=-24.0:lra=7.0:tp=-2.0") + stream (AudioStream): Input audio stream to analyze + + Returns: + bytes: JSON string containing the loudnorm statistics + """ + + if "print_format=json" not in loudnorm_args: + loudnorm_args = loudnorm_args + ":print_format=json" + + cdef Container container = stream.container + cdef AVFormatContext* format_ptr = container.ptr + + container.ptr = NULL # Prevent double-free + + cdef int stream_index = stream.index + cdef bytes py_args = loudnorm_args.encode("utf-8") + cdef const char* c_args = py_args + cdef char* result + + # Save log level since C function overwrite it. + level = get_level() + + with nogil: + result = loudnorm_get_stats(format_ptr, stream_index, c_args) + + if result == NULL: + raise RuntimeError("Failed to get loudnorm stats") + + py_result = result[:] # Make a copy of the string + free(result) # Free the C string + + set_level(level) + + return py_result diff --git a/lib/python3.10/site-packages/av/filter/loudnorm_impl.c b/lib/python3.10/site-packages/av/filter/loudnorm_impl.c new file mode 100644 index 0000000000000000000000000000000000000000..f6e22e4cebde12aa05cd8587ca4407ee74ac7c69 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/loudnorm_impl.c @@ -0,0 +1,201 @@ +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + #include +#else + #include +#endif + +#ifdef _WIN32 + static CRITICAL_SECTION json_mutex; + static CONDITION_VARIABLE json_cond; + static int mutex_initialized = 0; +#else + static pthread_mutex_t json_mutex = PTHREAD_MUTEX_INITIALIZER; + static pthread_cond_t json_cond = PTHREAD_COND_INITIALIZER; +#endif + +static char json_buffer[2048] = {0}; +static int json_captured = 0; + +// Custom logging callback +static void logging_callback(void *ptr, int level, const char *fmt, va_list vl) { + char line[2048]; + vsnprintf(line, sizeof(line), fmt, vl); + + const char *json_start = strstr(line, "{"); + if (json_start) { + #ifdef _WIN32 + EnterCriticalSection(&json_mutex); + #else + pthread_mutex_lock(&json_mutex); + #endif + + strncpy(json_buffer, json_start, sizeof(json_buffer) - 1); + json_captured = 1; + + #ifdef _WIN32 + WakeConditionVariable(&json_cond); + LeaveCriticalSection(&json_mutex); + #else + pthread_cond_signal(&json_cond); + pthread_mutex_unlock(&json_mutex); + #endif + } +} + +char* loudnorm_get_stats( + AVFormatContext* fmt_ctx, + int audio_stream_index, + const char* loudnorm_args +) { + char* result = NULL; + json_captured = 0; // Reset the captured flag + memset(json_buffer, 0, sizeof(json_buffer)); // Clear the buffer + + #ifdef _WIN32 + // Initialize synchronization objects if needed + if (!mutex_initialized) { + InitializeCriticalSection(&json_mutex); + InitializeConditionVariable(&json_cond); + mutex_initialized = 1; + } + #endif + + av_log_set_callback(logging_callback); + + AVFilterGraph *filter_graph = NULL; + AVFilterContext *src_ctx = NULL, *sink_ctx = NULL, *loudnorm_ctx = NULL; + + AVCodec *codec = NULL; + AVCodecContext *codec_ctx = NULL; + int ret; + + AVCodecParameters *codecpar = fmt_ctx->streams[audio_stream_index]->codecpar; + codec = (AVCodec *)avcodec_find_decoder(codecpar->codec_id); + codec_ctx = avcodec_alloc_context3(codec); + avcodec_parameters_to_context(codec_ctx, codecpar); + avcodec_open2(codec_ctx, codec, NULL); + + char ch_layout_str[64]; + av_channel_layout_describe(&codecpar->ch_layout, ch_layout_str, sizeof(ch_layout_str)); + + filter_graph = avfilter_graph_alloc(); + + char args[512]; + snprintf(args, sizeof(args), + "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=%s", + fmt_ctx->streams[audio_stream_index]->time_base.num, + fmt_ctx->streams[audio_stream_index]->time_base.den, + codecpar->sample_rate, + av_get_sample_fmt_name(codec_ctx->sample_fmt), + ch_layout_str); + + avfilter_graph_create_filter(&src_ctx, avfilter_get_by_name("abuffer"), + "src", args, NULL, filter_graph); + avfilter_graph_create_filter(&sink_ctx, avfilter_get_by_name("abuffersink"), + "sink", NULL, NULL, filter_graph); + avfilter_graph_create_filter(&loudnorm_ctx, avfilter_get_by_name("loudnorm"), + "loudnorm", loudnorm_args, NULL, filter_graph); + + avfilter_link(src_ctx, 0, loudnorm_ctx, 0); + avfilter_link(loudnorm_ctx, 0, sink_ctx, 0); + avfilter_graph_config(filter_graph, NULL); + + AVPacket *packet = av_packet_alloc(); + AVFrame *frame = av_frame_alloc(); + AVFrame *filt_frame = av_frame_alloc(); + + while ((ret = av_read_frame(fmt_ctx, packet)) >= 0) { + if (packet->stream_index != audio_stream_index) { + av_packet_unref(packet); + continue; + } + + ret = avcodec_send_packet(codec_ctx, packet); + if (ret < 0) { + av_packet_unref(packet); + continue; + } + + while (ret >= 0) { + ret = avcodec_receive_frame(codec_ctx, frame); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; + if (ret < 0) goto end; + + ret = av_buffersrc_add_frame_flags(src_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF); + if (ret < 0) goto end; + + while (1) { + ret = av_buffersink_get_frame(sink_ctx, filt_frame); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; + if (ret < 0) goto end; + av_frame_unref(filt_frame); + } + } + av_packet_unref(packet); + } + + // Flush decoder + avcodec_send_packet(codec_ctx, NULL); + while (avcodec_receive_frame(codec_ctx, frame) >= 0) { + ret = av_buffersrc_add_frame(src_ctx, frame); + if (ret < 0) goto end; + } + + // Flush filter + ret = av_buffersrc_add_frame(src_ctx, NULL); + if (ret < 0) goto end; + while (av_buffersink_get_frame(sink_ctx, filt_frame) >= 0) { + av_frame_unref(filt_frame); + } + + // Pushes graph + avfilter_graph_free(&filter_graph); + +end: + avcodec_free_context(&codec_ctx); + avformat_close_input(&fmt_ctx); + av_frame_free(&filt_frame); + av_frame_free(&frame); + av_packet_free(&packet); + + #ifdef _WIN32 + EnterCriticalSection(&json_mutex); + while (!json_captured) { + if (!SleepConditionVariableCS(&json_cond, &json_mutex, 5000)) { // 5 second timeout + fprintf(stderr, "Timeout waiting for JSON data\n"); + break; + } + } + if (json_captured) { + result = _strdup(json_buffer); // Use _strdup on Windows + } + LeaveCriticalSection(&json_mutex); + #else + struct timespec timeout; + clock_gettime(CLOCK_REALTIME, &timeout); + timeout.tv_sec += 5; // 5 second timeout + + pthread_mutex_lock(&json_mutex); + while (json_captured == 0) { + int ret = pthread_cond_timedwait(&json_cond, &json_mutex, &timeout); + if (ret == ETIMEDOUT) { + fprintf(stderr, "Timeout waiting for JSON data\n"); + break; + } + } + if (json_captured) { + result = strdup(json_buffer); + } + pthread_mutex_unlock(&json_mutex); + #endif + + av_log_set_callback(av_log_default_callback); + return result; +} diff --git a/lib/python3.10/site-packages/av/filter/loudnorm_impl.h b/lib/python3.10/site-packages/av/filter/loudnorm_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..7357e46689d5cbd5795ce00c5864f40e197e09dd --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/loudnorm_impl.h @@ -0,0 +1,12 @@ +#ifndef AV_FILTER_LOUDNORM_H +#define AV_FILTER_LOUDNORM_H + +#include + +char* loudnorm_get_stats( + AVFormatContext* fmt_ctx, + int audio_stream_index, + const char* loudnorm_args +); + +#endif // AV_FILTER_LOUDNORM_H \ No newline at end of file diff --git a/lib/python3.10/site-packages/av/filter/pad.pxd b/lib/python3.10/site-packages/av/filter/pad.pxd new file mode 100644 index 0000000000000000000000000000000000000000..15ac950fca1a3bcec2602b177775a456d9c20280 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/pad.pxd @@ -0,0 +1,23 @@ +cimport libav as lib + +from av.filter.context cimport FilterContext +from av.filter.filter cimport Filter +from av.filter.link cimport FilterLink + + +cdef class FilterPad: + + cdef readonly Filter filter + cdef readonly FilterContext context + cdef readonly bint is_input + cdef readonly int index + + cdef const lib.AVFilterPad *base_ptr + + +cdef class FilterContextPad(FilterPad): + + cdef FilterLink _link + + +cdef tuple alloc_filter_pads(Filter, const lib.AVFilterPad *ptr, bint is_input, FilterContext context=?) diff --git a/lib/python3.10/site-packages/av/filter/pad.pyi b/lib/python3.10/site-packages/av/filter/pad.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1a6c9bda66dbc730f34b86104e8a4001d90e9dfd --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/pad.pyi @@ -0,0 +1,10 @@ +from .link import FilterLink + +class FilterPad: + is_output: bool + name: str + type: str + +class FilterContextPad(FilterPad): + link: FilterLink | None + linked: FilterContextPad | None diff --git a/lib/python3.10/site-packages/av/filter/pad.pyx b/lib/python3.10/site-packages/av/filter/pad.pyx new file mode 100644 index 0000000000000000000000000000000000000000..873b31b04b481782f7427e9de54bcf55b9f3af65 --- /dev/null +++ b/lib/python3.10/site-packages/av/filter/pad.pyx @@ -0,0 +1,92 @@ +from av.filter.link cimport wrap_filter_link + + +cdef object _cinit_sentinel = object() + + +cdef class FilterPad: + def __cinit__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot construct FilterPad") + + def __repr__(self): + _filter = self.filter.name + _io = "inputs" if self.is_input else "outputs" + + return f"" + + @property + def is_output(self): + return not self.is_input + + @property + def name(self): + return lib.avfilter_pad_get_name(self.base_ptr, self.index) + + @property + def type(self): + """ + The media type of this filter pad. + + Examples: `'audio'`, `'video'`, `'subtitle'`. + + :type: str + """ + return lib.av_get_media_type_string(lib.avfilter_pad_get_type(self.base_ptr, self.index)) + + +cdef class FilterContextPad(FilterPad): + def __repr__(self): + _filter = self.filter.name + _io = "inputs" if self.is_input else "outputs" + context = self.context.name + + return f"" + + @property + def link(self): + if self._link: + return self._link + cdef lib.AVFilterLink **links = self.context.ptr.inputs if self.is_input else self.context.ptr.outputs + cdef lib.AVFilterLink *link = links[self.index] + if not link: + return + self._link = wrap_filter_link(self.context.graph, link) + return self._link + + @property + def linked(self): + cdef FilterLink link = self.link + if link: + return link.input if self.is_input else link.output + + +cdef tuple alloc_filter_pads(Filter filter, const lib.AVFilterPad *ptr, bint is_input, FilterContext context=None): + if not ptr: + return () + + pads = [] + + # We need to be careful and check our bounds if we know what they are, + # since the arrays on a AVFilterContext are not NULL terminated. + cdef int i = 0 + cdef int count + if context is None: + # This is a custom function defined using a macro in avfilter.pxd. Its usage + # can be changed after we stop supporting FFmpeg < 5.0. + count = lib.pyav_get_num_pads(filter.ptr, not is_input, ptr) + else: + count = (context.ptr.nb_inputs if is_input else context.ptr.nb_outputs) + + cdef FilterPad pad + while (i < count): + pad = FilterPad(_cinit_sentinel) if context is None else FilterContextPad(_cinit_sentinel) + pads.append(pad) + pad.filter = filter + pad.context = context + pad.is_input = is_input + pad.base_ptr = ptr + pad.index = i + i += 1 + + return tuple(pads) diff --git a/lib/python3.10/site-packages/av/plane.cpython-310-x86_64-linux-gnu.so b/lib/python3.10/site-packages/av/plane.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b4b8a12263db1d21935bc09e16dd3ef003a5f350 --- /dev/null +++ b/lib/python3.10/site-packages/av/plane.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1404a5db4227c355a02b1af26134c6e434a63b1c2110c7a66e3cca4b392f39f7 +size 392457 diff --git a/lib/python3.10/site-packages/av/subtitles/__init__.pxd b/lib/python3.10/site-packages/av/subtitles/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.10/site-packages/av/subtitles/__init__.py b/lib/python3.10/site-packages/av/subtitles/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.10/site-packages/av/subtitles/codeccontext.pxd b/lib/python3.10/site-packages/av/subtitles/codeccontext.pxd new file mode 100644 index 0000000000000000000000000000000000000000..42141aa4f80e00ad81dd88841cd1b9457d49c231 --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/codeccontext.pxd @@ -0,0 +1,5 @@ +from av.codec.context cimport CodecContext + + +cdef class SubtitleCodecContext(CodecContext): + pass diff --git a/lib/python3.10/site-packages/av/subtitles/codeccontext.pyi b/lib/python3.10/site-packages/av/subtitles/codeccontext.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0762c19f0602551e2b0fa4e218354d3b69ffdaf5 --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/codeccontext.pyi @@ -0,0 +1,6 @@ +from typing import Literal + +from av.codec.context import CodecContext + +class SubtitleCodecContext(CodecContext): + type: Literal["subtitle"] diff --git a/lib/python3.10/site-packages/av/subtitles/codeccontext.pyx b/lib/python3.10/site-packages/av/subtitles/codeccontext.pyx new file mode 100644 index 0000000000000000000000000000000000000000..c0712c92c50a789f99a3f83e5b3360def92d300b --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/codeccontext.pyx @@ -0,0 +1,23 @@ +cimport libav as lib + +from av.error cimport err_check +from av.packet cimport Packet +from av.subtitles.subtitle cimport SubtitleProxy, SubtitleSet + + +cdef class SubtitleCodecContext(CodecContext): + cdef _send_packet_and_recv(self, Packet packet): + if packet is None: + raise RuntimeError("packet cannot be None") + + cdef SubtitleProxy proxy = SubtitleProxy() + cdef int got_frame = 0 + + err_check( + lib.avcodec_decode_subtitle2(self.ptr, &proxy.struct, &got_frame, packet.ptr) + ) + + if got_frame: + return [SubtitleSet(proxy)] + else: + return [] diff --git a/lib/python3.10/site-packages/av/subtitles/stream.pxd b/lib/python3.10/site-packages/av/subtitles/stream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..745032af956c812f0d72f2f3dda9c888b23b1b7f --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/stream.pxd @@ -0,0 +1,6 @@ +from av.packet cimport Packet +from av.stream cimport Stream + + +cdef class SubtitleStream(Stream): + cpdef decode(self, Packet packet=?) diff --git a/lib/python3.10/site-packages/av/subtitles/stream.pyi b/lib/python3.10/site-packages/av/subtitles/stream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cb1ac34a25edbe387b1c1e2c390f14b0cb9fd19c --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/stream.pyi @@ -0,0 +1,6 @@ +from av.packet import Packet +from av.stream import Stream +from av.subtitles.subtitle import SubtitleSet + +class SubtitleStream(Stream): + def decode(self, packet: Packet | None = None) -> list[SubtitleSet]: ... diff --git a/lib/python3.10/site-packages/av/subtitles/stream.pyx b/lib/python3.10/site-packages/av/subtitles/stream.pyx new file mode 100644 index 0000000000000000000000000000000000000000..9f90b987153705de37a648e844852da83cf2375f --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/stream.pyx @@ -0,0 +1,23 @@ +from av.packet cimport Packet +from av.stream cimport Stream + + +cdef class SubtitleStream(Stream): + """ + A :class:`SubtitleStream` can contain many :class:`SubtitleSet` objects accessible via decoding. + """ + def __getattr__(self, name): + return getattr(self.codec_context, name) + + cpdef decode(self, Packet packet=None): + """ + Decode a :class:`.Packet` and return a list of :class:`.SubtitleSet`. + + :rtype: list[SubtitleSet] + + .. seealso:: This is a passthrough to :meth:`.CodecContext.decode`. + """ + if not packet: + packet = Packet() + + return self.codec_context.decode(packet) diff --git a/lib/python3.10/site-packages/av/subtitles/subtitle.pxd b/lib/python3.10/site-packages/av/subtitles/subtitle.pxd new file mode 100644 index 0000000000000000000000000000000000000000..508eb903480a4a0b112f6580eb66ba9ae9820491 --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/subtitle.pxd @@ -0,0 +1,31 @@ +cimport libav as lib + + +cdef class SubtitleProxy: + cdef lib.AVSubtitle struct + + +cdef class SubtitleSet: + cdef SubtitleProxy proxy + cdef readonly tuple rects + + +cdef class Subtitle: + cdef SubtitleProxy proxy + cdef lib.AVSubtitleRect *ptr + cdef readonly bytes type + +cdef class TextSubtitle(Subtitle): + pass + +cdef class ASSSubtitle(Subtitle): + pass + +cdef class BitmapSubtitle(Subtitle): + cdef readonly planes + +cdef class BitmapSubtitlePlane: + cdef readonly BitmapSubtitle subtitle + cdef readonly int index + cdef readonly long buffer_size + cdef void *_buffer diff --git a/lib/python3.10/site-packages/av/subtitles/subtitle.pyi b/lib/python3.10/site-packages/av/subtitles/subtitle.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2a35d0a5546694b1030c53cae6e8914e237ff62d --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/subtitle.pyi @@ -0,0 +1,37 @@ +from typing import Iterator, Literal + +class SubtitleSet: + format: int + start_display_time: int + end_display_time: int + pts: int + rects: tuple[Subtitle] + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[Subtitle]: ... + def __getitem__(self, i: int) -> Subtitle: ... + +class Subtitle: ... + +class BitmapSubtitle(Subtitle): + type: Literal[b"bitmap"] + x: int + y: int + width: int + height: int + nb_colors: int + planes: tuple[BitmapSubtitlePlane, ...] + +class BitmapSubtitlePlane: + subtitle: BitmapSubtitle + index: int + buffer_size: int + +class AssSubtitle(Subtitle): + type: Literal[b"ass", b"text"] + @property + def ass(self) -> bytes: ... + @property + def dialogue(self) -> bytes: ... + @property + def text(self) -> bytes: ... diff --git a/lib/python3.10/site-packages/av/subtitles/subtitle.pyx b/lib/python3.10/site-packages/av/subtitles/subtitle.pyx new file mode 100644 index 0000000000000000000000000000000000000000..373bb529b82a7c17eec1e9d00b58da5d5f178707 --- /dev/null +++ b/lib/python3.10/site-packages/av/subtitles/subtitle.pyx @@ -0,0 +1,204 @@ +from cpython cimport PyBuffer_FillInfo + + +cdef extern from "Python.h": + bytes PyBytes_FromString(char*) + + +cdef class SubtitleProxy: + def __dealloc__(self): + lib.avsubtitle_free(&self.struct) + + +cdef class SubtitleSet: + """ + A :class:`SubtitleSet` can contain many :class:`Subtitle` objects. + """ + def __cinit__(self, SubtitleProxy proxy): + self.proxy = proxy + cdef int i + self.rects = tuple(build_subtitle(self, i) for i in range(self.proxy.struct.num_rects)) + + def __repr__(self): + return f"<{self.__class__.__module__}.{self.__class__.__name__} at 0x{id(self):x}>" + + @property + def format(self): return self.proxy.struct.format + @property + def start_display_time(self): return self.proxy.struct.start_display_time + @property + def end_display_time(self): return self.proxy.struct.end_display_time + @property + def pts(self): return self.proxy.struct.pts + + def __len__(self): + return len(self.rects) + + def __iter__(self): + return iter(self.rects) + + def __getitem__(self, i): + return self.rects[i] + + +cdef Subtitle build_subtitle(SubtitleSet subtitle, int index): + """Build an av.Stream for an existing AVStream. + + The AVStream MUST be fully constructed and ready for use before this is + called. + + """ + + if index < 0 or index >= subtitle.proxy.struct.num_rects: + raise ValueError("subtitle rect index out of range") + cdef lib.AVSubtitleRect *ptr = subtitle.proxy.struct.rects[index] + + if ptr.type == lib.SUBTITLE_BITMAP: + return BitmapSubtitle(subtitle, index) + elif ptr.type == lib.SUBTITLE_ASS or ptr.type == lib.SUBTITLE_TEXT: + return AssSubtitle(subtitle, index) + else: + raise ValueError("unknown subtitle type %r" % ptr.type) + + +cdef class Subtitle: + """ + An abstract base class for each concrete type of subtitle. + Wraps :ffmpeg:`AVSubtitleRect` + """ + def __cinit__(self, SubtitleSet subtitle, int index): + if index < 0 or index >= subtitle.proxy.struct.num_rects: + raise ValueError("subtitle rect index out of range") + self.proxy = subtitle.proxy + self.ptr = self.proxy.struct.rects[index] + + if self.ptr.type == lib.SUBTITLE_NONE: + self.type = b"none" + elif self.ptr.type == lib.SUBTITLE_BITMAP: + self.type = b"bitmap" + elif self.ptr.type == lib.SUBTITLE_TEXT: + self.type = b"text" + elif self.ptr.type == lib.SUBTITLE_ASS: + self.type = b"ass" + else: + raise ValueError(f"unknown subtitle type {self.ptr.type!r}") + + def __repr__(self): + return f"<{self.__class__.__module__}.{self.__class__.__name__} at 0x{id(self):x}>" + + +cdef class BitmapSubtitle(Subtitle): + def __cinit__(self, SubtitleSet subtitle, int index): + self.planes = tuple( + BitmapSubtitlePlane(self, i) + for i in range(4) + if self.ptr.linesize[i] + ) + + def __repr__(self): + return ( + f"<{self.__class__.__module__}.{self.__class__.__name__} " + f"{self.width}x{self.height} at {self.x},{self.y}; at 0x{id(self):x}>" + ) + + @property + def x(self): return self.ptr.x + @property + def y(self): return self.ptr.y + @property + def width(self): return self.ptr.w + @property + def height(self): return self.ptr.h + @property + def nb_colors(self): return self.ptr.nb_colors + + def __len__(self): + return len(self.planes) + + def __iter__(self): + return iter(self.planes) + + def __getitem__(self, i): + return self.planes[i] + + +cdef class BitmapSubtitlePlane: + def __cinit__(self, BitmapSubtitle subtitle, int index): + if index >= 4: + raise ValueError("BitmapSubtitles have only 4 planes") + if not subtitle.ptr.linesize[index]: + raise ValueError("plane does not exist") + + self.subtitle = subtitle + self.index = index + self.buffer_size = subtitle.ptr.w * subtitle.ptr.h + self._buffer = subtitle.ptr.data[index] + + # New-style buffer support. + def __getbuffer__(self, Py_buffer *view, int flags): + PyBuffer_FillInfo(view, self, self._buffer, self.buffer_size, 0, flags) + + +cdef class AssSubtitle(Subtitle): + """ + Represents an ASS/Text subtitle format, as opposed to a bitmap Subtitle format. + """ + def __repr__(self): + return ( + f"<{self.__class__.__module__}.{self.__class__.__name__} " + f"{self.text!r} at 0x{id(self):x}>" + ) + + @property + def ass(self): + """ + Returns the subtitle in the ASS/SSA format. Used by the vast majority of subtitle formats. + """ + if self.ptr.ass is not NULL: + return PyBytes_FromString(self.ptr.ass) + return b"" + + @property + def dialogue(self): + """ + Extract the dialogue from the ass format. Strip comments. + """ + comma_count = 0 + i = 0 + cdef bytes ass_text = self.ass + cdef bytes result = b"" + + while comma_count < 8 and i < len(ass_text): + if bytes([ass_text[i]]) == b",": + comma_count += 1 + i += 1 + + state = False + while i < len(ass_text): + char = bytes([ass_text[i]]) + next_char = b"" if i + 1 >= len(ass_text) else bytes([ass_text[i + 1]]) + + if char == b"\\" and next_char == b"N": + result += b"\n" + i += 2 + continue + + if not state: + if char == b"{" and next_char != b"\\": + state = True + else: + result += char + elif char == b"}": + state = False + i += 1 + + return result + + @property + def text(self): + """ + Rarely used attribute. You're probably looking for dialogue. + """ + if self.ptr.text is not NULL: + return PyBytes_FromString(self.ptr.text) + return b"" diff --git a/lib/python3.10/site-packages/av/utils.cpython-310-x86_64-linux-gnu.so b/lib/python3.10/site-packages/av/utils.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4feacc68129223b078cfa1a223e486985252ba3c --- /dev/null +++ b/lib/python3.10/site-packages/av/utils.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9968a9c92b186c6c03e6b1da8f001c2f0d170dcaf53d2875ff4e5bb556ad2d9 +size 269185 diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/INSTALLER b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/LICENSE b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..710010f1fe0311afd9823e319ff958827a419964 --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/LICENSE @@ -0,0 +1,30 @@ +Copyright (C) 2010, 2011 Sebastian Thiel and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +* Neither the name of the async project nor the names of +its contributors may be used to endorse or promote products derived +from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/METADATA b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ce0537bde0f6d4cfee9549b001156bd5cabc107a --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/METADATA @@ -0,0 +1,113 @@ +Metadata-Version: 2.1 +Name: smmap +Version: 5.0.2 +Summary: A pure Python implementation of a sliding window memory map manager +Home-page: https://github.com/gitpython-developers/smmap +Author: Sebastian Thiel +Author-email: byronimo@gmail.com +License: BSD-3-Clause +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE + +## Motivation + +When reading from many possibly large files in a fashion similar to random access, it is usually the fastest and most efficient to use memory maps. + +Although memory maps have many advantages, they represent a very limited system resource as every map uses one file descriptor, whose amount is limited per process. On 32 bit systems, the amount of memory you can have mapped at a time is naturally limited to theoretical 4GB of memory, which may not be enough for some applications. + + +## Limitations + +* **System resources (file-handles) are likely to be leaked!** This is due to the library authors reliance on a deterministic `__del__()` destructor. +* The memory access is read-only by design. + + +## Overview + +![Python package](https://github.com/gitpython-developers/smmap/workflows/Python%20package/badge.svg) + +Smmap wraps an interface around mmap and tracks the mapped files as well as the amount of clients who use it. If the system runs out of resources, or if a memory limit is reached, it will automatically unload unused maps to allow continued operation. + +To allow processing large files even on 32 bit systems, it allows only portions of the file to be mapped. Once the user reads beyond the mapped region, smmap will automatically map the next required region, unloading unused regions using a LRU algorithm. + +Although the library can be used most efficiently with its native interface, a Buffer implementation is provided to hide these details behind a simple string-like interface. + +For performance critical 64 bit applications, a simplified version of memory mapping is provided which always maps the whole file, but still provides the benefit of unloading unused mappings on demand. + + + +## Prerequisites + +* Python 3.7+ +* OSX, Windows or Linux + +The package was tested on all of the previously mentioned configurations. + +## Installing smmap + +[![Documentation Status](https://readthedocs.org/projects/smmap/badge/?version=latest)](https://readthedocs.org/projects/smmap/?badge=latest) + +Its easiest to install smmap using the [pip](http://www.pip-installer.org/en/latest) program: + +```bash +$ pip install smmap +``` + +As the command will install smmap in your respective python distribution, you will most likely need root permissions to authorize the required changes. + +If you have downloaded the source archive, the package can be installed by running the `setup.py` script: + +```bash +$ python setup.py install +``` + +It is advised to have a look at the **Usage Guide** for a brief introduction on the different database implementations. + + + +## Homepage and Links + +The project is home on github at https://github.com/gitpython-developers/smmap . + +The latest source can be cloned from github as well: + +* git://github.com/gitpython-developers/smmap.git + + +For support, please use the git-python mailing list: + +* http://groups.google.com/group/git-python + + +Issues can be filed on github: + +* https://github.com/gitpython-developers/smmap/issues + +A link to the pypi page related to this repository: + +* https://pypi.org/project/smmap/ + + +## License Information + +*smmap* is licensed under the New BSD License. + diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/RECORD b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..308549593fe8f28f7d700f96caf0598a6ee2b238 --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/RECORD @@ -0,0 +1,18 @@ +smmap-5.0.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +smmap-5.0.2.dist-info/LICENSE,sha256=iOnZP3CNEQsyioNDAt0dXGr72lMOdyHRXYCzUR2G8jU,1519 +smmap-5.0.2.dist-info/METADATA,sha256=3BUpM_oN3bljLC5WDH9bxeo5JqXV-AGVQ4Epw1C5h2Y,4306 +smmap-5.0.2.dist-info/RECORD,, +smmap-5.0.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +smmap-5.0.2.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +smmap-5.0.2.dist-info/top_level.txt,sha256=h0Tp1UdaROCy2bjWNha1MFpwgVghxEUQsaLHbZs96Gw,6 +smmap-5.0.2.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +smmap/__init__.py,sha256=Bf9KWm-zr5__SoSEEXI20pqKOJFpUApidvardLulRLY,343 +smmap/buf.py,sha256=wElndUNa4Njhnes6JYmI_Xp4zwaohirLdr7eVR9XYNU,5762 +smmap/mman.py,sha256=HYxohllZqpPY4KgRF_D_lNp4fx0akZ-NQosutLDrQ60,24022 +smmap/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +smmap/test/lib.py,sha256=jYIT4rKckHw2s7-l5lwysft1jqrwDFkjtyNLKNpu_j0,1489 +smmap/test/test_buf.py,sha256=BCg9FbusakiYNs5MUNoJSiyuTP5HcMYl65HzvpY9SNo,5439 +smmap/test/test_mman.py,sha256=o3cPg5idyYJpq32zXgDy1qtD10RA_e88-1zPYBWi4Ms,10822 +smmap/test/test_tutorial.py,sha256=ZwCphCbKAGYt_fn_CiOJ9lWwpWwpqE4-zBUp-v-t9eM,3174 +smmap/test/test_util.py,sha256=3hJyW9Km7k7XSgxxtDOkG8eVagk3lIzP4H2pR0S2ewg,3468 +smmap/util.py,sha256=_Sl3Sd2KWdd-5nmhUegFMfT6L1j5BGchRT4z53Sobug,7476 diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/REQUESTED b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/WHEEL b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/top_level.txt b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2765cefa1c4976ec31a903f3ffb7b2f9f92531f3 --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/top_level.txt @@ -0,0 +1 @@ +smmap diff --git a/lib/python3.10/site-packages/smmap-5.0.2.dist-info/zip-safe b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/lib/python3.10/site-packages/smmap-5.0.2.dist-info/zip-safe @@ -0,0 +1 @@ +