diff --git a/.gitattributes b/.gitattributes index f8799fbca123896b60f10ce156174d110cb4362a..ab6c3709608a099736aa6dcb01a7215217b466fa 100644 --- a/.gitattributes +++ b/.gitattributes @@ -109,3 +109,45 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/av/plane.abi3.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/av/rational.abi3.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/av/sidedata/encparams.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/sidedata/sidedata.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/stream.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/subtitles/stream.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/subtitles/subtitle.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/utils.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/video/codeccontext.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/video/format.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/video/frame.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/video/plane.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/video/reformatter.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/video/stream.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libSvtAv1Enc-9393c086.so.4.1.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libasound-c7818c60.so.2.0.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libavcodec-5e6b81c2.so.62.28.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libavdevice-d91b4e17.so.62.3.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libavfilter-b5da520e.so.11.14.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libavformat-4639def2.so.62.12.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libavutil-5809ad29.so.60.26.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libdav1d-f4b27961.so.7.0.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libgmp-8c6c054f.so.10.5.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libgnutls-71454fd1.so.30.42.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libhogweed-006f41d4.so.6.11 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libmp3lame-8f9e436f.so.0.0.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libnettle-71a806b4.so.8.11 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libopencore-amrnb-d72c52e2.so.0.0.5 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libopus-114e2b1a.so.0.11.1 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libswresample-f0bc92fc.so.6.3.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libswscale-88e9f973.so.9.5.102 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libunistring-09f6121d.so.5.2.1 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libvpl-e4e9cae8.so.2.16 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libvpx-edb6de90.so.12.0.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libwebp-0c5118d0.so.7.2.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libx264-d6533a8d.so.165 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libx265-f5385bb8.so.216 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av.libs/libxcb-5ddf6756.so.1.1.0 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/bs4/__pycache__/element.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/charset_normalizer/cd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/charset_normalizer/md.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/contourpy/_contourpy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/cv2/cv2.abi3.so filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3e80fd78820494e7ece01943b2672f42f22348d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/METADATA @@ -0,0 +1,138 @@ +Metadata-Version: 2.4 +Name: av +Version: 18.1.0 +Summary: Pythonic bindings for FFmpeg's libraries. +Author-email: WyattBlue , Jeremy Lainé +License-Expression: BSD-3-Clause +Project-URL: Bug Tracker, https://github.com/PyAV-Org/PyAV/issues +Project-URL: Source Code, https://github.com/PyAV-Org/PyAV +Project-URL: homepage, https://pyav.basswood.io +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Multimedia :: Sound/Audio +Classifier: Topic :: Multimedia :: Sound/Audio :: Conversion +Classifier: Topic :: Multimedia :: Video +Classifier: Topic :: Multimedia :: Video :: Conversion +Requires-Python: >=3.11 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +License-File: AUTHORS.py +License-File: AUTHORS.rst +Dynamic: license-file + +PyAV +==== + +PyAV is a Pythonic binding for the [FFmpeg][ffmpeg] libraries. We aim to provide all the power and control of the underlying library, but manage the gritty details as much as possible. + +--- + +[![GitHub Test Status][github-tests-badge]][github-tests] [![Documentation][docs-badge]][docs] [![Python Package Index][pypi-badge]][pypi] [![Conda Forge][conda-badge]][conda] + +PyAV is for direct and precise access to your media via containers, streams, packets, codecs, and frames. It exposes a few transformations of that data, and helps you get your data to/from other packages (e.g. NumPy and Pillow). + +This power does come with some responsibility as working with media is horrendously complicated and PyAV can't abstract it away or make all the best decisions for you. If the `ffmpeg` command does the job without you bending over backwards, PyAV is likely going to be more of a hindrance than a help. + +But where you can't work without it, PyAV is a critical tool. + + +Installation +------------ + +PyAV requires Python 3.11 or later. Binary wheels are provided on [PyPI][pypi] for Linux, macOS, and Windows with FFmpeg bundled. You can install these wheels by running: + +```bash +pip install av +``` + +Another way of installing PyAV is via [conda-forge][conda-forge]: + +```bash +conda install av -c conda-forge +``` + +See the [Conda install][conda-install] docs to get started with Miniconda. + + +Alternative installation methods +-------------------------------- + +Due to the complexity of the dependencies, PyAV is not always the easiest Python package to install from source. This release supports FFmpeg 8.x. To build the source distribution against an existing FFmpeg installation on Linux or macOS, run: + +> [!WARNING] +> FFmpeg's development files and `pkg-config` must be available on your system. + +```bash +pip install av --no-binary av +``` + + +Installing from source +---------------------- + +On Linux or macOS, build PyAV from a Git checkout with: + +```bash +git clone https://github.com/PyAV-Org/PyAV.git +cd PyAV +source scripts/activate.sh + +# Build ffmpeg from source. You can skip this step if ffmpeg 8.x is already installed. +./scripts/build-deps + +# Build PyAV +make + +# Testing +make test + +# Install globally +deactivate +pip install . +``` + +On Windows, use a Conda environment and the FFmpeg development files maintained by the PyAV project: + +```powershell +git clone https://github.com/PyAV-Org/PyAV.git +cd PyAV +conda create --name pyav-dev --channel conda-forge python=3.11 cython setuptools numpy pillow pytest +conda activate pyav-dev +$ffmpegDir = Join-Path $env:CONDA_PREFIX "Library" +python scripts\fetch-vendor.py --config-file scripts\ffmpeg-latest.json $ffmpegDir +python setup.py build_ext --inplace --ffmpeg-dir=$ffmpegDir +python -m pytest +``` + +--- + +Have fun, [read the docs][docs], [come chat with us][discuss], and good luck! + + + +[conda-badge]: https://img.shields.io/conda/vn/conda-forge/av.svg?colorB=CCB39A +[conda]: https://anaconda.org/conda-forge/av +[docs-badge]: https://img.shields.io/badge/docs-on%20pyav.basswood.io-blue.svg +[docs]: https://pyav.basswood.io +[pypi-badge]: https://img.shields.io/pypi/v/av.svg?colorB=CCB39A +[pypi]: https://pypi.org/project/av +[discuss]: https://github.com/PyAV-Org/PyAV/discussions + +[github-tests-badge]: https://github.com/PyAV-Org/PyAV/workflows/tests/badge.svg +[github-tests]: https://github.com/PyAV-Org/PyAV/actions?workflow=tests +[github]: https://github.com/PyAV-Org/PyAV + +[ffmpeg]: https://ffmpeg.org/ +[conda-forge]: https://conda-forge.github.io/ +[conda-install]: https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..60601e4d50ca3530eab92e6fc2dee17729184359 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/RECORD @@ -0,0 +1,323 @@ +../../../bin/pyav,sha256=HyF6NnH5lLqu1iiSF8TgogO9BLvSepg0GxhlQOfg32I,242 +av-18.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +av-18.1.0.dist-info/METADATA,sha256=CZvqmxyxb7JPMj00ljbcJul7pRqymaP9stiuAoA6kJY,4993 +av-18.1.0.dist-info/RECORD,, +av-18.1.0.dist-info/WHEEL,sha256=9ihgoT5h-FKvqMl4BN4dg88cv4QchEls3Lpprl-N-EQ,112 +av-18.1.0.dist-info/entry_points.txt,sha256=3XMdM30ih673nLSRVzDsHLBmGYNlt7wQ1xyW8xoHAzg,42 +av-18.1.0.dist-info/licenses/AUTHORS.py,sha256=Tsbg3KPQcDrr77OG0-tu0UoF2W_osKoItSwtKVGBf-w,5558 +av-18.1.0.dist-info/licenses/AUTHORS.rst,sha256=rbOps1qLdLtZcybex3XXSp95tN7KxU2iZqndsgtdoUI,5996 +av-18.1.0.dist-info/licenses/LICENSE.txt,sha256=dq8EYf-5LhnxwURJ6VVX2Dot-qG68gLUnl8dh0bA2hk,1505 +av-18.1.0.dist-info/licenses/__pycache__/AUTHORS.cpython-312.pyc,, +av-18.1.0.dist-info/sboms/auditwheel.cdx.json,sha256=oGskzhiamLlRBdZxV1_IcecBIbUBFuOXfQvjH0tMgAs,3465 +av-18.1.0.dist-info/top_level.txt,sha256=TuQF-stvFHN8ilfr36ctqc7_MR5IOhUqrR0i6i5gNR8,3 +av.libs/libSvtAv1Enc-9393c086.so.4.1.0,sha256=nLX1cZYUNCfF8WX5i4ihdOBsWS5aiEUH9a3NiyBHJBQ,7061777 +av.libs/libXau-154567c4.so.6.0.0,sha256=BUhNJL94y47QMWnxywZyBNgpy3ryHeiCBADSnRFeQyA,22081 +av.libs/libasound-c7818c60.so.2.0.0,sha256=te_BfMX691jtFVTtOsQyLgOkO2tJAN7LdwAuRpSq-nA,1162289 +av.libs/libavcodec-5e6b81c2.so.62.28.102,sha256=0PC2XdjRlCeDCdzmSpZhBA8Pe9d9DSBzOg16Br2yals,18795033 +av.libs/libavdevice-d91b4e17.so.62.3.102,sha256=Xw712s5MnB7YwK_RHni8YgWjaR6NdbFgRSNFpQpQmc4,123897 +av.libs/libavfilter-b5da520e.so.11.14.102,sha256=XSRNQupsLJXmeDtr1lKPb3pebtTI3kPxqVUEaDhGs8Y,5464473 +av.libs/libavformat-4639def2.so.62.12.102,sha256=CyInc5goP7lmyKV_wJoY_icB_JO6K_cjZHhvMw7JTgM,2983097 +av.libs/libavutil-5809ad29.so.60.26.102,sha256=XFnC2NHa8POVb8ocEYwtiF54GlV84awabgRB-4MRZkM,1107705 +av.libs/libdav1d-f4b27961.so.7.0.0,sha256=sYnn4EKxIx5RzyjqxPVUyNpSohPKUZcT3XxB2fhJhFE,2024729 +av.libs/libdrm-b0291a67.so.2.4.0,sha256=K48ZAlNAuvSdX7i2toETxCm6886w4E17JmP2c8RM2-0,96417 +av.libs/libgmp-8c6c054f.so.10.5.0,sha256=POyCYSCU4iNC0ytLoiulgtibSmj_goe7CJ0n4TPcOl4,511649 +av.libs/libgnutls-71454fd1.so.30.42.0,sha256=Mv9Pl6q_G_gWlhmmyqtmMLkIf2c8UD_vvHarTCJThqc,2416425 +av.libs/libhogweed-006f41d4.so.6.11,sha256=5gcb1N1ENB4DXspKwqsQiHNOM2II6G10bgJ4ThXr2pw,333209 +av.libs/libmp3lame-8f9e436f.so.0.0.0,sha256=bMjkcPVkTCP3Qbfxfzi6C5VwAneDbXsjBSgLf-3yItY,421065 +av.libs/libnettle-71a806b4.so.8.11,sha256=OoCcTRU8wS1FhvrX8fwQW9fmNV9-O5xxl34Ya1bgV8E,359649 +av.libs/libopencore-amrnb-d72c52e2.so.0.0.5,sha256=kMlnxMZcS4gFbZbIhpg53b-ghS2o_PnIb3DVjzQBtQ8,172849 +av.libs/libopencore-amrwb-1b0ca122.so.0.0.5,sha256=rkqphHJ3tNeu98L1QSyGCDTdDfdPpv6cVI-YHUuFNcg,90761 +av.libs/libopus-114e2b1a.so.0.11.1,sha256=lpTrqVEREqoylszIbP5d9gQGgz8DsaVrAI5_BDGlFQc,433329 +av.libs/libsharpyuv-48a062bd.so.0.1.2,sha256=nMc9gQgGB-6M4YZfAZUehG6du7mtfrpVlHEgvVBISvY,46089 +av.libs/libswresample-f0bc92fc.so.6.3.102,sha256=Sl_yj8VL9ryCNWM2gG5sJC8X3RfsZneto2kNr3mWoBI,154433 +av.libs/libswscale-88e9f973.so.9.5.102,sha256=GNr4jgaZXWL5SLtwZ3svlOjfD1pCFh_QjpZz5ixbpPE,2017409 +av.libs/libunistring-09f6121d.so.5.2.1,sha256=Hn4676J-nV6TxcC4OzAuEuPC_LOiGgXN33QPLNIpCmg,2037033 +av.libs/libvpl-e4e9cae8.so.2.16,sha256=rPABXJx1HiJgkjZq2hQLBeizH4EgvUQ-RJRAWm2gkZ4,428369 +av.libs/libvpx-edb6de90.so.12.0.0,sha256=_Ie8PHxnR_L3banKPy9VdAb1NszOIlLSsBOWHoOu4Ic,2344937 +av.libs/libwebp-0c5118d0.so.7.2.0,sha256=KFSwxqeXV10Dxn2Rtw9b0tgtLOMOYt6tQRKxzuvL-5g,747633 +av.libs/libwebpmux-e1880640.so.3.1.2,sha256=b_J1mviieLVkRRID3qNrUHfhLfuuTHAFJVFtSYSojZE,64329 +av.libs/libx264-d6533a8d.so.165,sha256=VYfS0GCRTi5SaU41cDp8jyDzFD6vqVZwbgiQSd87WAs,2177713 +av.libs/libx265-f5385bb8.so.216,sha256=4wThs7Y2fpAoN7mgDQvFuQ2Dpw4fu2myfzTYyXDEt2U,20591817 +av.libs/libxcb-5ddf6756.so.1.1.0,sha256=nz68rypdEQsDEmaH2ocFH-QwZNYysTsgNNemRzthsYo,300553 +av.libs/libxcb-shape-7716c890.so.0.0.0,sha256=p0ZLLGuxNhoN5cno5pGLrVxaxgKbVfbUtZyHheHoikA,29969 +av.libs/libxcb-shm-0be6dfbf.so.0.0.0,sha256=ilL8Pu1J7Su0yGtafQImUnCB1BHUvpP7I67vH8ovsDE,29569 +av.libs/libxcb-xfixes-6de855b8.so.0.0.0,sha256=-dMxLTLj_NSQgTaMxs9fUuhKumupp4o9mX4moTLZoU8,65817 +av/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/__init__.py,sha256=y_DGbgqK5TVi2hJFsYWuktlvXr7t_q6535KRVuCvxM0,2284 +av/__main__.py,sha256=x6yMMfLGUHLly2_PlYwsHr1fsZIvaauzPVe3ZAVAuCM,1568 +av/__pycache__/__init__.cpython-312.pyc,, +av/__pycache__/__main__.cpython-312.pyc,, +av/__pycache__/_core.cpython-312.pyc,, +av/__pycache__/about.cpython-312.pyc,, +av/__pycache__/bitstream.cpython-312.pyc,, +av/__pycache__/buffer.cpython-312.pyc,, +av/__pycache__/datasets.cpython-312.pyc,, +av/__pycache__/device.cpython-312.pyc,, +av/__pycache__/dictionary.cpython-312.pyc,, +av/__pycache__/error.cpython-312.pyc,, +av/__pycache__/format.cpython-312.pyc,, +av/__pycache__/frame.cpython-312.pyc,, +av/__pycache__/index.cpython-312.pyc,, +av/__pycache__/logging.cpython-312.pyc,, +av/__pycache__/opaque.cpython-312.pyc,, +av/__pycache__/packet.cpython-312.pyc,, +av/__pycache__/plane.cpython-312.pyc,, +av/__pycache__/rational.cpython-312.pyc,, +av/__pycache__/stream.cpython-312.pyc,, +av/__pycache__/utils.cpython-312.pyc,, +av/_core.abi3.so,sha256=Om8OEqCwO4xCst1GAnRaVkul0iNsuKHQwqIN0qBhCxk,154817 +av/_core.pxd,sha256=TXUAwYD23r5VtNlUJVimz-n1ri2UmDcacXv3CiH4h8g,358 +av/_core.py,sha256=M2OoJt4fkxgYYXNOvbvk8OsV4D7dd3gv0TZhs10_3wA,1945 +av/_core.pyi,sha256=FAlEwvbG4HgiXmupnWpi1jebTWRqVvE8QFOTxZhqbp0,251 +av/about.py,sha256=SrT8bVZ04pLzmtF4bcRDj0VseCQU-29Nvhmvj8hqR7I,23 +av/audio/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/audio/__init__.py,sha256=cKjwtg1eO9LUrcUit-ELFZH1wVtPv8NFLpiyufJA680,91 +av/audio/__init__.pyi,sha256=krocmgFQBhOPCU9SphYLktfiz3KvNCGhFznzCcyAzGQ,2028 +av/audio/__pycache__/__init__.cpython-312.pyc,, +av/audio/__pycache__/codeccontext.cpython-312.pyc,, +av/audio/__pycache__/fifo.cpython-312.pyc,, +av/audio/__pycache__/format.cpython-312.pyc,, +av/audio/__pycache__/frame.cpython-312.pyc,, +av/audio/__pycache__/layout.cpython-312.pyc,, +av/audio/__pycache__/plane.cpython-312.pyc,, +av/audio/__pycache__/resampler.cpython-312.pyc,, +av/audio/__pycache__/stream.cpython-312.pyc,, +av/audio/codeccontext.abi3.so,sha256=JHpuGj_NAHZmRun-kj0NiYq_lhfIRJsch6xKVzktQZ4,334721 +av/audio/codeccontext.pxd,sha256=Yf6KxyJRo33v_ceKrqlk404otGtTvxZY-q3W_TISF6M,334 +av/audio/codeccontext.py,sha256=7Fx2KGRaXu6xVQ5NlwRWg8aiztvav5IJcDnJ_oMsUxU,3158 +av/audio/codeccontext.pyi,sha256=LkpAxJE_7j2gKmjBxwewgOZBCHQ1gzsGEUadsT4ixQs,1041 +av/audio/fifo.abi3.so,sha256=zJ6nxJCsy9La4Vjvikah4z4xp6BO2XnFHueull_JJaQ,503033 +av/audio/fifo.pxd,sha256=ZTO40EMP15fO1Adm34Qh4TzgQDXeVLLAn08DQlF5Q9c,461 +av/audio/fifo.py,sha256=AU6qTSJjPYVNI0icFuatilSeD5jbk9FlkD8nNLq2UfA,7197 +av/audio/fifo.pyi,sha256=I_nzPMFexnhzLcPZVjFQvIMevxrEHsEQxSjKmBdvh4E,712 +av/audio/format.abi3.so,sha256=FYNpm1irEhI_tGb70kHIK_1u31uwBSCqfvlV0APHflM,220209 +av/audio/format.pxd,sha256=vDyHNUlO76PM9Yo8mMxMxJPsa2KRJg4d9_Klq84PNW4,148 +av/audio/format.py,sha256=2kB8ndKkELpN7E803KnY13Q1DD0JiQAvYmqezKhdKqQ,3629 +av/audio/format.pyi,sha256=SrRDgZkJ8kzKtywq2htlbJKK3d2ae9PIL-Qcnyoui8s,236 +av/audio/frame.abi3.so,sha256=0cjzmGqgXLTz-bXoQK0T28zjGYno0Hl9ZRa0xW25Dc0,659097 +av/audio/frame.pxd,sha256=yRuyThzIm-1HI5qCGAQkhawW77vKaDTADBfb793C5Zc,739 +av/audio/frame.py,sha256=fnb0JQdkUT8rGt2U69rEYhRHtumVrvNmylQWZjR5_5g,6101 +av/audio/frame.pyi,sha256=3OTHyah_8yL4R2PXABt12J3w7V_3Zf-BJdWxnJZKD7w,1410 +av/audio/layout.abi3.so,sha256=tNd67rl-OLqhsTdtqVDGdAlKJ80kEOCLo3J3OdSyfo8,392873 +av/audio/layout.pxd,sha256=YQDkPvukGLIRgvHmWFpMKYCqyYWbpMZoQdGmMuy9peE,148 +av/audio/layout.py,sha256=9X-epVscUsJn44i7QDpB9MP7x08XjWyPYRl6DI_e0X4,3227 +av/audio/layout.pyi,sha256=cc0Y9RCsei824HWwZUt00tYAus92FKgIHuUk07lpEZw,250 +av/audio/plane.abi3.so,sha256=10Z7Mzw43uwokegQNQRIp9y2QLMXyKF-YR9X4DW0yzQ,281377 +av/audio/plane.pxd,sha256=H1vKYhmpwMOlz47ba0HeeMamzgeFfvxX7y_M1fZqrr0,132 +av/audio/plane.py,sha256=7tPNSBKjRk5q4zqciYZr8TPFsXL7d_Afs7gAlvaHfIk,421 +av/audio/plane.pyi,sha256=84IuSlDcyAhLh1wR-QPer4s0mfFVvF-yc88v0qfPntQ,74 +av/audio/resampler.abi3.so,sha256=tb-f3oP2Slh1ILDMCMtTdIhGcCq3K7e2IQw6tMyzrnw,552377 +av/audio/resampler.pxd,sha256=xUcsnas6rvyse1Czf6ZIC3wQKOJxZ9dyACS_PpdOT5g,521 +av/audio/resampler.py,sha256=OHzVxRVCT--Av7aF1nro7EG1NVwUdB0TDOkihyuyYBg,5017 +av/audio/resampler.pyi,sha256=4gC_VXC1lx9l81CfXBo_clvN6W3I6XqqZBaHTDBnd5U,641 +av/audio/stream.abi3.so,sha256=iGgsYVLi1QF_fdIEEmqjQNInjV_3R_dJS_XBP8xqC4A,330729 +av/audio/stream.pxd,sha256=E38lNdZrVkiNbVLUJo8sgqFLQYb_UVTjOLmhM-cjbbg,209 +av/audio/stream.py,sha256=B7eykBcEJuOlxLu9Xmi3UmRv8NNqjOe8_o7f89x7F-w,1778 +av/audio/stream.pyi,sha256=9OcxV5qNCwxGBN1vrommvbMfDwHtuumEPsujVw2ysbI,989 +av/bitstream.abi3.so,sha256=EZc2UCkl45SbxDJkoN2fuCTy3ARoEW6YB7lC_dsWDRs,289809 +av/bitstream.pxd,sha256=hi30kwIdgdCQEVjtUqXo2L4gioHU_1_yWgKu3SqCgTc,184 +av/bitstream.py,sha256=GeBLkCH_XUykojZ4js2ja_ppOn4Qv9Hdd2OzQUw88Ss,4331 +av/bitstream.pyi,sha256=i0pGrCTKvJFsGpoaGIQFHjfgD8dz2vO8g6nhy8ZvjT4,428 +av/buffer.abi3.so,sha256=jUTgA0DH-9GdH97X7Si1oQvpUVHD7_HVE5FyKYPnn04,335097 +av/buffer.pxd,sha256=KYPVOIDVZ-RTj-tSPRrYxyGIgrekKXt3kQSquZb6Ycw,363 +av/buffer.py,sha256=2cUibrqxK1jPPYAqehLzYY8RYplDdpHsMRDxBzAosvM,2900 +av/buffer.pyi,sha256=0JCfkCBhhP3a3-_1AIhMf4sbNYJ1Uyy8GOrQ5-U4EVs,316 +av/codec/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/codec/__init__.py,sha256=VXo6RkJOL8ro7cPgDHZ62x3TqdGqmZcNX3fkVVf7lbM,332 +av/codec/__pycache__/__init__.cpython-312.pyc,, +av/codec/__pycache__/codec.cpython-312.pyc,, +av/codec/__pycache__/context.cpython-312.pyc,, +av/codec/__pycache__/hwaccel.cpython-312.pyc,, +av/codec/codec.abi3.so,sha256=oEO55oYPoR6bKQGqEYd53zd1VK1yhk-QNjZs-ScEXpw,671609 +av/codec/codec.pxd,sha256=0yZubvg-MpyJ4t2JalN-BIxKB_zJM1VcG4s3iZpy_Is,263 +av/codec/codec.py,sha256=Nit9A2K6kMT5N_Ey1fZFlPOdWYCoQXejeRHpsap_KyU,14405 +av/codec/codec.pyi,sha256=EBRA9NzGKPNvHjFqFKaZ6XYLll8CXki6Uh4feWTdw-w,5220 +av/codec/context.abi3.so,sha256=F-nEHhp_-d6CYitKjf3KiZ3gH9lc7DQJZb7sBR5Kbw4,1417673 +av/codec/context.pxd,sha256=ls1PNL1alPUR5pgoZgU5FPRZn3H2x3pyarHrDqCAwHw,2619 +av/codec/context.py,sha256=iXrjzHgK24iSVCGz5zAJ75W5cQBLoseprFsleVe4tjA,33835 +av/codec/context.pyi,sha256=r-S3UALuTFmqXSG-AhUF5eJOFHDEm_WOj2Z_ykmNVt4,5441 +av/codec/hwaccel.abi3.so,sha256=TpW4317X5fDdB28eUb_6aJJIvE8yF8_mxU8wso0UVcE,659225 +av/codec/hwaccel.pxd,sha256=TkULWTlVpZLOh1jO4BsoqsXy-5WNVXsYWYLR0G_UmWQ,595 +av/codec/hwaccel.py,sha256=DlKnz91F2geCecZC85Mbc0h16JKF7b_NIMLQfKAeA4E,7810 +av/codec/hwaccel.pyi,sha256=YNfr_g0uAUACw7sYGXIT8-rPD_A4p0kbinuMSg5Wjyw,1528 +av/container/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/container/__init__.py,sha256=_GTpNeXz0bo93otTZ3v6fhS9238ZjOobn3CRQv2dd94,148 +av/container/__init__.pyi,sha256=OvEGnWBxXGuuGVG9n8raY8mfhsO5JKM7PiG9NF1xHzQ,63 +av/container/__pycache__/__init__.cpython-312.pyc,, +av/container/__pycache__/core.cpython-312.pyc,, +av/container/__pycache__/input.cpython-312.pyc,, +av/container/__pycache__/output.cpython-312.pyc,, +av/container/__pycache__/pyio.cpython-312.pyc,, +av/container/__pycache__/streams.cpython-312.pyc,, +av/container/core.abi3.so,sha256=0P_CSZA7aLArbQT6-53J4zl3nboZPqgdcltT-CiC-3E,1052985 +av/container/core.pxd,sha256=syRapDhoJUzeF5CNmz7PBAu4e7cGAi-vp2PVmtyv0rk,1353 +av/container/core.py,sha256=rd48vzvWAahutdjretWWlmMnXXGvrypqOwqvh0guDdI,22339 +av/container/core.pyi,sha256=SCpdf0ycMoSO8D5_3w_pigudu1QsoFn9uHzBI_gt96Q,5332 +av/container/input.abi3.so,sha256=nDbUXC70KTaLfohq-_j8mZ2OFad-W2RCtt9AFGavhCU,679929 +av/container/input.pxd,sha256=57CHqOcDRcXRvPinfLwG8Z83FI3hjGGTT07SDQqNMws,162 +av/container/input.py,sha256=EpRjtwXCE3Ut2y4-2omcM5uJRtNxm5wW3gBhunPi3N4,12558 +av/container/input.pyi,sha256=BfL74QUJdxkWGD5XBz_YLNLdYI9WYEiv6gWMqKoZfuY,3099 +av/container/output.abi3.so,sha256=sAukyweDx4Ifi5m1dxRwxKLpSF0naCUXn5lGNO5U6j8,1118497 +av/container/output.pxd,sha256=NyEjUdWr0tlMVuERgYOobF_jMSFa0Rj3NYgb_TFXTQQ,435 +av/container/output.py,sha256=LJYDY-4BNatZP1wDgJFHfwCW-lZO_MJN7dCH8Fjyfuo,28219 +av/container/output.pyi,sha256=HSL2a6Vmr1Swv1GYiW_vV_VdIQGmZR2ZiNFrCww0kfY,2479 +av/container/pyio.abi3.so,sha256=CyfUPj0ukYmFABnQyk7LelznXhgse1youMiJMs4-A4M,380041 +av/container/pyio.pxd,sha256=I3Cd0bbzKGcorFU4c2bzK-66lRjUMfjGPQTBBE4bt_U,732 +av/container/pyio.py,sha256=Nn_xKRcAOQ_gRCM1_Uj21O22ENbffiuIkFWstZTSXoQ,6341 +av/container/streams.abi3.so,sha256=y2wJjDqqi8MGjcaABE48gfwA-nEJkwzTCGA_xHWlTGw,655001 +av/container/streams.pxd,sha256=iHkTkzM1Ybs6VIuRfPuRkXFK1gayI3li95G-euLEmSY,151 +av/container/streams.py,sha256=SXNaQGLV6DT4MkU31TbFz7CCTGKLx0r4fm4Ly2v1s8A,5321 +av/container/streams.pyi,sha256=nZVx1T4ItyjTSbGKkJ_FBhda2qvQDBq7qupHOY-pS5Y,1167 +av/datasets.py,sha256=V7wpGle_8AQeT8_0CSeGWNhLSjShyY-JBSIRau7H19c,3004 +av/device.abi3.so,sha256=y_C1kGySE4PdBUfQ49HUWXtRVGgtj-JwCv1SDlKlJys,585585 +av/device.py,sha256=HBpdY2GDcrq24V3R4UYn6kumlOIhJTOJc9Euc6RiHRg,6334 +av/device.pyi,sha256=Ak39HPSoHGutW2UYt6_kxcZU7izvegAZf8axEOpv208,516 +av/dictionary.abi3.so,sha256=OhITplZRbGGXl-5Cc7QWnRIhVxfsOeZpQ3_tW3ekrK0,474817 +av/dictionary.pxd,sha256=zNNJW_zfBKILR23fwcUffhXjK2SFS316H_bbbKGOa2Y,168 +av/dictionary.py,sha256=odsCuz3YOn21-I0IaX4tCPQ9bZ28xOWM9VF25O3Ehbk,2299 +av/dictionary.pyi,sha256=CwPhD0aj38z-AMxERB7QfLcz_UQ2xYe-mnc-alZK8AU,614 +av/error.abi3.so,sha256=G0Lp6yeBQkaGngSk37qbmx7wOuVouAkDXiZCEjqu9CA,946041 +av/error.pxd,sha256=pIFybV6fBCAI3IveFVMnEv_9S_f8xv1ZCwRYHvbLaVQ,88 +av/error.py,sha256=KYWzLtJndYi5Wp_n8E-qlsaEjDB9jym4tdmerxMOHc0,10516 +av/error.pyi,sha256=ohKxnWMullPZ8ntE2inFQ7FrGNmitxNxFWW3Q3hdYDc,3213 +av/filter/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/filter/__init__.py,sha256=3PhVQg5b52PMmAaJf2pmMKbScTvo7cvKSa_1Zprd0gk,117 +av/filter/__init__.pyi,sha256=Jkfg79hkGdMuvHM5_rIK_YyP1flJJqlpSrV6w-znzig,90 +av/filter/__pycache__/__init__.cpython-312.pyc,, +av/filter/__pycache__/context.cpython-312.pyc,, +av/filter/__pycache__/filter.cpython-312.pyc,, +av/filter/__pycache__/graph.cpython-312.pyc,, +av/filter/__pycache__/link.cpython-312.pyc,, +av/filter/__pycache__/loudnorm.cpython-312.pyc,, +av/filter/context.abi3.so,sha256=HapHWijFa71fHykNYEi7olkJehz94okbJFK8YwM57jA,1638961 +av/filter/context.pxd,sha256=smnvm3jgnuzkj1BdmPUw3jIHMUBWYDSslidFxtR3Hoc,414 +av/filter/context.py,sha256=vnU5EVUwZmqD0cf5L7EmHtOiSRuDZQgoMgiZkhmZ8HM,6389 +av/filter/context.pyi,sha256=Mm1IwQXDdSoQjnebdIE5EDInxWHWj9HPDNSbFrVtOzg,559 +av/filter/filter.abi3.so,sha256=YIkebAD-KspSFwhYbdgUh9iQBtjARG2_eGUbGZryK1A,224129 +av/filter/filter.pxd,sha256=5w87wK9ugRAc8qUHPJ5f-iB0MW3aIHXk1BiaF4jqTNM,175 +av/filter/filter.py,sha256=h0OMjEcDdu4hCdP2fEuPj-V_1IPmAgTkr1MYRzmVZAc,1639 +av/filter/filter.pyi,sha256=Poi6pctZayAf1g23SAzu8LqZCXUuzn74Zv7m966YL58,141 +av/filter/graph.abi3.so,sha256=CUPm3Fl84i5Ep2Bb6DlAh8__7Ll_Wo-NxCDohpAvicA,847633 +av/filter/graph.pxd,sha256=wfx_P3AfcjnoFpDXkSmZY6zyWSu2bB98vmb36SOy33k,690 +av/filter/graph.py,sha256=nAC8ViPGFIyfplel_-kVc53K8GZAxdhfg08XF5uvSII,10578 +av/filter/graph.pyi,sha256=GWS9bps9W6S4778HcCl-j5Vnzp-ggl6avo2ZM6duuQo,1705 +av/filter/link.abi3.so,sha256=TmgCB9e_E4nrfDwIL0d8F_9kXVfJ5PhyYKSlyPldIb0,425225 +av/filter/link.pxd,sha256=qyA9oQF1M975aafIF1X5JpD6TW-3R8B8VTHckbQKEZU,786 +av/filter/link.py,sha256=1B1NxHGhCUvbsBEm9MLN7olyqvvgQRWBpnwhcGg1NI0,4541 +av/filter/link.pyi,sha256=UtgqwA_9EV5w311swXpS9pwZzruTl-nHtU7-hpEt5u4,27 +av/filter/loudnorm.abi3.so,sha256=dz6Mhw8dI8V18ibizu7byJ_lEvwQW3y58Th71VNMAU0,306665 +av/filter/loudnorm.pxd,sha256=mrKiGSe6WnIrMkDJU8uj1fs0Iwz_kxFPDL_NmnveyUE,464 +av/filter/loudnorm.py,sha256=OuTHzqHjkKOkOcKP3Pus2SXr_Giw4ZwaDToHxo5sfvU,1439 +av/filter/loudnorm.pyi,sha256=N_HuXpQlTaZLpnKjfqMk68ac3djymdy3x_9en33sA74,106 +av/filter/loudnorm_impl.c,sha256=iLbWh8uCbYqzycoeTwB2VECCI8mOhgIh-ZMvSbRBd6A,5597 +av/filter/loudnorm_impl.h,sha256=QmUqnvobMbPSmas5haev86WCVAs_a6iXaAZPwx-iVAk,240 +av/format.abi3.so,sha256=F3C16gHPiu1R819M4dGsaAkUm6T0BgyLcOSimPfcY-w,310425 +av/format.pxd,sha256=VbCPLqdb49zGSiOdyc4nk1IQA7JD1VChFyshmjV8mu4,258 +av/format.py,sha256=7bz0zL_-2EjpQUR1Hg0qkJkIwo0kZEXHpGvIU7DXV4E,5571 +av/format.pyi,sha256=dh49OMLec0IadFEiQxZ0-VKyu9eP0NDI1yDk8HrU6RY,1403 +av/frame.abi3.so,sha256=7gCVa-wX8S7ggjSrlJNGbRaJZHg61cBwiUW_NKWw_0A,367761 +av/frame.pxd,sha256=MdtAffABVLDFi_c5oQFm3lT-n6xVbya8IBEsppbf6tU,411 +av/frame.py,sha256=AI6Z_vmhfcFHhxhKt-njsgpi9UZ-1rIoONaMvd753vc,5997 +av/frame.pyi,sha256=CB7L3hNr7vJJ1AR4OGfjy2LPiUqJSs0jJ-DT1c-iErc,592 +av/index.abi3.so,sha256=0SUE3PSxQes8cYmlXGI_p5XaMkTztXtnUESLz6EVLWc,552721 +av/index.pxd,sha256=rPkSQuLLTZfmLFnRCzhEoj_y1WIDsflw2zmMy2YNCIw,290 +av/index.py,sha256=E_SscIwgHeKGTbZk1ywpuMdreK1i8w-QQCKA5Xvb5k4,4288 +av/index.pyi,sha256=sNFx1wHKbP6MUt2xgXPS_1NGzxnXJbbBI_b8Kvtllhw,586 +av/logging.abi3.so,sha256=BpI9gapvvMwpf8jdAIfvlkUwdsYcC6ul3sRnqo15dBE,646969 +av/logging.pxd,sha256=tFpeiXuAHyp6bhB0pBnmpHqG3gL3mXW4pNl6SSXQeNI,319 +av/logging.py,sha256=oT3tkaIeimk5kmai-X-xw7LamKRksqB7gwFFjhqA_XI,10382 +av/logging.pyi,sha256=LA3GF09sTd06CJX2tqp43uuwZj7a60z9ZSHWX2aGXiA,912 +av/opaque.abi3.so,sha256=vfbE8fh0I_EWLmcpSMcg-7H1OFdqXFZqgtg2qqA0h6s,220081 +av/opaque.pxd,sha256=vRgs17rMhB8CuiZ450z30WmSi6VMTiirDQr8ykLPwJs,236 +av/opaque.py,sha256=ORPtcIQoFO6P5YRTOwUJm9endDNcVyqCt88i7JlX1lk,1718 +av/packet.abi3.so,sha256=y65WYM50vE9sLs6wwEJCMSKmUiWYgY4GZ_7wSZT2hX4,905273 +av/packet.pxd,sha256=7L5wqv7vzE4yZUwAAcducxIdIVMvVXrqSKprNrTGiIo,561 +av/packet.py,sha256=rjg3aG8aWyQK8xxlI1A1HrETAp7gMQQmBkYa96QWeNU,14897 +av/packet.pyi,sha256=OpXSjfa3bax118lckZZDjBYm1E6dN16wYjM-1wPDt28,3355 +av/plane.abi3.so,sha256=avrRnUh526P1DVcLrPKDPg0wOluydrMdpzWoXoq2Z2w,297817 +av/plane.pxd,sha256=eOzjPaCDVvvaygHiTXmm477_bmwZZ5bDo4gqKZczvxE,194 +av/plane.py,sha256=FFCfzCS3XmzjQuHjFhmWWtPkoxMIirsz-O980CGn-nQ,626 +av/plane.pyi,sha256=qJLw7M73ekThXf05LqTllf1BLIfF3gckxEy6rEjKx4U,169 +av/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/rational.abi3.so,sha256=FsW5WdDWpXwfbpSHpRvYt8ex7DVNsLTYuwV30FmX7JA,519337 +av/rational.pxd,sha256=v_Jf-CcWKUhWP9e1iOPEfMcdsIn0UnGiE-jQ0s4wU7A,184 +av/rational.py,sha256=BeyWFxwwdfxB4vr25_w5utuXso12e9vEKdxn1WkwPZE,4846 +av/rational.pyi,sha256=KX0tlSLFdO5Uuj0tgD2fuiXzokS8nQSX-gAQGqtGWYg,1221 +av/sidedata/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/sidedata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/sidedata/__pycache__/__init__.cpython-312.pyc,, +av/sidedata/__pycache__/encparams.cpython-312.pyc,, +av/sidedata/__pycache__/motionvectors.cpython-312.pyc,, +av/sidedata/__pycache__/sidedata.cpython-312.pyc,, +av/sidedata/encparams.abi3.so,sha256=ho13GVs3YAW_bKQJRO7djJA9DLOraAzv5AC9iMiuOOI,511201 +av/sidedata/encparams.pxd,sha256=1ovAOjIZKwCm9KV_lxtY9kmUqNuuwmWI0nktf4hiRe0,181 +av/sidedata/encparams.py,sha256=Xg86RTjso4gXAwaIdSHmvOjO2VuBrWG5wUJadWbfVvE,6047 +av/sidedata/encparams.pyi,sha256=BebTdGqqzNLY8_7hkrW2poXWMuIeY4O-kBSXVvh0mUo,571 +av/sidedata/motionvectors.abi3.so,sha256=-otIBcMINC-VwcFuwo7dNztDHvqrNU9baAk4gJCMJ0M,626409 +av/sidedata/motionvectors.pxd,sha256=QetgIOGElsOMJokp9KIvYM0pH2L8x5cR995HaNZc1Eo,269 +av/sidedata/motionvectors.py,sha256=Toavw_91yx92lleFT8U0FZowmeQSN3k95wrrIQkL0uU,3557 +av/sidedata/motionvectors.pyi,sha256=p_9dVgneh52OdrdK4CRdZYg2ACZHrlRwEcbrbLH3rqA,536 +av/sidedata/sidedata.abi3.so,sha256=ugAF28yvR0boyokp6ih6EEzIYj7V7AMMWvM-qLy_kWI,544161 +av/sidedata/sidedata.pxd,sha256=OWx1tWeGoYHPLgRzFZbVBAe9WPHvLSeDVv4Wd5Q06AY,447 +av/sidedata/sidedata.py,sha256=2Jz0AqJ6vPQGfaqtF_KF3zgzlchOxFnv6OtuUtfivRA,4664 +av/sidedata/sidedata.pyi,sha256=U-A3gwDtdA-A0Fl8E0egyWM-XuX0VVReDoZ1-8YktQU,1969 +av/stream.abi3.so,sha256=ELmPnO4tx1HAsfxJS8lctnTuByNcUM40PYkMOCtyzx4,585065 +av/stream.pxd,sha256=8Iwre4dMibdmkH0ncZVbtZFqPxOLVIxf6R298FJ38Qw,820 +av/stream.py,sha256=9mdEYLjp96H92ZfBLb813iKC0knG1GeQAk0QYfOgJ6M,10203 +av/stream.pyi,sha256=7frqrvvwTOk6ImtQ_iKsdep0wW1_FlVMjAopeykKjUY,1966 +av/subtitles/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/subtitles/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/subtitles/__init__.pyi,sha256=Nm3uXOcN2bcpMjdlAXtwWLlMIVpmVMRRcL9rJCvPF8E,318 +av/subtitles/__pycache__/__init__.cpython-312.pyc,, +av/subtitles/__pycache__/codeccontext.cpython-312.pyc,, +av/subtitles/__pycache__/stream.cpython-312.pyc,, +av/subtitles/__pycache__/subtitle.cpython-312.pyc,, +av/subtitles/codeccontext.abi3.so,sha256=dCf58DRc1-iSunL2b2TSmhc7f5vvjJLWOecW49BU7-8,314305 +av/subtitles/codeccontext.pxd,sha256=HxtJUUihVM765_2DOYbLW25SNiyczTXYxuJXeVdjU-E,233 +av/subtitles/codeccontext.py,sha256=pMfTr6N6-GoAd6WC8nf--72Kyq98-ea-03iUzGIMLik,4741 +av/subtitles/codeccontext.pyi,sha256=HcPuzR5BuwD0Ph4OnUHfIUXJFqeuN6pjo1N0886v0ao,385 +av/subtitles/stream.abi3.so,sha256=UOO4OGIVIpc3lCe3q8ws5MmPHR3ibBkmv-XWJUMDNmU,256777 +av/subtitles/stream.pxd,sha256=Lo4RBTTOWErzKgNqc07AoNDaAgkUsF_Q25DJaAIo52Y,137 +av/subtitles/stream.py,sha256=VNULPgt2OfrzwTLwC0GoFP92YSgmM64AtsPqippERVM,686 +av/subtitles/stream.pyi,sha256=-MNPQeqPG4dMUzIfB6Xv9lFvNZSl8KyyO4RiHrmfybk,431 +av/subtitles/subtitle.abi3.so,sha256=kKTCuRlpfE2ezoT_cujkpP7EmeaZdXkcN6JvEUvKyQc,970465 +av/subtitles/subtitle.pxd,sha256=N_QwXo5kimdZY-T2SxIowRkqiD38qHA4MEjOaZD619A,590 +av/subtitles/subtitle.py,sha256=nJ7-QMS8jy2JWPG7WoN3p-Q0IupPlCKtCqDVLcHOoDU,10151 +av/subtitles/subtitle.pyi,sha256=msy0Gt2VtGDF_2eYxU-Gqijg3P5u_zc_DIMYvc5VGEc,1011 +av/utils.abi3.so,sha256=_JFIgZVBdasU0ajPPImPekqSFcU_mHUJWft1WTDAGoY,232329 +av/utils.pxd,sha256=NGyU6Ve4JWjw2Epk0-8se5D3FRUm56VhL72j-V6AJiA,366 +av/utils.py,sha256=F1DNSuNIRbtF9-1blgXPKgBlCVSCPpD3vPFyGvnify4,2008 +av/video/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +av/video/__init__.py,sha256=Vq396L7PMjMhTDhvFZPbcLqU9mgdAR82NWk1K08QH64,91 +av/video/__init__.pyi,sha256=C2nYm35O8Gt7lYgbHzs2E6UjfleXaFEBtITUV7G5Z-0,3051 +av/video/__pycache__/__init__.cpython-312.pyc,, +av/video/__pycache__/codeccontext.cpython-312.pyc,, +av/video/__pycache__/format.cpython-312.pyc,, +av/video/__pycache__/frame.cpython-312.pyc,, +av/video/__pycache__/plane.cpython-312.pyc,, +av/video/__pycache__/reformatter.cpython-312.pyc,, +av/video/__pycache__/stream.cpython-312.pyc,, +av/video/codeccontext.abi3.so,sha256=bYHJs1DPU9Jgl_DXyHO6AvcAzjdClbLPCDXxZRhBxIs,691369 +av/video/codeccontext.pxd,sha256=jjYYT4W25PdNv-ndmk8_39rYyFlROPSanQEddTukgu8,941 +av/video/codeccontext.py,sha256=xULTUf6YmsKpNBikwgvyToozrhYxVjBwVHExMYxKw78,15783 +av/video/codeccontext.pyi,sha256=wJZcgtr1Y9ZDzvATAXX_S1bbuNAh5glpxm0-e-HQ_j0,1175 +av/video/format.abi3.so,sha256=M8SZYUIemc01MlGpAqcRRvIEc2-mLAAE2j2AYcQvvsU,622281 +av/video/format.pxd,sha256=hUqOV0DEGy8yRhfX1e2I246BcBwaGOWrixhNazO2v-g,686 +av/video/format.py,sha256=NzLQ-Ti99j_UJzyRz5YH0qD6yS_8_ufn4zKOpq8kOBs,6173 +av/video/format.pyi,sha256=XGTdOgcr5YMTR30ozRd9A8KC0NZVhXHl5hh9CxDdcjY,805 +av/video/frame.abi3.so,sha256=YO6oXfr5FpODImCU4ZMzXDR-2RyGiwcVXmdhE-Lz_G4,3953737 +av/video/frame.pxd,sha256=oxlQ5j4s6Gl2_kYhoKw-WrTSYmhwldGneftXchHwlLA,917 +av/video/frame.py,sha256=4c--f82XPtbv0pJ5RCQrFuFjVpmV28KU2M_g8iBWwZk,72329 +av/video/frame.pyi,sha256=f-pOIdtW7diDil2E2YmMENSSSSSzcI7f9ToOom_-mkQ,3397 +av/video/plane.abi3.so,sha256=4xs4pHhZrZdsDYvK_hcAT_rj5Anq8DK1RqgYxvbIN8o,572825 +av/video/plane.pxd,sha256=g3qjx6-1cSlBNnFS2Mif4iBkD_VvHA92D_SvbUTd3DY,772 +av/video/plane.py,sha256=aho3BQLa5vxCy-YjTAyKeL_nXI5_kRZfJSt_-zImp-c,13512 +av/video/plane.pyi,sha256=26hYzC63EN31pFyR3GTndf5uYc43vH2zWMaXLS_wMl0,385 +av/video/reformatter.abi3.so,sha256=mEO5tP-f_8oZkQ7n2Fv1gvFcBzOhAJOCtTquHeOeefU,593209 +av/video/reformatter.pxd,sha256=nNqQx2OHNUzcvbynF29dS0yoIMO71qxN54bllWIymjk,1527 +av/video/reformatter.py,sha256=KEsPXtn4Vww736mRf0iiifj3Fp4gYLhhg7JpECvyP9s,15117 +av/video/reformatter.pyi,sha256=l26pG8H6E19agkVVxf9aZmOZC_tbbrF_4YwVlQKDT20,2783 +av/video/stream.abi3.so,sha256=5uhtOrCjkUixej6tbGqsgfvs1tFey_Mgz1VMzy-de-E,478681 +av/video/stream.pxd,sha256=6z65wy60rKFRpN0rjWd4smgnPOd6P6EzNh3umZenD9c,528 +av/video/stream.py,sha256=QkgscvxS_e1UhxKMZB_bgjI_9Fq1NNKGeLcoJins-aY,7108 +av/video/stream.pyi,sha256=JK30Yc2TQ1LtQDK2YYvOb7emtxD6Rg-M5M6uz2QZofQ,1416 diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12448d2cf29daf870b07d7687061630c5c9d95df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: false +Tag: cp311-abi3-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..60fa2439e030a3e73d660335bb0f93033d182c92 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +pyav = av.__main__:main diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/AUTHORS.py b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/AUTHORS.py new file mode 100644 index 0000000000000000000000000000000000000000..1d68e08b1bcf9bcde64e4fcaf1d8c5c3f3094d9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/AUTHORS.py @@ -0,0 +1,182 @@ +""" Generate the AUTHORS.rst file from git commit history. + +This module reads git commit logs and produces a formatted list of contributors +grouped by their contribution count, mapping email aliases and GitHub usernames. +""" + +from dataclasses import dataclass +import math +import subprocess # noqa: S404 + + +def main() -> None: + """ Generate and print the AUTHORS.rst content. """ + + contributors = get_git_contributors() + print_contributors(contributors) +# ------------------------------------------------------------------------------ + + +EMAIL_ALIASES: dict[str, str | None] = { + # Maintainers. + "git@mikeboers.com": "github@mikeboers.com", + "mboers@keypics.com": "github@mikeboers.com", + "mikeb@loftysky.com": "github@mikeboers.com", + "mikeb@markmedia.co": "github@mikeboers.com", + "westernx@mikeboers.com": "github@mikeboers.com", + # Junk. + "mark@mark-VirtualBox.(none)": None, + # Aliases. + "a.davoudi@aut.ac.ir": "davoudialireza@gmail.com", + "tcaswell@bnl.gov": "tcaswell@gmail.com", + "xxr3376@gmail.com": "xxr@megvii.com", + "dallan@pha.jhu.edu": "daniel.b.allan@gmail.com", + "61652821+laggykiller@users.noreply.github.com": "chaudominic2@gmail.com", +} + +CANONICAL_NAMES: dict[str, str] = { + "caspervdw@gmail.com": "Casper van der Wel", + "daniel.b.allan@gmail.com": "Dan Allan", + "mgoacolou@cls.fr": "Manuel Goacolou", + "mindmark@gmail.com": "Mark Reid", + "moritzkassner@gmail.com": "Moritz Kassner", + "vidartf@gmail.com": "Vidar Tonaas Fauske", + "xxr@megvii.com": "Xinran Xu", +} + +GITHUB_USERNAMES: dict[str, str] = { + "billy.shambrook@gmail.com": "billyshambrook", + "daniel.b.allan@gmail.com": "danielballan", + "davoudialireza@gmail.com": "adavoudi", + "github@mikeboers.com": "mikeboers", + "jeremy.laine@m4x.org": "jlaine", + "kalle.litterfeldt@gmail.com": "litterfeldt", + "mindmark@gmail.com": "markreidvfx", + "moritzkassner@gmail.com": "mkassner", + "rush@logic.cz": "radek-senfeld", + "self@brendanlong.com": "brendanlong", + "tcaswell@gmail.com": "tacaswell", + "ulrik.mikaelsson@magine.com": "rawler", + "vidartf@gmail.com": "vidartf", + "willpatera@gmail.com": "willpatera", + "xxr@megvii.com": "xxr3376", + "chaudominic2@gmail.com": "laggykiller", + "wyattblue@auto-editor.com": "WyattBlue", + "Curtis@GreenKey.net": "dotysan", +} + + +@dataclass +class Contributor: + """ Represents a contributor with their email, names, and GitHub username. """ + + email: str + names: set[str] + github: str | None = None + commit_count: int = 0 + + @property + def display_name(self) -> str: + """ Return the formatted display name for the contributor. + + Returns: + Comma-separated sorted list of contributor names. + """ + + return ", ".join(sorted(self.names)) + + def format_line(self, bullet: str) -> str: + """ Format the contributor line for RST output. + + Args: + bullet: The bullet character to use (- or *). + + Returns: + Formatted RST line with contributor info. + """ + + if self.github: + return ( + f"{bullet} {self.display_name} <{self.email}>; " + f"`@{self.github} `_" + ) + return f"{bullet} {self.display_name} <{self.email}>" + + +def get_git_contributors() -> dict[str, Contributor]: + """ Parse git log and return contributors grouped by canonical email. + + Returns: + Dictionary mapping canonical emails to Contributor objects. + """ + + contributors: dict[str, Contributor] = {} + git_log = subprocess.check_output( + ["git", "log", "--format=%aN,%aE"], # noqa: S607 + text=True, + ).splitlines() + + for line in git_log: + name, email = line.strip().rsplit(",", 1) + canonical_email = EMAIL_ALIASES.get(email, email) + + if not canonical_email: + continue + + if canonical_email not in contributors: + contributors[canonical_email] = Contributor( + email=canonical_email, + names=set(), + github=GITHUB_USERNAMES.get(canonical_email), + ) + + contributor = contributors[canonical_email] + contributor.names.add(name) + contributor.commit_count += 1 + + for email, canonical_name in CANONICAL_NAMES.items(): + if email in contributors: + contributors[email].names = {canonical_name} + + return contributors + + +def print_contributors(contributors: dict[str, Contributor]) -> None: + """Print contributors grouped by logarithmic order of commits. + + Args: + contributors: Dictionary of contributors to print. + """ + + print("""\ + Contributors + ============ + + All contributors (by number of commits): + """.replace(" ", "")) + + sorted_contributors = sorted( + contributors.values(), + key=lambda c: (-c.commit_count, c.email), + ) + + last_order: int | None = None + block_index = 0 + + for contributor in sorted_contributors: + # This is the natural log, because of course it should be. ;) + order = int(math.log(contributor.commit_count)) + + if last_order and last_order != order: + block_index += 1 + print() + last_order = order + + # The '-' vs '*' is so that Sphinx treats them as different lists, and + # introduces a gap between them. + bullet = "-*"[block_index % 2] + print(contributor.format_line(bullet)) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/AUTHORS.rst b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/AUTHORS.rst new file mode 100644 index 0000000000000000000000000000000000000000..5238156e216b0832099a71789802a6a468bd27ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/AUTHORS.rst @@ -0,0 +1,129 @@ +Contributors +============ + +All contributors (by number of commits): + +- Mike Boers ; `@mikeboers `_ +- WyattBlue ; `@WyattBlue `_ + +* Jeremy Lainé ; `@jlaine `_ + +- Mark Reid ; `@markreidvfx `_ + +* Lukas Geiger + +- Vidar Tonaas Fauske ; `@vidartf `_ +- laggykiller ; `@laggykiller `_ +- Billy Shambrook ; `@billyshambrook `_ +- Casper van der Wel +- Philip de Nier +- Tadas Dailyda +- Dave Johansen +- Mark Harfouche +- JoeUgly <41972063+JoeUgly@users.noreply.github.com> +- Justin Wong <46082645+uvjustin@users.noreply.github.com> +- Santtu Keskinen + +* Alba Mendez +* Curtis Doty ; `@dotysan `_ +* Xinran Xu ; `@xxr3376 `_ +* z-khan +* Marc Mueller <30130371+cdce8p@users.noreply.github.com> +* Dan Allan ; `@danielballan `_ +* Moonsik Park +* velsinki <40809145+velsinki@users.noreply.github.com> +* Christoph Rackwitz +* David Plowman +* Alireza Davoudi ; `@adavoudi `_ +* Jonathan Drolet +* Matthew Lai +* Kim Minjong +* Moritz Kassner ; `@mkassner `_ +* Thomas A Caswell ; `@tacaswell `_ +* Ulrik Mikaelsson ; `@rawler `_ +* Wel C. van der +* Will Patera ; `@willpatera `_ + +- zzjjbb <31069326+zzjjbb@users.noreply.github.com> +- Joe Schiff <41972063+JoeSchiff@users.noreply.github.com> +- Nils DEYBACH <68770774+ndeybach@users.noreply.github.com> +- Dexer <73297572+DexerBR@users.noreply.github.com> +- DE-AI <81620697+DE-AI@users.noreply.github.com> +- rutsh +- Felix Vollmer +- Benedikt Lorch, benedikt-grl +- Santiago Castro +- Christian Clauss +- Ihor Liubymov +- Johannes Erdfelt +- Karl Litterfeldt ; `@litterfeldt `_ +- Leon White +- Martin Larralde +- Simon-Martin Schröder +- Matteo Destro +- Mattias Wadman +- mephi42 +- Miles Kaufmann +- Nathan Goldbaum +- Pablo Prietz +- Andrew Wason +- Radek Senfeld ; `@radek-senfeld `_ +- robinechuca +- Nick <24689722+ntjohnson1@users.noreply.github.com> +- Benjamin Chrétien <2742231+bchretien@users.noreply.github.com> +- 吴小白 <296015668@qq.com> +- davidplowman <38045873+davidplowman@users.noreply.github.com> +- Hanz <40712686+HanzCEO@users.noreply.github.com> +- Clay Castronovo <42858023+clayy24@users.noreply.github.com> +- Kesh Ikuma <79113787+tikuma-lsuhsc@users.noreply.github.com> +- Artturin +- Ian Lee +- Ryan Huang +- Arthur Barros +- bdavid-evertz +- Carlos Ruiz +- Carlos Ruiz +- Maxime Desroches +- egao1980 +- Eric Kalosa-Kenyon +- elxy +- Gemfield +- henri-gasc +- Jonathan Martin +- HotariTobu +- Joshua +- Johan Jeppsson Karlin +- Kazuki Oikawa +- Kian-Meng Ang +- Philipp Klaus +- Marcell Pardavi +- Matteo Destro +- Max Ehrlich +- Manuel Goacolou +- Julian Schweizer +- Nikhil Idiculla +- Ömer Sezgin Uğurlu +- Orivej Desh +- Philipp Krähenbühl +- Mattia Procopio +- Max Ehrlich +- ramoncaldeira +- Roland van Laar +- Santiago Castro +- Kengo Sawatsu +- FirefoxMetzger +- hyenal +- Brendan Long ; `@brendanlong `_ +- Семён Марьясин +- Stephen.Y +- Tom Flanagan +- Tim O'Shea +- Tim Ahpee +- Jonas Tingeborn +- Pino Toscano +- Ulrik Mikaelsson +- Vasiliy Kotov +- Koichi Akabe +- David Joy +- Sviatoslav Sydorenko (Святослав Сидоренко) +- Jiabei Zhu diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/LICENSE.txt b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..9db1661e7d701c7fd262ed77efc2acc3831e41a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,23 @@ +Copyright retained by original committers. 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 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 HOLDERS 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/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/__pycache__/AUTHORS.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/__pycache__/AUTHORS.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e36eb8704a3f53df2a8ec37ee764aa4e9e98d58b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/licenses/__pycache__/AUTHORS.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/sboms/auditwheel.cdx.json b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/sboms/auditwheel.cdx.json new file mode 100644 index 0000000000000000000000000000000000000000..82b7e4acfe16c28f1be6f44afdefaa31de7b5e81 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/sboms/auditwheel.cdx.json @@ -0,0 +1 @@ +{"bomFormat": "CycloneDX", "specVersion": "1.4", "version": 1, "metadata": {"component": {"type": "library", "bom-ref": "pkg:pypi/av@18.1.0?file_name=av-18.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", "name": "av", "version": "18.1.0", "purl": "pkg:pypi/av@18.1.0?file_name=av-18.1.0-cp311-abi3-manylinux_2_28_x86_64.whl"}, "tools": [{"name": "auditwheel", "version": "6.7.0"}]}, "components": [{"type": "library", "bom-ref": "pkg:pypi/av@18.1.0?file_name=av-18.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", "name": "av", "version": "18.1.0", "purl": "pkg:pypi/av@18.1.0?file_name=av-18.1.0-cp311-abi3-manylinux_2_28_x86_64.whl"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#6c32c0eb1fdae8b53d48bf63b90db8c0dc1591ca2eb752e841996904a55c6e78", "name": "libxcb", "version": "1.13.1-1.el8", "purl": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#62b69720e9664025a12f9971b2872f61b0b8acd3de00cc9ecfe351773c62ed91", "name": "libxcb", "version": "1.13.1-1.el8", "purl": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libXau@1.0.9-3.el8#ac77887fa9a50833ff7a34d7e27ebe243468552bc94f6628693cb1dfdaf102e7", "name": "libXau", "version": "1.0.9-3.el8", "purl": "pkg:rpm/almalinux/libXau@1.0.9-3.el8"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#66bec2d3d7dd69fd6c3ff19cd0da52ae820f936812e127f411c783ca1df43a13", "name": "libxcb", "version": "1.13.1-1.el8", "purl": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#124885c4e4c50f1f62c2e8972a17cf0a611aaab3f5850992677a7161cb660e66", "name": "libxcb", "version": "1.13.1-1.el8", "purl": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libdrm@2.4.115-2.el8#6bf0a77f707216e85f075c14376973902bc63a98d0556326cace0b2199df53cc", "name": "libdrm", "version": "2.4.115-2.el8", "purl": "pkg:rpm/almalinux/libdrm@2.4.115-2.el8"}], "dependencies": [{"ref": "pkg:pypi/av@18.1.0?file_name=av-18.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", "dependsOn": ["pkg:rpm/almalinux/libxcb@1.13.1-1.el8#6c32c0eb1fdae8b53d48bf63b90db8c0dc1591ca2eb752e841996904a55c6e78", "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#62b69720e9664025a12f9971b2872f61b0b8acd3de00cc9ecfe351773c62ed91", "pkg:rpm/almalinux/libXau@1.0.9-3.el8#ac77887fa9a50833ff7a34d7e27ebe243468552bc94f6628693cb1dfdaf102e7", "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#66bec2d3d7dd69fd6c3ff19cd0da52ae820f936812e127f411c783ca1df43a13", "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#124885c4e4c50f1f62c2e8972a17cf0a611aaab3f5850992677a7161cb660e66", "pkg:rpm/almalinux/libdrm@2.4.115-2.el8#6bf0a77f707216e85f075c14376973902bc63a98d0556326cace0b2199df53cc"]}, {"ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#6c32c0eb1fdae8b53d48bf63b90db8c0dc1591ca2eb752e841996904a55c6e78"}, {"ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#62b69720e9664025a12f9971b2872f61b0b8acd3de00cc9ecfe351773c62ed91"}, {"ref": "pkg:rpm/almalinux/libXau@1.0.9-3.el8#ac77887fa9a50833ff7a34d7e27ebe243468552bc94f6628693cb1dfdaf102e7"}, {"ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#66bec2d3d7dd69fd6c3ff19cd0da52ae820f936812e127f411c783ca1df43a13"}, {"ref": "pkg:rpm/almalinux/libxcb@1.13.1-1.el8#124885c4e4c50f1f62c2e8972a17cf0a611aaab3f5850992677a7161cb660e66"}, {"ref": "pkg:rpm/almalinux/libdrm@2.4.115-2.el8#6bf0a77f707216e85f075c14376973902bc63a98d0556326cace0b2199df53cc"}]} \ No newline at end of file diff --git a/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc1ce6e8a1399e86a202114c4837e05d5ee491c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av-18.1.0.dist-info/top_level.txt @@ -0,0 +1 @@ +av diff --git a/.venv/lib/python3.12/site-packages/av.libs/libSvtAv1Enc-9393c086.so.4.1.0 b/.venv/lib/python3.12/site-packages/av.libs/libSvtAv1Enc-9393c086.so.4.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..d4c515821d5f0c1001fca62d13a0abc120160363 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libSvtAv1Enc-9393c086.so.4.1.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cb5f57196143427c5f165f98b88a174e06c592e5a884507f5adcd8b20472414 +size 7061777 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libXau-154567c4.so.6.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libXau-154567c4.so.6.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..ff06a58be7b9ff80cee9b8eb45d5e9a28cf67d1b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libXau-154567c4.so.6.0.0 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libasound-c7818c60.so.2.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libasound-c7818c60.so.2.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..c22c104cf7eb388e6ce70c63c62b5f81d8eb6fc1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libasound-c7818c60.so.2.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5efc17cc5faf758ed1554ed3ac4322e03a43b6b4900decb77002e4694aafa70 +size 1162289 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libavcodec-5e6b81c2.so.62.28.102 b/.venv/lib/python3.12/site-packages/av.libs/libavcodec-5e6b81c2.so.62.28.102 new file mode 100644 index 0000000000000000000000000000000000000000..234421cb6559156c8bf17f228b045d86f1685f07 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libavcodec-5e6b81c2.so.62.28.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0f0b65dd8d194278309dce64a9661040f0f7bd77d0d20733a0d7a06bdb26a5b +size 18795033 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libavdevice-d91b4e17.so.62.3.102 b/.venv/lib/python3.12/site-packages/av.libs/libavdevice-d91b4e17.so.62.3.102 new file mode 100644 index 0000000000000000000000000000000000000000..45fd19cb9f87ff3ce0b6359bad3aed520c4028b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libavdevice-d91b4e17.so.62.3.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f0ef5dace4c9c1ed8c0afd11e78bc6205a3691e8d75b160452345a50a5099ce +size 123897 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libavfilter-b5da520e.so.11.14.102 b/.venv/lib/python3.12/site-packages/av.libs/libavfilter-b5da520e.so.11.14.102 new file mode 100644 index 0000000000000000000000000000000000000000..9ff6691c6cd6059ee41c2af9210f28774b4b358a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libavfilter-b5da520e.so.11.14.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d244d42ea6c2c95e6783b6bd6528f6f7a5e6ed4c8de43f1a95504683846b3c6 +size 5464473 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libavformat-4639def2.so.62.12.102 b/.venv/lib/python3.12/site-packages/av.libs/libavformat-4639def2.so.62.12.102 new file mode 100644 index 0000000000000000000000000000000000000000..864932bef0ee1e27172871120e138638c59763a8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libavformat-4639def2.so.62.12.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b22277398283fb966c8a57fc09a18fe2701fc93ba2bf72364786f330ec94e03 +size 2983097 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libavutil-5809ad29.so.60.26.102 b/.venv/lib/python3.12/site-packages/av.libs/libavutil-5809ad29.so.60.26.102 new file mode 100644 index 0000000000000000000000000000000000000000..e497ab0c20381ad2da7213d15c3bd6fcc6706655 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libavutil-5809ad29.so.60.26.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c59c2d8d1daf0f3956fca1c118c2d885e781a557ce1ac1a6e0441fb83116643 +size 1107705 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libdav1d-f4b27961.so.7.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libdav1d-f4b27961.so.7.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..b1731c8a01a5028e20f11d03ae0825672faf4859 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libdav1d-f4b27961.so.7.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b189e7e042b1231e51cf28eac4f554c8da52a213ca519713dd7c41d9f8498451 +size 2024729 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libdrm-b0291a67.so.2.4.0 b/.venv/lib/python3.12/site-packages/av.libs/libdrm-b0291a67.so.2.4.0 new file mode 100644 index 0000000000000000000000000000000000000000..02907d158f0bbd54243161f297f72a5d5d1bc9e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libdrm-b0291a67.so.2.4.0 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libgmp-8c6c054f.so.10.5.0 b/.venv/lib/python3.12/site-packages/av.libs/libgmp-8c6c054f.so.10.5.0 new file mode 100644 index 0000000000000000000000000000000000000000..7eb86604226d02f0a8ef65b7f531a09a79808620 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libgmp-8c6c054f.so.10.5.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cec82612094e22342d32b4ba22ba582d89b4a68ff8287bb089d27e133dc3a5e +size 511649 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libgnutls-71454fd1.so.30.42.0 b/.venv/lib/python3.12/site-packages/av.libs/libgnutls-71454fd1.so.30.42.0 new file mode 100644 index 0000000000000000000000000000000000000000..38dcfde8a50cb07ce004cbcf5afd4e418d61c765 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libgnutls-71454fd1.so.30.42.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32ff4f97aabf1bf8169619a6caab6630b9087f673c503fefbc76ab4c225386a7 +size 2416425 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libhogweed-006f41d4.so.6.11 b/.venv/lib/python3.12/site-packages/av.libs/libhogweed-006f41d4.so.6.11 new file mode 100644 index 0000000000000000000000000000000000000000..8212c90bc44517e15a5eb8a0e436a5bbafbdfe77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libhogweed-006f41d4.so.6.11 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6071bd4dd44341e035eca4ac2ab1088734e336208e86d746e02784e15ebda9c +size 333209 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libmp3lame-8f9e436f.so.0.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libmp3lame-8f9e436f.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..20abfecd4e5bbeab84a0adb244c15f82f3902f48 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libmp3lame-8f9e436f.so.0.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cc8e470f5644c23f741b7f17f38ba0b95700277836d7b2305280b7fedf222d6 +size 421065 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libnettle-71a806b4.so.8.11 b/.venv/lib/python3.12/site-packages/av.libs/libnettle-71a806b4.so.8.11 new file mode 100644 index 0000000000000000000000000000000000000000..5b931867c16ae2d31a7c80a34a191e3a7a3b01f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libnettle-71a806b4.so.8.11 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a809c4d153cc12d4586fad7f1fc105bd7e6355f7e3b9c71977e186b56e057c1 +size 359649 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libopencore-amrnb-d72c52e2.so.0.0.5 b/.venv/lib/python3.12/site-packages/av.libs/libopencore-amrnb-d72c52e2.so.0.0.5 new file mode 100644 index 0000000000000000000000000000000000000000..7a7320fddac891acf8869beeb84c1e1839c606ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libopencore-amrnb-d72c52e2.so.0.0.5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90c967c4c65c4b88056d96c8869839ddbfa0852da8fcf9c86f70d58f3401b50f +size 172849 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libopencore-amrwb-1b0ca122.so.0.0.5 b/.venv/lib/python3.12/site-packages/av.libs/libopencore-amrwb-1b0ca122.so.0.0.5 new file mode 100644 index 0000000000000000000000000000000000000000..9726e7092127f992b8e6e89338f52a5e7e35d8b0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libopencore-amrwb-1b0ca122.so.0.0.5 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libopus-114e2b1a.so.0.11.1 b/.venv/lib/python3.12/site-packages/av.libs/libopus-114e2b1a.so.0.11.1 new file mode 100644 index 0000000000000000000000000000000000000000..e9f3a20a1cd59755c262f810d939646ba82401ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libopus-114e2b1a.so.0.11.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9694eba9511112aa3296ccc86cfe5df60406833f03b1a56b008e7f0431a51507 +size 433329 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libsharpyuv-48a062bd.so.0.1.2 b/.venv/lib/python3.12/site-packages/av.libs/libsharpyuv-48a062bd.so.0.1.2 new file mode 100644 index 0000000000000000000000000000000000000000..bb1c1ee52d03a76d38d94349e37e847afe573e1e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libsharpyuv-48a062bd.so.0.1.2 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libswresample-f0bc92fc.so.6.3.102 b/.venv/lib/python3.12/site-packages/av.libs/libswresample-f0bc92fc.so.6.3.102 new file mode 100644 index 0000000000000000000000000000000000000000..40276afbcd204a2a8f88ce450e38870702274553 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libswresample-f0bc92fc.so.6.3.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a5ff28fc54bf6bc82356336806e6c242f17dd17ec6677ada3690daf7996a012 +size 154433 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libswscale-88e9f973.so.9.5.102 b/.venv/lib/python3.12/site-packages/av.libs/libswscale-88e9f973.so.9.5.102 new file mode 100644 index 0000000000000000000000000000000000000000..3ba50fbed98be42ca280a440742238bcd19223e4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libswscale-88e9f973.so.9.5.102 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18daf88e06995d62f948bb70677b2f94e8df0f5a42161fd08e9673e62c5ba4f1 +size 2017409 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libunistring-09f6121d.so.5.2.1 b/.venv/lib/python3.12/site-packages/av.libs/libunistring-09f6121d.so.5.2.1 new file mode 100644 index 0000000000000000000000000000000000000000..7ef7d7e1f5b0f60e12dff70cc49b910dd2a26e6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libunistring-09f6121d.so.5.2.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e7e3aefa27e9d5e93c5c0b83b302e12e3c2fcb3a21a05cddf740f2cd2290a68 +size 2037033 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libvpl-e4e9cae8.so.2.16 b/.venv/lib/python3.12/site-packages/av.libs/libvpl-e4e9cae8.so.2.16 new file mode 100644 index 0000000000000000000000000000000000000000..22d5bffa3d955714c4ee159bf435263064e01734 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libvpl-e4e9cae8.so.2.16 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acf0015c9c751e226092366ada140b05e8b31f8120bd443e4494405a6da0919e +size 428369 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libvpx-edb6de90.so.12.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libvpx-edb6de90.so.12.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..4eeeffff86ae1db1df0a666c3c8653e460df7e29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libvpx-edb6de90.so.12.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc87bc3c7c6747f2f76da9ca3f2f557406f536ccce2252d2b013961e83aee087 +size 2344937 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libwebp-0c5118d0.so.7.2.0 b/.venv/lib/python3.12/site-packages/av.libs/libwebp-0c5118d0.so.7.2.0 new file mode 100644 index 0000000000000000000000000000000000000000..f3a8b9d9cf4b520e2a0cfcefe2460222ea31d3a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libwebp-0c5118d0.so.7.2.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2854b0c6a797575d03c67d91b70f5bd2d82d2ce30e62dead4112b1ceebcbfb98 +size 747633 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libwebpmux-e1880640.so.3.1.2 b/.venv/lib/python3.12/site-packages/av.libs/libwebpmux-e1880640.so.3.1.2 new file mode 100644 index 0000000000000000000000000000000000000000..df2688a8c25eebc56139eebae1305318210a89f7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libwebpmux-e1880640.so.3.1.2 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libx264-d6533a8d.so.165 b/.venv/lib/python3.12/site-packages/av.libs/libx264-d6533a8d.so.165 new file mode 100644 index 0000000000000000000000000000000000000000..2287554e8617088b374d3b8f7d1cbb251b06db79 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libx264-d6533a8d.so.165 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5587d2d060914e2e52694e35703a7c8f20f3143eafa956706e089049df3b580b +size 2177713 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libx265-f5385bb8.so.216 b/.venv/lib/python3.12/site-packages/av.libs/libx265-f5385bb8.so.216 new file mode 100644 index 0000000000000000000000000000000000000000..0aed5baf2f32a4f033c615c5ea17743239d5d6f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libx265-f5385bb8.so.216 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e304e1b3b6367e902837b9a00d0bc5b90d83a70e1fbb69b27f34d8c970c4b765 +size 20591817 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libxcb-5ddf6756.so.1.1.0 b/.venv/lib/python3.12/site-packages/av.libs/libxcb-5ddf6756.so.1.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..daf0a33f2e54a1d4a56b65344b9ff82607f02146 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av.libs/libxcb-5ddf6756.so.1.1.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f3ebcaf2a5d110b03126687da87051fe43064d632b13b2034d7a6473b61b18a +size 300553 diff --git a/.venv/lib/python3.12/site-packages/av.libs/libxcb-shape-7716c890.so.0.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libxcb-shape-7716c890.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..02da931d4d22ac4e88485fd716a4ce723b0997d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libxcb-shape-7716c890.so.0.0.0 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libxcb-shm-0be6dfbf.so.0.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libxcb-shm-0be6dfbf.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..2c9e69daefe32fd77b0f50fa47d1607d4dc4f267 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libxcb-shm-0be6dfbf.so.0.0.0 differ diff --git a/.venv/lib/python3.12/site-packages/av.libs/libxcb-xfixes-6de855b8.so.0.0.0 b/.venv/lib/python3.12/site-packages/av.libs/libxcb-xfixes-6de855b8.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..cd612b54ce5c236735c1aa89aaec253c129414e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av.libs/libxcb-xfixes-6de855b8.so.0.0.0 differ diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/encparams.pyi b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.pyi new file mode 100644 index 0000000000000000000000000000000000000000..de962ba512a2056bc90e2944012ff50878305ded --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.pyi @@ -0,0 +1,27 @@ +from enum import IntEnum +from typing import Any, cast + +import numpy as np + +class VideoEncParamsType(IntEnum): + NONE = cast(int, ...) + VP9 = cast(int, ...) + H264 = cast(int, ...) + MPEG2 = cast(int, ...) + +class VideoEncParams: + nb_blocks: int + blocks_offset: int + block_size: int + codec_type: VideoEncParamsType + qp: int + delta_qp: int + def block_params(self, idx: int) -> VideoBlockParams: ... + def qp_map(self) -> np.ndarray[Any, Any]: ... + +class VideoBlockParams: + src_x: int + src_y: int + w: int + h: int + delta_qp: int diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.abi3.so b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..6557d3b2804c22cab99547c26d00d9c811809ebd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa8b4805c308342f95c1c16ec28edd373b431efaab354f5b68093880908c2743 +size 626409 diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.pxd b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.pxd new file mode 100644 index 0000000000000000000000000000000000000000..0786483258c6c7c0c6810f68b58958c80ff7029c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.pxd @@ -0,0 +1,14 @@ +cimport libav as lib + +from av.frame cimport Frame +from av.sidedata.sidedata cimport SideData + + +cdef class MotionVectors(SideData): + cdef dict _vectors + cdef Py_ssize_t _len + + +cdef class MotionVector: + cdef MotionVectors parent + cdef lib.AVMotionVector *ptr diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.py b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.py new file mode 100644 index 0000000000000000000000000000000000000000..369832ba6b607d87c2dfb1c01c5205c7c34a9acf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.py @@ -0,0 +1,136 @@ +import cython +from cython.cimports import libav as lib +from cython.cimports.av.sidedata.sidedata import SideData +from cython.cimports.libc.stdint import uintptr_t + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.final +@cython.cclass +class MotionVectors(SideData): + def __init__(self, sentinel, frame: Frame, index: cython.int): + SideData.__init__(self, sentinel, frame, index) + self._vectors = {} + self._len = self.ptr.size // cython.sizeof(lib.AVMotionVector) + + def __repr__(self): + return ( + f"" + ) + + def __len__(self): + return self._len + + def __getitem__(self, index: cython.Py_ssize_t): + try: + return self._vectors[index] + except KeyError: + pass + + if index >= self._len: + raise IndexError(index) + + vector = self._vectors[index] = MotionVector( + _cinit_bypass_sentinel, self, index + ) + return vector + + def __iter__(self): + """Iterate over all motion vectors.""" + for i in range(self._len): + yield self[i] + + def to_ndarray(self): + """ + Convert motion vectors to a NumPy structured array. + + Returns a NumPy array with fields corresponding to the AVMotionVector structure. + """ + import numpy as np + + return np.frombuffer( + self, + dtype=np.dtype( + [ + ("source", "int32"), + ("w", "uint8"), + ("h", "uint8"), + ("src_x", "int16"), + ("src_y", "int16"), + ("dst_x", "int16"), + ("dst_y", "int16"), + ("flags", "uint64"), + ("motion_x", "int32"), + ("motion_y", "int32"), + ("motion_scale", "uint16"), + ], + align=True, + ), + ) + + +@cython.final +@cython.cclass +class MotionVector: + """ + Represents a single motion vector from video frame data. + + Motion vectors describe the motion of a block of pixels between frames. + """ + + def __init__(self, sentinel, parent: MotionVectors, index: cython.int): + if sentinel is not _cinit_bypass_sentinel: + raise RuntimeError("cannot manually instantiate MotionVector") + self.parent = parent + base: cython.pointer[lib.AVMotionVector] = cython.cast( + cython.pointer[lib.AVMotionVector], parent.ptr.data + ) + self.ptr = base + index + + def __repr__(self): + return ( + f"" + ) + + @property + def source(self): + return self.ptr.source + + @property + def w(self): + return self.ptr.w + + @property + def h(self): + return self.ptr.h + + @property + def src_x(self): + return self.ptr.src_x + + @property + def src_y(self): + return self.ptr.src_y + + @property + def dst_x(self): + return self.ptr.dst_x + + @property + def dst_y(self): + return self.ptr.dst_y + + @property + def motion_x(self): + return self.ptr.motion_x + + @property + def motion_y(self): + return self.ptr.motion_y + + @property + def motion_scale(self): + return self.ptr.motion_scale diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.pyi b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6b9971fb449b70a9494da6239fce25df1d24c965 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/motionvectors.pyi @@ -0,0 +1,25 @@ +from typing import Any, overload + +import numpy as np + +from .sidedata import SideData + +class MotionVectors(SideData): + @overload + def __getitem__(self, index: int) -> MotionVector: ... + @overload + def __getitem__(self, index: slice) -> list[MotionVector]: ... + def __len__(self) -> int: ... + def to_ndarray(self) -> np.ndarray[Any, Any]: ... + +class MotionVector: + source: int + w: int + h: int + src_x: int + src_y: int + dst_x: int + dst_y: int + motion_x: int + motion_y: int + motion_scale: int diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.abi3.so b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..805c58819bf8fcb384f060d66f9144b43943f9d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba0005dbccaf4746e8ca8929ea287a104cc8623ed5ec030c5af33ea8bcbf9162 +size 544161 diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.pxd b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d97903c16df474b7570cb50292ef07ccdc6e02c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.pxd @@ -0,0 +1,19 @@ +cimport libav as lib + +from av.buffer cimport Buffer +from av.dictionary cimport Dictionary, wrap_dictionary +from av.frame cimport Frame + + +cdef class SideData(Buffer): + cdef Frame frame + cdef lib.AVFrameSideData *ptr + cdef Dictionary metadata + +cdef SideData wrap_side_data(Frame frame, int index) +cdef int get_display_rotation(Frame frame) + +cdef class _SideDataContainer: + cdef Frame frame + cdef list _by_index + cdef dict _by_type diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.py b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fa7b0d166398f1d2062ecdbce6b32728dc94ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.py @@ -0,0 +1,135 @@ +from collections.abc import Mapping +from enum import Enum + +import cython +from cython.cimports.libc.stdint import int32_t, uintptr_t + +from av.sidedata.encparams import VideoEncParams +from av.sidedata.motionvectors import MotionVectors + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +class Type(Enum): + """ + Enum class representing different types of frame data in audio/video processing. + Values are mapped to corresponding AV_FRAME_DATA constants from FFmpeg. + + From: https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/frame.h + """ + + PANSCAN = lib.AV_FRAME_DATA_PANSCAN + A53_CC = lib.AV_FRAME_DATA_A53_CC + STEREO3D = lib.AV_FRAME_DATA_STEREO3D + MATRIXENCODING = lib.AV_FRAME_DATA_MATRIXENCODING + DOWNMIX_INFO = lib.AV_FRAME_DATA_DOWNMIX_INFO + REPLAYGAIN = lib.AV_FRAME_DATA_REPLAYGAIN + DISPLAYMATRIX = lib.AV_FRAME_DATA_DISPLAYMATRIX + AFD = lib.AV_FRAME_DATA_AFD + MOTION_VECTORS = lib.AV_FRAME_DATA_MOTION_VECTORS + SKIP_SAMPLES = lib.AV_FRAME_DATA_SKIP_SAMPLES + AUDIO_SERVICE_TYPE = lib.AV_FRAME_DATA_AUDIO_SERVICE_TYPE + MASTERING_DISPLAY_METADATA = lib.AV_FRAME_DATA_MASTERING_DISPLAY_METADATA + GOP_TIMECODE = lib.AV_FRAME_DATA_GOP_TIMECODE + SPHERICAL = lib.AV_FRAME_DATA_SPHERICAL + CONTENT_LIGHT_LEVEL = lib.AV_FRAME_DATA_CONTENT_LIGHT_LEVEL + ICC_PROFILE = lib.AV_FRAME_DATA_ICC_PROFILE + S12M_TIMECODE = lib.AV_FRAME_DATA_S12M_TIMECODE + DYNAMIC_HDR_PLUS = lib.AV_FRAME_DATA_DYNAMIC_HDR_PLUS + REGIONS_OF_INTEREST = lib.AV_FRAME_DATA_REGIONS_OF_INTEREST + VIDEO_ENC_PARAMS = lib.AV_FRAME_DATA_VIDEO_ENC_PARAMS + SEI_UNREGISTERED = lib.AV_FRAME_DATA_SEI_UNREGISTERED + FILM_GRAIN_PARAMS = lib.AV_FRAME_DATA_FILM_GRAIN_PARAMS + DETECTION_BBOXES = lib.AV_FRAME_DATA_DETECTION_BBOXES + DOVI_RPU_BUFFER = lib.AV_FRAME_DATA_DOVI_RPU_BUFFER + DOVI_METADATA = lib.AV_FRAME_DATA_DOVI_METADATA + DYNAMIC_HDR_VIVID = lib.AV_FRAME_DATA_DYNAMIC_HDR_VIVID + AMBIENT_VIEWING_ENVIRONMENT = lib.AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT + VIDEO_HINT = lib.AV_FRAME_DATA_VIDEO_HINT + + +@cython.cfunc +def wrap_side_data(frame: Frame, index: cython.int) -> SideData: + if frame.ptr.side_data[index].type == lib.AV_FRAME_DATA_MOTION_VECTORS: + return MotionVectors(_cinit_bypass_sentinel, frame, index) + elif frame.ptr.side_data[index].type == lib.AV_FRAME_DATA_VIDEO_ENC_PARAMS: + return VideoEncParams(_cinit_bypass_sentinel, frame, index) + else: + return SideData(_cinit_bypass_sentinel, frame, index) + + +@cython.cfunc +def get_display_rotation(frame: Frame) -> cython.int: + for i in range(frame.ptr.nb_side_data): + if frame.ptr.side_data[i].type == lib.AV_FRAME_DATA_DISPLAYMATRIX: + return int( + lib.av_display_rotation_get( + cython.cast( + cython.pointer[cython.const[int32_t]], + frame.ptr.side_data[i].data, + ) + ) + ) + return 0 + + +@cython.cclass +class SideData(Buffer): + def __init__(self, sentinel, frame: Frame, index: cython.int): + if sentinel is not _cinit_bypass_sentinel: + raise RuntimeError("cannot manually instatiate SideData") + self.frame = frame + self.ptr = frame.ptr.side_data[index] + self.metadata = wrap_dictionary(self.ptr.metadata) + + @cython.cfunc + def _buffer_size(self) -> cython.size_t: + return self.ptr.size + + @cython.cfunc + def _buffer_ptr(self) -> cython.p_void: + return self.ptr.data + + @cython.cfunc + def _buffer_writable(self) -> cython.bint: + return False + + def __repr__(self): + return f"" + + @property + def type(self): + return Type(self.ptr.type) + + +@cython.cclass +class _SideDataContainer: + def __init__(self, frame: Frame): + self.frame = frame + self._by_index: list = [] + self._by_type: dict = {} + + i: cython.int + data: SideData + + for i in range(self.frame.ptr.nb_side_data): + data = wrap_side_data(frame, i) + self._by_index.append(data) + self._by_type[data.type] = data + + def __len__(self): + return len(self._by_index) + + def __iter__(self): + return iter(self._by_index) + + def __getitem__(self, key): + if isinstance(key, int): + return self._by_index[key] + if isinstance(key, str): + return self._by_type[Type[key]] + return self._by_type[key] + + +class SideDataContainer(_SideDataContainer, Mapping): + pass diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.pyi b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3f8ef398ee02df6bc958c4667d19e4b2f816eb05 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/sidedata.pyi @@ -0,0 +1,52 @@ +from collections.abc import Iterator, Mapping, Sequence +from enum import Enum +from typing import ClassVar, cast, overload + +from av.buffer import Buffer +from av.frame import Frame + +class Type(Enum): + PANSCAN = cast(ClassVar[Type], ...) + A53_CC = cast(ClassVar[Type], ...) + STEREO3D = cast(ClassVar[Type], ...) + MATRIXENCODING = cast(ClassVar[Type], ...) + DOWNMIX_INFO = cast(ClassVar[Type], ...) + REPLAYGAIN = cast(ClassVar[Type], ...) + DISPLAYMATRIX = cast(ClassVar[Type], ...) + AFD = cast(ClassVar[Type], ...) + MOTION_VECTORS = cast(ClassVar[Type], ...) + SKIP_SAMPLES = cast(ClassVar[Type], ...) + AUDIO_SERVICE_TYPE = cast(ClassVar[Type], ...) + MASTERING_DISPLAY_METADATA = cast(ClassVar[Type], ...) + GOP_TIMECODE = cast(ClassVar[Type], ...) + SPHERICAL = cast(ClassVar[Type], ...) + CONTENT_LIGHT_LEVEL = cast(ClassVar[Type], ...) + ICC_PROFILE = cast(ClassVar[Type], ...) + S12M_TIMECODE = cast(ClassVar[Type], ...) + DYNAMIC_HDR_PLUS = cast(ClassVar[Type], ...) + REGIONS_OF_INTEREST = cast(ClassVar[Type], ...) + VIDEO_ENC_PARAMS = cast(ClassVar[Type], ...) + SEI_UNREGISTERED = cast(ClassVar[Type], ...) + FILM_GRAIN_PARAMS = cast(ClassVar[Type], ...) + DETECTION_BBOXES = cast(ClassVar[Type], ...) + DOVI_RPU_BUFFER = cast(ClassVar[Type], ...) + DOVI_METADATA = cast(ClassVar[Type], ...) + DYNAMIC_HDR_VIVID = cast(ClassVar[Type], ...) + AMBIENT_VIEWING_ENVIRONMENT = cast(ClassVar[Type], ...) + VIDEO_HINT = cast(ClassVar[Type], ...) + +class SideData(Buffer): + type: Type + +class SideDataContainer(Mapping): + frame: Frame + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[SideData]: ... + @overload + def __getitem__(self, key: str | int | Type) -> SideData: ... + @overload + def __getitem__(self, key: slice) -> Sequence[SideData]: ... + @overload + def __getitem__( + self, key: str | int | Type | slice + ) -> SideData | Sequence[SideData]: ... diff --git a/.venv/lib/python3.12/site-packages/av/stream.abi3.so b/.venv/lib/python3.12/site-packages/av/stream.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..ad16f2cb95633570ed8e401fa387b6a00866f35a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/stream.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10b98f9cee2dc751c0b1fc494bc95cb674ee07235c50ce343d890c382b72cf1e +size 585065 diff --git a/.venv/lib/python3.12/site-packages/av/stream.pxd b/.venv/lib/python3.12/site-packages/av/stream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..727e420eaf1c831b3a581c939c898cc89d0564e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/stream.pxd @@ -0,0 +1,36 @@ +cimport libav as lib + +from av.codec.context cimport CodecContext +from av.container.core cimport Container +from av.frame cimport Frame +from av.index cimport IndexEntries +from av.packet cimport Packet + + +cdef class Stream: + cdef lib.AVStream *ptr + + # Stream attributes. + cdef readonly Container container + cdef readonly dict metadata + + # CodecContext attributes. + cdef readonly CodecContext codec_context + + cdef readonly IndexEntries index_entries + + # Private API. + cdef _init(self, Container, lib.AVStream*, CodecContext) + cdef _assert_has_codec_context(self, int err=*) + cdef _finalize_for_output(self) + cdef _set_id(self, value) + + +cdef Stream wrap_stream(Container, lib.AVStream*, CodecContext) + + +cdef class DataStream(Stream): + pass + +cdef class AttachmentStream(Stream): + pass diff --git a/.venv/lib/python3.12/site-packages/av/stream.py b/.venv/lib/python3.12/site-packages/av/stream.py new file mode 100644 index 0000000000000000000000000000000000000000..2d087c8adb1ae5a7aa8ebd1a377949ddca285c4d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/stream.py @@ -0,0 +1,373 @@ +from enum import IntEnum, IntFlag + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.error import err_check +from cython.cimports.av.index import wrap_index_entries +from cython.cimports.av.utils import ( + avdict_to_dict, + avrational_to_fraction, + dict_to_avdict, + to_avrational, +) + + +class Disposition(IntFlag): + default = 1 << 0 + dub = 1 << 1 + original = 1 << 2 + comment = 1 << 3 + lyrics = 1 << 4 + karaoke = 1 << 5 + forced = 1 << 6 + hearing_impaired = 1 << 7 + visual_impaired = 1 << 8 + clean_effects = 1 << 9 + attached_pic = 1 << 10 + timed_thumbnails = 1 << 11 + non_diegetic = 1 << 12 + captions = 1 << 16 + descriptions = 1 << 17 + metadata = 1 << 18 + dependent = 1 << 19 + still_image = 1 << 20 + multilayer = 1 << 21 + + +class Discard(IntEnum): + none = lib.AVDISCARD_NONE + default = lib.AVDISCARD_DEFAULT + nonref = lib.AVDISCARD_NONREF + bidir = lib.AVDISCARD_BIDIR + nonintra = lib.AVDISCARD_NONINTRA + nonkey = lib.AVDISCARD_NONKEY + all = lib.AVDISCARD_ALL + + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def wrap_stream( + container: Container, + c_stream: cython.pointer[lib.AVStream], + codec_context: CodecContext, +) -> Stream: + """Build an av.Stream for an existing AVStream. + + The AVStream MUST be fully constructed and ready for use before this is called. + """ + + # This better be the right one... + assert container.ptr.streams[c_stream.index] == c_stream + + py_stream: Stream + + from av.audio.stream import AudioStream + from av.subtitles.stream import SubtitleStream + from av.video.stream import VideoStream + + if c_stream.codecpar.codec_type == lib.AVMEDIA_TYPE_VIDEO: + py_stream = VideoStream.__new__(VideoStream, _cinit_bypass_sentinel) + elif c_stream.codecpar.codec_type == lib.AVMEDIA_TYPE_AUDIO: + py_stream = AudioStream.__new__(AudioStream, _cinit_bypass_sentinel) + elif c_stream.codecpar.codec_type == lib.AVMEDIA_TYPE_SUBTITLE: + py_stream = SubtitleStream.__new__(SubtitleStream, _cinit_bypass_sentinel) + elif c_stream.codecpar.codec_type == lib.AVMEDIA_TYPE_ATTACHMENT: + py_stream = AttachmentStream.__new__(AttachmentStream, _cinit_bypass_sentinel) + elif c_stream.codecpar.codec_type == lib.AVMEDIA_TYPE_DATA: + py_stream = DataStream.__new__(DataStream, _cinit_bypass_sentinel) + else: + py_stream = Stream.__new__(Stream, _cinit_bypass_sentinel) + + py_stream._init(container, c_stream, codec_context) + return py_stream + + +@cython.cclass +class Stream: + """ + A single stream of audio, video or subtitles within a :class:`.Container`. + + :: + + >>> fh = av.open(video_path) + >>> stream = fh.streams.video[0] + >>> stream + + + This encapsulates a :class:`.CodecContext`, located at :attr:`Stream.codec_context`. + Attribute access is passed through to that context when attributes are missing + on the stream itself. E.g. ``stream.options`` will be the options on the + context. + """ + + def __cinit__(self, name): + if name is _cinit_bypass_sentinel: + return + raise RuntimeError("cannot manually instantiate Stream") + + @cython.cfunc + def _init( + self, + container: Container, + stream: cython.pointer[lib.AVStream], + codec_context: CodecContext, + ): + self.container = container + self.ptr = stream + self.index_entries = wrap_index_entries(self.ptr) + + self.codec_context = codec_context + if self.codec_context: + self.codec_context.stream_index = stream.index + + self.metadata = avdict_to_dict( + stream.metadata, + encoding=self.container.metadata_encoding, + errors=self.container.metadata_errors, + ) + + @cython.cfunc + def _assert_has_codec_context( + self, err: cython.int = lib.AVERROR_DECODER_NOT_FOUND + ): + # Calling into a NULL codec_context is a segfault, not an AttributeError. + if self.codec_context is None: + err_check(err) + + def __repr__(self): + name = getattr(self, "name", None) + return ( + f"'}/" + f"{name or ''} at 0x{id(self):x}>" + ) + + def __setattr__(self, name, value): + if name == "id": + self._set_id(value) + return + if name == "disposition": + self.ptr.disposition = value + return + if name == "discard": + self.ptr.discard = Discard(value).value + return + if name == "time_base": + to_avrational(value, cython.address(self.ptr.time_base)) + return + + # Convenience setter for codec context properties. + if self.codec_context is not None: + setattr(self.codec_context, name, value) + + @cython.cfunc + def _finalize_for_output(self): + dict_to_avdict( + cython.address(self.ptr.metadata), + self.metadata, + encoding=self.container.metadata_encoding, + errors=self.container.metadata_errors, + ) + + if self.codec_context is None: + return + + if not self.ptr.time_base.num: + self.ptr.time_base = self.codec_context.ptr.time_base + + # It prefers if we pass it parameters via this other object. Let's just copy what we want. + err_check( + lib.avcodec_parameters_from_context( + self.ptr.codecpar, self.codec_context.ptr + ) + ) + + @property + def id(self): + """ + The format-specific ID of this stream. + + :type: int + + """ + return self.ptr.id + + @cython.cfunc + def _set_id(self, value): + if value is None: + self.ptr.id = 0 + else: + self.ptr.id = value + + @property + def profiles(self): + """ + List the available profiles for this stream. + + :type: list[str] + """ + if self.codec_context: + return self.codec_context.profiles + else: + return [] + + @property + def profile(self): + """ + The profile of this stream. + + :type: str + """ + if self.codec_context: + return self.codec_context.profile + else: + return None + + @property + def index(self): + """ + The index of this stream in its :class:`.Container`. + + :type: int + """ + return self.ptr.index + + @property + def time_base(self): + """ + The unit of time (in fractional seconds) in which timestamps are expressed. + + :type: fractions.Fraction | None + + """ + return avrational_to_fraction(cython.address(self.ptr.time_base)) + + @property + def start_time(self): + """ + The presentation timestamp in :attr:`time_base` units of the first + frame in this stream. + + :type: int | None + """ + if self.ptr.start_time != lib.AV_NOPTS_VALUE: + return self.ptr.start_time + + @property + def duration(self): + """ + The duration of this stream in :attr:`time_base` units. + + :type: int | None + + """ + if self.ptr.duration != lib.AV_NOPTS_VALUE: + return self.ptr.duration + + @property + def frames(self): + """ + The number of frames this stream contains. + + Returns ``0`` if it is not known. + + :type: int + """ + return self.ptr.nb_frames + + @property + def language(self): + """ + The language of the stream. + + :type: str | None + """ + return self.metadata.get("language") + + @property + def disposition(self): + return Disposition(self.ptr.disposition) + + @property + def discard(self): + """ + Controls which packets of this stream are discarded by the demuxer. + + Set this to e.g. :attr:`Discard.all` on streams you don't need so that + :meth:`.Container.demux` and :meth:`.Container.seek` skip them, avoiding + the cost of synchronizing streams you never read. + + :type: Discard + """ + return Discard(self.ptr.discard) + + @property + def type(self): + """ + The type of the stream. + + :type: Literal["audio", "video", "subtitle", "data", "attachment"] + """ + media_type = lib.av_get_media_type_string(self.ptr.codecpar.codec_type) + return "unknown" if media_type == cython.NULL else media_type + + +@cython.final +@cython.cclass +class DataStream(Stream): + def __repr__(self): + return ( + f"'} at 0x{id(self):x}>" + ) + + @property + def name(self): + desc: cython.pointer[cython.const[lib.AVCodecDescriptor]] = ( + lib.avcodec_descriptor_get(self.ptr.codecpar.codec_id) + ) + if desc == cython.NULL: + return None + return desc.name + + +@cython.final +@cython.cclass +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") + + @property + def data(self): + """Return the raw attachment payload as bytes.""" + extradata: cython.p_uchar = self.ptr.codecpar.extradata + size: cython.Py_ssize_t = self.ptr.codecpar.extradata_size + if extradata == cython.NULL or size <= 0: + return b"" + + payload = bytearray(size) + for i in range(size): + payload[i] = extradata[i] + + return bytes(payload) diff --git a/.venv/lib/python3.12/site-packages/av/stream.pyi b/.venv/lib/python3.12/site-packages/av/stream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f9148021fa905bb6be770918a16fae638bffe8df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/stream.pyi @@ -0,0 +1,75 @@ +from enum import IntEnum, IntFlag +from fractions import Fraction +from typing import Literal, cast + +from .codec import Codec, CodecContext +from .container import Container +from .index import IndexEntries + +class Disposition(IntFlag): + default = cast(int, ...) + dub = cast(int, ...) + original = cast(int, ...) + comment = cast(int, ...) + lyrics = cast(int, ...) + karaoke = cast(int, ...) + forced = cast(int, ...) + hearing_impaired = cast(int, ...) + visual_impaired = cast(int, ...) + clean_effects = cast(int, ...) + attached_pic = cast(int, ...) + timed_thumbnails = cast(int, ...) + non_diegetic = cast(int, ...) + captions = cast(int, ...) + descriptions = cast(int, ...) + metadata = cast(int, ...) + dependent = cast(int, ...) + still_image = cast(int, ...) + multilayer = cast(int, ...) + +class Discard(IntEnum): + none = cast(int, ...) + default = cast(int, ...) + nonref = cast(int, ...) + bidir = cast(int, ...) + nonintra = cast(int, ...) + nonkey = cast(int, ...) + all = cast(int, ...) + +class Stream: + name: str | None + container: Container + codec: Codec + codec_context: CodecContext + metadata: dict[str, str] + index_entries: IndexEntries + id: int + profiles: list[str] + profile: str | None + index: int + options: dict[str, object] + time_base: Fraction | None + average_rate: Fraction | None + base_rate: Fraction | None + guessed_rate: Fraction | None + start_time: int | None + duration: int | None + disposition: Disposition + discard: Discard + frames: int + language: str | None + type: Literal["video", "audio", "data", "subtitle", "attachment", "unknown"] + + # From context + codec_tag: str + +class DataStream(Stream): + type: Literal["data"] + name: str | None + +class AttachmentStream(Stream): + type: Literal["attachment"] + @property + def mimetype(self) -> str | None: ... + @property + def data(self) -> bytes: ... diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__init__.pxd b/.venv/lib/python3.12/site-packages/av/subtitles/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__init__.py b/.venv/lib/python3.12/site-packages/av/subtitles/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__init__.pyi b/.venv/lib/python3.12/site-packages/av/subtitles/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c02a535517af289f4584232bbf8af9646e66fe70 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/__init__.pyi @@ -0,0 +1,18 @@ +from typing import Literal + +# FFmpeg 8.1 encoders and the codec descriptor aliases that resolve to them. +_SubtitleCodecName = Literal[ + "ass", + "dvb_subtitle", + "dvbsub", + "dvd_subtitle", + "dvdsub", + "mov_text", + "srt", + "ssa", + "subrip", + "text", + "ttml", + "webvtt", + "xsub", +] diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f431d9c02714978bcfd08f6a7406a1130409419a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/codeccontext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/codeccontext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae621c7383fa3b515e2f4a6e6252f5342709c95b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/codeccontext.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/stream.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/stream.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e67908d59ef1c53246676a50aa0217fd1438d0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/stream.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/subtitle.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/subtitle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51b824bc954b2567ec5f236dc0ec247e45092747 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/subtitles/__pycache__/subtitle.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.abi3.so b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..6d2ef8442fdfcd30b0383c15bad19118b25aadb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7427f9f0345cd7e892ba72f66f64d29a173b7f9bef8c92d639e716e3d054efef +size 314305 diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.pxd b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.pxd new file mode 100644 index 0000000000000000000000000000000000000000..fb5748294d591378dbf7c2c2dbe2a478f28ebfc0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.pxd @@ -0,0 +1,8 @@ +from av.codec.context cimport CodecContext +from av.packet cimport Packet + + +cdef class SubtitleCodecContext(CodecContext): + cdef bint subtitle_header_set + cdef _decode(self, Packet packet) + cpdef decode2(self, Packet packet) diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.py b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.py new file mode 100644 index 0000000000000000000000000000000000000000..34dc868cf6a34e3cdb6185b2b4b982b3b2b6ad3c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.py @@ -0,0 +1,146 @@ +import cython +from cython.cimports import libav as lib +from cython.cimports.av.buffer import ByteSource, bytesource +from cython.cimports.av.codec.context import CodecContext +from cython.cimports.av.error import err_check +from cython.cimports.av.packet import Packet +from cython.cimports.av.subtitles.subtitle import SubtitleProxy, SubtitleSet +from cython.cimports.cpython.bytes import PyBytes_FromStringAndSize +from cython.cimports.libc.string import memcpy + + +@cython.final +@cython.cclass +class SubtitleCodecContext(CodecContext): + @property + def subtitle_header(self) -> bytes | None: + """Get the subtitle header data (ASS/SSA format for text subtitles).""" + if ( + self.ptr.subtitle_header == cython.NULL + or self.ptr.subtitle_header_size <= 0 + ): + return None + return PyBytes_FromStringAndSize( + cython.cast(cython.p_char, self.ptr.subtitle_header), + self.ptr.subtitle_header_size, + ) + + @subtitle_header.setter + def subtitle_header(self, data: bytes | None) -> None: + """Set the subtitle header data.""" + source: ByteSource + if data is None: + lib.av_freep(cython.address(self.ptr.subtitle_header)) + self.ptr.subtitle_header_size = 0 + else: + source = bytesource(data) + self.ptr.subtitle_header = cython.cast( + cython.p_uchar, + lib.av_realloc( + self.ptr.subtitle_header, + source.length + lib.AV_INPUT_BUFFER_PADDING_SIZE, + ), + ) + if not self.ptr.subtitle_header: + raise MemoryError("Cannot allocate subtitle_header") + memcpy(self.ptr.subtitle_header, source.ptr, source.length) + self.ptr.subtitle_header_size = cython.cast(cython.int, source.length) + self.subtitle_header_set = True + + def __dealloc__(self) -> None: + if self.ptr and self.subtitle_header_set: + lib.av_freep(cython.address(self.ptr.subtitle_header)) + + def encode_subtitle(self, subtitle: SubtitleSet) -> Packet: + """ + Encode a SubtitleSet into a Packet. + + Args: + subtitle: The SubtitleSet to encode + + Returns: + A Packet containing the encoded subtitle data + """ + if not self.codec.ptr: + raise ValueError("Cannot encode with unknown codec") + + self.open(strict=False) + + buf: cython.p_uchar = cython.cast(cython.p_uchar, lib.av_malloc(1024 * 1024)) + if buf == cython.NULL: + raise MemoryError() + + ret: cython.int = lib.avcodec_encode_subtitle( + self.ptr, + buf, + 1024 * 1024, + cython.address(subtitle.proxy.struct), + ) + if ret < 0: + lib.av_free(buf) + err_check(ret, "avcodec_encode_subtitle()") + + packet: Packet = Packet(ret) + memcpy(packet.ptr.data, buf, ret) + lib.av_free(buf) + packet.ptr.pts = subtitle.proxy.struct.pts + packet.ptr.dts = subtitle.proxy.struct.pts + packet.ptr.duration = ( + subtitle.proxy.struct.end_display_time + - subtitle.proxy.struct.start_display_time + ) + + return packet + + @cython.cfunc + def _decode(self, packet: Packet | None): + """Decode a subtitle packet, returning a list of :class:`.Subtitle` objects + if a subtitle was decoded, or an empty list otherwise.""" + if not self.codec.ptr: + raise ValueError("cannot decode unknown codec") + + if packet is None: + raise RuntimeError("packet cannot be None") + + self.open(strict=False) + proxy: SubtitleProxy = SubtitleProxy() + got_frame: cython.int = 0 + + err_check( + lib.avcodec_decode_subtitle2( + self.ptr, + cython.address(proxy.struct), + cython.address(got_frame), + packet.ptr, + ) + ) + + if got_frame: + return list(SubtitleSet(proxy)) + return [] + + @cython.ccall + def decode2(self, packet: Packet): + """ + Returns SubtitleSet if you really need it. + """ + if not self.codec.ptr: + raise ValueError("cannot decode unknown codec") + + self.open(strict=False) + + proxy: SubtitleProxy = SubtitleProxy() + got_frame: cython.int = 0 + + err_check( + lib.avcodec_decode_subtitle2( + self.ptr, + cython.address(proxy.struct), + cython.address(got_frame), + packet.ptr, + ) + ) + + if got_frame: + return SubtitleSet(proxy) + return None diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.pyi b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7f8a49d09bdc1117b51de16be5f424fabc6b9000 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/codeccontext.pyi @@ -0,0 +1,11 @@ +from typing import Literal + +from av.codec.context import CodecContext +from av.packet import Packet +from av.subtitles.subtitle import SubtitleSet + +class SubtitleCodecContext(CodecContext): + type: Literal["subtitle"] + subtitle_header: bytes | None + def decode2(self, packet: Packet) -> SubtitleSet | None: ... + def encode_subtitle(self, subtitle: SubtitleSet) -> Packet: ... diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/stream.abi3.so b/.venv/lib/python3.12/site-packages/av/subtitles/stream.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..c557c55c698635e6b9f1fa71be86b4808bee5c3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/stream.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50e3b83862152297379427b7abcc2ce4c98f1d1de26c1926bfe5d62543033665 +size 256777 diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/stream.pxd b/.venv/lib/python3.12/site-packages/av/subtitles/stream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..745032af956c812f0d72f2f3dda9c888b23b1b7f --- /dev/null +++ b/.venv/lib/python3.12/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/.venv/lib/python3.12/site-packages/av/subtitles/stream.py b/.venv/lib/python3.12/site-packages/av/subtitles/stream.py new file mode 100644 index 0000000000000000000000000000000000000000..a39f8b0a32497bb9e7fe7d0bfc006a8a54718b52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/stream.py @@ -0,0 +1,25 @@ +import cython +from cython.cimports.av.packet import Packet +from cython.cimports.av.stream import Stream + + +@cython.final +@cython.cclass +class SubtitleStream(Stream): + def __getattr__(self, name): + return getattr(self.codec_context, name) + + @cython.ccall + def decode(self, packet: Packet | None = None): + """ + Decode a :class:`.Packet` and returns a subtitle object. + + :rtype: list[AssSubtitle] | list[BitmapSubtitle] + + .. seealso:: This is a passthrough to :meth:`.CodecContext.decode`. + """ + self._assert_has_codec_context() + if not packet: + packet = Packet() + + return self.codec_context.decode(packet) diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/stream.pyi b/.venv/lib/python3.12/site-packages/av/subtitles/stream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4c3326f79c192893bfb5ec78082f46c1ca48109e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/stream.pyi @@ -0,0 +1,12 @@ +from av.packet import Packet +from av.stream import Stream +from av.subtitles.subtitle import AssSubtitle, BitmapSubtitle, SubtitleSet + +from .codeccontext import SubtitleCodecContext + +class SubtitleStream(Stream): + codec_context: SubtitleCodecContext + def decode( + self, packet: Packet | None = None + ) -> list[AssSubtitle] | list[BitmapSubtitle]: ... + def decode2(self, packet: Packet) -> SubtitleSet | None: ... diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.abi3.so b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..fd5347120f85fb8f622d4fbb45d89effeae32267 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90a4c2b919697c4d9ece84ff72e8e4a4fec499e69975791c37a26f114bcac907 +size 970465 diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.pxd b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.pxd new file mode 100644 index 0000000000000000000000000000000000000000..4f85567421d014bd877c248d3ee2c812dc8730ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.pxd @@ -0,0 +1,29 @@ +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/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.py b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2b53df650fb161b9a90b3d0226d8848d56fbb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.py @@ -0,0 +1,336 @@ +import cython +from cython.cimports.cpython import PyBuffer_FillInfo, PyBytes_FromString +from cython.cimports.libc.string import memcpy + + +@cython.final +@cython.cclass +class SubtitleProxy: + def __dealloc__(self): + lib.avsubtitle_free(cython.address(self.struct)) + + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.final +@cython.cclass +class SubtitleSet: + """ + A :class:`SubtitleSet` can contain many :class:`Subtitle` objects. + + Wraps :ffmpeg:`AVSubtitle`. + """ + + def __cinit__(self, proxy_or_sentinel=None): + if proxy_or_sentinel is _cinit_bypass_sentinel: + # Creating empty SubtitleSet for encoding + self.proxy = SubtitleProxy() + self.rects = () + elif isinstance(proxy_or_sentinel, SubtitleProxy): + # Creating from decoded subtitle + self.proxy = proxy_or_sentinel + self.rects = tuple( + build_subtitle(self, i) for i in range(self.proxy.struct.num_rects) + ) + else: + raise TypeError( + "SubtitleSet requires a SubtitleProxy or use SubtitleSet.create()" + ) + + @staticmethod + def create( + text: bytes, + start: int, + end: int, + pts: int = 0, + subtitle_format: int = 1, + ) -> SubtitleSet: + """ + Create a SubtitleSet for encoding. + + :param text: The subtitle text in ASS dialogue format + (e.g. ``b"0,0,Default,,0,0,0,,Hello World"``) + :param start: Start display time as offset from pts (typically 0) + :param end: End display time as offset from pts (i.e., duration) + :param pts: Presentation timestamp in stream time_base units + :param subtitle_format: Subtitle format (default 1 for text) + :return: A SubtitleSet ready for encoding + + .. note:: + All timing values should be in stream time_base units. + For MKV (time_base=1/1000), units are milliseconds. + For MP4 (time_base=1/1000000), units are microseconds. + """ + subset: SubtitleSet = SubtitleSet(_cinit_bypass_sentinel) + + subset.proxy.struct.format = subtitle_format + subset.proxy.struct.start_display_time = start + subset.proxy.struct.end_display_time = end + subset.proxy.struct.pts = pts + + subset.proxy.struct.num_rects = 1 + subset.proxy.struct.rects = cython.cast( + cython.pointer[cython.pointer[lib.AVSubtitleRect]], + lib.av_mallocz(cython.sizeof(cython.pointer[lib.AVSubtitleRect])), + ) + if subset.proxy.struct.rects == cython.NULL: + raise MemoryError("Failed to allocate subtitle rects array") + + rect: cython.pointer[lib.AVSubtitleRect] = cython.cast( + cython.pointer[lib.AVSubtitleRect], + lib.av_mallocz(cython.sizeof(lib.AVSubtitleRect)), + ) + if rect == cython.NULL: + lib.av_free(subset.proxy.struct.rects) + subset.proxy.struct.rects = cython.NULL + raise MemoryError("Failed to allocate subtitle rect") + + subset.proxy.struct.rects[0] = rect + + rect.x = 0 + rect.y = 0 + rect.w = 0 + rect.h = 0 + rect.nb_colors = 0 + rect.type = lib.SUBTITLE_ASS + rect.text = cython.NULL + rect.flags = 0 + + text_len: cython.Py_ssize_t = len(text) + rect.ass = cython.cast(cython.p_char, lib.av_malloc(text_len + 1)) + if rect.ass == cython.NULL: + raise MemoryError("Failed to allocate subtitle text") + memcpy(rect.ass, cython.cast(cython.p_char, text), text_len) + rect.ass[text_len] = 0 + + subset.rects = (AssSubtitle(subset, 0),) + + return subset + + 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 + + @format.setter + def format(self, value: int): + self.proxy.struct.format = value + + @property + def start_display_time(self): + return self.proxy.struct.start_display_time + + @start_display_time.setter + def start_display_time(self, value: int): + self.proxy.struct.start_display_time = value + + @property + def end_display_time(self): + return self.proxy.struct.end_display_time + + @end_display_time.setter + def end_display_time(self, value: int): + self.proxy.struct.end_display_time = value + + @property + def pts(self): + """Same as packet pts, in av.time_base.""" + return self.proxy.struct.pts + + @pts.setter + def pts(self, value: int): + self.proxy.struct.pts = value + + def __len__(self): + return len(self.rects) + + def __iter__(self): + return iter(self.rects) + + def __getitem__(self, i): + return self.rects[i] + + +@cython.cfunc +def build_subtitle(subtitle: SubtitleSet, index: cython.int) -> Subtitle: + """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 cython.cast(cython.uint, index) >= subtitle.proxy.struct.num_rects: + raise ValueError("subtitle rect index out of range") + + ptr: cython.pointer[lib.AVSubtitleRect] = subtitle.proxy.struct.rects[index] + + if ptr.type == lib.SUBTITLE_BITMAP: + return BitmapSubtitle(subtitle, index) + if ptr.type == lib.SUBTITLE_ASS or ptr.type == lib.SUBTITLE_TEXT: + return AssSubtitle(subtitle, index) + + raise ValueError(f"unknown subtitle type {ptr.type!r}") + + +@cython.cclass +class Subtitle: + """ + An abstract base class for each concrete type of subtitle. + Wraps :ffmpeg:`AVSubtitleRect` + """ + + def __cinit__(self, subtitle: SubtitleSet, index: cython.int): + if ( + index < 0 + or cython.cast(cython.uint, 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"" + + +@cython.final +@cython.cclass +class BitmapSubtitle(Subtitle): + def __cinit__(self, subtitle: SubtitleSet, index: cython.int): + 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] + + +@cython.final +@cython.cclass +class BitmapSubtitlePlane: + def __cinit__(self, subtitle: BitmapSubtitle, index: cython.int): + 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 = cython.cast(cython.p_void, subtitle.ptr.data[index]) + + # New-style buffer support. + def __getbuffer__(self, view: cython.pointer[Py_buffer], flags: cython.int): + PyBuffer_FillInfo(view, self, self._buffer, self.buffer_size, 0, flags) + + +@cython.final +@cython.cclass +class AssSubtitle(Subtitle): + """ + Represents an ASS/Text subtitle format, as opposed to a bitmap Subtitle format. + """ + + def __repr__(self): + return f"" + + @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 cython.NULL: + return PyBytes_FromString(self.ptr.ass) + return b"" + + @property + def dialogue(self): + """ + Extract the dialogue from the ass format. Strip comments. + """ + comma_count: cython.short = 0 + i: cython.Py_ssize_t = 0 + state: cython.bint = False + ass_text: bytes = self.ass + char, next_char = cython.declare(cython.uchar) + result: bytearray = bytearray() + text_len: cython.Py_ssize_t = len(ass_text) + + while comma_count < 8 and i < text_len: + if ass_text[i] == b","[0]: + comma_count += 1 + i += 1 + + while i < text_len: + char = ass_text[i] + next_char = 0 if i + 1 >= text_len else ass_text[i + 1] + + if char == b"\\"[0] and next_char == b"N"[0]: + result.append(b"\n"[0]) + i += 2 + continue + + if not state: + if char == b"{"[0] and next_char != b"\\"[0]: + state = True + else: + result.append(char) + elif char == b"}"[0]: + state = False + i += 1 + + return bytes(result) + + @property + def text(self): + """ + Rarely used attribute. You're probably looking for dialogue. + """ + if self.ptr.text is not cython.NULL: + return PyBytes_FromString(self.ptr.text) + return b"" diff --git a/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.pyi b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5f277eba098957ec91d7caf2a78fb2ee1e257bef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/subtitles/subtitle.pyi @@ -0,0 +1,46 @@ +from collections.abc import Iterator +from typing import Literal + +class SubtitleSet: + format: int + start_display_time: int + end_display_time: int + pts: int + rects: tuple[Subtitle, ...] + + @staticmethod + def create( + text: bytes, + start: int, + end: int, + pts: int = 0, + subtitle_format: int = 1, + ) -> SubtitleSet: ... + 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/.venv/lib/python3.12/site-packages/av/utils.abi3.so b/.venv/lib/python3.12/site-packages/av/utils.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..30948edcb546e68948e362002e2ddab3186f1c77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/utils.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc914881954175ab14d1a8cf3c898f7a4a9215c53f98750959fb755930c01a86 +size 232329 diff --git a/.venv/lib/python3.12/site-packages/av/utils.pxd b/.venv/lib/python3.12/site-packages/av/utils.pxd new file mode 100644 index 0000000000000000000000000000000000000000..60279e513e3592b55bdddad7cd799957d28e461a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/utils.pxd @@ -0,0 +1,9 @@ +cimport libav as lib + + +cdef dict avdict_to_dict(lib.AVDictionary *input, str encoding, str errors) +cdef dict_to_avdict(lib.AVDictionary **dst, dict src, str encoding, str errors) + +cdef object avrational_to_fraction(const lib.AVRational *input) +cdef void to_avrational(object frac, lib.AVRational *input) +cdef void check_ndarray(object array, object dtype, int ndim) diff --git a/.venv/lib/python3.12/site-packages/av/utils.py b/.venv/lib/python3.12/site-packages/av/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..300d315f23d98a56b0051ed1d27a0e612f8b7ef3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/utils.py @@ -0,0 +1,74 @@ +# type: ignore +from fractions import Fraction + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.error import err_check + + +@cython.cfunc +def _decode(s: cython.pointer[cython.char], encoding, errors) -> str: + return cython.cast(bytes, s).decode(encoding, errors) + + +@cython.cfunc +def avdict_to_dict( + input: cython.pointer[lib.AVDictionary], encoding: str, errors: str +) -> dict: + element: cython.pointer[lib.AVDictionaryEntry] = cython.NULL + output: dict = {} + while True: + element = lib.av_dict_get(input, "", element, lib.AV_DICT_IGNORE_SUFFIX) + if element == cython.NULL: + break + output[_decode(element.key, encoding, errors)] = _decode( + element.value, encoding, errors + ) + + return output + + +@cython.cfunc +def dict_to_avdict( + dst: cython.pointer[cython.pointer[lib.AVDictionary]], + src: dict, + encoding: str, + errors: str, +): + lib.av_dict_free(dst) + for key, value in src.items(): + err_check( + lib.av_dict_set( + dst, key.encode(encoding, errors), value.encode(encoding, errors), 0 + ) + ) + + +@cython.cfunc +def avrational_to_fraction( + input: cython.pointer[cython.const[lib.AVRational]], +) -> object: + if input.num and input.den: + return Fraction(input.num, input.den) + return None + + +@cython.cfunc +def to_avrational(frac: object, input: cython.pointer[lib.AVRational]) -> cython.void: + input.num = frac.numerator + input.den = frac.denominator + + +@cython.cfunc +def check_ndarray(array: object, dtype: object, ndim: cython.int) -> cython.void: + """ + Check a numpy array has the expected data type and number of dimensions. + """ + if array.dtype != dtype: + raise ValueError( + f"Expected numpy array with dtype `{dtype}` but got `{array.dtype}`" + ) + if array.ndim != ndim: + raise ValueError( + f"Expected numpy array with ndim `{ndim}` but got `{array.ndim}`" + ) diff --git a/.venv/lib/python3.12/site-packages/av/video/__init__.pxd b/.venv/lib/python3.12/site-packages/av/video/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/video/__init__.py b/.venv/lib/python3.12/site-packages/av/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f781103fa934ce3f59fb4e33f782161c9f7bbc9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/__init__.py @@ -0,0 +1,2 @@ +from .frame import VideoFrame as VideoFrame +from .stream import VideoStream as VideoStream diff --git a/.venv/lib/python3.12/site-packages/av/video/__init__.pyi b/.venv/lib/python3.12/site-packages/av/video/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..63b5e0501c12e34f70e08440d5415fccba2e7577 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/__init__.pyi @@ -0,0 +1,197 @@ +from typing import Literal + +from .frame import VideoFrame +from .stream import VideoStream + +# FFmpeg 8.1 encoders and the codec descriptor aliases that resolve to them. +_VideoCodecName = Literal[ + "a64_multi", + "a64_multi5", + "a64multi", + "a64multi5", + "alias_pix", + "amv", + "apng", + "apv", + "asv1", + "asv2", + "av1", + "av1_amf", + "av1_d3d12va", + "av1_mediacodec", + "av1_mf", + "av1_nvenc", + "av1_qsv", + "av1_vaapi", + "av1_vulkan", + "avrp", + "avs2", + "avui", + "bitpacked", + "bmp", + "cavs", + "cfhd", + "cinepak", + "cljr", + "dirac", + "dnxhd", + "dpx", + "dvvideo", + "dxv", + "evc", + "exr", + "ffv1", + "ffv1_vulkan", + "ffvhuff", + "fits", + "flashsv", + "flashsv2", + "flv", + "flv1", + "gif", + "h261", + "h263", + "h263_v4l2m2m", + "h263p", + "h264", + "h264_amf", + "h264_d3d12va", + "h264_mediacodec", + "h264_mf", + "h264_nvenc", + "h264_oh", + "h264_omx", + "h264_qsv", + "h264_rkmpp", + "h264_v4l2m2m", + "h264_vaapi", + "h264_videotoolbox", + "h264_vulkan", + "hap", + "hdr", + "hevc", + "hevc_amf", + "hevc_d3d12va", + "hevc_mediacodec", + "hevc_mf", + "hevc_nvenc", + "hevc_oh", + "hevc_qsv", + "hevc_rkmpp", + "hevc_v4l2m2m", + "hevc_vaapi", + "hevc_videotoolbox", + "hevc_vulkan", + "huffyuv", + "jpeg2000", + "jpegls", + "jpegxl", + "jpegxl_anim", + "jpegxs", + "libaom-av1", + "libjxl", + "libjxl_anim", + "libkvazaar", + "liboapv", + "libopenh264", + "libopenjpeg", + "librav1e", + "libsvtav1", + "libsvtjpegxs", + "libtheora", + "libvpx", + "libvpx-vp9", + "libvvenc", + "libwebp", + "libwebp_anim", + "libx262", + "libx264", + "libx264rgb", + "libx265", + "libxavs", + "libxavs2", + "libxeve", + "libxvid", + "ljpeg", + "magicyuv", + "mjpeg", + "mjpeg_qsv", + "mjpeg_vaapi", + "mpeg1video", + "mpeg2_qsv", + "mpeg2_vaapi", + "mpeg2video", + "mpeg4", + "mpeg4_mediacodec", + "mpeg4_omx", + "mpeg4_v4l2m2m", + "msmpeg4", + "msmpeg4v2", + "msmpeg4v3", + "msrle", + "msvideo1", + "pam", + "pbm", + "pcx", + "pfm", + "pgm", + "pgmyuv", + "phm", + "png", + "ppm", + "prores", + "prores_aw", + "prores_ks", + "prores_ks_vulkan", + "prores_videotoolbox", + "qoi", + "qtrle", + "r10k", + "r210", + "rawvideo", + "roq", + "roqvideo", + "rpza", + "rv10", + "rv20", + "sgi", + "smc", + "snow", + "speedhq", + "sunrast", + "svq1", + "targa", + "theora", + "tiff", + "utvideo", + "v210", + "v308", + "v408", + "v410", + "vbn", + "vc2", + "vnull", + "vp8", + "vp8_mediacodec", + "vp8_v4l2m2m", + "vp8_vaapi", + "vp9", + "vp9_mediacodec", + "vp9_qsv", + "vp9_vaapi", + "vvc", + "wbmp", + "webp", + "wmv1", + "wmv2", + "wrapped_avframe", + "xbm", + "xface", + "xwd", + "y41p", + "yuv4", + "zlib", + "zmbv", +] + +__all__ = ("VideoFrame", "VideoStream") diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44965c6b643bde51e3302fe0af5c98a125bbe328 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/codeccontext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/codeccontext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b209802d4844752180d1bbabb40768609d7fb46 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/codeccontext.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/format.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b4bf1c8911e9dbe2f90aee085c22dba6b16fd12 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/format.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b88dc99b121d023cac226dbc5a42e68d92a5c5f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/frame.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/plane.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/plane.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a01e3fa9ae96ee979ea36d41ce6e996f424e1f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/plane.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/reformatter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/reformatter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1687c68c5da1c78579e116a8265ac77bbd8214a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/reformatter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/__pycache__/stream.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/video/__pycache__/stream.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24007c176758303b4e96f78765c650fc87ea9bcd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/video/__pycache__/stream.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/video/codeccontext.abi3.so b/.venv/lib/python3.12/site-packages/av/video/codeccontext.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..d34d6ffabf1a068933f685efd9db52717344c40b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/codeccontext.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d81c9b350cf53d26097f0d7c873ba02f700ce374295b2cf0835f1651841c48b +size 691369 diff --git a/.venv/lib/python3.12/site-packages/av/video/codeccontext.pxd b/.venv/lib/python3.12/site-packages/av/video/codeccontext.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d15a9fc022240920bd935c5c85f0551bd61a4dc9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/codeccontext.pxd @@ -0,0 +1,22 @@ +cimport libav as lib + +from av.codec.context cimport CodecContext +from av.video.format cimport VideoFormat +from av.video.frame cimport VideoFrame +from av.video.reformatter cimport VideoReformatter + + +# The get_format callback in AVCodecContext is called by the decoder to pick a format out of a list. +# When we want accelerated decoding, we need to figure out ahead of time what the format should be, +# and find a way to pass that into our callback so we can return it to the decoder. We use the 'opaque' +# user data field in AVCodecContext for that. This is the struct we store a pointer to in that field. +cdef struct AVCodecPrivateData: + lib.AVPixelFormat hardware_pix_fmt + bint allow_software_fallback + + +cdef class VideoCodecContext(CodecContext): + cdef AVCodecPrivateData _private_data + cdef readonly VideoReformatter reformatter + cdef VideoFrame next_frame + cdef VideoFrame _encode_upload_frame(self, VideoFrame vframe) diff --git a/.venv/lib/python3.12/site-packages/av/video/codeccontext.py b/.venv/lib/python3.12/site-packages/av/video/codeccontext.py new file mode 100644 index 0000000000000000000000000000000000000000..27dbaacb9ad20401ae4de27d2eec5029344c38f7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/codeccontext.py @@ -0,0 +1,497 @@ +import cython +import cython.cimports.libav as lib +from cython.cimports.av.codec.context import CodecContext +from cython.cimports.av.codec.hwaccel import HWAccel +from cython.cimports.av.error import err_check +from cython.cimports.av.frame import Frame +from cython.cimports.av.packet import Packet +from cython.cimports.av.utils import avrational_to_fraction, to_avrational +from cython.cimports.av.video.format import VideoFormat, get_pix_fmt, get_video_format +from cython.cimports.av.video.frame import VideoFrame, alloc_video_frame +from cython.cimports.av.video.reformatter import VideoReformatter +from cython.cimports.libc.stdint import int64_t + + +@cython.cfunc +@cython.exceptval(check=False) +def _get_hw_format( + ctx: cython.pointer[lib.AVCodecContext], + pix_fmts: cython.pointer[cython.const[lib.AVPixelFormat]], +) -> lib.AVPixelFormat: + # In the case where we requested accelerated decoding, the decoder first calls this function + # with a list that includes both the hardware format and software formats. + # First we try to pick the hardware format if it's in the list. + # However, if the decoder fails to initialize the hardware, it will call this function again, + # with only software formats in pix_fmts. We return ctx->sw_pix_fmt regardless in this case, + # because that should be in the candidate list. If not, we are out of ideas anyways. + private_data: cython.pointer[AVCodecPrivateData] = cython.cast( + cython.pointer[AVCodecPrivateData], ctx.opaque + ) + i: cython.int = 0 + while pix_fmts[i] != -1: + if pix_fmts[i] == private_data.hardware_pix_fmt: + return pix_fmts[i] + i += 1 + return ( + ctx.sw_pix_fmt if private_data.allow_software_fallback else lib.AV_PIX_FMT_NONE + ) + + +@cython.final +@cython.cclass +class VideoCodecContext(CodecContext): + @cython.cfunc + def _init( + self, + ptr: cython.pointer[lib.AVCodecContext], + codec: cython.pointer[cython.const[lib.AVCodec]], + hwaccel: HWAccel | None, + ): + CodecContext._init(self, ptr, codec, hwaccel) + + if hwaccel is None: + return + + if self.is_encoder: + # Hardware-accelerated encoding. We only attach the device context here; + # the hardware frames context depends on the final width/height/pixel + # format (set by the user after add_stream()), so it is built lazily in + # CodecContext.open() via _setup_encode_hwframes(). + self.hwaccel_ctx = hwaccel.create(self.codec, for_encoding=True) + self.ptr.hw_device_ctx = lib.av_buffer_ref(self.hwaccel_ctx.ptr) + return + + try: + self.hwaccel_ctx = hwaccel.create(self.codec) + self.ptr.hw_device_ctx = lib.av_buffer_ref(self.hwaccel_ctx.ptr) + self.ptr.pix_fmt = self.hwaccel_ctx.config.ptr.pix_fmt + self.ptr.get_format = _get_hw_format + self._private_data.hardware_pix_fmt = self.hwaccel_ctx.config.ptr.pix_fmt + self._private_data.allow_software_fallback = ( + self.hwaccel.allow_software_fallback + ) + self.ptr.opaque = cython.address(self._private_data) + except NotImplementedError: + # Some streams may not have a hardware decoder. For example, many action + # cam videos have a low resolution mjpeg stream, which is usually not + # compatible with hardware decoders. + # The user may have passed in a hwaccel because they want to decode the main + # stream with it, so we shouldn't abort even if we find a stream that can't + # be HW decoded. + # If the user wants to make sure hwaccel is actually used, they can check with the + # is_hwaccel() function on each stream's codec context. + self.hwaccel_ctx = None + + @cython.cfunc + def _encode_upload_frame(self, vframe: VideoFrame) -> VideoFrame: + # Upload a software frame onto the device for hardware-accelerated encoding. + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data + ) + + # If the user already handed us a matching hardware frame, pass it through. + if vframe.ptr.format == frames_ctx.format: + return vframe + + # Convert to the frames context's software format and size before uploading, + # since av_hwframe_transfer_data() does not change pixel format or scale. + if ( + vframe.ptr.format != frames_ctx.sw_format + or vframe.ptr.width != frames_ctx.width + or vframe.ptr.height != frames_ctx.height + ): + if not self.reformatter: + self.reformatter = VideoReformatter() + vframe = self.reformatter.reformat( + vframe, + frames_ctx.width, + frames_ctx.height, + get_video_format( + frames_ctx.sw_format, frames_ctx.width, frames_ctx.height + ), + threads=self.ptr.thread_count, + ) + + hwframe: VideoFrame = alloc_video_frame() + err_check(lib.av_hwframe_get_buffer(self.ptr.hw_frames_ctx, hwframe.ptr, 0)) + err_check(lib.av_hwframe_transfer_data(hwframe.ptr, vframe.ptr, 0)) + hwframe._copy_internal_attributes(vframe, data_layout=False) + hwframe._init_user_attributes() + + if hwframe.ptr.pts == lib.AV_NOPTS_VALUE: + hwframe.ptr.pts = self.ptr.frame_num + + return hwframe + + @cython.cfunc + def _prepare_frames_for_encode(self, input: Frame | None) -> list: + if input is None or not input: + return [None] + + vframe: VideoFrame = input + + # Hardware-accelerated encoding: upload the (software) frame to the device. + if self.ptr.hw_frames_ctx != cython.NULL: + return [self._encode_upload_frame(vframe)] + + if ( + vframe.format.pix_fmt != self.pix_fmt + or vframe.width != self.ptr.width + or vframe.height != self.ptr.height + ): + if not self.reformatter: + self.reformatter = VideoReformatter() + + vframe = self.reformatter.reformat( + vframe, + self.ptr.width, + self.ptr.height, + self.format, + threads=self.ptr.thread_count, + ) + + if vframe.ptr.pts == lib.AV_NOPTS_VALUE: + vframe.ptr.pts = self.ptr.frame_num + + return [vframe] + + @cython.cfunc + def _alloc_next_frame(self) -> Frame: + return alloc_video_frame() + + @cython.cfunc + def _setup_decoded_frame(self, frame: Frame, packet: Packet): + CodecContext._setup_decoded_frame(self, frame, packet) + vframe: VideoFrame = frame + vframe._init_user_attributes() + + @cython.cfunc + def _transfer_hwframe(self, frame: Frame): + if self.hwaccel_ctx is None: + return frame + if frame.ptr.format != self.hwaccel_ctx.config.ptr.pix_fmt: + # If we get a software frame, that means we are in software fallback mode, and don't actually + # need to transfer. + return frame + + if self.hwaccel_ctx.is_hw_owned: + cython.cast(VideoFrame, frame)._device_id = self.hwaccel_ctx.device_id + return frame + + frame_sw: Frame = self._alloc_next_frame() + err_check(lib.av_hwframe_transfer_data(frame_sw.ptr, frame.ptr, 0)) + frame_sw._copy_internal_attributes(frame, data_layout=False) + return frame_sw + + @property + def format(self): + return get_video_format( + cython.cast(lib.AVPixelFormat, self.ptr.pix_fmt), + self.ptr.width, + self.ptr.height, + ) + + @format.setter + def format(self, format: VideoFormat): + self._assert_not_open("format") + self.ptr.pix_fmt = format.pix_fmt + self.ptr.width = format.width + self.ptr.height = format.height + + @property + def width(self): + if self.ptr is cython.NULL: + return 0 + return self.ptr.width + + @width.setter + def width(self, value: cython.uint): + self._assert_not_open("width") + self.ptr.width = value + + @property + def height(self): + if self.ptr is cython.NULL: + return 0 + return self.ptr.height + + @height.setter + def height(self, value: cython.uint): + self._assert_not_open("height") + self.ptr.height = value + + @property + def bits_per_coded_sample(self): + """ + The number of bits per sample in the codedwords. It's mandatory for this to be set for some formats to decode properly. + + Wraps :ffmpeg:`AVCodecContext.bits_per_coded_sample`. + + :type: int + """ + return self.ptr.bits_per_coded_sample + + @bits_per_coded_sample.setter + def bits_per_coded_sample(self, value: cython.int): + if self.is_encoder: + raise ValueError("Not supported for encoders") + + self.ptr.bits_per_coded_sample = value + + @property + def pix_fmt(self): + """ + The pixel format's name. + + :type: str | None + """ + desc: cython.pointer[cython.const[lib.AVPixFmtDescriptor]] = ( + lib.av_pix_fmt_desc_get(cython.cast(lib.AVPixelFormat, self.ptr.pix_fmt)) + ) + if desc == cython.NULL: + return None + return cython.cast(str, desc.name) + + @pix_fmt.setter + def pix_fmt(self, value): + self._assert_not_open("pix_fmt") + self.ptr.pix_fmt = get_pix_fmt(value) + + @property + def sw_format(self): + """ + For a hardware context (e.g. ``format.name == "cuda"``), the underlying + software pixel format (``nv12``, ``p010le``, ...). ``None`` for a regular + software context. + + :type: VideoFormat | None + """ + if not self.ptr.hw_frames_ctx: + if self.ptr.sw_pix_fmt != lib.AV_PIX_FMT_NONE: + return get_video_format( + cython.cast(lib.AVPixelFormat, self.ptr.sw_pix_fmt), + self.ptr.width, + self.ptr.height, + ) + return None + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data + ) + return get_video_format(frames_ctx.sw_format, self.ptr.width, self.ptr.height) + + @sw_format.setter + def sw_format(self, value): + self._assert_not_open("sw_format") + self.ptr.sw_pix_fmt = get_pix_fmt(value) + + @property + def framerate(self): + """ + The frame rate, in frames per second. + + :type: fractions.Fraction + """ + return avrational_to_fraction(cython.address(self.ptr.framerate)) + + @framerate.setter + def framerate(self, value): + self._assert_not_open("framerate") + to_avrational(value, cython.address(self.ptr.framerate)) + + @property + def rate(self): + """Another name for :attr:`framerate`.""" + return self.framerate + + @rate.setter + def rate(self, value): + self.framerate = value + + @property + def gop_size(self): + """ + Sets the number of frames between keyframes. Used only for encoding. + + :type: int + """ + if self.is_decoder: + raise RuntimeError("Cannot access 'gop_size' as a decoder") + return self.ptr.gop_size + + @gop_size.setter + def gop_size(self, value: cython.int): + if self.is_decoder: + raise RuntimeError("Cannot access 'gop_size' as a decoder") + self.ptr.gop_size = value + + @property + def sample_aspect_ratio(self): + return avrational_to_fraction(cython.address(self.ptr.sample_aspect_ratio)) + + @sample_aspect_ratio.setter + def sample_aspect_ratio(self, value): + to_avrational(value, cython.address(self.ptr.sample_aspect_ratio)) + + @property + def display_aspect_ratio(self): + dar: lib.AVRational + lib.av_reduce( + cython.address(dar.num), + cython.address(dar.den), + self.ptr.width * self.ptr.sample_aspect_ratio.num, + self.ptr.height * self.ptr.sample_aspect_ratio.den, + 1024 * 1024, + ) + + return avrational_to_fraction(cython.address(dar)) + + @property + def has_b_frames(self): + """ + :type: bool + """ + return bool(self.ptr.has_b_frames) + + @property + def reorder_depth(self): + """Raw ``has_b_frames`` value from FFmpeg (int, not bool). + + After :meth:`flush_buffers`, FFmpeg may reset the internal reorder + heuristic. Set this to the known reorder depth *after* seeking to + avoid dropped hierarchical B-frames. + """ + return self.ptr.has_b_frames + + @reorder_depth.setter + def reorder_depth(self, value: cython.int): + self.ptr.has_b_frames = value + + @property + def coded_width(self): + """ + :type: int + """ + return self.ptr.coded_width + + @property + def coded_height(self): + """ + :type: int + """ + return self.ptr.coded_height + + @property + def color_range(self): + """ + Describes the signal range of the colorspace. + + Wraps :ffmpeg:`AVFrame.color_range`. + + :type: int + """ + return self.ptr.color_range + + @color_range.setter + def color_range(self, value): + self.ptr.color_range = value + + @property + def color_primaries(self): + """ + Describes the RGB/XYZ matrix of the colorspace. + + Wraps :ffmpeg:`AVFrame.color_primaries`. + + :type: int + """ + return self.ptr.color_primaries + + @color_primaries.setter + def color_primaries(self, value): + self.ptr.color_primaries = value + + @property + def color_trc(self): + """ + Describes the linearization function (a.k.a. transformation characteristics) of the colorspace. + + Wraps :ffmpeg:`AVFrame.color_trc`. + + :type: int + """ + return self.ptr.color_trc + + @color_trc.setter + def color_trc(self, value): + self.ptr.color_trc = value + + @property + def colorspace(self): + """ + Describes the YUV/RGB transformation matrix of the colorspace. + + Wraps :ffmpeg:`AVFrame.colorspace`. + + :type: int + """ + return self.ptr.colorspace + + @colorspace.setter + def colorspace(self, value): + self.ptr.colorspace = value + + @property + def field_order(self): + """The video field order as FFmpeg's raw integer value. + + Wraps :ffmpeg:`AVCodecContext.field_order`. + + """ + return self.ptr.field_order + + @field_order.setter + def field_order(self, value: cython.int): + self.ptr.field_order = cython.cast(lib.AVFieldOrder, value) + + @property + def max_b_frames(self): + """ + The maximum run of consecutive B frames when encoding a video. + + :type: int + """ + return self.ptr.max_b_frames + + @max_b_frames.setter + def max_b_frames(self, value): + self.ptr.max_b_frames = value + + @property + def qmin(self): + """ + The minimum quantiser value of an encoded stream. + + Wraps :ffmpeg:`AVCodecContext.qmin`. + + :type: int + """ + return self.ptr.qmin + + @qmin.setter + def qmin(self, value): + self.ptr.qmin = value + + @property + def qmax(self): + """ + The maximum quantiser value of an encoded stream. + + Wraps :ffmpeg:`AVCodecContext.qmax`. + + :type: int + """ + return self.ptr.qmax + + @qmax.setter + def qmax(self, value): + self.ptr.qmax = value diff --git a/.venv/lib/python3.12/site-packages/av/video/codeccontext.pyi b/.venv/lib/python3.12/site-packages/av/video/codeccontext.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6f11c9aa984e1bbb1d7c49232b32a294a7a983a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/codeccontext.pyi @@ -0,0 +1,42 @@ +from collections.abc import Iterator +from fractions import Fraction +from typing import Literal + +from av.codec.context import CodecContext +from av.packet import Packet + +from .format import VideoFormat +from .frame import VideoFrame + +class VideoCodecContext(CodecContext): + format: VideoFormat | None + width: int + height: int + bits_per_coded_sample: int + pix_fmt: str | None + @property + def sw_format(self) -> VideoFormat | None: ... + @sw_format.setter + def sw_format(self, value: str) -> None: ... + framerate: Fraction + rate: Fraction + gop_size: int + sample_aspect_ratio: Fraction | None + display_aspect_ratio: Fraction | None + has_b_frames: bool + reorder_depth: int + max_b_frames: int + coded_width: int + coded_height: int + color_range: int + color_primaries: int + color_trc: int + colorspace: int + field_order: int + qmin: int + qmax: int + type: Literal["video"] + + def encode(self, frame: VideoFrame | None = None) -> list[Packet]: ... + def encode_lazy(self, frame: VideoFrame | None = None) -> Iterator[Packet]: ... + def decode(self, packet: Packet | None = None) -> list[VideoFrame]: ... diff --git a/.venv/lib/python3.12/site-packages/av/video/format.abi3.so b/.venv/lib/python3.12/site-packages/av/video/format.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..f4b81eb4c47d07fd7524d24378fc3a6bc99b93d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/format.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33c49961421e99cd353251a902a71146f204736fa62c0004da3d8061c42fbec5 +size 622281 diff --git a/.venv/lib/python3.12/site-packages/av/video/format.pxd b/.venv/lib/python3.12/site-packages/av/video/format.pxd new file mode 100644 index 0000000000000000000000000000000000000000..679525a2a3736ae415141b95d244ca8da980b802 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/format.pxd @@ -0,0 +1,20 @@ +cimport libav as lib + + +cdef class VideoFormat: + cdef lib.AVPixelFormat pix_fmt + cdef const lib.AVPixFmtDescriptor *ptr + cdef readonly unsigned int width, height + cdef _init(self, lib.AVPixelFormat pix_fmt, unsigned int width, unsigned int height) + cpdef chroma_width(self, int luma_width=?) + cpdef chroma_height(self, int luma_height=?) + + +cdef class VideoFormatComponent: + cdef VideoFormat format + cdef readonly unsigned int index + cdef const lib.AVComponentDescriptor *ptr + + +cdef VideoFormat get_video_format(lib.AVPixelFormat c_format, unsigned int width, unsigned int height) +cdef lib.AVPixelFormat get_pix_fmt(const char *name) except lib.AV_PIX_FMT_NONE diff --git a/.venv/lib/python3.12/site-packages/av/video/format.py b/.venv/lib/python3.12/site-packages/av/video/format.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab505051b287de9b5cf3d5b73b7886f4b3ec7d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/format.py @@ -0,0 +1,209 @@ +import cython +from cython import uint as cuint + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def get_video_format( + c_format: lib.AVPixelFormat, width: cuint, height: cuint +) -> VideoFormat | None: + if c_format == lib.AV_PIX_FMT_NONE: + return None + + format: VideoFormat = VideoFormat.__new__(VideoFormat, _cinit_bypass_sentinel) + format._init(c_format, width, height) + return format + + +@cython.cfunc +@cython.exceptval(lib.AV_PIX_FMT_NONE, check=False) +def get_pix_fmt(name: cython.p_const_char) -> lib.AVPixelFormat: + """Wrapper for lib.av_get_pix_fmt with error checking.""" + + pix_fmt: lib.AVPixelFormat = lib.av_get_pix_fmt(name) + if pix_fmt == lib.AV_PIX_FMT_NONE: + raise ValueError(f"not a pixel format: {name!r}") + return pix_fmt + + +@cython.final +@cython.cclass +class VideoFormat: + """ + + >>> format = VideoFormat('rgb24') + >>> format.name + 'rgb24' + + """ + + def __cinit__(self, name, width=0, height=0): + if name is _cinit_bypass_sentinel: + return + + if isinstance(name, VideoFormat): + other: VideoFormat = cython.cast(VideoFormat, name) + self._init(other.pix_fmt, width or other.width, height or other.height) + return + + pix_fmt: lib.AVPixelFormat = get_pix_fmt(name) + self._init(pix_fmt, width, height) + + @cython.cfunc + def _init(self, pix_fmt: lib.AVPixelFormat, width: cuint, height: cuint): + self.pix_fmt = pix_fmt + self.ptr = lib.av_pix_fmt_desc_get(pix_fmt) + self.width = width + self.height = height + + def __repr__(self): + if self.width or self.height: + return f"" + else: + return f"" + + def __int__(self): + return int(self.pix_fmt) + + @property + def name(self): + """Canonical name of the pixel format.""" + return cython.cast(str, self.ptr.name) + + @property + def components(self): + return tuple( + VideoFormatComponent(self, i) for i in range(self.ptr.nb_components) + ) + + @property + def bits_per_pixel(self): + return lib.av_get_bits_per_pixel(self.ptr) + + @property + def padded_bits_per_pixel(self): + return lib.av_get_padded_bits_per_pixel(self.ptr) + + @property + def is_big_endian(self): + """Pixel format is big-endian.""" + return bool(self.ptr.flags & lib.AV_PIX_FMT_FLAG_BE) + + @property + def has_palette(self): + """Pixel format has a palette in data[1], values are indexes in this palette.""" + return bool(self.ptr.flags & lib.AV_PIX_FMT_FLAG_PAL) + + @property + def is_bit_stream(self): + """All values of a component are bit-wise packed end to end.""" + return bool(self.ptr.flags & lib.AV_PIX_FMT_FLAG_BITSTREAM) + + @property + def is_planar(self): + """At least one pixel component is not in the first data plane.""" + return bool(self.ptr.flags & lib.AV_PIX_FMT_FLAG_PLANAR) + + @property + def is_rgb(self): + """The pixel format contains RGB-like data (as opposed to YUV/grayscale).""" + return bool(self.ptr.flags & lib.AV_PIX_FMT_FLAG_RGB) + + @property + def is_bayer(self): + """The pixel format contains Bayer data.""" + return bool(self.ptr.flags & lib.AV_PIX_FMT_FLAG_BAYER) + + @cython.ccall + def chroma_width(self, luma_width: cython.int = 0): + """chroma_width(luma_width=0) + + Width of a chroma plane relative to a luma plane. + + :param int luma_width: Width of the luma plane; defaults to ``self.width``. + + """ + luma_width = luma_width or self.width + return -((-luma_width) >> self.ptr.log2_chroma_w) if luma_width else 0 + + @cython.ccall + def chroma_height(self, luma_height: cython.int = 0): + """chroma_height(luma_height=0) + + Height of a chroma plane relative to a luma plane. + + :param int luma_height: Height of the luma plane; defaults to ``self.height``. + + """ + luma_height = luma_height or self.height + return -((-luma_height) >> self.ptr.log2_chroma_h) if luma_height else 0 + + +@cython.final +@cython.cclass +class VideoFormatComponent: + def __cinit__(self, format: VideoFormat, index: cython.uint): + self.format = format + self.index = index + self.ptr = cython.address(format.ptr.comp[index]) + + @property + def plane(self): + """The index of the plane which contains this component.""" + return self.ptr.plane + + @property + def bits(self): + """Number of bits in the component.""" + return self.ptr.depth + + @property + def is_alpha(self): + """Is this component an alpha channel?""" + return (self.index == 1 and self.format.ptr.nb_components == 2) or ( + self.index == 3 and self.format.ptr.nb_components == 4 + ) + + @property + def is_luma(self): + """Is this component a luma channel?""" + return self.index == 0 and ( + self.format.ptr.nb_components == 1 + or self.format.ptr.nb_components == 2 + or not self.format.is_rgb + ) + + @property + def is_chroma(self): + """Is this component a chroma channel?""" + return (self.index == 1 or self.index == 2) and ( + self.format.ptr.log2_chroma_w or self.format.ptr.log2_chroma_h + ) + + @property + def width(self): + """The width of this component's plane. + + Requires the parent :class:`VideoFormat` to have a width. + + """ + return self.format.chroma_width() if self.is_chroma else self.format.width + + @property + def height(self): + """The height of this component's plane. + + Requires the parent :class:`VideoFormat` to have a height. + + """ + return self.format.chroma_height() if self.is_chroma else self.format.height + + +names = set() +desc = cython.declare(cython.pointer[cython.const[lib.AVPixFmtDescriptor]], cython.NULL) +while True: + desc = lib.av_pix_fmt_desc_next(desc) + if not desc: + break + names.add(desc.name) diff --git a/.venv/lib/python3.12/site-packages/av/video/format.pyi b/.venv/lib/python3.12/site-packages/av/video/format.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1ee0bc7a7c266b403678ac2534b4f920da833e4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/format.pyi @@ -0,0 +1,30 @@ +class VideoFormat: + name: str + bits_per_pixel: int + padded_bits_per_pixel: int + is_big_endian: bool + has_palette: bool + is_bit_stream: bool + is_planar: bool + width: int + height: int + @property + def components(self) -> tuple[VideoFormatComponent, ...]: ... + @property + def is_rgb(self) -> bool: ... + @property + def is_bayer(self) -> bool: ... + def __init__(self, name: str, width: int = 0, height: int = 0) -> None: ... + def chroma_width(self, luma_width: int = 0) -> int: ... + def chroma_height(self, luma_height: int = 0) -> int: ... + +class VideoFormatComponent: + plane: int + bits: int + is_alpha: bool + is_luma: bool + is_chroma: bool + width: int + height: int + + def __init__(self, format: VideoFormat, index: int) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/video/frame.abi3.so b/.venv/lib/python3.12/site-packages/av/video/frame.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..d761c814489bca3df3ecb255fc5c9b3ef3a308eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/frame.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60eea85dfaf9169383226094e193335c347ed91c868b07155e676113e2f3fc6e +size 3953737 diff --git a/.venv/lib/python3.12/site-packages/av/video/frame.pxd b/.venv/lib/python3.12/site-packages/av/video/frame.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7f93c99ece31e880a7f989d11481b23b935f0839 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/frame.pxd @@ -0,0 +1,29 @@ +cimport libav as lib +from libc.stdint cimport uint8_t, uintptr_t + +from av.frame cimport Frame +from av.video.format cimport VideoFormat +from av.video.reformatter cimport VideoReformatter + + +cdef class CudaContext: + cdef readonly int device_id + cdef readonly bint primary_ctx + cdef readonly bint current_ctx + cdef readonly uintptr_t cuda_stream + cdef lib.AVBufferRef* _device_ref + cdef dict _frames_cache + cdef lib.AVBufferRef* _get_device_ref(self) + cdef public lib.AVBufferRef* get_frames_ctx( + self, lib.AVPixelFormat sw_fmt, int width, int height + ) + +cdef class VideoFrame(Frame): + cdef CudaContext _cuda_ctx + cdef VideoReformatter reformatter + cdef readonly VideoFormat format + cdef readonly int _device_id + cdef _init(self, lib.AVPixelFormat format, unsigned int width, unsigned int height) + cdef _init_user_attributes(self) + +cdef VideoFrame alloc_video_frame() diff --git a/.venv/lib/python3.12/site-packages/av/video/frame.py b/.venv/lib/python3.12/site-packages/av/video/frame.py new file mode 100644 index 0000000000000000000000000000000000000000..0d22c481cb9b2467fd25862effe6eebeaf93d0d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/frame.py @@ -0,0 +1,1933 @@ +import sys +from enum import IntEnum + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.dictionary import Dictionary +from cython.cimports.av.error import err_check +from cython.cimports.av.sidedata.sidedata import get_display_rotation +from cython.cimports.av.utils import check_ndarray +from cython.cimports.av.video.format import get_pix_fmt, get_video_format +from cython.cimports.av.video.plane import DLManagedTensor, VideoPlane, kCPU, kCuda +from cython.cimports.cpython.exc import PyErr_Clear +from cython.cimports.cpython.pycapsule import ( + PyCapsule_GetPointer, + PyCapsule_IsValid, + PyCapsule_SetName, +) +from cython.cimports.cpython.ref import Py_DECREF, Py_INCREF +from cython.cimports.hwcontext_cuda import AVCUDADeviceContext, CUstream +from cython.cimports.libc.stdint import int64_t, uint8_t, uintptr_t + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def _cuda_device_ctx_free( + device_ctx: cython.pointer[lib.AVHWDeviceContext], +) -> cython.void: + owner_ref: cython.pointer[lib.AVBufferRef] = cython.cast( + cython.pointer[lib.AVBufferRef], device_ctx.user_opaque + ) + lib.av_buffer_unref(cython.address(owner_ref)) + device_ctx.user_opaque = cython.NULL + + +@cython.final +@cython.cclass +class CudaContext: + """A reusable FFmpeg CUDA context for frames imported with DLPack. + + :param int device_id: CUDA device ordinal. + :param bool primary_ctx: Retain the device's primary CUDA context. + :param bool current_ctx: Wrap the CUDA context current on the calling thread + when this object is first used. This is mutually exclusive with + ``primary_ctx``. + :param int cuda_stream: Optional raw ``CUstream`` pointer for FFmpeg CUDA + operations, including NVENC input and output. The caller owns the + stream and must keep it alive as long as this context can be used. + Nonzero stream pointers are currently supported only for logical CUDA + device 0. To use another physical GPU, expose it as logical device 0 + via ``CUDA_VISIBLE_DEVICES``. + """ + + def __cinit__( + self, + device_id: cython.int = 0, + primary_ctx: cython.bint = True, + current_ctx: cython.bint = False, + cuda_stream: object = None, + ): + self.device_id = device_id + self.primary_ctx = primary_ctx + self.current_ctx = current_ctx + self.cuda_stream = 0 + self._device_ref = cython.NULL + self._frames_cache = {} + if primary_ctx and current_ctx: + raise ValueError("primary_ctx and current_ctx are mutually exclusive") + if cuda_stream is not None: + if not isinstance(cuda_stream, int): + raise TypeError("cuda_stream must be an integer or None") + if cuda_stream < 0: + raise ValueError("cuda_stream must be non-negative") + self.cuda_stream = cython.cast(uintptr_t, cuda_stream) + if self.cuda_stream and self.device_id != 0: + raise ValueError( + "cuda_stream currently requires device_id 0; expose the desired " + "physical GPU as logical device 0 via CUDA_VISIBLE_DEVICES" + ) + + def __dealloc__(self): + ref: cython.pointer[lib.AVBufferRef] + + for v in self._frames_cache.values(): + ref = cython.cast( + cython.pointer[lib.AVBufferRef], + cython.cast(cython.size_t, v), + ) + lib.av_buffer_unref(cython.address(ref)) + self._frames_cache.clear() + + ref = self._device_ref + if ref != cython.NULL: + lib.av_buffer_unref(cython.address(ref)) + self._device_ref = cython.NULL + + @cython.cfunc + def _get_device_ref(self) -> cython.pointer[lib.AVBufferRef]: + device_ref: cython.pointer[lib.AVBufferRef] = self._device_ref + owner_ref: cython.pointer[lib.AVBufferRef] + if device_ref != cython.NULL: + return device_ref + + owner_ref = cython.NULL + device_bytes = f"{self.device_id}".encode() + c_device: cython.p_char = device_bytes + options_dict = {"primary_ctx": "1" if self.primary_ctx else "0"} + if self.current_ctx: + options_dict["current_ctx"] = "1" + options: Dictionary = Dictionary(options_dict) + err_check( + lib.av_hwdevice_ctx_create( + cython.address(owner_ref), + lib.AV_HWDEVICE_TYPE_CUDA, + c_device, + options.ptr, + 0, + ) + ) + if not self.cuda_stream: + self._device_ref = owner_ref + return owner_ref + + device_ref = lib.av_hwdevice_ctx_alloc(lib.AV_HWDEVICE_TYPE_CUDA) + if device_ref == cython.NULL: + lib.av_buffer_unref(cython.address(owner_ref)) + raise MemoryError("av_hwdevice_ctx_alloc() failed") + + try: + owner_device_ctx: cython.pointer[lib.AVHWDeviceContext] = cython.cast( + cython.pointer[lib.AVHWDeviceContext], owner_ref.data + ) + owner_cuda_ctx: cython.pointer[AVCUDADeviceContext] = cython.cast( + cython.pointer[AVCUDADeviceContext], owner_device_ctx.hwctx + ) + device_ctx: cython.pointer[lib.AVHWDeviceContext] = cython.cast( + cython.pointer[lib.AVHWDeviceContext], device_ref.data + ) + cuda_ctx: cython.pointer[AVCUDADeviceContext] = cython.cast( + cython.pointer[AVCUDADeviceContext], device_ctx.hwctx + ) + cuda_ctx.cuda_ctx = owner_cuda_ctx.cuda_ctx + cuda_ctx.stream = cython.cast(CUstream, self.cuda_stream) + device_ctx.free = _cuda_device_ctx_free + device_ctx.user_opaque = cython.cast(cython.p_void, owner_ref) + owner_ref = cython.NULL + err_check(lib.av_hwdevice_ctx_init(device_ref)) + except Exception: + lib.av_buffer_unref(cython.address(device_ref)) + lib.av_buffer_unref(cython.address(owner_ref)) + raise + + self._device_ref = device_ref + return device_ref + + @cython.cfunc + def get_frames_ctx( + self, + sw_fmt: lib.AVPixelFormat, + width: cython.int, + height: cython.int, + ) -> cython.pointer[lib.AVBufferRef]: + key = (int(sw_fmt), int(width), int(height)) + cached = self._frames_cache.get(key) + cached_ref: cython.pointer[lib.AVBufferRef] + out_ref: cython.pointer[lib.AVBufferRef] + + if cached is not None: + cached_ref = cython.cast( + cython.pointer[lib.AVBufferRef], + cython.cast(cython.size_t, cached), + ) + out_ref = lib.av_buffer_ref(cached_ref) + if out_ref == cython.NULL: + raise MemoryError("av_buffer_ref() failed") + return out_ref + + device_ref = self._get_device_ref() + + frames_ref: cython.pointer[lib.AVBufferRef] = lib.av_hwframe_ctx_alloc( + device_ref + ) + if frames_ref == cython.NULL: + raise MemoryError("av_hwframe_ctx_alloc() failed") + + try: + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], frames_ref.data + ) + frames_ctx.format = get_pix_fmt(b"cuda") + frames_ctx.sw_format = sw_fmt + frames_ctx.width = int(width) + frames_ctx.height = int(height) + err_check(lib.av_hwframe_ctx_init(frames_ref)) + except Exception: + lib.av_buffer_unref(cython.address(frames_ref)) + raise + + out_ref = lib.av_buffer_ref(frames_ref) + if out_ref == cython.NULL: + lib.av_buffer_unref(cython.address(frames_ref)) + raise MemoryError("av_buffer_ref() failed") + + self._frames_cache[key] = cython.cast(cython.size_t, frames_ref) + return out_ref + + +@cython.cfunc +def _consume_dlpack(obj: object, stream: object) -> cython.pointer[DLManagedTensor]: + capsule: object + managed: cython.pointer[DLManagedTensor] + + if hasattr(obj, "__dlpack__"): + capsule = obj.__dlpack__() if stream is None else obj.__dlpack__(stream=stream) + else: + capsule = obj + + if not PyCapsule_IsValid(capsule, b"dltensor"): + PyErr_Clear() + raise TypeError( + "expected a DLPack capsule or an object implementing __dlpack__" + ) + + managed = cython.cast( + cython.pointer[DLManagedTensor], + PyCapsule_GetPointer(capsule, b"dltensor"), + ) + if managed == cython.NULL: + raise ValueError("PyCapsule_GetPointer returned NULL") + + if PyCapsule_SetName(capsule, b"used_dltensor") != 0: + raise RuntimeError("PyCapsule_SetName failed") + + return managed + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def _dlpack_avbuffer_free( + opaque: cython.p_void, + data: cython.pointer[uint8_t], +) -> cython.void: + managed: cython.pointer[DLManagedTensor] = cython.cast( + cython.pointer[DLManagedTensor], opaque + ) + if managed != cython.NULL: + managed.deleter(managed) + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def _numpy_avbuffer_free( + opaque: cython.p_void, + data: cython.pointer[uint8_t], +) -> cython.void: + if opaque != cython.NULL: + with cython.gil: + Py_DECREF(cython.cast(object, opaque)) + + +_cinit_bypass_sentinel = cython.declare(object, object()) + +# `pix_fmt`s supported by Frame.to_ndarray() and Frame.from_ndarray() +supported_np_pix_fmts = { + "abgr", + "argb", + "bayer_bggr16be", + "bayer_bggr16le", + "bayer_bggr8", + "bayer_gbrg16be", + "bayer_gbrg16le", + "bayer_gbrg8", + "bayer_grbg16be", + "bayer_grbg16le", + "bayer_grbg8", + "bayer_rggb16be", + "bayer_rggb16le", + "bayer_rggb8", + "bgr24", + "bgr48be", + "bgr48le", + "bgr8", + "bgra", + "bgra64be", + "bgra64le", + "gbrap", + "gbrap10be", + "gbrap10le", + "gbrap12be", + "gbrap12le", + "gbrap14be", + "gbrap14le", + "gbrap16be", + "gbrap16le", + "gbrapf32be", + "gbrapf32le", + "gbrp", + "gbrp10be", + "gbrp10le", + "gbrp12be", + "gbrp12le", + "gbrp14be", + "gbrp14le", + "gbrp16be", + "gbrp16le", + "gbrp9be", + "gbrp9le", + "gbrpf32be", + "gbrpf32le", + "gray", + "gray10be", + "gray10le", + "gray12be", + "gray12le", + "gray14be", + "gray14le", + "gray16be", + "gray16le", + "gray8", + "gray9be", + "gray9le", + "grayf32be", + "grayf32le", + "nv12", + "pal8", + "rgb24", + "rgb48be", + "rgb48le", + "rgb8", + "rgba", + "rgba64be", + "rgba64le", + "rgbaf16be", + "rgbaf16le", + "rgbaf32be", + "rgbaf32le", + "rgbf32be", + "rgbf32le", + "yuv420p", + "yuv420p10le", + "yuv422p10le", + "yuv444p", + "yuv444p16be", + "yuv444p16le", + "yuva444p16be", + "yuva444p16le", + "yuvj420p", + "yuvj444p", + "yuyv422", +} + +# Mapping from format name to (itemsize, dtype) for formats where planes +# are simply concatenated into shape (height, width, channels). +_np_pix_fmt_dtypes = cython.declare( + dict[str, tuple[cython.uint, str]], + { + "abgr": (4, "uint8"), + "argb": (4, "uint8"), + "bayer_bggr8": (1, "uint8"), + "bayer_gbrg8": (1, "uint8"), + "bayer_grbg8": (1, "uint8"), + "bayer_rggb8": (1, "uint8"), + "bayer_bggr16le": (2, "uint16"), + "bayer_bggr16be": (2, "uint16"), + "bayer_gbrg16le": (2, "uint16"), + "bayer_gbrg16be": (2, "uint16"), + "bayer_grbg16le": (2, "uint16"), + "bayer_grbg16be": (2, "uint16"), + "bayer_rggb16le": (2, "uint16"), + "bayer_rggb16be": (2, "uint16"), + "bgr24": (3, "uint8"), + "bgr48be": (6, "uint16"), + "bgr48le": (6, "uint16"), + "bgr8": (1, "uint8"), + "bgra": (4, "uint8"), + "bgra64be": (8, "uint16"), + "bgra64le": (8, "uint16"), + "gbrap": (1, "uint8"), + "gbrap10be": (2, "uint16"), + "gbrap10le": (2, "uint16"), + "gbrap12be": (2, "uint16"), + "gbrap12le": (2, "uint16"), + "gbrap14be": (2, "uint16"), + "gbrap14le": (2, "uint16"), + "gbrap16be": (2, "uint16"), + "gbrap16le": (2, "uint16"), + "gbrapf32be": (4, "float32"), + "gbrapf32le": (4, "float32"), + "gbrp": (1, "uint8"), + "gbrp10be": (2, "uint16"), + "gbrp10le": (2, "uint16"), + "gbrp12be": (2, "uint16"), + "gbrp12le": (2, "uint16"), + "gbrp14be": (2, "uint16"), + "gbrp14le": (2, "uint16"), + "gbrp16be": (2, "uint16"), + "gbrp16le": (2, "uint16"), + "gbrp9be": (2, "uint16"), + "gbrp9le": (2, "uint16"), + "gbrpf32be": (4, "float32"), + "gbrpf32le": (4, "float32"), + "gray": (1, "uint8"), + "gray10be": (2, "uint16"), + "gray10le": (2, "uint16"), + "gray12be": (2, "uint16"), + "gray12le": (2, "uint16"), + "gray14be": (2, "uint16"), + "gray14le": (2, "uint16"), + "gray16be": (2, "uint16"), + "gray16le": (2, "uint16"), + "gray8": (1, "uint8"), + "gray9be": (2, "uint16"), + "gray9le": (2, "uint16"), + "grayf32be": (4, "float32"), + "grayf32le": (4, "float32"), + "rgb24": (3, "uint8"), + "rgb48be": (6, "uint16"), + "rgb48le": (6, "uint16"), + "rgb8": (1, "uint8"), + "rgba": (4, "uint8"), + "rgba64be": (8, "uint16"), + "rgba64le": (8, "uint16"), + "rgbaf16be": (8, "float16"), + "rgbaf16le": (8, "float16"), + "rgbaf32be": (16, "float32"), + "rgbaf32le": (16, "float32"), + "rgbf32be": (12, "float32"), + "rgbf32le": (12, "float32"), + "yuv444p": (1, "uint8"), + "yuv444p16be": (2, "uint16"), + "yuv444p16le": (2, "uint16"), + "yuva444p16be": (2, "uint16"), + "yuva444p16le": (2, "uint16"), + "yuvj444p": (1, "uint8"), + "yuyv422": (2, "uint8"), + }, +) + + +@cython.cfunc +def alloc_video_frame() -> VideoFrame: + """Get a mostly uninitialized VideoFrame. + + You MUST call VideoFrame._init(...) or VideoFrame._init_user_attributes() + before exposing to the user. + + """ + return VideoFrame(_cinit_bypass_sentinel) + + +class PictureType(IntEnum): + NONE = lib.AV_PICTURE_TYPE_NONE # Undefined + I = lib.AV_PICTURE_TYPE_I # Intra + P = lib.AV_PICTURE_TYPE_P # Predicted + B = lib.AV_PICTURE_TYPE_B # Bi-directional predicted + S = lib.AV_PICTURE_TYPE_S # S(GMC)-VOP MPEG-4 + SI = lib.AV_PICTURE_TYPE_SI # Switching intra + SP = lib.AV_PICTURE_TYPE_SP # Switching predicted + BI = lib.AV_PICTURE_TYPE_BI # BI type + + +_is_big_endian = cython.declare(cython.bint, sys.byteorder == "big") + + +@cython.cfunc +@cython.inline +def byteswap_array(array, big_endian: cython.bint): + if _is_big_endian != big_endian: + return array.byteswap() + return array + + +@cython.cfunc +def copy_bytes_to_plane( + img_bytes, + plane: VideoPlane, + bytes_per_pixel: cython.uint, + flip_horizontal: cython.bint, + flip_vertical: cython.bint, +): + i_buf: cython.const[uint8_t][:] = img_bytes + i_pos: cython.size_t = 0 + i_stride: cython.size_t = plane.width * bytes_per_pixel + + o_buf: uint8_t[:] = plane + o_pos: cython.size_t = 0 + o_stride: cython.size_t = abs(plane.line_size) + + start_row, end_row, step = cython.declare(cython.int) + if flip_vertical: + start_row = plane.height - 1 + end_row = -1 + step = -1 + else: + start_row = 0 + end_row = plane.height + step = 1 + + for row in range(start_row, end_row, step): + i_pos = row * i_stride + if flip_horizontal: + i: cython.Py_ssize_t + for i in range(0, i_stride, bytes_per_pixel): + j: cython.Py_ssize_t + for j in range(bytes_per_pixel): + o_buf[o_pos + i + j] = i_buf[ + i_pos + i_stride - i - bytes_per_pixel + j + ] + else: + o_buf[o_pos : o_pos + i_stride] = i_buf[i_pos : i_pos + i_stride] + o_pos += o_stride + + +@cython.cfunc +def copy_array_to_plane(array, plane: VideoPlane, bytes_per_pixel: cython.uint): + imgbytes: bytes = array.tobytes() + copy_bytes_to_plane(imgbytes, plane, bytes_per_pixel, False, False) + + +@cython.cfunc +@cython.inline +def useful_array( + plane: VideoPlane, bytes_per_pixel: cython.uint = 1, dtype: str = "uint8" +): + """ + Return the useful part of the VideoPlane as a strided array. + + We are simply creating a view that discards any padding which was added for + alignment. + """ + import numpy as np + + dtype_obj = np.dtype(dtype) + line_size = plane.frame.ptr.linesize[plane.index] + total_line_size = abs(line_size) + itemsize = dtype_obj.itemsize + channels = bytes_per_pixel // itemsize + + if channels == 1: + shape = (plane.height, plane.width) + strides = (total_line_size, itemsize) + else: + shape = (plane.height, plane.width, channels) + strides = (total_line_size, bytes_per_pixel, itemsize) + + if line_size < 0: + offset = (plane.height - 1) * total_line_size + strides = (-total_line_size, *strides[1:]) + return np.ndarray( + shape, dtype=dtype_obj, buffer=plane, offset=offset, strides=strides + ) + + return np.ndarray(shape, dtype=dtype_obj, buffer=plane, strides=strides) + + +@cython.cfunc +def check_ndarray_shape(array: object, ok: cython.bint): + if not ok: + raise ValueError(f"Unexpected numpy array shape `{array.shape}`") + + +@cython.final +@cython.cclass +class VideoFrame(Frame): + def __cinit__(self, width=0, height=0, format="yuv420p"): + if width is _cinit_bypass_sentinel: + return + + c_format: lib.AVPixelFormat = get_pix_fmt(format) + self._init(c_format, width, height) + + @cython.cfunc + def _init(self, format: lib.AVPixelFormat, width: cython.uint, height: cython.uint): + res: cython.int = 0 + + with cython.nogil: + self.ptr.width = width + self.ptr.height = height + self.ptr.format = format + + # We enforce aligned buffers, otherwise `sws_scale_frame` can perform + # poorly or even cause out-of-bounds reads and writes. + if width and height: + res = lib.av_frame_get_buffer(self.ptr, 16) + + if res: + err_check(res) + + self._init_user_attributes() + + @cython.cfunc + def _init_user_attributes(self): + self.format = get_video_format( + cython.cast(lib.AVPixelFormat, self.ptr.format), + self.ptr.width, + self.ptr.height, + ) + + def __dealloc__(self): + lib.av_frame_unref(self.ptr) + + @property + def sw_format(self): + """ + For a hardware frame (e.g. ``format.name == "cuda"``), the underlying + software pixel format (``nv12``, ``yuv444p``, ``p010le``, ...). ``None`` + for a regular software frame. + + :type: VideoFormat | None + """ + if not self.ptr.hw_frames_ctx: + return None + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data + ) + return get_video_format(frames_ctx.sw_format, self.ptr.width, self.ptr.height) + + def __repr__(self): + return ( + f"" + ) + + @property + def planes(self): + """ + A tuple of :class:`.VideoPlane` objects. + """ + # We need to detect which planes actually exist, but also constrain ourselves to + # the maximum plane count (as determined only by VideoFrames so far), in case + # the library implementation does not set the last plane to NULL. + fmt = self.format + if self.ptr.hw_frames_ctx: + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data + ) + fmt = get_video_format( + frames_ctx.sw_format, self.ptr.width, self.ptr.height + ) + + max_plane_count: cython.int = 0 + for i in range(fmt.ptr.nb_components): + count = fmt.ptr.comp[i].plane + 1 + if max_plane_count < count: + max_plane_count = count + if fmt.name == "pal8": + max_plane_count = 2 + + plane_count: cython.int = 0 + while plane_count < max_plane_count and self.ptr.extended_data[plane_count]: + plane_count += 1 + if plane_count == 1: + return (VideoPlane(self, 0),) + return tuple([VideoPlane(self, i) for i in range(plane_count)]) + + @property + def width(self): + """Width of the image, in pixels.""" + return self.ptr.width + + @property + def height(self): + """Height of the image, in pixels.""" + return self.ptr.height + + @property + def rotation(self): + """The rotation component of the `DISPLAYMATRIX` transformation matrix. + + Returns: + int: The angle (in degrees) by which the transformation rotates the frame + counterclockwise. The angle will be in range [-180, 180]. + """ + return get_display_rotation(self) + + @property + def interlaced_frame(self): + """Is this frame an interlaced or progressive?""" + + return bool(self.ptr.flags & lib.AV_FRAME_FLAG_INTERLACED) + + @property + def pict_type(self): + """Returns an integer that corresponds to the PictureType enum. + + Wraps :ffmpeg:`AVFrame.pict_type` + + :type: int + """ + return self.ptr.pict_type + + @pict_type.setter + def pict_type(self, value): + self.ptr.pict_type = value + + @property + def colorspace(self): + """Colorspace of frame. + + Wraps :ffmpeg:`AVFrame.colorspace`. + + """ + return self.ptr.colorspace + + @colorspace.setter + def colorspace(self, value): + self.ptr.colorspace = value + + @property + def color_range(self): + """Color range of frame. + + Wraps :ffmpeg:`AVFrame.color_range`. + + """ + return self.ptr.color_range + + @color_range.setter + def color_range(self, value): + self.ptr.color_range = value + + @property + def color_trc(self): + """Transfer characteristic of frame. + + Wraps :ffmpeg:`AVFrame.color_trc`. + + """ + return self.ptr.color_trc + + @color_trc.setter + def color_trc(self, value): + self.ptr.color_trc = value + + @property + def color_primaries(self): + """Color primaries of frame. + + Wraps :ffmpeg:`AVFrame.color_primaries`. + + """ + return self.ptr.color_primaries + + @color_primaries.setter + def color_primaries(self, value): + self.ptr.color_primaries = value + + def reformat(self, *args, **kwargs): + """reformat(width=None, height=None, format=None, src_colorspace=None, dst_colorspace=None, interpolation=None, threads=None) + + Create a new :class:`VideoFrame` with the given width/height/format/colorspace. + + .. seealso:: :meth:`.VideoReformatter.reformat` for arguments. + + """ + if not self.reformatter: + self.reformatter = VideoReformatter() + return self.reformatter.reformat(self, *args, **kwargs) + + def to_rgb(self, **kwargs): + """Get an RGB version of this frame. + + Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`. + + >>> frame = VideoFrame(1920, 1080) + >>> frame.format.name + 'yuv420p' + >>> frame.to_rgb().format.name + 'rgb24' + + """ + return self.reformat(format="rgb24", **kwargs) + + def save(self, filepath: object, **options): + """Save a VideoFrame as a JPG or PNG. + + :param filepath: str | Path + :param \\**options: Encoder options, e.g. ``pred="none"`` or + ``compression_level=1`` for PNG, ``qscale=2`` for JPG. Values are + coerced to ``str``. The PNG defaults favor file size over speed; + ``pred="none"`` is roughly 3x faster and 2x larger. + """ + is_jpg: cython.bint + name: str = str(filepath) + + if name.endswith(".png"): + is_jpg = False + elif name.endswith(".jpg") or name.endswith(".jpeg"): + is_jpg = True + else: + raise ValueError("filepath must end with png or jpg.") + + encoder: str = "mjpeg" if is_jpg else "png" + pix_fmt: str = "yuvj420p" if is_jpg else "rgb24" + + from av.container.core import open + + with open(filepath, "w", options={"update": "1"}) as output: + output_stream = output.add_stream( + encoder, + pix_fmt=pix_fmt, + options={k: str(v) for k, v in options.items()}, + ) + output_stream.width = self.width + output_stream.height = self.height + + output.mux(output_stream.encode(self.reformat(format=pix_fmt))) + output.mux(output_stream.encode(None)) + + def to_image(self, **kwargs): + """Get an RGB ``PIL.Image`` of this frame. + + Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`. + + .. note:: PIL or Pillow must be installed. + + """ + from PIL import Image + + plane: VideoPlane = self.reformat(format="rgb24", **kwargs).planes[0] + + i_buf: cython.const[uint8_t][:] = plane + line_size: cython.int = plane.line_size + i_stride: cython.size_t = abs(line_size) + + o_pos: cython.size_t = 0 + o_stride: cython.size_t = plane.width * 3 + o_size: cython.size_t = plane.height * o_stride + o_buf: bytearray = bytearray(o_size) + + # For bottom-up frames (negative line_size) the buffer protocol exposes + # rows from the lowest address, so the top display row is at the far end. + i_pos: cython.size_t = (plane.height - 1) * i_stride if line_size < 0 else 0 + + while o_pos < o_size: + o_buf[o_pos : o_pos + o_stride] = i_buf[i_pos : i_pos + o_stride] + if line_size < 0: + i_pos -= i_stride + else: + i_pos += i_stride + o_pos += o_stride + + return Image.frombytes( + "RGB", (plane.width, plane.height), bytes(o_buf), "raw", "RGB", 0, 1 + ) + + @cython.cdivision(True) + def to_ndarray(self, channel_last=False, **kwargs): + """Get a numpy array of this frame. + + Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`. + + The array returned is generally of dimension (height, width, channels). + + :param bool channel_last: If True, the shape of array will be + (height, width, channels) rather than (channels, height, width) for + the "yuv444p" and "yuvj444p" formats. + + .. note:: Numpy must be installed. + + .. note:: For formats which return an array of ``uint16``, ``float16`` or ``float32``, + the samples will be in the system's native byte order. + + .. note:: For ``pal8``, an ``(image, palette)`` tuple will be returned, + with the palette being in ARGB (PyAV will swap bytes if needed). + + .. note:: For ``gbrp`` formats, channels are flipped to RGB order. + + """ + if self.ptr.hw_frames_ctx and "format" not in kwargs: + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data + ) + kwargs = dict(kwargs) + kwargs["format"] = get_video_format( + frames_ctx.sw_format, self.ptr.width, self.ptr.height + ).name + + frame: VideoFrame = self.reformat(**kwargs) if len(kwargs) > 0 else self + if frame.ptr.hw_frames_ctx: + raise ValueError("Cannot convert a hardware frame to numpy directly.") + + import numpy as np + + # check size + format_name = frame.format.name + planes: tuple[VideoPlane, ...] = frame.planes + # cases planes are simply concatenated in shape (height, width, channels) + if format_name in _np_pix_fmt_dtypes: + if format_name == "yuyv422": + assert frame.ptr.width % 2 == 0, "width has to be even for yuyv422" + assert frame.ptr.height % 2 == 0, "height has to be even for yuyv422" + itemsize: cython.uint + itemsize, dtype = _np_pix_fmt_dtypes[format_name] + num_planes: cython.size_t = len(planes) + if num_planes == 1: # shortcut, avoid memory copy + array = useful_array(planes[0], itemsize, dtype) + else: # general case + array = np.empty( + (frame.ptr.height, frame.ptr.width, num_planes), dtype=dtype + ) + if format_name.startswith("gbr"): + plane_indices = (2, 0, 1, *range(3, num_planes)) + else: + plane_indices = range(num_planes) + for i, p_idx in enumerate(plane_indices): + array[:, :, i] = useful_array(planes[p_idx], itemsize, dtype) + array = byteswap_array(array, format_name.endswith("be")) + if not channel_last and format_name in {"yuv444p", "yuvj444p"}: + array = np.moveaxis(array, 2, 0) + return array + + # special cases + if format_name in {"yuv420p", "yuvj420p", "yuv422p", "yuv420p10le"}: + assert frame.ptr.width % 2 == 0, "width has to be even for this format" + assert frame.ptr.height % 2 == 0, "height has to be even for this format" + is_10bit: cython.bint = format_name == "yuv420p10le" + itemsize = 2 if is_10bit else 1 + dtype = "uint16" if is_10bit else "uint8" + if frame.ptr.width == 0 or frame.ptr.height == 0: + return np.empty((0, frame.ptr.width), dtype=dtype) + return np.hstack( + [ + useful_array(planes[0], itemsize, dtype).reshape(-1), + useful_array(planes[1], itemsize, dtype).reshape(-1), + useful_array(planes[2], itemsize, dtype).reshape(-1), + ] + ).reshape(-1, frame.ptr.width) + if format_name == "yuv422p10le": + assert frame.ptr.width % 2 == 0, "width has to be even for this format" + assert frame.ptr.height % 2 == 0, "height has to be even for this format" + # Read planes as uint16 at their original width + y = useful_array(planes[0], 2, "uint16") + u = useful_array(planes[1], 2, "uint16") + v = useful_array(planes[2], 2, "uint16") + + # Double the width of U and V by repeating each value + u_full = np.repeat(u, 2, axis=1) + v_full = np.repeat(v, 2, axis=1) + if channel_last: + return np.stack([y, u_full, v_full], axis=2) + return np.stack([y, u_full, v_full], axis=0) + if format_name == "pal8": + image = useful_array(planes[0]) + palette = ( + np.frombuffer(planes[1], "i4") + .astype(">i4") + .reshape(-1, 1) + .view(np.uint8) + ) + return image, palette + if format_name == "nv12": + return np.hstack( + [ + useful_array(planes[0]).reshape(-1), + useful_array(planes[1], 2).reshape(-1), + ] + ).reshape(-1, frame.ptr.width) + + raise ValueError( + f"Conversion to numpy array with format `{format_name}` is not yet supported" + ) + + def set_image(self, img): + """ + Update content from a ``PIL.Image``. + """ + if img.mode != "RGB": + img = img.convert("RGB") + + copy_array_to_plane(img, self.planes[0], 3) + + @staticmethod + def from_image(img): + """ + Construct a frame from a ``PIL.Image``. + """ + frame: VideoFrame = VideoFrame(img.size[0], img.size[1], "rgb24") + frame.set_image(img) + + return frame + + @staticmethod + def from_numpy_buffer(array, format="rgb24", width=0): + """ + Construct a frame from a numpy buffer. + + :param int width: optional width of actual image, if different from the array width. + + .. note:: For formats which expect an array of ``uint16``, ``float16`` or ``float32``, + the samples must be in the system's native byte order. + + .. note:: for ``gbrp`` formats, channels are assumed to be given in RGB order. + + .. note:: For formats where width of the array is not the same as the width of the image, + for example with yuv420p images the UV rows at the bottom have padding bytes in the middle of the + row as well as at the end. To cope with these, callers need to be able to pass the actual width. + """ + import numpy as np + + height = array.shape[0] + if not width: + width = array.shape[1] + + if format in {"rgb24", "bgr24"}: + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[2] == 3) + if array.strides[1:] != (3, 1): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"rgb48le", "rgb48be", "bgr48le", "bgr48be"}: + check_ndarray(array, "uint16", 3) + check_ndarray_shape(array, array.shape[2] == 3) + if array.strides[1:] != (6, 2): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"rgbf32le", "rgbf32be"}: + check_ndarray(array, "float32", 3) + check_ndarray_shape(array, array.shape[2] == 3) + if array.strides[1:] != (12, 4): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"rgba", "bgra", "argb", "abgr"}: + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (4, 1): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"rgba64le", "rgba64be", "bgra64le", "bgra64be"}: + check_ndarray(array, "uint16", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (8, 2): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"rgbaf16le", "rgbaf16be"}: + check_ndarray(array, "float16", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (8, 2): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"rgbaf32le", "rgbaf32be"}: + check_ndarray(array, "float32", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (16, 4): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in { + "gray", + "gray8", + "rgb8", + "bgr8", + "bayer_bggr8", + "bayer_gbrg8", + "bayer_grbg8", + "bayer_rggb8", + }: + check_ndarray(array, "uint8", 2) + if array.strides[1] != 1: + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in { + "gray9be", + "gray9le", + "gray10be", + "gray10le", + "gray12be", + "gray12le", + "gray14be", + "gray14le", + "gray16be", + "gray16le", + "bayer_bggr16be", + "bayer_bggr16le", + "bayer_gbrg16be", + "bayer_gbrg16le", + "bayer_grbg16be", + "bayer_grbg16le", + "bayer_rggb16be", + "bayer_rggb16le", + }: + check_ndarray(array, "uint16", 2) + if array.strides[1] != 2: + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"grayf32le", "grayf32be"}: + check_ndarray(array, "float32", 2) + if array.strides[1] != 4: + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = (array.strides[0],) + elif format in {"gbrp"}: + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[2] == 3) + if array.strides[1:] != (3, 1): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = ( + array.strides[0] // 3, + array.strides[0] // 3, + array.strides[0] // 3, + ) + elif format in { + "gbrp9be", + "gbrp9le", + "gbrp10be", + "gbrp10le", + "gbrp12be", + "gbrp12le", + "gbrp14be", + "gbrp14le", + "gbrp16be", + "gbrp16le", + }: + check_ndarray(array, "uint16", 3) + check_ndarray_shape(array, array.shape[2] == 3) + if array.strides[1:] != (6, 2): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = ( + array.strides[0] // 3, + array.strides[0] // 3, + array.strides[0] // 3, + ) + elif format in {"gbrpf32be", "gbrpf32le"}: + check_ndarray(array, "float32", 3) + check_ndarray_shape(array, array.shape[2] == 3) + if array.strides[1:] != (12, 4): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = ( + array.strides[0] // 3, + array.strides[0] // 3, + array.strides[0] // 3, + ) + elif format in {"gbrap"}: + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (4, 1): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = ( + array.strides[0] // 4, + array.strides[0] // 4, + array.strides[0] // 4, + array.strides[0] // 4, + ) + elif format in { + "gbrap10be", + "gbrap10le", + "gbrap12be", + "gbrap12le", + "gbrap14be", + "gbrap14le", + "gbrap16be", + "gbrap16le", + }: + check_ndarray(array, "uint16", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (8, 2): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = ( + array.strides[0] // 4, + array.strides[0] // 4, + array.strides[0] // 4, + array.strides[0] // 4, + ) + elif format in {"gbrapf32be", "gbrapf32le"}: + check_ndarray(array, "float32", 3) + check_ndarray_shape(array, array.shape[2] == 4) + if array.strides[1:] != (16, 4): + raise ValueError("provided array does not have C_CONTIGUOUS rows") + linesizes = ( + array.strides[0] // 4, + array.strides[0] // 4, + array.strides[0] // 4, + array.strides[0] // 4, + ) + elif format in {"yuv420p", "yuvj420p", "nv12"}: + check_ndarray(array, "uint8", 2) + check_ndarray_shape(array, array.shape[0] % 3 == 0) + check_ndarray_shape(array, array.shape[1] % 2 == 0) + height = height // 6 * 4 + if array.strides[1] != 1: + raise ValueError("provided array does not have C_CONTIGUOUS rows") + if format in {"yuv420p", "yuvj420p"}: + # For YUV420 planar formats, the UV plane stride is always half the Y stride. + linesizes = ( + array.strides[0], + array.strides[0] // 2, + array.strides[0] // 2, + ) + else: + # Planes where U and V are interleaved have the same stride as Y. + linesizes = (array.strides[0], array.strides[0]) + else: + raise ValueError( + f"Conversion from numpy array with format `{format}` is not yet supported" + ) + + if format.startswith("gbrap"): # rgba -> gbra + array = np.ascontiguousarray(np.moveaxis(array[..., [1, 2, 0, 3]], -1, 0)) + elif format.startswith("gbrp"): # rgb -> gbr + array = np.ascontiguousarray(np.moveaxis(array[..., [1, 2, 0]], -1, 0)) + + frame = VideoFrame(_cinit_bypass_sentinel) + frame._image_fill_pointers_numpy(array, width, height, linesizes, format) + return frame + + def _image_fill_pointers_numpy(self, buffer, width, height, linesizes, format): + # If you want to use the numpy notation, then you need to include the following lines at the top of the file: + # cimport numpy as cnp + # cnp.import_array() + + # And add the numpy include directories to the setup.py files + # hint np.get_include() + # cdef cnp.ndarray[ + # dtype=cnp.uint8_t, ndim=1, + # negative_indices=False, mode='c'] c_buffer + # c_buffer = buffer.reshape(-1) + # c_ptr = &c_buffer[0] + # c_ptr = ((buffer.ctypes.data)) + + # Using buffer.ctypes.data helps avoid any kind of usage of the c-api from + # numpy, which avoid the need to add numpy as a compile time dependency. + + c_data: cython.Py_ssize_t = buffer.ctypes.data + c_ptr: cython.pointer[uint8_t] = cython.cast(cython.pointer[uint8_t], c_data) + c_format: lib.AVPixelFormat = get_pix_fmt(format) + lib.av_frame_unref(self.ptr) + + # Hold on to a reference for the numpy buffer so that it doesn't get accidentally garbage collected + self.ptr.format = c_format + self.ptr.width = width + self.ptr.height = height + for i, linesize in enumerate(linesizes): + self.ptr.linesize[i] = linesize + + required = err_check( + lib.av_image_fill_pointers( + self.ptr.data, + cython.cast(lib.AVPixelFormat, self.ptr.format), + self.ptr.height, + c_ptr, + self.ptr.linesize, + ) + ) + + py_buf = cython.cast(object, buffer) + Py_INCREF(py_buf) + + self.ptr.buf[0] = lib.av_buffer_create( + c_ptr, + required, + _numpy_avbuffer_free, + cython.cast(cython.p_void, py_buf), + 0, + ) + if self.ptr.buf[0] == cython.NULL: + Py_DECREF(py_buf) + raise MemoryError("av_buffer_create failed") + + self._init_user_attributes() + + @staticmethod + @cython.cdivision(True) + def from_ndarray(array, format="rgb24", channel_last=False): + """ + Construct a frame from a numpy array. + + :param bool channel_last: If False (default), the shape for the yuv444p and yuvj444p + is given by (channels, height, width) rather than (height, width, channels). + + .. note:: For formats which expect an array of ``uint16``, ``float16`` or ``float32``, + the samples must be in the system's native byte order. + + .. note:: for ``pal8``, an ``(image, palette)`` pair must be passed. `palette` must + have shape (256, 4) and is given in ARGB format (PyAV will swap bytes if needed). + + .. note:: for ``gbrp`` formats, channels are assumed to be given in RGB order. + + """ + import numpy as np + + # case layers are concatenated + channels, itemsize, dtype = { + "bayer_bggr16be": (1, 2, "uint16"), + "bayer_bggr16le": (1, 2, "uint16"), + "bayer_bggr8": (1, 1, "uint8"), + "bayer_gbrg16be": (1, 2, "uint16"), + "bayer_gbrg16le": (1, 2, "uint16"), + "bayer_gbrg8": (1, 1, "uint8"), + "bayer_grbg16be": (1, 2, "uint16"), + "bayer_grbg16le": (1, 2, "uint16"), + "bayer_grbg8": (1, 1, "uint8"), + "bayer_rggb16be": (1, 2, "uint16"), + "bayer_rggb16le": (1, 2, "uint16"), + "bayer_rggb8": (1, 1, "uint8"), + "bgr8": (1, 1, "uint8"), + "gbrap": (4, 1, "uint8"), + "gbrap10be": (4, 2, "uint16"), + "gbrap10le": (4, 2, "uint16"), + "gbrap12be": (4, 2, "uint16"), + "gbrap12le": (4, 2, "uint16"), + "gbrap14be": (4, 2, "uint16"), + "gbrap14le": (4, 2, "uint16"), + "gbrap16be": (4, 2, "uint16"), + "gbrap16le": (4, 2, "uint16"), + "gbrapf32be": (4, 4, "float32"), + "gbrapf32le": (4, 4, "float32"), + "gbrp": (3, 1, "uint8"), + "gbrp10be": (3, 2, "uint16"), + "gbrp10le": (3, 2, "uint16"), + "gbrp12be": (3, 2, "uint16"), + "gbrp12le": (3, 2, "uint16"), + "gbrp14be": (3, 2, "uint16"), + "gbrp14le": (3, 2, "uint16"), + "gbrp16be": (3, 2, "uint16"), + "gbrp16le": (3, 2, "uint16"), + "gbrp9be": (3, 2, "uint16"), + "gbrp9le": (3, 2, "uint16"), + "gbrpf32be": (3, 4, "float32"), + "gbrpf32le": (3, 4, "float32"), + "gray": (1, 1, "uint8"), + "gray10be": (1, 2, "uint16"), + "gray10le": (1, 2, "uint16"), + "gray12be": (1, 2, "uint16"), + "gray12le": (1, 2, "uint16"), + "gray14be": (1, 2, "uint16"), + "gray14le": (1, 2, "uint16"), + "gray16be": (1, 2, "uint16"), + "gray16le": (1, 2, "uint16"), + "gray8": (1, 1, "uint8"), + "gray9be": (1, 2, "uint16"), + "gray9le": (1, 2, "uint16"), + "grayf32be": (1, 4, "float32"), + "grayf32le": (1, 4, "float32"), + "rgb8": (1, 1, "uint8"), + "yuv444p": (3, 1, "uint8"), + "yuv444p16be": (3, 2, "uint16"), + "yuv444p16le": (3, 2, "uint16"), + "yuva444p16be": (4, 2, "uint16"), + "yuva444p16le": (4, 2, "uint16"), + "yuvj444p": (3, 1, "uint8"), + }.get(format, (None, None, None)) + if channels is not None: + if array.ndim == 2: # (height, width) -> (height, width, 1) + array = array[:, :, None] + check_ndarray(array, dtype, 3) + if not channel_last and format in {"yuv444p", "yuvj444p"}: + array = np.moveaxis(array, 0, 2) # (channels, h, w) -> (h, w, channels) + check_ndarray_shape(array, array.shape[2] == channels) + array = byteswap_array(array, format.endswith("be")) + frame = VideoFrame(array.shape[1], array.shape[0], format) + if frame.format.name.startswith("gbr"): # rgb -> gbr + array = np.concatenate( + [ # not inplace to avoid bad surprises + array[:, :, 1:3], + array[:, :, 0:1], + array[:, :, 3:], + ], + axis=2, + ) + for i in range(channels): + copy_array_to_plane(array[:, :, i], frame.planes[i], itemsize) + return frame + + # other cases + if format == "pal8": + array, palette = array + check_ndarray(array, "uint8", 2) + check_ndarray(palette, "uint8", 2) + check_ndarray_shape(palette, palette.shape == (256, 4)) + + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane(array, frame.planes[0], 1) + frame.planes[1].update(palette.view(">i4").astype("i4").tobytes()) + return frame + elif format in {"yuv420p", "yuvj420p"}: + check_ndarray(array, "uint8", 2) + check_ndarray_shape(array, array.shape[0] % 3 == 0) + check_ndarray_shape(array, array.shape[1] % 2 == 0) + + frame = VideoFrame(array.shape[1], (array.shape[0] * 2) // 3, format) + if frame.width == 0 or frame.height == 0: + return frame + u_start = frame.width * frame.height + v_start = 5 * u_start // 4 + flat = array.reshape(-1) + copy_array_to_plane(flat[0:u_start], frame.planes[0], 1) + copy_array_to_plane(flat[u_start:v_start], frame.planes[1], 1) + copy_array_to_plane(flat[v_start:], frame.planes[2], 1) + return frame + elif format == "yuv420p10le": + check_ndarray(array, "uint16", 2) + check_ndarray_shape(array, array.shape[0] % 3 == 0) + check_ndarray_shape(array, array.shape[1] % 2 == 0) + + frame = VideoFrame(array.shape[1], (array.shape[0] * 2) // 3, format) + if frame.width == 0 or frame.height == 0: + return frame + u_start = frame.width * frame.height + v_start = 5 * u_start // 4 + flat = array.reshape(-1) + copy_array_to_plane(flat[0:u_start], frame.planes[0], 2) + copy_array_to_plane(flat[u_start:v_start], frame.planes[1], 2) + copy_array_to_plane(flat[v_start:], frame.planes[2], 2) + return frame + elif format == "yuv422p": + check_ndarray(array, "uint8", 2) + check_ndarray_shape(array, array.shape[0] % 4 == 0) + check_ndarray_shape(array, array.shape[1] % 2 == 0) + + frame = VideoFrame(array.shape[1], array.shape[0] // 2, format) + if frame.width == 0 or frame.height == 0: + return frame + u_start = frame.width * frame.height + v_start = u_start + u_start // 2 + flat = array.reshape(-1) + copy_array_to_plane(flat[0:u_start], frame.planes[0], 1) + copy_array_to_plane(flat[u_start:v_start], frame.planes[1], 1) + copy_array_to_plane(flat[v_start:], frame.planes[2], 1) + return frame + elif format == "yuv422p10le": + if not isinstance(array, np.ndarray) or array.dtype != np.uint16: + raise ValueError("Array must be uint16 type") + + # Convert to channel-first if needed + if channel_last and array.shape[2] == 3: + array = np.moveaxis(array, 2, 0) + elif not (array.shape[0] == 3): + raise ValueError( + "Array must have shape (3, height, width) or (height, width, 3)" + ) + + height, width = array.shape[1:] + if width % 2 != 0 or height % 2 != 0: + raise ValueError("Width and height must be even") + + frame = VideoFrame(width, height, format) + copy_array_to_plane(array[0], frame.planes[0], 2) + # Subsample U and V by taking every other column + u = array[1, :, ::2].copy() # Need copy to ensure C-contiguous + v = array[2, :, ::2].copy() # Need copy to ensure C-contiguous + copy_array_to_plane(u, frame.planes[1], 2) + copy_array_to_plane(v, frame.planes[2], 2) + return frame + elif format == "yuyv422": + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[0] % 2 == 0) + check_ndarray_shape(array, array.shape[1] % 2 == 0) + check_ndarray_shape(array, array.shape[2] == 2) + elif format in {"rgb24", "bgr24"}: + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[2] == 3) + elif format in {"argb", "rgba", "abgr", "bgra"}: + check_ndarray(array, "uint8", 3) + check_ndarray_shape(array, array.shape[2] == 4) + elif format in {"rgb48be", "rgb48le", "bgr48be", "bgr48le"}: + check_ndarray(array, "uint16", 3) + check_ndarray_shape(array, array.shape[2] == 3) + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane( + byteswap_array(array, format.endswith("be")), frame.planes[0], 6 + ) + return frame + elif format in {"rgbf32be", "rgbf32le"}: + check_ndarray(array, "float32", 3) + check_ndarray_shape(array, array.shape[2] == 3) + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane( + byteswap_array(array, format.endswith("be")), frame.planes[0], 12 + ) + return frame + elif format in {"rgba64be", "rgba64le", "bgra64be", "bgra64le"}: + check_ndarray(array, "uint16", 3) + check_ndarray_shape(array, array.shape[2] == 4) + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane( + byteswap_array(array, format.endswith("be")), frame.planes[0], 8 + ) + return frame + elif format in {"rgbaf16be", "rgbaf16le"}: + check_ndarray(array, "float16", 3) + check_ndarray_shape(array, array.shape[2] == 4) + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane( + byteswap_array(array, format.endswith("be")), frame.planes[0], 8 + ) + return frame + elif format in {"rgbaf32be", "rgbaf32le"}: + check_ndarray(array, "float32", 3) + check_ndarray_shape(array, array.shape[2] == 4) + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane( + byteswap_array(array, format.endswith("be")), frame.planes[0], 16 + ) + return frame + elif format == "nv12": + check_ndarray(array, "uint8", 2) + check_ndarray_shape(array, array.shape[0] % 3 == 0) + check_ndarray_shape(array, array.shape[1] % 2 == 0) + + frame = VideoFrame(array.shape[1], (array.shape[0] * 2) // 3, format) + uv_start = frame.width * frame.height + flat = array.reshape(-1) + copy_array_to_plane(flat[:uv_start], frame.planes[0], 1) + copy_array_to_plane(flat[uv_start:], frame.planes[1], 2) + return frame + else: + raise ValueError( + f"Conversion from numpy array with format `{format}` is not yet supported" + ) + + frame = VideoFrame(array.shape[1], array.shape[0], format) + copy_array_to_plane( + array, frame.planes[0], 1 if array.ndim == 2 else array.shape[2] + ) + + return frame + + @staticmethod + def from_bytes( + img_bytes: bytes, + width: int, + height: int, + format="rgba", + flip_horizontal=False, + flip_vertical=False, + ): + frame = VideoFrame(width, height, format) + if format == "rgba": + copy_bytes_to_plane( + img_bytes, frame.planes[0], 4, flip_horizontal, flip_vertical + ) + elif format in { + "bayer_bggr8", + "bayer_rggb8", + "bayer_gbrg8", + "bayer_grbg8", + "bayer_bggr16le", + "bayer_rggb16le", + "bayer_gbrg16le", + "bayer_grbg16le", + "bayer_bggr16be", + "bayer_rggb16be", + "bayer_gbrg16be", + "bayer_grbg16be", + }: + copy_bytes_to_plane( + img_bytes, + frame.planes[0], + 1 if format.endswith("8") else 2, + flip_horizontal, + flip_vertical, + ) + else: + raise NotImplementedError(f"Format '{format}' is not supported.") + return frame + + @staticmethod + def from_dlpack( + planes, + format: str = "nv12", + width: int = 0, + height: int = 0, + stream=None, + device_id: int | None = None, + primary_ctx: bool | None = None, + cuda_context=None, + current_ctx: bool | None = None, + ): + if not isinstance(planes, (tuple, list)): + planes = (planes,) + + sw_fmt: lib.AVPixelFormat = get_pix_fmt(format) + nv12 = get_pix_fmt(b"nv12") + p010le = get_pix_fmt(b"p010le") + p016le = get_pix_fmt(b"p016le") + + if sw_fmt not in (nv12, p010le, p016le): + return VideoFrame._from_dlpack_planar( + planes, sw_fmt, format, width, height, stream, device_id + ) + + if len(planes) != 2: + raise ValueError( + "from_dlpack currently supports 2-plane formats only (nv12/p010le/p016le)" + ) + + expected_bits = 8 if sw_fmt == nv12 else 16 + itemsize = 1 if expected_bits == 8 else 2 + + m0: cython.pointer[DLManagedTensor] = cython.NULL + m1: cython.pointer[DLManagedTensor] = cython.NULL + frame: VideoFrame = None + + try: + m0 = _consume_dlpack(planes[0], stream) + m1 = _consume_dlpack(planes[1], stream) + + dev_type0 = m0.dl_tensor.device_type + dev_type1 = m1.dl_tensor.device_type + if dev_type0 != dev_type1: + raise ValueError("plane tensors must have the same device_type") + if dev_type0 not in (kCuda, kCPU): + raise NotImplementedError( + "only CPU and CUDA DLPack tensors are supported" + ) + + dev0 = m0.dl_tensor.device_id + dev1 = m1.dl_tensor.device_id + if dev0 != dev1: + raise ValueError("plane tensors must be on the same CUDA device") + if dev_type0 == kCuda: + if device_id is None: + device_id = dev0 + elif device_id != dev0: + raise ValueError( + "device_id does not match the DLPack tensor device_id" + ) + else: + if device_id not in (None, 0): + raise ValueError("device_id must be 0 for CPU tensors") + device_id = 0 + if dev_type0 == kCPU and (dev0 != 0 or dev1 != 0): + raise ValueError("CPU DLPack tensors must have device_id == 0") + + if ( + m0.dl_tensor.dtype.code != 1 + or m0.dl_tensor.dtype.bits != expected_bits + or m0.dl_tensor.dtype.lanes != 1 + ): + raise TypeError("unexpected dtype for plane 0") + if ( + m1.dl_tensor.dtype.code != 1 + or m1.dl_tensor.dtype.bits != expected_bits + or m1.dl_tensor.dtype.lanes != 1 + ): + raise TypeError("unexpected dtype for plane 1") + + if m0.dl_tensor.ndim != 2: + raise ValueError("plane 0 must be 2D (H, W)") + + y_h = cython.cast(int64_t, m0.dl_tensor.shape[0]) + y_w = cython.cast(int64_t, m0.dl_tensor.shape[1]) + + if width == 0 and height == 0: + width = cython.cast(int, y_w) + height = cython.cast(int, y_h) + elif width == 0 or height == 0: + raise ValueError("either specify both width/height or neither") + else: + if y_w != width or y_h != height: + raise ValueError("plane 0 shape does not match width/height") + + if width % 2 or height % 2: + raise ValueError("width/height must be even for nv12/p010le/p016le") + + if m0.dl_tensor.strides != cython.NULL: + if m0.dl_tensor.strides[1] != 1: + raise ValueError("plane 0 must be contiguous in the last dimension") + y_pitch_elems = cython.cast(int64_t, m0.dl_tensor.strides[0]) + else: + y_pitch_elems = cython.cast(int64_t, width) + + y_linesize = cython.cast(int, y_pitch_elems * itemsize) + y_size = cython.cast(int, y_linesize * height) + + uv_ndim = m1.dl_tensor.ndim + uv_h_expected = height // 2 + + if uv_ndim == 2: + uv_h = cython.cast(int, m1.dl_tensor.shape[0]) + uv_w = cython.cast(int, m1.dl_tensor.shape[1]) + if uv_h != uv_h_expected or uv_w != width: + raise ValueError("plane 1 must have shape (H/2, W) for 2D UV") + if m1.dl_tensor.strides != cython.NULL: + if m1.dl_tensor.strides[1] != 1: + raise ValueError( + "plane 1 must be contiguous in the last dimension" + ) + uv_pitch_elems = cython.cast(int64_t, m1.dl_tensor.strides[0]) + else: + uv_pitch_elems = cython.cast(int64_t, uv_w) + elif uv_ndim == 3: + uv_h = cython.cast(int, m1.dl_tensor.shape[0]) + uv_w2 = cython.cast(int, m1.dl_tensor.shape[1]) + uv_c = cython.cast(int, m1.dl_tensor.shape[2]) + if uv_h != uv_h_expected or uv_w2 != (width // 2) or uv_c != 2: + raise ValueError("plane 1 must have shape (H/2, W/2, 2) for 3D UV") + if m1.dl_tensor.strides != cython.NULL: + if m1.dl_tensor.strides[2] != 1 or m1.dl_tensor.strides[1] != 2: + raise ValueError( + "unexpected UV plane strides for (H/2, W/2, 2)" + ) + uv_pitch_elems = cython.cast(int64_t, m1.dl_tensor.strides[0]) + else: + uv_pitch_elems = cython.cast(int64_t, width) + else: + raise ValueError("plane 1 must be 2D or 3D") + + uv_linesize = cython.cast(int, uv_pitch_elems * itemsize) + uv_size = cython.cast(int, uv_linesize * (height // 2)) + + frame = alloc_video_frame() + frame.ptr.width = width + frame.ptr.height = height + if dev_type0 == kCuda: + ctx: CudaContext + frames_ref: cython.pointer[lib.AVBufferRef] + if cuda_context is None: + ctx = CudaContext( + device_id=device_id, + primary_ctx=( + not current_ctx if primary_ctx is None else primary_ctx + ), + current_ctx=bool(current_ctx), + ) + else: + if not isinstance(cuda_context, CudaContext): + raise TypeError("cuda_context must be a CudaContext") + if int(cuda_context.device_id) != int(device_id): + raise ValueError( + "cuda_context.device_id does not match the DLPack tensor device_id" + ) + if primary_ctx is not None and bool( + cuda_context.primary_ctx + ) != bool(primary_ctx): + raise ValueError( + "cuda_context.primary_ctx does not match primary_ctx" + ) + if current_ctx is not None and bool( + cuda_context.current_ctx + ) != bool(current_ctx): + raise ValueError( + "cuda_context.current_ctx does not match current_ctx" + ) + ctx = cython.cast(CudaContext, cuda_context) + + frames_ref = ctx.get_frames_ctx(sw_fmt, width, height) + frame.ptr.format = get_pix_fmt(b"cuda") + frame.ptr.hw_frames_ctx = frames_ref + frame._device_id = device_id + frame._cuda_ctx = ctx + else: + frame.ptr.format = sw_fmt + + y_ptr = cython.cast( + cython.pointer[uint8_t], m0.dl_tensor.data + ) + cython.cast(cython.size_t, m0.dl_tensor.byte_offset) + uv_ptr = cython.cast( + cython.pointer[uint8_t], m1.dl_tensor.data + ) + cython.cast(cython.size_t, m1.dl_tensor.byte_offset) + + frame.ptr.buf[0] = lib.av_buffer_create( + y_ptr, y_size, _dlpack_avbuffer_free, cython.cast(cython.p_void, m0), 0 + ) + if frame.ptr.buf[0] == cython.NULL: + raise MemoryError("av_buffer_create failed for plane 0") + frame.ptr.data[0] = y_ptr + frame.ptr.linesize[0] = y_linesize + m0 = cython.NULL + + frame.ptr.buf[1] = lib.av_buffer_create( + uv_ptr, + uv_size, + _dlpack_avbuffer_free, + cython.cast(cython.p_void, m1), + 0, + ) + if frame.ptr.buf[1] == cython.NULL: + raise MemoryError("av_buffer_create failed for plane 1") + frame.ptr.data[1] = uv_ptr + frame.ptr.linesize[1] = uv_linesize + m1 = cython.NULL + + frame._init_user_attributes() + return frame + + except Exception: + if frame is not None: + lib.av_frame_unref(frame.ptr) + if m0 != cython.NULL: + m0.deleter(m0) + if m1 != cython.NULL: + m1.deleter(m1) + raise + + @staticmethod + def _from_dlpack_planar(planes, sw_fmt, format, width, height, stream, device_id): + # CPU-only import for planar formats whose planes each hold a single + # component: yuv420p/yuv422p/yuv444p, gray, gbrp, and their 16-bit + # little-endian variants. nv12/p010le/p016le keep their dedicated + # 2-plane path in from_dlpack(). + desc: cython.pointer[cython.const[lib.AVPixFmtDescriptor]] = ( + lib.av_pix_fmt_desc_get(sw_fmt) + ) + if desc == cython.NULL: + raise NotImplementedError(f"unknown pixel format {format!r}") + if desc.flags & ( + lib.AV_PIX_FMT_FLAG_BITSTREAM + | lib.AV_PIX_FMT_FLAG_PAL + | lib.AV_PIX_FMT_FLAG_BAYER + ): + raise NotImplementedError( + f"from_dlpack does not support bitstream, palette, or Bayer " + f"formats ({format!r})" + ) + + i: cython.int + nb_planes: cython.int = 0 + for i in range(desc.nb_components): + if cython.cast(cython.int, desc.comp[i].plane) + 1 > nb_planes: + nb_planes = desc.comp[i].plane + 1 + + p: cython.int + count: cython.int + comp_of_plane = [0] * nb_planes + for p in range(nb_planes): + count = 0 + for i in range(desc.nb_components): + if cython.cast(cython.int, desc.comp[i].plane) == p: + comp_of_plane[p] = i + count += 1 + if count != 1: + raise NotImplementedError( + "from_dlpack supports nv12/p010le/p016le and planar " + f"single-component formats; {format!r} is not supported" + ) + + if len(planes) != nb_planes: + raise ValueError( + f"{format!r} requires {nb_planes} plane(s), got {len(planes)}" + ) + + itemsize: cython.int = desc.comp[0].step + if itemsize != 1 and itemsize != 2: + raise NotImplementedError( + "only 8- and 16-bit components are supported for DLPack import" + ) + if itemsize == 2 and desc.flags & lib.AV_PIX_FMT_FLAG_BE: + raise NotImplementedError( + "big-endian formats are not supported for DLPack import" + ) + expected_bits: cython.int = itemsize * 8 + + if device_id not in (None, 0): + raise ValueError("device_id must be 0 for CPU tensors") + + log2_w: cython.int = desc.log2_chroma_w + log2_h: cython.int = desc.log2_chroma_h + + frame: VideoFrame = None + m: cython.pointer[DLManagedTensor] = cython.NULL + try: + frame = alloc_video_frame() + frame.ptr.format = sw_fmt + + for p in range(nb_planes): + m = _consume_dlpack(planes[p], stream) + + if m.dl_tensor.device_type != kCPU: + raise NotImplementedError( + "only CPU DLPack tensors are supported for this format" + ) + if m.dl_tensor.device_id != 0: + raise ValueError("CPU DLPack tensors must have device_id == 0") + + if ( + m.dl_tensor.dtype.code != 1 + or m.dl_tensor.dtype.bits != expected_bits + or m.dl_tensor.dtype.lanes != 1 + ): + raise TypeError(f"unexpected dtype for plane {p}") + + if m.dl_tensor.ndim != 2: + raise ValueError(f"plane {p} must be 2D (H, W)") + + ph = cython.cast(int64_t, m.dl_tensor.shape[0]) + pw = cython.cast(int64_t, m.dl_tensor.shape[1]) + + if p == 0: + if width == 0 and height == 0: + width = cython.cast(int, pw) + height = cython.cast(int, ph) + elif width == 0 or height == 0: + raise ValueError("either specify both width/height or neither") + elif pw != width or ph != height: + raise ValueError("plane 0 shape does not match width/height") + if (log2_w and width % 2) or (log2_h and height % 2): + raise ValueError(f"width/height must be even for {format!r}") + frame.ptr.width = width + frame.ptr.height = height + + comp_idx = comp_of_plane[p] + is_chroma = (comp_idx == 1 or comp_idx == 2) and (log2_w or log2_h) + exp_w = (-((-width) >> log2_w)) if is_chroma else width + exp_h = (-((-height) >> log2_h)) if is_chroma else height + + if pw != exp_w or ph != exp_h: + raise ValueError(f"plane {p} must have shape ({exp_h}, {exp_w})") + + if m.dl_tensor.strides != cython.NULL: + if m.dl_tensor.strides[1] != 1: + raise ValueError( + f"plane {p} must be contiguous in the last dimension" + ) + pitch_elems = cython.cast(int64_t, m.dl_tensor.strides[0]) + else: + pitch_elems = cython.cast(int64_t, exp_w) + + linesize = cython.cast(int, pitch_elems * itemsize) + size = cython.cast(int, linesize * exp_h) + + ptr = cython.cast( + cython.pointer[uint8_t], m.dl_tensor.data + ) + cython.cast(cython.size_t, m.dl_tensor.byte_offset) + + frame.ptr.buf[p] = lib.av_buffer_create( + ptr, size, _dlpack_avbuffer_free, cython.cast(cython.p_void, m), 0 + ) + if frame.ptr.buf[p] == cython.NULL: + raise MemoryError(f"av_buffer_create failed for plane {p}") + frame.ptr.data[p] = ptr + frame.ptr.linesize[p] = linesize + m = cython.NULL + + frame._init_user_attributes() + return frame + + except Exception: + if frame is not None: + lib.av_frame_unref(frame.ptr) + if m != cython.NULL: + m.deleter(m) + raise diff --git a/.venv/lib/python3.12/site-packages/av/video/frame.pyi b/.venv/lib/python3.12/site-packages/av/video/frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b2240ab9c8c0e3657a87200c85e0e7d201801c00 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/frame.pyi @@ -0,0 +1,123 @@ +from enum import IntEnum +from pathlib import Path +from typing import Any + +import numpy as np + +from av.frame import Frame + +from .format import VideoFormat +from .plane import VideoPlane +from .reformatter import ColorPrimaries, ColorTrc + +_SupportedNDarray = ( + np.ndarray[Any, np.dtype[np.uint8]] + | np.ndarray[Any, np.dtype[np.uint16]] + | np.ndarray[Any, np.dtype[np.float16]] + | np.ndarray[Any, np.dtype[np.float32]] +) + +supported_np_pix_fmts: set[str] + +class PictureType(IntEnum): + NONE = 0 + I = 1 + P = 2 + B = 3 + S = 4 + SI = 5 + SP = 6 + BI = 7 + +class CudaContext: + @property + def device_id(self) -> int: ... + @property + def primary_ctx(self) -> bool: ... + @property + def current_ctx(self) -> bool: ... + @property + def cuda_stream(self) -> int: ... + def __init__( + self, + device_id: int = 0, + primary_ctx: bool = True, + current_ctx: bool = False, + cuda_stream: int | None = None, + ) -> None: ... + +class VideoFrame(Frame): + format: VideoFormat + planes: tuple[VideoPlane, ...] + pict_type: int + colorspace: int + color_range: int + color_trc: int + color_primaries: int + + @property + def sw_format(self) -> VideoFormat | None: ... + @property + def time(self) -> float: ... + @property + def width(self) -> int: ... + @property + def height(self) -> int: ... + @property + def interlaced_frame(self) -> bool: ... + @property + def rotation(self) -> int: ... + def __init__( + self, width: int = 0, height: int = 0, format: str = "yuv420p" + ) -> None: ... + def reformat( + self, + width: int | None = None, + height: int | None = None, + format: str | None = None, + src_colorspace: str | int | None = None, + dst_colorspace: str | int | None = None, + interpolation: int | str | None = None, + src_color_range: int | str | None = None, + dst_color_range: int | str | None = None, + dst_color_trc: int | ColorTrc | None = None, + dst_color_primaries: int | ColorPrimaries | None = None, + threads: int | None = None, + ) -> VideoFrame: ... + def to_rgb(self, **kwargs: Any) -> VideoFrame: ... + def save(self, filepath: str | Path, **options: Any) -> None: ... + def to_image(self, **kwargs): ... + def to_ndarray( + self, channel_last: bool = False, **kwargs: Any + ) -> _SupportedNDarray: ... + @staticmethod + def from_image(img): ... + @staticmethod + def from_numpy_buffer( + array: _SupportedNDarray, format: str = "rgb24", width: int = 0 + ) -> VideoFrame: ... + @staticmethod + def from_ndarray( + array: _SupportedNDarray, format: str = "rgb24", channel_last: bool = False + ) -> VideoFrame: ... + @staticmethod + def from_bytes( + data: bytes, + width: int, + height: int, + format: str = "rgba", + flip_horizontal: bool = False, + flip_vertical: bool = False, + ) -> VideoFrame: ... + @staticmethod + def from_dlpack( + planes: object | tuple[object, ...], + format: str = "nv12", + width: int = 0, + height: int = 0, + stream: int | None = None, + device_id: int | None = None, + primary_ctx: bool | None = None, + cuda_context: CudaContext | None = None, + current_ctx: bool | None = None, + ) -> VideoFrame: ... diff --git a/.venv/lib/python3.12/site-packages/av/video/plane.abi3.so b/.venv/lib/python3.12/site-packages/av/video/plane.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..4c21935a1ee64d812577adb3c90d597f0dbb7969 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/plane.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e31b38a47859ad976c0d8bcafe17004ffae3e409eaf032b546a818c6f6c837ca +size 572825 diff --git a/.venv/lib/python3.12/site-packages/av/video/plane.pxd b/.venv/lib/python3.12/site-packages/av/video/plane.pxd new file mode 100644 index 0000000000000000000000000000000000000000..80ff79050e36b74359c6a57179d997a811e059f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/plane.pxd @@ -0,0 +1,38 @@ +from libc.stdint cimport int64_t, uint8_t, uint16_t, uint64_t + +from av.plane cimport Plane +from av.video.format cimport VideoFormatComponent + + +cdef class VideoPlane(Plane): + cdef readonly size_t buffer_size + cdef readonly unsigned int width, height + + +cdef enum DeviceType: + kCPU = 1 + kCuda = 2 + +cdef struct DLDataType: + uint8_t code + uint8_t bits + uint16_t lanes + +cdef struct DLTensor: + void* data + int device_type + int device_id + int ndim + DLDataType dtype + int64_t* shape + int64_t* strides + uint64_t byte_offset + +cdef struct DLManagedTensor + +ctypedef void (*DLManagedTensorDeleter)(DLManagedTensor*) noexcept nogil + +cdef struct DLManagedTensor: + DLTensor dl_tensor + void* manager_ctx + DLManagedTensorDeleter deleter diff --git a/.venv/lib/python3.12/site-packages/av/video/plane.py b/.venv/lib/python3.12/site-packages/av/video/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..51a3a13f1bccc8e524b1ca59aee8d462b1ee1f05 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/plane.py @@ -0,0 +1,373 @@ +import cython +import cython.cimports.libav as lib +from cython.cimports.av.error import err_check +from cython.cimports.av.video.format import ( + VideoFormatComponent, + get_pix_fmt, + get_video_format, +) +from cython.cimports.av.video.frame import VideoFrame +from cython.cimports.cpython import PyBUF_WRITABLE, PyBuffer_FillInfo +from cython.cimports.cpython.buffer import Py_buffer +from cython.cimports.cpython.pycapsule import ( + PyCapsule_GetPointer, + PyCapsule_IsValid, + PyCapsule_New, +) +from cython.cimports.libc.stdlib import free, malloc + + +@cython.final +@cython.cclass +class VideoPlane(Plane): + def __cinit__(self, frame: VideoFrame, index: cython.int): + # The palette plane has no associated component or linesize; set fields manually + fmt = frame.format + if frame.ptr.hw_frames_ctx: + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], frame.ptr.hw_frames_ctx.data + ) + fmt = get_video_format( + frames_ctx.sw_format, frame.ptr.width, frame.ptr.height + ) + + if index == 1 and fmt.name == "pal8": + self.width = 256 + self.height = 1 + self.buffer_size = 256 * 4 + return + + for i in range(fmt.ptr.nb_components): + if fmt.ptr.comp[i].plane == index: + component = VideoFormatComponent(fmt, i) + self.width = component.width + self.height = component.height + break + else: + raise RuntimeError(f"could not find plane {index} of {fmt!r}") + + # Sometimes, linesize is negative (and that is meaningful). We are only + # insisting that the buffer size be based on the extent of linesize, and + # ignore it's direction. + self.buffer_size = abs(self.frame.ptr.linesize[self.index]) * self.height + + @cython.cfunc + def _buffer_size(self) -> cython.size_t: + return self.buffer_size + + @property + def line_size(self): + """ + Bytes per horizontal line in this plane. + + :type: int + """ + return self.frame.ptr.linesize[self.index] + + @cython.cfunc + def _buffer_writable(self) -> cython.bint: + if self.frame.ptr.hw_frames_ctx: + return False + return True + + def __getbuffer__(self, view: cython.pointer[Py_buffer], flags: cython.int): + if self.frame.ptr.hw_frames_ctx: + raise TypeError( + "Hardware frame planes do not support the Python buffer protocol. " + "Use DLPack (__dlpack__) or download to a software frame." + ) + if flags & PyBUF_WRITABLE and not self._buffer_writable(): + raise ValueError("buffer is not writable") + + ptr: cython.p_void = self._buffer_ptr() + line_size: cython.int = self.frame.ptr.linesize[self.index] + if line_size < 0: + height: cython.int = self.height + ptr = cython.cast(cython.p_char, ptr) + (height - 1) * line_size + + PyBuffer_FillInfo(view, self, ptr, self._buffer_size(), 0, flags) + + def __dlpack_device__(self): + if self.frame.ptr.hw_frames_ctx: + if cython.cast(lib.AVPixelFormat, self.frame.ptr.format) != get_pix_fmt( + b"cuda" + ): + raise NotImplementedError( + "DLPack export is only implemented for CUDA hw frames" + ) + return (kCuda, self.frame._device_id) + return (kCPU, 0) + + def __dlpack__(self, *, stream: int | None = None): + if self.frame.ptr.buf[0] == cython.NULL: + raise TypeError( + "DLPack export requires a refcounted AVFrame (frame.buf[0] is NULL)" + ) + + sw_fmt: lib.AVPixelFormat + device_type: cython.int + device_id: cython.int + + if self.frame.ptr.hw_frames_ctx: + if cython.cast(lib.AVPixelFormat, self.frame.ptr.format) != get_pix_fmt( + b"cuda" + ): + raise NotImplementedError( + "DLPack export is only implemented for CUDA hw frames" + ) + if stream is not None: + raise NotImplementedError( + "CUDA stream synchronization is not supported. " + "Pass stream=None and synchronize before calling __dlpack__." + ) + + frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( + cython.pointer[lib.AVHWFramesContext], self.frame.ptr.hw_frames_ctx.data + ) + sw_fmt = frames_ctx.sw_format + device_type = kCuda + device_id = self.frame._device_id + else: + sw_fmt = cython.cast(lib.AVPixelFormat, self.frame.ptr.format) + device_type = kCPU + device_id = 0 + + line_size = self.line_size + if line_size < 0: + raise NotImplementedError( + "negative linesize is not supported for DLPack export" + ) + + nv12 = get_pix_fmt(b"nv12") + p010le = get_pix_fmt(b"p010le") + p016le = get_pix_fmt(b"p016le") + + ndim, bits, itemsize = cython.declare(cython.int) + s0, s1, s2 = cython.declare(int64_t) + st0, st1, st2 = cython.declare(int64_t) + + if sw_fmt == nv12: + itemsize = 1 + bits = 8 + if self.index == 0: + ndim = 2 + s0 = self.frame.ptr.height + s1 = self.frame.ptr.width + st0 = line_size + st1 = 1 + elif self.index == 1: + ndim = 3 + s0 = self.frame.ptr.height // 2 + s1 = self.frame.ptr.width // 2 + s2 = 2 + st0 = line_size + st1 = 2 + st2 = 1 + else: + raise ValueError("invalid plane index for NV12") + elif sw_fmt == p010le or sw_fmt == p016le: + itemsize = 2 + bits = 16 + if line_size % itemsize: + raise ValueError("linesize is not aligned to dtype") + if self.index == 0: + ndim = 2 + s0 = self.frame.ptr.height + s1 = self.frame.ptr.width + st0 = line_size // itemsize + st1 = 1 + elif self.index == 1: + ndim = 3 + s0 = self.frame.ptr.height // 2 + s1 = self.frame.ptr.width // 2 + s2 = 2 + st0 = line_size // itemsize + st1 = 2 + st2 = 1 + else: + raise ValueError("invalid plane index for P010/P016") + elif device_type != kCPU: + raise NotImplementedError("unsupported sw_format for DLPack export") + else: + # Generic CPU export. Describe the plane straight from its + # pixel-format descriptor: planes holding a single component (the + # Y/U/V planes of planar YUV, gray, ...) become 2D (H, W), while + # planes that interleave several components (packed RGB, the chroma + # plane of NV12, ...) become 3D (H, W, C). + desc: cython.pointer[cython.const[lib.AVPixFmtDescriptor]] = ( + lib.av_pix_fmt_desc_get(sw_fmt) + ) + if desc == cython.NULL: + raise NotImplementedError("unknown pixel format for DLPack export") + if desc.flags & ( + lib.AV_PIX_FMT_FLAG_BITSTREAM + | lib.AV_PIX_FMT_FLAG_PAL + | lib.AV_PIX_FMT_FLAG_BAYER + ): + raise NotImplementedError( + "bitstream, palette, and Bayer formats are not supported for " + "DLPack export" + ) + + step_bytes: cython.int = 0 + ncomp: cython.int = 0 + i: cython.int + for i in range(desc.nb_components): + if desc.comp[i].plane != self.index: + continue + if ncomp == 0: + step_bytes = desc.comp[i].step + elif cython.cast(cython.int, desc.comp[i].step) != step_bytes: + raise NotImplementedError( + "mixed component step is not supported for DLPack export" + ) + ncomp += 1 + + if ncomp == 0: + raise ValueError(f"plane {self.index} has no components") + if step_bytes % ncomp: + raise NotImplementedError( + "unsupported component packing for DLPack export" + ) + itemsize = step_bytes // ncomp + if itemsize != 1 and itemsize != 2: + raise NotImplementedError( + "only 8- and 16-bit components are supported for DLPack export" + ) + if itemsize == 2 and desc.flags & lib.AV_PIX_FMT_FLAG_BE: + raise NotImplementedError( + "big-endian formats are not supported for DLPack export" + ) + bits = itemsize * 8 + if line_size % itemsize: + raise ValueError("linesize is not aligned to dtype") + + if ncomp == 1: + ndim = 2 + s0 = self.height + s1 = self.width + st0 = line_size // itemsize + st1 = 1 + else: + ndim = 3 + s0 = self.height + s1 = self.width + s2 = ncomp + st0 = line_size // itemsize + st1 = ncomp + st2 = 1 + + frame_ref: cython.pointer[lib.AVFrame] = lib.av_frame_alloc() + if frame_ref == cython.NULL: + raise MemoryError("av_frame_alloc() failed") + err_check(lib.av_frame_ref(frame_ref, self.frame.ptr)) + + shape = cython.cast( + cython.pointer[int64_t], malloc(ndim * cython.sizeof(int64_t)) + ) + strides = cython.cast( + cython.pointer[int64_t], malloc(ndim * cython.sizeof(int64_t)) + ) + if shape == cython.NULL or strides == cython.NULL: + if shape != cython.NULL: + free(shape) + if strides != cython.NULL: + free(strides) + lib.av_frame_free(cython.address(frame_ref)) + raise MemoryError("malloc() failed") + + if ndim == 2: + shape[0] = s0 + shape[1] = s1 + strides[0] = st0 + strides[1] = st1 + else: + shape[0] = s0 + shape[1] = s1 + shape[2] = s2 + strides[0] = st0 + strides[1] = st1 + strides[2] = st2 + + ctx = cython.cast( + cython.pointer[cython.p_void], malloc(3 * cython.sizeof(cython.p_void)) + ) + if ctx == cython.NULL: + free(shape) + free(strides) + lib.av_frame_free(cython.address(frame_ref)) + raise MemoryError("malloc() failed") + + ctx[0] = cython.cast(cython.p_void, frame_ref) + ctx[1] = cython.cast(cython.p_void, shape) + ctx[2] = cython.cast(cython.p_void, strides) + + managed = cython.cast( + cython.pointer[DLManagedTensor], malloc(cython.sizeof(DLManagedTensor)) + ) + if managed == cython.NULL: + free(ctx) + free(shape) + free(strides) + lib.av_frame_free(cython.address(frame_ref)) + raise MemoryError("malloc() failed") + + managed.dl_tensor.data = cython.cast(cython.p_void, frame_ref.data[self.index]) + managed.dl_tensor.device_type = device_type + managed.dl_tensor.device_id = device_id + managed.dl_tensor.ndim = ndim + managed.dl_tensor.dtype = DLDataType(code=1, bits=bits, lanes=1) + managed.dl_tensor.shape = shape + managed.dl_tensor.strides = strides + managed.dl_tensor.byte_offset = 0 + managed.manager_ctx = cython.cast(cython.p_void, ctx) + managed.deleter = _dlpack_managed_tensor_deleter + + try: + capsule = PyCapsule_New( + cython.cast(cython.p_void, managed), + b"dltensor", + _dlpack_capsule_destructor, + ) + except Exception: + _dlpack_managed_tensor_deleter(managed) + raise + + return capsule + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def _dlpack_managed_tensor_deleter( + managed: cython.pointer[DLManagedTensor], +) -> cython.void: + if managed == cython.NULL: + return + ctx = cython.cast(cython.pointer[cython.p_void], managed.manager_ctx) + if ctx != cython.NULL: + frame_ref = cython.cast(cython.pointer[lib.AVFrame], ctx[0]) + shape = cython.cast(cython.pointer[int64_t], ctx[1]) + strides = cython.cast(cython.pointer[int64_t], ctx[2]) + + if frame_ref != cython.NULL: + lib.av_frame_free(cython.address(frame_ref)) + if shape != cython.NULL: + free(shape) + if strides != cython.NULL: + free(strides) + free(ctx) + + free(managed) + + +@cython.cfunc +@cython.exceptval(check=False) +def _dlpack_capsule_destructor(capsule: object) -> cython.void: + if PyCapsule_IsValid(capsule, b"dltensor"): + managed = cython.cast( + cython.pointer[DLManagedTensor], + PyCapsule_GetPointer(capsule, b"dltensor"), + ) + if managed != cython.NULL: + managed.deleter(managed) diff --git a/.venv/lib/python3.12/site-packages/av/video/plane.pyi b/.venv/lib/python3.12/site-packages/av/video/plane.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fcbf8e6edf0c0621e3c576d2fc1813204418a482 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/plane.pyi @@ -0,0 +1,15 @@ +from types import CapsuleType + +from av.plane import Plane + +from .frame import VideoFrame + +class VideoPlane(Plane): + line_size: int + width: int + height: int + buffer_size: int + + def __init__(self, frame: VideoFrame, index: int) -> None: ... + def __dlpack_device__(self) -> tuple[int, int]: ... + def __dlpack__(self, *, stream: int | None = None) -> CapsuleType: ... diff --git a/.venv/lib/python3.12/site-packages/av/video/reformatter.abi3.so b/.venv/lib/python3.12/site-packages/av/video/reformatter.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..c8c50efb083788cb304a5b6d54b68f5ba5321bd4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/reformatter.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9843b9b4ff9fffca19910ee7d85bf582f15c0733a1009382b53aae1de39e79f5 +size 593209 diff --git a/.venv/lib/python3.12/site-packages/av/video/reformatter.pxd b/.venv/lib/python3.12/site-packages/av/video/reformatter.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1645d3943da800d87dd72810ba81d3c79f177a07 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/reformatter.pxd @@ -0,0 +1,50 @@ +cimport libav as lib + +from av.video.frame cimport VideoFrame + + +cdef extern from "libswscale/swscale.h" nogil: + cdef struct SwsContext: + unsigned flags + int threads + + cdef int SWS_FAST_BILINEAR + cdef int SWS_BILINEAR + cdef int SWS_BICUBIC + cdef int SWS_X + cdef int SWS_POINT + cdef int SWS_AREA + cdef int SWS_BICUBLIN + cdef int SWS_GAUSS + cdef int SWS_SINC + cdef int SWS_LANCZOS + cdef int SWS_SPLINE + cdef int SWS_PRINT_INFO + cdef int SWS_FULL_CHR_H_INT + cdef int SWS_FULL_CHR_H_INP + cdef int SWS_DIRECT_BGR + cdef int SWS_ACCURATE_RND + cdef int SWS_BITEXACT + cdef int SWS_ERROR_DIFFUSION + cdef int SWS_CS_ITU709 + cdef int SWS_CS_FCC + cdef int SWS_CS_ITU601 + cdef int SWS_CS_ITU624 + cdef int SWS_CS_SMPTE170M + cdef int SWS_CS_SMPTE240M + cdef int SWS_CS_DEFAULT + cdef int SWS_CS_BT2020 + + cdef SwsContext *sws_alloc_context() + cdef void sws_free_context(SwsContext **ctx) + cdef int sws_is_noop(const lib.AVFrame *dst, const lib.AVFrame *src) + cdef int sws_scale_frame(SwsContext *c, lib.AVFrame *dst, const lib.AVFrame *src) + +cdef class VideoReformatter: + cdef SwsContext *ptr + cdef _reformat(self, VideoFrame frame, int width, int height, + lib.AVPixelFormat format, int src_colorspace, + int dst_colorspace, int interpolation, + int src_color_range, int dst_color_range, + int dst_color_trc, int dst_color_primaries, + int threads) diff --git a/.venv/lib/python3.12/site-packages/av/video/reformatter.py b/.venv/lib/python3.12/site-packages/av/video/reformatter.py new file mode 100644 index 0000000000000000000000000000000000000000..59725571b39307cfd7e8cf8d5ac7efb2938fe766 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/reformatter.py @@ -0,0 +1,359 @@ +from enum import IntEnum, IntFlag + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.error import err_check +from cython.cimports.av.video.format import VideoFormat, get_pix_fmt +from cython.cimports.av.video.frame import alloc_video_frame + + +class Interpolation(IntFlag): + FAST_BILINEAR: "Fast bilinear" = SWS_FAST_BILINEAR + BILINEAR: "Bilinear" = SWS_BILINEAR + BICUBIC: "2-tap cubic B-spline" = SWS_BICUBIC + X: "Experimental" = SWS_X + POINT: "Nearest neighbor / point" = SWS_POINT + AREA: "Area averaging" = SWS_AREA + BICUBLIN: "Bicubic luma / Bilinear chroma" = SWS_BICUBLIN + GAUSS: "Gaussian approximation" = SWS_GAUSS + SINC: "Unwindowed Sinc" = SWS_SINC + LANCZOS: "3-tap sinc/sinc" = SWS_LANCZOS + SPLINE: "Unwindowed natural cubic spline" = SWS_SPLINE + PRINT_INFO: "Emit verbose scaler info to the log" = SWS_PRINT_INFO + FULL_CHR_H_INT: "Full chroma interpolation" = SWS_FULL_CHR_H_INT + FULL_CHR_H_INP: "Full chroma input" = SWS_FULL_CHR_H_INP + DIRECT_BGR: "Direct BGR" = SWS_DIRECT_BGR + ACCURATE_RND: "Accurate rounding" = SWS_ACCURATE_RND + BITEXACT: "Bit-exact output" = SWS_BITEXACT + ERROR_DIFFUSION: "Error diffusion dither" = SWS_ERROR_DIFFUSION + + +class Colorspace(IntEnum): + ITU709 = SWS_CS_ITU709 + FCC = SWS_CS_FCC + ITU601 = SWS_CS_ITU601 + ITU624 = SWS_CS_ITU624 + SMPTE170M = SWS_CS_SMPTE170M + SMPTE240M = SWS_CS_SMPTE240M + DEFAULT = SWS_CS_DEFAULT + BT2020 = SWS_CS_BT2020 + # Lowercase for b/c. + itu709 = SWS_CS_ITU709 + fcc = SWS_CS_FCC + itu601 = SWS_CS_ITU601 + itu624 = SWS_CS_ITU624 + smpte170m = SWS_CS_SMPTE170M + smpte240m = SWS_CS_SMPTE240M + default = SWS_CS_DEFAULT + bt2020 = SWS_CS_BT2020 + + +class ColorRange(IntEnum): + UNSPECIFIED: "Unspecified" = lib.AVCOL_RANGE_UNSPECIFIED + MPEG: "MPEG (limited) YUV range, 219*2^(n-8)" = lib.AVCOL_RANGE_MPEG + JPEG: "JPEG (full) YUV range, 2^n-1" = lib.AVCOL_RANGE_JPEG + NB: "Not part of ABI" = lib.AVCOL_RANGE_NB + + +class ColorTrc(IntEnum): + """Transfer characteristic (gamma curve) of a video frame. + + Maps to FFmpeg's ``AVColorTransferCharacteristic``. + """ + + BT709: "BT.709" = lib.AVCOL_TRC_BT709 + UNSPECIFIED: "Unspecified" = lib.AVCOL_TRC_UNSPECIFIED + GAMMA22: "Gamma 2.2 (BT.470M)" = lib.AVCOL_TRC_GAMMA22 + GAMMA28: "Gamma 2.8 (BT.470BG)" = lib.AVCOL_TRC_GAMMA28 + SMPTE170M: "SMPTE 170M" = lib.AVCOL_TRC_SMPTE170M + SMPTE240M: "SMPTE 240M" = lib.AVCOL_TRC_SMPTE240M + LINEAR: "Linear" = lib.AVCOL_TRC_LINEAR + LOG: "Logarithmic (100:1 range)" = lib.AVCOL_TRC_LOG + LOG_SQRT: "Logarithmic (100*sqrt(10):1 range)" = lib.AVCOL_TRC_LOG_SQRT + IEC61966_2_4: "IEC 61966-2-4 (sRGB)" = lib.AVCOL_TRC_IEC61966_2_4 + BT1361_ECG: "BT.1361 extended colour gamut" = lib.AVCOL_TRC_BT1361_ECG + IEC61966_2_1: "IEC 61966-2-1 (sYCC)" = lib.AVCOL_TRC_IEC61966_2_1 + BT2020_10: "BT.2020 10-bit" = lib.AVCOL_TRC_BT2020_10 + BT2020_12: "BT.2020 12-bit" = lib.AVCOL_TRC_BT2020_12 + SMPTE2084: "SMPTE 2084 (PQ, HDR10)" = lib.AVCOL_TRC_SMPTE2084 + SMPTE428: "SMPTE 428-1" = lib.AVCOL_TRC_SMPTE428 + ARIB_STD_B67: "ARIB STD-B67 (HLG)" = lib.AVCOL_TRC_ARIB_STD_B67 + + +class ColorPrimaries(IntEnum): + """Color primaries of a video frame. + + Maps to FFmpeg's ``AVColorPrimaries``. + """ + + BT709: "BT.709 / sRGB / sYCC" = lib.AVCOL_PRI_BT709 + UNSPECIFIED: "Unspecified" = lib.AVCOL_PRI_UNSPECIFIED + BT470M: "BT.470M" = lib.AVCOL_PRI_BT470M + BT470BG: "BT.470BG / BT.601-6 625" = lib.AVCOL_PRI_BT470BG + SMPTE170M: "SMPTE 170M / BT.601-6 525" = lib.AVCOL_PRI_SMPTE170M + SMPTE240M: "SMPTE 240M" = lib.AVCOL_PRI_SMPTE240M + FILM: "Generic film (Illuminant C)" = lib.AVCOL_PRI_FILM + BT2020: "BT.2020 / BT.2100" = lib.AVCOL_PRI_BT2020 + SMPTE428: "SMPTE 428-1 / XYZ" = lib.AVCOL_PRI_SMPTE428 + SMPTE431: "SMPTE 431-2 (DCI-P3)" = lib.AVCOL_PRI_SMPTE431 + SMPTE432: "SMPTE 432-1 (Display P3)" = lib.AVCOL_PRI_SMPTE432 + EBU3213: "EBU 3213-E / JEDEC P22" = lib.AVCOL_PRI_EBU3213 + + +@cython.cfunc +@cython.inline +def _resolve_enum_value( + value: object, enum_class: object, default: cython.int +) -> cython.int: + # Helper function to resolve enum values from different input types. + if value is None: + return default + if isinstance(value, enum_class): + return value.value + if isinstance(value, int): + return value + if isinstance(value, str): + return enum_class[value].value + raise ValueError(f"Cannot convert {value} to {enum_class.__name__}") + + +@cython.cfunc +@cython.inline +def _resolve_format(format: object, default: lib.AVPixelFormat) -> lib.AVPixelFormat: + if format is None: + return default + if isinstance(format, VideoFormat): + return cython.cast(VideoFormat, format).pix_fmt + return get_pix_fmt(format) + + +@cython.cfunc +def _set_frame_colorspace( + frame: cython.pointer(lib.AVFrame), + colorspace: cython.int, + color_range: cython.int, +): + """Set AVFrame colorspace/range from SWS_CS_* and AVColorRange values.""" + if color_range != lib.AVCOL_RANGE_UNSPECIFIED: + frame.color_range = cython.cast(lib.AVColorRange, color_range) + # Mapping from SWS_CS_* (swscale colorspace) to AVColorSpace (frame metadata). + # Note: SWS_CS_ITU601, SWS_CS_ITU624, SWS_CS_SMPTE170M, and SWS_CS_DEFAULT all have + # the same value (5), so we map 5 -> AVCOL_SPC_SMPTE170M as the most common case. + # SWS_CS_DEFAULT is handled specially by not setting frame metadata. + if colorspace == SWS_CS_ITU709: + frame.colorspace = lib.AVCOL_SPC_BT709 + elif colorspace == SWS_CS_FCC: + frame.colorspace = lib.AVCOL_SPC_FCC + elif colorspace == SWS_CS_ITU601: + frame.colorspace = lib.AVCOL_SPC_SMPTE170M + elif colorspace == SWS_CS_SMPTE240M: + frame.colorspace = lib.AVCOL_SPC_SMPTE240M + elif colorspace == SWS_CS_BT2020: + frame.colorspace = lib.AVCOL_SPC_BT2020_NCL + + +@cython.final +@cython.cclass +class VideoReformatter: + """An object for reformatting size and pixel format of :class:`.VideoFrame`. + + It is most efficient to have a reformatter object for each set of parameters + you will use as calling :meth:`reformat` will reconfigure the internal object. + + """ + + def __dealloc__(self): + with cython.nogil: + sws_free_context(cython.address(self.ptr)) + + def reformat( + self, + frame: VideoFrame, + width=None, + height=None, + format=None, + src_colorspace=None, + dst_colorspace=None, + interpolation=None, + src_color_range=None, + dst_color_range=None, + dst_color_trc=None, + dst_color_primaries=None, + threads=None, + ): + """Create a new :class:`VideoFrame` with the given width/height/format/colorspace. + + Returns the same frame untouched if nothing needs to be done to it. + + :param int width: New width, or ``None`` for the same width. + :param int height: New height, or ``None`` for the same height. + :param format: New format, or ``None`` for the same format. + :type format: :class:`.VideoFormat` or ``str`` + :param src_colorspace: Current colorspace, or ``None`` for the frame colorspace. + :type src_colorspace: :class:`Colorspace` or ``str`` + :param dst_colorspace: Desired colorspace, or ``None`` for the frame colorspace. + :type dst_colorspace: :class:`Colorspace` or ``str`` + :param interpolation: The scaling algorithm to use, or ``None`` for ``BILINEAR``. + Option flags such as ``ACCURATE_RND`` or ``BITEXACT`` may be combined with + the algorithm using ``|``, e.g. ``Interpolation.BILINEAR | Interpolation.ACCURATE_RND``. + :type interpolation: :class:`Interpolation` or ``str`` + :param src_color_range: Current color range, or ``None`` for the ``UNSPECIFIED``. + :type src_color_range: :class:`ColorRange` or ``str`` + :param dst_color_range: Desired color range, or ``None`` for the ``UNSPECIFIED``. + :type dst_color_range: :class:`ColorRange` or ``str`` + :param dst_color_trc: Desired transfer characteristic to tag on the output frame, + or ``None`` to preserve the source frame's value. This sets frame metadata only; + it does not perform a pixel-level transfer function conversion. + :type dst_color_trc: :class:`ColorTrc` or ``int`` + :param dst_color_primaries: Desired color primaries to tag on the output frame, + or ``None`` to preserve the source frame's value. + :type dst_color_primaries: :class:`ColorPrimaries` or ``int`` + :param int threads: How many threads to use for scaling, or ``0`` for automatic + selection based on the number of available CPUs. Defaults to ``0`` (auto). + + """ + c_dst_format = _resolve_format(format, frame.format.pix_fmt) + c_src_colorspace = _resolve_enum_value( + src_colorspace, Colorspace, frame.ptr.colorspace + ) + c_dst_colorspace = _resolve_enum_value( + dst_colorspace, Colorspace, frame.ptr.colorspace + ) + c_interpolation = _resolve_enum_value( + interpolation, Interpolation, SWS_BILINEAR + ) + c_src_color_range = _resolve_enum_value(src_color_range, ColorRange, 0) + c_dst_color_range = _resolve_enum_value(dst_color_range, ColorRange, 0) + # Default to UNSPECIFIED (not the source's value) so that a transfer / + # primaries conversion is only performed when explicitly requested. See + # _reformat for why. + c_dst_color_trc = _resolve_enum_value( + dst_color_trc, ColorTrc, lib.AVCOL_TRC_UNSPECIFIED + ) + c_dst_color_primaries = _resolve_enum_value( + dst_color_primaries, ColorPrimaries, lib.AVCOL_PRI_UNSPECIFIED + ) + c_threads: cython.int = threads if threads is not None else 0 + c_width: cython.int = width if width is not None else frame.ptr.width + c_height: cython.int = height if height is not None else frame.ptr.height + + return self._reformat( + frame, + c_width, + c_height, + c_dst_format, + c_src_colorspace, + c_dst_colorspace, + c_interpolation, + c_src_color_range, + c_dst_color_range, + c_dst_color_trc, + c_dst_color_primaries, + c_threads, + ) + + @cython.cfunc + def _reformat( + self, + frame: VideoFrame, + width: cython.int, + height: cython.int, + dst_format: lib.AVPixelFormat, + src_colorspace: cython.int, + dst_colorspace: cython.int, + interpolation: cython.int, + src_color_range: cython.int, + dst_color_range: cython.int, + dst_color_trc: cython.int, + dst_color_primaries: cython.int, + threads: cython.int, + ): + if frame.ptr.hw_frames_ctx: + frame_sw = alloc_video_frame() + err_check(lib.av_hwframe_transfer_data(frame_sw.ptr, frame.ptr, 0)) + frame_sw._copy_internal_attributes(frame, data_layout=False) + frame_sw._init_user_attributes() + frame = frame_sw + + new_frame: VideoFrame = alloc_video_frame() + new_frame._copy_internal_attributes(frame, data_layout=False) + new_frame.ptr.format = dst_format + new_frame.ptr.width = width + new_frame.ptr.height = height + + # A transfer-characteristic / primaries conversion is opt-in. Unlike the + # pre-17.0 sws_scale, sws_scale_frame inspects color_trc/color_primaries + # and rejects RESERVED (and other unsupported) values with EOPNOTSUPP, + # which regressed plain reformats of e.g. VP9 / NVDEC frames (#2208). So + # only feed these fields to swscale when the caller explicitly requested a + # destination value; otherwise neutralize them for the scale (as the old + # sws_scale effectively did) while still preserving the source's tags on + # the returned frame's metadata. + convert_trc: cython.bint = dst_color_trc != lib.AVCOL_TRC_UNSPECIFIED + convert_primaries: cython.bint = ( + dst_color_primaries != lib.AVCOL_PRI_UNSPECIFIED + ) + frame_src_color_trc: lib.AVColorTransferCharacteristic = frame.ptr.color_trc + frame_src_color_primaries: lib.AVColorPrimaries = frame.ptr.color_primaries + + if convert_trc: + new_frame.ptr.color_trc = cython.cast( + lib.AVColorTransferCharacteristic, dst_color_trc + ) + else: + frame.ptr.color_trc = lib.AVCOL_TRC_UNSPECIFIED + new_frame.ptr.color_trc = lib.AVCOL_TRC_UNSPECIFIED + + if convert_primaries: + new_frame.ptr.color_primaries = cython.cast( + lib.AVColorPrimaries, dst_color_primaries + ) + else: + frame.ptr.color_primaries = lib.AVCOL_PRI_UNSPECIFIED + new_frame.ptr.color_primaries = lib.AVCOL_PRI_UNSPECIFIED + + # Translate source and destination colorspace/range from SWS_CS_* to AVCOL_* + # so sws_is_noop and sws_scale_frame understand them + frame_src_colorspace: lib.AVColorSpace = frame.ptr.colorspace + frame_src_color_range: lib.AVColorRange = frame.ptr.color_range + _set_frame_colorspace(frame.ptr, src_colorspace, src_color_range) + _set_frame_colorspace(new_frame.ptr, dst_colorspace, dst_color_range) + + # Shortcut if sws_scale_frame would be a no-op + is_noop: cython.bint = sws_is_noop(new_frame.ptr, frame.ptr) != 0 + if is_noop: + # Restore source frame metadata to avoid side effects + frame.ptr.colorspace = frame_src_colorspace + frame.ptr.color_range = frame_src_color_range + frame.ptr.color_trc = frame_src_color_trc + frame.ptr.color_primaries = frame_src_color_primaries + return frame + + if self.ptr == cython.NULL: + self.ptr = sws_alloc_context() + if self.ptr == cython.NULL: + raise MemoryError("Could not allocate SwsContext") + self.ptr.threads = threads + self.ptr.flags = cython.cast(cython.uint, interpolation) + + # Allocate frame buffers and perform the conversion + new_frame._init(dst_format, width, height) + with cython.nogil: + ret = sws_scale_frame(self.ptr, new_frame.ptr, frame.ptr) + + # Restore source frame metadata to avoid side effects + frame.ptr.colorspace = frame_src_colorspace + frame.ptr.color_range = frame_src_color_range + frame.ptr.color_trc = frame_src_color_trc + frame.ptr.color_primaries = frame_src_color_primaries + + # Preserve the source's transfer/primaries on the output when no explicit + # conversion was requested (the scale ran with neutralized tags). + if not convert_trc: + new_frame.ptr.color_trc = frame_src_color_trc + if not convert_primaries: + new_frame.ptr.color_primaries = frame_src_color_primaries + + err_check(ret) + + return new_frame diff --git a/.venv/lib/python3.12/site-packages/av/video/reformatter.pyi b/.venv/lib/python3.12/site-packages/av/video/reformatter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..480860d0b776bc31770c0e305cf78a74bb6616fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/reformatter.pyi @@ -0,0 +1,98 @@ +from enum import IntEnum, IntFlag +from typing import cast + +from .frame import VideoFrame + +class Interpolation(IntFlag): + FAST_BILINEAR = cast(int, ...) + BILINEAR = cast(int, ...) + BICUBIC = cast(int, ...) + X = cast(int, ...) + POINT = cast(int, ...) + AREA = cast(int, ...) + BICUBLIN = cast(int, ...) + GAUSS = cast(int, ...) + SINC = cast(int, ...) + LANCZOS = cast(int, ...) + SPLINE = cast(int, ...) + PRINT_INFO = cast(int, ...) + FULL_CHR_H_INT = cast(int, ...) + FULL_CHR_H_INP = cast(int, ...) + DIRECT_BGR = cast(int, ...) + ACCURATE_RND = cast(int, ...) + BITEXACT = cast(int, ...) + ERROR_DIFFUSION = cast(int, ...) + +class Colorspace(IntEnum): + ITU709 = cast(int, ...) + FCC = cast(int, ...) + ITU601 = cast(int, ...) + ITU624 = cast(int, ...) + SMPTE170M = cast(int, ...) + SMPTE240M = cast(int, ...) + DEFAULT = cast(int, ...) + BT2020 = cast(int, ...) + itu709 = cast(int, ...) + fcc = cast(int, ...) + itu601 = cast(int, ...) + itu624 = cast(int, ...) + smpte170m = cast(int, ...) + smpte240m = cast(int, ...) + default = cast(int, ...) + bt2020 = cast(int, ...) + +class ColorRange(IntEnum): + UNSPECIFIED = 0 + MPEG = 1 + JPEG = 2 + NB = 3 + +class ColorTrc(IntEnum): + BT709 = cast(int, ...) + UNSPECIFIED = cast(int, ...) + GAMMA22 = cast(int, ...) + GAMMA28 = cast(int, ...) + SMPTE170M = cast(int, ...) + SMPTE240M = cast(int, ...) + LINEAR = cast(int, ...) + LOG = cast(int, ...) + LOG_SQRT = cast(int, ...) + IEC61966_2_4 = cast(int, ...) + BT1361_ECG = cast(int, ...) + IEC61966_2_1 = cast(int, ...) + BT2020_10 = cast(int, ...) + BT2020_12 = cast(int, ...) + SMPTE2084 = cast(int, ...) + SMPTE428 = cast(int, ...) + ARIB_STD_B67 = cast(int, ...) + +class ColorPrimaries(IntEnum): + BT709 = cast(int, ...) + UNSPECIFIED = cast(int, ...) + BT470M = cast(int, ...) + BT470BG = cast(int, ...) + SMPTE170M = cast(int, ...) + SMPTE240M = cast(int, ...) + FILM = cast(int, ...) + BT2020 = cast(int, ...) + SMPTE428 = cast(int, ...) + SMPTE431 = cast(int, ...) + SMPTE432 = cast(int, ...) + EBU3213 = cast(int, ...) + +class VideoReformatter: + def reformat( + self, + frame: VideoFrame, + width: int | None = None, + height: int | None = None, + format: str | None = None, + src_colorspace: int | None = None, + dst_colorspace: int | None = None, + interpolation: Interpolation | int | str | None = None, + src_color_range: int | str | None = None, + dst_color_range: int | str | None = None, + dst_color_trc: int | ColorTrc | None = None, + dst_color_primaries: int | ColorPrimaries | None = None, + threads: int | None = None, + ) -> VideoFrame: ... diff --git a/.venv/lib/python3.12/site-packages/av/video/stream.abi3.so b/.venv/lib/python3.12/site-packages/av/video/stream.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..116aaa702fdbba5d5c32d6c96d31a3c86c809ced --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/stream.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6e86d3ab0a39148b17a3ead6c6aac81fbecd6d15ecbf320cf554ccf2f9d7be1 +size 478681 diff --git a/.venv/lib/python3.12/site-packages/av/video/stream.pxd b/.venv/lib/python3.12/site-packages/av/video/stream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1a553f34cab44d2c0123299a8a75a72b07298695 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/stream.pxd @@ -0,0 +1,18 @@ +from libc.stdint cimport int32_t, uint8_t + +from av.packet cimport Packet +from av.stream cimport Stream + +from .frame cimport VideoFrame + + +cdef class VideoStream(Stream): + # Display matrix (9 int32, native-endian) written as AV_PKT_DATA_DISPLAYMATRIX + # coded side data at mux time, applied only when _has_display_matrix is set. + cdef int32_t _display_matrix[9] + cdef uint8_t _has_display_matrix + + cdef _apply_display_matrix(self) + + cpdef encode(self, VideoFrame frame=?) + cpdef decode(self, Packet packet=?) diff --git a/.venv/lib/python3.12/site-packages/av/video/stream.py b/.venv/lib/python3.12/site-packages/av/video/stream.py new file mode 100644 index 0000000000000000000000000000000000000000..ed8a79aea59c7545902b4db5d50605d1548a5ef8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/stream.py @@ -0,0 +1,191 @@ +import cython +from cython.cimports import libav as lib +from cython.cimports.av.packet import Packet +from cython.cimports.av.stream import Stream +from cython.cimports.av.utils import avrational_to_fraction +from cython.cimports.av.video.frame import VideoFrame +from cython.cimports.libc.stdint import int32_t +from cython.cimports.libc.string import memcpy + + +@cython.final +@cython.cclass +class VideoStream(Stream): + def __repr__(self): + if self.codec_context is None: + return f" at 0x{id(self):x}>" + return ( + f"" + ) + + def __getattr__(self, name): + if name in ("framerate", "rate"): + raise AttributeError( + f"'{type(self).__name__}' object has no attribute '{name}'" + ) + if self.codec_context is None: + raise AttributeError( + f"'{type(self).__name__}' object has no attribute '{name}'" + ) + return getattr(self.codec_context, name) + + @cython.ccall + def encode(self, frame: VideoFrame | None = None): + """ + Encode an :class:`.VideoFrame` and return a list of :class:`.Packet`. + + :rtype: list[Packet] + + .. seealso:: This is mostly a passthrough to :meth:`.CodecContext.encode`. + """ + self._assert_has_codec_context(lib.AVERROR_ENCODER_NOT_FOUND) + packets = self.codec_context.encode(frame) + packet: Packet + for packet in packets: + packet._stream = self + packet.ptr.stream_index = self.ptr.index + return packets + + @cython.ccall + def decode(self, packet: Packet | None = None): + """ + Decode a :class:`.Packet` and return a list of :class:`.VideoFrame`. + + :rtype: list[VideoFrame] + + .. seealso:: This is a passthrough to :meth:`.CodecContext.decode`. + """ + self._assert_has_codec_context() + return self.codec_context.decode(packet) + + @cython.cfunc + def _finalize_for_output(self): + Stream._finalize_for_output(self) + if self.codec_context is not None: + self.ptr.avg_frame_rate = self.codec_context.ptr.framerate + # avcodec_parameters_from_context() overwrites codecpar.coded_side_data, + # so inject the display matrix after it, before avformat_write_header(). + if self.codec_context is not None and self._has_display_matrix: + self._apply_display_matrix() + + @cython.cfunc + def _apply_display_matrix(self): + n: cython.int = 9 * cython.sizeof(int32_t) + sd: cython.pointer[lib.AVPacketSideData] = lib.av_packet_side_data_new( + cython.address(self.ptr.codecpar.coded_side_data), + cython.address(self.ptr.codecpar.nb_coded_side_data), + lib.AV_PKT_DATA_DISPLAYMATRIX, + n, + 0, + ) + if sd == cython.NULL: + raise MemoryError("could not allocate display matrix side data") + + memcpy(sd.data, self._display_matrix, n) + + def set_display_matrix(self, matrix): + """Set the display matrix written to the container as coded side data. + + ``matrix`` is a sequence of 9 integers in FFmpeg's ``AV_PKT_DATA_DISPLAYMATRIX`` + layout, or ``None`` to clear. Must be called before the first frame is + encoded. See :meth:`set_display_rotation` for a higher-level helper. + """ + if matrix is None: + self._has_display_matrix = False + return + + vals = [int(v) for v in matrix] + if len(vals) != 9: + raise ValueError("display matrix must have exactly 9 elements") + i: cython.int + for i in range(9): + self._display_matrix[i] = vals[i] + self._has_display_matrix = True + + def set_display_rotation(self, degrees, hflip=False, vflip=False): + """Set the container display matrix from a rotation and optional flips. + + ``degrees`` is a counter-clockwise rotation (matching the value read back + from :attr:`VideoFrame.rotation`); ``hflip`` / ``vflip`` mirror after it. + Together these express all eight EXIF orientations. Must be called before + the first frame is encoded. + """ + # av_display_rotation_set() takes a clockwise angle; negate so our public + # `degrees` is counter-clockwise, matching VideoFrame.rotation on read. + lib.av_display_rotation_set(self._display_matrix, -float(degrees)) + lib.av_display_matrix_flip(self._display_matrix, bool(hflip), bool(vflip)) + self._has_display_matrix = True + + @property + def average_rate(self): + """ + The average frame rate of this video stream. + + This is calculated when the file is opened by looking at the first + few frames and averaging their rate. + + :type: fractions.Fraction | None + """ + return avrational_to_fraction(cython.address(self.ptr.avg_frame_rate)) + + @property + def base_rate(self): + """ + The base frame rate of this stream. + + This is calculated as the lowest framerate at which the timestamps of + frames can be represented accurately. See :ffmpeg:`AVStream.r_frame_rate` + for more. + + :type: fractions.Fraction | None + """ + return avrational_to_fraction(cython.address(self.ptr.r_frame_rate)) + + @property + def guessed_rate(self): + """The guessed frame rate of this stream. + + This is a wrapper around :ffmpeg:`av_guess_frame_rate`, and uses multiple + heuristics to decide what is "the" frame rate. + + :type: fractions.Fraction | None + """ + val: lib.AVRational = lib.av_guess_frame_rate( + cython.NULL, self.ptr, cython.NULL + ) + return avrational_to_fraction(cython.address(val)) + + @property + def sample_aspect_ratio(self): + """The guessed sample aspect ratio (SAR) of this stream. + + This is a wrapper around :ffmpeg:`av_guess_sample_aspect_ratio`, and uses multiple + heuristics to decide what is "the" sample aspect ratio. + + :type: fractions.Fraction | None + """ + sar: lib.AVRational = lib.av_guess_sample_aspect_ratio( + self.container.ptr, self.ptr, cython.NULL + ) + return avrational_to_fraction(cython.address(sar)) + + @property + def display_aspect_ratio(self): + """The guessed display aspect ratio (DAR) of this stream. + + This is calculated from :meth:`.VideoStream.guessed_sample_aspect_ratio`. + + :type: fractions.Fraction | None + """ + dar = cython.declare(lib.AVRational) + lib.av_reduce( + cython.address(dar.num), + cython.address(dar.den), + self.format.width * self.sample_aspect_ratio.num, + self.format.height * self.sample_aspect_ratio.den, + 1024 * 1024, + ) + + return avrational_to_fraction(cython.address(dar)) diff --git a/.venv/lib/python3.12/site-packages/av/video/stream.pyi b/.venv/lib/python3.12/site-packages/av/video/stream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e6797f413d4a33339c23984e95908f678d73d436 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/video/stream.pyi @@ -0,0 +1,48 @@ +from collections.abc import Iterator, Sequence +from fractions import Fraction +from typing import Literal + +from av.codec.context import ThreadType +from av.packet import Packet +from av.stream import Stream + +from .codeccontext import VideoCodecContext +from .format import VideoFormat +from .frame import VideoFrame + +class VideoStream(Stream): + bit_rate: int | None + max_bit_rate: int | None + bit_rate_tolerance: int + sample_aspect_ratio: Fraction | None + display_aspect_ratio: Fraction | None + codec_context: VideoCodecContext + + def encode(self, frame: VideoFrame | None = None) -> list[Packet]: ... + def encode_lazy(self, frame: VideoFrame | None = None) -> Iterator[Packet]: ... + def decode(self, packet: Packet | None = None) -> list[VideoFrame]: ... + def set_display_matrix(self, matrix: Sequence[int] | None) -> None: ... + def set_display_rotation( + self, degrees: float, hflip: bool = ..., vflip: bool = ... + ) -> None: ... + + # from codec context + format: VideoFormat + thread_count: int + thread_type: ThreadType + width: int + height: int + bits_per_coded_sample: int + pix_fmt: str | None + framerate: Fraction + rate: Fraction + gop_size: int + has_b_frames: bool + max_b_frames: int + coded_width: int + coded_height: int + color_range: int + color_primaries: int + color_trc: int + colorspace: int + type: Literal["video"] diff --git a/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..43c537f628976f6e71e524f27a0388b13199a08b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/METADATA @@ -0,0 +1,123 @@ +Metadata-Version: 2.4 +Name: beautifulsoup4 +Version: 4.15.0 +Summary: Screen-scraping library +Project-URL: Download, https://www.crummy.com/software/BeautifulSoup/bs4/download/ +Project-URL: Homepage, https://www.crummy.com/software/BeautifulSoup/bs4/ +Author-email: Leonard Richardson +License: MIT License +License-File: AUTHORS +License-File: LICENSE +Keywords: HTML,XML,parse,soup +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Topic :: Text Processing :: Markup :: SGML +Classifier: Topic :: Text Processing :: Markup :: XML +Requires-Python: >=3.7.0 +Requires-Dist: soupsieve>=1.6.1 +Requires-Dist: typing-extensions>=4.0.0 +Provides-Extra: cchardet +Requires-Dist: cchardet; extra == 'cchardet' +Provides-Extra: chardet +Requires-Dist: chardet; extra == 'chardet' +Provides-Extra: charset-normalizer +Requires-Dist: charset-normalizer; extra == 'charset-normalizer' +Provides-Extra: html5lib +Requires-Dist: html5lib; extra == 'html5lib' +Provides-Extra: lxml +Requires-Dist: lxml; extra == 'lxml' +Description-Content-Type: text/markdown + +Beautiful Soup is a library that makes it easy to scrape information +from web pages. It sits atop an HTML or XML parser, providing Pythonic +idioms for iterating, searching, and modifying the parse tree. + +# Quick start + +``` +>>> from bs4 import BeautifulSoup +>>> soup = BeautifulSoup("

SomebadHTML") +>>> print(soup.prettify()) + + +

+ Some + + bad + + HTML + + +

+ + +>>> soup.find(string="bad") +'bad' +>>> soup.i +HTML +# +>>> soup = BeautifulSoup("SomebadXML", "xml") +# +>>> print(soup.prettify()) + + + Some + + bad + + XML + + +``` + +To go beyond the basics, [comprehensive documentation is available](https://www.crummy.com/software/BeautifulSoup/bs4/doc/). + +# Links + +* [Homepage](https://www.crummy.com/software/BeautifulSoup/bs4/) +* [Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) +* [Discussion group](https://groups.google.com/group/beautifulsoup/) +* [Development](https://code.launchpad.net/beautifulsoup/) +* [Bug tracker](https://bugs.launchpad.net/beautifulsoup/) +* [Complete changelog](https://git.launchpad.net/beautifulsoup/tree/CHANGELOG) + +# Note on Python 2 sunsetting + +Beautiful Soup's support for Python 2 was discontinued on December 31, +2020: one year after the sunset date for Python 2 itself. From this +point onward, new Beautiful Soup development will exclusively target +Python 3. The final release of Beautiful Soup 4 to support Python 2 +was 4.9.3. + +# Supporting the project + +If you use Beautiful Soup as part of your professional work, please consider a +[Tidelift subscription](https://tidelift.com/subscription/pkg/pypi-beautifulsoup4?utm_source=pypi-beautifulsoup4&utm_medium=referral&utm_campaign=readme). +This will support many of the free software projects your organization +depends on, not just Beautiful Soup. + +If you use Beautiful Soup for personal projects, the best way to say +thank you is to read +[Tool Safety](https://www.crummy.com/software/BeautifulSoup/zine/), a zine I +wrote about what Beautiful Soup has taught me about software +development. + +# Building the documentation + +The bs4/doc/ directory contains full documentation in Sphinx +format. Run `make html` in that directory to create HTML +documentation. + +# Running the unit tests + +Beautiful Soup supports unit test discovery using Pytest: + +``` +$ pytest +``` + diff --git a/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d56719ad04ca43135d4d4f84247a2d9089bed921 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/RECORD @@ -0,0 +1,37 @@ +beautifulsoup4-4.15.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +beautifulsoup4-4.15.0.dist-info/METADATA,sha256=sviIEDJZ8WB8hfOxFjvhvEn8mUGjJDw7iaIQdb_G1Ps,3812 +beautifulsoup4-4.15.0.dist-info/RECORD,, +beautifulsoup4-4.15.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +beautifulsoup4-4.15.0.dist-info/licenses/AUTHORS,sha256=uYkjiRjh_aweRnF8tAW2PpJJeickE68NmJwd9siry28,2201 +beautifulsoup4-4.15.0.dist-info/licenses/LICENSE,sha256=VbTY1LHlvIbRDvrJG3TIe8t3UmsPW57a-LnNKtxzl7I,1441 +bs4/__init__.py,sha256=kOAH-CqfxbzyKo3zs5W3vFJF5U1lzWj9UcoSpBRxjU4,44562 +bs4/__pycache__/__init__.cpython-312.pyc,, +bs4/__pycache__/_deprecation.cpython-312.pyc,, +bs4/__pycache__/_typing.cpython-312.pyc,, +bs4/__pycache__/_warnings.cpython-312.pyc,, +bs4/__pycache__/css.cpython-312.pyc,, +bs4/__pycache__/dammit.cpython-312.pyc,, +bs4/__pycache__/diagnose.cpython-312.pyc,, +bs4/__pycache__/element.cpython-312.pyc,, +bs4/__pycache__/exceptions.cpython-312.pyc,, +bs4/__pycache__/filter.cpython-312.pyc,, +bs4/__pycache__/formatter.cpython-312.pyc,, +bs4/_deprecation.py,sha256=niHJCk37APg8KEuFOa57ZXaxLdBmc_2V6uuaJqu7r30,2408 +bs4/_typing.py,sha256=zNcx7R1yCTK8WwtumP28hc7CJ3pMyZXj_VAeYaNXMZA,7549 +bs4/_warnings.py,sha256=ZuOETgcnEbZgw2N0nnNXn6wvtrn2ut7AF0d98bvkMFc,4711 +bs4/builder/__init__.py,sha256=Rl4qjOXvdyyyjayOFqbkgoUoo81IgoyKD-RwWeVK59g,31194 +bs4/builder/__pycache__/__init__.cpython-312.pyc,, +bs4/builder/__pycache__/_html5lib.cpython-312.pyc,, +bs4/builder/__pycache__/_htmlparser.cpython-312.pyc,, +bs4/builder/__pycache__/_lxml.cpython-312.pyc,, +bs4/builder/_html5lib.py,sha256=hL6xUk4_I2i5CMguFoYFlrI26cY4Dut7fOEQrUctHIM,23607 +bs4/builder/_htmlparser.py,sha256=SrjQvuL8SKOrXyjzNhE1XTBJpGslpE1LK-3B1vm7_r0,19866 +bs4/builder/_lxml.py,sha256=ks1e8boA_nOA2oomAhxeudccR6ThbEE-EllFqHRoPLA,18969 +bs4/css.py,sha256=_m_l_4SGWHnY620VJ21j_qQH1RX3p91sYVemgKxaLsM,12713 +bs4/dammit.py,sha256=0mFwW_-Hklybot_Mg3goTqYYfKfluKJT_WJU4ojbQF4,57485 +bs4/diagnose.py,sha256=at98iuxyOrqec4V8iwkTIbNUqBCsq9Lr3fDAQx2129Y,7846 +bs4/element.py,sha256=oQm8ZK9P1RN7TnOawlS5wdUYwss2OR0h5ZET6VuGJkE,125805 +bs4/exceptions.py,sha256=Q9FOadNe8QRvzDMaKSXe2Wtl8JK_oAZW7mbFZBVP_GE,951 +bs4/filter.py,sha256=d9wtWHkg8cx3bU0BPjLeGgFpHVORzX6HAnftB6rsXqM,29180 +bs4/formatter.py,sha256=uBT0k6W8O5kJ9PCuJYjra97yoUqC-dlM9D_v-oRM0r8,10478 +bs4/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/licenses/AUTHORS b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..18926c29de853ed7408b80d440fcf0821646ad1f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/licenses/AUTHORS @@ -0,0 +1,49 @@ +Behold, mortal, the origins of Beautiful Soup... +================================================ + +Leonard Richardson is the primary maintainer. + +Aaron DeVore, Isaac Muse and Chris Papademetrious have made +significant contributions to the code base. + +Mark Pilgrim provided the encoding detection code that forms the base +of UnicodeDammit. + +Thomas Kluyver and Ezio Melotti finished the work of getting Beautiful +Soup 4 working under Python 3. + +Simon Willison wrote soupselect, which was used to make Beautiful Soup +support CSS selectors. Isaac Muse wrote SoupSieve, which made it +possible to _remove_ the CSS selector code from Beautiful Soup. + +Sam Ruby helped with a lot of edge cases. + +Jonathan Ellis was awarded the prestigious Beau Potage D'Or for his +work in solving the nestable tags conundrum. + +An incomplete list of people have contributed patches to Beautiful +Soup: + + Istvan Albert, Andrew Lin, Anthony Baxter, Oliver Beattie, Andrew +Boyko, Tony Chang, Francisco Canas, "Delong", Zephyr Fang, Fuzzy, +Roman Gaufman, Yoni Gilad, Richie Hindle, Toshihiro Kamiya, Peteris +Krumins, Kent Johnson, Marek Kapolka, Andreas Kostyrka, Roel Kramer, +Ben Last, Robert Leftwich, Stefaan Lippens, "liquider", Staffan +Malmgren, Ksenia Marasanova, JP Moins, Adam Monsen, John Nagle, "Jon", +Ed Oskiewicz, Martijn Peters, Greg Phillips, Giles Radford, Stefano +Revera, Arthur Rudolph, Marko Samastur, James Salter, Jouni Seppänen, +Alexander Schmolck, Tim Shirley, Geoffrey Sneddon, Ville Skyttä, +"Vikas", Jens Svalgaard, Andy Theyers, Eric Weiser, Glyn Webster, John +Wiseman, Paul Wright, Danny Yoo + +An incomplete list of people who made suggestions or found bugs or +found ways to break Beautiful Soup: + + Hanno Böck, Matteo Bertini, Chris Curvey, Simon Cusack, Bruce Eckel, + Matt Ernst, Michael Foord, Tom Harris, Bill de hOra, Donald Howes, + Matt Patterson, Scott Roberts, Steve Strassmann, Mike Williams, + warchild at redho dot com, Sami Kuisma, Carlos Rocha, Bob Hutchison, + Joren Mc, Michal Migurski, John Kleven, Tim Heaney, Tripp Lilley, Ed + Summers, Dennis Sutch, Chris Smith, Aaron Swartz, Stuart + Turner, Greg Edwards, Kevin J Kalupson, Nikos Kouremenos, Artur de + Sousa Rocha, Yichun Wei, Per Vognsen diff --git a/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..08e3a9cf8c7143d74a4c5716e8a4f00eb3caac41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/beautifulsoup4-4.15.0.dist-info/licenses/LICENSE @@ -0,0 +1,31 @@ +Beautiful Soup is made available under the MIT license: + + Copyright (c) Leonard Richardson + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +Beautiful Soup incorporates code from the html5lib library, which is +also made available under the MIT license. Copyright (c) James Graham +and other contributors + +Beautiful Soup has an optional dependency on the soupsieve library, +which is also made available under the MIT license. Copyright (c) +Isaac Muse diff --git a/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0eaeb1d24ef611bd970c53b653c61c8155e8dee5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/METADATA @@ -0,0 +1,10 @@ +Metadata-Version: 2.1 +Name: bs4 +Version: 0.0.2 +Summary: Dummy package for Beautiful Soup (beautifulsoup4) +Author-email: Leonard Richardson +License: MIT License +Requires-Dist: beautifulsoup4 +Description-Content-Type: text/x-rst + +This is a dummy package designed to prevent namesquatting on PyPI. You should install `beautifulsoup4 `_ instead. diff --git a/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..36b77a707d55fa41ae34c7347c09b7898379bf3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/RECORD @@ -0,0 +1,5 @@ +README.rst,sha256=KMs4D-t40JC-oge8vGS3O5gueksurGqAIFxPtHZAMXQ,159 +bs4-0.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +bs4-0.0.2.dist-info/METADATA,sha256=GEwOSFCOYLu11XQR3O2dMO7ZTpKFZpGoIUG0gkFVgA8,411 +bs4-0.0.2.dist-info/RECORD,, +bs4-0.0.2.dist-info/WHEEL,sha256=VYAwk8D_V6zmIA2XKK-k7Fem_KAtVk3hugaRru3yjGc,105 diff --git a/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..a5543bae8de8b5636341fae2f789b174140e9865 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4-0.0.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.21.0 +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/bs4/__init__.py b/.venv/lib/python3.12/site-packages/bs4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b41ee74e6657304d3257021d41f19862aecb191 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4/__init__.py @@ -0,0 +1,1179 @@ +"""Beautiful Soup Elixir and Tonic - "The Screen-Scraper's Friend". + +http://www.crummy.com/software/BeautifulSoup/ + +Beautiful Soup uses a pluggable XML or HTML parser to parse a +(possibly invalid) document into a tree representation. Beautiful Soup +provides methods and Pythonic idioms that make it easy to navigate, +search, and modify the parse tree. + +Beautiful Soup works with Python 3.7 and up. It works better if lxml +and/or html5lib is installed, but they are not required. + +For more than you ever wanted to know about Beautiful Soup, see the +documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ +""" + +__author__ = "Leonard Richardson (leonardr@segfault.org)" +__version__ = "4.15.0" +__copyright__ = "Copyright (c) 2004-2026 Leonard Richardson" +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +__all__ = [ + "AttributeResemblesVariableWarning", + "BeautifulSoup", + "Comment", + "Declaration", + "ProcessingInstruction", + "ResultSet", + "CSS", + "Script", + "Stylesheet", + "Tag", + "TemplateString", + "ElementFilter", + "UnicodeDammit", + "CData", + "Doctype", + + # Exceptions + "FeatureNotFound", + "ParserRejectedMarkup", + "StopParsing", + + # Warnings + "AttributeResemblesVariableWarning", + "GuessedAtParserWarning", + "MarkupResemblesLocatorWarning", + "UnusualUsageWarning", + "XMLParsedAsHTMLWarning", +] + +from collections import Counter +import io +import sys +import warnings + +# The very first thing we do is give a useful error if someone is +# running this code under Python 2. +if sys.version_info.major < 3: + raise ImportError( + "You are trying to use a Python 3-specific version of Beautiful Soup under Python 2. This will not work. The final version of Beautiful Soup to support Python 2 was 4.9.3." + ) + +from .builder import ( + builder_registry, + TreeBuilder, +) +from .builder._htmlparser import HTMLParserTreeBuilder +from .dammit import UnicodeDammit +from .css import CSS +from ._deprecation import ( + _deprecated, +) +from .element import ( + CData, + Comment, + DEFAULT_OUTPUT_ENCODING, + Declaration, + Doctype, + NavigableString, + PageElement, + ProcessingInstruction, + PYTHON_SPECIFIC_ENCODINGS, + ResultSet, + Script, + Stylesheet, + Tag, + TemplateString, +) +from .formatter import Formatter +from .filter import ( + ElementFilter, + SoupStrainer, +) +from typing import ( + Any, + cast, + Counter as CounterType, + Dict, + Iterator, + List, + Sequence, + Sized, + Optional, + Type, + Union, +) + +from bs4._typing import ( + _Encoding, + _Encodings, + _IncomingMarkup, + _InsertableElement, + _RawAttributeValue, + _RawAttributeValues, + _RawMarkup, +) + +# Import all warnings and exceptions into the main package. +from bs4.exceptions import ( + FeatureNotFound, + ParserRejectedMarkup, + StopParsing, +) +from bs4._warnings import ( + AttributeResemblesVariableWarning, + GuessedAtParserWarning, + MarkupResemblesLocatorWarning, + UnusualUsageWarning, + XMLParsedAsHTMLWarning, +) + + +class BeautifulSoup(Tag): + """A data structure representing a parsed HTML or XML document. + + Most of the methods you'll call on a BeautifulSoup object are inherited from + PageElement or Tag. + + Internally, this class defines the basic interface called by the + tree builders when converting an HTML/XML document into a data + structure. The interface abstracts away the differences between + parsers. To write a new tree builder, you'll need to understand + these methods as a whole. + + These methods will be called by the BeautifulSoup constructor: + * reset() + * feed(markup) + + The tree builder may call these methods from its feed() implementation: + * handle_starttag(name, attrs) # See note about return value + * handle_endtag(name) + * handle_data(data) # Appends to the current data node + * endData(containerClass) # Ends the current data node + + No matter how complicated the underlying parser is, you should be + able to build a tree using 'start tag' events, 'end tag' events, + 'data' events, and "done with data" events. + + If you encounter an empty-element tag (aka a self-closing tag, + like HTML's
tag), call handle_starttag and then + handle_endtag. + """ + + #: Since `BeautifulSoup` subclasses `Tag`, it's possible to treat it as + #: a `Tag` with a `Tag.name`. Hoever, this name makes it clear the + #: `BeautifulSoup` object isn't a real markup tag. + ROOT_TAG_NAME: str = "[document]" + + #: If the end-user gives no indication which tree builder they + #: want, look for one with these features. + DEFAULT_BUILDER_FEATURES: Sequence[str] = ["html", "fast"] + + #: A string containing all ASCII whitespace characters, used in + #: during parsing to detect data chunks that seem 'empty'. + ASCII_SPACES: str = "\x20\x0a\x09\x0c\x0d" + + # FUTURE PYTHON: + element_classes: Dict[Type[PageElement], Type[PageElement]] #: :meta private: + builder: TreeBuilder #: :meta private: + is_xml: bool + known_xml: Optional[bool] + parse_only: Optional[SoupStrainer] #: :meta private: + + # These members are only used while parsing markup. + markup: Optional[_RawMarkup] #: :meta private: + current_data: List[str] #: :meta private: + currentTag: Optional[Tag] #: :meta private: + tagStack: List[Tag] #: :meta private: + open_tag_counter: CounterType[str] #: :meta private: + preserve_whitespace_tag_stack: List[Tag] #: :meta private: + string_container_stack: List[Tag] #: :meta private: + _most_recent_element: Optional[PageElement] #: :meta private: + + #: Beautiful Soup's best guess as to the character encoding of the + #: original document. + original_encoding: Optional[_Encoding] + + #: The character encoding, if any, that was explicitly defined + #: in the original document. This may or may not match + #: `BeautifulSoup.original_encoding`. + declared_html_encoding: Optional[_Encoding] + + #: This is True if the markup that was parsed contains + #: U+FFFD REPLACEMENT_CHARACTER characters which were not present + #: in the original markup. These mark character sequences that + #: could not be represented in Unicode. + contains_replacement_characters: bool + + def __init__( + self, + markup: _IncomingMarkup = "", + features: Optional[Union[str, Sequence[str]]] = None, + builder: Optional[Union[TreeBuilder, Type[TreeBuilder]]] = None, + parse_only: Optional[SoupStrainer] = None, + from_encoding: Optional[_Encoding] = None, + exclude_encodings: Optional[_Encodings] = None, + element_classes: Optional[Dict[Type[PageElement], Type[PageElement]]] = None, + **kwargs: Any, + ): + """Constructor. + + :param markup: A string or a file-like object representing + markup to be parsed. + + :param features: Desirable features of the parser to be + used. This may be the name of a specific parser ("lxml", + "lxml-xml", "html.parser", or "html5lib") or it may be the + type of markup to be used ("html", "html5", "xml"). It's + recommended that you name a specific parser, so that + Beautiful Soup gives you the same results across platforms + and virtual environments. + + :param builder: A TreeBuilder subclass to instantiate (or + instance to use) instead of looking one up based on + `features`. You only need to use this if you've implemented a + custom TreeBuilder. + + :param parse_only: A SoupStrainer. Only parts of the document + matching the SoupStrainer will be considered. This is useful + when parsing part of a document that would otherwise be too + large to fit into memory. + + :param from_encoding: A string indicating the encoding of the + document to be parsed. Pass this in if Beautiful Soup is + guessing wrongly about the document's encoding. + + :param exclude_encodings: A list of strings indicating + encodings known to be wrong. Pass this in if you don't know + the document's encoding but you know Beautiful Soup's guess is + wrong. + + :param element_classes: A dictionary mapping BeautifulSoup + classes like Tag and NavigableString, to other classes you'd + like to be instantiated instead as the parse tree is + built. This is useful for subclassing Tag or NavigableString + to modify default behavior. + + :param kwargs: For backwards compatibility purposes, the + constructor accepts certain keyword arguments used in + Beautiful Soup 3. None of these arguments do anything in + Beautiful Soup 4; they will result in a warning and then be + ignored. + + Apart from this, any keyword arguments passed into the + BeautifulSoup constructor are propagated to the TreeBuilder + constructor. This makes it possible to configure a + TreeBuilder by passing in arguments, not just by saying which + one to use. + """ + if "convertEntities" in kwargs: + del kwargs["convertEntities"] + warnings.warn( + "BS4 does not respect the convertEntities argument to the " + "BeautifulSoup constructor. Entities are always converted " + "to Unicode characters." + ) + + if "markupMassage" in kwargs: + del kwargs["markupMassage"] + warnings.warn( + "BS4 does not respect the markupMassage argument to the " + "BeautifulSoup constructor. The tree builder is responsible " + "for any necessary markup massage." + ) + + if "smartQuotesTo" in kwargs: + del kwargs["smartQuotesTo"] + warnings.warn( + "BS4 does not respect the smartQuotesTo argument to the " + "BeautifulSoup constructor. Smart quotes are always converted " + "to Unicode characters." + ) + + if "selfClosingTags" in kwargs: + del kwargs["selfClosingTags"] + warnings.warn( + "Beautiful Soup 4 does not respect the selfClosingTags argument to the " + "BeautifulSoup constructor. The tree builder is responsible " + "for understanding self-closing tags." + ) + + if "isHTML" in kwargs: + del kwargs["isHTML"] + warnings.warn( + "Beautiful Soup 4 does not respect the isHTML argument to the " + "BeautifulSoup constructor. Suggest you use " + "features='lxml' for HTML and features='lxml-xml' for " + "XML." + ) + + def deprecated_argument(old_name: str, new_name: str) -> Optional[Any]: + if old_name in kwargs: + warnings.warn( + 'The "%s" argument to the BeautifulSoup constructor ' + 'was renamed to "%s" in Beautiful Soup 4.0.0' + % (old_name, new_name), + DeprecationWarning, + stacklevel=3, + ) + return kwargs.pop(old_name) + return None + + parse_only = parse_only or deprecated_argument("parseOnlyThese", "parse_only") + if parse_only is not None: + # Issue a warning if we can tell in advance that + # parse_only will exclude the entire tree. + if parse_only.excludes_everything: + warnings.warn( + f"The given value for parse_only will exclude everything: {parse_only}", + UserWarning, + stacklevel=3, + ) + + from_encoding = from_encoding or deprecated_argument( + "fromEncoding", "from_encoding" + ) + + if from_encoding and isinstance(markup, str): + warnings.warn( + "You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored." + ) + from_encoding = None + + self.element_classes = element_classes or dict() + + # We need this information to track whether or not the builder + # was specified well enough that we can omit the 'you need to + # specify a parser' warning. + original_builder = builder + original_features = features + + builder_class: Optional[Type[TreeBuilder]] = None + if isinstance(builder, type): + # A builder class was passed in; it needs to be instantiated. + builder_class = builder + builder = None + elif builder is None: + if isinstance(features, str): + features = [features] + if features is None or len(features) == 0: + features = self.DEFAULT_BUILDER_FEATURES + possible_builder_class = builder_registry.lookup(*features) + if possible_builder_class is None: + raise FeatureNotFound( + "Couldn't find a tree builder with the features you " + "requested: %s. Do you need to install a parser library?" + % ",".join(features) + ) + builder_class = possible_builder_class + + # At this point either we have a TreeBuilder instance in + # builder, or we have a builder_class that we can instantiate + # with the remaining **kwargs. + if builder is None: + assert builder_class is not None + builder = builder_class(**kwargs) + if ( + not original_builder + and not ( + original_features == builder.NAME + or ( + isinstance(original_features, str) + and original_features in builder.ALTERNATE_NAMES + ) + ) + and markup + ): + # The user did not tell us which TreeBuilder to use, + # and we had to guess. Issue a warning. + if builder.is_xml: + markup_type = "XML" + else: + markup_type = "HTML" + + # This code adapted from warnings.py so that we get the same line + # of code as our warnings.warn() call gets, even if the answer is wrong + # (as it may be in a multithreading situation). + caller = None + try: + caller = sys._getframe(1) + except ValueError: + pass + if caller: + globals = caller.f_globals + line_number = caller.f_lineno + else: + globals = sys.__dict__ + line_number = 1 + filename = globals.get("__file__") + if filename: + fnl = filename.lower() + if fnl.endswith((".pyc", ".pyo")): + filename = filename[:-1] + if filename: + # If there is no filename at all, the user is most likely in a REPL, + # and the warning is not necessary. + values = dict( + filename=filename, + line_number=line_number, + parser=builder.NAME, + markup_type=markup_type, + ) + warnings.warn( + GuessedAtParserWarning.MESSAGE % values, + GuessedAtParserWarning, + stacklevel=2, + ) + else: + if kwargs: + warnings.warn( + "Keyword arguments to the BeautifulSoup constructor will be ignored. These would normally be passed into the TreeBuilder constructor, but a TreeBuilder instance was passed in as `builder`." + ) + + self.builder = builder + self.is_xml = builder.is_xml + self.known_xml = self.is_xml + self._namespaces = dict() + self.parse_only = parse_only + + if hasattr(markup, "read"): # It's a file-type object. + markup = cast(io.IOBase, markup).read() + elif not isinstance(markup, (bytes, str)) and not hasattr(markup, "__len__"): + raise TypeError( + f"Incoming markup is of an invalid type: {markup!r}. Markup must be a string, a bytestring, or an open filehandle." + ) + elif isinstance(markup, Sized) and len(markup) <= 256 and ( + (isinstance(markup, bytes) and b"<" not in markup and b"\n" not in markup) + or (isinstance(markup, str) and "<" not in markup and "\n" not in markup) + ): + # Issue warnings for a couple beginner problems + # involving passing non-markup to Beautiful Soup. + # Beautiful Soup will still parse the input as markup, + # since that is sometimes the intended behavior. + if not self._markup_is_url(markup): + self._markup_resembles_filename(markup) + + # At this point we know markup is a string or bytestring. If + # it was a file-type object, we've read from it. + markup = cast(_RawMarkup, markup) + + rejections = [] + success = False + for ( + self.markup, + self.original_encoding, + self.declared_html_encoding, + self.contains_replacement_characters, + ) in self.builder.prepare_markup( + markup, from_encoding, exclude_encodings=exclude_encodings + ): + self.reset() + self.builder.initialize_soup(self) + try: + self._feed() + success = True + break + except ParserRejectedMarkup as e: + rejections.append(e) + pass + + if not success: + other_exceptions = [str(e) for e in rejections] + raise ParserRejectedMarkup( + "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.\n\nOriginal exception(s) from parser:\n " + + "\n ".join(other_exceptions) + ) + + # Clear out the markup and remove the builder's circular + # reference to this object. + self.markup = None + self.builder.soup = None + + def copy_self(self) -> "BeautifulSoup": + """Create a new BeautifulSoup object with the same TreeBuilder, + but not associated with any markup. + + This is the first step of the deepcopy process. + """ + clone = type(self)("", None, self.builder) + + # Keep track of the encoding of the original document, + # since we won't be parsing it again. + clone.original_encoding = self.original_encoding + return clone + + def __getstate__(self) -> Dict[str, Any]: + # Frequently a tree builder can't be pickled. + d = dict(self.__dict__) + if "builder" in d and d["builder"] is not None and not self.builder.picklable: + d["builder"] = type(self.builder) + # Store the contents as a Unicode string. + d["contents"] = [] + d["markup"] = self.decode() + + # If _most_recent_element is present, it's a Tag object left + # over from initial parse. It might not be picklable and we + # don't need it. + if "_most_recent_element" in d: + del d["_most_recent_element"] + return d + + def __setstate__(self, state: Dict[str, Any]) -> None: + # If necessary, restore the TreeBuilder by looking it up. + self.__dict__ = state + if isinstance(self.builder, type): + self.builder = self.builder() + elif not self.builder: + # We don't know which builder was used to build this + # parse tree, so use a default we know is always available. + self.builder = HTMLParserTreeBuilder() + self.builder.soup = self + self.reset() + self._feed() + + @property + def _is_root(self): + """Yes, a BeautifulSoup object is the root of its parse tree. Used by the _root_object internal property.""" + return True + + @classmethod + @_deprecated( + replaced_by="nothing (private method, will be removed)", version="4.13.0" + ) + def _decode_markup(cls, markup: _RawMarkup) -> str: + """Ensure `markup` is Unicode so it's safe to send into warnings.warn. + + warnings.warn had this problem back in 2010 but fortunately + not anymore. This has not been used for a long time; I just + noticed that fact while working on 4.13.0. + """ + if isinstance(markup, bytes): + decoded = markup.decode("utf-8", "replace") + else: + decoded = markup + return decoded + + @classmethod + def _markup_is_url(cls, markup: _RawMarkup) -> bool: + """Error-handling method to raise a warning if incoming markup looks + like a URL. + + :param markup: A string of markup. + :return: Whether or not the markup resembled a URL + closely enough to justify issuing a warning. + """ + problem: bool = False + if isinstance(markup, bytes): + problem = ( + any(markup.startswith(prefix) for prefix in (b"http:", b"https:")) + and b" " not in markup + ) + elif isinstance(markup, str): + problem = ( + any(markup.startswith(prefix) for prefix in ("http:", "https:")) + and " " not in markup + ) + else: + return False + + if not problem: + return False + warnings.warn( + MarkupResemblesLocatorWarning.URL_MESSAGE % dict(what="URL"), + MarkupResemblesLocatorWarning, + stacklevel=3, + ) + return True + + @classmethod + def _markup_resembles_filename(cls, markup: _RawMarkup) -> bool: + """Error-handling method to issue a warning if incoming markup + resembles a filename. + + :param markup: A string of markup. + :return: Whether or not the markup resembled a filename + closely enough to justify issuing a warning. + """ + markup_b: bytes + + # We're only checking ASCII characters, so rather than write + # the same tests twice, convert Unicode to a bytestring and + # operate on the bytestring. + if isinstance(markup, str): + markup_b = markup.encode("utf8") + else: + markup_b = markup + + # Step 1: does it end with a common textual file extension? + filelike = False + lower = markup_b.lower() + extensions = [b".html", b".htm", b".xml", b".xhtml", b".txt"] + if any(lower.endswith(ext) for ext in extensions): + filelike = True + if not filelike: + return False + + # Step 2: it _might_ be a file, but there are a few things + # we can look for that aren't very common in filenames. + + # Characters that have special meaning to Unix shells. (< was + # excluded before this method was called.) + # + # Many of these are also reserved characters that cannot + # appear in Windows filenames. + for byte in markup_b: + if byte in b"?*#&;>$|": + return False + + # Two consecutive forward slashes (as seen in a URL) or two + # consecutive spaces (as seen in fixed-width data). + # + # (Paths to Windows network shares contain consecutive + # backslashes, so checking that doesn't seem as helpful.) + if b"//" in markup_b: + return False + if b" " in markup_b: + return False + + # A colon in any position other than position 1 (e.g. after a + # Windows drive letter). + if markup_b.startswith(b":"): + return False + colon_i = markup_b.rfind(b":") + if colon_i not in (-1, 1): + return False + + # Step 3: If it survived all of those checks, it's similar + # enough to a file to justify issuing a warning. + warnings.warn( + MarkupResemblesLocatorWarning.FILENAME_MESSAGE % dict(what="filename"), + MarkupResemblesLocatorWarning, + stacklevel=3, + ) + return True + + def _feed(self) -> None: + """Internal method that parses previously set markup, creating a large + number of Tag and NavigableString objects. + """ + # Convert the document to Unicode. + self.builder.reset() + + if self.markup is not None: + self.builder.feed(self.markup) + # Close out any unfinished strings and close all the open tags. + self.endData() + while ( + self.currentTag is not None and self.currentTag.name != self.ROOT_TAG_NAME + ): + self.popTag() + + def reset(self) -> None: + """Reset this object to a state as though it had never parsed any + markup. + """ + Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME) + self.hidden = True + self.builder.reset() + self.current_data = [] + self.currentTag = None + self.tagStack = [] + self.open_tag_counter = Counter() + self.preserve_whitespace_tag_stack = [] + self.string_container_stack = [] + self._most_recent_element = None + self.pushTag(self) + + def new_tag( + self, + name: str, + namespace: Optional[str] = None, + nsprefix: Optional[str] = None, + attrs: Optional[_RawAttributeValues] = None, + sourceline: Optional[int] = None, + sourcepos: Optional[int] = None, + string: Optional[str] = None, + **kwattrs: _RawAttributeValue, + ) -> Tag: + """Create a new Tag associated with this BeautifulSoup object. + + :param name: The name of the new Tag. + :param namespace: The URI of the new Tag's XML namespace, if any. + :param prefix: The prefix for the new Tag's XML namespace, if any. + :param attrs: A dictionary of this Tag's attribute values; can + be used instead of ``kwattrs`` for attributes like 'class' + that are reserved words in Python. + :param sourceline: The line number where this tag was + (purportedly) found in its source document. + :param sourcepos: The character position within ``sourceline`` where this + tag was (purportedly) found. + :param string: String content for the new Tag, if any. + :param kwattrs: Keyword arguments for the new Tag's attribute values. + + """ + attr_container = self.builder.attribute_dict_class(**kwattrs) + if attrs is not None: + attr_container.update(attrs) + tag_class = self.element_classes.get(Tag, Tag) + + # Assume that this is either Tag or a subclass of Tag. If not, + # the user brought type-unsafety upon themselves. + tag_class = cast(Type[Tag], tag_class) + tag = tag_class( + None, + self.builder, + name, + namespace, + nsprefix, + attr_container, + sourceline=sourceline, + sourcepos=sourcepos, + ) + + if string is not None: + tag.string = string + return tag + + def string_container( + self, base_class: Optional[Type[NavigableString]] = None + ) -> Type[NavigableString]: + """Find the class that should be instantiated to hold a given kind of + string. + + This may be a built-in Beautiful Soup class or a custom class passed + in to the BeautifulSoup constructor. + """ + container = base_class or NavigableString + + # The user may want us to use some other class (hopefully a + # custom subclass) instead of the one we'd use normally. + container = cast( + Type[NavigableString], self.element_classes.get(container, container) + ) + + # On top of that, we may be inside a tag that needs a special + # container class. + if self.string_container_stack and container is NavigableString: + container = self.builder.string_containers.get( + self.string_container_stack[-1].name, container + ) + return container + + def new_string( + self, s: str, subclass: Optional[Type[NavigableString]] = None + ) -> NavigableString: + """Create a new `NavigableString` associated with this `BeautifulSoup` + object. + + :param s: The string content of the `NavigableString` + :param subclass: The subclass of `NavigableString`, if any, to + use. If a document is being processed, an appropriate + subclass for the current location in the document will + be determined automatically. + """ + container = self.string_container(subclass) + return container(s) + + def insert_before(self, *args: _InsertableElement) -> List[PageElement]: + """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement + it because there is nothing before or after it in the parse tree. + """ + raise NotImplementedError( + "BeautifulSoup objects don't support insert_before()." + ) + + def insert_after(self, *args: _InsertableElement) -> List[PageElement]: + """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement + it because there is nothing before or after it in the parse tree. + """ + raise NotImplementedError("BeautifulSoup objects don't support insert_after().") + + def popTag(self) -> Optional[Tag]: + """Internal method called by _popToTag when a tag is closed. + + :meta private: + """ + if not self.tagStack: + # Nothing to pop. This shouldn't happen. + return None + tag = self.tagStack.pop() + if tag.name in self.open_tag_counter: + self.open_tag_counter[tag.name] -= 1 + if ( + self.preserve_whitespace_tag_stack + and tag == self.preserve_whitespace_tag_stack[-1] + ): + self.preserve_whitespace_tag_stack.pop() + if self.string_container_stack and tag == self.string_container_stack[-1]: + self.string_container_stack.pop() + # print("Pop", tag.name) + if self.tagStack: + self.currentTag = self.tagStack[-1] + return self.currentTag + + def pushTag(self, tag: Tag) -> None: + """Internal method called by handle_starttag when a tag is opened. + + :meta private: + """ + # print("Push", tag.name) + if self.currentTag is not None: + self.currentTag.contents.append(tag) + self.tagStack.append(tag) + self.currentTag = self.tagStack[-1] + if tag.name != self.ROOT_TAG_NAME: + self.open_tag_counter[tag.name] += 1 + if tag.name in self.builder.preserve_whitespace_tags: + self.preserve_whitespace_tag_stack.append(tag) + if tag.name in self.builder.string_containers: + self.string_container_stack.append(tag) + + def endData(self, containerClass: Optional[Type[NavigableString]] = None) -> None: + """Method called by the TreeBuilder when the end of a data segment + occurs. + + :param containerClass: The class to use when incorporating the + data segment into the parse tree. + + :meta private: + """ + if self.current_data: + current_data = "".join(self.current_data) + # If whitespace is not preserved, and this string contains + # nothing but ASCII spaces, replace it with a single space + # or newline. + if not self.preserve_whitespace_tag_stack: + strippable = True + for i in current_data: + if i not in self.ASCII_SPACES: + strippable = False + break + if strippable: + if "\n" in current_data: + current_data = "\n" + else: + current_data = " " + + # Reset the data collector. + self.current_data = [] + + # Should we add this string to the tree at all? + if ( + self.parse_only + and len(self.tagStack) <= 1 + and (not self.parse_only.allow_string_creation(current_data)) + ): + return + + containerClass = self.string_container(containerClass) + o = containerClass(current_data) + self.object_was_parsed(o) + + def object_was_parsed( + self, + o: PageElement, + parent: Optional[Tag] = None, + most_recent_element: Optional[PageElement] = None, + ) -> None: + """Method called by the TreeBuilder to integrate an object into the + parse tree. + + :meta private: + """ + if parent is None: + parent = self.currentTag + assert parent is not None + previous_element: Optional[PageElement] + if most_recent_element is not None: + previous_element = most_recent_element + else: + previous_element = self._most_recent_element + + next_element = previous_sibling = next_sibling = None + if isinstance(o, Tag): + next_element = o.next_element + next_sibling = o.next_sibling + previous_sibling = o.previous_sibling + if previous_element is None: + previous_element = o.previous_element + + fix = parent.next_element is not None + + o.setup(parent, previous_element, next_element, previous_sibling, next_sibling) + + self._most_recent_element = o + parent.contents.append(o) + + # Check if we are inserting into an already parsed node. + if fix: + self._linkage_fixer(parent) + + def _linkage_fixer(self, el: Tag) -> None: + """Make sure linkage of this fragment is sound.""" + + first = el.contents[0] + child = el.contents[-1] + descendant: PageElement = child + + if child is first and el.parent is not None: + # Parent should be linked to first child + el.next_element = child + # We are no longer linked to whatever this element is + prev_el = child.previous_element + if prev_el is not None and prev_el is not el: + prev_el.next_element = None + # First child should be linked to the parent, and no previous siblings. + child.previous_element = el + child.previous_sibling = None + + # We have no sibling as we've been appended as the last. + child.next_sibling = None + + # This index is a tag, dig deeper for a "last descendant" + if isinstance(child, Tag) and child.contents: + # _last_decendant is typed as returning Optional[PageElement], + # but the value can't be None here, because el is a Tag + # which we know has contents. + descendant = cast(PageElement, child._last_descendant(False)) + + # As the final step, link last descendant. It should be linked + # to the parent's next sibling (if found), else walk up the chain + # and find a parent with a sibling. It should have no next sibling. + descendant.next_element = None + descendant.next_sibling = None + + target: Optional[Tag] = el + while True: + if target is None: + break + elif target.next_sibling is not None: + descendant.next_element = target.next_sibling + target.next_sibling.previous_element = child + break + target = target.parent + + def _popToTag( + self, name: str, nsprefix: Optional[str] = None, inclusivePop: bool = True + ) -> Optional[Tag]: + """Pops the tag stack up to and including the most recent + instance of the given tag. + + If there are no open tags with the given name, nothing will be + popped. + + :param name: Pop up to the most recent tag with this name. + :param nsprefix: The namespace prefix that goes with `name`. + :param inclusivePop: It this is false, pops the tag stack up + to but *not* including the most recent instqance of the + given tag. + + :meta private: + """ + # print("Popping to %s" % name) + if name == self.ROOT_TAG_NAME: + # The BeautifulSoup object itself can never be popped. + return None + + most_recently_popped = None + + stack_size = len(self.tagStack) + for i in range(stack_size - 1, 0, -1): + if not self.open_tag_counter.get(name): + break + t = self.tagStack[i] + if name == t.name and nsprefix == t.prefix: + if inclusivePop: + most_recently_popped = self.popTag() + break + most_recently_popped = self.popTag() + + return most_recently_popped + + def handle_starttag( + self, + name: str, + namespace: Optional[str], + nsprefix: Optional[str], + attrs: _RawAttributeValues, + sourceline: Optional[int] = None, + sourcepos: Optional[int] = None, + namespaces: Optional[Dict[str, str]] = None, + ) -> Optional[Tag]: + """Called by the tree builder when a new tag is encountered. + + :param name: Name of the tag. + :param nsprefix: Namespace prefix for the tag. + :param attrs: A dictionary of attribute values. Note that + attribute values are expected to be simple strings; processing + of multi-valued attributes such as "class" comes later. + :param sourceline: The line number where this tag was found in its + source document. + :param sourcepos: The character position within `sourceline` where this + tag was found. + :param namespaces: A dictionary of all namespace prefix mappings + currently in scope in the document. + + If this method returns None, the tag was rejected by an active + `ElementFilter`. You should proceed as if the tag had not occurred + in the document. For instance, if this was a self-closing tag, + don't call handle_endtag. + + :meta private: + """ + # print("Start tag %s: %s" % (name, attrs)) + self.endData() + + if ( + self.parse_only + and len(self.tagStack) <= 1 + and not self.parse_only.allow_tag_creation(nsprefix, name, attrs) + ): + return None + + tag_class = self.element_classes.get(Tag, Tag) + # Assume that this is either Tag or a subclass of Tag. If not, + # the user brought type-unsafety upon themselves. + tag_class = cast(Type[Tag], tag_class) + tag = tag_class( + self, + self.builder, + name, + namespace, + nsprefix, + attrs, + self.currentTag, + self._most_recent_element, + sourceline=sourceline, + sourcepos=sourcepos, + namespaces=namespaces, + ) + if tag is None: + return tag + if self._most_recent_element is not None: + self._most_recent_element.next_element = tag + self._most_recent_element = tag + self.pushTag(tag) + return tag + + def handle_endtag(self, name: str, nsprefix: Optional[str] = None) -> None: + """Called by the tree builder when an ending tag is encountered. + + :param name: Name of the tag. + :param nsprefix: Namespace prefix for the tag. + + :meta private: + """ + # print("End tag: " + name) + self.endData() + self._popToTag(name, nsprefix) + + def handle_data(self, data: str) -> None: + """Called by the tree builder when a chunk of textual data is + encountered. + + :meta private: + """ + self.current_data.append(data) + + def decode( + self, + indent_level: Optional[int] = None, + eventual_encoding: _Encoding = DEFAULT_OUTPUT_ENCODING, + formatter: Union[Formatter, str] = "minimal", + iterator: Optional[Iterator[PageElement]] = None, + **kwargs: Any, + ) -> str: + """Returns a string representation of the parse tree + as a full HTML or XML document. + + :param indent_level: Each line of the rendering will be + indented this many levels. (The ``formatter`` decides what a + 'level' means, in terms of spaces or other characters + output.) This is used internally in recursive calls while + pretty-printing. + :param eventual_encoding: The encoding of the final document. + If this is None, the document will be a Unicode string. + :param formatter: Either a `Formatter` object, or a string naming one of + the standard formatters. + :param iterator: The iterator to use when navigating over the + parse tree. This is only used by `Tag.decode_contents` and + you probably won't need to use it. + """ + if self.is_xml: + # Print the XML declaration + encoding_part = "" + declared_encoding: Optional[str] = eventual_encoding + if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS: + # This is a special Python encoding; it can't actually + # go into an XML document because it means nothing + # outside of Python. + declared_encoding = None + if declared_encoding is not None: + encoding_part = ' encoding="%s"' % declared_encoding + prefix = '\n' % encoding_part + else: + prefix = "" + + # Prior to 4.13.0, the first argument to this method was a + # bool called pretty_print, which gave the method a different + # signature from its superclass implementation, Tag.decode. + # + # The signatures of the two methods now match, but just in + # case someone is still passing a boolean in as the first + # argument to this method (or a keyword argument with the old + # name), we can handle it and put out a DeprecationWarning. + warning: Optional[str] = None + pretty_print: Optional[bool] = None + if isinstance(indent_level, bool): + if indent_level is True: + indent_level = 0 + elif indent_level is False: + indent_level = None + warning = f"As of 4.13.0, the first argument to BeautifulSoup.decode has been changed from bool to int, to match Tag.decode. Pass in a value of {indent_level} instead." + else: + pretty_print = kwargs.pop("pretty_print", None) + assert not kwargs + if pretty_print is not None: + if pretty_print is True: + indent_level = 0 + elif pretty_print is False: + indent_level = None + warning = f"As of 4.13.0, the pretty_print argument to BeautifulSoup.decode has been removed, to match Tag.decode. Pass in a value of indent_level={indent_level} instead." + + if warning: + warnings.warn(warning, DeprecationWarning, stacklevel=2) + elif indent_level is False or pretty_print is False: + indent_level = None + return prefix + super(BeautifulSoup, self).decode( + indent_level, eventual_encoding, formatter, iterator + ) + + +# Aliases to make it easier to get started quickly, e.g. 'from bs4 import _soup' +_s = BeautifulSoup +_soup = BeautifulSoup + + +class BeautifulStoneSoup(BeautifulSoup): + """Deprecated interface to an XML parser.""" + + def __init__(self, *args: Any, **kwargs: Any): + kwargs["features"] = "xml" + warnings.warn( + "The BeautifulStoneSoup class was deprecated in version 4.0.0. Instead of using " + 'it, pass features="xml" into the BeautifulSoup constructor.', + DeprecationWarning, + stacklevel=2, + ) + super(BeautifulStoneSoup, self).__init__(*args, **kwargs) + + +# If this file is run as a script, act as an HTML pretty-printer. +if __name__ == "__main__": + import sys + + soup = BeautifulSoup(sys.stdin) + print((soup.prettify())) diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abe715b50c5dfb96a8b6fd17549b5b12fbbcddfc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/_deprecation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/_deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee07f8843e7cd99bf3812a9ee663493baa057467 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/_deprecation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/_typing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c45d648dd80f66e0448060f7f9f91cf970fef00b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/_typing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/_warnings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/_warnings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53b776fee808d4de1ed8fbffbdb19b332e7825c2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/_warnings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/css.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/css.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91de9fe583e45d25716d938a58514d9bed471adf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/css.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/dammit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/dammit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bc8ae413bef981dcbde0289922f466be081e997 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/dammit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/element.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/element.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecfd410478852b6a043e8e76d02f0e3979e235e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4/__pycache__/element.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa09f8d787e1e2ebd522f657964ddfe353e4ecc2ac67423d8b05354bac7dea21 +size 119947 diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1e5237d355a3384a83ed9dd939a80c73b24e28 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/filter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..623986205b73f27e179a8aee0dff5fde6db90891 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/filter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/__pycache__/formatter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/bs4/__pycache__/formatter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8270234c3bc972f66f3bbed947019db164212322 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/bs4/__pycache__/formatter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/bs4/_deprecation.py b/.venv/lib/python3.12/site-packages/bs4/_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7b5685b8ab8b40597e1f006e721ae2cc12c4b03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4/_deprecation.py @@ -0,0 +1,80 @@ +"""Helper functions for deprecation. + +This interface is itself unstable and may change without warning. Do +not use these functions yourself, even as a joke. The underscores are +there for a reason. No support will be given. + +In particular, most of this will go away without warning once +Beautiful Soup drops support for Python 3.11, since Python 3.12 +defines a `@typing.deprecated() +decorator. `_ +""" + +import functools +import warnings + +from typing import ( + Any, + Callable, +) + + +def _deprecated_alias(old_name: str, new_name: str, version: str): + """Alias one attribute name to another for backward compatibility + + :meta private: + """ + + @property # type:ignore + def alias(self) -> Any: + ":meta private:" + warnings.warn( + f"Access to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(self, new_name) + + @alias.setter + def alias(self, value: str) -> None: + ":meta private:" + warnings.warn( + f"Write to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return setattr(self, new_name, value) + + return alias + + +def _deprecated_function_alias( + old_name: str, new_name: str, version: str +) -> Callable[[Any], Any]: + def alias(self, *args: Any, **kwargs: Any) -> Any: + ":meta private:" + warnings.warn( + f"Call to deprecated method {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(self, new_name)(*args, **kwargs) + + return alias + + +def _deprecated(replaced_by: str, version: str) -> Callable: + def deprecate(func: Callable) -> Callable: + @functools.wraps(func) + def with_warning(*args: Any, **kwargs: Any) -> Any: + ":meta private:" + warnings.warn( + f"Call to deprecated method {func.__name__}. (Replaced by {replaced_by}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return with_warning + + return deprecate diff --git a/.venv/lib/python3.12/site-packages/bs4/_typing.py b/.venv/lib/python3.12/site-packages/bs4/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab69df14360e9b344a1e165bab77eebffdb8eb6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4/_typing.py @@ -0,0 +1,205 @@ +# Custom type aliases used throughout Beautiful Soup to improve readability. + +# Notes on improvements to the type system in newer versions of Python +# that can be used once Beautiful Soup drops support for older +# versions: +# +# * ClassVar can be put on class variables now. +# * In 3.10, x|y is an accepted shorthand for Union[x,y]. +# * In 3.10, TypeAlias gains capabilities that can be used to +# improve the tree matching types (I don't remember what, exactly). +# * In 3.9 it's possible to specialize the re.Match type, +# e.g. re.Match[str]. In 3.8 there's a typing.re namespace for this, +# but it's removed in 3.12, so to support the widest possible set of +# versions I'm not using it. + +from typing_extensions import ( + runtime_checkable, + Protocol, + TypeAlias, +) +from typing import ( + Any, + Callable, + Dict, + IO, + Iterable, + Mapping, + Optional, + Pattern, + TYPE_CHECKING, + Union, +) + +if TYPE_CHECKING: + from bs4.element import ( + AttributeValueList, + NamespacedAttribute, + NavigableString, + PageElement, + ResultSet, + Tag, + ) + + +@runtime_checkable +class _RegularExpressionProtocol(Protocol): + """A protocol object which can accept either Python's built-in + `re.Pattern` objects, or the similar ``Regex`` objects defined by the + third-party ``regex`` package. + """ + + def search( + self, string: str, pos: int = ..., endpos: int = ... + ) -> Optional[Any]: ... + + @property + def pattern(self) -> str: ... + + +# Aliases for markup in various stages of processing. +# +#: The rawest form of markup: either a string, bytestring, or an open filehandle. +_IncomingMarkup: TypeAlias = Union[str, bytes, IO[str], IO[bytes]] + +#: Markup that is in memory but has (potentially) yet to be converted +#: to Unicode. +_RawMarkup: TypeAlias = Union[str, bytes] + +# Aliases for character encodings +# + +#: A data encoding. +_Encoding: TypeAlias = str + +#: One or more data encodings. +_Encodings: TypeAlias = Iterable[_Encoding] + +# Aliases for XML namespaces +# + +#: The prefix for an XML namespace. +_NamespacePrefix: TypeAlias = str + +#: The URL of an XML namespace +_NamespaceURL: TypeAlias = str + +#: A mapping of prefixes to namespace URLs. +_NamespaceMapping: TypeAlias = Dict[_NamespacePrefix, _NamespaceURL] + +#: A mapping of namespace URLs to prefixes +_InvertedNamespaceMapping: TypeAlias = Dict[_NamespaceURL, _NamespacePrefix] + +# Aliases for the attribute values associated with HTML/XML tags. +# + +#: The value associated with an HTML or XML attribute. This is the +#: relatively unprocessed value Beautiful Soup expects to come from a +#: `TreeBuilder`. +_RawAttributeValue: TypeAlias = str + +#: A dictionary of names to `_RawAttributeValue` objects. This is how +#: Beautiful Soup expects a `TreeBuilder` to represent a tag's +#: attribute values. +_RawAttributeValues: TypeAlias = ( + "Mapping[Union[str, NamespacedAttribute], _RawAttributeValue]" +) + +#: An attribute value in its final form, as stored in the +# `Tag` class, after it has been processed and (in some cases) +# split into a list of strings. +_AttributeValue: TypeAlias = Union[str, "AttributeValueList"] + +#: A dictionary of names to :py:data:`_AttributeValue` objects. This is what +#: a tag's attributes look like after processing. +_AttributeValues: TypeAlias = Dict[str, _AttributeValue] + +#: The methods that deal with turning :py:data:`_RawAttributeValue` into +#: :py:data:`_AttributeValue` may be called several times, even after the values +#: are already processed (e.g. when cloning a tag), so they need to +#: be able to acommodate both possibilities. +_RawOrProcessedAttributeValues: TypeAlias = Union[_RawAttributeValues, _AttributeValues] + +#: A number of tree manipulation methods can take either a `PageElement` or a +#: normal Python string (which will be converted to a `NavigableString`). +_InsertableElement: TypeAlias = Union["PageElement", str] + +# Aliases to represent the many possibilities for matching bits of a +# parse tree. +# +# This is very complicated because we're applying a formal type system +# to some very DWIM code. The types we end up with will be the types +# of the arguments to the SoupStrainer constructor and (more +# familiarly to Beautiful Soup users) the find* methods. + +#: A function that takes a PageElement and returns a yes-or-no answer. +_PageElementMatchFunction: TypeAlias = Callable[["PageElement"], bool] + +#: A function that takes the raw parsed ingredients of a markup tag +#: and returns a yes-or-no answer. +# Not necessary at the moment. +# _AllowTagCreationFunction:TypeAlias = Callable[[Optional[str], str, Optional[_RawAttributeValues]], bool] + +#: A function that takes the raw parsed ingredients of a markup string node +#: and returns a yes-or-no answer. +# Not necessary at the moment. +# _AllowStringCreationFunction:TypeAlias = Callable[[Optional[str]], bool] + +#: A function that takes a `Tag` and returns a yes-or-no answer. +#: A `TagNameMatchRule` expects this kind of function, if you're +#: going to pass it a function. +_TagMatchFunction: TypeAlias = Callable[["Tag"], bool] + +#: A function that takes a string (or None) and returns a yes-or-no +#: answer. An `AttributeValueMatchRule` expects this kind of function, if +#: you're going to pass it a function. +_NullableStringMatchFunction: TypeAlias = Callable[[Optional[str]], bool] + +#: A function that takes a string and returns a yes-or-no answer. A +# `StringMatchRule` expects this kind of function, if you're going to +# pass it a function. +_StringMatchFunction: TypeAlias = Callable[[str], bool] + +#: Either a tag name, an attribute value or a string can be matched +#: against a string, bytestring, regular expression, or a boolean. +_BaseStrainable: TypeAlias = Union[str, bytes, Pattern[str], bool] + +#: A tag can be matched either with the `_BaseStrainable` options, or +#: using a function that takes the `Tag` as its sole argument. +_BaseStrainableElement: TypeAlias = Union[_BaseStrainable, _TagMatchFunction] + +#: A tag's attribute value can be matched either with the +#: `_BaseStrainable` options, or using a function that takes that +#: value as its sole argument. +_BaseStrainableAttribute: TypeAlias = Union[_BaseStrainable, _NullableStringMatchFunction] + +#: A tag can be matched using either a single criterion or a list of +#: criteria. +_StrainableElement: TypeAlias = Union[ + _BaseStrainableElement, Iterable[_BaseStrainableElement] +] + +#: An attribute value can be matched using either a single criterion +#: or a list of criteria. +_StrainableAttribute: TypeAlias = Union[ + _BaseStrainableAttribute, Iterable[_BaseStrainableAttribute] +] + +#: An string can be matched using the same techniques as +#: an attribute value. +_StrainableString: TypeAlias = _StrainableAttribute + +#: A dictionary may be used to match against multiple attribute vlaues at once. +_StrainableAttributes: TypeAlias = Dict[str, _StrainableAttribute] + +#: Many Beautiful soup methods return a PageElement or an ResultSet of +#: PageElements. A PageElement is either a Tag or a NavigableString. +#: These convenience aliases make it easier for IDE users to see which methods +#: are available on the objects they're dealing with. +_OneElement: TypeAlias = Union["PageElement", "Tag", "NavigableString"] +_AtMostOneElement: TypeAlias = Optional[_OneElement] +_AtMostOneTag: TypeAlias = Optional["Tag"] +_AtMostOneNavigableString: TypeAlias = Optional["NavigableString"] +_QueryResults: TypeAlias = "ResultSet[_OneElement]" +_SomeTags: TypeAlias = "ResultSet[Tag]" +_SomeNavigableStrings: TypeAlias = "ResultSet[NavigableString]" diff --git a/.venv/lib/python3.12/site-packages/bs4/_warnings.py b/.venv/lib/python3.12/site-packages/bs4/_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..43094730458541fd387595dfd61c483f477b95f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4/_warnings.py @@ -0,0 +1,98 @@ +"""Define some custom warnings.""" + + +class GuessedAtParserWarning(UserWarning): + """The warning issued when BeautifulSoup has to guess what parser to + use -- probably because no parser was specified in the constructor. + """ + + MESSAGE: str = """No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system ("%(parser)s"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. + +The code that caused this warning is on line %(line_number)s of the file %(filename)s. To get rid of this warning, pass the additional argument 'features="%(parser)s"' to the BeautifulSoup constructor. +""" + + +class UnusualUsageWarning(UserWarning): + """A superclass for warnings issued when Beautiful Soup sees + something that is typically the result of a mistake in the calling + code, but might be intentional on the part of the user. If it is + in fact intentional, you can filter the individual warning class + to get rid of the warning. If you don't like Beautiful Soup + second-guessing what you are doing, you can filter the + UnusualUsageWarningclass itself and get rid of these entirely. + """ + + +class MarkupResemblesLocatorWarning(UnusualUsageWarning): + """The warning issued when BeautifulSoup is given 'markup' that + actually looks like a resource locator -- a URL or a path to a file + on disk. + """ + + #: :meta private: + GENERIC_MESSAGE: str = """ + +However, if you want to parse some data that happens to look like a %(what)s, then nothing has gone wrong: you are using Beautiful Soup correctly, and this warning is spurious and can be filtered. To make this warning go away, run this code before calling the BeautifulSoup constructor: + + from bs4 import MarkupResemblesLocatorWarning + import warnings + + warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning) + """ + + URL_MESSAGE: str = ( + """The input passed in on this line looks more like a URL than HTML or XML. + +If you meant to use Beautiful Soup to parse the web page found at a certain URL, then something has gone wrong. You should use an Python package like 'requests' to fetch the content behind the URL. Once you have the content as a string, you can feed that string into Beautiful Soup.""" + + GENERIC_MESSAGE + ) + + FILENAME_MESSAGE: str = ( + """The input passed in on this line looks more like a filename than HTML or XML. + +If you meant to use Beautiful Soup to parse the contents of a file on disk, then something has gone wrong. You should open the file first, using code like this: + + filehandle = open(your filename) + +You can then feed the open filehandle into Beautiful Soup instead of using the filename.""" + + GENERIC_MESSAGE + ) + + +class AttributeResemblesVariableWarning(UnusualUsageWarning, SyntaxWarning): + """The warning issued when Beautiful Soup suspects a provided + attribute name may actually be the misspelled name of a Beautiful + Soup variable. Generally speaking, this is only used in cases like + "_class" where it's very unlikely the user would be referencing an + XML attribute with that name. + """ + + MESSAGE: str = """%(original)r is an unusual attribute name and is a common misspelling for %(autocorrect)r. + +If you meant %(autocorrect)r, change your code to use it, and this warning will go away. + +If you really did mean to check the %(original)r attribute, this warning is spurious and can be filtered. To make it go away, run this code before creating your BeautifulSoup object: + + from bs4 import AttributeResemblesVariableWarning + import warnings + + warnings.filterwarnings("ignore", category=AttributeResemblesVariableWarning) +""" + + +class XMLParsedAsHTMLWarning(UnusualUsageWarning): + """The warning issued when an HTML parser is used to parse + XML that is not (as far as we can tell) XHTML. + """ + + MESSAGE: str = """It looks like you're using an HTML parser to parse an XML document. + +Assuming this really is an XML document, what you're doing might work, but you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the Python package 'lxml' installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor. + +If you want or need to use an HTML parser on this document, you can make this warning go away by filtering it. To do that, run this code before calling the BeautifulSoup constructor: + + from bs4 import XMLParsedAsHTMLWarning + import warnings + + warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning) +""" diff --git a/.venv/lib/python3.12/site-packages/bs4/builder/__init__.py b/.venv/lib/python3.12/site-packages/bs4/builder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4aae4d330789cf01057918d25eea372f739d6e56 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/bs4/builder/__init__.py @@ -0,0 +1,848 @@ +from __future__ import annotations + +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +from collections import defaultdict +import re +from types import ModuleType +from typing import ( + Any, + cast, + Dict, + Iterable, + List, + Optional, + Pattern, + Set, + Tuple, + Type, + TYPE_CHECKING, +) +import warnings +import sys +from bs4.element import ( + AttributeDict, + AttributeValueList, + CharsetMetaAttributeValue, + ContentMetaAttributeValue, + RubyParenthesisString, + RubyTextString, + Stylesheet, + Script, + TemplateString, + nonwhitespace_re, +) + +# Exceptions were moved to their own module in 4.13. Import here for +# backwards compatibility. +from bs4.exceptions import ParserRejectedMarkup + +from bs4._typing import ( + _AttributeValues, + _RawAttributeValue, +) + +from bs4._warnings import XMLParsedAsHTMLWarning + +if TYPE_CHECKING: + from bs4 import BeautifulSoup + from bs4.element import ( + NavigableString, + Tag, + ) + from bs4._typing import ( + _AttributeValue, + _Encoding, + _Encodings, + _RawOrProcessedAttributeValues, + _RawMarkup, + ) + +__all__ = [ + "HTMLTreeBuilder", + "SAXTreeBuilder", + "TreeBuilder", + "TreeBuilderRegistry", +] + +# Some useful features for a TreeBuilder to have. +FAST = "fast" +PERMISSIVE = "permissive" +STRICT = "strict" +XML = "xml" +HTML = "html" +HTML_5 = "html5" + +__all__ = [ + "TreeBuilderRegistry", + "TreeBuilder", + "HTMLTreeBuilder", + "DetectsXMLParsedAsHTML", + + "ParserRejectedMarkup", # backwards compatibility only as of 4.13.0 +] + +class TreeBuilderRegistry(object): + """A way of looking up TreeBuilder subclasses by their name or by desired + features. + """ + + builders_for_feature: Dict[str, List[Type[TreeBuilder]]] + builders: List[Type[TreeBuilder]] + + def __init__(self) -> None: + self.builders_for_feature = defaultdict(list) + self.builders = [] + + def register(self, treebuilder_class: type[TreeBuilder]) -> None: + """Register a treebuilder based on its advertised features. + + :param treebuilder_class: A subclass of `TreeBuilder`. its + `TreeBuilder.features` attribute should list its features. + """ + for feature in treebuilder_class.features: + self.builders_for_feature[feature].insert(0, treebuilder_class) + self.builders.insert(0, treebuilder_class) + + def lookup(self, *features: str) -> Optional[Type[TreeBuilder]]: + """Look up a TreeBuilder subclass with the desired features. + + :param features: A list of features to look for. If none are + provided, the most recently registered TreeBuilder subclass + will be used. + :return: A TreeBuilder subclass, or None if there's no + registered subclass with all the requested features. + """ + if len(self.builders) == 0: + # There are no builders at all. + return None + + if len(features) == 0: + # They didn't ask for any features. Give them the most + # recently registered builder. + return self.builders[0] + + # Go down the list of features in order, and eliminate any builders + # that don't match every feature. + feature_list = list(features) + feature_list.reverse() + candidates = None + candidate_set = None + while len(feature_list) > 0: + feature = feature_list.pop() + we_have_the_feature = self.builders_for_feature.get(feature, []) + if len(we_have_the_feature) > 0: + if candidates is None: + candidates = we_have_the_feature + candidate_set = set(candidates) + elif candidate_set is not None: + # Eliminate any candidates that don't have this feature. + candidate_set = candidate_set.intersection(set(we_have_the_feature)) + + # The only valid candidates are the ones in candidate_set. + # Go through the original list of candidates and pick the first one + # that's in candidate_set. + if candidate_set is None or candidates is None: + return None + for candidate in candidates: + if candidate in candidate_set: + return candidate + return None + + +#: The `BeautifulSoup` constructor will take a list of features +#: and use it to look up `TreeBuilder` classes in this registry. +builder_registry: TreeBuilderRegistry = TreeBuilderRegistry() + + +class TreeBuilder(object): + """Turn a textual document into a Beautiful Soup object tree. + + This is an abstract superclass which smooths out the behavior of + different parser libraries into a single, unified interface. + + :param multi_valued_attributes: If this is set to None, the + TreeBuilder will not turn any values for attributes like + 'class' into lists. Setting this to a dictionary will + customize this behavior; look at :py:attr:`bs4.builder.HTMLTreeBuilder.DEFAULT_CDATA_LIST_ATTRIBUTES` + for an example. + + Internally, these are called "CDATA list attributes", but that + probably doesn't make sense to an end-user, so the argument name + is ``multi_valued_attributes``. + + :param preserve_whitespace_tags: A set of tags to treat + the way
 tags are treated in HTML. Tags in this set
+     are immune from pretty-printing; their contents will always be
+     output as-is.
+
+    :param string_containers: A dictionary mapping tag names to
+     the classes that should be instantiated to contain the textual
+     contents of those tags. The default is to use NavigableString
+     for every tag, no matter what the name. You can override the
+     default by changing :py:attr:`DEFAULT_STRING_CONTAINERS`.
+
+    :param store_line_numbers: If the parser keeps track of the line
+     numbers and positions of the original markup, that information
+     will, by default, be stored in each corresponding
+     :py:class:`bs4.element.Tag` object. You can turn this off by
+     passing store_line_numbers=False; then Tag.sourcepos and
+     Tag.sourceline will always be None. If the parser you're using
+     doesn't keep track of this information, then store_line_numbers
+     is irrelevant.
+
+    :param attribute_dict_class: The value of a multi-valued attribute
+      (such as HTML's 'class') willl be stored in an instance of this
+      class.  The default is Beautiful Soup's built-in
+      `AttributeValueList`, which is a normal Python list, and you
+      will probably never need to change it.
+    """
+
+    USE_DEFAULT: Any = object()  #: :meta private:
+
+    def __init__(
+        self,
+        multi_valued_attributes: Dict[str, Set[str]] = USE_DEFAULT,
+        preserve_whitespace_tags: Set[str] = USE_DEFAULT,
+        store_line_numbers: bool = USE_DEFAULT,
+        string_containers: Dict[str, Type[NavigableString]] = USE_DEFAULT,
+        empty_element_tags: Set[str] = USE_DEFAULT,
+        attribute_dict_class: Type[AttributeDict] = AttributeDict,
+        attribute_value_list_class: Type[AttributeValueList] = AttributeValueList,
+    ):
+        self.soup = None
+        if multi_valued_attributes is self.USE_DEFAULT:
+            multi_valued_attributes = self.DEFAULT_CDATA_LIST_ATTRIBUTES
+        self.cdata_list_attributes = multi_valued_attributes
+        if preserve_whitespace_tags is self.USE_DEFAULT:
+            preserve_whitespace_tags = self.DEFAULT_PRESERVE_WHITESPACE_TAGS
+        self.preserve_whitespace_tags = preserve_whitespace_tags
+        if empty_element_tags is self.USE_DEFAULT:
+            self.empty_element_tags = self.DEFAULT_EMPTY_ELEMENT_TAGS
+        else:
+            self.empty_element_tags = empty_element_tags
+        # TODO: store_line_numbers is probably irrelevant now that
+        # the behavior of sourceline and sourcepos has been made consistent
+        # everywhere.
+        if store_line_numbers == self.USE_DEFAULT:
+            store_line_numbers = self.TRACKS_LINE_NUMBERS
+        self.store_line_numbers = store_line_numbers
+        if string_containers == self.USE_DEFAULT:
+            string_containers = self.DEFAULT_STRING_CONTAINERS
+        self.string_containers = string_containers
+        self.attribute_dict_class = attribute_dict_class
+        self.attribute_value_list_class = attribute_value_list_class
+
+    NAME: str = "[Unknown tree builder]"
+    ALTERNATE_NAMES: Iterable[str] = []
+    features: Iterable[str] = []
+
+    is_xml: bool = False
+    picklable: bool = False
+
+    soup: Optional[BeautifulSoup]  #: :meta private:
+
+    #: A tag will be considered an empty-element
+    #: tag when and only when it has no contents.
+    empty_element_tags: Optional[Set[str]] = None  #: :meta private:
+    cdata_list_attributes: Dict[str, Set[str]]  #: :meta private:
+    preserve_whitespace_tags: Set[str]  #: :meta private:
+    string_containers: Dict[str, Type[NavigableString]]  #: :meta private:
+    tracks_line_numbers: bool  #: :meta private:
+
+    #: A value for these tag/attribute combinations is a space- or
+    #: comma-separated list of CDATA, rather than a single CDATA.
+    DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = defaultdict(set)
+
+    #: Whitespace should be preserved inside these tags.
+    DEFAULT_PRESERVE_WHITESPACE_TAGS: Set[str] = set()
+
+    #: The textual contents of tags with these names should be
+    #: instantiated with some class other than `bs4.element.NavigableString`.
+    DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = {} # type:ignore
+
+    #: By default, tags are treated as empty-element tags if they have
+    #: no contents--that is, using XML rules. HTMLTreeBuilder
+    #: defines a different set of DEFAULT_EMPTY_ELEMENT_TAGS based on the
+    #: HTML 4 and HTML5 standards.
+    DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = None
+
+    #: Most parsers don't keep track of line numbers.
+    TRACKS_LINE_NUMBERS: bool = False
+
+    def initialize_soup(self, soup: BeautifulSoup) -> None:
+        """The BeautifulSoup object has been initialized and is now
+        being associated with the TreeBuilder.
+
+        :param soup: A BeautifulSoup object.
+        """
+        self.soup = soup
+
+    def reset(self) -> None:
+        """Do any work necessary to reset the underlying parser
+        for a new document.
+
+        By default, this does nothing.
+        """
+        pass
+
+    def can_be_empty_element(self, tag_name: str) -> bool:
+        """Might a tag with this name be an empty-element tag?
+
+        The final markup may or may not actually present this tag as
+        self-closing.
+
+        For instance: an HTMLBuilder does not consider a 

tag to be + an empty-element tag (it's not in + HTMLBuilder.empty_element_tags). This means an empty

tag + will be presented as "

", not "

" or "

". + + The default implementation has no opinion about which tags are + empty-element tags, so a tag will be presented as an + empty-element tag if and only if it has no children. + "" will become "", and "bar" will + be left alone. + + :param tag_name: The name of a markup tag. + """ + if self.empty_element_tags is None: + return True + return tag_name in self.empty_element_tags + + def feed(self, markup: _RawMarkup) -> None: + """Run incoming markup through some parsing process.""" + raise NotImplementedError() + + def prepare_markup( + self, + markup: _RawMarkup, + user_specified_encoding: Optional[_Encoding] = None, + document_declared_encoding: Optional[_Encoding] = None, + exclude_encodings: Optional[_Encodings] = None, + ) -> Iterable[Tuple[_RawMarkup, Optional[_Encoding], Optional[_Encoding], bool]]: + """Run any preliminary steps necessary to make incoming markup + acceptable to the parser. + + :param markup: The markup that's about to be parsed. + :param user_specified_encoding: The user asked to try this encoding + to convert the markup into a Unicode string. + :param document_declared_encoding: The markup itself claims to be + in this encoding. NOTE: This argument is not used by the + calling code and can probably be removed. + :param exclude_encodings: The user asked *not* to try any of + these encodings. + + :yield: A series of 4-tuples: (markup, encoding, declared encoding, + has undergone character replacement) + + Each 4-tuple represents a strategy that the parser can try + to convert the document to Unicode and parse it. Each + strategy will be tried in turn. + + By default, the only strategy is to parse the markup + as-is. See `LXMLTreeBuilderForXML` and + `HTMLParserTreeBuilder` for implementations that take into + account the quirks of particular parsers. + + :meta private: + + """ + yield markup, None, None, False + + def test_fragment_to_document(self, fragment: str) -> str: + """Wrap an HTML fragment to make it look like a document. + + Different parsers do this differently. For instance, lxml + introduces an empty tag, and html5lib + doesn't. Abstracting this away lets us write simple tests + which run HTML fragments through the parser and compare the + results against other HTML fragments. + + This method should not be used outside of unit tests. + + :param fragment: A fragment of HTML. + :return: A full HTML document. + :meta private: + """ + return fragment + + def set_up_substitutions(self, tag: Tag) -> bool: + """Set up any substitutions that will need to be performed on + a `Tag` when it's output as a string. + + By default, this does nothing. See `HTMLTreeBuilder` for a + case where this is used. + + :return: Whether or not a substitution was performed. + :meta private: + """ + return False + + def _replace_cdata_list_attribute_values( + self, tag_name: str, attrs: _RawOrProcessedAttributeValues + ) -> _AttributeValues: + """When an attribute value is associated with a tag that can + have multiple values for that attribute, convert the string + value to a list of strings. + + Basically, replaces class="foo bar" with class=["foo", "bar"] + + NOTE: This method modifies its input in place. + + :param tag_name: The name of a tag. + :param attrs: A dictionary containing the tag's attributes. + Any appropriate attribute values will be modified in place. + :return: The modified dictionary that was originally passed in. + """ + + # First, cast the attrs dict to _AttributeValues. This might + # not be accurate yet, but it will be by the time this method + # returns. + modified_attrs = cast(_AttributeValues, attrs) + if not modified_attrs or not self.cdata_list_attributes: + # Nothing to do. + return modified_attrs + + # There is at least a possibility that we need to modify one of + # the attribute values. + universal: Set[str] = self.cdata_list_attributes.get("*", set()) + tag_specific = self.cdata_list_attributes.get(tag_name.lower(), None) + for attr in list(modified_attrs.keys()): + modified_value: _AttributeValue + if attr in universal or (tag_specific and attr in tag_specific): + # We have a "class"-type attribute whose string + # value is a whitespace-separated list of + # values. Split it into a list. + original_value: _AttributeValue = modified_attrs[attr] + if isinstance(original_value, _RawAttributeValue): + # This is a _RawAttributeValue (a string) that + # needs to be split and converted to a + # AttributeValueList so it can be an + # _AttributeValue. + modified_value = self.attribute_value_list_class( + nonwhitespace_re.findall(original_value) + ) + else: + # html5lib calls setAttributes twice for the + # same tag when rearranging the parse tree. On + # the second call the attribute value here is + # already a list. This can also happen when a + # Tag object is cloned. If this happens, leave + # the value alone rather than trying to split + # it again. + modified_value = original_value + modified_attrs[attr] = modified_value + return modified_attrs + + +class SAXTreeBuilder(TreeBuilder): + """A Beautiful Soup treebuilder that listens for SAX events. + + This is not currently used for anything, and it will be removed + soon. It was a good idea, but it wasn't properly integrated into the + rest of Beautiful Soup, so there have been long stretches where it + hasn't worked properly. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + warnings.warn( + "The SAXTreeBuilder class was deprecated in 4.13.0 and will be removed soon thereafter. It is completely untested and probably doesn't work; do not use it.", + DeprecationWarning, + stacklevel=2, + ) + super(SAXTreeBuilder, self).__init__(*args, **kwargs) + + def feed(self, markup: _RawMarkup) -> None: + raise NotImplementedError() + + def close(self) -> None: + pass + + def startElement(self, name: str, attrs: Dict[str, str]) -> None: + attrs = AttributeDict((key[1], value) for key, value in list(attrs.items())) + # print("Start %s, %r" % (name, attrs)) + assert self.soup is not None + self.soup.handle_starttag(name, None, None, attrs) + + def endElement(self, name: str) -> None: + # print("End %s" % name) + assert self.soup is not None + self.soup.handle_endtag(name) + + def startElementNS( + self, nsTuple: Tuple[str, str], nodeName: str, attrs: Dict[str, str] + ) -> None: + # Throw away (ns, nodeName) for now. + self.startElement(nodeName, attrs) + + def endElementNS(self, nsTuple: Tuple[str, str], nodeName: str) -> None: + # Throw away (ns, nodeName) for now. + self.endElement(nodeName) + # handler.endElementNS((ns, node.nodeName), node.nodeName) + + def startPrefixMapping(self, prefix: str, nodeValue: str) -> None: + # Ignore the prefix for now. + pass + + def endPrefixMapping(self, prefix: str) -> None: + # Ignore the prefix for now. + # handler.endPrefixMapping(prefix) + pass + + def characters(self, content: str) -> None: + assert self.soup is not None + self.soup.handle_data(content) + + def startDocument(self) -> None: + pass + + def endDocument(self) -> None: + pass + + +class HTMLTreeBuilder(TreeBuilder): + """This TreeBuilder knows facts about HTML, such as which tags are treated + specially by the HTML standard. + """ + + #: Some HTML tags are defined as having no contents. Beautiful Soup + #: treats these specially. + DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = set( + [ + # These are from HTML5. + "area", + "base", + "br", + "col", + "embed", + "hr", + "img", + "input", + "keygen", + "link", + "menuitem", + "meta", + "param", + "source", + "track", + "wbr", + # These are from earlier versions of HTML and are removed in HTML5. + "basefont", + "bgsound", + "command", + "frame", + "image", + "isindex", + "nextid", + "spacer", + ] + ) + + #: The HTML standard defines these tags as block-level elements. Beautiful + #: Soup does not treat these elements differently from other elements, + #: but it may do so eventually, and this information is available if + #: you need to use it. + DEFAULT_BLOCK_ELEMENTS: Set[str] = set( + [ + "address", + "article", + "aside", + "blockquote", + "canvas", + "dd", + "div", + "dl", + "dt", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "header", + "hr", + "li", + "main", + "nav", + "noscript", + "ol", + "output", + "p", + "pre", + "section", + "table", + "tfoot", + "ul", + "video", + ] + ) + + #: These HTML tags need special treatment so they can be + #: represented by a string class other than `bs4.element.NavigableString`. + #: + #: For some of these tags, it's because the HTML standard defines + #: an unusual content model for them. I made this list by going + #: through the HTML spec + #: (https://html.spec.whatwg.org/#metadata-content) and looking for + #: "metadata content" elements that can contain strings. + #: + #: The Ruby tags ( and ) are here despite being normal + #: "phrasing content" tags, because the content they contain is + #: qualitatively different from other text in the document, and it + #: can be useful to be able to distinguish it. + #: + #: TODO: Arguably