diff --git a/.gitattributes b/.gitattributes index 56fdd96b369521a3b4d9b4c9aff46e841e43718f..f8799fbca123896b60f10ce156174d110cb4362a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -73,3 +73,39 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/_polars_runtime_32/_polars_runtime.abi3.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312-pytest-9.1.1.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/_core.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/codeccontext.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/fifo.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/format.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/frame.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/layout.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/plane.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/resampler.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/audio/stream.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/bitstream.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/buffer.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/codec/codec.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/codec/context.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/codec/hwaccel.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/container/core.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/container/input.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/container/output.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/container/pyio.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/container/streams.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/device.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/dictionary.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/error.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/filter/context.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/filter/filter.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/filter/graph.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/filter/link.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/filter/loudnorm.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/format.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/frame.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/index.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/logging.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/opaque.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/av/packet.abi3.so 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 diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..13734ecac7501953843b99eef680987bad705350 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/METADATA @@ -0,0 +1,108 @@ +Metadata-Version: 2.4 +Name: anyio +Version: 4.15.1 +Summary: High-level concurrency and networking framework on top of asyncio or Trio +Author-email: Alex Grönholm +License-Expression: MIT +Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/ +Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html +Project-URL: Source code, https://github.com/agronholm/anyio +Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Framework :: AnyIO +Classifier: Typing :: Typed +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +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: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11" +Requires-Dist: idna>=2.8 +Requires-Dist: typing_extensions>=4.16.0; python_version < "3.15" +Provides-Extra: trio +Requires-Dist: trio>=0.32.0; extra == "trio" +Dynamic: license-file + +.. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg + :target: https://github.com/agronholm/anyio/actions/workflows/test.yml + :alt: Build Status +.. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master + :target: https://coveralls.io/github/agronholm/anyio?branch=master + :alt: Code Coverage +.. image:: https://readthedocs.org/projects/anyio/badge/?version=latest + :target: https://anyio.readthedocs.io/en/latest/?badge=latest + :alt: Documentation +.. image:: https://badges.gitter.im/gitterHQ/gitter.svg + :target: https://gitter.im/python-trio/AnyIO + :alt: Gitter chat +.. image:: https://tidelift.com/badges/package/pypi/anyio + :target: https://tidelift.com/subscription/pkg/pypi-anyio + :alt: Tidelift + +AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or +Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony +with the native SC of Trio itself. + +Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or +Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full +refactoring necessary. It will blend in with the native libraries of your chosen backend. + +To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it +`here `_. + +Documentation +------------- + +View full documentation at: https://anyio.readthedocs.io/ + +Features +-------- + +AnyIO offers the following functionality: + +* Task groups (nurseries_ in trio terminology) +* High-level networking (TCP, UDP and UNIX sockets) + + * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python + 3.8) + * async/await style UDP sockets (unlike asyncio where you still have to use Transports and + Protocols) + +* A versatile API for byte streams and object streams +* Inter-task synchronization and communication (locks, conditions, events, semaphores, object + streams and futures) +* Worker threads +* Subprocesses +* Subinterpreter support for code parallelization (on Python 3.13 and later) +* Asynchronous file I/O (using worker threads) +* Signal handling +* Asynchronous versions of the functools_ and itertools_ modules + +AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures. +It even works with the popular Hypothesis_ library. + +.. _asyncio: https://docs.python.org/3/library/asyncio.html +.. _Trio: https://github.com/python-trio/trio +.. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency +.. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning +.. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs +.. _pytest: https://docs.pytest.org/en/latest/ +.. _functools: https://docs.python.org/3/library/functools.html +.. _itertools: https://docs.python.org/3/library/itertools.html +.. _Hypothesis: https://hypothesis.works/ + +Security contact information +---------------------------- + +To report a security vulnerability, please use the `Tidelift security contact`_. +Tidelift will coordinate the fix and disclosure. + +.. _Tidelift security contact: https://tidelift.com/security diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3946aab45aded3021e39684ed39f2568d09d3664 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/RECORD @@ -0,0 +1,100 @@ +anyio-4.15.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anyio-4.15.1.dist-info/METADATA,sha256=BDrstXGvcYnopsUo9djjJUXxss36r3YdUebVtn6jyoE,4733 +anyio-4.15.1.dist-info/RECORD,, +anyio-4.15.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91 +anyio-4.15.1.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39 +anyio-4.15.1.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081 +anyio-4.15.1.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6 +anyio/__init__.py,sha256=OfroYRjIUw_JFj0Zwh1JAaajMQg4VqtoAt0XoOHDRwE,7602 +anyio/__pycache__/__init__.cpython-312.pyc,, +anyio/__pycache__/_lazyimport.cpython-312.pyc,, +anyio/__pycache__/from_thread.cpython-312.pyc,, +anyio/__pycache__/functools.cpython-312.pyc,, +anyio/__pycache__/itertools.cpython-312.pyc,, +anyio/__pycache__/lowlevel.cpython-312.pyc,, +anyio/__pycache__/pytest_plugin.cpython-312.pyc,, +anyio/__pycache__/to_interpreter.cpython-312.pyc,, +anyio/__pycache__/to_process.cpython-312.pyc,, +anyio/__pycache__/to_thread.cpython-312.pyc,, +anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_backends/__pycache__/__init__.cpython-312.pyc,, +anyio/_backends/__pycache__/_asyncio.cpython-312.pyc,, +anyio/_backends/__pycache__/_trio.cpython-312.pyc,, +anyio/_backends/_asyncio.py,sha256=Vqy7O1ymmEpxTiPzehSuBCVTziGALNV-BbsIRaKXsg4,107767 +anyio/_backends/_trio.py,sha256=Gs8XzX0IeBvje8IEZtJmpNylKCUAChKv7I_YZi3wlmg,45715 +anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_core/__pycache__/__init__.cpython-312.pyc,, +anyio/_core/__pycache__/_asyncio_selector_thread.cpython-312.pyc,, +anyio/_core/__pycache__/_concurrency_utils.cpython-312.pyc,, +anyio/_core/__pycache__/_contextmanagers.cpython-312.pyc,, +anyio/_core/__pycache__/_eventloop.cpython-312.pyc,, +anyio/_core/__pycache__/_exceptions.cpython-312.pyc,, +anyio/_core/__pycache__/_fileio.cpython-312.pyc,, +anyio/_core/__pycache__/_futures.cpython-312.pyc,, +anyio/_core/__pycache__/_resources.cpython-312.pyc,, +anyio/_core/__pycache__/_signals.cpython-312.pyc,, +anyio/_core/__pycache__/_sockets.cpython-312.pyc,, +anyio/_core/__pycache__/_streams.cpython-312.pyc,, +anyio/_core/__pycache__/_subprocesses.cpython-312.pyc,, +anyio/_core/__pycache__/_synchronization.cpython-312.pyc,, +anyio/_core/__pycache__/_tasks.cpython-312.pyc,, +anyio/_core/__pycache__/_tempfile.cpython-312.pyc,, +anyio/_core/__pycache__/_testing.cpython-312.pyc,, +anyio/_core/__pycache__/_typedattr.cpython-312.pyc,, +anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626 +anyio/_core/_concurrency_utils.py,sha256=kvRXMrnDqgQTBkZc-f279-lBnZM4YbSToXqhnAUCfSc,4522 +anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215 +anyio/_core/_eventloop.py,sha256=ByZUeJD9alMfcyTseRo5IzTO0IltEul_Gyq9iqSjqDk,6658 +anyio/_core/_exceptions.py,sha256=B4ZhLkBQT4tI6vShv4-GJui492IJsoIDTw1FQJEkmAI,5618 +anyio/_core/_fileio.py,sha256=q--ft9h5Y_FRLzhAnoYrXf3tOuZ8ZyIN2A9mCfMbZRc,34163 +anyio/_core/_futures.py,sha256=YQq5uhnCnKQMQD62tOLfzEm7dUXY3GQorJdH6ghfgIQ,6177 +anyio/_core/_resources.py,sha256=Ld5duCe9NwgPfI7EIOh3CMIBYQ7rq6ZQEa7CFS0u9Ec,450 +anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016 +anyio/_core/_sockets.py,sha256=C8b-3w5H9n0Fo4g7X8WJvk0m6CGh6NVAAFtieBGHK3g,35289 +anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806 +anyio/_core/_subprocesses.py,sha256=TMBuGNILz-47w5t9vayJ1GpCpDT6LxsMohJDFCewIRc,7938 +anyio/_core/_synchronization.py,sha256=ggsd74QPd846faA2HQeT07ONQ5HQ1S78gy8mvB3qCrw,21658 +anyio/_core/_tasks.py,sha256=J2dhM_Jq3Grsfg_enNWpRz2SxfM15uLt-pEfvoQq3uA,15391 +anyio/_core/_tempfile.py,sha256=IgoBCFaPhrFvsF9KHcCcrnCRn-UqMfw0WRdSDWgxAiI,19726 +anyio/_core/_testing.py,sha256=ZRucLh5kqhiFWAJMMbd8yZ6uIvz0rq3WwL72ldosxAU,2340 +anyio/_core/_typedattr.py,sha256=gt9Dzn-IL0QW14aHPDD8PAtq95FYKNNupHyf37xZGPQ,2607 +anyio/_lazyimport.py,sha256=LCjnYanIfYE9G-Dv_EsqNLDuVRppNicWZjCTfS9-sJU,6082 +anyio/abc/__init__.py,sha256=XIVvCI2c6oyaOcqXe94k2rzU5_s7-ZNnlxGTk34H4T0,3050 +anyio/abc/__pycache__/__init__.cpython-312.pyc,, +anyio/abc/__pycache__/_eventloop.cpython-312.pyc,, +anyio/abc/__pycache__/_resources.cpython-312.pyc,, +anyio/abc/__pycache__/_sockets.cpython-312.pyc,, +anyio/abc/__pycache__/_streams.cpython-312.pyc,, +anyio/abc/__pycache__/_subprocesses.cpython-312.pyc,, +anyio/abc/__pycache__/_tasks.cpython-312.pyc,, +anyio/abc/__pycache__/_testing.cpython-312.pyc,, +anyio/abc/_eventloop.py,sha256=0-UwgB351rkocCt8m3fjTmcNx2Fxn52nUoujG5DzMvU,11127 +anyio/abc/_resources.py,sha256=hrb0LXUgHSp3i8G6W8JJchdzKXgg1m0T-L7udXmv2y0,900 +anyio/abc/_sockets.py,sha256=jQWnPX7iDIDyvyvVkbuFhjezw4oI2WggzbW6Vl2-eqs,13162 +anyio/abc/_streams.py,sha256=IMeOPPutFXRbyeAutxV1HJe7FUQZYp2qKrJJpP1DCv0,7620 +anyio/abc/_subprocesses.py,sha256=CDqU1p0HuBS0pXUzBW_hbfhihTJRM67n__7qZmoPU84,2123 +anyio/abc/_tasks.py,sha256=HBPpT72aOy0bwMAxBCKmnXsR328wCYRjYm3iaVw2fQo,7070 +anyio/abc/_testing.py,sha256=A9Y8RAClIPn1A0aNHBN8YoaRy_MKOpbFGEbTHAXgB6U,2145 +anyio/from_thread.py,sha256=iZZbfcNySi4wAcx1_cxAQE4J0YZC88qRMIYqQ6SF9sc,19415 +anyio/functools.py,sha256=T4JS8IXq-x1S0Lbo2owF8l9fza2KypO147QLeyz4cjs,11797 +anyio/itertools.py,sha256=TS7_UCa2Y3cggtaLlWHbjOyf6QhPfQUdPduNW-ddXTE,16255 +anyio/lowlevel.py,sha256=QyWkvfetbCH0mHkqv1yxGwOaiZ7fyxhpZkHWOXPV5JU,6280 +anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/pytest_plugin.py,sha256=oLXyOstvRZW3VVbqIODhZsPt4jSz2UGh44YeG2nJXx0,14516 +anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/streams/__pycache__/__init__.cpython-312.pyc,, +anyio/streams/__pycache__/buffered.cpython-312.pyc,, +anyio/streams/__pycache__/file.cpython-312.pyc,, +anyio/streams/__pycache__/memory.cpython-312.pyc,, +anyio/streams/__pycache__/stapled.cpython-312.pyc,, +anyio/streams/__pycache__/text.cpython-312.pyc,, +anyio/streams/__pycache__/tls.cpython-312.pyc,, +anyio/streams/buffered.py,sha256=u7hCD8SNrYHcutG6K5wEiy1F88-pizgjvEFM22Kq2Cw,6746 +anyio/streams/file.py,sha256=6jujI2m-QJITqqKFamrupX_DNsU7y2Fz3omLZxOLuY0,4524 +anyio/streams/memory.py,sha256=rpxNzDMag9PCOynBqN64KyuAfAPB41vFyRP-Npo-lE0,10793 +anyio/streams/stapled.py,sha256=UJ2Rgt0NUmM1VovRNOoZoic960lcbDjb3vhfZg3b_Z0,4845 +anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765 +anyio/streams/tls.py,sha256=fqLmxvULFO9rvxGyJ33VPrOIN7E3eiU1q90BkmKigQ8,15818 +anyio/to_interpreter.py,sha256=ATnoT6kei9wDmQZtXTA3SsY4CK7XKr8Ta4_x5i6pbTw,7100 +anyio/to_process.py,sha256=p6n8j0nreJUl1DEkR_9PL6KRoKtNqFxORTn8qZBvn94,9850 +anyio/to_thread.py,sha256=8MPVrrQq8ttGvV21cSd68rMto5bhxJ0-i9CupXag5Gs,2750 diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..13013d7b49be5a84c3ee5931b06285b9553cf5d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..44dd9bdc3039122cc98014c1439ca254313fd014 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[pytest11] +anyio = anyio.pytest_plugin diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..104eebf5a3002fccdaceef3a4cb936173c1c2035 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018 Alex Grönholm + +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. diff --git a/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c77c069ecc9b7f8b1f97dbcfec905725db0253a8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/top_level.txt @@ -0,0 +1 @@ +anyio diff --git a/.venv/lib/python3.12/site-packages/anyio/abc/_resources.py b/.venv/lib/python3.12/site-packages/anyio/abc/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..9373f71a3fc4ccfb2002d03328cf62f78802375a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/abc/_resources.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from types import TracebackType +from typing import TypeVar + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +T = TypeVar("T") + + +class AsyncResource(metaclass=ABCMeta): + """ + Abstract base class for all closeable asynchronous resources. + + Works as an asynchronous context manager which returns the instance itself on enter, + and calls :meth:`aclose` on exit. + """ + + __slots__ = () + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.aclose() + + @abstractmethod + async def aclose(self) -> None: + """Close the resource.""" diff --git a/.venv/lib/python3.12/site-packages/anyio/abc/_sockets.py b/.venv/lib/python3.12/site-packages/anyio/abc/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a1139dfd9d31776c581b25db1309d9bfbb080e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/abc/_sockets.py @@ -0,0 +1,401 @@ +from __future__ import annotations + +import errno +import socket +from abc import abstractmethod +from collections.abc import Callable, Collection, Mapping +from contextlib import AsyncExitStack +from io import IOBase +from ipaddress import IPv4Address, IPv6Address +from socket import AddressFamily +from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar + +from .._core._eventloop import get_async_backend +from .._core._typedattr import ( + TypedAttributeProvider, + TypedAttributeSet, + typed_attribute, +) +from ._streams import ByteStream, Listener, UnreliableObjectStream + +if TYPE_CHECKING: + from ._tasks import TaskGroup + +IPAddressType: TypeAlias = str | IPv4Address | IPv6Address +IPSockAddrType: TypeAlias = tuple[str, int] +SockAddrType: TypeAlias = IPSockAddrType | str +UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType] +UNIXDatagramPacketType: TypeAlias = tuple[bytes, str] +T_Retval = TypeVar("T_Retval") + + +def _validate_socket( + sock_or_fd: socket.socket | int, + sock_type: socket.SocketKind, + addr_family: socket.AddressFamily = socket.AF_UNSPEC, + *, + require_connected: bool = False, + require_bound: bool = False, +) -> socket.socket: + if isinstance(sock_or_fd, int): + try: + sock = socket.socket(fileno=sock_or_fd) + except OSError as exc: + if exc.errno == errno.ENOTSOCK: + raise ValueError( + "the file descriptor does not refer to a socket" + ) from exc + elif require_connected: + raise ValueError("the socket must be connected") from exc + elif require_bound: + raise ValueError("the socket must be bound to a local address") from exc + else: + raise + elif isinstance(sock_or_fd, socket.socket): + sock = sock_or_fd + else: + raise TypeError( + f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead" + ) + + try: + if require_connected: + try: + sock.getpeername() + except OSError as exc: + raise ValueError("the socket must be connected") from exc + + if require_bound: + try: + if sock.family in (socket.AF_INET, socket.AF_INET6): + bound_addr = sock.getsockname()[1] + else: + bound_addr = sock.getsockname() + except OSError: + bound_addr = None + + if not bound_addr: + raise ValueError("the socket must be bound to a local address") + + if addr_family != socket.AF_UNSPEC and sock.family != addr_family: + raise ValueError( + f"address family mismatch: expected {addr_family.name}, got " + f"{sock.family.name}" + ) + + if sock.type != sock_type: + raise ValueError( + f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}" + ) + except BaseException: + # Avoid ResourceWarning from the locally constructed socket object + if isinstance(sock_or_fd, int): + sock.detach() + + raise + + sock.setblocking(False) + return sock + + +class SocketAttribute(TypedAttributeSet): + """ + .. attribute:: family + :type: socket.AddressFamily + + the address family of the underlying socket + + .. attribute:: local_address + :type: tuple[str, int] | str + + the local address the underlying socket is connected to + + .. attribute:: local_port + :type: int + + for IP based sockets, the local port the underlying socket is bound to + + .. attribute:: raw_socket + :type: socket.socket + + the underlying stdlib socket object + + .. attribute:: remote_address + :type: tuple[str, int] | str + + the remote address the underlying socket is connected to + + .. attribute:: remote_port + :type: int + + for IP based sockets, the remote port the underlying socket is connected to + """ + + family: AddressFamily = typed_attribute() + local_address: SockAddrType = typed_attribute() + local_port: int = typed_attribute() + raw_socket: socket.socket = typed_attribute() + remote_address: SockAddrType = typed_attribute() + remote_port: int = typed_attribute() + + +class _SocketProvider(TypedAttributeProvider): + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + from .._core._sockets import convert_ipv6_sockaddr as convert + + attributes: dict[Any, Callable[[], Any]] = { + SocketAttribute.family: lambda: self._raw_socket.family, + SocketAttribute.local_address: lambda: convert( + self._raw_socket.getsockname() + ), + SocketAttribute.raw_socket: lambda: self._raw_socket, + } + try: + peername: tuple[str, int] | None = convert(self._raw_socket.getpeername()) + except OSError: + peername = None + + # Provide the remote address for connected sockets + if peername is not None: + attributes[SocketAttribute.remote_address] = lambda: peername + + # Provide local and remote ports for IP based sockets + if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6): + attributes[SocketAttribute.local_port] = lambda: ( + self._raw_socket.getsockname()[1] + ) + if peername is not None: + remote_port = peername[1] + attributes[SocketAttribute.remote_port] = lambda: remote_port + + return attributes + + @property + @abstractmethod + def _raw_socket(self) -> socket.socket: + pass + + +class SocketStream(ByteStream, _SocketProvider): + """ + Transports bytes over a socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream: + """ + Wrap an existing socket object or file descriptor as a socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket stream + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True) + return await get_async_backend().wrap_stream_socket(sock) + + +class UNIXSocketStream(SocketStream): + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream: + """ + Wrap an existing socket object or file descriptor as a UNIX socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX socket stream + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_unix_stream_socket(sock) + + @abstractmethod + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + """ + Send file descriptors along with a message to the peer. + + :param message: a non-empty bytestring + :param fds: a collection of files (either numeric file descriptors or open file + or socket objects) + """ + + @abstractmethod + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + """ + Receive file descriptors along with a message from the peer. + + :param msglen: length of the message to expect from the peer + :param maxfds: maximum number of file descriptors to expect from the peer + :return: a tuple of (message, file descriptors) + """ + + +class SocketListener(Listener[SocketStream], _SocketProvider): + """ + Listens to incoming socket connections. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> SocketListener: + """ + Wrap an existing socket object or file descriptor as a socket listener. + + The newly created listener takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket listener + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True) + return await get_async_backend().wrap_listener_socket(sock) + + @abstractmethod + async def accept(self) -> SocketStream: + """Accept an incoming connection.""" + + async def serve( + self, + handler: Callable[[SocketStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + from .. import create_task_group + + async with AsyncExitStack() as stack: + if task_group is None: + task_group = await stack.enter_async_context(create_task_group()) + + while True: + stream = await self.accept() + task_group.start_soon(handler, stream) + + +class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider): + """ + Represents an unconnected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket: + """ + Wrap an existing socket object or file descriptor as a UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must be bound to a local address. + + :param sock_or_fd: a socket object or file descriptor + :return: a UDP socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True) + return await get_async_backend().wrap_udp_socket(sock) + + async def sendto(self, data: bytes, host: str, port: int) -> None: + """ + Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))). + + """ + return await self.send((data, (host, port))) + + +class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents an connected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket: + """ + Wrap an existing socket object or file descriptor as a connected UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UDP socket + + """ + sock = _validate_socket( + sock_or_fd, + socket.SOCK_DGRAM, + require_connected=True, + ) + return await get_async_backend().wrap_connected_udp_socket(sock) + + +class UNIXDatagramSocket( + UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider +): + """ + Represents an unconnected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> UNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX datagram socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX) + return await get_async_backend().wrap_unix_datagram_socket(sock) + + async def sendto(self, data: bytes, path: str) -> None: + """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path)).""" + return await self.send((data, path)) + + +class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents a connected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> ConnectedUNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a connected UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UNIX datagram socket + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_connected_unix_datagram_socket(sock) diff --git a/.venv/lib/python3.12/site-packages/anyio/abc/_streams.py b/.venv/lib/python3.12/site-packages/anyio/abc/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..daf335dc3235ff8e4d5253610cd5e68de17c3f6d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/abc/_streams.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeVar + +from .._core._exceptions import EndOfStream +from .._core._typedattr import TypedAttributeProvider +from ._resources import AsyncResource + +if TYPE_CHECKING: + from ._tasks import TaskGroup + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class UnreliableObjectReceiveStream( + AsyncResource, TypedAttributeProvider, Generic[T_co] +): + """ + An interface for receiving objects. + + This interface makes no guarantees that the received messages arrive in the order in + which they were sent, or that no messages are missed. + + Asynchronously iterating over objects of this type will yield objects matching the + given type parameter. + """ + + def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]: + return self + + async def __anext__(self) -> T_co: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self) -> T_co: + """ + Receive the next item. + + :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly + closed + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectSendStream( + AsyncResource, TypedAttributeProvider, Generic[T_contra] +): + """ + An interface for sending objects. + + This interface makes no guarantees that the messages sent will reach the + recipient(s) in the same order in which they were sent, or at all. + """ + + @abstractmethod + async def send(self, item: T_contra) -> None: + """ + Send an item to the peer(s). + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if the send stream has been explicitly + closed + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectStream( + UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item] +): + """ + A bidirectional message stream which does not guarantee the order or reliability of + message delivery. + """ + + +class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]): + """ + A receive message stream which guarantees that messages are received in the same + order in which they were sent, and that no messages are missed. + """ + + +class ObjectSendStream(UnreliableObjectSendStream[T_contra]): + """ + A send message stream which guarantees that messages are delivered in the same order + in which they were sent, without missing any messages in the middle. + """ + + +class ObjectStream( + ObjectReceiveStream[T_Item], + ObjectSendStream[T_Item], + UnreliableObjectStream[T_Item], +): + """ + A bidirectional message stream which guarantees the order and reliability of message + delivery. + """ + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +class ByteReceiveStream(AsyncResource, TypedAttributeProvider): + """ + An interface for receiving bytes from a single peer. + + Iterating this byte stream will yield a byte string of arbitrary length, but no more + than 65536 bytes. + """ + + def __aiter__(self) -> ByteReceiveStream: + return self + + async def __anext__(self) -> bytes: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self, max_bytes: int = 65536) -> bytes: + """ + Receive at most ``max_bytes`` bytes from the peer. + + .. note:: Implementers of this interface should not return an empty + :class:`bytes` object, and users should ignore them. + + :param max_bytes: maximum number of bytes to receive (must be a positive + integer) + :return: the received bytes + :raises ValueError: if ``max_bytes`` is less than 1 + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + """ + + +class ByteSendStream(AsyncResource, TypedAttributeProvider): + """An interface for sending bytes to a single peer.""" + + @abstractmethod + async def send(self, item: bytes) -> None: + """ + Send the given bytes to the peer. + + :param item: the bytes to send + """ + + +class ByteStream(ByteReceiveStream, ByteSendStream): + """A bidirectional byte stream.""" + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +#: Type alias for all unreliable bytes-oriented receive streams. +AnyUnreliableByteReceiveStream: TypeAlias = ( + UnreliableObjectReceiveStream[bytes] | ByteReceiveStream +) +#: Type alias for all unreliable bytes-oriented send streams. +AnyUnreliableByteSendStream: TypeAlias = ( + UnreliableObjectSendStream[bytes] | ByteSendStream +) +#: Type alias for all unreliable bytes-oriented streams. +AnyUnreliableByteStream: TypeAlias = UnreliableObjectStream[bytes] | ByteStream +#: Type alias for all bytes-oriented receive streams. +AnyByteReceiveStream: TypeAlias = ObjectReceiveStream[bytes] | ByteReceiveStream +#: Type alias for all bytes-oriented send streams. +AnyByteSendStream: TypeAlias = ObjectSendStream[bytes] | ByteSendStream +#: Type alias for all bytes-oriented streams. +AnyByteStream: TypeAlias = ObjectStream[bytes] | ByteStream + + +class Listener(AsyncResource, TypedAttributeProvider, Generic[T_co]): + """An interface for objects that let you accept incoming connections.""" + + @abstractmethod + async def serve( + self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None + ) -> None: + """ + Accept incoming connections as they come in and start tasks to handle them. + + :param handler: a callable that will be used to handle each accepted connection + :param task_group: the task group that will be used to start tasks for handling + each accepted connection (if omitted, an ad-hoc task group will be created) + """ + + +class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ObjectStream[T_co]: + """ + Connect to the remote endpoint. + + :return: an object stream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +class ByteStreamConnectable(metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ByteStream: + """ + Connect to the remote endpoint. + + :return: a bytestream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +#: Type alias for all connectables returning bytestreams or bytes-oriented object streams +AnyByteStreamConnectable: TypeAlias = ( + ObjectStreamConnectable[bytes] | ByteStreamConnectable +) diff --git a/.venv/lib/python3.12/site-packages/anyio/abc/_subprocesses.py b/.venv/lib/python3.12/site-packages/anyio/abc/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..555f15f10d2b8375a791a620eafd87795d8e9107 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/abc/_subprocesses.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from abc import abstractmethod +from signal import Signals +from typing import TYPE_CHECKING + +from ._resources import AsyncResource + +if TYPE_CHECKING: + from ._streams import ByteReceiveStream, ByteSendStream + + +class Process(AsyncResource): + """An asynchronous version of :class:`subprocess.Popen`.""" + + @abstractmethod + async def wait(self) -> int: + """ + Wait until the process exits. + + :return: the exit code of the process + """ + + @abstractmethod + def terminate(self) -> None: + """ + Terminates the process, gracefully if possible. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGTERM`` to the process. + + .. seealso:: :meth:`subprocess.Popen.terminate` + """ + + @abstractmethod + def kill(self) -> None: + """ + Kills the process. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGKILL`` to the process. + + .. seealso:: :meth:`subprocess.Popen.kill` + """ + + @abstractmethod + def send_signal(self, signal: Signals) -> None: + """ + Send a signal to the subprocess. + + .. seealso:: :meth:`subprocess.Popen.send_signal` + + :param signal: the signal number (e.g. :data:`signal.SIGHUP`) + """ + + @property + @abstractmethod + def pid(self) -> int: + """The process ID of the process.""" + + @property + @abstractmethod + def returncode(self) -> int | None: + """ + The return code of the process. If the process has not yet terminated, this will + be ``None``. + """ + + @property + @abstractmethod + def stdin(self) -> ByteSendStream | None: + """The stream for the standard input of the process.""" + + @property + @abstractmethod + def stdout(self) -> ByteReceiveStream | None: + """The stream for the standard output of the process.""" + + @property + @abstractmethod + def stderr(self) -> ByteReceiveStream | None: + """The stream for the standard error output of the process.""" diff --git a/.venv/lib/python3.12/site-packages/anyio/abc/_tasks.py b/.venv/lib/python3.12/site-packages/anyio/abc/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..0a019e2ed3bd6bc36c97f87f3a8b9eee2ba0f657 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/abc/_tasks.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Coroutine +from contextvars import Context +from types import TracebackType +from typing import TYPE_CHECKING, Any, Literal, Protocol, final, overload + +if sys.version_info >= (3, 13): + from typing import TypeVar +else: + from typing_extensions import TypeVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from .._core._tasks import CancelScope, TaskHandle + +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True, default=None) +PosArgsT = TypeVarTuple("PosArgsT") + + +def get_coro_name(coro: Coroutine[Any, Any, object], override: object = None) -> str: + if override is not None: + return str(override) + + try: + cr_frame = coro.cr_frame # type: ignore[attr-defined] + module = cr_frame.f_globals["__name__"] + except (AttributeError, KeyError): + module = None + + qualname = getattr(coro, "__qualname__", None) + return ".".join([x for x in (module, qualname) if x]) + + +def get_callable_name(func: Callable, override: object = None) -> str: + if override is not None: + return str(override) + + module = getattr(func, "__module__", None) + qualname = getattr(func, "__qualname__", None) + return ".".join([x for x in (module, qualname) if x]) + + +def call_for_coroutine( + func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], + args: tuple[Unpack[PosArgsT]], + **kwargs: Any, +) -> Coroutine[Any, Any, T_co]: + """ + Call the given function with the given positional and keyword arguments. + + :return: the resulting coroutine + :raises TypeError: if the return value was not a coroutine object + + """ + coro = func(*args, **kwargs) + if not isinstance(coro, Coroutine): + prefix = f"{func.__module__}." if hasattr(func, "__module__") else "" + raise TypeError( + f"Expected {prefix}{func.__qualname__}() to return a coroutine, but " + f"the return value ({coro!r}) is not a coroutine object" + ) + + return coro + + +class TaskStatus(Protocol[T_contra]): + @overload + def started(self: TaskStatus[None]) -> None: ... + + @overload + def started(self, value: T_contra) -> None: ... + + def started(self, value: T_contra | None = None) -> None: + """ + Signal that the task has started. + + :param value: object passed back to the starter of the task + """ + + +class TaskGroup(metaclass=ABCMeta): + """ + Groups several asynchronous tasks together. + + :ivar cancel_scope: the cancel scope inherited by all child tasks + :vartype cancel_scope: CancelScope + + .. note:: On asyncio, support for eager task factories is considered to be + **experimental**. In particular, they don't follow the usual semantics of new + tasks being scheduled on the next iteration of the event loop, and may thus + cause unexpected behavior in code that wasn't written with such semantics in + mind. + """ + + cancel_scope: CancelScope + + def cancel(self, reason: str | None = None) -> None: + """ + Cancel this task group's cancel scope immediately. + + This is a shortcut for calling ``.cancel_scope.cancel()`` on the task group. + + :param reason: a message describing the reason for the cancellation + + .. versionadded:: 4.14.0 + + """ + self.cancel_scope.cancel(reason) + + @abstractmethod + def create_task( + self, + coro: Coroutine[Any, Any, T_co], + *, + name: object = None, + context: Context | None = None, + ) -> TaskHandle[T_co]: + """ + Create a new task from a coroutine object and schedule it to run. + + :param coro: a coroutine object + :param name: optional name to give the task + :param context: optional context to run the task in + :return: a task handle + + .. versionadded:: 4.14.0 + """ + + @final + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> TaskHandle[T_co]: + """ + Start a new task in this task group. + + :param func: a coroutine function + :param args: positional arguments to call the function with + :param name: name of the task, for the purposes of introspection and debugging + :return: a task handle + + .. versionadded:: 3.0 + .. versionchanged:: 4.14.0 + This method now returns a task handle. + + """ + final_name = get_callable_name(func, name) + return self.create_task(call_for_coroutine(func, args), name=final_name) + + @overload + async def start( + self, + func: Callable[..., Coroutine[Any, Any, T_co]], + *args: object, + name: object = None, + return_handle: Literal[False] = ..., + ) -> Any: ... + + @overload + async def start( + self, + func: Callable[..., Coroutine[Any, Any, T_co]], + *args: object, + name: object = None, + return_handle: Literal[True], + ) -> TaskHandle[T_co, Any]: ... + + @abstractmethod + async def start( + self, + func: Callable[..., Coroutine[Any, Any, T_co]], + *args: object, + name: object = None, + return_handle: Literal[False, True] = False, + ) -> Any: + """ + Start a new task and wait until it signals for readiness. + + The target callable must accept a keyword argument ``task_status`` (of type + :class:`TaskStatus`). Awaiting on this method will return whatever was passed to + ``task_status.started()`` (``None`` by default). + + .. note:: The :class:`TaskStatus` class is generic, and the type argument should + indicate the type of the value that will be passed to + ``task_status.started()``. + + :param func: a coroutine function that accepts the ``task_status`` keyword + argument + :param args: positional arguments to call the function with + :param name: an optional name for the task, for introspection and debugging + :param return_handle: if ``True``, return a :class:`TaskHandle` which also + contains the start value in ``start_value`` + :return: the value passed to ``task_status.started()`` + :raises RuntimeError: if the task finishes without calling + ``task_status.started()`` + + .. seealso:: :ref:`start_initialize` + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def __aenter__(self) -> TaskGroup: + """Enter the task group context and allow starting new tasks.""" + + @abstractmethod + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + """Exit the task group context waiting for all tasks to finish.""" diff --git a/.venv/lib/python3.12/site-packages/anyio/abc/_testing.py b/.venv/lib/python3.12/site-packages/anyio/abc/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..b18d8357e7a71d228877584e98b1286d273928f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/abc/_testing.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import sys +import types +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable +from typing import Any, TypeVar + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_T = TypeVar("_T") + + +class TestRunner(metaclass=ABCMeta): + """ + Encapsulates a running event loop. Every call made through this object will use the + same event loop. + """ + + def __enter__(self) -> Self: + return self + + @abstractmethod + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool | None: ... + + @abstractmethod + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[_T, Any]], + kwargs: dict[str, Any], + ) -> Iterable[_T]: + """ + Run an async generator fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: an iterator yielding the value yielded from the async generator + """ + + @abstractmethod + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, _T]], + kwargs: dict[str, Any], + ) -> _T: + """ + Run an async fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: the return value of the fixture function + """ + + @abstractmethod + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + """ + Run an async test function. + + :param test_func: the test function + :param kwargs: keyword arguments to call the test function with + """ + + @abstractmethod + def is_running(self) -> bool: + """ + Check if the test runner is running. + + :return: ``True`` if the coroutine is currently being run, ``False`` otherwise. + """ diff --git a/.venv/lib/python3.12/site-packages/anyio/from_thread.py b/.venv/lib/python3.12/site-packages/anyio/from_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..f163d818b030f752350558e805988bf8c558b262 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/from_thread.py @@ -0,0 +1,588 @@ +from __future__ import annotations + +__all__ = ( + "BlockingPortal", + "BlockingPortalProvider", + "check_cancelled", + "run", + "run_sync", + "start_blocking_portal", +) + +import sys +from collections.abc import Awaitable, Callable, Coroutine, Generator +from concurrent.futures import Future +from contextlib import ( + AbstractAsyncContextManager, + AbstractContextManager, + contextmanager, +) +from contextvars import Context +from dataclasses import dataclass, field +from functools import partial +from inspect import isawaitable +from threading import Lock, Thread, current_thread, get_ident +from types import TracebackType +from typing import ( + Any, + Generic, + TypeVar, + cast, + overload, +) + +from ._core._eventloop import ( + get_cancelled_exc_class, + threadlocals, +) +from ._core._eventloop import run as run_eventloop +from ._core._exceptions import NoEventLoopError +from ._core._synchronization import Event +from ._core._tasks import CancelScope, create_task_group +from .abc._tasks import TaskStatus +from .lowlevel import EventLoopToken, current_token + +if sys.version_info >= (3, 11): + from typing import Self, TypeVarTuple, Unpack +else: + from typing_extensions import Self, TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +T_co = TypeVar("T_co", covariant=True) +PosArgsT = TypeVarTuple("PosArgsT") + + +def _token_or_error(token: EventLoopToken | None) -> EventLoopToken: + if token is not None: + return token + + try: + return threadlocals.current_token + except AttributeError: + raise NoEventLoopError( + "Not running inside an AnyIO worker thread, and no event loop token was " + "provided" + ) from None + + +def run( + func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], + *args: Unpack[PosArgsT], + token: EventLoopToken | None = None, +) -> T_co: + """ + Call a coroutine function from a worker thread. + + :param func: a coroutine function + :param args: positional arguments for the callable + :param token: an event loop token to use to get back to the event loop thread + (required if calling this function from outside an AnyIO worker thread) + :return: the return value of the coroutine function + :raises MissingTokenError: if no token was provided and called from outside an + AnyIO worker thread + :raises RunFinishedError: if the event loop tied to ``token`` is no longer running + + .. versionchanged:: 4.11.0 + Added the ``token`` parameter. + + """ + explicit_token = token is not None + token = _token_or_error(token) + return token.backend_class.run_async_from_thread( + func, args, token=token.native_token if explicit_token else None + ) + + +def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + token: EventLoopToken | None = None, +) -> T_Retval: + """ + Call a function in the event loop thread from a worker thread. + + :param func: a callable + :param args: positional arguments for the callable + :param token: an event loop token to use to get back to the event loop thread + (required if calling this function from outside an AnyIO worker thread) + :return: the return value of the callable + :raises MissingTokenError: if no token was provided and called from outside an + AnyIO worker thread + :raises RunFinishedError: if the event loop tied to ``token`` is no longer running + + .. versionchanged:: 4.11.0 + Added the ``token`` parameter. + + """ + explicit_token = token is not None + token = _token_or_error(token) + return token.backend_class.run_sync_from_thread( + func, args, token=token.native_token if explicit_token else None + ) + + +class _BlockingAsyncContextManager(AbstractContextManager, Generic[T_co]): + _enter_future: Future[T_co] + _exit_future: Future[bool | None] + _exit_event: Event + _exit_exc_info: tuple[ + type[BaseException] | None, BaseException | None, TracebackType | None + ] = (None, None, None) + + def __init__( + self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal + ): + self._async_cm = async_cm + self._portal = portal + + async def run_async_cm(self) -> bool | None: + try: + self._exit_event = Event() + value = await self._async_cm.__aenter__() + except BaseException as exc: + self._enter_future.set_exception(exc) + raise + else: + self._enter_future.set_result(value) + + try: + # Wait for the sync context manager to exit. + # This next statement can raise `get_cancelled_exc_class()` if + # something went wrong in a task group in this async context + # manager. + await self._exit_event.wait() + finally: + # In case of cancellation, it could be that we end up here before + # `_BlockingAsyncContextManager.__exit__` is called, and an + # `_exit_exc_info` has been set. + result = await self._async_cm.__aexit__(*self._exit_exc_info) + + return result + + def __enter__(self) -> T_co: + self._enter_future = Future() + self._exit_future = self._portal.start_task_soon(self.run_async_cm) + return self._enter_future.result() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + /, + ) -> bool | None: + self._exit_exc_info = exc_type, exc_value, traceback + self._portal.call(self._exit_event.set) + return self._exit_future.result() + + +class _BlockingPortalTaskStatus(TaskStatus): + def __init__(self, future: Future): + self._future = future + + def started(self, value: object = None) -> None: + self._future.set_result(value) + + +class BlockingPortal: + """ + An object that lets external threads run code in an asynchronous event loop. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + """ + + def __init__(self) -> None: + self._token = current_token() + self._event_loop_thread_id: int | None = get_ident() + self._stop_event = Event() + self._task_group = create_task_group() + + async def __aenter__(self) -> Self: + await self._task_group.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + await self.stop() + return await self._task_group.__aexit__(exc_type, exc_val, exc_tb) + + def _check_running(self) -> None: + if self._event_loop_thread_id is None: + raise RuntimeError("This portal is not running") + if self._event_loop_thread_id == get_ident(): + raise RuntimeError( + "This method cannot be called from the event loop thread" + ) + + async def sleep_until_stopped(self) -> None: + """Sleep until :meth:`stop` is called.""" + await self._stop_event.wait() + + async def stop(self, cancel_remaining: bool = False) -> None: + """ + Signal the portal to shut down. + + This marks the portal as no longer accepting new calls and exits from + :meth:`sleep_until_stopped`. + + :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` + to let them finish before returning + + """ + self._event_loop_thread_id = None + self._stop_event.set() + if cancel_remaining: + self._task_group.cancel_scope.cancel("the blocking portal is shutting down") + + async def _call_func( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + future: Future[T_Retval], + ) -> None: + event_loop_thread_id = self._event_loop_thread_id + + def callback(f: Future[T_Retval]) -> None: + if f.cancelled(): + if event_loop_thread_id == get_ident(): + scope.cancel("the future was cancelled") + elif event_loop_thread_id is not None: + run_sync( + scope.cancel, "the future was cancelled", token=self._token + ) + + try: + retval_or_awaitable = func(*args, **kwargs) + if isawaitable(retval_or_awaitable): + with CancelScope() as scope: + future.add_done_callback(callback) + retval = await retval_or_awaitable + else: + retval = retval_or_awaitable + except get_cancelled_exc_class(): + future.cancel() + future.set_running_or_notify_cancel() + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + # Let base exceptions fall through + if not isinstance(exc, Exception): + raise + else: + if not future.cancelled(): + future.set_result(retval) + finally: + scope = None # type: ignore[assignment] + + def _spawn_task_from_thread( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + name: object, + future: Future[T_Retval], + ) -> None: + """ + Spawn a new task using the given callable. + + :param func: a callable + :param args: positional arguments to be passed to the callable + :param kwargs: keyword arguments to be passed to the callable + :param name: name of the task (will be coerced to a string if not ``None``) + :param future: a future that will resolve to the return value of the callable, + or the exception raised during its execution + + """ + run_sync( + partial(self._task_group.start_soon, name=name), + self._call_func, + func, + args, + kwargs, + future, + token=self._token, + ) + + @overload + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + ) -> T_Retval: ... + + @overload + def call( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: ... + + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + ) -> T_Retval: + """ + Call the given function in the event loop thread. + + If the callable returns a coroutine object, it is awaited on. + + :param func: any callable + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + + """ + return cast(T_Retval, self.start_task_soon(func, *args).result()) + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: + """ + Start a task in the portal's task group. + + The task will be run inside a cancel scope which can be cancelled by cancelling + the returned future. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a future that resolves with the return value of the callable if the + task completes successfully, or with the exception raised in the task + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + :rtype: concurrent.futures.Future[T_Retval] + + .. versionadded:: 3.0 + + """ + self._check_running() + f: Future[T_Retval] = Future() + self._spawn_task_from_thread(func, args, {}, name, f) + return f + + def start_task( + self, + func: Callable[..., Awaitable[T_Retval]], + *args: object, + name: object = None, + ) -> tuple[Future[T_Retval], Any]: + """ + Start a task in the portal's task group and wait until it signals for readiness. + + This method works the same way as :meth:`.abc.TaskGroup.start`. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a tuple of (future, task_status_value) where the ``task_status_value`` + is the value passed to ``task_status.started()`` from within the target + function + :rtype: tuple[concurrent.futures.Future[T_Retval], Any] + + .. versionadded:: 3.0 + + """ + + def task_done(future: Future[T_Retval]) -> None: + if not task_status_future.done(): + if future.cancelled(): + task_status_future.cancel() + elif future.exception(): + task_status_future.set_exception(future.exception()) + else: + exc = RuntimeError( + "Task exited without calling task_status.started()" + ) + task_status_future.set_exception(exc) + + self._check_running() + task_status_future: Future = Future() + task_status = _BlockingPortalTaskStatus(task_status_future) + f: Future = Future() + f.add_done_callback(task_done) + self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f) + return f, task_status_future.result() + + def wrap_async_context_manager( + self, cm: AbstractAsyncContextManager[T_co] + ) -> AbstractContextManager[T_co]: + """ + Wrap an async context manager as a synchronous context manager via this portal. + + Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping + in the middle until the synchronous context manager exits. + + :param cm: an asynchronous context manager + :return: a synchronous context manager + + .. versionadded:: 2.1 + + """ + return _BlockingAsyncContextManager(cm, self) + + +@dataclass +class BlockingPortalProvider: + """ + A manager for a blocking portal. Used as a context manager. The first thread to + enter this context manager causes a blocking portal to be started with the specific + parameters, and the last thread to exit causes the portal to be shut down. Thus, + there will be exactly one blocking portal running in this context as long as at + least one thread has entered this context manager. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + + .. versionadded:: 4.4 + """ + + backend: str = "asyncio" + backend_options: dict[str, Any] | None = None + _lock: Lock = field(init=False, default_factory=Lock) + _leases: int = field(init=False, default=0) + _portal: BlockingPortal = field(init=False) + _portal_cm: AbstractContextManager[BlockingPortal] | None = field( + init=False, default=None + ) + + def __enter__(self) -> BlockingPortal: + with self._lock: + if self._portal_cm is None: + self._portal_cm = start_blocking_portal( + self.backend, self.backend_options + ) + self._portal = self._portal_cm.__enter__() + + self._leases += 1 + return self._portal + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + portal_cm: AbstractContextManager[BlockingPortal] | None = None + with self._lock: + assert self._portal_cm + assert self._leases > 0 + self._leases -= 1 + if not self._leases: + portal_cm = self._portal_cm + self._portal_cm = None + del self._portal + + if portal_cm: + portal_cm.__exit__(None, None, None) + + +@contextmanager +def start_blocking_portal( + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, + *, + name: str | None = None, +) -> Generator[BlockingPortal, Any, None]: + """ + Start a new event loop in a new thread and run a blocking portal in its main task. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + :param name: name of the thread + :return: a context manager that yields a blocking portal + + .. versionchanged:: 3.0 + Usage as a context manager is now required. + + """ + + async def run_portal() -> None: + async with BlockingPortal() as portal_: + if name is None: + current_thread().name = f"{backend}-portal-{id(portal_):x}" + + future.set_result(portal_) + await portal_.sleep_until_stopped() + + def run_blocking_portal() -> None: + if future.set_running_or_notify_cancel(): + try: + run_eventloop( + run_portal, backend=backend, backend_options=backend_options + ) + except BaseException as exc: + if not future.done(): + future.set_exception(exc) + + future: Future[BlockingPortal] = Future() + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 14): + kwargs["context"] = Context() + + thread = Thread(target=run_blocking_portal, daemon=True, name=name, **kwargs) + thread.start() + try: + cancel_remaining_tasks = False + portal = future.result() + try: + yield portal + except BaseException: + cancel_remaining_tasks = True + raise + finally: + try: + portal.call(portal.stop, cancel_remaining_tasks) + except RuntimeError: + pass + finally: + thread.join() + + +def check_cancelled() -> None: + """ + Check if the cancel scope of the host task's running the current worker thread has + been cancelled. + + If the host task's current cancel scope has indeed been cancelled, the + backend-specific cancellation exception will be raised. + + :raises RuntimeError: if the current thread was not spawned by + :func:`.to_thread.run_sync` + + """ + try: + token: EventLoopToken = threadlocals.current_token + except AttributeError: + raise NoEventLoopError( + "This function can only be called inside an AnyIO worker thread" + ) from None + + token.backend_class.check_cancelled() diff --git a/.venv/lib/python3.12/site-packages/anyio/functools.py b/.venv/lib/python3.12/site-packages/anyio/functools.py new file mode 100644 index 0000000000000000000000000000000000000000..b0bdfb4585efc4e4799388547668fba86fb5c687 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/functools.py @@ -0,0 +1,400 @@ +from __future__ import annotations + +__all__ = ( + "AsyncCacheInfo", + "AsyncCacheParameters", + "AsyncLRUCacheWrapper", + "cache", + "lru_cache", + "reduce", +) + +import functools +from collections import OrderedDict +from collections.abc import ( + AsyncIterable, + Awaitable, + Callable, + Coroutine, + Hashable, + Iterable, +) +from functools import update_wrapper +from inspect import iscoroutinefunction +from typing import ( + Any, + Generic, + NamedTuple, + ParamSpec, + TypedDict, + TypeVar, + cast, + final, + overload, +) +from weakref import WeakKeyDictionary + +from ._core._eventloop import current_time +from ._core._synchronization import Lock +from .lowlevel import RunVar, checkpoint + +T = TypeVar("T") +S = TypeVar("S") +P = ParamSpec("P") +lru_cache_items: RunVar[ + WeakKeyDictionary[ + AsyncLRUCacheWrapper[Any, Any], + OrderedDict[ + Hashable, + tuple[_InitialMissingType, Lock, float | None] + | tuple[Any, None, float | None], + ], + ] +] = RunVar("lru_cache_items") + + +class _InitialMissingType: + pass + + +initial_missing: _InitialMissingType = _InitialMissingType() + + +class AsyncCacheInfo(NamedTuple): + hits: int + misses: int + maxsize: int | None + currsize: int + ttl: int | None + + +class AsyncCacheParameters(TypedDict): + maxsize: int | None + typed: bool + always_checkpoint: bool + ttl: int | None + + +class _LRUMethodWrapper(Generic[T]): + def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object): + self.__wrapper = wrapper + self.__instance = instance + + def cache_info(self) -> AsyncCacheInfo: + return self.__wrapper.cache_info() + + def cache_parameters(self) -> AsyncCacheParameters: + return self.__wrapper.cache_parameters() + + def cache_clear(self) -> None: + self.__wrapper.cache_clear() + + async def __call__(self, *args: Any, **kwargs: Any) -> T: + if self.__instance is None: + return await self.__wrapper(*args, **kwargs) + + return await self.__wrapper(self.__instance, *args, **kwargs) + + +@final +class AsyncLRUCacheWrapper(Generic[P, T]): + def __init__( + self, + func: Callable[P, Awaitable[T]], + maxsize: int | None, + typed: bool, + always_checkpoint: bool, + ttl: int | None, + ): + self.__wrapped__ = func + self._hits: int = 0 + self._misses: int = 0 + self._maxsize = max(maxsize, 0) if maxsize is not None else None + self._currsize: int = 0 + self._typed = typed + self._always_checkpoint = always_checkpoint + self._ttl = ttl + update_wrapper(self, func) + + def cache_info(self) -> AsyncCacheInfo: + return AsyncCacheInfo( + self._hits, self._misses, self._maxsize, self._currsize, self._ttl + ) + + def cache_parameters(self) -> AsyncCacheParameters: + return { + "maxsize": self._maxsize, + "typed": self._typed, + "always_checkpoint": self._always_checkpoint, + "ttl": self._ttl, + } + + def cache_clear(self) -> None: + if cache := lru_cache_items.get(None): + cache.pop(self, None) + self._hits = self._misses = self._currsize = 0 + + async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: + # Easy case first: if maxsize == 0, no caching is done + if self._maxsize == 0: + value = await self.__wrapped__(*args, **kwargs) + self._misses += 1 + return value + + # The key is constructed as a flat tuple to avoid memory overhead + key: tuple[Any, ...] = args + if kwargs: + # initial_missing is used as a separator + key += (initial_missing,) + sum(kwargs.items(), ()) + + if self._typed: + key += tuple(type(arg) for arg in args) + if kwargs: + key += (initial_missing,) + tuple(type(val) for val in kwargs.values()) + + try: + cache = lru_cache_items.get() + except LookupError: + cache = WeakKeyDictionary() + lru_cache_items.set(cache) + + try: + cache_entry = cache[self] + except KeyError: + cache_entry = cache[self] = OrderedDict() + + cached_value: T | _InitialMissingType + try: + cached_value, lock, expires_at = cache_entry[key] + except KeyError: + # We're the first task to call this function + cached_value, lock, expires_at = ( + initial_missing, + Lock(fast_acquire=not self._always_checkpoint), + None, + ) + cache_entry[key] = cached_value, lock, expires_at + + if lock is None: + if expires_at is not None and current_time() >= expires_at: + self._currsize -= 1 + cached_value, lock, expires_at = ( + initial_missing, + Lock(fast_acquire=not self._always_checkpoint), + None, + ) + cache_entry[key] = cached_value, lock, expires_at + else: + # The value was already cached + self._hits += 1 + cache_entry.move_to_end(key) + if self._always_checkpoint: + await checkpoint() + + return cast(T, cached_value) + + async with lock: + # Check if another task filled the cache while we acquired the lock + if (cached_value := cache_entry[key][0]) is initial_missing: + self._misses += 1 + if self._maxsize is not None and self._currsize >= self._maxsize: + cache_entry.popitem(last=False) + else: + self._currsize += 1 + + value = await self.__wrapped__(*args, **kwargs) + expires_at = ( + current_time() + self._ttl if self._ttl is not None else None + ) + cache_entry[key] = value, None, expires_at + else: + # Another task filled the cache while we were waiting for the lock + self._hits += 1 + cache_entry.move_to_end(key) + value = cast(T, cached_value) + + return value + + def __get__( + self, instance: object, owner: type | None = None + ) -> _LRUMethodWrapper[T]: + wrapper = _LRUMethodWrapper(self, instance) + update_wrapper(wrapper, self.__wrapped__) + return wrapper + + +class _LRUCacheWrapper: + def __init__( + self, maxsize: int | None, typed: bool, always_checkpoint: bool, ttl: int | None + ): + self._maxsize = maxsize + self._typed = typed + self._always_checkpoint = always_checkpoint + self._ttl = ttl + + @overload + def __call__( # type: ignore[overload-overlap] + self, func: Callable[P, Coroutine[Any, Any, T]], / + ) -> AsyncLRUCacheWrapper[P, T]: ... + + @overload + def __call__( + self, func: Callable[..., T], / + ) -> functools._lru_cache_wrapper[T]: ... + + def __call__( + self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], / + ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]: + if iscoroutinefunction(f): + return AsyncLRUCacheWrapper( + f, self._maxsize, self._typed, self._always_checkpoint, self._ttl + ) + + return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type] + + +@overload +def cache( # type: ignore[overload-overlap] + func: Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T]: ... + + +@overload +def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... + + +def cache(func: Callable[..., Any] | Callable[P, Coroutine[Any, Any, Any]], /) -> Any: + """ + A convenient shortcut for :func:`lru_cache` with ``maxsize=None``. + + This is the asynchronous equivalent to :func:`functools.cache`. + + """ + return lru_cache(maxsize=None)(func) + + +@overload +def lru_cache( + *, + maxsize: int | None = ..., + typed: bool = ..., + always_checkpoint: bool = ..., + ttl: int | None = ..., +) -> _LRUCacheWrapper: ... + + +@overload +def lru_cache( # type: ignore[overload-overlap] + func: Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T]: ... + + +@overload +def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... + + +def lru_cache( + func: Callable[..., Coroutine[Any, Any, Any]] | Callable[..., Any] | None = None, + /, + *, + maxsize: int | None = 128, + typed: bool = False, + always_checkpoint: bool = False, + ttl: int | None = None, +) -> Any: + """ + An asynchronous version of :func:`functools.lru_cache`. + + If a synchronous function is passed, the standard library + :func:`functools.lru_cache` is applied instead. + + :param always_checkpoint: if ``True``, every call to the cached function will be + guaranteed to yield control to the event loop at least once + :param ttl: time in seconds after which to invalidate cache entries + + .. note:: Caches and locks are managed on a per-event loop basis. + + """ + if func is None: + return _LRUCacheWrapper(maxsize, typed, always_checkpoint, ttl) + + if not callable(func): + raise TypeError("the first argument must be callable") + + return _LRUCacheWrapper(maxsize, typed, always_checkpoint, ttl)(func) + + +@overload +async def reduce( + function: Callable[[T, S], Awaitable[T]], + iterable: Iterable[S] | AsyncIterable[S], + /, + initial: T, +) -> T: ... + + +@overload +async def reduce( + function: Callable[[T, T], Awaitable[T]], + iterable: Iterable[T] | AsyncIterable[T], + /, +) -> T: ... + + +async def reduce( # type: ignore[misc] + function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]], + iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S], + /, + initial: T | _InitialMissingType = initial_missing, +) -> T: + """ + Asynchronous version of :func:`functools.reduce`. + + :param function: a coroutine function that takes two arguments: the accumulated + value and the next element from the iterable + :param iterable: an iterable or async iterable + :param initial: the initial value (if missing, the first element of the iterable is + used as the initial value) + + """ + element: Any + function_called = False + if isinstance(iterable, AsyncIterable): + async_it = iterable.__aiter__() + if initial is initial_missing: + try: + value = cast(T, await async_it.__anext__()) + except StopAsyncIteration: + raise TypeError( + "reduce() of empty sequence with no initial value" + ) from None + else: + value = cast(T, initial) + + async for element in async_it: + value = await function(value, element) + function_called = True + elif isinstance(iterable, Iterable): + it = iter(iterable) + if initial is initial_missing: + try: + value = cast(T, next(it)) + except StopIteration: + raise TypeError( + "reduce() of empty sequence with no initial value" + ) from None + else: + value = cast(T, initial) + + for element in it: + value = await function(value, element) + function_called = True + else: + raise TypeError("reduce() argument 2 must be an iterable or async iterable") + + # Make sure there is at least one checkpoint, even if an empty iterable and an + # initial value were given + if not function_called: + await checkpoint() + + return value diff --git a/.venv/lib/python3.12/site-packages/anyio/itertools.py b/.venv/lib/python3.12/site-packages/anyio/itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..2a10cfd3ba01b22f424d18accaf9758233a67cca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/itertools.py @@ -0,0 +1,629 @@ +from __future__ import annotations + +__all__ = ( + "Chain", + "accumulate", + "batched", + "combinations", + "combinations_with_replacement", + "compress", + "count", + "cycle", + "dropwhile", + "filterfalse", + "groupby", + "islice", + "pairwise", + "permutations", + "product", + "repeat", + "starmap", + "takewhile", + "tee", + "zip_longest", +) + +import itertools +import operator +import sys +from collections.abc import ( + AsyncGenerator, + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Iterable, + Iterator, +) +from dataclasses import dataclass, field +from typing import Any, Generic, TypeVar, cast, overload + +from ._core._synchronization import Lock +from ._core._tasks import CancelScope +from .lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled + +if sys.version_info < (3, 15): + from typing_extensions import sentinel + +T = TypeVar("T") +R = TypeVar("R") +_tee_end = sentinel("_tee_end") + + +@dataclass(eq=False) +class _IterableAsyncIterator(AsyncIterator[T]): + iterator: Iterator[T] + + async def __anext__(self) -> T: + await checkpoint_if_cancelled() + try: + result = next(self.iterator) + except StopIteration: + await cancel_shielded_checkpoint() + raise StopAsyncIteration from None + + await cancel_shielded_checkpoint() + return result + + +def _iterate(iterable: Iterable[T] | AsyncIterable[T]) -> AsyncIterator[T]: + if isinstance(iterable, AsyncIterator): + return iterable + + if isinstance(iterable, AsyncIterable): + return iterable.__aiter__() + + return _IterableAsyncIterator(iter(iterable)) + + +@dataclass(eq=False) +class _TeeLink(Generic[T]): + value: object | None = None + next: _TeeLink[T] | None = None + filled: bool = False + + +@dataclass(eq=False) +class _TeeState(Generic[T]): + iterator: AsyncIterator[T] + lock: Lock = field(default_factory=Lock) + + async def fill(self, link: _TeeLink[T]) -> bool: + if link.filled: + return False + + async with self.lock: + if link.filled: + return True + + link.value = await anext(self.iterator, _tee_end) + if link.value is not _tee_end: + link.next = _TeeLink() + + link.filled = True + return True + + +class _TeeAsyncIterator(AsyncIterator[T]): + _state: _TeeState[T] + _link: _TeeLink[T] + _element_yielded: bool + + def __init__( + self, iterable: Iterable[T] | AsyncIterable[T] | _TeeAsyncIterator[T] + ) -> None: + if isinstance(iterable, _TeeAsyncIterator): + self._state = iterable._state + self._link = iterable._link + else: + self._state = _TeeState(_iterate(iterable)) + self._link = _TeeLink() + + self._element_yielded = False + + async def __anext__(self) -> T: + had_yieldpoint = await self._state.fill(self._link) + if self._link.value is _tee_end: + if not self._element_yielded: + await checkpoint() + + raise StopAsyncIteration + + if not had_yieldpoint: + await checkpoint_if_cancelled() + + self._element_yielded = True + value = cast(T, self._link.value) + next_link = self._link.next + assert next_link is not None + self._link = next_link + if not had_yieldpoint: + await cancel_shielded_checkpoint() + + return value + + +async def _operator_add(x: T, y: T) -> T: + return operator.add(x, y) + + +async def accumulate( + iterable: Iterable[T] | AsyncIterable[T], + function: Callable[[T, T], Awaitable[T]] = _operator_add, + *, + initial: T | None = None, +) -> AsyncGenerator[T, None]: + iterator = _iterate(iterable) + if initial is None: + try: + total = await anext(iterator) + except StopAsyncIteration: + await checkpoint() + return + else: + await checkpoint_if_cancelled() + total = initial + await cancel_shielded_checkpoint() + + yield total + + async for element in iterator: + total = await function(total, element) + yield total + + +async def batched( + iterable: Iterable[T] | AsyncIterable[T], n: int, *, strict: bool = False +) -> AsyncGenerator[tuple[T, ...], None]: + if n < 1: + raise ValueError("n must be at least one") + + iterator = _iterate(iterable) + + while True: + batch: list[T] = [] + for _ in range(n): + try: + batch.append(await anext(iterator)) + except StopAsyncIteration: + if not batch: + await checkpoint() + return + if strict: + raise ValueError("batched(): incomplete batch") from None + + yield tuple(batch) + return + + yield tuple(batch) + + +class Chain: + def __call__( + self, *iterables: Iterable[T] | AsyncIterable[T] + ) -> AsyncGenerator[T, None]: + return self.from_iterable(iterables) + + async def from_iterable( + self, + iterables: ( + Iterable[Iterable[T] | AsyncIterable[T]] + | AsyncIterable[Iterable[T] | AsyncIterable[T]] + ), + ) -> AsyncGenerator[T, None]: + element_yielded = False + outer_iter = _iterate(iterables) + + try: + async for iterable in outer_iter: + async for element in _iterate(iterable): + element_yielded = True + yield element + finally: + aclose = getattr(outer_iter, "aclose", None) + if aclose is not None: + with CancelScope(shield=True): + await aclose() + + if not element_yielded: + await checkpoint() + + +chain: Chain = Chain() + + +async def combinations( + iterable: Iterable[T] | AsyncIterable[T], r: int +) -> AsyncGenerator[tuple[T, ...], None]: + pool: list[T] = [element async for element in _iterate(iterable)] + async for combination in _iterate(itertools.combinations(pool, r)): + yield combination + + +async def combinations_with_replacement( + iterable: Iterable[T] | AsyncIterable[T], r: int +) -> AsyncGenerator[tuple[T, ...], None]: + pool: list[T] = [element async for element in _iterate(iterable)] + async for combination in _iterate(itertools.combinations_with_replacement(pool, r)): + yield combination + + +async def compress( + data: Iterable[T] | AsyncIterable[T], + selectors: Iterable[object] | AsyncIterable[object], +) -> AsyncGenerator[T, None]: + data_iterator = _iterate(data) + selector_iterator = _iterate(selectors) + element_yielded = False + + while True: + try: + datum = await anext(data_iterator) + selector = await anext(selector_iterator) + except StopAsyncIteration: + if not element_yielded: + await checkpoint() + + return + + if selector: + element_yielded = True + yield datum + + +async def count(start: int = 0, step: int = 1) -> AsyncGenerator[int, None]: + n = start + while True: + await checkpoint_if_cancelled() + value = n + n += step + await cancel_shielded_checkpoint() + yield value + + +async def cycle( + iterable: Iterable[T] | AsyncIterable[T], +) -> AsyncGenerator[T, None]: + saved: list[T] = [] + async for element in _iterate(iterable): + saved.append(element) + yield element + + if not saved: + await checkpoint() + return + + while True: + for element in saved: + await checkpoint() + yield element + + +async def dropwhile( + predicate: Callable[[T], Awaitable[object]], + iterable: Iterable[T] | AsyncIterable[T], +) -> AsyncGenerator[T, None]: + element_yielded = False + dropping = True + + async for element in _iterate(iterable): + if dropping and await predicate(element): + continue + + dropping = False + element_yielded = True + yield element + + if not element_yielded: + await checkpoint() + + +async def filterfalse( + predicate: Callable[[T], Awaitable[object]], + iterable: Iterable[T] | AsyncIterable[T], +) -> AsyncGenerator[T, None]: + element_yielded = False + + async for element in _iterate(iterable): + if not await predicate(element): + element_yielded = True + yield element + + if not element_yielded: + await checkpoint() + + +@overload +def groupby( + iterable: Iterable[T] | AsyncIterable[T], +) -> AsyncGenerator[tuple[T, list[T]], None]: ... + + +@overload +def groupby( + iterable: Iterable[T] | AsyncIterable[T], + key: Callable[[T], Awaitable[R]], +) -> AsyncGenerator[tuple[R, list[T]], None]: ... + + +async def groupby( + iterable: Iterable[T] | AsyncIterable[T], + key: Callable[[T], Awaitable[object]] | None = None, +) -> AsyncGenerator[tuple[object, list[T]], None]: + iterator = _iterate(iterable) + try: + element = await anext(iterator) + except StopAsyncIteration: + await checkpoint() + return + + group_key = element if key is None else await key(element) + values = [element] + + async for element in iterator: + next_key = element if key is None else await key(element) + if next_key != group_key: + completed_group = group_key, values + group_key = next_key + values = [element] + yield completed_group + else: + values.append(element) + + yield group_key, values + + +@overload +def islice( + iterable: Iterable[T] | AsyncIterable[T], + stop: int | None, + /, +) -> AsyncGenerator[T, None]: ... + + +@overload +def islice( + iterable: Iterable[T] | AsyncIterable[T], + start: int | None, + stop: int | None, + step: int | None = 1, + /, +) -> AsyncGenerator[T, None]: ... + + +async def islice( + iterable: Iterable[T] | AsyncIterable[T], + *args: int | None, +) -> AsyncGenerator[T, None]: + if not args: + raise TypeError("islice expected at least 2 arguments, got 1") + if len(args) > 3: + raise TypeError(f"islice expected at most 4 arguments, got {len(args) + 1}") + + slice_args = slice(*args) + + start_message = ( + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize." + ) + stop_message = ( + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." + ) + step_message = "Step for islice() must be a positive integer or None." + + def normalize_index(value: object, message: str) -> int: + try: + index = operator.index(cast(Any, value)) + except TypeError: + raise ValueError(message) from None + + if index < 0 or index > sys.maxsize: + raise ValueError(message) + + return index + + start = ( + 0 + if slice_args.start is None + else normalize_index(slice_args.start, start_message) + ) + stop = ( + None + if slice_args.stop is None + else normalize_index(slice_args.stop, stop_message) + ) + step = ( + 1 if slice_args.step is None else normalize_index(slice_args.step, step_message) + ) + + if step <= 0: + raise ValueError(step_message) + + if stop == 0 or start == stop: + await checkpoint() + return + + iterator = _iterate(iterable) + index = 0 + element_yielded = False + + while stop is None or index < stop: + try: + element = await anext(iterator) + except StopAsyncIteration: + if not element_yielded: + await checkpoint() + + return + + if index >= start and (index - start) % step == 0: + index += 1 + element_yielded = True + yield element + else: + index += 1 + + if not element_yielded: + await checkpoint() + + +async def pairwise( + iterable: Iterable[T] | AsyncIterable[T], +) -> AsyncGenerator[tuple[T, T], None]: + iterator = _iterate(iterable) + try: + previous = await anext(iterator) + except StopAsyncIteration: + await checkpoint() + return + + element_yielded = False + async for element in iterator: + element_yielded = True + pair = (previous, element) + previous = element + yield pair + + if not element_yielded: + await checkpoint() + + +async def permutations( + iterable: Iterable[T] | AsyncIterable[T], r: int | None = None +) -> AsyncGenerator[tuple[T, ...], None]: + pool: list[T] = [element async for element in _iterate(iterable)] + n = len(pool) + if r is None: + r = n + elif not isinstance(r, int): + raise TypeError("Expected int as r") + elif r < 0: + raise ValueError("r must be non-negative") + + async for permutation in _iterate(itertools.permutations(pool, r)): + yield permutation + + +async def product( + *iterables: Iterable[T] | AsyncIterable[T], repeat: int = 1 +) -> AsyncGenerator[tuple[T, ...], None]: + repeat = operator.index(repeat) + if repeat < 0: + raise ValueError("repeat argument cannot be negative") + + pools: list[tuple[T, ...]] = [] + for iterable in iterables: + pool: list[T] = [element async for element in _iterate(iterable)] + pools.append(tuple(pool)) + + async for value in _iterate(itertools.product(*pools, repeat=repeat)): + yield value + + +async def repeat(element: T, times: int | None = None) -> AsyncGenerator[T, None]: + if times is None: + while True: + await checkpoint() + yield element + + remaining = operator.index(cast(Any, times)) + if remaining <= 0: + await checkpoint() + return + + while remaining > 0: + await checkpoint_if_cancelled() + remaining -= 1 + await cancel_shielded_checkpoint() + yield element + + +async def starmap( + function: Callable[..., Awaitable[R]], + iterable: ( + Iterable[Iterable[object] | AsyncIterable[object]] + | AsyncIterable[Iterable[object] | AsyncIterable[object]] + ), +) -> AsyncGenerator[R, None]: + result_yielded = False + + async for args_iterable in _iterate(iterable): + args = [element async for element in _iterate(args_iterable)] + result_yielded = True + yield await function(*args) + + if not result_yielded: + await checkpoint() + + +def tee( + iterable: Iterable[T] | AsyncIterable[T], n: int = 2 +) -> tuple[AsyncIterator[T], ...]: + n = operator.index(cast(Any, n)) + if n < 0: + raise ValueError("n must be >= 0") + if n == 0: + return () + + iterator = _TeeAsyncIterator(iterable) + iterators: list[AsyncIterator[T]] = [iterator] + iterators.extend(_TeeAsyncIterator(iterator) for _ in range(n - 1)) + return tuple(iterators) + + +async def takewhile( + predicate: Callable[[T], Awaitable[object]], + iterable: Iterable[T] | AsyncIterable[T], +) -> AsyncGenerator[T, None]: + element_yielded = False + + async for element in _iterate(iterable): + if not await predicate(element): + if not element_yielded: + await checkpoint() + + return + + element_yielded = True + yield element + + if not element_yielded: + await checkpoint() + + +async def zip_longest( + *iterables: Iterable[object] | AsyncIterable[object], + fillvalue: object = None, +) -> AsyncGenerator[tuple[object, ...], None]: + iterators = [_iterate(iterable) for iterable in iterables] + num_active = len(iterators) + if not num_active: + await checkpoint() + return + + active = [True] * num_active + tuple_yielded = False + + while True: + values: list[object] = [] + for index, iterator in enumerate(iterators): + if not active[index]: + values.append(fillvalue) + continue + + try: + value = await anext(iterator) + except StopAsyncIteration: + active[index] = False + num_active -= 1 + if not num_active: + if not tuple_yielded: + await checkpoint() + + return + + value = fillvalue + + values.append(value) + + tuple_yielded = True + yield tuple(values) diff --git a/.venv/lib/python3.12/site-packages/anyio/lowlevel.py b/.venv/lib/python3.12/site-packages/anyio/lowlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..361b2eb84d3600e8c64afe9b010825fd2b8c5288 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/lowlevel.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +__all__ = ( + "EventLoopToken", + "RunVar", + "RunvarToken", + "cancel_shielded_checkpoint", + "checkpoint", + "checkpoint_if_cancelled", + "current_token", +) + +import enum +from dataclasses import dataclass +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, final, overload +from weakref import WeakKeyDictionary + +from ._core._eventloop import get_async_backend + +if TYPE_CHECKING: + from .abc import AsyncBackend + +T = TypeVar("T") +D = TypeVar("D") + + +async def checkpoint() -> None: + """ + Check for cancellation and allow the scheduler to switch to another task. + + Equivalent to (but more efficient than):: + + await checkpoint_if_cancelled() + await cancel_shielded_checkpoint() + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint() + + +async def checkpoint_if_cancelled() -> None: + """ + Enter a checkpoint if the enclosing cancel scope has been cancelled. + + This does not allow the scheduler to switch to a different task. + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint_if_cancelled() + + +async def cancel_shielded_checkpoint() -> None: + """ + Allow the scheduler to switch to another task but without checking for cancellation. + + Equivalent to (but potentially more efficient than):: + + with CancelScope(shield=True): + await checkpoint() + + .. versionadded:: 3.0 + + """ + await get_async_backend().cancel_shielded_checkpoint() + + +@final +@dataclass(frozen=True, repr=False) +class EventLoopToken: + """ + An opaque object that holds a reference to an event loop. + + .. versionadded:: 4.11.0 + """ + + backend_class: type[AsyncBackend] + native_token: object + + +def current_token() -> EventLoopToken: + """ + Return a token object that can be used to call code in the current event loop from + another thread. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. versionadded:: 4.11.0 + + """ + backend_class = get_async_backend() + raw_token = backend_class.current_token() + return EventLoopToken(backend_class, raw_token) + + +_run_vars: WeakKeyDictionary[object, dict[RunVar[Any], Any]] = WeakKeyDictionary() + + +class _NoValueSet(enum.Enum): + NO_VALUE_SET = enum.auto() + + +class RunvarToken(Generic[T]): + """ + A token that can be used to restore a :class:`RunVar` to its previous value. + + Returned by :meth:`RunVar.set`. Can be used as a context manager to automatically + reset the variable on exit, or passed directly to :meth:`RunVar.reset`. + """ + + __slots__ = "_redeemed", "_value", "_var" + + def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]): + self._var = var + self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value + self._redeemed = False + + def __enter__(self) -> RunvarToken[T]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._var.reset(self) + + +class RunVar(Generic[T]): + """ + Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop. + + Can be used as a context manager, Just like :class:`~contextvars.ContextVar`, that + will reset the variable to its previous value when the context block is exited. + """ + + __slots__ = "_default", "_name" + + NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET + + def __init__( + self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ): + self._name = name + self._default = default + + @property + def _current_vars(self) -> dict[RunVar[T], T]: + native_token = current_token().native_token + try: + return _run_vars[native_token] + except KeyError: + run_vars = _run_vars[native_token] = {} + return run_vars + + @overload + def get(self, default: D) -> T | D: ... + + @overload + def get(self) -> T: ... + + def get( + self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ) -> T | D: + """ + Return the current value of this run variable. + + :param default: a fallback value to return if no value has been set + :return: the current value, the provided default, or the variable's own default + :raises LookupError: if no value is set and no default is available + + """ + try: + return self._current_vars[self] + except KeyError: + if default is not RunVar.NO_VALUE_SET: + return default + elif self._default is not RunVar.NO_VALUE_SET: + return self._default + + raise LookupError( + f'Run variable "{self._name}" has no value and no default set' + ) + + def set(self, value: T) -> RunvarToken[T]: + """ + Set the value of this run variable for the current event loop. + + :param value: the new value + :return: a token that can be used to restore the previous value + + """ + current_vars = self._current_vars + token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET)) + current_vars[self] = value + return token + + def reset(self, token: RunvarToken[T]) -> None: + """ + Restore this run variable to the value it held before the matching :meth:`set`. + + :param token: the token returned by :meth:`set` + :raises ValueError: if the token belongs to a different :class:`RunVar` or the token + has already been used + + """ + if token._var is not self: + raise ValueError("This token does not belong to this RunVar") + + if token._redeemed: + raise ValueError("This token has already been used") + + if token._value is _NoValueSet.NO_VALUE_SET: + try: + del self._current_vars[self] + except KeyError: + pass + else: + self._current_vars[self] = token._value + + token._redeemed = True + + def __repr__(self) -> str: + return f"" diff --git a/.venv/lib/python3.12/site-packages/anyio/py.typed b/.venv/lib/python3.12/site-packages/anyio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/anyio/pytest_plugin.py b/.venv/lib/python3.12/site-packages/anyio/pytest_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..d6238cd110ab793ccccb9671fc7eccc33c5415e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/pytest_plugin.py @@ -0,0 +1,404 @@ +from __future__ import annotations + +import dataclasses +import socket +import sys +from collections.abc import Callable, Generator, Iterator +from contextlib import ExitStack, contextmanager +from inspect import isasyncgenfunction, iscoroutinefunction, ismethod +from typing import TYPE_CHECKING, Any, cast + +import pytest +from _pytest.fixtures import FuncFixtureInfo, SubRequest +from _pytest.outcomes import Exit +from _pytest.scope import Scope + +from . import get_available_backends +from ._core._eventloop import ( + current_async_library, + get_async_backend, + reset_current_async_library, + set_current_async_library, +) +from ._core._exceptions import iterate_exceptions + +if TYPE_CHECKING: + from .abc import TestRunner + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +if TYPE_CHECKING: + # pytest >= 9.2 keeps CallSpec2 as a TYPE_CHECKING-only alias of CallSpec + from _pytest.python import CallSpec2 as CallSpec +else: + try: + # c.f. https://github.com/pytest-dev/pytest/pull/14742 + # pytest >= 9.2 + from _pytest.python import CallSpec + except ImportError: + from _pytest.python import CallSpec2 as CallSpec + +_current_runner: TestRunner | None = None +_runner_stack: ExitStack | None = None +_runner_leases = 0 + + +def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]: + if isinstance(backend, str): + return backend, {} + elif isinstance(backend, tuple) and len(backend) == 2: + if isinstance(backend[0], str) and isinstance(backend[1], dict): + return cast(tuple[str, dict[str, Any]], backend) + + raise TypeError("anyio_backend must be either a string or tuple of (string, dict)") + + +@contextmanager +def get_runner( + backend_name: str, backend_options: dict[str, Any] +) -> Iterator[TestRunner]: + global _current_runner, _runner_leases, _runner_stack + if _current_runner is None: + asynclib = get_async_backend(backend_name) + _runner_stack = ExitStack() + if current_async_library() is None: + # Since we're in control of the event loop, we can cache the name of the + # async library + token = set_current_async_library(backend_name) + _runner_stack.callback(reset_current_async_library, token) + + backend_options = backend_options or {} + _current_runner = _runner_stack.enter_context( + asynclib.create_test_runner(backend_options) + ) + + _runner_leases += 1 + try: + yield _current_runner + finally: + _runner_leases -= 1 + if not _runner_leases: + assert _runner_stack is not None + _runner_stack.close() + _runner_stack = _current_runner = None + + +def pytest_addoption(parser: pytest.Parser) -> None: + group = parser.getgroup("anyio") + parser.addini( + "anyio_mode", + default="strict", + help='AnyIO plugin mode (either "strict" or "auto")', + ) + group.addoption( + "--anyio-mode", + default=None, + dest="anyio_mode", + help=""" + 'auto' - All async test functions will be handled by AnyIO pytest plugin + 'strict' - Disabling autoprocessing(useful when anyio tests + need to coexist with other async test plugins) + """, + ) + + +def _is_auto_mode(config: pytest.Config, mode: str) -> bool: + return ( + config.getoption(mode, default=None) == "auto" or config.getini(mode) == "auto" + ) + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line( + "markers", + "anyio: mark the (coroutine function) test to be run asynchronously via anyio.", + ) + if ( + _is_auto_mode(config, "anyio_mode") + and config.pluginmanager.has_plugin("asyncio") + and _is_auto_mode(config, "asyncio_mode") + ): + config.issue_config_time_warning( + pytest.PytestConfigWarning( + "AnyIO auto mode has been enabled together with pytest-asyncio auto " + "mode. This may cause unexpected behavior." + ), + 1, + ) + + +@pytest.hookimpl(hookwrapper=True) +def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]: + def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any: + # Rebind any fixture methods to the request instance + if ( + request.instance + and ismethod(func) + and type(func.__self__) is type(request.instance) + ): + local_func = func.__func__.__get__(request.instance) + else: + local_func = func + + backend_name, backend_options = extract_backend_and_options(anyio_backend) + if has_backend_arg: + kwargs["anyio_backend"] = anyio_backend + + if has_request_arg: + kwargs["request"] = request + + with get_runner(backend_name, backend_options) as runner: + # re-entrant call into the test runner detected. this happens when an async fixture + # is dynamically requested via request.getfixturevalue() from inside a running async + # test or fixture. on asyncio this raises RuntimeError: This event loop is already + # running, on trio the runner deadlocks - the host loop blocks waiting for the + # coroutine to return, but the coroutine is waiting for the host loop. raising here + # prevents the hang and gives a consistent error across backends. + if runner.is_running(): + raise RuntimeError( + "Cannot schedule a coroutine in the test runner while another is already running; " + "likely caused by request.getfixturevalue() on an async fixture." + ) + + if isasyncgenfunction(local_func): + yield from runner.run_asyncgen_fixture(local_func, kwargs) + else: + yield runner.run_fixture(local_func, kwargs) + + # Only apply this to coroutine functions and async generator functions in requests + # that involve the anyio_backend fixture + func = fixturedef.func + if isasyncgenfunction(func) or iscoroutinefunction(func): + if "anyio_backend" in request.fixturenames: + fixturedef.func = wrapper + original_argname = fixturedef.argnames + + if not (has_backend_arg := "anyio_backend" in fixturedef.argnames): + fixturedef.argnames += ("anyio_backend",) + + if not (has_request_arg := "request" in fixturedef.argnames): + fixturedef.argnames += ("request",) + + try: + return (yield) + finally: + fixturedef.func = func + fixturedef.argnames = original_argname + + return (yield) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pycollect_makeitem( + collector: pytest.Module | pytest.Class, name: str, obj: object +) -> None: + if collector.istestfunction(obj, name): + inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj + if iscoroutinefunction(inner_func): + anyio_auto_mode = _is_auto_mode(collector.config, "anyio_mode") + marker = collector.get_closest_marker("anyio") + own_markers = getattr(obj, "pytestmark", ()) + if ( + anyio_auto_mode + or marker + or any(marker.name == "anyio" for marker in own_markers) + ): + pytest.mark.usefixtures("anyio_backend")(obj) + + +def pytest_collection_finish(session: pytest.Session) -> None: + for i, item in reversed(list(enumerate(session.items))): + if ( + isinstance(item, pytest.Function) + and iscoroutinefunction(item.function) + and item.get_closest_marker("anyio") is not None + and "anyio_backend" not in item.fixturenames + ): + new_items = [] + try: + cs_fields = {f.name for f in dataclasses.fields(CallSpec)} + except TypeError: + cs_fields = set() + + for param_index, backend in enumerate(get_available_backends()): + if "_arg2scope" in cs_fields: # pytest >= 8 + callspec = CallSpec( + params={"anyio_backend": backend}, + indices={"anyio_backend": param_index}, + _arg2scope={"anyio_backend": Scope.Module}, + _idlist=[backend], + marks=[], + ) + else: # pytest 7.x + callspec = CallSpec( # type: ignore[call-arg] + funcargs={}, + params={"anyio_backend": backend}, + indices={"anyio_backend": param_index}, + arg2scope={"anyio_backend": Scope.Module}, + idlist=[backend], + marks=[], + ) + + fi = item._fixtureinfo + new_names_closure = list(fi.names_closure) + if "anyio_backend" not in new_names_closure: + new_names_closure.append("anyio_backend") + + new_fixtureinfo = FuncFixtureInfo( + argnames=fi.argnames, + initialnames=fi.initialnames, + names_closure=new_names_closure, + name2fixturedefs=fi.name2fixturedefs, + ) + new_item = pytest.Function.from_parent( + item.parent, + name=f"{item.originalname}[{backend}]", + callspec=callspec, + callobj=item.obj, + fixtureinfo=new_fixtureinfo, + keywords=item.keywords, + originalname=item.originalname, + ) + new_items.append(new_item) + + session.items[i : i + 1] = new_items + + +@pytest.hookimpl(tryfirst=True) +def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None: + def run_with_hypothesis(**kwargs: Any) -> None: + with get_runner(backend_name, backend_options) as runner: + runner.run_test(original_func, kwargs) + + backend = pyfuncitem.funcargs.get("anyio_backend") + if backend: + backend_name, backend_options = extract_backend_and_options(backend) + + if hasattr(pyfuncitem.obj, "hypothesis"): + # Wrap the inner test function unless it's already wrapped + original_func = pyfuncitem.obj.hypothesis.inner_test + if original_func.__qualname__ != run_with_hypothesis.__qualname__: + if iscoroutinefunction(original_func): + pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis + + return None + + if iscoroutinefunction(pyfuncitem.obj): + funcargs = pyfuncitem.funcargs + testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} + with get_runner(backend_name, backend_options) as runner: + try: + runner.run_test(pyfuncitem.obj, testargs) + except ExceptionGroup as excgrp: + for exc in iterate_exceptions(excgrp): + if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)): + raise exc from excgrp + + raise + + return True + + return None + + +@pytest.fixture(scope="module", params=get_available_backends()) +def anyio_backend(request: Any) -> Any: + return request.param + + +@pytest.fixture +def anyio_backend_name(anyio_backend: Any) -> str: + if isinstance(anyio_backend, str): + return anyio_backend + else: + return anyio_backend[0] + + +@pytest.fixture +def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]: + if isinstance(anyio_backend, str): + return {} + else: + return anyio_backend[1] + + +class FreePortFactory: + """ + Manages port generation based on specified socket kind, ensuring no duplicate + ports are generated. + + This class provides functionality for generating available free ports on the + system. It is initialized with a specific socket kind and can generate ports + for given address families while avoiding reuse of previously generated ports. + + Users should not instantiate this class directly, but use the + ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple + uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead. + """ + + def __init__(self, kind: socket.SocketKind) -> None: + self._kind = kind + self._generated = set[int]() + + @property + def kind(self) -> socket.SocketKind: + """ + The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or + :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability + + """ + return self._kind + + def __call__(self, family: socket.AddressFamily | None = None) -> int: + """ + Return an unbound port for the given address family. + + :param family: if omitted, both IPv4 and IPv6 addresses will be tried + :return: a port number + + """ + if family is not None: + families = [family] + else: + families = [socket.AF_INET] + if socket.has_ipv6: + families.append(socket.AF_INET6) + + while True: + port = 0 + with ExitStack() as stack: + for fam in families: + sock = stack.enter_context(socket.socket(fam, self._kind)) + addr = "::1" if fam == socket.AF_INET6 else "127.0.0.1" + try: + sock.bind((addr, port)) + except OSError: + break + + if not port: + port = sock.getsockname()[1] + else: + if port not in self._generated: + self._generated.add(port) + return port + + +@pytest.fixture(scope="session") +def free_tcp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_STREAM) + + +@pytest.fixture(scope="session") +def free_udp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_DGRAM) + + +@pytest.fixture +def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int: + return free_tcp_port_factory() + + +@pytest.fixture +def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int: + return free_udp_port_factory() diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__init__.py b/.venv/lib/python3.12/site-packages/anyio/streams/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312-pytest-9.1.1.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87affb0bb6f460e74f750edf09532e615be8e52c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312-pytest-9.1.1.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87affb0bb6f460e74f750edf09532e615be8e52c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/buffered.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/buffered.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..709196b697d7e12736e1cccc320fac332dd06470 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/buffered.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/file.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/file.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..598d650dbf2914158bcfa985813de83f37689ceb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/file.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312-pytest-9.1.1.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b5ec8c4d8e215347bc2d507fcb005311b4c99b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312-pytest-9.1.1.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98d87ecc78572b1f29449a4a1a839f0d2d240023 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312-pytest-9.1.1.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25722e4d2d44fe1da46a2fa558d1d6717011e601 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312-pytest-9.1.1.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92e2e25109a1d5e79846af5a64bf11fad0233a76 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/text.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a117a82cf6e13ee7bd758c2df406163ce65333f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/text.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312-pytest-9.1.1.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a6c17b553b50d1157c0a982823bfb2a85de629c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312-pytest-9.1.1.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2a751cdeee168c226f60ede0bca9e3946eb584a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/buffered.py b/.venv/lib/python3.12/site-packages/anyio/streams/buffered.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b07f73ac44d5876c239fd0317846564ef06f91 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/streams/buffered.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +__all__ = ( + "BufferedByteReceiveStream", + "BufferedByteStream", + "BufferedConnectable", +) + +import sys +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import Any, SupportsIndex + +from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead +from ..abc import ( + AnyByteReceiveStream, + AnyByteStream, + AnyByteStreamConnectable, + ByteReceiveStream, + ByteStream, + ByteStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class BufferedByteReceiveStream(ByteReceiveStream): + """ + Wraps any bytes-based receive stream and uses a buffer to provide sophisticated + receiving capabilities in the form of a byte stream. + """ + + receive_stream: AnyByteReceiveStream + _buffer: bytearray = field(init=False, default_factory=bytearray) + _closed: bool = field(init=False, default=False) + + async def aclose(self) -> None: + await self.receive_stream.aclose() + self._closed = True + + @property + def buffer(self) -> bytes: + """The bytes currently in the buffer.""" + return bytes(self._buffer) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.receive_stream.extra_attributes + + def feed_data(self, data: Iterable[SupportsIndex], /) -> None: + """ + Append data directly into the buffer. + + Any data in the buffer will be consumed by receive operations before receiving + anything from the wrapped stream. + + :param data: the data to append to the buffer (can be bytes or anything else + that supports ``__index__()``) + + """ + self._buffer.extend(data) + + async def receive(self, max_bytes: int = 65536) -> bytes: + if max_bytes < 1: + raise ValueError("max_bytes must be a positive integer") + + if self._closed: + raise ClosedResourceError + + if self._buffer: + chunk = bytes(self._buffer[:max_bytes]) + del self._buffer[:max_bytes] + return chunk + elif isinstance(self.receive_stream, ByteReceiveStream): + return await self.receive_stream.receive(max_bytes) + else: + # With a bytes-oriented object stream, we need to handle any surplus bytes + # we get from the receive() call + chunk = await self.receive_stream.receive() + if len(chunk) > max_bytes: + # Save the surplus bytes in the buffer + self._buffer.extend(chunk[max_bytes:]) + return chunk[:max_bytes] + else: + return chunk + + async def receive_exactly(self, nbytes: int) -> bytes: + """ + Read exactly the given amount of bytes from the stream. + + :param nbytes: the number of bytes to read + :return: the bytes read + :raises ~anyio.IncompleteRead: if the stream was closed before the requested + amount of bytes could be read from the stream + + """ + while True: + remaining = nbytes - len(self._buffer) + if remaining <= 0: + retval = self._buffer[:nbytes] + del self._buffer[:nbytes] + return bytes(retval) + + try: + if isinstance(self.receive_stream, ByteReceiveStream): + chunk = await self.receive_stream.receive(remaining) + else: + chunk = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + self._buffer.extend(chunk) + + async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes: + """ + Read from the stream until the delimiter is found or max_bytes have been read. + + :param delimiter: the marker to look for in the stream + :param max_bytes: maximum number of bytes that will be read before raising + :exc:`~anyio.DelimiterNotFound` + :return: the bytes read (not including the delimiter) + :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter + was found + :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the + bytes read up to the maximum allowed + + """ + delimiter_size = len(delimiter) + offset = 0 + while True: + # Check if the delimiter can be found in the current buffer + index = self._buffer.find(delimiter, offset) + if index >= 0: + found = self._buffer[:index] + del self._buffer[: index + len(delimiter) :] + return bytes(found) + + # Check if the buffer is already at or over the limit + if len(self._buffer) >= max_bytes: + raise DelimiterNotFound(max_bytes) + + # Read more data into the buffer from the socket + try: + data = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + # Move the offset forward and add the new data to the buffer + offset = max(len(self._buffer) - delimiter_size + 1, 0) + self._buffer.extend(data) + + +class BufferedByteStream(BufferedByteReceiveStream, ByteStream): + """ + A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed + through to the wrapped stream as-is. + """ + + def __init__(self, stream: AnyByteStream): + """ + :param stream: the stream to be wrapped + + """ + super().__init__(stream) + self._stream = stream + + @override + async def send_eof(self) -> None: + await self._stream.send_eof() + + @override + async def send(self, item: bytes) -> None: + await self._stream.send(item) + + +class BufferedConnectable(ByteStreamConnectable): + """ + Wraps a byte stream connectable to produce :class:`BufferedByteStream` connections. + + Use this when you want the streams returned by :meth:`connect` to have the buffered + receive API (e.g. :meth:`~BufferedByteReceiveStream.receive_exactly` and + :meth:`~BufferedByteReceiveStream.receive_until`). + + :param connectable: the byte stream connectable to wrap + """ + + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the connectable to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> BufferedByteStream: + stream = await self.connectable.connect() + return BufferedByteStream(stream) diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/file.py b/.venv/lib/python3.12/site-packages/anyio/streams/file.py new file mode 100644 index 0000000000000000000000000000000000000000..b9d7ca4f3341a7ad7e44553e4e15134f223cb750 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/streams/file.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +__all__ = ( + "FileReadStream", + "FileStreamAttribute", + "FileWriteStream", +) + +from collections.abc import Callable, Mapping +from io import SEEK_SET, UnsupportedOperation +from os import PathLike +from pathlib import Path +from typing import IO, Any + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + TypedAttributeSet, + to_thread, + typed_attribute, +) +from ..abc import ByteReceiveStream, ByteSendStream + + +class FileStreamAttribute(TypedAttributeSet): + #: the open file descriptor + file: IO[bytes] = typed_attribute() + #: the path of the file on the file system, if available (file must be a real file) + path: Path = typed_attribute() + #: the file number, if available (file must be a real file or a TTY) + fileno: int = typed_attribute() + + +class _BaseFileStream: + def __init__(self, file: IO[bytes]): + self._file = file + + async def aclose(self) -> None: + await to_thread.run_sync(self._file.close) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict[Any, Callable[[], Any]] = { + FileStreamAttribute.file: lambda: self._file, + } + + if hasattr(self._file, "name"): + attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) + + try: + self._file.fileno() + except UnsupportedOperation: + pass + else: + attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() + + return attributes + + +class FileReadStream(_BaseFileStream, ByteReceiveStream): + """ + A byte stream that reads from a file in the file system. + + :param file: a file that has been opened for reading in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: + """ + Create a file read stream by opening the given file. + + :param path: path of the file to read from + + """ + file = await to_thread.run_sync(Path(path).open, "rb") + return cls(file) + + async def receive(self, max_bytes: int = 65536) -> bytes: + if max_bytes < 1: + raise ValueError("max_bytes must be a positive integer") + + try: + data = await to_thread.run_sync(self._file.read, max_bytes) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc + + if data: + return data + else: + raise EndOfStream + + async def seek(self, position: int, whence: int = SEEK_SET) -> int: + """ + Seek the file to the given position. + + .. seealso:: :meth:`io.IOBase.seek` + + .. note:: Not all file descriptors are seekable. + + :param position: position to seek the file to + :param whence: controls how ``position`` is interpreted + :return: the new absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.seek, position, whence) + + async def tell(self) -> int: + """ + Return the current stream position. + + .. note:: Not all file descriptors are seekable. + + :return: the current absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.tell) + + +class FileWriteStream(_BaseFileStream, ByteSendStream): + """ + A byte stream that writes to a file in the file system. + + :param file: a file that has been opened for writing in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path( + cls, path: str | PathLike[str], append: bool = False + ) -> FileWriteStream: + """ + Create a file write stream by opening the given file for writing. + + :param path: path of the file to write to + :param append: if ``True``, open the file for appending; if ``False``, any + existing file at the given path will be truncated + + """ + mode = "ab" if append else "wb" + file = await to_thread.run_sync(Path(path).open, mode) + return cls(file) + + async def send(self, item: bytes) -> None: + try: + await to_thread.run_sync(self._file.write, item) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/memory.py b/.venv/lib/python3.12/site-packages/anyio/streams/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..329a75e44b7af979042c54e65529c7148e67cd8d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/streams/memory.py @@ -0,0 +1,326 @@ +from __future__ import annotations + +__all__ = ( + "MemoryObjectReceiveStream", + "MemoryObjectSendStream", + "MemoryObjectStreamStatistics", +) + +import warnings +from collections import OrderedDict, deque +from dataclasses import dataclass, field +from types import TracebackType +from typing import Generic, NamedTuple, TypeVar + +from .._core._exceptions import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + WouldBlock, +) +from .._core._synchronization import Event +from .._core._testing import TaskInfo, get_current_task +from ..abc import ObjectReceiveStream, ObjectSendStream +from ..lowlevel import checkpoint + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class MemoryObjectStreamStatistics(NamedTuple): + current_buffer_used: int #: number of items stored in the buffer + #: maximum number of items that can be stored on this stream (or :data:`math.inf`) + max_buffer_size: float + open_send_streams: int #: number of unclosed clones of the send stream + open_receive_streams: int #: number of unclosed clones of the receive stream + #: number of tasks blocked on :meth:`MemoryObjectSendStream.send` + tasks_waiting_send: int + #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive` + tasks_waiting_receive: int + + +@dataclass(eq=False) +class _MemoryObjectItemReceiver(Generic[T_Item]): + task_info: TaskInfo = field(init=False, default_factory=get_current_task) + item: T_Item = field(init=False) + + def __repr__(self) -> str: + # When item is not defined, we get following error with default __repr__: + # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item' + item = getattr(self, "item", None) + return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})" + + +@dataclass(eq=False) +class _MemoryObjectStreamState(Generic[T_Item]): + max_buffer_size: float = field() + buffer: deque[T_Item] = field(init=False, default_factory=deque) + open_send_channels: int = field(init=False, default=0) + open_receive_channels: int = field(init=False, default=0) + waiting_receivers: OrderedDict[Event, _MemoryObjectItemReceiver[T_Item]] = field( + init=False, default_factory=OrderedDict + ) + waiting_senders: OrderedDict[Event, T_Item] = field( + init=False, default_factory=OrderedDict + ) + + def statistics(self) -> MemoryObjectStreamStatistics: + return MemoryObjectStreamStatistics( + len(self.buffer), + self.max_buffer_size, + self.open_send_channels, + self.open_receive_channels, + len(self.waiting_senders), + len(self.waiting_receivers), + ) + + +@dataclass(eq=False) +class MemoryObjectReceiveStream(ObjectReceiveStream[T_co], Generic[T_co]): + _state: _MemoryObjectStreamState[T_co] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_receive_channels += 1 + + def receive_nowait(self) -> T_co: + """ + Receive the next item if it can be done without waiting. + + :return: the received item + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been + closed from the sending end + :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks + waiting to send + + """ + if self._closed: + raise ClosedResourceError + + if self._state.waiting_senders: + # Get the item from the next sender + send_event, item = self._state.waiting_senders.popitem(last=False) + self._state.buffer.append(item) + send_event.set() + + if self._state.buffer: + return self._state.buffer.popleft() + elif not self._state.open_send_channels: + raise EndOfStream + + raise WouldBlock + + async def receive(self) -> T_co: + await checkpoint() + try: + return self.receive_nowait() + except WouldBlock: + # Add ourselves in the queue + receive_event = Event() + receiver = _MemoryObjectItemReceiver[T_co]() + self._state.waiting_receivers[receive_event] = receiver + + try: + await receive_event.wait() + finally: + self._state.waiting_receivers.pop(receive_event, None) + + try: + return receiver.item + except AttributeError: + raise EndOfStream from None + + def clone(self) -> MemoryObjectReceiveStream[T_co]: + """ + Create a clone of this receive stream. + + Each clone can be closed separately. Only when all clones have been closed will + the receiving end of the memory stream be considered closed by the sending ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectReceiveStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_receive_channels -= 1 + if self._state.open_receive_channels == 0: + send_events = list(self._state.waiting_senders.keys()) + for event in send_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectReceiveStream[T_co]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) + + +@dataclass(eq=False) +class MemoryObjectSendStream(ObjectSendStream[T_contra], Generic[T_contra]): + _state: _MemoryObjectStreamState[T_contra] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_send_channels += 1 + + def send_nowait(self, item: T_contra) -> None: + """ + Send an item immediately if it can be done without waiting. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting + to receive + + """ + if self._closed: + raise ClosedResourceError + if not self._state.open_receive_channels: + raise BrokenResourceError + + while self._state.waiting_receivers: + receive_event, receiver = self._state.waiting_receivers.popitem(last=False) + if not receiver.task_info.has_pending_cancellation(): + receiver.item = item + receive_event.set() + return + + if len(self._state.buffer) < self._state.max_buffer_size: + self._state.buffer.append(item) + else: + raise WouldBlock + + async def send(self, item: T_contra) -> None: + """ + Send an item to the stream. + + If the buffer is full, this method blocks until there is again room in the + buffer or the item can be sent directly to a receiver. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + + """ + await checkpoint() + try: + self.send_nowait(item) + except WouldBlock: + # Wait until there's someone on the receiving end + send_event = Event() + self._state.waiting_senders[send_event] = item + try: + await send_event.wait() + except BaseException: + self._state.waiting_senders.pop(send_event, None) + raise + + if send_event in self._state.waiting_senders: + del self._state.waiting_senders[send_event] + raise BrokenResourceError from None + + def clone(self) -> MemoryObjectSendStream[T_contra]: + """ + Create a clone of this send stream. + + Each clone can be closed separately. Only when all clones have been closed will + the sending end of the memory stream be considered closed by the receiving ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectSendStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_send_channels -= 1 + if self._state.open_send_channels == 0: + receive_events = list(self._state.waiting_receivers.keys()) + self._state.waiting_receivers.clear() + for event in receive_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectSendStream[T_contra]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/stapled.py b/.venv/lib/python3.12/site-packages/anyio/streams/stapled.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7534563b1aa9613516cd468daf6e68b4fa8a71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/streams/stapled.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +__all__ = ( + "MultiListener", + "StapledByteStream", + "StapledObjectStream", +) + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +from ..abc import ( + ByteReceiveStream, + ByteSendStream, + ByteStream, + Listener, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + TaskGroup, +) + +T_Item = TypeVar("T_Item") +T_Stream = TypeVar("T_Stream") + + +@dataclass(eq=False) +class StapledByteStream(ByteStream): + """ + Combines two byte streams into a single, bidirectional byte stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ByteSendStream send_stream: the sending byte stream + :param ByteReceiveStream receive_stream: the receiving byte stream + """ + + send_stream: ByteSendStream + receive_stream: ByteReceiveStream + + async def receive(self, max_bytes: int = 65536) -> bytes: + if max_bytes < 1: + raise ValueError("max_bytes must be a positive integer") + + return await self.receive_stream.receive(max_bytes) + + async def send(self, item: bytes) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class StapledObjectStream(ObjectStream[T_Item], Generic[T_Item]): + """ + Combines two object streams into a single, bidirectional object stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ObjectSendStream send_stream: the sending object stream + :param ObjectReceiveStream receive_stream: the receiving object stream + """ + + send_stream: ObjectSendStream[T_Item] + receive_stream: ObjectReceiveStream[T_Item] + + async def receive(self) -> T_Item: + return await self.receive_stream.receive() + + async def send(self, item: T_Item) -> None: + await self.send_stream.send(item) + + def send_nowait(self, item: T_Item) -> None: + try: + send_nowait = self.send_stream.send_nowait # type: ignore[attr-defined] + except AttributeError as exc: + raise NotImplementedError( + f"'send_nowait' method not implemented in {type(self.send_stream)}" + ) from exc + + send_nowait(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class MultiListener(Listener[T_Stream], Generic[T_Stream]): + """ + Combines multiple listeners into one, serving connections from all of them at once. + + Any MultiListeners in the given collection of listeners will have their listeners + moved into this one. + + Extra attributes are provided from each listener, with each successive listener + overriding any conflicting attributes from the previous one. + + :param listeners: listeners to serve + :type listeners: Sequence[Listener[T_Stream]] + """ + + listeners: Sequence[Listener[T_Stream]] + + def __post_init__(self) -> None: + listeners: list[Listener[T_Stream]] = [] + for listener in self.listeners: + if isinstance(listener, MultiListener): + listeners.extend(listener.listeners) + del listener.listeners[:] # type: ignore[attr-defined] + else: + listeners.append(listener) + + self.listeners = listeners + + async def serve( + self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None + ) -> None: + from .. import create_task_group + + async with create_task_group() as tg: + for listener in self.listeners: + tg.start_soon(listener.serve, handler, task_group) + + async def aclose(self) -> None: + for listener in self.listeners: + await listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict = {} + for listener in self.listeners: + attributes.update(listener.extra_attributes) + + return attributes diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/text.py b/.venv/lib/python3.12/site-packages/anyio/streams/text.py new file mode 100644 index 0000000000000000000000000000000000000000..296cd250459f3848bb333301fff1ac32973f219a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/streams/text.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +__all__ = ( + "TextConnectable", + "TextReceiveStream", + "TextSendStream", + "TextStream", +) + +import codecs +import sys +from collections.abc import Callable, Mapping +from dataclasses import InitVar, dataclass, field +from typing import Any + +from ..abc import ( + AnyByteReceiveStream, + AnyByteSendStream, + AnyByteStream, + AnyByteStreamConnectable, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + ObjectStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class TextReceiveStream(ObjectReceiveStream[str]): + """ + Stream wrapper that decodes bytes to strings using the given encoding. + + Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any + completely received unicode characters as soon as they come in. + + :param transport_stream: any bytes-based receive stream + :param encoding: character encoding to use for decoding bytes to strings (defaults + to ``utf-8``) + :param errors: handling scheme for decoding errors (defaults to ``strict``; see the + `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteReceiveStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _decoder: codecs.IncrementalDecoder = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + decoder_class = codecs.getincrementaldecoder(encoding) + self._decoder = decoder_class(errors=errors) + + async def receive(self) -> str: + while True: + chunk = await self.transport_stream.receive() + decoded = self._decoder.decode(chunk) + if decoded: + return decoded + + async def aclose(self) -> None: + await self.transport_stream.aclose() + self._decoder.reset() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextSendStream(ObjectSendStream[str]): + """ + Sends strings to the wrapped stream as bytes using the given encoding. + + :param AnyByteSendStream transport_stream: any bytes-based send stream + :param str encoding: character encoding to use for encoding strings to bytes + (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteSendStream + encoding: InitVar[str] = "utf-8" + errors: str = "strict" + _encoder: Callable[..., tuple[bytes, int]] = field(init=False) + + def __post_init__(self, encoding: str) -> None: + self._encoder = codecs.getencoder(encoding) + + async def send(self, item: str) -> None: + encoded = self._encoder(item, self.errors)[0] + await self.transport_stream.send(encoded) + + async def aclose(self) -> None: + await self.transport_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextStream(ObjectStream[str]): + """ + A bidirectional stream that decodes bytes to strings on receive and encodes strings + to bytes on send. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param AnyByteStream transport_stream: any bytes-based stream + :param str encoding: character encoding to use for encoding/decoding strings to/from + bytes (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _receive_stream: TextReceiveStream = field(init=False) + _send_stream: TextSendStream = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + self._receive_stream = TextReceiveStream( + self.transport_stream, encoding=encoding, errors=errors + ) + self._send_stream = TextSendStream( + self.transport_stream, encoding=encoding, errors=errors + ) + + async def receive(self) -> str: + return await self._receive_stream.receive() + + async def send(self, item: str) -> None: + await self._send_stream.send(item) + + async def send_eof(self) -> None: + await self.transport_stream.send_eof() + + async def aclose(self) -> None: + await self._send_stream.aclose() + await self._receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self._send_stream.extra_attributes, + **self._receive_stream.extra_attributes, + } + + +class TextConnectable(ObjectStreamConnectable[str]): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the bytestream endpoint to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> TextStream: + stream = await self.connectable.connect() + return TextStream(stream) diff --git a/.venv/lib/python3.12/site-packages/anyio/streams/tls.py b/.venv/lib/python3.12/site-packages/anyio/streams/tls.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ddf1d333143767b737bbd5915bebe1309481b2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/streams/tls.py @@ -0,0 +1,436 @@ +from __future__ import annotations + +__all__ = ( + "TLSAttribute", + "TLSConnectable", + "TLSListener", + "TLSStream", +) + +import logging +import re +import ssl +import sys +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from functools import wraps +from ssl import SSLContext +from typing import Any, TypeAlias, TypeVar + +from .. import ( + BrokenResourceError, + EndOfStream, + aclose_forcefully, + get_cancelled_exc_class, + to_thread, +) +from .._core._typedattr import TypedAttributeSet, typed_attribute +from ..abc import ( + AnyByteStream, + AnyByteStreamConnectable, + ByteStream, + ByteStreamConnectable, + Listener, + TaskGroup, +) + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] + + +class TLSAttribute(TypedAttributeSet): + """Contains Transport Layer Security related attributes.""" + + #: the selected ALPN protocol + alpn_protocol: str | None = typed_attribute() + #: the channel binding for type ``tls-unique`` + channel_binding_tls_unique: bytes = typed_attribute() + #: the selected cipher + cipher: tuple[str, str, int] = typed_attribute() + #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert` + # for more information) + peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute() + #: the peer certificate in binary form + peer_certificate_binary: bytes | None = typed_attribute() + #: ``True`` if this is the server side of the connection + server_side: bool = typed_attribute() + #: ciphers shared by the client during the TLS handshake (``None`` if this is the + #: client side) + shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute() + #: the :class:`~ssl.SSLObject` used for encryption + ssl_object: ssl.SSLObject = typed_attribute() + #: ``True`` if this stream does (and expects) a closing TLS handshake when the + #: stream is being closed + standard_compatible: bool = typed_attribute() + #: the TLS protocol version (e.g. ``TLSv1.2``) + tls_version: str = typed_attribute() + + +@dataclass(eq=False) +class TLSStream(ByteStream): + """ + A stream wrapper that encrypts all sent data and decrypts received data. + + This class has no public initializer; use :meth:`wrap` instead. + All extra attributes from :class:`~TLSAttribute` are supported. + + :var AnyByteStream transport_stream: the wrapped stream + + """ + + transport_stream: AnyByteStream + standard_compatible: bool + _ssl_object: ssl.SSLObject + _read_bio: ssl.MemoryBIO + _write_bio: ssl.MemoryBIO + + @classmethod + async def wrap( + cls, + transport_stream: AnyByteStream, + *, + server_side: bool | None = None, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> TLSStream: + """ + Wrap an existing stream with Transport Layer Security. + + This performs a TLS handshake with the peer. + + :param transport_stream: a bytes-transporting stream to wrap + :param server_side: ``True`` if this is the server side of the connection, + ``False`` if this is the client side (if omitted, will be set to ``False`` + if ``hostname`` has been provided, ``False`` otherwise). Used only to create + a default context when an explicit context has not been provided. + :param hostname: host name of the peer (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure + default will be created) + :param standard_compatible: if ``False``, skip the closing handshake when + closing the connection, and don't raise an exception if the peer does the + same + :raises ~ssl.SSLError: if the TLS handshake fails + + """ + if server_side is None: + server_side = not hostname + + if not ssl_context: + purpose = ( + ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH + ) + ssl_context = ssl.create_default_context(purpose) + + # Re-enable detection of unexpected EOFs if it was disabled by Python + if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): + ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF + + bio_in = ssl.MemoryBIO() + bio_out = ssl.MemoryBIO() + + # Resolve international host names using IDNA 2008. + # Otherwise wrap_bio() would resolve them with IDNA 2003. + if hostname is not None: + from .._core._sockets import idna2008_resolve + + server_hostname: bytes | None = idna2008_resolve(hostname) + else: + server_hostname = None + + # External SSLContext implementations may do blocking I/O in wrap_bio(), + # but the standard library implementation won't + if type(ssl_context) is ssl.SSLContext: + ssl_object = ssl_context.wrap_bio( + bio_in, + bio_out, + server_side=server_side, + server_hostname=server_hostname, + ) + else: + ssl_object = await to_thread.run_sync( + ssl_context.wrap_bio, + bio_in, + bio_out, + server_side, + server_hostname, + None, + ) + + wrapper = cls( + transport_stream=transport_stream, + standard_compatible=standard_compatible, + _ssl_object=ssl_object, + _read_bio=bio_in, + _write_bio=bio_out, + ) + await wrapper._call_sslobject_method(ssl_object.do_handshake) + return wrapper + + async def _call_sslobject_method( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: + while True: + try: + result = func(*args) + except ssl.SSLWantReadError: + try: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + data = await self.transport_stream.receive() + except EndOfStream: + self._read_bio.write_eof() + except OSError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + else: + self._read_bio.write(data) + except ssl.SSLWantWriteError: + await self.transport_stream.send(self._write_bio.read()) + except ssl.SSLSyscallError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + except ssl.SSLError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + if isinstance(exc, ssl.SSLEOFError) or ( + exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror + ): + if self.standard_compatible: + raise BrokenResourceError from exc + else: + raise EndOfStream from None + + raise + else: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + return result + + async def unwrap(self) -> tuple[AnyByteStream, bytes]: + """ + Does the TLS closing handshake. + + :return: a tuple of (wrapped byte stream, bytes left in the read buffer) + + """ + await self._call_sslobject_method(self._ssl_object.unwrap) + self._read_bio.write_eof() + self._write_bio.write_eof() + return self.transport_stream, self._read_bio.read() + + async def aclose(self) -> None: + if self.standard_compatible: + try: + await self.unwrap() + except BaseException: + await aclose_forcefully(self.transport_stream) + raise + + await self.transport_stream.aclose() + + async def receive(self, max_bytes: int = 65536) -> bytes: + if max_bytes < 1: + raise ValueError("max_bytes must be a positive integer") + + data = await self._call_sslobject_method(self._ssl_object.read, max_bytes) + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + await self._call_sslobject_method(self._ssl_object.write, item) + + async def send_eof(self) -> None: + tls_version = self.extra(TLSAttribute.tls_version) + match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version) + if match: + major, minor = int(match.group(1)), int(match.group(2) or 0) + if (major, minor) < (1, 3): + raise NotImplementedError( + f"send_eof() requires at least TLSv1.3; current " + f"session uses {tls_version}" + ) + + raise NotImplementedError( + "send_eof() has not yet been implemented for TLS streams" + ) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.transport_stream.extra_attributes, + TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol, + TLSAttribute.channel_binding_tls_unique: ( + self._ssl_object.get_channel_binding + ), + TLSAttribute.cipher: self._ssl_object.cipher, + TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False), + TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert( + True + ), + TLSAttribute.server_side: lambda: self._ssl_object.server_side, + TLSAttribute.shared_ciphers: lambda: ( + self._ssl_object.shared_ciphers() + if self._ssl_object.server_side + else None + ), + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + TLSAttribute.ssl_object: lambda: self._ssl_object, + TLSAttribute.tls_version: self._ssl_object.version, + } + + +@dataclass(eq=False) +class TLSListener(Listener[TLSStream]): + """ + A convenience listener that wraps another listener and auto-negotiates a TLS session + on every accepted connection. + + If the TLS handshake times out or raises an exception, + :meth:`handle_handshake_error` is called to do whatever post-mortem processing is + deemed necessary. + + Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute. + + :param Listener listener: the listener to wrap + :param ssl_context: the SSL context object + :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap` + :param handshake_timeout: time limit for the TLS handshake + (passed to :func:`~anyio.fail_after`) + """ + + listener: Listener[Any] + ssl_context: ssl.SSLContext + standard_compatible: bool = True + handshake_timeout: float = 30 + + @staticmethod + async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None: + """ + Handle an exception raised during the TLS handshake. + + This method does 3 things: + + #. Forcefully closes the original stream + #. Logs the exception (unless it was a cancellation exception) using the + ``anyio.streams.tls`` logger + #. Reraises the exception if it was a base exception or a cancellation exception + + :param exc: the exception + :param stream: the original stream + + """ + await aclose_forcefully(stream) + + # Log all except cancellation exceptions + if not isinstance(exc, get_cancelled_exc_class()): + # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using + # any asyncio implementation, so we explicitly pass the exception to log + # (https://github.com/python/cpython/issues/108668). Trio does not have this + # issue because it works around the CPython bug. + logging.getLogger(__name__).exception( + "Error during TLS handshake", exc_info=exc + ) + + # Only reraise base exceptions and cancellation exceptions + if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()): + raise # noqa: PLE0704 + + async def serve( + self, + handler: Callable[[TLSStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + @wraps(handler) + async def handler_wrapper(stream: AnyByteStream) -> None: + from .. import fail_after + + try: + with fail_after(self.handshake_timeout): + wrapped_stream = await TLSStream.wrap( + stream, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException as exc: + await self.handle_handshake_error(exc, stream) + else: + await handler(wrapped_stream) + + await self.listener.serve(handler_wrapper, task_group) + + async def aclose(self) -> None: + await self.listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + } + + +class TLSConnectable(ByteStreamConnectable): + """ + Wraps another connectable and does TLS negotiation after a successful connection. + + :param connectable: the connectable to wrap + :param hostname: host name of the server (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure default + will be created) + :param standard_compatible: if ``False``, skip the closing handshake when closing + the connection, and don't raise an exception if the server does the same + """ + + def __init__( + self, + connectable: AnyByteStreamConnectable, + *, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> None: + self.connectable = connectable + self.ssl_context: SSLContext = ssl_context or ssl.create_default_context( + ssl.Purpose.SERVER_AUTH + ) + if not isinstance(self.ssl_context, ssl.SSLContext): + raise TypeError( + "ssl_context must be an instance of ssl.SSLContext, not " + f"{type(self.ssl_context).__name__}" + ) + self.hostname = hostname + self.standard_compatible = standard_compatible + + @override + async def connect(self) -> TLSStream: + stream = await self.connectable.connect() + try: + return await TLSStream.wrap( + stream, + hostname=self.hostname, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException: + await aclose_forcefully(stream) + raise diff --git a/.venv/lib/python3.12/site-packages/anyio/to_interpreter.py b/.venv/lib/python3.12/site-packages/anyio/to_interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..54ef4a8b8c58db9ea05e4188cf6d7899c8ff8c72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/to_interpreter.py @@ -0,0 +1,246 @@ +from __future__ import annotations + +__all__ = ( + "current_default_interpreter_limiter", + "run_sync", +) + +import atexit +import os +import sys +from collections import deque +from collections.abc import Callable +from typing import Any, Final, TypeVar + +from . import current_time, to_thread +from ._core._exceptions import BrokenWorkerInterpreter +from ._core._synchronization import CapacityLimiter +from .lowlevel import RunVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 14): + from concurrent.interpreters import ExecutionFailed, create + + def _interp_call( + func: Callable[..., Any], args: tuple[Any, ...] + ) -> tuple[Any, bool]: + try: + retval = func(*args) + except BaseException as exc: + return exc, True + else: + return retval, False + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter = create() + + def destroy(self) -> None: + self._interpreter.close() + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + try: + res, is_exception = self._interpreter.call(_interp_call, func, args) + except ExecutionFailed as exc: + raise BrokenWorkerInterpreter(exc.excinfo) from exc + + if is_exception: + raise res + + return res +elif sys.version_info >= (3, 13): + import _interpqueues + import _interpreters + + UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib + FMT_UNPICKLED: Final = 0 + FMT_PICKLED: Final = 1 + QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND) + QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND) + + _run_func = compile( + """ +import _interpqueues +from _interpreters import NotShareableError +from pickle import loads, dumps, HIGHEST_PROTOCOL + +QUEUE_PICKLE_ARGS = (1, 2) +QUEUE_UNPICKLE_ARGS = (0, 2) + +item = _interpqueues.get(queue_id)[0] +try: + func, args = loads(item) + retval = func(*args) +except BaseException as exc: + is_exception = True + retval = exc +else: + is_exception = False + +try: + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS) +except NotShareableError: + retval = dumps(retval, HIGHEST_PROTOCOL) + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS) + """, + "", + "exec", + ) + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter_id = _interpreters.create() + self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS) + _interpreters.set___main___attrs( + self._interpreter_id, {"queue_id": self._queue_id} + ) + + def destroy(self) -> None: + _interpqueues.destroy(self._queue_id) + _interpreters.destroy(self._interpreter_id) + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + import pickle + + item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL) + _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS) + exc_info = _interpreters.exec(self._interpreter_id, _run_func) + if exc_info: + raise BrokenWorkerInterpreter(exc_info) + + res = _interpqueues.get(self._queue_id) + (res, is_exception), fmt = res[:2] + if fmt == FMT_PICKLED: + res = pickle.loads(res) + + if is_exception: + raise res + + return res +else: + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + raise RuntimeError("subinterpreters require at least Python 3.13") + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + raise NotImplementedError + + def destroy(self) -> None: + pass + + +DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value +MAX_WORKER_IDLE_TIME = ( + 30 # seconds a subinterpreter can be idle before becoming eligible for pruning +) + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_idle_workers = RunVar[deque[_Worker]]("_available_workers") +_default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter") + + +def _stop_workers(workers: deque[_Worker]) -> None: + for worker in workers: + worker.destroy() + + workers.clear() + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a subinterpreter. + + .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet + available, so the code path for that Python version relies on an undocumented, + private API. As such, it is recommended to not rely on this function for anything + mission-critical on Python 3.13. + + :param func: a callable + :param args: the positional arguments for the callable + :param limiter: capacity limiter to use to limit the total number of subinterpreters + running (if omitted, the default limiter is used) + :return: the result of the call + :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter + + """ + if limiter is None: + limiter = current_default_interpreter_limiter() + + try: + idle_workers = _idle_workers.get() + except LookupError: + idle_workers = deque() + _idle_workers.set(idle_workers) + atexit.register(_stop_workers, idle_workers) + + async with limiter: + try: + worker = idle_workers.pop() + except IndexError: + worker = _Worker() + + try: + return await to_thread.run_sync( + worker.call, + func, + args, + limiter=limiter, + ) + finally: + # Prune workers that have been idle for too long + now = current_time() + while idle_workers: + if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME: + break + + await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter) + + worker.last_used = current_time() + idle_workers.append(worker) + + +def current_default_interpreter_limiter() -> CapacityLimiter: + """ + Return the capacity limiter used by default to limit the number of concurrently + running subinterpreters. + + Defaults to the number of CPU cores. + + :return: a capacity limiter object + + """ + try: + return _default_interpreter_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT) + _default_interpreter_limiter.set(limiter) + return limiter diff --git a/.venv/lib/python3.12/site-packages/anyio/to_process.py b/.venv/lib/python3.12/site-packages/anyio/to_process.py new file mode 100644 index 0000000000000000000000000000000000000000..584128ec3b2d4bbd0a9634fc7f2f39caf1fe968d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/to_process.py @@ -0,0 +1,269 @@ +from __future__ import annotations + +__all__ = ( + "current_default_process_limiter", + "process_worker", + "run_sync", +) + +import os +import pickle +import runpy +import subprocess +import sys +from collections import deque +from collections.abc import Callable +from types import ModuleType +from typing import TypeVar, cast + +from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class +from ._core._exceptions import BrokenWorkerProcess +from ._core._subprocesses import open_process +from ._core._synchronization import CapacityLimiter +from ._core._tasks import CancelScope, fail_after +from .abc import ByteReceiveStream, ByteSendStream, Process +from .lowlevel import RunVar, checkpoint_if_cancelled +from .streams.buffered import BufferedByteReceiveStream + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +WORKER_MAX_IDLE_TIME = 300 # 5 minutes + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers") +_process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar( + "_process_pool_idle_workers" +) +_default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter") + + +async def run_sync( # type: ignore[return] + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + cancellable: bool = False, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker process. + + If the ``cancellable`` option is enabled and the task waiting for its completion is + cancelled, the worker process running it will be abruptly terminated using SIGKILL + (or ``terminateProcess()`` on Windows). + + :param func: a callable + :param args: positional arguments for the callable + :param cancellable: ``True`` to allow cancellation of the operation while it's + running + :param limiter: capacity limiter to use to limit the total amount of processes + running (if omitted, the default limiter is used) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + :return: an awaitable that yields the return value of the function. + + """ + + async def send_raw_command(pickled_cmd: bytes) -> object: + try: + await stdin.send(pickled_cmd) + response = await buffered.receive_until(b"\n", 50) + status, length = response.split(b" ") + if status not in (b"RETURN", b"EXCEPTION"): + raise RuntimeError( + f"Worker process returned unexpected response: {response!r}" + ) + + pickled_response = await buffered.receive_exactly(int(length)) + except BaseException as exc: + workers.discard(process) + try: + process.kill() + with CancelScope(shield=True): + await process.aclose() + except ProcessLookupError: + pass + + if isinstance(exc, get_cancelled_exc_class()): + raise + else: + raise BrokenWorkerProcess from exc + + retval = pickle.loads(pickled_response) + if status == b"EXCEPTION": + assert isinstance(retval, BaseException) + raise retval + else: + return retval + + # First pickle the request before trying to reserve a worker process + await checkpoint_if_cancelled() + request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL) + + # If this is the first run in this event loop thread, set up the necessary variables + try: + workers = _process_pool_workers.get() + idle_workers = _process_pool_idle_workers.get() + except LookupError: + workers = set() + idle_workers = deque() + _process_pool_workers.set(workers) + _process_pool_idle_workers.set(idle_workers) + get_async_backend().setup_process_pool_exit_at_shutdown(workers) + + async with limiter or current_default_process_limiter(): + # Pop processes from the pool (starting from the most recently used) until we + # find one that hasn't exited yet + process: Process + while idle_workers: + process, _idle_since = idle_workers.pop() + if process.returncode is None: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + + # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME + # seconds or longer + now = current_time() + killed_processes: list[Process] = [] + while idle_workers: + if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME: + break + + process_to_kill, _idle_since = idle_workers.popleft() + process_to_kill.kill() + workers.remove(process_to_kill) + killed_processes.append(process_to_kill) + + with CancelScope(shield=True): + for killed_process in killed_processes: + await killed_process.aclose() + + break + + workers.remove(process) + else: + command = [sys.executable, "-u", "-m", __name__] + process = await open_process( + command, stdin=subprocess.PIPE, stdout=subprocess.PIPE + ) + try: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + with fail_after(20): + message = await buffered.receive(6) + + if message != b"READY\n": + raise BrokenWorkerProcess( + f"Worker process returned unexpected response: {message!r}" + ) + + main_module_path = getattr(sys.modules["__main__"], "__file__", None) + pickled = pickle.dumps( + ("init", sys.path, main_module_path), + protocol=pickle.HIGHEST_PROTOCOL, + ) + await send_raw_command(pickled) + except (BrokenWorkerProcess, get_cancelled_exc_class()): + raise + except BaseException as exc: + process.kill() + raise BrokenWorkerProcess( + "Error during worker process initialization" + ) from exc + + workers.add(process) + + with CancelScope(shield=not cancellable): + try: + return cast(T_Retval, await send_raw_command(request)) + finally: + if process in workers: + idle_workers.append((process, current_time())) + + +def current_default_process_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of worker + processes. + + :return: a capacity limiter object + + """ + try: + return _default_process_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or 2) + _default_process_limiter.set(limiter) + return limiter + + +def process_worker() -> None: + # Redirect standard streams to os.devnull so that user code won't interfere with the + # parent-worker communication + stdin = sys.stdin + stdout = sys.stdout + sys.stdin = open(os.devnull) + sys.stdout = open(os.devnull, "w") + sys.stderr = open(os.devnull, "w") + + stdout.buffer.write(b"READY\n") + while True: + retval = exception = None + try: + command, *args = pickle.load(stdin.buffer) + except EOFError: + return + except BaseException as exc: + exception = exc + else: + if command == "run": + func, args = args + try: + retval = func(*args) + except BaseException as exc: + exception = exc + elif command == "init": + main_module_path: str | None + sys.path, main_module_path = args + del sys.modules["__main__"] + if main_module_path and os.path.isfile(main_module_path): + # Load the parent's main module but as __mp_main__ instead of + # __main__ (like multiprocessing does) to avoid infinite recursion + try: + main = ModuleType("__mp_main__") + main_content = runpy.run_path( + main_module_path, run_name="__mp_main__" + ) + main.__dict__.update(main_content) + sys.modules["__main__"] = sys.modules["__mp_main__"] = main + except BaseException as exc: + exception = exc + try: + if exception is not None: + status = b"EXCEPTION" + pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL) + else: + status = b"RETURN" + pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL) + except BaseException as exc: + exception = exc + status = b"EXCEPTION" + pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL) + + stdout.buffer.write(b"%s %d\n" % (status, len(pickled))) + stdout.buffer.write(pickled) + + # Respect SIGTERM + if isinstance(exception, SystemExit): + raise exception + + +if __name__ == "__main__": + process_worker() diff --git a/.venv/lib/python3.12/site-packages/anyio/to_thread.py b/.venv/lib/python3.12/site-packages/anyio/to_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..5cdb7253e3c0a4f99ad2f893d31cc32f8fbda298 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/anyio/to_thread.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +__all__ = ( + "current_default_thread_limiter", + "run_sync", +) + +import sys +from collections.abc import Callable +from typing import TYPE_CHECKING, TypeVar +from warnings import warn + +from ._core._eventloop import get_async_backend + +if TYPE_CHECKING: + from ._core._synchronization import CapacityLimiter + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + abandon_on_cancel: bool = False, + cancellable: bool | None = None, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker thread. + + If the ``abandon_on_cancel`` option is enabled and the task waiting for its + completion is cancelled, the thread will still run its course but its + return value (or any raised exception) will be ignored. + + :param func: a callable + :param args: positional arguments for the callable + :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run + unchecked on own) if the host task is cancelled, ``False`` to ignore + cancellations in the host task until the operation has completed in the worker + thread + :param cancellable: deprecated alias of ``abandon_on_cancel``; will override + ``abandon_on_cancel`` if both parameters are passed + :param limiter: capacity limiter to use to limit the total amount of threads running + (if omitted, the default limiter is used) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + :return: an awaitable that yields the return value of the function. + + """ + if cancellable is not None: + abandon_on_cancel = cancellable + warn( + "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is " + "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead", + DeprecationWarning, + stacklevel=2, + ) + + return await get_async_backend().run_sync_in_worker_thread( + func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter + ) + + +def current_default_thread_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of + concurrent threads. + + :return: a capacity limiter object + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_default_thread_limiter() diff --git a/.venv/lib/python3.12/site-packages/av/__init__.pxd b/.venv/lib/python3.12/site-packages/av/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/__init__.py b/.venv/lib/python3.12/site-packages/av/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..964b93891e7f10f7996ffa1e28d9f9a45d265a40 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/__init__.py @@ -0,0 +1,73 @@ +# MUST import the core before anything else in order to initialize the underlying +# library that is being wrapped. +from av._core import time_base, library_versions, ffmpeg_version_info + +# Capture logging (by importing it). +from av import logging + +# For convenience, import all common attributes. +from av.about import __version__ +from av.audio.codeccontext import AudioCodecContext +from av.audio.fifo import AudioFifo +from av.audio.format import AudioFormat +from av.audio.frame import AudioFrame +from av.audio.layout import AudioLayout +from av.audio.resampler import AudioResampler +from av.audio.stream import AudioStream +from av.bitstream import BitStreamFilterContext, bitstream_filters_available +from av.codec.codec import Codec, codecs_available +from av.codec.context import CodecContext +from av.container import open +from av.device import DeviceInfo, enumerate_input_devices, enumerate_output_devices +from av.format import ContainerFormat, formats_available +from av.packet import Packet +from av.rational import AVRational +from av.error import * # noqa: F403; This is limited to exception types. +from av.video.codeccontext import VideoCodecContext +from av.video.format import VideoFormat +from av.video.frame import VideoFrame +from av.video.stream import VideoStream + +__all__ = ( + "__version__", + "time_base", + "ffmpeg_version_info", + "library_versions", + "AudioCodecContext", + "AudioFifo", + "AudioFormat", + "AudioFrame", + "AudioLayout", + "AudioResampler", + "AudioStream", + "BitStreamFilterContext", + "bitstream_filters_available", + "Codec", + "codecs_available", + "CodecContext", + "open", + "DeviceInfo", + "enumerate_input_devices", + "enumerate_output_devices", + "ContainerFormat", + "formats_available", + "Packet", + "VideoCodecContext", + "VideoFormat", + "VideoFrame", + "VideoStream", +) + + +def get_include() -> str: + """ + Returns the path to the `include` folder to be used when building extensions to av. + """ + import os + + # Installed package + include_path = os.path.join(os.path.dirname(__file__), "include") + if os.path.exists(include_path): + return include_path + # Running from source directory + return os.path.join(os.path.dirname(__file__), os.pardir, "include") diff --git a/.venv/lib/python3.12/site-packages/av/__main__.py b/.venv/lib/python3.12/site-packages/av/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2b9d0ac00c1151ed5bb1947dc5d52e357255e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/__main__.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import argparse + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--codecs", action="store_true") + parser.add_argument("--hwdevices", action="store_true") + parser.add_argument("--hwconfigs", action="store_true") + parser.add_argument("--version", action="store_true") + args = parser.parse_args() + + if args.version: + import av + import av._core + + print(f"PyAV v{av.__version__}") + + by_config: dict = {} + for libname, config in sorted(av._core.library_meta.items()): + version = config["version"] + if version[0] >= 0: + by_config.setdefault( + (config["configuration"], config["license"]), [] + ).append((libname, config)) + + for (config, license), libs in sorted(by_config.items()): + print("library configuration:", config) + print("library license:", license) + for libname, config in libs: + version = config["version"] + print(f"{libname:<13} {version[0]:3d}.{version[1]:3d}.{version[2]:3d}") + + if args.hwdevices: + from av.codec.hwaccel import hwdevices_available + + print("Hardware device types:") + for x in hwdevices_available(): + print(" ", x) + + if args.hwconfigs: + from av.codec.codec import dump_hwconfigs + + dump_hwconfigs() + + if args.codecs: + from av.codec.codec import dump_codecs + + dump_codecs() + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63ce57194093bb992e3f53b27e58fb40d5f9794f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0007e33bccc6f2358470c56c28e57ca238f86c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/_core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43ffa03117f0dae3ff910dbf078f1213a63e4d04 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/_core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/about.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/about.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4d6e0f98224950ce7442443114c607b0e0a70d9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/about.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/bitstream.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/bitstream.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eb3fb33adcf05a92ba2a050ef66612df1bcef48 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/bitstream.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/buffer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..615de6d697014db26b42b4b2f3d8eaf1a8a2b958 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/buffer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/datasets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/datasets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c633cddf6fef56fc02771eca9eae41acd89581f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/datasets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/device.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/device.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..296eb68b654f5d9dd72900b0d3ec80426afb6d63 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/device.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/dictionary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/dictionary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa72e525be3c8ea099640633be135c8eff9c8efe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/dictionary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/error.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c46aa4589254cfdc43bd0e08b0734eca99bbdfb7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/error.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/format.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddb2ed90107b88105ddb5904b4e8a82df7edff15 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/format.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a4c91bee10e0245dbdacd7b2c2e17d0d649ea5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/frame.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/index.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/index.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfcc593a12a2eeefa9103c97591417588cdb48d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/index.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8a95c1f11d928ed046ec396f11d6233928dc547 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/logging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/opaque.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/opaque.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..245c6c1f08ff5b2777b55832dca570a8ed20cb96 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/opaque.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/packet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/packet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c6ebfd74c67103db4a1636ee997c50da518e482 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/packet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/plane.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/plane.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae9080a938eaa8b4498cd2853a05562476af440 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/plane.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/rational.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/rational.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e4348c5ae615c93f616685ed14ea29c248c11dc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/rational.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/stream.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/stream.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..776433c5fc3239e8801bd31a512a83a241dccd0f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/stream.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80f2e9a9bb54fefa2cb2c602f7ed9d0e3cdbff18 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/_core.abi3.so b/.venv/lib/python3.12/site-packages/av/_core.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..b99bd2cdf8a73396e0b6c00854002ab9d9ddda80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/_core.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a6f0e12a0b03b8c42b2dd4602745a564ba5d2236cb8a1d0c2a20dd2a0610b19 +size 154817 diff --git a/.venv/lib/python3.12/site-packages/av/_core.pxd b/.venv/lib/python3.12/site-packages/av/_core.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2d9e9520980d35392ab563df78244b5e0ebb0a2a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/_core.pxd @@ -0,0 +1,9 @@ +cdef extern from "libswscale/swscale.h" nogil: + cdef unsigned int swscale_version() + cdef const char* swscale_configuration() + cdef const char* swscale_license() + +cdef extern from "libswresample/swresample.h" nogil: + cdef unsigned int swresample_version() + cdef const char* swresample_configuration() + cdef const char* swresample_license() diff --git a/.venv/lib/python3.12/site-packages/av/_core.py b/.venv/lib/python3.12/site-packages/av/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..6ad38df5b20593cba9e59047bd9ef33249560934 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/_core.py @@ -0,0 +1,65 @@ +import cython +import cython.cimports.libav as lib + +lib.avdevice_register_all() + +# Exports. +time_base = lib.AV_TIME_BASE + + +@cython.cfunc +def decode_version(v): + if v < 0: + return (-1, -1, -1) + + major: cython.int = (v >> 16) & 0xFF + minor: cython.int = (v >> 8) & 0xFF + micro: cython.int = (v) & 0xFF + return (major, minor, micro) + + +# Return an informative version string. +# This usually is the actual release version number or a git commit +# description. This string has no fixed format and can change any time. It +# should never be parsed by code. +ffmpeg_version_info = lib.av_version_info() + +library_meta = { + "libavutil": dict( + version=decode_version(lib.avutil_version()), + configuration=lib.avutil_configuration(), + license=lib.avutil_license(), + ), + "libavcodec": dict( + version=decode_version(lib.avcodec_version()), + configuration=lib.avcodec_configuration(), + license=lib.avcodec_license(), + ), + "libavformat": dict( + version=decode_version(lib.avformat_version()), + configuration=lib.avformat_configuration(), + license=lib.avformat_license(), + ), + "libavdevice": dict( + version=decode_version(lib.avdevice_version()), + configuration=lib.avdevice_configuration(), + license=lib.avdevice_license(), + ), + "libavfilter": dict( + version=decode_version(lib.avfilter_version()), + configuration=lib.avfilter_configuration(), + license=lib.avfilter_license(), + ), + "libswscale": dict( + version=decode_version(swscale_version()), + configuration=swscale_configuration(), + license=swscale_license(), + ), + "libswresample": dict( + version=decode_version(swresample_version()), + configuration=swresample_configuration(), + license=swresample_license(), + ), +} + +library_versions = {name: meta["version"] for name, meta in library_meta.items()} diff --git a/.venv/lib/python3.12/site-packages/av/_core.pyi b/.venv/lib/python3.12/site-packages/av/_core.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0ee0a562677bdb1c4a98c52722af95e0a4f08d00 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/_core.pyi @@ -0,0 +1,12 @@ +from typing import TypedDict + +class _Meta(TypedDict): + version: tuple[int, int, int] + configuration: str + license: str + +library_meta: dict[str, _Meta] +library_versions: dict[str, tuple[int, int, int]] +ffmpeg_version_info: str + +time_base: int diff --git a/.venv/lib/python3.12/site-packages/av/about.py b/.venv/lib/python3.12/site-packages/av/about.py new file mode 100644 index 0000000000000000000000000000000000000000..c84c510d7bd414e3c7f6c6211bd6c0edb6d61f43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/about.py @@ -0,0 +1 @@ +__version__ = "18.1.0" diff --git a/.venv/lib/python3.12/site-packages/av/audio/__init__.pxd b/.venv/lib/python3.12/site-packages/av/audio/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/audio/__init__.py b/.venv/lib/python3.12/site-packages/av/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f57d62046e523db854310bd48655f40c23951cf0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/__init__.py @@ -0,0 +1,2 @@ +from .frame import AudioFrame as AudioFrame +from .stream import AudioStream as AudioStream diff --git a/.venv/lib/python3.12/site-packages/av/audio/__init__.pyi b/.venv/lib/python3.12/site-packages/av/audio/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b6a5c78e0695995c373ae7290e12b36ec1a3ab7f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/__init__.pyi @@ -0,0 +1,122 @@ +from typing import Literal + +from .frame import AudioFrame +from .stream import AudioStream + +# FFmpeg 8.1 encoders and the codec descriptor aliases that resolve to them. +_AudioCodecName = Literal[ + "aac", + "aac_at", + "aac_mf", + "ac3", + "ac3_fixed", + "ac3_mf", + "adpcm_adx", + "adpcm_argo", + "adpcm_g722", + "adpcm_g726", + "adpcm_g726le", + "adpcm_ima_alp", + "adpcm_ima_amv", + "adpcm_ima_apm", + "adpcm_ima_qt", + "adpcm_ima_ssi", + "adpcm_ima_wav", + "adpcm_ima_ws", + "adpcm_ms", + "adpcm_swf", + "adpcm_yamaha", + "alac", + "alac_at", + "amr_nb", + "amr_wb", + "anull", + "aptx", + "aptx_hd", + "codec2", + "comfortnoise", + "dca", + "dfpwm", + "dts", + "eac3", + "flac", + "g722", + "g723_1", + "g726", + "g726le", + "gsm", + "gsm_ms", + "ilbc", + "ilbc_at", + "lc3", + "libcodec2", + "libfdk_aac", + "libgsm", + "libgsm_ms", + "libilbc", + "liblc3", + "libmp3lame", + "libopencore_amrnb", + "libopus", + "libshine", + "libspeex", + "libtwolame", + "libvo_amrwbenc", + "libvorbis", + "mlp", + "mp2", + "mp2fixed", + "mp3", + "mp3_mf", + "nellymoser", + "opus", + "pcm_alaw", + "pcm_alaw_at", + "pcm_bluray", + "pcm_dvd", + "pcm_f32be", + "pcm_f32le", + "pcm_f64be", + "pcm_f64le", + "pcm_mulaw", + "pcm_mulaw_at", + "pcm_s16be", + "pcm_s16be_planar", + "pcm_s16le", + "pcm_s16le_planar", + "pcm_s24be", + "pcm_s24daud", + "pcm_s24le", + "pcm_s24le_planar", + "pcm_s32be", + "pcm_s32le", + "pcm_s32le_planar", + "pcm_s64be", + "pcm_s64le", + "pcm_s8", + "pcm_s8_planar", + "pcm_u16be", + "pcm_u16le", + "pcm_u24be", + "pcm_u24le", + "pcm_u32be", + "pcm_u32le", + "pcm_u8", + "pcm_vidc", + "ra_144", + "real_144", + "roq_dpcm", + "s302m", + "sbc", + "sonic", + "sonicls", + "speex", + "truehd", + "tta", + "vorbis", + "wavpack", + "wmav1", + "wmav2", +] + +__all__ = ("AudioFrame", "AudioStream") diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..753e96cb95142ca875cbd0819dd2779ec82b6971 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/codeccontext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/codeccontext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9323ccb3672551616798855c0ced22ffa78a0be6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/codeccontext.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/fifo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/fifo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfebe682fb81ef9447a0886f6057a587bf9d2559 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/fifo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/format.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daef2c59833831af8b55569e7e3c958443b60e18 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/format.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fda2832c636a099346ca03c47879c9ac3ce1885 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/frame.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/layout.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/layout.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b18257833fa211d4fc947205fc97f9ddfe070f33 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/layout.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/plane.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/plane.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53897653037f2d93a63cbf62f0ff706edfc85ab8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/plane.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/resampler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/resampler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f57c530f49f0860c2f999474a69a07087c719a2a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/resampler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/__pycache__/stream.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/stream.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b4265e290565e9755d1a931dcf3b531bfb7bab3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/audio/__pycache__/stream.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/audio/codeccontext.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..74f9aebdfc5a17896d089e58ebb7f6e22d5456a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:247a6e1a3fcd00766646e9fe923d0d898abf9617c8449b1c87ac4a57392d419e +size 334721 diff --git a/.venv/lib/python3.12/site-packages/av/audio/codeccontext.pxd b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.pxd new file mode 100644 index 0000000000000000000000000000000000000000..55ad15e9f0404d2b77810682774fd25ab434fadb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.pxd @@ -0,0 +1,11 @@ + +from av.audio.frame cimport AudioFrame +from av.audio.resampler cimport AudioResampler +from av.codec.context cimport CodecContext + + +cdef class AudioCodecContext(CodecContext): + # Hold onto the frames that we will decode until we have a full one. + cdef AudioFrame next_frame + # For encoding. + cdef AudioResampler resampler diff --git a/.venv/lib/python3.12/site-packages/av/audio/codeccontext.py b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.py new file mode 100644 index 0000000000000000000000000000000000000000..86ac107cfb8d9daa557fab33b7ad3c64748d275f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.py @@ -0,0 +1,109 @@ +import cython +from cython.cimports import libav as lib +from cython.cimports.av.audio.format import AudioFormat, get_audio_format +from cython.cimports.av.audio.frame import AudioFrame, alloc_audio_frame +from cython.cimports.av.audio.layout import AudioLayout, get_audio_layout +from cython.cimports.av.frame import Frame +from cython.cimports.av.packet import Packet + + +@cython.final +@cython.cclass +class AudioCodecContext(CodecContext): + @cython.cfunc + def _prepare_frames_for_encode(self, input_frame: Frame | None) -> list: + frame: AudioFrame | None = input_frame + allow_var_frame_size: cython.bint = ( + self.ptr.codec.capabilities & lib.AV_CODEC_CAP_VARIABLE_FRAME_SIZE + ) + + # Note that the resampler will simply return an input frame if there is + # no resampling to be done. The control flow was just a little easier this way. + if not self.resampler: + self.resampler = AudioResampler( + format=self.format, + layout=self.layout, + rate=self.ptr.sample_rate, + frame_size=None if allow_var_frame_size else self.ptr.frame_size, + ) + frames = self.resampler.resample(frame) + if input_frame is None: + frames.append(None) # flush if input frame is None + + return frames + + @cython.cfunc + def _alloc_next_frame(self) -> Frame: + return alloc_audio_frame() + + @cython.cfunc + def _setup_decoded_frame(self, frame: Frame, packet: Packet): + CodecContext._setup_decoded_frame(self, frame, packet) + aframe: AudioFrame = frame + aframe._init_user_attributes() + + @property + def frame_size(self): + """ + Number of samples per channel in an audio frame. + + :type: int + """ + return self.ptr.frame_size + + @property + def sample_rate(self): + """ + Sample rate of the audio data, in samples per second. + + :type: int + """ + return self.ptr.sample_rate + + @sample_rate.setter + def sample_rate(self, value: cython.int): + self._assert_not_open("sample_rate") + self.ptr.sample_rate = value + + @property + def rate(self): + """Another name for :attr:`sample_rate`.""" + return self.sample_rate + + @rate.setter + def rate(self, value): + self.sample_rate = value + + @property + def channels(self): + return self.layout.nb_channels + + @property + def layout(self): + """ + The audio channel layout. + + :type: AudioLayout + """ + return get_audio_layout(self.ptr.ch_layout) + + @layout.setter + def layout(self, value): + self._assert_not_open("layout") + layout: AudioLayout = AudioLayout(value) + self.ptr.ch_layout = layout.layout + + @property + def format(self): + """ + The audio sample format. + + :type: AudioFormat + """ + return get_audio_format(self.ptr.sample_fmt) + + @format.setter + def format(self, value): + self._assert_not_open("format") + format: AudioFormat = AudioFormat(value) + self.ptr.sample_fmt = format.sample_fmt diff --git a/.venv/lib/python3.12/site-packages/av/audio/codeccontext.pyi b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e871db698a93a664e4b1f1bcceca2c72b7d54016 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/codeccontext.pyi @@ -0,0 +1,30 @@ +from collections.abc import Iterator +from typing import Literal + +from av.codec.context import CodecContext +from av.packet import Packet + +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class _Format: + def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ... + def __set__(self, instance: object, value: AudioFormat | str) -> None: ... + +class _Layout: + def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ... + def __set__(self, instance: object, value: AudioLayout | str) -> None: ... + +class AudioCodecContext(CodecContext): + frame_size: int + sample_rate: int + rate: int + type: Literal["audio"] + format: _Format + layout: _Layout + @property + def channels(self) -> int: ... + def encode(self, frame: AudioFrame | None = None) -> list[Packet]: ... + def encode_lazy(self, frame: AudioFrame | None = None) -> Iterator[Packet]: ... + def decode(self, packet: Packet | None = None) -> list[AudioFrame]: ... diff --git a/.venv/lib/python3.12/site-packages/av/audio/fifo.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/fifo.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..65cabd449ecca010dd674049135802486d46e4fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/fifo.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc9ea7c490accbd2dae158ef8a46a1e33e31a7a04ed979c51ee7ae965fc925a4 +size 503033 diff --git a/.venv/lib/python3.12/site-packages/av/audio/fifo.pxd b/.venv/lib/python3.12/site-packages/av/audio/fifo.pxd new file mode 100644 index 0000000000000000000000000000000000000000..0ace5e4b1ec84daaeb09f27f6f9689a56d026912 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/fifo.pxd @@ -0,0 +1,19 @@ +cimport libav as lib +from libc.stdint cimport int64_t, uint64_t + +from av.audio.frame cimport AudioFrame + + +cdef class AudioFifo: + + cdef lib.AVAudioFifo *ptr + + cdef AudioFrame template + + cdef readonly uint64_t samples_written + cdef readonly uint64_t samples_read + cdef readonly double pts_per_sample + + cpdef write(self, AudioFrame frame) + cpdef read(self, int samples=*, bint partial=*) + cpdef read_many(self, int samples, bint partial=*) diff --git a/.venv/lib/python3.12/site-packages/av/audio/fifo.py b/.venv/lib/python3.12/site-packages/av/audio/fifo.py new file mode 100644 index 0000000000000000000000000000000000000000..00db125b7152457bf0e15bc571d3120bd27eba3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/fifo.py @@ -0,0 +1,222 @@ +import cython +from cython.cimports.av.audio.frame import alloc_audio_frame +from cython.cimports.av.error import err_check + + +@cython.final +@cython.cclass +class AudioFifo: + """A simple audio sample FIFO (First In First Out) buffer.""" + + def __repr__(self): + try: + result = ( + f"" + ) + except AttributeError: + result = ( + f"" + ) + return result + + def __dealloc__(self): + if self.ptr: + lib.av_audio_fifo_free(self.ptr) + + @cython.ccall + def write(self, frame: AudioFrame | None): + """write(frame) + + Push a frame of samples into the queue. + + :param AudioFrame frame: The frame of samples to push. + + The FIFO will remember the attributes from the first frame, and use those + to populate all output frames. + + If there is a :attr:`~.Frame.pts` and :attr:`~.Frame.time_base` and + :attr:`~.AudioFrame.sample_rate`, then the FIFO will assert that the incoming + timestamps are continuous. + + """ + + if frame is None: + raise TypeError("AudioFifo must be given an AudioFrame.") + + if not frame.ptr.nb_samples: + return + + if not self.ptr: + # Hold onto a copy of the attributes of the first frame to populate + # output frames with. + self.template = alloc_audio_frame() + self.template._copy_internal_attributes(frame) + self.template._init_user_attributes() + + # Figure out our "time_base". + if frame._time_base.num and frame.ptr.sample_rate: + self.pts_per_sample = frame._time_base.den / float(frame._time_base.num) + self.pts_per_sample /= frame.ptr.sample_rate + else: + self.pts_per_sample = 0 + + self.ptr = lib.av_audio_fifo_alloc( + cython.cast(lib.AVSampleFormat, frame.ptr.format), + frame.layout.nb_channels, + frame.ptr.nb_samples + * 2, # Just a default number of samples; it will adjust. + ) + + if not self.ptr: + raise RuntimeError("Could not allocate AVAudioFifo.") + + # Make sure nothing changed. + elif ( + frame.ptr.format != self.template.ptr.format + or frame.ptr.sample_rate != self.template.ptr.sample_rate + or ( + frame._time_base.num + and self.template._time_base.num + and ( + frame._time_base.num != self.template._time_base.num + or frame._time_base.den != self.template._time_base.den + ) + ) + ): + raise ValueError("Frame does not match AudioFifo parameters.") + + # Assert that the PTS are what we expect. + expected_pts = cython.declare(int64_t) + if self.pts_per_sample and frame.ptr.pts != lib.AV_NOPTS_VALUE: + expected_pts = cython.cast( + int64_t, self.pts_per_sample * self.samples_written + ) + if frame.ptr.pts != expected_pts: + raise ValueError( + f"Frame.pts ({frame.ptr.pts}) != expected ({expected_pts}); " + "fix or set to None." + ) + + err_check( + lib.av_audio_fifo_write( + self.ptr, + cython.cast(cython.pointer[cython.p_void], frame.ptr.extended_data), + frame.ptr.nb_samples, + ) + ) + + self.samples_written += frame.ptr.nb_samples + + @cython.ccall + def read(self, samples: cython.int = 0, partial: cython.bint = False): + """read(samples=0, partial=False) + + Read samples from the queue. + + :param int samples: The number of samples to pull; 0 gets all. + :param bool partial: Allow returning less than requested. + :returns: New :class:`AudioFrame` or ``None`` (if empty). + + If the incoming frames had valid a :attr:`~.Frame.time_base`, + :attr:`~.AudioFrame.sample_rate` and :attr:`~.Frame.pts`, the returned frames + will have accurate timing. + + """ + + if not self.ptr: + return + + buffered_samples: cython.int = lib.av_audio_fifo_size(self.ptr) + if buffered_samples < 1: + return + + samples = samples or buffered_samples + + if buffered_samples < samples: + if partial: + samples = buffered_samples + else: + return + + frame: AudioFrame = alloc_audio_frame() + frame._copy_internal_attributes(self.template) + frame._init( + cython.cast(lib.AVSampleFormat, self.template.ptr.format), + cython.cast(lib.AVChannelLayout, self.template.ptr.ch_layout), + samples, + 1, # Align? + ) + + err_check( + lib.av_audio_fifo_read( + self.ptr, + cython.cast(cython.pointer[cython.p_void], frame.ptr.extended_data), + samples, + ) + ) + + if self.pts_per_sample: + frame.ptr.pts = cython.cast( + uint64_t, self.pts_per_sample * self.samples_read + ) + else: + frame.ptr.pts = lib.AV_NOPTS_VALUE + + self.samples_read += samples + return frame + + @cython.ccall + def read_many(self, samples: cython.int, partial: cython.bint = False): + """read_many(samples, partial=False) + + Read as many frames as we can. + + :param int samples: How large for the frames to be. + :param bool partial: If we should return a partial frame. + :returns: A ``list`` of :class:`AudioFrame`. + + """ + + frame: AudioFrame + frames: list = [] + while True: + frame = self.read(samples, partial=partial) + if frame is not None: + frames.append(frame) + else: + break + + return frames + + @property + def format(self): + """The :class:`.AudioFormat` of this FIFO.""" + if not self.ptr: + raise AttributeError( + f"'{__name__}.AudioFifo' object has no attribute 'format'" + ) + return self.template.format + + @property + def layout(self): + """The :class:`.AudioLayout` of this FIFO.""" + if not self.ptr: + raise AttributeError( + f"'{__name__}.AudioFifo' object has no attribute 'layout'" + ) + return self.template.layout + + @property + def sample_rate(self): + if not self.ptr: + raise AttributeError( + f"'{__name__}.AudioFifo' object has no attribute 'sample_rate'" + ) + return self.template.sample_rate + + @property + def samples(self): + """Number of audio samples (per channel) in the buffer.""" + return lib.av_audio_fifo_size(self.ptr) if self.ptr else 0 diff --git a/.venv/lib/python3.12/site-packages/av/audio/fifo.pyi b/.venv/lib/python3.12/site-packages/av/audio/fifo.pyi new file mode 100644 index 0000000000000000000000000000000000000000..085ed4bba1039b77675da29e26ef9ccbd539c8e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/fifo.pyi @@ -0,0 +1,22 @@ +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class AudioFifo: + def write(self, frame: AudioFrame) -> None: ... + def read(self, samples: int = 0, partial: bool = False) -> AudioFrame | None: ... + def read_many(self, samples: int, partial: bool = False) -> list[AudioFrame]: ... + @property + def format(self) -> AudioFormat: ... + @property + def layout(self) -> AudioLayout: ... + @property + def sample_rate(self) -> int: ... + @property + def samples(self) -> int: ... + @property + def samples_written(self) -> int: ... + @property + def samples_read(self) -> int: ... + @property + def pts_per_sample(self) -> float: ... diff --git a/.venv/lib/python3.12/site-packages/av/audio/format.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/format.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..99dc643a10ede55551d6776b360c9b7de86476e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/format.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1583699b58ab12123fb466fbd241c82bfd6edf5bb00520aa7ef955d003c77e53 +size 220209 diff --git a/.venv/lib/python3.12/site-packages/av/audio/format.pxd b/.venv/lib/python3.12/site-packages/av/audio/format.pxd new file mode 100644 index 0000000000000000000000000000000000000000..c4d4bc552a5a9736ab87a83817a97f6ca62d6b2a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/format.pxd @@ -0,0 +1,7 @@ +cimport libav as lib + + +cdef class AudioFormat: + cdef lib.AVSampleFormat sample_fmt + +cdef AudioFormat get_audio_format(lib.AVSampleFormat format) diff --git a/.venv/lib/python3.12/site-packages/av/audio/format.py b/.venv/lib/python3.12/site-packages/av/audio/format.py new file mode 100644 index 0000000000000000000000000000000000000000..d398f6924c491e5a86c67dcd8e5054e4f327b57b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/format.py @@ -0,0 +1,145 @@ +import sys + +import cython + +container_format_postfix = cython.declare( + str, "le" if sys.byteorder == "little" else "be" +) +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def get_audio_format(c_format: lib.AVSampleFormat) -> AudioFormat: + """Get an AudioFormat without going through a string.""" + + if c_format < 0: + return None + + format: AudioFormat = AudioFormat(_cinit_bypass_sentinel) + format.sample_fmt = c_format + return format + + +@cython.final +@cython.cclass +class AudioFormat: + """Descriptor of audio formats.""" + + def __cinit__(self, name): + if name is _cinit_bypass_sentinel: + return + + sample_fmt: lib.AVSampleFormat + if isinstance(name, AudioFormat): + sample_fmt = cython.cast(AudioFormat, name).sample_fmt + else: + sample_fmt = lib.av_get_sample_fmt(name) + + if sample_fmt < 0: + raise ValueError(f"Not a sample format: {name!r}") + + self.sample_fmt = sample_fmt + + def __repr__(self): + return f"" + + @property + def name(self): + """Canonical name of the sample format. + + >>> AudioFormat('s16p').name + 's16p' + + """ + return lib.av_get_sample_fmt_name(self.sample_fmt) + + @property + def bytes(self): + """Number of bytes per sample. + + >>> AudioFormat('s16p').bytes + 2 + + """ + return lib.av_get_bytes_per_sample(self.sample_fmt) + + @property + def bits(self): + """Number of bits per sample. + + >>> AudioFormat('s16p').bits + 16 + + """ + return lib.av_get_bytes_per_sample(self.sample_fmt) << 3 + + @property + def is_planar(self): + """Is this a planar format? + + Strictly opposite of :attr:`is_packed`. + + """ + return bool(lib.av_sample_fmt_is_planar(self.sample_fmt)) + + @property + def is_packed(self): + """Is this a packed format? + + Strictly opposite of :attr:`is_planar`. + + """ + return not lib.av_sample_fmt_is_planar(self.sample_fmt) + + @property + def planar(self): + """The planar variant of this format. + + Is itself when planar: + + >>> fmt = AudioFormat('s16p') + >>> fmt.planar is fmt + True + + """ + if self.is_planar: + return self + return get_audio_format(lib.av_get_planar_sample_fmt(self.sample_fmt)) + + @property + def packed(self): + """The packed variant of this format. + + Is itself when packed: + + >>> fmt = AudioFormat('s16') + >>> fmt.packed is fmt + True + + """ + if self.is_packed: + return self + return get_audio_format(lib.av_get_packed_sample_fmt(self.sample_fmt)) + + @property + def container_name(self): + """The name of a :class:`ContainerFormat` which directly accepts this data. + + :raises ValueError: when planar, since there are no such containers. + + """ + if self.is_planar: + raise ValueError("no planar container formats") + + if self.sample_fmt == lib.AV_SAMPLE_FMT_U8: + return "u8" + elif self.sample_fmt == lib.AV_SAMPLE_FMT_S16: + return "s16" + container_format_postfix + elif self.sample_fmt == lib.AV_SAMPLE_FMT_S32: + return "s32" + container_format_postfix + elif self.sample_fmt == lib.AV_SAMPLE_FMT_FLT: + return "f32" + container_format_postfix + elif self.sample_fmt == lib.AV_SAMPLE_FMT_DBL: + return "f64" + container_format_postfix + + raise ValueError("unknown layout") diff --git a/.venv/lib/python3.12/site-packages/av/audio/format.pyi b/.venv/lib/python3.12/site-packages/av/audio/format.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5f7e322edc85d831b5b6cc9979fd4dfca4b994c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/format.pyi @@ -0,0 +1,11 @@ +class AudioFormat: + name: str + bytes: int + bits: int + is_planar: bool + is_packed: bool + planar: AudioFormat + packed: AudioFormat + container_name: str + + def __init__(self, name: str | AudioFormat) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/audio/frame.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/frame.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..005599d8fe07f9ba2e52af8dbff1d94864fa3d51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/frame.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1c8f3986aa05cb4f3f9b5e840ad13dbcce31989e8d0797d6516b4c56db90dcd +size 659097 diff --git a/.venv/lib/python3.12/site-packages/av/audio/frame.pxd b/.venv/lib/python3.12/site-packages/av/audio/frame.pxd new file mode 100644 index 0000000000000000000000000000000000000000..398d76d33ea1173e31a5e13809ba3910385572b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/frame.pxd @@ -0,0 +1,31 @@ +cimport libav as lib +from libc.stdint cimport uint8_t, uint64_t + +from av.audio.format cimport AudioFormat +from av.audio.layout cimport AudioLayout +from av.frame cimport Frame + + +cdef class AudioFrame(Frame): + # For raw storage of the frame's data; don't ever touch this. + cdef uint8_t *_buffer + cdef size_t _buffer_size + + cdef readonly AudioLayout layout + """ + The audio channel layout. + + :type: AudioLayout + """ + + cdef readonly AudioFormat format + """ + The audio sample format. + + :type: AudioFormat + """ + + cdef _init(self, lib.AVSampleFormat format, lib.AVChannelLayout layout, unsigned int nb_samples, unsigned int align) + cdef _init_user_attributes(self) + +cdef AudioFrame alloc_audio_frame() diff --git a/.venv/lib/python3.12/site-packages/av/audio/frame.py b/.venv/lib/python3.12/site-packages/av/audio/frame.py new file mode 100644 index 0000000000000000000000000000000000000000..214a947e3c2cbbd0cb11b874bbdffd3c5d2375fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/frame.py @@ -0,0 +1,206 @@ +import cython +from cython.cimports.av.audio.format import get_audio_format +from cython.cimports.av.audio.layout import get_audio_layout +from cython.cimports.av.audio.plane import AudioPlane +from cython.cimports.av.error import err_check +from cython.cimports.av.utils import check_ndarray + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def alloc_audio_frame() -> AudioFrame: + return AudioFrame(_cinit_bypass_sentinel) + + +format_dtypes = { + "dbl": "f8", + "dblp": "f8", + "flt": "f4", + "fltp": "f4", + "s16": "i2", + "s16p": "i2", + "s32": "i4", + "s32p": "i4", + "u8": "u1", + "u8p": "u1", +} + + +@cython.final +@cython.cclass +class AudioFrame(Frame): + """A frame of audio.""" + + def __cinit__(self, format="s16", layout="stereo", samples=0, align=1): + if format is _cinit_bypass_sentinel: + return + + cy_format: AudioFormat = AudioFormat(format) + cy_layout: AudioLayout = AudioLayout(layout) + self._init(cy_format.sample_fmt, cy_layout.layout, samples, align) + + @cython.cfunc + def _init( + self, + format: lib.AVSampleFormat, + layout: lib.AVChannelLayout, + nb_samples: cython.uint, + align: cython.uint, + ): + self.ptr.nb_samples = nb_samples + self.ptr.format = format + self.ptr.ch_layout = layout + + # Sometimes this is called twice. Oh well. + self._init_user_attributes() + + if self.layout.nb_channels != 0 and nb_samples: + # Cleanup the old buffer. + lib.av_freep(cython.address(self._buffer)) + + # Get a new one. + self._buffer_size = err_check( + lib.av_samples_get_buffer_size( + cython.NULL, self.layout.nb_channels, nb_samples, format, align + ) + ) + self._buffer = cython.cast( + cython.pointer[uint8_t], lib.av_malloc(self._buffer_size) + ) + if not self._buffer: + raise MemoryError("cannot allocate AudioFrame buffer") + + # Connect the data pointers to the buffer. + err_check( + lib.avcodec_fill_audio_frame( + self.ptr, + self.layout.nb_channels, + cython.cast(lib.AVSampleFormat, self.ptr.format), + self._buffer, + cython.cast(cython.int, self._buffer_size), + align, + ) + ) + + def __dealloc__(self): + lib.av_freep(cython.address(self._buffer)) + + @cython.cfunc + def _init_user_attributes(self): + self.layout = get_audio_layout(self.ptr.ch_layout) + self.format = get_audio_format(cython.cast(lib.AVSampleFormat, self.ptr.format)) + + def __repr__(self): + return ( + f"" + ) + + @staticmethod + def from_ndarray(array, format="s16", layout="stereo"): + """ + Construct a frame from a numpy array. + """ + import numpy as np + + py_format = format if isinstance(format, AudioFormat) else AudioFormat(format) + py_layout = layout if isinstance(layout, AudioLayout) else AudioLayout(layout) + format = py_format.name + + # map avcodec type to numpy type + try: + dtype = np.dtype(format_dtypes[format]) + except KeyError: + raise ValueError( + f"Conversion from numpy array with format `{format}` is not yet supported" + ) + + # check input format + nb_channels = py_layout.nb_channels + check_ndarray(array, dtype, 2) + if py_format.is_planar: + if array.shape[0] != nb_channels: + raise ValueError( + f"Expected planar `array.shape[0]` to equal `{nb_channels}` but got `{array.shape[0]}`" + ) + samples = array.shape[1] + else: + if array.shape[0] != 1: + raise ValueError( + f"Expected packed `array.shape[0]` to equal `1` but got `{array.shape[0]}`" + ) + samples = array.shape[1] // nb_channels + + frame = AudioFrame(format=py_format, layout=py_layout, samples=samples) + for i, plane in enumerate(frame.planes): + plane.update(array[i, :]) + return frame + + @property + def planes(self): + """ + A tuple of :class:`~av.audio.plane.AudioPlane`. + + :type: tuple + """ + plane_count: cython.int = 0 + while self.ptr.extended_data[plane_count]: + plane_count += 1 + + return tuple([AudioPlane(self, i) for i in range(plane_count)]) + + @property + def samples(self): + """ + Number of audio samples (per channel). + + :type: int + """ + return self.ptr.nb_samples + + @property + def sample_rate(self): + """ + Sample rate of the audio data, in samples per second. + + :type: int + """ + return self.ptr.sample_rate + + @sample_rate.setter + def sample_rate(self, value): + self.ptr.sample_rate = value + + @property + def rate(self): + """Another name for :attr:`sample_rate`.""" + return self.ptr.sample_rate + + @rate.setter + def rate(self, value): + self.ptr.sample_rate = value + + def to_ndarray(self): + """Get a numpy array of this frame. + + .. note:: Numpy must be installed. + + """ + import numpy as np + + try: + dtype = np.dtype(format_dtypes[self.format.name]) + except KeyError: + raise ValueError( + f"Conversion from {self.format.name!r} format to numpy array is not supported." + ) + + if self.format.is_planar: + count = self.samples + else: + count = self.samples * self.layout.nb_channels + + return np.vstack( + [np.frombuffer(x, dtype=dtype, count=count) for x in self.planes] + ) diff --git a/.venv/lib/python3.12/site-packages/av/audio/frame.pyi b/.venv/lib/python3.12/site-packages/av/audio/frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8efb2676063769e56e9cddbf17d2c7586aa5b6cd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/frame.pyi @@ -0,0 +1,49 @@ +from typing import Any + +import numpy as np + +from av.frame import Frame + +from .format import AudioFormat +from .layout import AudioLayout +from .plane import AudioPlane + +format_dtypes: dict[str, str] +_SupportedNDarray = ( + np.ndarray[Any, np.dtype[np.float64]] # f8 + | np.ndarray[Any, np.dtype[np.float32]] # f4 + | np.ndarray[Any, np.dtype[np.int32]] # i4 + | np.ndarray[Any, np.dtype[np.int16]] # i2 + | np.ndarray[Any, np.dtype[np.uint8]] # u1 +) + +class _Format: + def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ... + def __set__(self, instance: object, value: AudioFormat | str) -> None: ... + +class _Layout: + def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ... + def __set__(self, instance: object, value: AudioLayout | str) -> None: ... + +class AudioFrame(Frame): + planes: tuple[AudioPlane, ...] + samples: int + sample_rate: int + rate: int + format: _Format + layout: _Layout + + def __init__( + self, + format: AudioFormat | str = "s16", + layout: AudioLayout | str = "stereo", + samples: int = 0, + align: int = 1, + ) -> None: ... + @staticmethod + def from_ndarray( + array: _SupportedNDarray, + format: AudioFormat | str = "s16", + layout: AudioLayout | str = "stereo", + ) -> AudioFrame: ... + def to_ndarray(self) -> _SupportedNDarray: ... diff --git a/.venv/lib/python3.12/site-packages/av/audio/layout.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/layout.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..cad03f13460223fe96813cced6f8244a5009cf5d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/layout.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4d77aeeb97e38baa1b1376da950c674094a27cd2410e08ba3727739d4b27e8f +size 392873 diff --git a/.venv/lib/python3.12/site-packages/av/audio/layout.pxd b/.venv/lib/python3.12/site-packages/av/audio/layout.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d7e991e95586e41b6cafe444aab25c010d20d330 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/layout.pxd @@ -0,0 +1,7 @@ +cimport libav as lib + + +cdef class AudioLayout: + cdef lib.AVChannelLayout layout + +cdef AudioLayout get_audio_layout(lib.AVChannelLayout c_layout) diff --git a/.venv/lib/python3.12/site-packages/av/audio/layout.py b/.venv/lib/python3.12/site-packages/av/audio/layout.py new file mode 100644 index 0000000000000000000000000000000000000000..f3adb3514c5eeecc5f03d3f39e49c0c18fd55ee2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/layout.py @@ -0,0 +1,109 @@ +from dataclasses import dataclass + +import cython +from cython.cimports import libav as lib +from cython.cimports.cpython.bytes import PyBytes_FromStringAndSize + + +@dataclass +class AudioChannel: + name: str + description: str + + def __repr__(self): + return f"" + + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def get_audio_layout(c_layout: lib.AVChannelLayout) -> AudioLayout: + """Get an AudioLayout from Cython land.""" + layout: AudioLayout = AudioLayout(_cinit_bypass_sentinel) + layout.layout = c_layout + return layout + + +@cython.final +@cython.cclass +class AudioLayout: + def __dealloc__(self): + lib.av_channel_layout_uninit(cython.address(self.layout)) + + def __cinit__(self, layout): + if layout is _cinit_bypass_sentinel: + return + + if type(layout) is str: + ret = lib.av_channel_layout_from_string(cython.address(c_layout), layout) + if ret != 0: + raise ValueError(f"Invalid layout: {layout}") + elif isinstance(layout, AudioLayout): + c_layout = cython.cast(AudioLayout, layout).layout + else: + raise TypeError( + f"layout must be of type: string | av.AudioLayout, got {type(layout)}" + ) + + self.layout = c_layout + + def __repr__(self): + return f"" + + def __eq__(self, other): + if not isinstance(other, AudioLayout): + return False + c_other: lib.AVChannelLayout = cython.cast(AudioLayout, other).layout + return ( + lib.av_channel_layout_compare( + cython.address(self.layout), cython.address(c_other) + ) + == 0 + ) + + @property + def nb_channels(self): + return self.layout.nb_channels + + @property + def channels(self): + buf: cython.char[16] + buf2: cython.char[128] + + results: list = [] + for index in range(self.layout.nb_channels): + size = lib.av_channel_name( + buf, + cython.sizeof(buf), + lib.av_channel_layout_channel_from_index( + cython.address(self.layout), index + ), + ) + size2 = lib.av_channel_description( + buf2, + cython.sizeof(buf2), + lib.av_channel_layout_channel_from_index( + cython.address(self.layout), index + ), + ) + results.append( + AudioChannel( + PyBytes_FromStringAndSize(buf, size - 1).decode("utf-8"), + PyBytes_FromStringAndSize(buf2, size2 - 1).decode("utf-8"), + ) + ) + + return tuple(results) + + @property + def name(self) -> str: + """The canonical name of the audio layout.""" + layout_name: cython.char[129] + ret: cython.int = lib.av_channel_layout_describe( + cython.address(self.layout), layout_name, cython.sizeof(layout_name) + ) + if ret < 0: + raise RuntimeError(f"Failed to get layout name: {ret}") + + return layout_name diff --git a/.venv/lib/python3.12/site-packages/av/audio/layout.pyi b/.venv/lib/python3.12/site-packages/av/audio/layout.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9fdf0ac1531ff4d74ac60ee191ab899755443cf1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/layout.pyi @@ -0,0 +1,12 @@ +from dataclasses import dataclass + +class AudioLayout: + name: str + nb_channels: int + channels: tuple[AudioChannel, ...] + def __init__(self, layout: str | AudioLayout): ... + +@dataclass +class AudioChannel: + name: str + description: str diff --git a/.venv/lib/python3.12/site-packages/av/audio/plane.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/plane.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..eec89312f043038600153b9bd52d4fa0b0aed5f5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/plane.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7467b333c38deec2891e810350448a7dcb640b317c8a17e611f57e035b4cb34 +size 281377 diff --git a/.venv/lib/python3.12/site-packages/av/audio/plane.pxd b/.venv/lib/python3.12/site-packages/av/audio/plane.pxd new file mode 100644 index 0000000000000000000000000000000000000000..de912ac2216b9ff4e9bf3bdda8ee93763e870a4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/plane.pxd @@ -0,0 +1,6 @@ +from av.plane cimport Plane + + +cdef class AudioPlane(Plane): + cdef readonly size_t buffer_size + cdef size_t _buffer_size(self) diff --git a/.venv/lib/python3.12/site-packages/av/audio/plane.py b/.venv/lib/python3.12/site-packages/av/audio/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..e68b5403e1b2d494a1b7d23e3a90ba9bc265d6a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/plane.py @@ -0,0 +1,14 @@ +import cython +from cython.cimports.av.audio.frame import AudioFrame + + +@cython.final +@cython.cclass +class AudioPlane(Plane): + def __cinit__(self, frame: AudioFrame, index: cython.int): + # Only the first linesize is ever populated, but it applies to every plane. + self.buffer_size = self.frame.ptr.linesize[0] + + @cython.cfunc + def _buffer_size(self) -> cython.size_t: + return self.buffer_size diff --git a/.venv/lib/python3.12/site-packages/av/audio/plane.pyi b/.venv/lib/python3.12/site-packages/av/audio/plane.pyi new file mode 100644 index 0000000000000000000000000000000000000000..64524dcdb5170ebfbee5aaafff86f37f9a476444 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/plane.pyi @@ -0,0 +1,4 @@ +from av.plane import Plane + +class AudioPlane(Plane): + buffer_size: int diff --git a/.venv/lib/python3.12/site-packages/av/audio/resampler.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/resampler.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..66ca12b4946db1907d59d4ce8e76f58b1cee775f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/resampler.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5bf9fde83f64a587520b0cc08cb53748846702ab72bb7b6210c3ab4ccb3ae7c +size 552377 diff --git a/.venv/lib/python3.12/site-packages/av/audio/resampler.pxd b/.venv/lib/python3.12/site-packages/av/audio/resampler.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2846bdfb64376d4c4d9f9dbaebd30b0a51ddde8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/resampler.pxd @@ -0,0 +1,19 @@ +from av.audio.format cimport AudioFormat +from av.audio.frame cimport AudioFrame +from av.audio.layout cimport AudioLayout +from av.filter.graph cimport Graph + + +cdef class AudioResampler: + cdef readonly bint is_passthrough + cdef AudioFrame template + + # Destination descriptors + cdef readonly AudioFormat format + cdef readonly AudioLayout layout + cdef readonly int rate + cdef readonly unsigned int frame_size + cdef readonly dict options + + cdef Graph graph + cpdef list resample(self, AudioFrame) diff --git a/.venv/lib/python3.12/site-packages/av/audio/resampler.py b/.venv/lib/python3.12/site-packages/av/audio/resampler.py new file mode 100644 index 0000000000000000000000000000000000000000..785e522b9f05656f536139d080e90e0649682a7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/resampler.py @@ -0,0 +1,140 @@ +from errno import EAGAIN + +import cython +from cython.cimports.av.filter.graph import Graph + +from av.error import FFmpegError + + +@cython.final +@cython.cclass +class AudioResampler: + """AudioResampler(format=None, layout=None, rate=None, frame_size=None, options=None) + + :param AudioFormat format: The target format, or string that parses to one + (e.g. ``"s16"``). + :param AudioLayout layout: The target layout, or an int/string that parses + to one (e.g. ``"stereo"``). + :param int rate: The target sample rate. + :param int frame_size: The number of samples per output frame. + :param dict options: ``libswresample`` options passed to the underlying + ``aresample`` filter (e.g. ``{"resampler": "soxr", "precision": "28"}``). + See the `FFmpeg resampler documentation + `_ for the full list. + """ + + def __cinit__( + self, format=None, layout=None, rate=None, frame_size=None, options=None + ): + if format is not None: + self.format = ( + format if isinstance(format, AudioFormat) else AudioFormat(format) + ) + + if layout is not None: + self.layout = AudioLayout(layout) + + self.rate = int(rate) if rate else 0 + self.frame_size = int(frame_size) if frame_size else 0 + self.options = {str(k): str(v) for k, v in options.items()} if options else {} + self.graph = None + + @cython.ccall + def resample(self, frame: AudioFrame | None) -> list: + """resample(frame) + + Convert the ``sample_rate``, ``channel_layout`` and/or ``format`` of + a :class:`~.AudioFrame`. + + :param AudioFrame frame: The frame to convert or `None` to flush. + :returns: A list of :class:`AudioFrame` in new parameters. If the nothing is to be done return the same frame + as a single element list. + + """ + # We don't have any input, so don't bother even setting up. + if not self.graph and frame is None: + return [] + + # Shortcut for passthrough. + if self.is_passthrough: + return [frame] + + # Take source settings from the first frame. + if not self.graph: + self.template = frame + + # Set some default descriptors. + self.format = self.format or frame.format + self.layout = self.layout or frame.layout + self.rate = self.rate or frame.sample_rate + + # Check if we can passthrough or if there is actually work to do. + if ( + frame.format.sample_fmt == self.format.sample_fmt + and frame.layout == self.layout + and frame.sample_rate == self.rate + and self.frame_size == 0 + ): + self.is_passthrough = True + return [frame] + + # handle resampling with aformat filter + # (similar to configure_output_audio_filter from ffmpeg) + self.graph = Graph() + extra_args = {} + if frame.time_base is not None: + extra_args["time_base"] = f"{frame.time_base}" + + abuffer = self.graph.add( + "abuffer", + sample_rate=f"{frame.sample_rate}", + sample_fmt=AudioFormat(frame.format).name, + channel_layout=frame.layout.name, + **extra_args, + ) + aformat = self.graph.add( + "aformat", + sample_rates=f"{self.rate}", + sample_fmts=self.format.name, + channel_layouts=self.layout.name, + ) + abuffersink = self.graph.add("abuffersink") + + # When libswresample options are given, do the conversion with an + # explicit aresample filter (which owns the SwrContext) instead of + # relying on the one FFmpeg auto-inserts before aformat. + if self.options: + aresample = self.graph.add("aresample", **self.options) + abuffer.link_to(aresample) + aresample.link_to(aformat) + else: + abuffer.link_to(aformat) + + aformat.link_to(abuffersink) + self.graph.configure() + + if self.frame_size > 0: + self.graph.set_audio_frame_size(self.frame_size) + + if frame is not None: + if ( + frame.format.sample_fmt != self.template.format.sample_fmt + or frame.layout != self.template.layout + or frame.sample_rate != self.template.rate + ): + raise ValueError("Frame does not match AudioResampler setup.") + + self.graph.push(frame) + + output: list = [] + while True: + try: + output.append(self.graph.pull()) + except EOFError: + break + except FFmpegError as e: + if e.errno != EAGAIN: + raise + break + + return output diff --git a/.venv/lib/python3.12/site-packages/av/audio/resampler.pyi b/.venv/lib/python3.12/site-packages/av/audio/resampler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..80c16cf08c44f825ebd97db1ef261dfdb363c3f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/resampler.pyi @@ -0,0 +1,23 @@ +from av.filter.graph import Graph + +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class AudioResampler: + rate: int + frame_size: int + format: AudioFormat + layout: AudioLayout + options: dict[str, str] + graph: Graph | None + + def __init__( + self, + format: str | int | AudioFormat | None = None, + layout: str | int | AudioLayout | None = None, + rate: int | None = None, + frame_size: int | None = None, + options: dict[str, str] | None = None, + ) -> None: ... + def resample(self, frame: AudioFrame | None) -> list[AudioFrame]: ... diff --git a/.venv/lib/python3.12/site-packages/av/audio/stream.abi3.so b/.venv/lib/python3.12/site-packages/av/audio/stream.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..d0c20ea83cf6268ef4e6e49aed47cc1e8413dc99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/stream.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88682c6152e2d5017f7dd204126aa340d2278d5ff747f7494bf5c13fcc6a0b80 +size 330729 diff --git a/.venv/lib/python3.12/site-packages/av/audio/stream.pxd b/.venv/lib/python3.12/site-packages/av/audio/stream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..8462061f8e0da6cd418527a73ac80d8ce59d7f0e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/stream.pxd @@ -0,0 +1,9 @@ +from av.packet cimport Packet +from av.stream cimport Stream + +from .frame cimport AudioFrame + + +cdef class AudioStream(Stream): + cpdef encode(self, AudioFrame frame=?) + cpdef decode(self, Packet packet=?) diff --git a/.venv/lib/python3.12/site-packages/av/audio/stream.py b/.venv/lib/python3.12/site-packages/av/audio/stream.py new file mode 100644 index 0000000000000000000000000000000000000000..e7fc63560cbc504ea005ee90dc94dd9fdeb77482 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/stream.py @@ -0,0 +1,54 @@ +import cython +from cython.cimports import libav as lib +from cython.cimports.av.audio.frame import AudioFrame +from cython.cimports.av.packet import Packet + + +@cython.final +@cython.cclass +class AudioStream(Stream): + def __repr__(self): + if self.codec_context is None: + return f" at 0x{id(self):x}>" + form = self.format.name if self.format else None + return ( + f"" + ) + + def __getattr__(self, 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: AudioFrame | None = None): + """ + Encode an :class:`.AudioFrame` and return a list of :class:`.Packet`. + + :rtype: list[Packet] + + .. seealso:: This is mostly a passthrough to :meth:`.CodecContext.encode`. + """ + 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:`.AudioFrame`. + + :rtype: list[AudioFrame] + + .. seealso:: This is a passthrough to :meth:`.CodecContext.decode`. + """ + self._assert_has_codec_context() + return self.codec_context.decode(packet) diff --git a/.venv/lib/python3.12/site-packages/av/audio/stream.pyi b/.venv/lib/python3.12/site-packages/av/audio/stream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f92fb52ba2a941f1f539b690bb3b26fc434a8ec3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/audio/stream.pyi @@ -0,0 +1,32 @@ +from typing import Literal + +from av.packet import Packet +from av.stream import Stream + +from .codeccontext import AudioCodecContext +from .format import AudioFormat +from .frame import AudioFrame +from .layout import AudioLayout + +class _Format: + def __get__(self, i: object | None, owner: type | None = None) -> AudioFormat: ... + def __set__(self, instance: object, value: AudioFormat | str) -> None: ... + +class _Layout: + def __get__(self, i: object | None, owner: type | None = None) -> AudioLayout: ... + def __set__(self, instance: object, value: AudioLayout | str) -> None: ... + +class AudioStream(Stream): + codec_context: AudioCodecContext + def encode(self, frame: AudioFrame | None = None) -> list[Packet]: ... + def decode(self, packet: Packet | None = None) -> list[AudioFrame]: ... + + # From codec context + frame_size: int + sample_rate: int + bit_rate: int + rate: int + channels: int + type: Literal["audio"] + format: _Format + layout: _Layout diff --git a/.venv/lib/python3.12/site-packages/av/bitstream.abi3.so b/.venv/lib/python3.12/site-packages/av/bitstream.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..777cd4a56759413488f83965cfe20a0ce540d744 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/bitstream.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:119736502925e3949bc43264a0dd9fb824f2dc0468116e9807b942fddb160d1b +size 289809 diff --git a/.venv/lib/python3.12/site-packages/av/bitstream.pxd b/.venv/lib/python3.12/site-packages/av/bitstream.pxd new file mode 100644 index 0000000000000000000000000000000000000000..dbb89c9844551a1b17f839e03604b7821294f1a0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/bitstream.pxd @@ -0,0 +1,11 @@ +cimport libav as lib + +from av.packet cimport Packet + + +cdef class BitStreamFilterContext: + + cdef lib.AVBSFContext *ptr + + cpdef filter(self, Packet packet=?) + cpdef flush(self) diff --git a/.venv/lib/python3.12/site-packages/av/bitstream.py b/.venv/lib/python3.12/site-packages/av/bitstream.py new file mode 100644 index 0000000000000000000000000000000000000000..a3bc0088b551b927a1bc9acb9ce1ce953f49f4a8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/bitstream.py @@ -0,0 +1,132 @@ +import cython +import cython.cimports.libav as lib +from cython.cimports.av.codec.codec import Codec +from cython.cimports.av.error import err_check +from cython.cimports.av.packet import Packet +from cython.cimports.av.stream import Stream +from cython.cimports.libc.errno import EAGAIN + + +@cython.final +@cython.cclass +class BitStreamFilterContext: + """ + Initializes a bitstream filter: a way to directly modify packet data. + + Wraps :ffmpeg:`AVBSFContext` + + :param in_stream: Defines the input codec for the bitfilter. A :class:`.Stream` + copies the full input codec parameters, while a :class:`.Codec` or a codec-name + ``str`` only pins the input codec, which is all a codec-specific filter (such as + ``h264_mp4toannexb``) needs to initialize. + :type in_stream: :class:`.Stream`, :class:`.Codec`, str, or None + :param Stream out_stream: A stream whose codec is overwritten using the output parameters from the bitfilter. + """ + + def __cinit__( + self, + filter_description, + in_stream: Stream | Codec | str | None = None, + out_stream: Stream | None = None, + ): + res: cython.int + filter_str: cython.p_char = filter_description + + with cython.nogil: + res = lib.av_bsf_list_parse_str(filter_str, cython.address(self.ptr)) + err_check(res) + + if isinstance(in_stream, Stream): + with cython.nogil: + res = lib.avcodec_parameters_copy( + self.ptr.par_in, cython.cast(Stream, in_stream).ptr.codecpar + ) + err_check(res) + elif in_stream is not None: + # A Codec or codec name only pins the input codec, which is enough for + # codec-specific filters (e.g. h264_mp4toannexb) to initialize. + codec: Codec = ( + in_stream if isinstance(in_stream, Codec) else Codec(in_stream) + ) + self.ptr.par_in.codec_id = codec.ptr.id + self.ptr.par_in.codec_type = codec.ptr.type + + with cython.nogil: + res = lib.av_bsf_init(self.ptr) + err_check(res) + + if out_stream is not None: + with cython.nogil: + res = lib.avcodec_parameters_copy( + out_stream.ptr.codecpar, self.ptr.par_out + ) + err_check(res) + # codecpar carries everything the muxer needs; a mux-only stream + # (add_mux_stream) has no context to keep in sync. + if out_stream.codec_context is not None: + lib.avcodec_parameters_to_context( + out_stream.codec_context.ptr, out_stream.ptr.codecpar + ) + + def __dealloc__(self): + if self.ptr: + lib.av_bsf_free(cython.address(self.ptr)) + + @cython.ccall + def filter(self, packet: Packet | None = None): + """ + Processes a packet based on the filter_description set during initialization. + Multiple packets may be created. + + :type: list[Packet] + """ + res: cython.int + new_packet: Packet + + with cython.nogil: + res = lib.av_bsf_send_packet( + self.ptr, packet.ptr if packet is not None else cython.NULL + ) + err_check(res) + + output: list = [] + while True: + new_packet = Packet() + with cython.nogil: + res = lib.av_bsf_receive_packet(self.ptr, new_packet.ptr) + + if res == -EAGAIN or res == lib.AVERROR_EOF: + return output + + err_check(res) + if res: + return output + + output.append(new_packet) + + @cython.ccall + def flush(self): + """ + Reset the internal state of the filter. + Should be called e.g. when seeking. + Can be used to make the filter usable again after draining it with EOF marker packet. + """ + lib.av_bsf_flush(self.ptr) + + +@cython.cfunc +def get_filter_names() -> set: + names: set = set() + ptr: cython.pointer[cython.const[lib.AVBitStreamFilter]] + opaque: cython.p_void = cython.NULL + while True: + ptr = lib.av_bsf_iterate(cython.address(opaque)) + if ptr: + names.add(ptr.name) + else: + break + + return names + + +bitstream_filters_available = get_filter_names() diff --git a/.venv/lib/python3.12/site-packages/av/bitstream.pyi b/.venv/lib/python3.12/site-packages/av/bitstream.pyi new file mode 100644 index 0000000000000000000000000000000000000000..34adc16bfe8c669bae38733c3489beffd748db7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/bitstream.pyi @@ -0,0 +1,15 @@ +from .codec import Codec +from .packet import Packet +from .stream import Stream + +class BitStreamFilterContext: + def __init__( + self, + filter_description: str | bytes, + in_stream: Stream | Codec | str | None = None, + out_stream: Stream | None = None, + ): ... + def filter(self, packet: Packet | None) -> list[Packet]: ... + def flush(self) -> None: ... + +bitstream_filters_available: set[str] diff --git a/.venv/lib/python3.12/site-packages/av/buffer.abi3.so b/.venv/lib/python3.12/site-packages/av/buffer.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..efbebdc1fa0e300bdd89b0b8a91e5bf6110dfdde --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/buffer.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d44e00340c7fbd19d1fded7ed28b5a10be95151c3eff1d51391722983e79f4e +size 335097 diff --git a/.venv/lib/python3.12/site-packages/av/buffer.pxd b/.venv/lib/python3.12/site-packages/av/buffer.pxd new file mode 100644 index 0000000000000000000000000000000000000000..07ae34ae512fff2cfbc2dab7dd1222fe6946bd03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/buffer.pxd @@ -0,0 +1,16 @@ +from cpython.buffer cimport Py_buffer + + +cdef class ByteSource: + cdef object owner + cdef bint has_view + cdef Py_buffer view + cdef unsigned char *ptr + cdef size_t length + +cdef ByteSource bytesource(object, bint allow_none=*) + +cdef class Buffer: + cdef size_t _buffer_size(self) + cdef void* _buffer_ptr(self) + cdef bint _buffer_writable(self) diff --git a/.venv/lib/python3.12/site-packages/av/buffer.py b/.venv/lib/python3.12/site-packages/av/buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..3fefceee46f11c16b7e61f53f83f9dbd47881eab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/buffer.py @@ -0,0 +1,100 @@ +import cython +from cython.cimports.cpython import PyBUF_WRITABLE, PyBuffer_FillInfo +from cython.cimports.cpython.buffer import ( + PyBUF_SIMPLE, + PyBuffer_Release, + PyObject_CheckBuffer, + PyObject_GetBuffer, +) +from cython.cimports.libc.string import memcpy + + +@cython.final +@cython.cclass +class ByteSource: + def __cinit__(self, owner): + self.owner = owner + + try: + self.ptr = owner + except TypeError: + pass + else: + self.length = len(owner) + return + + if PyObject_CheckBuffer(owner): + # Can very likely use PyBUF_ND instead of PyBUF_SIMPLE + res = PyObject_GetBuffer(owner, cython.address(self.view), PyBUF_SIMPLE) + if not res: + self.has_view = True + self.ptr = cython.cast(cython.p_uchar, self.view.buf) + self.length = self.view.len + return + + raise TypeError("expected bytes, bytearray or memoryview") + + def __dealloc__(self): + if self.has_view: + PyBuffer_Release(cython.address(self.view)) + + +@cython.cfunc +def bytesource(obj, allow_none: cython.bint = False) -> ByteSource | None: + if allow_none and obj is None: + return None + elif isinstance(obj, ByteSource): + return obj + else: + return ByteSource(obj) + + +@cython.cclass +class Buffer: + """A base class for PyAV objects which support the buffer protocol, such + as :class:`.Packet` and :class:`.Plane`. + + """ + + @cython.cfunc + def _buffer_size(self) -> cython.size_t: + return 0 + + def _buffer_ptr(self) -> cython.p_void: + return cython.NULL + + def _buffer_writable(self) -> cython.bint: + return True + + def __getbuffer__(self, view: cython.pointer[Py_buffer], flags: cython.int): + if flags & PyBUF_WRITABLE and not self._buffer_writable(): + raise ValueError("buffer is not writable") + + PyBuffer_FillInfo(view, self, self._buffer_ptr(), self._buffer_size(), 0, flags) + + @property + def buffer_size(self): + return self._buffer_size() + + @property + def buffer_ptr(self): + """The memory address of the buffer.""" + return cython.cast(cython.size_t, self._buffer_ptr()) + + def update(self, input): + """Replace the data in this object with the given buffer. + + Accepts anything that supports the `buffer protocol `_, + e.g. bytes, NumPy arrays, other :class:`Buffer` objects, etc.. + + """ + if not self._buffer_writable(): + raise ValueError("buffer is not writable") + + source: ByteSource = bytesource(input) + size: cython.size_t = self._buffer_size() + + if source.length != size: + raise ValueError(f"got {source.length} bytes; need {size} bytes") + + memcpy(self._buffer_ptr(), source.ptr, size) diff --git a/.venv/lib/python3.12/site-packages/av/buffer.pyi b/.venv/lib/python3.12/site-packages/av/buffer.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bc1090d1deac54dcfc364fea49ee31bca526c6f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/buffer.pyi @@ -0,0 +1,9 @@ +# When Python 3.12 becomes our lowest supported version, we could make this +# class inherit `collections.abc.Buffer`. + +class Buffer: + buffer_size: int + buffer_ptr: int + def update(self, input: bytes) -> None: ... + def __buffer__(self, flags: int) -> memoryview: ... + def __bytes__(self) -> bytes: ... diff --git a/.venv/lib/python3.12/site-packages/av/codec/__init__.pxd b/.venv/lib/python3.12/site-packages/av/codec/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/codec/__init__.py b/.venv/lib/python3.12/site-packages/av/codec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f589de8e4bd8c5a3e9719eb23bf589f995fab8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/__init__.py @@ -0,0 +1,19 @@ +from .codec import ( + Capabilities, + Codec, + PixFmtLoss, + Properties, + codecs_available, + find_best_pix_fmt_of_list, +) +from .context import CodecContext + +__all__ = ( + "Capabilities", + "Codec", + "PixFmtLoss", + "Properties", + "codecs_available", + "find_best_pix_fmt_of_list", + "CodecContext", +) diff --git a/.venv/lib/python3.12/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8e292909f371e28166ebc003f4ff688df215138 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/codec/__pycache__/codec.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/codec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c328706b448f280242c6d1826083581e883b98d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/codec.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/codec/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..772d883a04c3136d4f8a87b2da76de6d777a0be3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/codec/__pycache__/hwaccel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/hwaccel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a0e8594c564fef04ab0ae6dc123ea6372dbd02 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/codec/__pycache__/hwaccel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/codec/codec.abi3.so b/.venv/lib/python3.12/site-packages/av/codec/codec.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..c284b29e3c488f6010ae49bf6985dcc0c510df86 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/codec.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a043b9e6860fa11e9b2901aa118779df377554ad72864f9036366cf927045e9c +size 671609 diff --git a/.venv/lib/python3.12/site-packages/av/codec/codec.pxd b/.venv/lib/python3.12/site-packages/av/codec/codec.pxd new file mode 100644 index 0000000000000000000000000000000000000000..576c659b46939204543b2313f33de1d6ae3ac2dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/codec.pxd @@ -0,0 +1,15 @@ +cimport libav as lib + + +cdef class Codec: + + cdef const lib.AVCodec *ptr + cdef const lib.AVCodecDescriptor *desc + cdef readonly bint is_encoder + + cdef tuple _hardware_configs + + cdef _init(self, name=?) + + +cdef Codec wrap_codec(const lib.AVCodec *ptr) diff --git a/.venv/lib/python3.12/site-packages/av/codec/codec.py b/.venv/lib/python3.12/site-packages/av/codec/codec.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8b958ec7a09321967414001ea10b5ce3bbc962 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/codec.py @@ -0,0 +1,485 @@ +from enum import Flag, IntEnum, IntFlag + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.audio.format import get_audio_format +from cython.cimports.av.codec.hwaccel import wrap_hwconfig +from cython.cimports.av.rational import from_avrational +from cython.cimports.av.utils import avrational_to_fraction +from cython.cimports.av.video.format import VideoFormat, get_pix_fmt, get_video_format +from cython.cimports.libc.stdlib import free, malloc + +_cinit_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def wrap_codec(ptr: cython.pointer[cython.const[lib.AVCodec]]) -> Codec: + codec: Codec = Codec(_cinit_sentinel) + codec.ptr = ptr + codec.is_encoder = lib.av_codec_is_encoder(ptr) + codec._init() + return codec + + +class Properties(Flag): + NONE = 0 + INTRA_ONLY = lib.AV_CODEC_PROP_INTRA_ONLY + LOSSY = lib.AV_CODEC_PROP_LOSSY + LOSSLESS = lib.AV_CODEC_PROP_LOSSLESS + REORDER = lib.AV_CODEC_PROP_REORDER + BITMAP_SUB = lib.AV_CODEC_PROP_BITMAP_SUB + TEXT_SUB = lib.AV_CODEC_PROP_TEXT_SUB + + +class Capabilities(IntEnum): + none = 0 + draw_horiz_band = lib.AV_CODEC_CAP_DRAW_HORIZ_BAND + dr1 = lib.AV_CODEC_CAP_DR1 + hwaccel = 1 << 4 + delay = lib.AV_CODEC_CAP_DELAY + small_last_frame = lib.AV_CODEC_CAP_SMALL_LAST_FRAME + hwaccel_vdpau = 1 << 7 + experimental = lib.AV_CODEC_CAP_EXPERIMENTAL + channel_conf = lib.AV_CODEC_CAP_CHANNEL_CONF + neg_linesizes = 1 << 11 + frame_threads = lib.AV_CODEC_CAP_FRAME_THREADS + slice_threads = lib.AV_CODEC_CAP_SLICE_THREADS + param_change = lib.AV_CODEC_CAP_PARAM_CHANGE + auto_threads = lib.AV_CODEC_CAP_OTHER_THREADS + variable_frame_size = lib.AV_CODEC_CAP_VARIABLE_FRAME_SIZE + avoid_probing = lib.AV_CODEC_CAP_AVOID_PROBING + hardware = lib.AV_CODEC_CAP_HARDWARE + hybrid = lib.AV_CODEC_CAP_HYBRID + encoder_reordered_opaque = 1 << 20 + encoder_flush = 1 << 21 + encoder_recon_frame = 1 << 22 + + +class PixFmtLoss(IntFlag): + """Flags describing what is lost when converting between pixel formats. + + Returned by :func:`find_best_pix_fmt_of_list`. Mirrors FFmpeg's + ``FF_LOSS_*`` flags. + """ + + NONE = 0 + RESOLUTION = 0x0001 # loss due to resolution change + DEPTH = 0x0002 # loss due to color depth change + COLORSPACE = 0x0004 # loss due to color space conversion + ALPHA = 0x0008 # loss of alpha bit + COLORQUANT = 0x0010 # loss due to color quantization + CHROMA = 0x0020 # loss of chroma (e.g. RGB to gray conversion) + + +class UnknownCodecError(ValueError): + pass + + +@cython.final +@cython.cclass +class Codec: + """Codec(name, mode='r') + + :param str name: The codec name. + :param str mode: ``'r'`` for decoding or ``'w'`` for encoding. + + This object exposes information about an available codec, and an avenue to + create a :class:`.CodecContext` to encode/decode directly. + + :: + + >>> codec = Codec('mpeg4', 'r') + >>> codec.name + 'mpeg4' + >>> codec.type + 'video' + >>> codec.is_encoder + False + + """ + + def __cinit__(self, name, mode="r"): + if name is _cinit_sentinel: + return + + if mode == "w": + self.ptr = lib.avcodec_find_encoder_by_name(name) + if not self.ptr: + self.desc = lib.avcodec_descriptor_get_by_name(name) + if self.desc: + self.ptr = lib.avcodec_find_encoder(self.desc.id) + + elif mode == "r": + self.ptr = lib.avcodec_find_decoder_by_name(name) + if not self.ptr: + self.desc = lib.avcodec_descriptor_get_by_name(name) + if self.desc: + self.ptr = lib.avcodec_find_decoder(self.desc.id) + + else: + raise ValueError('Invalid mode; must be "r" or "w".', mode) + + self._init(name) + + # Sanity check. + if (mode == "w") != self.is_encoder: + raise RuntimeError("Found codec does not match mode.", name, mode) + + @cython.cfunc + def _init(self, name=None): + if not self.ptr: + raise UnknownCodecError(name) + + if not self.desc: + self.desc = lib.avcodec_descriptor_get(self.ptr.id) + if not self.desc: + raise RuntimeError(f"No codec descriptor for {name!r}.") + + self.is_encoder = lib.av_codec_is_encoder(self.ptr) + + # Sanity check. + if self.is_encoder and lib.av_codec_is_decoder(self.ptr): + raise RuntimeError("%s is both encoder and decoder.") + + def __repr__(self): + mode = self.mode + return f"" + + def create(self, kind=None): + """Create a :class:`.CodecContext` for this codec. + + :param str kind: Gives a hint to static type checkers for what exact CodecContext is used. + """ + from .context import CodecContext + + return CodecContext.create(self) + + @property + def mode(self): + return "w" if self.is_encoder else "r" + + @property + def is_decoder(self): + return not self.is_encoder + + @property + def name(self): + return self.ptr.name or "" + + @property + def canonical_name(self): + """ + Returns the name of the codec, not a specific encoder. + """ + return lib.avcodec_get_name(self.ptr.id) + + @property + def long_name(self): + return self.ptr.long_name or "" + + @property + def type(self): + """ + The media type of this codec. + + E.g: ``'audio'``, ``'video'``, ``'subtitle'``. + + """ + media_type = lib.av_get_media_type_string(self.ptr.type) + return "unknown" if media_type == cython.NULL else media_type + + @property + def id(self): + return self.ptr.id + + @property + def frame_rates(self): + """A list of supported frame rates (:class:`av.AVRational`), or ``None``.""" + out: cython.pointer[cython.const[cython.void]] = cython.NULL + num: cython.int = 0 + lib.avcodec_get_supported_config( + cython.NULL, + self.ptr, + lib.AV_CODEC_CONFIG_FRAME_RATE, + 0, + cython.address(out), + cython.address(num), + ) + if not out: + return + rates = cython.cast(cython.pointer[lib.AVRational], out) + return [from_avrational(rates[i]) for i in range(num)] + + @property + def audio_rates(self): + """A list of supported audio sample rates (``int``), or ``None``.""" + out: cython.pointer[cython.const[cython.void]] = cython.NULL + num: cython.int = 0 + lib.avcodec_get_supported_config( + cython.NULL, + self.ptr, + lib.AV_CODEC_CONFIG_SAMPLE_RATE, + 0, + cython.address(out), + cython.address(num), + ) + if not out: + return + rates = cython.cast(cython.pointer[cython.int], out) + return [rates[i] for i in range(num)] + + @property + def video_formats(self): + """A list of supported :class:`.VideoFormat`, or ``None``.""" + out: cython.pointer[cython.const[cython.void]] = cython.NULL + num: cython.int = 0 + lib.avcodec_get_supported_config( + cython.NULL, + self.ptr, + lib.AV_CODEC_CONFIG_PIX_FORMAT, + 0, + cython.address(out), + cython.address(num), + ) + if not out: + return + fmts = cython.cast(cython.pointer[lib.AVPixelFormat], out) + return [get_video_format(fmts[i], 0, 0) for i in range(num)] + + @property + def audio_formats(self): + """A list of supported :class:`.AudioFormat`, or ``None``.""" + out: cython.pointer[cython.const[cython.void]] = cython.NULL + num: cython.int = 0 + lib.avcodec_get_supported_config( + cython.NULL, + self.ptr, + lib.AV_CODEC_CONFIG_SAMPLE_FORMAT, + 0, + cython.address(out), + cython.address(num), + ) + if not out: + return + fmts = cython.cast(cython.pointer[lib.AVSampleFormat], out) + return [get_audio_format(fmts[i]) for i in range(num)] + + @property + def hardware_configs(self): + if self._hardware_configs: + return self._hardware_configs + ret: list = [] + i: cython.int = 0 + ptr: cython.pointer[cython.const[lib.AVCodecHWConfig]] + while True: + ptr = lib.avcodec_get_hw_config(self.ptr, i) + if not ptr: + break + ret.append(wrap_hwconfig(ptr)) + i += 1 + self._hardware_configs = tuple(ret) + return self._hardware_configs + + @property + def properties(self): + return self.desc.props + + @property + def intra_only(self): + return bool(self.desc.props & lib.AV_CODEC_PROP_INTRA_ONLY) + + @property + def lossy(self): + return bool(self.desc.props & lib.AV_CODEC_PROP_LOSSY) + + @property + def lossless(self): + return bool(self.desc.props & lib.AV_CODEC_PROP_LOSSLESS) + + @property + def reorder(self): + return bool(self.desc.props & lib.AV_CODEC_PROP_REORDER) + + @property + def bitmap_sub(self): + return bool(self.desc.props & lib.AV_CODEC_PROP_BITMAP_SUB) + + @property + def text_sub(self): + return bool(self.desc.props & lib.AV_CODEC_PROP_TEXT_SUB) + + @property + def capabilities(self): + """ + Get the capabilities bitmask of the codec. + + This method returns an integer representing the codec capabilities bitmask, + which can be used to check specific codec features by performing bitwise + operations with the Capabilities enum values. + + :example: + + .. code-block:: python + + from av.codec import Codec, Capabilities + + codec = Codec("h264", "w") + + # Check if the codec can be fed a final frame with a smaller size. + # This can be used to prevent truncation of the last audio samples. + small_last_frame = bool(codec.capabilities & Capabilities.small_last_frame) + + :rtype: int + """ + return self.ptr.capabilities + + @property + def experimental(self): + """ + Check if codec is experimental and is thus avoided in favor of non experimental encoders. + + :rtype: bool + """ + return bool(self.ptr.capabilities & lib.AV_CODEC_CAP_EXPERIMENTAL) + + @property + def delay(self): + """ + If true, encoder or decoder requires flushing with `None` at the end in order to give the complete and correct output. + + :rtype: bool + """ + return bool(self.ptr.capabilities & lib.AV_CODEC_CAP_DELAY) + + +@cython.cfunc +def get_codec_names(): + names: cython.set = set() + ptr = cython.declare(cython.pointer[cython.const[lib.AVCodec]]) + opaque: cython.p_void = cython.NULL + while True: + ptr = lib.av_codec_iterate(cython.address(opaque)) + if ptr: + names.add(ptr.name) + else: + break + return names + + +codecs_available = get_codec_names() + + +def dump_codecs(): + """Print information about available codecs.""" + + print( + """Codecs: + D..... = Decoding supported + .E.... = Encoding supported + ..V... = Video codec + ..A... = Audio codec + ..S... = Subtitle codec + ...I.. = Intra frame-only codec + ....L. = Lossy compression + .....S = Lossless compression + ------""" + ) + + for name in sorted(codecs_available): + try: + e_codec = Codec(name, "w") + except ValueError: + e_codec = None + + try: + d_codec = Codec(name, "r") + except ValueError: + d_codec = None + + # TODO: Assert these always have the same properties. + codec = e_codec or d_codec + + try: + print( + f" {'.D'[bool(d_codec)]}{'.E'[bool(e_codec)]}{codec.type[0].upper()}" + f"{'.I'[codec.intra_only]}{'.L'[codec.lossy]}{'.S'[codec.lossless]}" + f" {codec.name:<18} {codec.long_name}" + ) + except Exception as e: + print(f"...... {codec.name:<18} ERROR: {e}") + + +def dump_hwconfigs(): + print("Hardware configs:") + for name in sorted(codecs_available): + try: + codec = Codec(name, "r") + except ValueError: + continue + + configs = codec.hardware_configs + if not configs: + continue + + print(" ", codec.name) + for config in configs: + print(" ", config) + + +def find_best_pix_fmt_of_list(pix_fmts, src_pix_fmt, has_alpha=False): + """ + Find the best pixel format to convert to given a source format. + + Wraps :ffmpeg:`avcodec_find_best_pix_fmt_of_list`. + + :param pix_fmts: Iterable of pixel formats to choose from (str or VideoFormat). + :param src_pix_fmt: Source pixel format (str or VideoFormat). + :param bool has_alpha: Whether the source alpha channel is used. + :return: (best_format, loss) + :rtype: (VideoFormat | None, PixFmtLoss) + """ + src: lib.AVPixelFormat + best: lib.AVPixelFormat + c_list: cython.pointer[lib.AVPixelFormat] = cython.NULL + n: cython.Py_ssize_t + i: cython.Py_ssize_t + item: object + c_loss: cython.int + + if pix_fmts is None: + raise TypeError("pix_fmts must not be None") + + pix_fmts = tuple(pix_fmts) + if not pix_fmts: + return None, PixFmtLoss.NONE + + if isinstance(src_pix_fmt, VideoFormat): + src = cython.cast(VideoFormat, src_pix_fmt).pix_fmt + else: + src = get_pix_fmt(cython.cast(str, src_pix_fmt)) + + n = len(pix_fmts) + c_list = cython.cast( + cython.pointer[lib.AVPixelFormat], + malloc((n + 1) * cython.sizeof(lib.AVPixelFormat)), + ) + if c_list == cython.NULL: + raise MemoryError() + + try: + for i in range(n): + item = pix_fmts[i] + if isinstance(item, VideoFormat): + c_list[i] = cython.cast(VideoFormat, item).pix_fmt + else: + c_list[i] = get_pix_fmt(cython.cast(str, item)) + c_list[n] = lib.AV_PIX_FMT_NONE + + c_loss = 0 + best = lib.avcodec_find_best_pix_fmt_of_list( + c_list, src, 1 if has_alpha else 0, cython.address(c_loss) + ) + return get_video_format(best, 0, 0), PixFmtLoss(c_loss) + finally: + if c_list != cython.NULL: + free(c_list) diff --git a/.venv/lib/python3.12/site-packages/av/codec/codec.pyi b/.venv/lib/python3.12/site-packages/av/codec/codec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..be3953dd33e1a4f8604beb074958d8326e435f3b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/codec.pyi @@ -0,0 +1,152 @@ +from collections.abc import Sequence +from enum import Flag, IntEnum, IntFlag +from typing import ClassVar, Literal, cast, overload + +from av.audio.codeccontext import AudioCodecContext +from av.audio.format import AudioFormat +from av.rational import AVRational +from av.subtitles.codeccontext import SubtitleCodecContext +from av.video.codeccontext import VideoCodecContext +from av.video.format import VideoFormat + +from .context import CodecContext +from .hwaccel import HWConfig + +class Properties(Flag): + NONE = cast(ClassVar[Properties], ...) + INTRA_ONLY = cast(ClassVar[Properties], ...) + LOSSY = cast(ClassVar[Properties], ...) + LOSSLESS = cast(ClassVar[Properties], ...) + REORDER = cast(ClassVar[Properties], ...) + BITMAP_SUB = cast(ClassVar[Properties], ...) + TEXT_SUB = cast(ClassVar[Properties], ...) + +class Capabilities(IntEnum): + none = cast(int, ...) + draw_horiz_band = cast(int, ...) + dr1 = cast(int, ...) + hwaccel = cast(int, ...) + delay = cast(int, ...) + small_last_frame = cast(int, ...) + hwaccel_vdpau = cast(int, ...) + subframes = cast(int, ...) + experimental = cast(int, ...) + channel_conf = cast(int, ...) + neg_linesizes = cast(int, ...) + frame_threads = cast(int, ...) + slice_threads = cast(int, ...) + param_change = cast(int, ...) + auto_threads = cast(int, ...) + variable_frame_size = cast(int, ...) + avoid_probing = cast(int, ...) + hardware = cast(int, ...) + hybrid = cast(int, ...) + encoder_reordered_opaque = cast(int, ...) + encoder_flush = cast(int, ...) + encoder_recon_frame = cast(int, ...) + +class PixFmtLoss(IntFlag): + NONE = cast(ClassVar[PixFmtLoss], ...) + RESOLUTION = cast(ClassVar[PixFmtLoss], ...) + DEPTH = cast(ClassVar[PixFmtLoss], ...) + COLORSPACE = cast(ClassVar[PixFmtLoss], ...) + ALPHA = cast(ClassVar[PixFmtLoss], ...) + COLORQUANT = cast(ClassVar[PixFmtLoss], ...) + CHROMA = cast(ClassVar[PixFmtLoss], ...) + +class UnknownCodecError(ValueError): ... + +class Codec: + @property + def is_encoder(self) -> bool: ... + @property + def is_decoder(self) -> bool: ... + @property + def mode(self) -> Literal["r", "w"]: ... + @property + def name(self) -> str: ... + @property + def canonical_name(self) -> str: ... + @property + def long_name(self) -> str: ... + @property + def type( + self, + ) -> Literal["video", "audio", "data", "subtitle", "attachment", "unknown"]: ... + @property + def id(self) -> int: ... + frame_rates: list[AVRational] | None + audio_rates: list[int] | None + video_formats: list[VideoFormat] | None + audio_formats: list[AudioFormat] | None + hardware_configs: list[HWConfig] + + @property + def properties(self) -> int: ... + @property + def intra_only(self) -> bool: ... + @property + def lossy(self) -> bool: ... + @property + def lossless(self) -> bool: ... + @property + def reorder(self) -> bool: ... + @property + def bitmap_sub(self) -> bool: ... + @property + def text_sub(self) -> bool: ... + @property + def capabilities(self) -> int: ... + @property + def experimental(self) -> bool: ... + @property + def delay(self) -> bool: ... + def __init__(self, name: str, mode: Literal["r", "w"] = "r") -> None: ... + @overload + def create(self, kind: Literal["video"]) -> VideoCodecContext: ... + @overload + def create(self, kind: Literal["audio"]) -> AudioCodecContext: ... + @overload + def create(self, kind: Literal["subtitle"]) -> SubtitleCodecContext: ... + @overload + def create(self, kind: None = None) -> CodecContext: ... + @overload + def create( + self, kind: Literal["video", "audio", "subtitle"] | None = None + ) -> ( + VideoCodecContext | AudioCodecContext | SubtitleCodecContext | CodecContext + ): ... + +codecs_available: set[str] + +def dump_codecs() -> None: ... +def dump_hwconfigs() -> None: ... + +PixFmtLike = str | VideoFormat + +def find_best_pix_fmt_of_list( + pix_fmts: Sequence[PixFmtLike], + src_pix_fmt: PixFmtLike, + has_alpha: bool = False, +) -> tuple[VideoFormat | None, PixFmtLoss]: + """ + Find the best pixel format to convert to given a source format. + + Wraps :ffmpeg:`avcodec_find_best_pix_fmt_of_list`. + + :param pix_fmts: Iterable of pixel formats to choose from (str or VideoFormat). + :param src_pix_fmt: Source pixel format (str or VideoFormat). + :param bool has_alpha: Whether the source alpha channel is used. + :return: (best_format, loss): best_format is the best matching pixel format from + the list, or None if no suitable format was found; loss is a combination of + :class:`PixFmtLoss` flags informing you what kind of losses will occur. + :rtype: (VideoFormat | None, PixFmtLoss) + + Note on loss: it is an :class:`enum.IntFlag` describing what kinds of information + would be lost converting from src_pix_fmt to best_format (e.g. loss of alpha, + chroma, colorspace, resolution, bit depth, etc.). Multiple losses can be present + at once, so the value can be tested with bitwise & against the :class:`PixFmtLoss` + members. + For exact behavior see: libavutil/pixdesc.c/get_pix_fmt_score() in ffmpeg source code. + """ + ... diff --git a/.venv/lib/python3.12/site-packages/av/codec/context.abi3.so b/.venv/lib/python3.12/site-packages/av/codec/context.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..5f0ebf1274b70d35694cfcc96c0e9ae4bc534e57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/context.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17e9c41e1a7ff9de82622b4a8dfdca899de01fd95cec340965beec051e4a6f0e +size 1417673 diff --git a/.venv/lib/python3.12/site-packages/av/codec/context.pxd b/.venv/lib/python3.12/site-packages/av/codec/context.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a9cb702a715868f0ea9c81902611cd397a301167 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/context.pxd @@ -0,0 +1,67 @@ +cimport libav as lib +from libc.stdint cimport int64_t, uint8_t + +from av.buffer cimport ByteSource +from av.codec.codec cimport Codec +from av.codec.hwaccel cimport HWAccel +from av.frame cimport Frame +from av.packet cimport Packet + + +cdef class CodecContext: + cdef lib.AVCodecContext *ptr + + # Used as a signal that this is within a stream, and also for us to access that + # stream. This is set "manually" by the stream after constructing this object. + cdef int stream_index + + cdef lib.AVCodecParserContext *parser + cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec, HWAccel hwaccel) + cdef _assert_not_open(self, name) + + # Public API. + cdef readonly bint is_open + cdef readonly Codec codec + cdef readonly HWAccel hwaccel + cdef public dict options + cpdef open(self, bint strict=?) + + # Wraps both versions of the transcode API, returning lists. + cpdef encode(self, Frame frame=?) + cpdef decode(self, Packet packet=?) + cdef _decode(self, Packet packet) + cpdef flush_buffers(self) + + # Used by hardware-accelerated decode. + cdef HWAccel hwaccel_ctx + + cdef uint8_t _ctxflags # ctxEnum: template_initialized + # True when created via add_stream_from_template(); start_encoding() skips + # avcodec_open2() and lets encode()/decode() open the codec lazily if needed. + + # Used by both transcode APIs to setup user-land objects. + # TODO: Remove the `Packet` from `_setup_decoded_frame` (because flushing packets + # are bogus). It should take all info it needs from the context and/or stream. + cdef _prepare_and_time_rebase_frames_for_encode(self, Frame frame) + cdef void _setup_encode_hwframes(self) + cdef list _prepare_frames_for_encode(self, Frame frame) + cdef _setup_encoded_packet(self, Packet) + cdef _setup_decoded_frame(self, Frame, Packet) + + # Implemented by base for the generic send/recv API. + # Note that the user cannot send without receiving. This is because + # `_prepare_frames_for_encode` may expand a frame into multiple (e.g. when + # resampling audio to a higher rate but with fixed size frames), and the + # send/recv buffer may be limited to a single frame. Ergo, we need to flush + # the buffer as often as possible. + cdef _recv_packet(self) + cdef _recv_frame(self) + + cdef _transfer_hwframe(self, Frame frame) + + # Implemented by children for the generic send/recv API, so we have the + # correct subclass of Frame. + cdef Frame _next_frame + cdef Frame _alloc_next_frame(self) + +cdef CodecContext wrap_codec_context(lib.AVCodecContext*, const lib.AVCodec*, HWAccel hwaccel) diff --git a/.venv/lib/python3.12/site-packages/av/codec/context.py b/.venv/lib/python3.12/site-packages/av/codec/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3fb7cca14f7031aa19b25fda2fc45b200f284d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/context.py @@ -0,0 +1,1007 @@ +from dataclasses import dataclass +from enum import Flag, IntEnum, IntFlag + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.buffer import ByteSource, bytesource +from cython.cimports.av.codec.codec import Codec, wrap_codec +from cython.cimports.av.dictionary import Dictionary +from cython.cimports.av.error import err_check +from cython.cimports.av.packet import Packet +from cython.cimports.av.utils import avrational_to_fraction, to_avrational +from cython.cimports.libc.errno import EAGAIN +from cython.cimports.libc.stdint import uint8_t +from cython.cimports.libc.string import memcpy, strcmp + +from av.error import InvalidDataError + +_cinit_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def wrap_codec_context( + c_ctx: cython.pointer[lib.AVCodecContext], + c_codec: cython.pointer[cython.const[lib.AVCodec]], + hwaccel: HWAccel, +) -> CodecContext: + """Build an bv.CodecContext for an existing AVCodecContext.""" + py_ctx: CodecContext + + if c_ctx.codec_type == lib.AVMEDIA_TYPE_VIDEO: + from av.video.codeccontext import VideoCodecContext + + py_ctx = VideoCodecContext(_cinit_sentinel) + elif c_ctx.codec_type == lib.AVMEDIA_TYPE_AUDIO: + from av.audio.codeccontext import AudioCodecContext + + py_ctx = AudioCodecContext(_cinit_sentinel) + elif c_ctx.codec_type == lib.AVMEDIA_TYPE_SUBTITLE: + from av.subtitles.codeccontext import SubtitleCodecContext + + py_ctx = SubtitleCodecContext(_cinit_sentinel) + else: + py_ctx = CodecContext(_cinit_sentinel) + + py_ctx._init(c_ctx, c_codec, hwaccel) + + return py_ctx + + +class ThreadType(Flag): + NONE = 0 + FRAME: "Decode more than one frame at once" = lib.FF_THREAD_FRAME + SLICE: "Decode more than one part of a single frame at once" = lib.FF_THREAD_SLICE + AUTO: "Decode using both FRAME and SLICE methods." = ( + lib.FF_THREAD_SLICE | lib.FF_THREAD_FRAME + ) + + +class Flags(IntEnum): + unaligned = lib.AV_CODEC_FLAG_UNALIGNED + qscale = lib.AV_CODEC_FLAG_QSCALE + four_mv = lib.AV_CODEC_FLAG_4MV + output_corrupt = lib.AV_CODEC_FLAG_OUTPUT_CORRUPT + qpel = lib.AV_CODEC_FLAG_QPEL + recon_frame = lib.AV_CODEC_FLAG_RECON_FRAME + copy_opaque = lib.AV_CODEC_FLAG_COPY_OPAQUE + frame_duration = lib.AV_CODEC_FLAG_FRAME_DURATION + pass1 = lib.AV_CODEC_FLAG_PASS1 + pass2 = lib.AV_CODEC_FLAG_PASS2 + loop_filter = lib.AV_CODEC_FLAG_LOOP_FILTER + gray = lib.AV_CODEC_FLAG_GRAY + psnr = lib.AV_CODEC_FLAG_PSNR + interlaced_dct = lib.AV_CODEC_FLAG_INTERLACED_DCT + low_delay = lib.AV_CODEC_FLAG_LOW_DELAY + global_header = lib.AV_CODEC_FLAG_GLOBAL_HEADER + bitexact = lib.AV_CODEC_FLAG_BITEXACT + ac_pred = lib.AV_CODEC_FLAG_AC_PRED + interlaced_me = lib.AV_CODEC_FLAG_INTERLACED_ME + closed_gop = lib.AV_CODEC_FLAG_CLOSED_GOP + + +class Flags2(IntEnum): + fast = lib.AV_CODEC_FLAG2_FAST + no_output = lib.AV_CODEC_FLAG2_NO_OUTPUT + local_header = lib.AV_CODEC_FLAG2_LOCAL_HEADER + chunks = lib.AV_CODEC_FLAG2_CHUNKS + ignore_crop = lib.AV_CODEC_FLAG2_IGNORE_CROP + show_all = lib.AV_CODEC_FLAG2_SHOW_ALL + export_mvs = lib.AV_CODEC_FLAG2_EXPORT_MVS + skip_manual = lib.AV_CODEC_FLAG2_SKIP_MANUAL + ro_flush_noop = lib.AV_CODEC_FLAG2_RO_FLUSH_NOOP + + +class OptionType(IntEnum): + FLAGS = lib.AV_OPT_TYPE_FLAGS + INT = lib.AV_OPT_TYPE_INT + INT64 = lib.AV_OPT_TYPE_INT64 + DOUBLE = lib.AV_OPT_TYPE_DOUBLE + FLOAT = lib.AV_OPT_TYPE_FLOAT + STRING = lib.AV_OPT_TYPE_STRING + RATIONAL = lib.AV_OPT_TYPE_RATIONAL + BINARY = lib.AV_OPT_TYPE_BINARY + DICT = lib.AV_OPT_TYPE_DICT + UINT64 = lib.AV_OPT_TYPE_UINT64 + CONST = lib.AV_OPT_TYPE_CONST + IMAGE_SIZE = lib.AV_OPT_TYPE_IMAGE_SIZE + PIXEL_FMT = lib.AV_OPT_TYPE_PIXEL_FMT + SAMPLE_FMT = lib.AV_OPT_TYPE_SAMPLE_FMT + VIDEO_RATE = lib.AV_OPT_TYPE_VIDEO_RATE + DURATION = lib.AV_OPT_TYPE_DURATION + COLOR = lib.AV_OPT_TYPE_COLOR + CHANNEL_LAYOUT = lib.AV_OPT_TYPE_CHLAYOUT + BOOL = lib.AV_OPT_TYPE_BOOL + UINT = lib.AV_OPT_TYPE_UINT + + +class OptionFlags(IntFlag): + ENCODING_PARAM = lib.AV_OPT_FLAG_ENCODING_PARAM + DECODING_PARAM = lib.AV_OPT_FLAG_DECODING_PARAM + AUDIO_PARAM = lib.AV_OPT_FLAG_AUDIO_PARAM + VIDEO_PARAM = lib.AV_OPT_FLAG_VIDEO_PARAM + SUBTITLE_PARAM = lib.AV_OPT_FLAG_SUBTITLE_PARAM + EXPORT = lib.AV_OPT_FLAG_EXPORT + READONLY = lib.AV_OPT_FLAG_READONLY + BITSTREAM_FILTER_PARAM = lib.AV_OPT_FLAG_BSF_PARAM + RUNTIME_PARAM = lib.AV_OPT_FLAG_RUNTIME_PARAM + FILTERING_PARAM = lib.AV_OPT_FLAG_FILTERING_PARAM + DEPRECATED = lib.AV_OPT_FLAG_DEPRECATED + CHILD_CONSTS = lib.AV_OPT_FLAG_CHILD_CONSTS + + +@dataclass(frozen=True, slots=True) +class CodecOptionChoice: + """A named value accepted by a codec option.""" + + name: str + help: str + + +@dataclass(frozen=True, slots=True) +class CodecOption: + """Description of a generic or codec-specific option.""" + + name: str + help: str + type: OptionType | int + is_array: bool + default: str | None + min: float + max: float + flags: OptionFlags + choices: tuple[CodecOptionChoice, ...] + + +@dataclass(frozen=True, slots=True) +class CodecOptionSet: + """Generic and codec-specific options supported by a codec context.""" + + generic: tuple[CodecOption, ...] + private: tuple[CodecOption, ...] + + +@cython.cfunc +def _get_option_default( + obj: cython.p_void, name: cython.pointer[cython.const[cython.char]] +): + value: cython.pointer[uint8_t] = cython.NULL + if lib.av_opt_get(obj, name, 0, cython.address(value)) < 0: + return None + try: + return cython.cast(cython.p_char, value) if value != cython.NULL else None + finally: + lib.av_free(value) + + +@cython.cfunc +def _get_supported_options(obj: cython.p_void): + options: list = [] + ptr: cython.pointer[cython.const[lib.AVOption]] = lib.av_opt_next(obj, cython.NULL) + choice_ptr: cython.pointer[cython.const[lib.AVOption]] + option_type: object + + while ptr != cython.NULL: + if ptr.type != lib.AV_OPT_TYPE_CONST: + choices: list = [] + if ptr.unit != cython.NULL: + choice_ptr = lib.av_opt_next(obj, cython.NULL) + while choice_ptr != cython.NULL: + if ( + choice_ptr.type == lib.AV_OPT_TYPE_CONST + and choice_ptr.unit != cython.NULL + and strcmp(choice_ptr.unit, ptr.unit) == 0 + ): + choices.append( + CodecOptionChoice( + choice_ptr.name, + choice_ptr.help + if choice_ptr.help != cython.NULL + else "", + ) + ) + choice_ptr = lib.av_opt_next(obj, choice_ptr) + + raw_type = cython.cast(cython.int, ptr.type) + is_array = bool(raw_type & lib.AV_OPT_TYPE_FLAG_ARRAY) + raw_type &= ~lib.AV_OPT_TYPE_FLAG_ARRAY + try: + option_type = OptionType(raw_type) + except ValueError: + option_type = raw_type + + options.append( + CodecOption( + ptr.name, + ptr.help if ptr.help != cython.NULL else "", + option_type, + is_array, + _get_option_default(obj, ptr.name), + ptr.min, + ptr.max, + OptionFlags(ptr.flags), + tuple(choices), + ) + ) + ptr = lib.av_opt_next(obj, ptr) + + return tuple(options) + + +@cython.cclass +class CodecContext: + @staticmethod + def create(codec, mode=None, hwaccel=None): + cy_codec: Codec = codec if isinstance(codec, Codec) else Codec(codec, mode) + c_ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3( + cy_codec.ptr + ) + return wrap_codec_context(c_ctx, cy_codec.ptr, hwaccel) + + def __cinit__(self, sentinel=None, *args, **kwargs): + if sentinel is not _cinit_sentinel: + raise RuntimeError("Cannot instantiate CodecContext") + + self.options = {} + self.stream_index = -1 # This is set by the container immediately. + self.is_open = False + + @property + def supported_options(self): + """Options supported by this codec context. + + ``generic`` contains options provided by :ffmpeg:`AVCodecContext`, while + ``private`` contains options provided by the selected codec. Values are + descriptors only; set options through :attr:`options`. + """ + ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3( + self.codec.ptr + ) + child: cython.p_void + private: list = [] + if ctx == cython.NULL: + raise MemoryError("Cannot allocate codec context") + try: + generic = _get_supported_options(ctx) + child = lib.av_opt_child_next(ctx, cython.NULL) + while child != cython.NULL: + private.extend(_get_supported_options(child)) + child = lib.av_opt_child_next(ctx, child) + return CodecOptionSet(generic, tuple(private)) + finally: + lib.avcodec_free_context(cython.address(ctx)) + + @cython.cfunc + def _init( + self, + ptr: cython.pointer[lib.AVCodecContext], + codec: cython.pointer[cython.const[lib.AVCodec]], + hwaccel: HWAccel, + ): + self.ptr = ptr + if self.ptr.codec and codec and self.ptr.codec != codec: + raise RuntimeError("Wrapping CodecContext with mismatched codec.") + self.codec = wrap_codec(codec if codec != cython.NULL else self.ptr.codec) + self.hwaccel = hwaccel + + # Set reasonable threading defaults. + self.ptr.thread_count = 0 # use as many threads as there are CPUs. + self.ptr.thread_type = 0x02 # thread within a frame. Does not change the API. + + @cython.cfunc + def _assert_not_open(self, name): + if self.is_open: + raise RuntimeError(f"Cannot change {name} after codec is open.") + + @property + def flags(self): + """ + Get and set the flags bitmask of CodecContext. + + :rtype: int + """ + return self.ptr.flags + + @flags.setter + def flags(self, value: cython.int): + self.ptr.flags = value + + @property + def qscale(self): + """ + Use fixed qscale. + + :rtype: bool + """ + return bool(self.ptr.flags & lib.AV_CODEC_FLAG_QSCALE) + + @qscale.setter + def qscale(self, value): + if value: + self.ptr.flags |= lib.AV_CODEC_FLAG_QSCALE + else: + self.ptr.flags &= ~lib.AV_CODEC_FLAG_QSCALE + + @property + def copy_opaque(self): + return bool(self.ptr.flags & lib.AV_CODEC_FLAG_COPY_OPAQUE) + + @copy_opaque.setter + def copy_opaque(self, value): + if value: + self.ptr.flags |= lib.AV_CODEC_FLAG_COPY_OPAQUE + else: + self.ptr.flags &= ~lib.AV_CODEC_FLAG_COPY_OPAQUE + + @property + def flags2(self): + """ + Get and set the flags2 bitmask of CodecContext. + + :rtype: int + """ + return self.ptr.flags2 + + @flags2.setter + def flags2(self, value: cython.int): + self.ptr.flags2 = value + + @property + def extradata(self): + if self.ptr is cython.NULL: + return None + if self.ptr.extradata_size > 0: + return cython.cast( + bytes, + cython.cast(cython.pointer[uint8_t], self.ptr.extradata)[ + : self.ptr.extradata_size + ], + ) + return None + + @extradata.setter + def extradata(self, data): + if data is None: + lib.av_freep(cython.address(self.ptr.extradata)) + self.ptr.extradata_size = 0 + else: + source = bytesource(data) + self.ptr.extradata = cython.cast( + cython.pointer[uint8_t], + lib.av_realloc( + self.ptr.extradata, source.length + lib.AV_INPUT_BUFFER_PADDING_SIZE + ), + ) + if not self.ptr.extradata: + raise MemoryError("Cannot allocate extradata") + memcpy(self.ptr.extradata, source.ptr, source.length) + self.ptr.extradata_size = cython.cast(cython.int, source.length) + + @property + def extradata_size(self): + return self.ptr.extradata_size + + @property + def is_encoder(self): + if self.ptr is cython.NULL: + return False + return lib.av_codec_is_encoder(self.ptr.codec) + + @property + def is_decoder(self): + if self.ptr is cython.NULL: + return False + return lib.av_codec_is_decoder(self.ptr.codec) + + @cython.ccall + def open(self, strict: cython.bint = True): + if self.is_open: + if strict: + raise ValueError("CodecContext is already open.") + return + + options: Dictionary = Dictionary() + options.update(self.options or {}) + + if not self.ptr.time_base.num and self.is_encoder: + if self.type == "video": + self.ptr.time_base.num = self.ptr.framerate.den or 1 + self.ptr.time_base.den = self.ptr.framerate.num or lib.AV_TIME_BASE + elif self.type == "audio": + self.ptr.time_base.num = 1 + self.ptr.time_base.den = self.ptr.sample_rate + else: + self.ptr.time_base.num = 1 + self.ptr.time_base.den = lib.AV_TIME_BASE + + self._setup_encode_hwframes() + + err_check( + lib.avcodec_open2(self.ptr, self.codec.ptr, cython.address(options.ptr)), + f'avcodec_open2("{self.codec.name}", {self.options})', + ) + self.is_open = True + self.options = dict(options) + + def __dealloc__(self): + if self.ptr: + lib.av_freep(cython.address(self.ptr.extradata)) + lib.avcodec_free_context(cython.address(self.ptr)) + if self.parser: + lib.av_parser_close(self.parser) + + def __repr__(self): + _type = self.type or "" + name = self.name or "" + return f"" + + def parse(self, raw_input=None): + """Split up a byte stream into list of :class:`.Packet`. + + This is only effectively splitting up a byte stream, and does no + actual interpretation of the data. + + It will return all packets that are fully contained within the given + input, and will buffer partial packets until they are complete. + + Any timing information the parser is able to infer (``pts``, ``dts``, + ``duration``, ``pos`` and the keyframe flag) is assigned onto the + returned packets. Fields the parser cannot determine are left unset. + + :param ByteSource raw_input: A chunk of a byte-stream to process. + Anything that can be turned into a :class:`.ByteSource` is fine. + ``None`` or empty inputs will flush the parser's buffers. + + :return: ``list`` of :class:`.Packet` newly available. + + """ + + if not self.parser: + self.parser = lib.av_parser_init(self.codec.ptr.id) + if not self.parser: + raise ValueError(f"No parser for {self.codec.name}") + + source: ByteSource = bytesource(raw_input, allow_none=True) + + in_data: cython.p_uchar = source.ptr if source is not None else cython.NULL + in_size: cython.int = ( + cython.cast(cython.int, source.length) if source is not None else 0 + ) + + out_data: cython.p_uchar + out_size: cython.int + consumed: cython.int + packet: Packet = None + packets: list = [] + + while True: + with cython.nogil: + consumed = lib.av_parser_parse2( + self.parser, + self.ptr, + cython.address(out_data), + cython.address(out_size), + in_data, + in_size, + lib.AV_NOPTS_VALUE, + lib.AV_NOPTS_VALUE, + 0, + ) + err_check(consumed) + + if out_size: + # We copy the data immediately, as we have yet to figure out + # the expected lifetime of the buffer we get back. All of the + # examples decode it immediately. + # + # We've also tried: + # packet = Packet() + # packet.data = out_data + # packet.size = out_size + # packet.source = source + # + # ... but this results in corruption. + + packet = Packet(out_size) + memcpy(packet.ptr.data, out_data, out_size) + + # Propagate the timing information the parser inferred for + # this frame onto the packet (mirrors FFmpeg's parse_packet). + packet.ptr.pts = self.parser.pts + packet.ptr.dts = self.parser.dts + packet.ptr.pos = self.parser.pos + if self.parser.duration: + packet.ptr.duration = self.parser.duration + if self.parser.key_frame == 1: + packet.ptr.flags |= lib.AV_PKT_FLAG_KEY + + packets.append(packet) + + if not in_size: + # This was a flush. Only one packet should ever be returned. + break + + in_data += consumed + in_size -= consumed + + if not in_size: + break + + return packets + + @property + def is_hwaccel(self): + """ + Returns ``True`` if this codec context is hardware accelerated, ``False`` otherwise. + """ + return self.hwaccel_ctx is not None + + def _send_frame_and_recv(self, frame: Frame | None): + packet: Packet + res: cython.int + with cython.nogil: + res = lib.avcodec_send_frame( + self.ptr, frame.ptr if frame is not None else cython.NULL + ) + err_check(res, "avcodec_send_frame()") + + packet = self._recv_packet() + while packet: + yield packet + packet = self._recv_packet() + + @cython.cfunc + def _setup_encode_hwframes(self) -> cython.void: + # Build the hardware frames context for hardware-accelerated encoding. + # + # Unlike the device context (attached at construction time), the frames + # context depends on the final width/height/pixel format, which the user + # sets after add_stream(). We therefore defer it until just before the + # codec is opened. + if self.hwaccel_ctx is None or not self.is_encoder: + return + if self.ptr.hw_frames_ctx: + return # Already set up. + + hw_format: lib.AVPixelFormat = self.hwaccel_ctx.config.ptr.pix_fmt + sw_format: lib.AVPixelFormat = cython.cast( + lib.AVPixelFormat, self.ptr.sw_pix_fmt + ) + + # The codec context's sw_pix_fmt holds the software format the user + # wants the hardware frames context to use. Fall back to pix_fmt to + # preserve the existing stream.pix_fmt configuration path. + if sw_format == lib.AV_PIX_FMT_NONE: + sw_format = cython.cast(lib.AVPixelFormat, self.ptr.pix_fmt) + + # If they left it as the hardware format (or unset), pick a sane default. + if sw_format == hw_format or sw_format == lib.AV_PIX_FMT_NONE: + sw_format = lib.av_get_pix_fmt(b"nv12") + + frames_ref: cython.pointer[lib.AVBufferRef] = lib.av_hwframe_ctx_alloc( + self.hwaccel_ctx.ptr + ) + 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 = hw_format + frames_ctx.sw_format = sw_format + frames_ctx.width = self.ptr.width + frames_ctx.height = self.ptr.height + frames_ctx.initial_pool_size = 32 + err_check(lib.av_hwframe_ctx_init(frames_ref)) + except Exception: + lib.av_buffer_unref(cython.address(frames_ref)) + raise + + # Ownership of frames_ref transfers to the codec context. + self.ptr.hw_frames_ctx = frames_ref + self.ptr.sw_pix_fmt = sw_format + self.ptr.pix_fmt = hw_format + + @cython.cfunc + def _prepare_frames_for_encode(self, frame: Frame | None) -> list: + return [frame] + + @cython.cfunc + def _alloc_next_frame(self) -> Frame: + raise NotImplementedError("Base CodecContext cannot decode.") + + @cython.cfunc + def _recv_frame(self): + if not self._next_frame: + self._next_frame = self._alloc_next_frame() + + frame: Frame = self._next_frame + res: cython.int + + with cython.nogil: + res = lib.avcodec_receive_frame(self.ptr, frame.ptr) + + if res == -EAGAIN or res == lib.AVERROR_EOF: + return + + err_check(res, "avcodec_receive_frame()") + frame = self._transfer_hwframe(frame) + + if not res: + self._next_frame = None + return frame + + @cython.cfunc + def _transfer_hwframe(self, frame: Frame): + return frame + + @cython.cfunc + def _recv_packet(self): + packet: Packet = Packet() + res: cython.int + + with cython.nogil: + res = lib.avcodec_receive_packet(self.ptr, packet.ptr) + + if res == -EAGAIN or res == lib.AVERROR_EOF: + return + + err_check(res, "avcodec_receive_packet()") + if not res: + return packet + + @cython.cfunc + def _prepare_and_time_rebase_frames_for_encode(self, frame: Frame): + if self.ptr.codec_type not in [lib.AVMEDIA_TYPE_VIDEO, lib.AVMEDIA_TYPE_AUDIO]: + raise NotImplementedError("Encoding is only supported for audio and video.") + + # A hardware frame (e.g. a CUDA frame from DLPack) carries its own frames + # context. Encoders like h264_nvenc require hw_frames_ctx to be set before + # avcodec_open2, so adopt the frame's if we don't already have one. + if ( + not self.is_open + and frame is not None + and frame.ptr.hw_frames_ctx != cython.NULL + and self.ptr.hw_frames_ctx == cython.NULL + ): + self.ptr.hw_frames_ctx = lib.av_buffer_ref(frame.ptr.hw_frames_ctx) + + self.open(strict=False) + + frames = self._prepare_frames_for_encode(frame) + + # Assert the frames are in our time base. + # TODO: Don't mutate time. + for frame in frames: + if frame is not None: + frame._rebase_time(self.ptr.time_base) + + return frames + + @cython.ccall + def encode(self, frame: Frame | None = None): + """Encode a list of :class:`.Packet` from the given :class:`.Frame`.""" + res = [] + for frame in self._prepare_and_time_rebase_frames_for_encode(frame): + for packet in self._send_frame_and_recv(frame): + self._setup_encoded_packet(packet) + res.append(packet) + return res + + def encode_lazy(self, frame: Frame | None = None): + for frame in self._prepare_and_time_rebase_frames_for_encode(frame): + for packet in self._send_frame_and_recv(frame): + self._setup_encoded_packet(packet) + yield packet + + @cython.cfunc + def _setup_encoded_packet(self, packet: Packet): + # We coerced the frame's time_base into the CodecContext's during encoding, + # and FFmpeg copied the frame's pts/dts to the packet, so keep track of + # this time_base in case the frame needs to be muxed to a container with + # a different time_base. + # + # NOTE: if the CodecContext's time_base is altered during encoding, all bets + # are off! + packet.ptr.time_base = self.ptr.time_base + + @cython.ccall + def decode(self, packet: Packet | None = None): + """Decode a list of :class:`.Frame` from the given :class:`.Packet`. + + If the packet is None, the buffers will be flushed. This is useful if + you do not want the library to automatically re-order frames for you + (if they are encoded with a codec that has B-frames). + + .. warning:: + + This method is **not thread-safe**. Calling :meth:`decode` concurrently + from multiple threads on the same :class:`CodecContext` will corrupt + internal FFmpeg state and likely cause a crash (segfault). FFmpeg 8.1 + enforces this more strictly than earlier releases. If you need to decode + from multiple threads, give each thread its own :class:`CodecContext`. + + """ + return self._decode(packet) + + @cython.cfunc + def _decode(self, packet: Packet | None): + if not self.codec.ptr: + raise ValueError("cannot decode unknown codec") + + self.open(strict=False) + + res: cython.int + with cython.nogil: + res = lib.avcodec_send_packet( + self.ptr, packet.ptr if packet is not None else cython.NULL + ) + err_check(res, "avcodec_send_packet()") + + out: list = [] + while True: + try: + frame = self._recv_frame() + except InvalidDataError: + if out: + break + raise + if frame is None: + break + self._setup_decoded_frame(frame, packet) + out.append(frame) + return out + + @cython.ccall + def flush_buffers(self): + """Reset the internal codec state and discard all internal buffers. + + Should be called before you start decoding from a new position e.g. + when seeking or when switching to a different stream. + + """ + if self.is_open: + with cython.nogil: + lib.avcodec_flush_buffers(self.ptr) + + @cython.cfunc + def _setup_decoded_frame(self, frame: Frame, packet: Packet | None): + # Propagate our manual times. + # While decoding, frame times are in stream time_base, which PyAV + # is carrying around. + # TODO: Somehow get this from the stream so we can not pass the + # packet here (because flushing packets are bogus). + if packet is not None: + frame._time_base = packet.ptr.time_base + + @property + def name(self): + return self.codec.name + + @property + def type(self): + return self.codec.type + + @property + def profiles(self): + """ + List the available profiles for this stream. + + :type: list[str] + """ + ret: list = [] + if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles: + return ret + + # Profiles are always listed in the codec descriptor, but not necessarily in + # the codec itself. So use the descriptor here. + desc = self.codec.desc + i: cython.int = 0 + while desc.profiles[i].profile != lib.AV_PROFILE_UNKNOWN: + ret.append(desc.profiles[i].name) + i += 1 + + return ret + + @property + def profile(self): + if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles: + return + + # Profiles are always listed in the codec descriptor, but not necessarily in + # the codec itself. So use the descriptor here. + desc = self.codec.desc + i: cython.int = 0 + while desc.profiles[i].profile != lib.AV_PROFILE_UNKNOWN: + if desc.profiles[i].profile == self.ptr.profile: + return desc.profiles[i].name + i += 1 + + @profile.setter + def profile(self, value): + if not self.codec or not self.codec.desc or not self.codec.desc.profiles: + return + + # Profiles are always listed in the codec descriptor, but not necessarily in + # the codec itself. So use the descriptor here. + desc = self.codec.desc + i: cython.int = 0 + while desc.profiles[i].profile != lib.AV_PROFILE_UNKNOWN: + if desc.profiles[i].name == value: + self.ptr.profile = desc.profiles[i].profile + return + i += 1 + + @property + def level(self): + """Codec level. + + Wraps :ffmpeg:`AVCodecContext.level`. + + """ + return self.ptr.level + + @level.setter + def level(self, value: cython.int): + self.ptr.level = value + + @property + def time_base(self): + if self.is_decoder: + raise RuntimeError("Cannot access 'time_base' as a decoder") + return avrational_to_fraction(cython.address(self.ptr.time_base)) + + @time_base.setter + def time_base(self, value): + if self.is_decoder: + raise RuntimeError("Cannot access 'time_base' as a decoder") + to_avrational(value, cython.address(self.ptr.time_base)) + + @property + def codec_tag(self): + return self.ptr.codec_tag.to_bytes(4, byteorder="little", signed=False).decode( + encoding="ascii" + ) + + @codec_tag.setter + def codec_tag(self, value): + if isinstance(value, str) and len(value) == 4: + self.ptr.codec_tag = int.from_bytes( + value.encode(encoding="ascii"), byteorder="little", signed=False + ) + else: + raise ValueError("Codec tag should be a 4 character string.") + + @property + @cython.cdivision(True) + def global_quality(self): + """Global quality for codecs which cannot change it per frame. + + Stored internally in lambda units; this property converts to/from + QP units using ``FF_QP2LAMBDA``. + + Wraps :ffmpeg:`AVCodecContext.global_quality`. + + """ + return self.ptr.global_quality // lib.FF_QP2LAMBDA + + @global_quality.setter + def global_quality(self, value: cython.int): + self.ptr.global_quality = value * lib.FF_QP2LAMBDA + + @property + def bit_rate(self): + return self.ptr.bit_rate if self.ptr.bit_rate > 0 else None + + @bit_rate.setter + def bit_rate(self, value: cython.longlong): + self.ptr.bit_rate = value + + @property + def max_bit_rate(self): + if self.ptr.rc_max_rate > 0: + return self.ptr.rc_max_rate + else: + return None + + @property + def bit_rate_tolerance(self): + self.ptr.bit_rate_tolerance + + @bit_rate_tolerance.setter + def bit_rate_tolerance(self, value: cython.int): + self.ptr.bit_rate_tolerance = value + + @property + def thread_count(self): + """How many threads to use; 0 means auto. + + Wraps :ffmpeg:`AVCodecContext.thread_count`. + + """ + return self.ptr.thread_count + + @thread_count.setter + def thread_count(self, value: cython.int): + if self.is_open: + raise RuntimeError("Cannot change thread_count after codec is open.") + self.ptr.thread_count = value + + @property + def thread_type(self): + """One of :class:`.ThreadType`. + + Wraps :ffmpeg:`AVCodecContext.thread_type`. + + """ + return ThreadType(self.ptr.thread_type) + + @thread_type.setter + def thread_type(self, value): + if self.is_open: + raise RuntimeError("Cannot change thread_type after codec is open.") + if type(value) is int: + self.ptr.thread_type = value + elif type(value) is str: + self.ptr.thread_type = ThreadType[value].value + else: + self.ptr.thread_type = value.value + + @property + def skip_frame(self): + """Returns one of the following str literals: + + "NONE" Discard nothing + "DEFAULT" Discard useless packets like 0 size packets in AVI + "NONREF" Discard all non reference + "BIDIR" Discard all bidirectional frames + "NONINTRA" Discard all non intra frames + "NONKEY Discard all frames except keyframes + "ALL" Discard all + + Wraps :ffmpeg:`AVCodecContext.skip_frame`. + """ + value = self.ptr.skip_frame + if value == lib.AVDISCARD_NONE: + return "NONE" + if value == lib.AVDISCARD_DEFAULT: + return "DEFAULT" + if value == lib.AVDISCARD_NONREF: + return "NONREF" + if value == lib.AVDISCARD_BIDIR: + return "BIDIR" + if value == lib.AVDISCARD_NONINTRA: + return "NONINTRA" + if value == lib.AVDISCARD_NONKEY: + return "NONKEY" + if value == lib.AVDISCARD_ALL: + return "ALL" + return f"{value}" + + @skip_frame.setter + def skip_frame(self, value): + if value == "NONE": + self.ptr.skip_frame = lib.AVDISCARD_NONE + elif value == "DEFAULT": + self.ptr.skip_frame = lib.AVDISCARD_DEFAULT + elif value == "NONREF": + self.ptr.skip_frame = lib.AVDISCARD_NONREF + elif value == "BIDIR": + self.ptr.skip_frame = lib.AVDISCARD_BIDIR + elif value == "NONINTRA": + self.ptr.skip_frame = lib.AVDISCARD_NONINTRA + elif value == "NONKEY": + self.ptr.skip_frame = lib.AVDISCARD_NONKEY + elif value == "ALL": + self.ptr.skip_frame = lib.AVDISCARD_ALL + else: + raise ValueError("Invalid skip_frame type") + + @property + def delay(self): + """Codec delay. + + Wraps :ffmpeg:`AVCodecContext.delay`. + + """ + return self.ptr.delay diff --git a/.venv/lib/python3.12/site-packages/av/codec/context.pyi b/.venv/lib/python3.12/site-packages/av/codec/context.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3dfb52285cfb55edbb42e4ed519bfc451131961d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/context.pyi @@ -0,0 +1,189 @@ +from dataclasses import dataclass +from enum import Flag, IntEnum, IntFlag +from fractions import Fraction +from typing import ClassVar, Literal, cast, overload + +from av.audio import _AudioCodecName +from av.audio.codeccontext import AudioCodecContext +from av.packet import Packet +from av.subtitles import _SubtitleCodecName +from av.subtitles.codeccontext import SubtitleCodecContext +from av.video import _VideoCodecName +from av.video.codeccontext import VideoCodecContext + +from .codec import Codec +from .hwaccel import HWAccel + +class ThreadType(Flag): + NONE = cast(ClassVar[ThreadType], ...) + FRAME = cast(ClassVar[ThreadType], ...) + SLICE = cast(ClassVar[ThreadType], ...) + AUTO = cast(ClassVar[ThreadType], ...) + def __get__(self, i: object | None, owner: type | None = None) -> ThreadType: ... + def __set__(self, instance: object, value: int | str | ThreadType) -> None: ... + +class Flags(IntEnum): + unaligned = cast(int, ...) + qscale = cast(int, ...) + four_mv = cast(int, ...) + output_corrupt = cast(int, ...) + qpel = cast(int, ...) + recon_frame = cast(int, ...) + copy_opaque = cast(int, ...) + frame_duration = cast(int, ...) + pass1 = cast(int, ...) + pass2 = cast(int, ...) + loop_filter = cast(int, ...) + gray = cast(int, ...) + psnr = cast(int, ...) + interlaced_dct = cast(int, ...) + low_delay = cast(int, ...) + global_header = cast(int, ...) + bitexact = cast(int, ...) + ac_pred = cast(int, ...) + interlaced_me = cast(int, ...) + closed_gop = cast(int, ...) + +class Flags2(IntEnum): + fast = cast(int, ...) + no_output = cast(int, ...) + local_header = cast(int, ...) + chunks = cast(int, ...) + ignore_crop = cast(int, ...) + show_all = cast(int, ...) + export_mvs = cast(int, ...) + skip_manual = cast(int, ...) + ro_flush_noop = cast(int, ...) + +class OptionType(IntEnum): + FLAGS = cast(int, ...) + INT = cast(int, ...) + INT64 = cast(int, ...) + DOUBLE = cast(int, ...) + FLOAT = cast(int, ...) + STRING = cast(int, ...) + RATIONAL = cast(int, ...) + BINARY = cast(int, ...) + DICT = cast(int, ...) + UINT64 = cast(int, ...) + CONST = cast(int, ...) + IMAGE_SIZE = cast(int, ...) + PIXEL_FMT = cast(int, ...) + SAMPLE_FMT = cast(int, ...) + VIDEO_RATE = cast(int, ...) + DURATION = cast(int, ...) + COLOR = cast(int, ...) + CHANNEL_LAYOUT = cast(int, ...) + BOOL = cast(int, ...) + UINT = cast(int, ...) + +class OptionFlags(IntFlag): + ENCODING_PARAM = cast(int, ...) + DECODING_PARAM = cast(int, ...) + AUDIO_PARAM = cast(int, ...) + VIDEO_PARAM = cast(int, ...) + SUBTITLE_PARAM = cast(int, ...) + EXPORT = cast(int, ...) + READONLY = cast(int, ...) + BITSTREAM_FILTER_PARAM = cast(int, ...) + RUNTIME_PARAM = cast(int, ...) + FILTERING_PARAM = cast(int, ...) + DEPRECATED = cast(int, ...) + CHILD_CONSTS = cast(int, ...) + +@dataclass(frozen=True, slots=True) +class CodecOptionChoice: + name: str + help: str + +@dataclass(frozen=True, slots=True) +class CodecOption: + name: str + help: str + type: OptionType | int + is_array: bool + default: str | None + min: float + max: float + flags: OptionFlags + choices: tuple[CodecOptionChoice, ...] + +@dataclass(frozen=True, slots=True) +class CodecOptionSet: + generic: tuple[CodecOption, ...] + private: tuple[CodecOption, ...] + +class CodecContext: + name: str + type: Literal["video", "audio", "data", "subtitle", "attachment"] + options: dict[str, str] + @property + def supported_options(self) -> CodecOptionSet: ... + profile: str | None + level: int + @property + def profiles(self) -> list[str]: ... + extradata: bytes | None + time_base: Fraction + codec_tag: str + global_quality: int + bit_rate: int | None + bit_rate_tolerance: int + thread_count: int + thread_type: ThreadType + skip_frame: Literal[ + "NONE", "DEFAULT", "NONREF", "BIDIR", "NONINTRA", "NONKEY", "ALL" + ] + flags: int + qscale: bool + copy_opaque: bool + flags2: int + @property + def is_open(self) -> bool: ... + @property + def is_encoder(self) -> bool: ... + @property + def is_decoder(self) -> bool: ... + @property + def codec(self) -> Codec: ... + @property + def max_bit_rate(self) -> int | None: ... + @property + def delay(self) -> bool: ... + @property + def extradata_size(self) -> int: ... + @property + def is_hwaccel(self) -> bool: ... + def open(self, strict: bool = True) -> None: ... + @overload + @staticmethod + def create( + codec: _AudioCodecName, + mode: Literal["r", "w"] | None = None, + hwaccel: HWAccel | None = None, + ) -> AudioCodecContext: ... + @overload + @staticmethod + def create( + codec: _VideoCodecName, + mode: Literal["r", "w"] | None = None, + hwaccel: HWAccel | None = None, + ) -> VideoCodecContext: ... + @overload + @staticmethod + def create( + codec: _SubtitleCodecName, + mode: Literal["r", "w"] | None = None, + hwaccel: HWAccel | None = None, + ) -> SubtitleCodecContext: ... + @overload + @staticmethod + def create( + codec: str | Codec, + mode: Literal["r", "w"] | None = None, + hwaccel: HWAccel | None = None, + ) -> CodecContext: ... + def parse( + self, raw_input: bytes | bytearray | memoryview | None = None + ) -> list[Packet]: ... + def flush_buffers(self) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/codec/hwaccel.abi3.so b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..8250b8853b9cee02ee58388600e7a94880e0632a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e95b8df5ed7e5f0dd076f1e51bffa689248bc4f3217cfe6c54f30b28d1455c1 +size 659225 diff --git a/.venv/lib/python3.12/site-packages/av/codec/hwaccel.pxd b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.pxd new file mode 100644 index 0000000000000000000000000000000000000000..fd9bb1720977171a15f8112d42cc102dd31a0c6b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.pxd @@ -0,0 +1,23 @@ +cimport libav as lib + +from av.codec.codec cimport Codec + + +cdef class HWConfig: + cdef object __weakref__ + cdef const lib.AVCodecHWConfig *ptr + cdef void _init(self, const lib.AVCodecHWConfig *ptr) + +cdef HWConfig wrap_hwconfig(const lib.AVCodecHWConfig *ptr) + +cdef class HWAccel: + cdef int _device_type + cdef str _device + cdef readonly Codec codec + cdef readonly HWConfig config + cdef lib.AVBufferRef *ptr + cdef readonly int device_id + cdef readonly bint is_hw_owned + cdef public bint allow_software_fallback + cdef public dict options + cdef public int flags diff --git a/.venv/lib/python3.12/site-packages/av/codec/hwaccel.py b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.py new file mode 100644 index 0000000000000000000000000000000000000000..93e7accecf752a2fb886169db62bad798bcdaaea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.py @@ -0,0 +1,220 @@ +import weakref +from enum import IntEnum + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.codec.codec import Codec +from cython.cimports.av.dictionary import Dictionary +from cython.cimports.av.error import err_check +from cython.cimports.av.video.format import get_video_format + + +class HWDeviceType(IntEnum): + none = lib.AV_HWDEVICE_TYPE_NONE + vdpau = lib.AV_HWDEVICE_TYPE_VDPAU + cuda = lib.AV_HWDEVICE_TYPE_CUDA + vaapi = lib.AV_HWDEVICE_TYPE_VAAPI + dxva2 = lib.AV_HWDEVICE_TYPE_DXVA2 + qsv = lib.AV_HWDEVICE_TYPE_QSV + videotoolbox = lib.AV_HWDEVICE_TYPE_VIDEOTOOLBOX + d3d11va = lib.AV_HWDEVICE_TYPE_D3D11VA + drm = lib.AV_HWDEVICE_TYPE_DRM + opencl = lib.AV_HWDEVICE_TYPE_OPENCL + mediacodec = lib.AV_HWDEVICE_TYPE_MEDIACODEC + vulkan = lib.AV_HWDEVICE_TYPE_VULKAN + d3d12va = lib.AV_HWDEVICE_TYPE_D3D12VA + amf = 13 # FFmpeg >=8 + ohcodec = 14 + # TODO: When ffmpeg major is changed, check this enum. + + +class HWConfigMethod(IntEnum): + none = 0 + hw_device_ctx = ( + lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX + ) # This is the only one we support. + hw_frame_ctx = lib.AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX + internal = lib.AV_CODEC_HW_CONFIG_METHOD_INTERNAL + ad_hoc = lib.AV_CODEC_HW_CONFIG_METHOD_AD_HOC + + +_cinit_sentinel = cython.declare(object, object()) +_singletons = cython.declare(object, weakref.WeakValueDictionary()) + + +@cython.cfunc +def wrap_hwconfig(ptr: cython.pointer[cython.const[lib.AVCodecHWConfig]]) -> HWConfig: + try: + return _singletons[cython.cast(cython.Py_ssize_t, ptr)] + except KeyError: + pass + config: HWConfig = HWConfig(_cinit_sentinel) + config._init(ptr) + _singletons[cython.cast(cython.Py_ssize_t, ptr)] = config + return config + + +@cython.final +@cython.cclass +class HWConfig: + def __init__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("Cannot instantiate CodecContext") + + @cython.cfunc + def _init( + self, ptr: cython.pointer[cython.const[lib.AVCodecHWConfig]] + ) -> cython.void: + self.ptr = ptr + + def __repr__(self): + return ( + f"" + ) + + @property + def device_type(self): + return HWDeviceType(self.ptr.device_type) + + @property + def format(self): + return get_video_format(self.ptr.pix_fmt, 0, 0) + + @property + def methods(self): + return HWConfigMethod(self.ptr.methods) + + @property + def is_supported(self): + return bool(self.ptr.methods & lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) + + +@cython.ccall +def hwdevices_available(): + """Return the names of the hardware device types FFmpeg was built with, + e.g. ``["cuda", "videotoolbox"]``.""" + result: list = [] + x: lib.AVHWDeviceType = lib.AV_HWDEVICE_TYPE_NONE + while True: + x = lib.av_hwdevice_iterate_types(x) + if x == lib.AV_HWDEVICE_TYPE_NONE: + break + result.append(lib.av_hwdevice_get_type_name(HWDeviceType(x))) + return result + + +@cython.final +@cython.cclass +class HWAccel: + """HWAccel(device_type, device=None, allow_software_fallback=True, options=None, flags=None, is_hw_owned=False) + + Settings for hardware-accelerated decoding and encoding. Pass an instance to + :func:`av.open` to decode on the device, or to + :meth:`OutputContainer.add_stream ` + to encode on it. + + :param device_type: The kind of device, e.g. ``"cuda"``, ``"vaapi"``, + ``"videotoolbox"``. See :func:`hwdevices_available` for the types + supported by the loaded FFmpeg. + :type device_type: str or HWDeviceType + :param str device: An optional device identifier, e.g. a DRI render node path + (``"/dev/dri/renderD128"``) for VAAPI or a device index (``"1"``) for CUDA. + Uses the default device if ``None``. + :param bool allow_software_fallback: Whether decoding falls back to a software + decoder when the hardware decoder cannot handle the stream. + :param dict options: Options passed to ``av_hwdevice_ctx_create``. + :param int flags: Flags passed to ``av_hwdevice_ctx_create``. + :param bool is_hw_owned: If True, decoded frames stay on the device (for + consumption via DLPack, for example) instead of being downloaded to + system memory. + """ + + def __init__( + self, + device_type, + device=None, + allow_software_fallback=True, + options=None, + flags=None, + is_hw_owned=False, + ): + if isinstance(device_type, HWDeviceType): + self._device_type = device_type + elif isinstance(device_type, str): + self._device_type = int(lib.av_hwdevice_find_type_by_name(device_type)) + elif isinstance(device_type, int): + self._device_type = device_type + else: + raise ValueError("Unknown type for device_type") + + self.is_hw_owned = is_hw_owned + self.device_id = 0 + if self._device_type == HWDeviceType.cuda and device: + self.device_id = int(device) + + self._device = None if device is None else f"{device}" + self.allow_software_fallback = allow_software_fallback + + self.options = {} if not options else dict(options) + if self._device_type == HWDeviceType.cuda and self.is_hw_owned: + self.options.setdefault("primary_ctx", "1") + self.flags = 0 if not flags else flags + self.ptr = cython.NULL + self.config = None + + def _initialize_hw_context(self, codec: Codec, for_encoding: bool = False): + # Decoders advertise the device-context method, while encoders (e.g. + # h264_vaapi) advertise the frames-context method. Accept either one when + # setting up an encoder. + supported_methods: cython.int = lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX + if for_encoding: + supported_methods |= lib.AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX + + config: HWConfig + for config in codec.hardware_configs: + if not (config.ptr.methods & supported_methods): + continue + if self._device_type and config.device_type != self._device_type: + continue + break + else: # nobreak + raise NotImplementedError(f"No supported hardware config for {codec}") + + self.config = config + c_device: cython.p_char = cython.NULL + if self._device: + device_bytes = self._device.encode() + c_device = device_bytes + c_options: Dictionary = Dictionary(self.options) + + err_check( + lib.av_hwdevice_ctx_create( + cython.address(self.ptr), + config.ptr.device_type, + c_device, + c_options.ptr, + self.flags, + ) + ) + + def create(self, codec: Codec, for_encoding: bool = False) -> HWAccel: + """Create a new hardware accelerator context with the given codec""" + if self.ptr: + raise RuntimeError("Hardware context already initialized") + + ret = HWAccel( + device_type=self._device_type, + device=self._device, + allow_software_fallback=self.allow_software_fallback, + options=self.options, + is_hw_owned=self.is_hw_owned, + ) + ret._initialize_hw_context(codec, for_encoding=for_encoding) + return ret + + def __dealloc__(self): + if self.ptr: + lib.av_buffer_unref(cython.address(self.ptr)) diff --git a/.venv/lib/python3.12/site-packages/av/codec/hwaccel.pyi b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b3b0c3ff0e76d87dfbbf6d21ad2f4e8d048dfe84 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/codec/hwaccel.pyi @@ -0,0 +1,57 @@ +from enum import IntEnum +from typing import cast + +from av.codec.codec import Codec +from av.video.format import VideoFormat + +class HWDeviceType(IntEnum): + none = cast(int, ...) + vdpau = cast(int, ...) + cuda = cast(int, ...) + vaapi = cast(int, ...) + dxva2 = cast(int, ...) + qsv = cast(int, ...) + videotoolbox = cast(int, ...) + d3d11va = cast(int, ...) + drm = cast(int, ...) + opencl = cast(int, ...) + mediacodec = cast(int, ...) + vulkan = cast(int, ...) + d3d12va = cast(int, ...) + +class HWConfigMethod(IntEnum): + none = cast(int, ...) + hw_device_ctx = cast(int, ...) + hw_frame_ctx = cast(int, ...) + internal = cast(int, ...) + ad_hoc = cast(int, ...) + +class HWConfig: + @property + def device_type(self) -> HWDeviceType: ... + @property + def format(self) -> VideoFormat | None: ... + @property + def methods(self) -> HWConfigMethod: ... + @property + def is_supported(self) -> bool: ... + +class HWAccel: + options: dict[str, object] + + @property + def is_hw_owned(self) -> bool: ... + @property + def device_id(self) -> int: ... + def __init__( + self, + device_type: str | HWDeviceType, + device: str | int | None = None, + allow_software_fallback: bool = False, + options: dict[str, object] | None = None, + flags: int | None = None, + is_hw_owned: bool = False, + ) -> None: ... + def create(self, codec: Codec, for_encoding: bool = False) -> HWAccel: ... + +def hwdevices_available() -> list[str]: ... diff --git a/.venv/lib/python3.12/site-packages/av/container/__init__.pxd b/.venv/lib/python3.12/site-packages/av/container/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/container/__init__.py b/.venv/lib/python3.12/site-packages/av/container/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c5dde46ea6f5cbdc72d990623fb27ee6f27af69c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/__init__.py @@ -0,0 +1,3 @@ +from .core import Container, Flags, open +from .input import InputContainer as InputContainer +from .output import OutputContainer as OutputContainer diff --git a/.venv/lib/python3.12/site-packages/av/container/__init__.pyi b/.venv/lib/python3.12/site-packages/av/container/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7160777cc06b6ebf854ad7988da98d9740b7a36b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/__init__.pyi @@ -0,0 +1,3 @@ +from .core import * +from .input import * +from .output import * diff --git a/.venv/lib/python3.12/site-packages/av/container/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/container/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4653cf68c346fb6142eeb9b91bfd309e12ef86c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/container/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/container/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/container/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef2312c20cd69b59078569cc639d27e4c4b85c3f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/container/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/container/__pycache__/input.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/container/__pycache__/input.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b54a73118628c352bb0398c2e397dd1029aa2d5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/container/__pycache__/input.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/container/__pycache__/output.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/container/__pycache__/output.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..951c04c914c15523f8a45d8f105d751c2d454125 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/container/__pycache__/output.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/container/__pycache__/pyio.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/container/__pycache__/pyio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9e2302ce982f73b15b784abf55a53474f0b3f0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/container/__pycache__/pyio.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/container/__pycache__/streams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/container/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494c66201ea36a9a229b97722eddcace84fa99a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/container/__pycache__/streams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/container/core.abi3.so b/.venv/lib/python3.12/site-packages/av/container/core.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..aab257d031e9f352769a440d124dd3f7497e0075 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/core.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0ffc249903b68b02b6d04fafb9dc9e339779dba193ea81d725b53f82882fb71 +size 1052985 diff --git a/.venv/lib/python3.12/site-packages/av/container/core.pxd b/.venv/lib/python3.12/site-packages/av/container/core.pxd new file mode 100644 index 0000000000000000000000000000000000000000..bd298a7a0be6293ca74d03aa3b6af36bc937d748 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/core.pxd @@ -0,0 +1,49 @@ +cimport libav as lib +from libc.stdint cimport uint8_t + +from av.codec.hwaccel cimport HWAccel +from av.container.pyio cimport PyIOFile +from av.container.streams cimport StreamContainer +from av.dictionary cimport Dictionary +from av.format cimport ContainerFormat +from av.stream cimport Stream + +# Interrupt callback information, times are in seconds. +ctypedef struct timeout_info: + double start_time + double timeout + + +cdef class Container: + cdef lib.AVFormatContext *ptr + cdef readonly object name + cdef readonly str metadata_encoding + cdef readonly str metadata_errors + + cdef readonly PyIOFile file + cdef int buffer_size + cdef readonly object io_open + cdef readonly object open_files + + cdef readonly ContainerFormat format + + cdef readonly dict options + cdef readonly dict container_options + cdef readonly list stream_options + + cdef HWAccel hwaccel + + cdef readonly StreamContainer streams + cdef dict _metadata + + # Private API. + cdef uint8_t _myflag # enum: writeable, input_was_opened, started, done, extradata_planned + cdef _assert_open(self) + cdef int err_check(self, int value) except -1 + + # Timeouts + cdef readonly object open_timeout + cdef readonly object read_timeout + cdef timeout_info interrupt_callback_info + cdef set_timeout(self, object) + cdef start_timeout(self) diff --git a/.venv/lib/python3.12/site-packages/av/container/core.py b/.venv/lib/python3.12/site-packages/av/container/core.py new file mode 100644 index 0000000000000000000000000000000000000000..bd82e86a4b0970fdc6c6c437a5ba96928a991145 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/core.py @@ -0,0 +1,612 @@ +import os +import time +from enum import Flag, IntEnum +from pathlib import Path + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.container.core import timeout_info +from cython.cimports.av.container.input import InputContainer +from cython.cimports.av.container.output import OutputContainer +from cython.cimports.av.container.pyio import pyio_close_custom_gil, pyio_close_gil +from cython.cimports.av.error import err_check, stash_exception +from cython.cimports.av.format import build_container_format +from cython.cimports.av.utils import ( + avdict_to_dict, + avrational_to_fraction, + dict_to_avdict, + to_avrational, +) +from cython.cimports.libc.stdint import int64_t +from cython.operator import dereference + +from av.logging import Capture as LogCapture + +_cinit_sentinel = cython.declare(object, object()) + +AVChapterPtrPtr = cython.typedef(cython.pointer[cython.pointer[lib.AVChapter]]) + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def interrupt_cb(p: cython.p_void) -> cython.int: + info: timeout_info = dereference(cython.cast(cython.pointer[timeout_info], p)) + if info.timeout < 0: # timeout < 0 means no timeout + return 0 + + current_time: cython.double + with cython.gil: + current_time = time.monotonic() + if current_time < info.start_time: + # Raise this when we get back to Python. + stash_exception( + ( + RuntimeError, + RuntimeError("Clock has been changed to before timeout start"), + None, + ) + ) + return 1 + + if current_time > info.start_time + info.timeout: + return 1 + return 0 + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def pyav_io_open( + s: cython.pointer[lib.AVFormatContext], + pb: cython.pointer[cython.pointer[lib.AVIOContext]], + url: cython.p_const_char, + flags: cython.int, + options: cython.pointer[cython.pointer[lib.AVDictionary]], +) -> cython.int: + with cython.gil: + return pyav_io_open_gil(s, pb, url, flags, options) + + +@cython.cfunc +@cython.exceptval(check=False) +def pyav_io_open_gil( + s: cython.pointer[lib.AVFormatContext], + pb: cython.pointer[cython.pointer[lib.AVIOContext]], + url: cython.p_const_char, + flags: cython.int, + options: cython.pointer[cython.pointer[lib.AVDictionary]], +) -> cython.int: + container: Container + file: object + pyio_file: PyIOFile + try: + container = cython.cast(Container, dereference(s).opaque) + + if options is not cython.NULL: + options_dict = avdict_to_dict( + dereference( + cython.cast( + cython.pointer[cython.pointer[lib.AVDictionary]], options + ) + ), + encoding=container.metadata_encoding, + errors=container.metadata_errors, + ) + else: + options_dict = {} + + file = container.io_open( + cython.cast(str, url) if url is not cython.NULL else "", flags, options_dict + ) + + pyio_file = PyIOFile( + file, container.buffer_size, (flags & lib.AVIO_FLAG_WRITE) != 0 + ) + + # Add it to the container to avoid it being deallocated + container.open_files[cython.cast(int64_t, pyio_file.iocontext.opaque)] = ( + pyio_file + ) + pb[0] = pyio_file.iocontext + return 0 + except Exception: + return stash_exception() + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def pyav_io_close( + s: cython.pointer[lib.AVFormatContext], pb: cython.pointer[lib.AVIOContext] +) -> cython.int: + with cython.gil: + return pyav_io_close_gil(s, pb) + + +@cython.cfunc +@cython.exceptval(check=False) +def pyav_io_close_gil( + s: cython.pointer[lib.AVFormatContext], pb: cython.pointer[lib.AVIOContext] +) -> cython.int: + container: Container + result: cython.int = 0 + try: + container = cython.cast(Container, dereference(s).opaque) + if ( + container.open_files is not None + and cython.cast(int64_t, pb.opaque) in container.open_files + ): + result = pyio_close_custom_gil(pb) + + # Remove it from the container so that it can be deallocated + del container.open_files[cython.cast(int64_t, pb.opaque)] + else: + result = pyio_close_gil(pb) + + except Exception: + stash_exception() + result = lib.AVERROR_UNKNOWN # Or another appropriate error code + + return result + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def _free_chapters(ctx: cython.pointer[lib.AVFormatContext]) -> cython.void: + i: cython.Py_ssize_t + if ctx.chapters != cython.NULL: + for i in range(ctx.nb_chapters): + if ctx.chapters[i] != cython.NULL: + if ctx.chapters[i].metadata != cython.NULL: + lib.av_dict_free(cython.address(ctx.chapters[i].metadata)) + lib.av_freep( + cython.cast(cython.pp_void, cython.address(ctx.chapters[i])) + ) + lib.av_freep(cython.cast(cython.pp_void, cython.address(ctx.chapters))) + ctx.nb_chapters = 0 + + +# fmt: off +class Flags(Flag): + gen_pts: "Generate missing pts even if it requires parsing future frames." = lib.AVFMT_FLAG_GENPTS + ign_idx: "Ignore index." = lib.AVFMT_FLAG_IGNIDX + non_block: "Do not block when reading packets from input." = lib.AVFMT_FLAG_NONBLOCK + ign_dts: "Ignore DTS on frames that contain both DTS & PTS." = lib.AVFMT_FLAG_IGNDTS + no_fillin: "Do not infer any values from other values, just return what is stored in the container." = lib.AVFMT_FLAG_NOFILLIN + no_parse: "Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fill in code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled." = lib.AVFMT_FLAG_NOPARSE + no_buffer: "Do not buffer frames when possible." = lib.AVFMT_FLAG_NOBUFFER + custom_io: "The caller has supplied a custom AVIOContext, don't avio_close() it." = lib.AVFMT_FLAG_CUSTOM_IO + discard_corrupt: "Discard frames marked corrupted." = lib.AVFMT_FLAG_DISCARD_CORRUPT + flush_packets: "Flush the AVIOContext every packet." = lib.AVFMT_FLAG_FLUSH_PACKETS + bitexact: "When muxing, try to avoid writing any random/volatile data to the output. This includes any random IDs, real-time timestamps/dates, muxer version, etc. This flag is mainly intended for testing." = lib.AVFMT_FLAG_BITEXACT + sort_dts: "Try to interleave outputted packets by dts (using this flag can slow demuxing down)." = lib.AVFMT_FLAG_SORT_DTS + fast_seek: "Enable fast, but inaccurate seeks for some formats." = lib.AVFMT_FLAG_FAST_SEEK + auto_bsf: "Add bitstream filters as requested by the muxer." = lib.AVFMT_FLAG_AUTO_BSF + +class AudioCodec(IntEnum): + """Enumeration for audio codec IDs.""" + none = lib.AV_CODEC_ID_NONE # No codec. + pcm_alaw = lib.AV_CODEC_ID_PCM_ALAW # PCM A-law. + pcm_bluray = lib.AV_CODEC_ID_PCM_BLURAY # PCM Blu-ray. + pcm_dvd = lib.AV_CODEC_ID_PCM_DVD # PCM DVD. + pcm_f16le = lib.AV_CODEC_ID_PCM_F16LE # PCM F16 little-endian. + pcm_f24le = lib.AV_CODEC_ID_PCM_F24LE # PCM F24 little-endian. + pcm_f32be = lib.AV_CODEC_ID_PCM_F32BE # PCM F32 big-endian. + pcm_f32le = lib.AV_CODEC_ID_PCM_F32LE # PCM F32 little-endian. + pcm_f64be = lib.AV_CODEC_ID_PCM_F64BE # PCM F64 big-endian. + pcm_f64le = lib.AV_CODEC_ID_PCM_F64LE # PCM F64 little-endian. + pcm_lxf = lib.AV_CODEC_ID_PCM_LXF # PCM LXF. + pcm_mulaw = lib.AV_CODEC_ID_PCM_MULAW # PCM μ-law. + pcm_s16be = lib.AV_CODEC_ID_PCM_S16BE # PCM signed 16-bit big-endian. + pcm_s16be_planar = lib.AV_CODEC_ID_PCM_S16BE_PLANAR # PCM signed 16-bit big-endian planar. + pcm_s16le = lib.AV_CODEC_ID_PCM_S16LE # PCM signed 16-bit little-endian. + pcm_s16le_planar = lib.AV_CODEC_ID_PCM_S16LE_PLANAR # PCM signed 16-bit little-endian planar. + pcm_s24be = lib.AV_CODEC_ID_PCM_S24BE # PCM signed 24-bit big-endian. + pcm_s24daud = lib.AV_CODEC_ID_PCM_S24DAUD # PCM signed 24-bit D-Cinema audio. + pcm_s24le = lib.AV_CODEC_ID_PCM_S24LE # PCM signed 24-bit little-endian. + pcm_s24le_planar = lib.AV_CODEC_ID_PCM_S24LE_PLANAR # PCM signed 24-bit little-endian planar. + pcm_s32be = lib.AV_CODEC_ID_PCM_S32BE # PCM signed 32-bit big-endian. + pcm_s32le = lib.AV_CODEC_ID_PCM_S32LE # PCM signed 32-bit little-endian. + pcm_s32le_planar = lib.AV_CODEC_ID_PCM_S32LE_PLANAR # PCM signed 32-bit little-endian planar. + pcm_s64be = lib.AV_CODEC_ID_PCM_S64BE # PCM signed 64-bit big-endian. + pcm_s64le = lib.AV_CODEC_ID_PCM_S64LE # PCM signed 64-bit little-endian. + pcm_s8 = lib.AV_CODEC_ID_PCM_S8 # PCM signed 8-bit. + pcm_s8_planar = lib.AV_CODEC_ID_PCM_S8_PLANAR # PCM signed 8-bit planar. + pcm_u16be = lib.AV_CODEC_ID_PCM_U16BE # PCM unsigned 16-bit big-endian. + pcm_u16le = lib.AV_CODEC_ID_PCM_U16LE # PCM unsigned 16-bit little-endian. + pcm_u24be = lib.AV_CODEC_ID_PCM_U24BE # PCM unsigned 24-bit big-endian. + pcm_u24le = lib.AV_CODEC_ID_PCM_U24LE # PCM unsigned 24-bit little-endian. + pcm_u32be = lib.AV_CODEC_ID_PCM_U32BE # PCM unsigned 32-bit big-endian. + pcm_u32le = lib.AV_CODEC_ID_PCM_U32LE # PCM unsigned 32-bit little-endian. + pcm_u8 = lib.AV_CODEC_ID_PCM_U8 # PCM unsigned 8-bit. + pcm_vidc = lib.AV_CODEC_ID_PCM_VIDC # PCM VIDC. +# fmt: on + + +@cython.cclass +class Container: + def __cinit__( + self, + sentinel, + file_, + format_name, + options, + container_options, + stream_options, + hwaccel, + metadata_encoding, + metadata_errors, + buffer_size, + open_timeout, + read_timeout, + io_open, + ): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot construct base Container") + + writeable: cython.bint = isinstance(self, OutputContainer) + if not writeable and not isinstance(self, InputContainer): + raise RuntimeError("Container cannot be directly extended.") + + if isinstance(file_, str): + self.name = file_ + else: + self.name = str(getattr(file_, "name", "")) + + self.options = dict(options or ()) + self.container_options = dict(container_options or ()) + self.stream_options = [dict(x) for x in stream_options or ()] + + self.hwaccel = hwaccel + + self.metadata_encoding = metadata_encoding + self.metadata_errors = metadata_errors + + self.open_timeout = open_timeout + self.read_timeout = read_timeout + + self.buffer_size = buffer_size + self.io_open = io_open + + acodec = None # no audio codec specified + if format_name is not None: + if ":" in format_name: + format_name, acodec = format_name.split(":") + self.format = ContainerFormat(format_name) + + res: cython.int + name_obj: bytes = os.fsencode(self.name) + name: cython.p_char = name_obj + ofmt: cython.pointer[cython.const[lib.AVOutputFormat]] + + if writeable: + self._myflag |= 1 # enum.writeable = True + ofmt = ( + self.format.optr + if self.format + else lib.av_guess_format(cython.NULL, name, cython.NULL) + ) + if ofmt == cython.NULL: + raise ValueError("Could not determine output format") + + with cython.nogil: + # This does not actually open the file. + res = lib.avformat_alloc_output_context2( + cython.address(self.ptr), + ofmt, + cython.NULL, + name, + ) + self.err_check(res) + else: + # We need the context before we open the input AND setup Python IO. + self.ptr = lib.avformat_alloc_context() + + # Setup interrupt callback + if self.open_timeout is not None or self.read_timeout is not None: + self.ptr.interrupt_callback.callback = interrupt_cb + self.ptr.interrupt_callback.opaque = cython.address( + self.interrupt_callback_info + ) + + if acodec is not None: + self.ptr.audio_codec_id = getattr(AudioCodec, acodec) + + self.ptr.flags |= lib.AVFMT_FLAG_GENPTS + self.ptr.opaque = cython.cast(cython.p_void, self) + + # Setup Python IO. + self.open_files = {} + if not isinstance(file_, basestring): + self.file = PyIOFile(file_, buffer_size, writeable) + self.ptr.pb = self.file.iocontext + + if io_open is not None: + self.ptr.io_open = pyav_io_open + self.ptr.io_close2 = pyav_io_close + self.ptr.flags |= lib.AVFMT_FLAG_CUSTOM_IO + + ifmt: cython.pointer[cython.const[lib.AVInputFormat]] + c_options: Dictionary + if not writeable: + ifmt = self.format.iptr if self.format else cython.NULL + c_options = Dictionary(self.options, self.container_options) + + self.set_timeout(self.open_timeout) + self.start_timeout() + with cython.nogil: + res = lib.avformat_open_input( + cython.address(self.ptr), name, ifmt, cython.address(c_options.ptr) + ) + self.set_timeout(None) + self.err_check(res) + self._myflag |= 2 # enum.input_was_opened = True + + if format_name is None: + self.format = build_container_format(self.ptr.iformat, self.ptr.oformat) + + def __dealloc__(self): + with cython.nogil: + lib.avformat_free_context(self.ptr) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def close(self): + raise NotImplementedError + + def __repr__(self): + return f"" + + @cython.cfunc + @cython.exceptval(-1, check=False) + def err_check(self, value: cython.int) -> cython.int: + return err_check(value, filename=self.name) + + def dumps_format(self): + self._assert_open() + with LogCapture() as logs: + lib.av_dump_format(self.ptr, 0, "", isinstance(self, OutputContainer)) + return "".join(log[2] for log in logs) + + @cython.cfunc + def set_timeout(self, timeout): + if timeout is None: + self.interrupt_callback_info.timeout = -1.0 + else: + self.interrupt_callback_info.timeout = timeout + + @cython.cfunc + def start_timeout(self): + self.interrupt_callback_info.start_time = time.monotonic() + + @cython.cfunc + def _assert_open(self): + if self.ptr == cython.NULL: + raise AssertionError("Container is not open") + + @property + def video_codec_id(self): + self._assert_open() + return self.ptr.video_codec_id + + @video_codec_id.setter + def video_codec_id(self, value: lib.AVCodecID): + self._assert_open() + self.ptr.video_codec_id = value + + @property + def flags(self): + self._assert_open() + return self.ptr.flags + + @flags.setter + def flags(self, value: cython.int): + self._assert_open() + self.ptr.flags = value + + @property + def input_was_opened(self): + return self._myflag & 2 + + @property + def metadata(self) -> dict: + # Lazily created so output containers that never touch metadata don't + # allocate a dict. Input containers populate ``_metadata`` eagerly. + if self._metadata is None: + self._metadata = {} + return self._metadata + + def chapters(self): + self._assert_open() + result: list = [] + i: cython.Py_ssize_t + for i in range(self.ptr.nb_chapters): + ch = self.ptr.chapters[i] + result.append( + { + "id": ch.id, + "start": ch.start, + "end": ch.end, + "time_base": avrational_to_fraction(cython.address(ch.time_base)), + "metadata": avdict_to_dict( + ch.metadata, self.metadata_encoding, self.metadata_errors + ), + } + ) + return result + + def set_chapters(self, chapters): + self._assert_open() + + count: cython.Py_ssize_t = len(chapters) + i: cython.Py_ssize_t + ch_array: AVChapterPtrPtr + ch: cython.pointer[lib.AVChapter] + entry: dict + + with cython.nogil: + _free_chapters(self.ptr) + + if count == 0: + self.ptr.nb_chapters = 0 + self.ptr.chapters = cython.NULL + return + + ch_array = cython.cast( + AVChapterPtrPtr, + lib.av_malloc(count * cython.sizeof(cython.pointer[lib.AVChapter])), + ) + if ch_array == cython.NULL: + raise MemoryError("av_malloc failed for chapters") + + for i in range(count): + entry = chapters[i] + ch = cython.cast( + cython.pointer[lib.AVChapter], + lib.av_malloc(cython.sizeof(lib.AVChapter)), + ) + if ch == cython.NULL: + raise MemoryError("av_malloc failed for chapter") + ch.id = entry["id"] + ch.start = cython.cast(int64_t, entry["start"]) + ch.end = cython.cast(int64_t, entry["end"]) + to_avrational(entry["time_base"], cython.address(ch.time_base)) + ch.metadata = cython.NULL + if "metadata" in entry: + dict_to_avdict( + cython.address(ch.metadata), + entry["metadata"], + self.metadata_encoding, + self.metadata_errors, + ) + ch_array[i] = ch + + self.ptr.nb_chapters = cython.cast(cython.uint, count) + self.ptr.chapters = ch_array + + +def open( + file, + mode=None, + format=None, + options=None, + container_options=None, + stream_options=None, + metadata_encoding="utf-8", + metadata_errors="strict", + buffer_size=32768, + timeout=None, + io_open=None, + hwaccel=None, +): + """open(file, mode='r', **kwargs) + + Main entrypoint to opening files/streams. + + :param str file: The file to open, which can be either a string or a file-like object. + :param str mode: ``"r"`` for reading and ``"w"`` for writing. + :param str format: Specific format to use. Defaults to autodect. + :param dict options: Options to pass to the container and all streams. + :param dict container_options: Options to pass to the container. + :param list stream_options: Options to pass to each stream. + :param str metadata_encoding: Encoding to use when reading or writing file metadata. + Defaults to ``"utf-8"``. + :param str metadata_errors: Specifies how to handle encoding errors; behaves like + ``str.encode`` parameter. Defaults to ``"strict"``. + :param int buffer_size: Size of buffer for Python input/output operations in bytes. + Honored only when ``file`` is a file-like object. Defaults to 32768 (32k). + :param timeout: How many seconds to wait for data before giving up, as a float, or a + ``(open timeout, read timeout)`` tuple. + :param callable io_open: Custom I/O callable for opening files/streams. + This option is intended for formats that need to open additional + file-like objects to ``file`` using custom I/O. + The callable signature is ``io_open(url: str, flags: int, options: dict)``, where + ``url`` is the url to open, ``flags`` is a combination of AVIO_FLAG_* and + ``options`` is a dictionary of additional options. The callable should return a + file-like object. + :param HWAccel hwaccel: Optional settings for hardware-accelerated decoding. + :rtype: Container + + For devices (via ``libavdevice``), pass the name of the device to ``format``, + e.g.:: + + >>> # Open webcam on MacOS. + >>> av.open('0', format='avfoundation') # doctest: +SKIP + + For DASH and custom I/O using ``io_open``, add a protocol prefix to the ``file`` to + prevent the DASH encoder defaulting to the file protocol and using temporary files. + The custom I/O callable can be used to remove the protocol prefix to reveal the actual + name for creating the file-like object. E.g.:: + + >>> av.open("customprotocol://manifest.mpd", "w", io_open=custom_io) # doctest: +SKIP + + .. seealso:: :ref:`garbage_collection` + + More information on using input and output devices is available on the + `FFmpeg website `_. + """ + + if not (mode is None or (isinstance(mode, str) and mode == "r" or mode == "w")): + raise ValueError(f"mode must be 'r', 'w', or None, got: {mode}") + + if isinstance(file, str): + pass + elif isinstance(file, Path): + file = f"{file}" + elif mode is None: + mode = getattr(file, "mode", None) + + if mode is None: + mode = "r" + + if isinstance(timeout, tuple): + if not len(timeout) == 2: + raise ValueError("timeout must be `float` or `tuple[float, float]`") + + open_timeout, read_timeout = timeout + else: + open_timeout = timeout + read_timeout = timeout + + if mode.startswith("r"): + return InputContainer( + _cinit_sentinel, + file, + format, + options, + container_options, + stream_options, + hwaccel, + metadata_encoding, + metadata_errors, + buffer_size, + open_timeout, + read_timeout, + io_open, + ) + + if stream_options: + raise ValueError( + "Provide stream options via Container.add_stream(..., options={})." + ) + return OutputContainer( + _cinit_sentinel, + file, + format, + options, + container_options, + stream_options, + None, + metadata_encoding, + metadata_errors, + buffer_size, + open_timeout, + read_timeout, + io_open, + ) diff --git a/.venv/lib/python3.12/site-packages/av/container/core.pyi b/.venv/lib/python3.12/site-packages/av/container/core.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ec4a84d8916a51085e178df8e2ce30804bc47e99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/core.pyi @@ -0,0 +1,168 @@ +from collections.abc import Callable +from enum import Flag, IntEnum +from fractions import Fraction +from pathlib import Path +from types import TracebackType +from typing import Any, ClassVar, Literal, Self, TypedDict, cast, overload + +from av.codec.hwaccel import HWAccel +from av.format import ContainerFormat + +from .input import InputContainer +from .output import OutputContainer +from .streams import StreamContainer + +Real = int | float | Fraction + +class Flags(Flag): + gen_pts = cast(ClassVar[Flags], ...) + ign_idx = cast(ClassVar[Flags], ...) + non_block = cast(ClassVar[Flags], ...) + ign_dts = cast(ClassVar[Flags], ...) + no_fillin = cast(ClassVar[Flags], ...) + no_parse = cast(ClassVar[Flags], ...) + no_buffer = cast(ClassVar[Flags], ...) + custom_io = cast(ClassVar[Flags], ...) + discard_corrupt = cast(ClassVar[Flags], ...) + flush_packets = cast(ClassVar[Flags], ...) + bitexact = cast(ClassVar[Flags], ...) + sort_dts = cast(ClassVar[Flags], ...) + fast_seek = cast(ClassVar[Flags], ...) + shortest = cast(ClassVar[Flags], ...) + auto_bsf = cast(ClassVar[Flags], ...) + +class AudioCodec(IntEnum): + none = cast(int, ...) + pcm_alaw = cast(int, ...) + pcm_bluray = cast(int, ...) + pcm_dvd = cast(int, ...) + pcm_f16le = cast(int, ...) + pcm_f24le = cast(int, ...) + pcm_f32be = cast(int, ...) + pcm_f32le = cast(int, ...) + pcm_f64be = cast(int, ...) + pcm_f64le = cast(int, ...) + pcm_lxf = cast(int, ...) + pcm_mulaw = cast(int, ...) + pcm_s16be = cast(int, ...) + pcm_s16be_planar = cast(int, ...) + pcm_s16le = cast(int, ...) + pcm_s16le_planar = cast(int, ...) + pcm_s24be = cast(int, ...) + pcm_s24daud = cast(int, ...) + pcm_s24le = cast(int, ...) + pcm_s24le_planar = cast(int, ...) + pcm_s32be = cast(int, ...) + pcm_s32le = cast(int, ...) + pcm_s32le_planar = cast(int, ...) + pcm_s64be = cast(int, ...) + pcm_s64le = cast(int, ...) + pcm_s8 = cast(int, ...) + pcm_s8_planar = cast(int, ...) + pcm_u16be = cast(int, ...) + pcm_u16le = cast(int, ...) + pcm_u24be = cast(int, ...) + pcm_u24le = cast(int, ...) + pcm_u32be = cast(int, ...) + pcm_u32le = cast(int, ...) + pcm_u8 = cast(int, ...) + pcm_vidc = cast(int, ...) + +class Chapter(TypedDict): + id: int + start: int + end: int + time_base: Fraction | None + metadata: dict[str, str] + +class Container: + name: str + metadata_encoding: str + metadata_errors: str + file: Any + buffer_size: int + io_open: Any + open_files: Any + format: ContainerFormat + options: dict[str, str] + container_options: dict[str, str] + stream_options: list[dict[str, str]] + streams: StreamContainer + metadata: dict[str, str] + open_timeout: Real | None + read_timeout: Real | None + flags: int + video_codec_id: int + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: ... + @property + def input_was_opened(self) -> bool: ... + def close(self) -> None: ... + def chapters(self) -> list[Chapter]: ... + def set_chapters(self, chapters: list[Chapter]) -> None: ... + +@overload +def open( + file: Any, + mode: Literal["r"], + format: str | None = None, + options: dict[str, str] | None = None, + container_options: dict[str, str] | None = None, + stream_options: list[str] | None = None, + metadata_encoding: str = "utf-8", + metadata_errors: str = "strict", + buffer_size: int = 32768, + timeout: Real | None | tuple[Real | None, Real | None] = None, + io_open: Callable[..., Any] | None = None, + hwaccel: HWAccel | None = None, +) -> InputContainer: ... +@overload +def open( + file: str | Path, + mode: Literal["r"] | None = None, + format: str | None = None, + options: dict[str, str] | None = None, + container_options: dict[str, str] | None = None, + stream_options: list[str] | None = None, + metadata_encoding: str = "utf-8", + metadata_errors: str = "strict", + buffer_size: int = 32768, + timeout: Real | None | tuple[Real | None, Real | None] = None, + io_open: Callable[..., Any] | None = None, + hwaccel: HWAccel | None = None, +) -> InputContainer: ... +@overload +def open( + file: Any, + mode: Literal["w"], + format: str | None = None, + options: dict[str, str] | None = None, + container_options: dict[str, str] | None = None, + stream_options: list[str] | None = None, + metadata_encoding: str = "utf-8", + metadata_errors: str = "strict", + buffer_size: int = 32768, + timeout: Real | None | tuple[Real | None, Real | None] = None, + io_open: Callable[..., Any] | None = None, + hwaccel: HWAccel | None = None, +) -> OutputContainer: ... +@overload +def open( + file: Any, + mode: Literal["r", "w"] | None = None, + format: str | None = None, + options: dict[str, str] | None = None, + container_options: dict[str, str] | None = None, + stream_options: list[str] | None = None, + metadata_encoding: str = "utf-8", + metadata_errors: str = "strict", + buffer_size: int = 32768, + timeout: Real | None | tuple[Real | None, Real | None] = None, + io_open: Callable[..., Any] | None = None, + hwaccel: HWAccel | None = None, +) -> InputContainer | OutputContainer: ... diff --git a/.venv/lib/python3.12/site-packages/av/container/input.abi3.so b/.venv/lib/python3.12/site-packages/av/container/input.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..6dfca85a13e5cbfd9aaada0a59dd92580265415a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/input.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c36d45c2ef429368b7e886afbf8fc999d8e15a77e5b6442b6df401466af8425 +size 679929 diff --git a/.venv/lib/python3.12/site-packages/av/container/input.pxd b/.venv/lib/python3.12/site-packages/av/container/input.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2e65025b9f0df813ecaca624b6785954a7d1a47a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/input.pxd @@ -0,0 +1,8 @@ +cimport libav as lib + +from av.container.core cimport Container +from av.stream cimport Stream + + +cdef class InputContainer(Container): + cdef flush_buffers(self) diff --git a/.venv/lib/python3.12/site-packages/av/container/input.py b/.venv/lib/python3.12/site-packages/av/container/input.py new file mode 100644 index 0000000000000000000000000000000000000000..2e26ef3e548fbfb7e370b4885dc5c3f14d1665b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/input.py @@ -0,0 +1,331 @@ +import cython +from cython.cimports.av.codec.context import CodecContext, wrap_codec_context +from cython.cimports.av.container.streams import StreamContainer +from cython.cimports.av.dictionary import Dictionary +from cython.cimports.av.error import err_check +from cython.cimports.av.packet import Packet +from cython.cimports.av.stream import Stream, wrap_stream +from cython.cimports.av.utils import avdict_to_dict +from cython.cimports.libc.stdint import int64_t, uint8_t +from cython.cimports.libc.stdlib import free, malloc + + +@cython.cfunc +def close_input(self: InputContainer): + self.streams = StreamContainer() + with cython.nogil: + if self._myflag & 2: + # This causes `self.ptr` to be set to NULL. + lib.avformat_close_input(cython.address(self.ptr)) + self._myflag &= ~2 # enum.input_was_opened = False + + +@cython.final +@cython.cclass +class InputContainer(Container): + def __cinit__(self, *args, **kwargs): + py_codec_context: CodecContext + i: cython.uint + stream: cython.pointer[lib.AVStream] + codec: cython.pointer[cython.const[lib.AVCodec]] + codec_context: cython.pointer[lib.AVCodecContext] + + # If we have either the global `options`, or a `stream_options`, prepare + # a mashup of those options for each stream. + c_options: cython.pointer[cython.pointer[lib.AVDictionary]] = cython.NULL + base_dict: Dictionary + stream_dict: Dictionary + nb_streams_before: cython.uint = self.ptr.nb_streams + if self.stream_options and nb_streams_before == 0: + raise ValueError( + "stream_options were provided, but this format does not expose " + "its streams before avformat_find_stream_info (e.g. MPEG). " + "Per-stream options cannot be applied." + ) + # Only allocate c_options when streams are already known. + if (self.options or self.stream_options) and nb_streams_before > 0: + base_dict = Dictionary(self.options) + c_options = cython.cast( + cython.pointer[cython.pointer[lib.AVDictionary]], + malloc(nb_streams_before * cython.sizeof(cython.p_void)), + ) + for i in range(nb_streams_before): + c_options[i] = cython.NULL + if i < len(self.stream_options) and self.stream_options: + stream_dict = base_dict.copy() + stream_dict.update(self.stream_options[i]) + lib.av_dict_copy(cython.address(c_options[i]), stream_dict.ptr, 0) + else: + lib.av_dict_copy(cython.address(c_options[i]), base_dict.ptr, 0) + + self.set_timeout(self.open_timeout) + self.start_timeout() + with cython.nogil: + ret = lib.avformat_find_stream_info(self.ptr, c_options) + self.set_timeout(None) + self.err_check(ret) + + if c_options: + for i in range(nb_streams_before): + lib.av_dict_free(cython.address(c_options[i])) + free(c_options) + + at_least_one_accelerated_context = False + + self.streams = StreamContainer() + for i in range(self.ptr.nb_streams): + stream = self.ptr.streams[i] + codec = lib.avcodec_find_decoder(stream.codecpar.codec_id) + if codec: + codec_context = lib.avcodec_alloc_context3(codec) + err_check( + lib.avcodec_parameters_to_context(codec_context, stream.codecpar) + ) + codec_context.pkt_timebase = stream.time_base + py_codec_context = wrap_codec_context( + codec_context, codec, self.hwaccel + ) + if py_codec_context.is_hwaccel: + at_least_one_accelerated_context = True + else: + # no decoder is available + py_codec_context = None + self.streams.add_stream(wrap_stream(self, stream, py_codec_context)) + + if ( + self.hwaccel + and not self.hwaccel.allow_software_fallback + and not at_least_one_accelerated_context + ): + raise RuntimeError( + "Hardware accelerated decode requested but no stream is compatible" + ) + + self._metadata = avdict_to_dict( + self.ptr.metadata, self.metadata_encoding, self.metadata_errors + ) + + def __dealloc__(self): + close_input(self) + + @property + def start_time(self): + self._assert_open() + if self.ptr.start_time != lib.AV_NOPTS_VALUE: + return self.ptr.start_time + + @property + def start_time_realtime(self): + """Start time of the stream in real world time, in microseconds since the + Unix epoch, or ``None`` if unknown. + + Only a few demuxers know this; RTSP computes it from RTCP sender reports, + which is what makes it useful for aligning analytics with a camera's clock. + + Wraps :ffmpeg:`AVFormatContext.start_time_realtime`. + """ + self._assert_open() + if self.ptr.start_time_realtime != lib.AV_NOPTS_VALUE: + return self.ptr.start_time_realtime + + @property + def duration(self): + self._assert_open() + if self.ptr.duration != lib.AV_NOPTS_VALUE: + return self.ptr.duration + + @property + def bit_rate(self): + self._assert_open() + return self.ptr.bit_rate + + @property + def size(self): + self._assert_open() + return lib.avio_size(self.ptr.pb) + + def close(self): + close_input(self) + + def demux(self, *args, **kwargs): + """demux(streams=None, video=None, audio=None, subtitles=None, data=None) + + Yields a series of :class:`.Packet` from the given set of :class:`.Stream`:: + + for packet in container.demux(): + # Do something with `packet`, often: + for frame in packet.decode(): + # Do something with `frame`. + + .. seealso:: :meth:`.StreamContainer.get` for the interpretation of + the arguments. + + .. note:: The last packets are dummy packets that when decoded will flush the buffers. + + """ + self._assert_open() + + streams: list[Stream] = self.streams.get(*args, **kwargs) + if self.ptr.nb_streams == 0: + return + include_stream: cython.pointer[uint8_t] = cython.cast( + cython.pointer[uint8_t], + malloc(self.ptr.nb_streams * cython.sizeof(uint8_t)), + ) + if include_stream == cython.NULL: + raise MemoryError() + + i: cython.uint + packet: Packet + read_packet: cython.pointer[lib.AVPacket] + ret: cython.int + + self.set_timeout(self.read_timeout) + try: + for i in range(self.ptr.nb_streams): + include_stream[i] = 0 + for stream in streams: + i = stream.index + if i >= self.ptr.nb_streams: + raise ValueError(f"stream index {i} out of range") + include_stream[i] = 1 + + # Pre-allocate a AVPacket that is reused as the read buffer. + with cython.nogil: + read_packet = lib.av_packet_alloc() + if read_packet == cython.NULL: + raise MemoryError("Could not allocate packet") + + while True: + # Reset the read buffer + with cython.nogil: + lib.av_packet_unref(read_packet) + try: + self.start_timeout() + with cython.nogil: + ret = lib.av_read_frame(self.ptr, read_packet) + self.err_check(ret) + except EOFError: + break + + if include_stream[read_packet.stream_index]: + # If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams + # may also appear in av_read_frame(). + # http://ffmpeg.org/doxygen/trunk/structAVFormatContext.html + # TODO: find better way to handle this + if read_packet.stream_index < len(self.streams): + # Move the encoded data out of the read buffer into a + # fresh Packet for the caller. + packet = Packet() + with cython.nogil: + lib.av_packet_move_ref(packet.ptr, read_packet) + packet._stream = self.streams[packet.ptr.stream_index] + # Keep track of this so that remuxing is easier. + packet.ptr.time_base = packet._stream.ptr.time_base + yield packet + + # Flush! + for i in range(self.ptr.nb_streams): + if include_stream[i]: + packet = Packet() + packet._stream = self.streams[i] + packet.ptr.time_base = packet._stream.ptr.time_base + yield packet + + finally: + self.set_timeout(None) + free(include_stream) + if read_packet != cython.NULL: + lib.av_packet_free(cython.address(read_packet)) + + def decode(self, *args, **kwargs): + """decode(streams=None, video=None, audio=None, subtitles=None, data=None) + + Yields a series of :class:`.Frame` from the given set of streams:: + + for frame in container.decode(): + # Do something with `frame`. + + .. seealso:: :meth:`.StreamContainer.get` for the interpretation of + the arguments. + + """ + self._assert_open() + for packet in self.demux(*args, **kwargs): + yield from packet.decode() + + def seek( + self, + offset, + *, + backward: cython.bint = True, + any_frame: cython.bint = False, + stream: Stream | None = None, + unsupported_frame_offset: cython.bint = False, + unsupported_byte_offset: cython.bint = False, + ): + """seek(offset, *, backward=True, any_frame=False, stream=None) + + Seek to a (key)frame nearest to the given timestamp. + + :param int offset: Time to seek to, expressed in``stream.time_base`` if ``stream`` + is given, otherwise in :data:`av.time_base`. + :param bool backward: If there is not a (key)frame at the given offset, + look backwards for it. + :param bool any_frame: Seek to any frame, not just a keyframe. + :param Stream stream: The stream who's ``time_base`` the ``offset`` is in. + + :param bool unsupported_frame_offset: ``offset`` is a frame + index instead of a time; not supported by any known format. + :param bool unsupported_byte_offset: ``offset`` is a byte + location in the file; not supported by any known format. + + After seeking, packets that you demux should correspond (roughly) to + the position you requested. + + In most cases, the defaults of ``backwards = True`` and ``any_frame = False`` + are the best course of action, followed by you demuxing/decoding to + the position that you want. This is because to properly decode video frames + you need to start from the previous keyframe. + + .. seealso:: :ffmpeg:`avformat_seek_file` for discussion of the flags. + + """ + self._assert_open() + + if not isinstance(offset, int): + raise TypeError("Container.seek only accepts integer offset.", type(offset)) + + c_offset: int64_t = offset + flags: cython.int = 0 + ret: cython.int + + if backward: + flags |= lib.AVSEEK_FLAG_BACKWARD + if any_frame: + flags |= lib.AVSEEK_FLAG_ANY + + # If someone really wants (and to experiment), expose these. + if unsupported_frame_offset: + flags |= lib.AVSEEK_FLAG_FRAME + if unsupported_byte_offset: + flags |= lib.AVSEEK_FLAG_BYTE + + stream_index: cython.int = stream.index if stream else -1 + with cython.nogil: + ret = lib.av_seek_frame(self.ptr, stream_index, c_offset, flags) + err_check(ret) + + self.flush_buffers() + + @cython.cfunc + def flush_buffers(self): + self._assert_open() + + stream: Stream + codec_context: CodecContext + + for stream in self.streams: + codec_context = stream.codec_context + if codec_context: + codec_context.flush_buffers() diff --git a/.venv/lib/python3.12/site-packages/av/container/input.pyi b/.venv/lib/python3.12/site-packages/av/container/input.pyi new file mode 100644 index 0000000000000000000000000000000000000000..caea60b945bcf3a444f2720153d00250caaa2924 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/input.pyi @@ -0,0 +1,90 @@ +from collections.abc import Iterator +from typing import Any, overload + +from av.audio.frame import AudioFrame +from av.audio.stream import AudioStream +from av.packet import Packet +from av.stream import AttachmentStream, DataStream, Stream +from av.subtitles.stream import SubtitleStream +from av.subtitles.subtitle import SubtitleSet +from av.video.frame import VideoFrame +from av.video.stream import VideoStream + +from .core import Container + +class InputContainer(Container): + start_time: int + start_time_realtime: int | None + duration: int | None + bit_rate: int + size: int + + @overload + def demux(self, video_stream: VideoStream) -> Iterator[Packet[VideoStream]]: ... + @overload + def demux( + self, video_streams: tuple[VideoStream, ...] + ) -> Iterator[Packet[VideoStream]]: ... + @overload + def demux(self, *, video: Any) -> Iterator[Packet[VideoStream]]: ... + @overload + def demux(self, audio_stream: AudioStream) -> Iterator[Packet[AudioStream]]: ... + @overload + def demux( + self, audio_streams: tuple[AudioStream, ...] + ) -> Iterator[Packet[AudioStream]]: ... + @overload + def demux(self, *, audio: Any) -> Iterator[Packet[AudioStream]]: ... + @overload + def demux( + self, subtitle_stream: SubtitleStream + ) -> Iterator[Packet[SubtitleStream]]: ... + @overload + def demux( + self, subtitle_streams: tuple[SubtitleStream, ...] + ) -> Iterator[Packet[SubtitleStream]]: ... + @overload + def demux(self, data_stream: DataStream) -> Iterator[Packet[DataStream]]: ... + @overload + def demux( + self, data_streams: tuple[DataStream, ...] + ) -> Iterator[Packet[DataStream]]: ... + @overload + def demux(self, *, data: Any) -> Iterator[Packet[DataStream]]: ... + @overload + def demux( + self, attachment_stream: AttachmentStream + ) -> Iterator[Packet[AttachmentStream]]: ... + @overload + def demux( + self, attachment_streams: tuple[AttachmentStream, ...] + ) -> Iterator[Packet[AttachmentStream]]: ... + @overload + def demux(self, *args: Any, **kwargs: Any) -> Iterator[Packet[Stream]]: ... + @overload + def decode(self, video: int) -> Iterator[VideoFrame]: ... + @overload + def decode(self, audio: int) -> Iterator[AudioFrame]: ... + @overload + def decode(self, subtitles: int) -> Iterator[SubtitleSet]: ... + @overload + def decode(self, *args: VideoStream) -> Iterator[VideoFrame]: ... + @overload + def decode(self, *args: AudioStream) -> Iterator[AudioFrame]: ... + @overload + def decode(self, *args: SubtitleStream) -> Iterator[SubtitleSet]: ... + @overload + def decode( + self, *args: Any, **kwargs: Any + ) -> Iterator[VideoFrame | AudioFrame | SubtitleSet]: ... + def seek( + self, + offset: int, + *, + backward: bool = True, + any_frame: bool = False, + stream: Stream | VideoStream | AudioStream | None = None, + unsupported_frame_offset: bool = False, + unsupported_byte_offset: bool = False, + ) -> None: ... + def flush_buffers(self) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/container/output.abi3.so b/.venv/lib/python3.12/site-packages/av/container/output.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..1aaa19b3b08d12b3e85d7206df010db6eabf5a13 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/output.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b00ba4cb0783c7821f8b99b5771470c4a2e9485d276825179f994634ee54ea3f +size 1118497 diff --git a/.venv/lib/python3.12/site-packages/av/container/output.pxd b/.venv/lib/python3.12/site-packages/av/container/output.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2ef93206f0b660ea5de4e7112ef91f2a0f024365 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/output.pxd @@ -0,0 +1,15 @@ +cimport libav as lib + +from av.container.core cimport Container +from av.packet cimport Packet +from av.stream cimport Stream + + +cdef class OutputContainer(Container): + cdef lib.AVPacket *packet_ptr + cdef dict _extradata_bsfs + cdef list _buffered_packets + cdef _mux_one(self, Packet packet) + cdef _buffer_for_extradata(self, Packet packet) + cdef _try_extract_extradata(self, Packet packet) + cpdef start_encoding(self) diff --git a/.venv/lib/python3.12/site-packages/av/container/output.py b/.venv/lib/python3.12/site-packages/av/container/output.py new file mode 100644 index 0000000000000000000000000000000000000000..a33dadd61b9cda095b703ba4c9080c5c5be617a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/output.py @@ -0,0 +1,718 @@ +import os + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.bitstream import BitStreamFilterContext +from cython.cimports.av.codec.codec import Codec +from cython.cimports.av.codec.context import CodecContext, wrap_codec_context +from cython.cimports.av.codec.hwaccel import HWAccel +from cython.cimports.av.container.streams import StreamContainer +from cython.cimports.av.dictionary import Dictionary +from cython.cimports.av.error import err_check +from cython.cimports.av.packet import Packet +from cython.cimports.av.stream import Stream, wrap_stream +from cython.cimports.av.utils import dict_to_avdict, to_avrational +from cython.cimports.libc.stdint import uint8_t +from cython.cimports.libc.string import memcpy, memset + + +@cython.cfunc +def _set_codecpar_extradata( + stream: cython.pointer[lib.AVStream], + data: cython.pointer[uint8_t], + size: cython.int, +): + buf: cython.p_uchar = cython.cast( + cython.p_uchar, lib.av_malloc(size + lib.AV_INPUT_BUFFER_PADDING_SIZE) + ) + if buf == cython.NULL: + raise MemoryError("Could not allocate extradata") + + memcpy(buf, data, size) + memset(buf + size, 0, lib.AV_INPUT_BUFFER_PADDING_SIZE) + + lib.av_freep(cython.address(stream.codecpar.extradata)) + stream.codecpar.extradata = buf + stream.codecpar.extradata_size = size + + +@cython.cfunc +def close_output(self: OutputContainer): + if self.packet_ptr != cython.NULL and self._buffered_packets: + buffered: list = self._buffered_packets + self._buffered_packets = [] + packet: Packet + for packet in buffered: + self._mux_one(packet) + + self.streams = StreamContainer() + if self._myflag & 12 == 4: # enum.started and not enum.done + # If the underlying Python IO file was already closed (e.g. during GC + # finalization where cycle ordering is undefined), skip the trailer. + if self.file is not None and getattr(self.file.file, "closed", False): + self._myflag |= 8 # enum.done = True + return + # We must only ever call av_write_trailer *once*, otherwise we get a + # segmentation fault. Therefore no matter whether it succeeds or not + # we must absolutely set enum.done. + try: + self.err_check(lib.av_write_trailer(self.ptr)) + finally: + if self.file is None and not (self.ptr.oformat.flags & lib.AVFMT_NOFILE): + lib.avio_closep(cython.address(self.ptr.pb)) + self._myflag |= 8 # enum.done = True + + +@cython.final +@cython.cclass +class OutputContainer(Container): + def __cinit__(self, *args, **kwargs): + self.streams = StreamContainer() + self._extradata_bsfs = {} + self._buffered_packets = [] + with cython.nogil: + self.packet_ptr = lib.av_packet_alloc() + + def __del__(self): + close_output(self) + + def __dealloc__(self): + with cython.nogil: + lib.av_packet_free(cython.address(self.packet_ptr)) + + def add_stream( + self, + codec_name, + rate=None, + options: dict | None = None, + hwaccel: HWAccel | None = None, + **kwargs, + ): + """add_stream(codec_name, rate=None, *, hwaccel=None) + + Creates a new stream from a codec name and returns it. + Supports video, audio, and subtitle streams. + + :param codec_name: The name of a codec. + :type codec_name: str + :param dict options: Stream options. + :param HWAccel hwaccel: Optional settings for hardware-accelerated encoding. + Only applies to video streams (e.g. ``h264_vaapi``); software frames + passed to :meth:`~av.codec.context.CodecContext.encode` are uploaded to + the device automatically. + :param \\**kwargs: Set attributes for the stream. + :rtype: The new :class:`~av.stream.Stream`. + + .. warning:: + + Configure every output stream before muxing the first packet. Writing + the file header opens all stream codec contexts, after which structural + properties such as format, dimensions, layout, and rate cannot change. + + """ + + codec_obj: Codec = Codec(codec_name, "w") + codec: cython.pointer[cython.const[lib.AVCodec]] = codec_obj.ptr + + # Assert that this format supports the requested codec. + if not lib.avformat_query_codec( + self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL + ): + raise ValueError( + f"{self.format.name!r} format does not support {codec_obj.name!r} codec" + ) + + # Create new stream in the AVFormatContext, set AVCodecContext values. + stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec) + ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3(codec) + + # Now lets set some more sane video defaults + if codec.type == lib.AVMEDIA_TYPE_VIDEO: + ctx.pix_fmt = lib.AV_PIX_FMT_YUV420P + ctx.width = kwargs.pop("width", 640) + ctx.height = kwargs.pop("height", 480) + ctx.bit_rate = kwargs.pop("bit_rate", 0) + ctx.bit_rate_tolerance = kwargs.pop("bit_rate_tolerance", 128000) + try: + to_avrational(kwargs.pop("time_base"), cython.address(ctx.time_base)) + except KeyError: + pass + to_avrational(rate or 24, cython.address(ctx.framerate)) + + stream.avg_frame_rate = ctx.framerate + stream.time_base = ctx.time_base + + # Some sane audio defaults + elif codec.type == lib.AVMEDIA_TYPE_AUDIO: + out: cython.pointer[cython.const[cython.void]] = cython.NULL + lib.avcodec_get_supported_config( + cython.NULL, + codec, + lib.AV_CODEC_CONFIG_SAMPLE_FORMAT, + 0, + cython.address(out), + cython.NULL, + ) + if out: + ctx.sample_fmt = cython.cast(cython.pointer[lib.AVSampleFormat], out)[0] + ctx.bit_rate = kwargs.pop("bit_rate", 0) + ctx.bit_rate_tolerance = kwargs.pop("bit_rate_tolerance", 32000) + try: + to_avrational(kwargs.pop("time_base"), cython.address(ctx.time_base)) + except KeyError: + pass + + if rate is None: + ctx.sample_rate = 48000 + elif type(rate) is int: + ctx.sample_rate = rate + else: + raise TypeError("audio stream `rate` must be: int | None") + stream.time_base = ctx.time_base + lib.av_channel_layout_default(cython.address(ctx.ch_layout), 2) + + # Some formats want stream headers to be separate + if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER: + ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER + + # Initialise stream codec parameters to populate the codec type. + # + # Subsequent changes to the codec context will be applied just before + # encoding starts in `start_encoding()`. + err_check(lib.avcodec_parameters_from_context(stream.codecpar, ctx)) + + # Construct the user-land stream + py_codec_context: CodecContext = wrap_codec_context(ctx, codec, hwaccel) + py_stream: Stream = wrap_stream(self, stream, py_codec_context) + self.streams.add_stream(py_stream) + + if options: + py_stream.options.update(options) + + for k, v in kwargs.items(): + setattr(py_stream, k, v) + + return py_stream + + def add_mux_stream(self, codec_name: str, rate=None, **kwargs) -> Stream: + """add_mux_stream(codec_name, rate=None) + + Creates a new stream for muxing pre-encoded data without creating a + :class:`.CodecContext`. Use this when you want to mux packets that were + already encoded externally and no encoding/decoding is needed. + + :param codec_name: The name of a codec. + :type codec_name: str + :param \\**kwargs: Set attributes for the stream (e.g. ``width``, ``height``, + ``time_base``). + :rtype: The new :class:`~av.stream.Stream`. + + """ + # Find the codec to get its id and type (try encoder first, then decoder). + codec_name_bytes: bytes = codec_name.encode() + codec: cython.pointer[cython.const[lib.AVCodec]] = ( + lib.avcodec_find_encoder_by_name(codec_name_bytes) + ) + codec_descriptor: cython.pointer[cython.const[lib.AVCodecDescriptor]] = ( + cython.NULL + ) + if codec == cython.NULL: + codec = lib.avcodec_find_decoder_by_name(codec_name_bytes) + if codec == cython.NULL: + codec_descriptor = lib.avcodec_descriptor_get_by_name(codec_name_bytes) + if codec_descriptor == cython.NULL: + raise ValueError(f"Unknown codec: {codec_name!r}") + + codec_id: lib.AVCodecID + codec_type: lib.AVMediaType + if codec != cython.NULL: + codec_id = codec.id + codec_type = codec.type + else: + codec_id = codec_descriptor.id + codec_type = codec_descriptor.type + + # Assert that this format supports the requested codec. + if not lib.avformat_query_codec( + self.ptr.oformat, codec_id, lib.FF_COMPLIANCE_NORMAL + ): + raise ValueError( + f"{self.format.name!r} format does not support {codec_name!r} codec" + ) + + # Create stream with no codec context. + stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream( + self.ptr, cython.NULL + ) + if stream == cython.NULL: + raise MemoryError("Could not allocate stream") + + stream.codecpar.codec_id = codec_id + stream.codecpar.codec_type = codec_type + + if codec_type == lib.AVMEDIA_TYPE_VIDEO: + stream.codecpar.width = kwargs.pop("width", 0) + stream.codecpar.height = kwargs.pop("height", 0) + if rate is not None: + to_avrational(rate, cython.address(stream.avg_frame_rate)) + elif codec_type == lib.AVMEDIA_TYPE_AUDIO: + if rate is not None: + if type(rate) is int: + stream.codecpar.sample_rate = rate + else: + raise TypeError("audio stream `rate` must be: int | None") + + # Construct the user-land stream (no codec context). + py_stream: Stream = wrap_stream(self, stream, None) + self.streams.add_stream(py_stream) + + for k, v in kwargs.items(): + setattr(py_stream, k, v) + + return py_stream + + def add_stream_from_template( + self, template: Stream, opaque: bool | None = None, **kwargs + ): + """ + Creates a new stream from a template. Supports video, audio, subtitle, data and attachment streams. + + :param template: Copy codec from another :class:`~av.stream.Stream` instance. + :param opaque: If True, copy opaque data from the template's codec context. + :param \\**kwargs: Set attributes for the stream. + :rtype: The new :class:`~av.stream.Stream`. + """ + if opaque is None: + opaque = template.type != "video" + + if template.codec_context is None: + return self._add_stream_without_codec_from_template(template, **kwargs) + + codec_obj: Codec + if opaque: # Copy ctx from template. + codec_obj = template.codec_context.codec + else: # Construct new codec object. + codec_obj = Codec(template.codec_context.codec.name, "w") + + codec: cython.pointer[cython.const[lib.AVCodec]] = codec_obj.ptr + + # Assert that this format supports the requested codec. + if not lib.avformat_query_codec( + self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL + ): + raise ValueError( + f"{self.format.name!r} format does not support {codec_obj.name!r} codec" + ) + + # Create new stream in the AVFormatContext, set AVCodecContext values. + stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec) + ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3(codec) + + err_check(lib.avcodec_parameters_to_context(ctx, template.ptr.codecpar)) + # Reset the codec tag assuming we are remuxing. + ctx.codec_tag = 0 + + # Copy the template's stream time_base + stream.time_base = template.ptr.time_base + ctx.time_base = template.ptr.time_base + + # Some formats want stream headers to be separate + if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER: + ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER + + # Copy flags If we're creating a new codec object. This fixes some muxing issues. + # Overwriting `ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER` is intentional. + if not opaque: + ctx.flags = template.codec_context.flags + + # Initialize stream codec parameters to populate the codec type. Subsequent changes to + # the codec context will be applied just before encoding starts in `start_encoding()`. + err_check(lib.avcodec_parameters_from_context(stream.codecpar, ctx)) + + # Construct the user-land stream + py_codec_context: CodecContext = wrap_codec_context(ctx, codec, None) + py_codec_context._ctxflags |= 1 # _template_initialized = True + py_stream: Stream = wrap_stream(self, stream, py_codec_context) + self.streams.add_stream(py_stream) + + for k, v in kwargs.items(): + setattr(py_stream, k, v) + + return py_stream + + def _add_stream_without_codec_from_template( + self, template: Stream, **kwargs + ) -> Stream: + codec_type: cython.int = template.ptr.codecpar.codec_type + if codec_type not in {lib.AVMEDIA_TYPE_ATTACHMENT, lib.AVMEDIA_TYPE_DATA}: + raise ValueError( + f"template stream of type {template.type} has no codec context" + ) + + stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream( + self.ptr, cython.NULL + ) + if stream == cython.NULL: + raise MemoryError("Could not allocate stream") + + err_check(lib.avcodec_parameters_copy(stream.codecpar, template.ptr.codecpar)) + + # Mirror basic properties that are not derived from a codec context. + stream.time_base = template.ptr.time_base + stream.start_time = template.ptr.start_time + stream.duration = template.ptr.duration + stream.disposition = template.ptr.disposition + + py_stream: Stream = wrap_stream(self, stream, None) + self.streams.add_stream(py_stream) + + py_stream.metadata = dict(template.metadata) + + for k, v in kwargs.items(): + setattr(py_stream, k, v) + + return py_stream + + def add_attachment(self, name: str, mimetype: str, data: bytes): + """ + Create an attachment stream and embed its payload into the container header. + + - Only supported by formats that support attachments (e.g. Matroska). + - No per-packet muxing is required; attachments are written at header time. + """ + # Create stream with no codec (attachments are codec-less). + stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream( + self.ptr, cython.NULL + ) + if stream == cython.NULL: + raise MemoryError("Could not allocate stream") + + stream.codecpar.codec_type = lib.AVMEDIA_TYPE_ATTACHMENT + stream.codecpar.codec_id = lib.AV_CODEC_ID_NONE + + # Allocate and copy payload into codecpar.extradata. + payload_size: cython.size_t = len(data) + if payload_size: + buf = cython.cast(cython.p_uchar, lib.av_malloc(payload_size + 1)) + if buf == cython.NULL: + raise MemoryError("Could not allocate attachment data") + # Copy bytes. + for i in range(payload_size): + buf[i] = data[i] + buf[payload_size] = 0 + stream.codecpar.extradata = cython.cast(cython.p_uchar, buf) + stream.codecpar.extradata_size = cython.cast(cython.int, payload_size) + + # Wrap as user-land stream. + meta_ptr = cython.address(stream.metadata) + err_check(lib.av_dict_set(meta_ptr, b"filename", name.encode(), 0)) + mime_bytes = mimetype.encode() + err_check(lib.av_dict_set(meta_ptr, b"mimetype", mime_bytes, 0)) + + py_stream: Stream = wrap_stream(self, stream, None) + self.streams.add_stream(py_stream) + return py_stream + + def add_data_stream(self, codec_name=None, options: dict | None = None): + """add_data_stream(codec_name=None) + + Creates a new data stream and returns it. + + :param codec_name: Optional name of the data codec (e.g. 'klv') + :type codec_name: str | None + :param dict options: Stream options. + :rtype: The new :class:`~av.data.stream.DataStream`. + """ + codec: cython.pointer[cython.const[lib.AVCodec]] = cython.NULL + codec_descriptor: cython.pointer[cython.const[lib.AVCodecDescriptor]] = ( + cython.NULL + ) + + if codec_name is not None: + codec_name_bytes: bytes = codec_name.encode() + codec = lib.avcodec_find_encoder_by_name(codec_name_bytes) + if codec == cython.NULL: + codec = lib.avcodec_find_decoder_by_name(codec_name_bytes) + if codec == cython.NULL: + codec_descriptor = lib.avcodec_descriptor_get_by_name(codec_name_bytes) + if codec_descriptor == cython.NULL: + raise ValueError(f"Unknown data codec: {codec_name}") + + # Verify format supports this codec + codec_id = codec.id if codec != cython.NULL else codec_descriptor.id + if not lib.avformat_query_codec( + self.ptr.oformat, codec_id, lib.FF_COMPLIANCE_NORMAL + ): + raise ValueError( + f"{self.format.name!r} format does not support {codec_name!r} codec" + ) + + # Create new stream in the AVFormatContext + stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec) + if stream == cython.NULL: + raise MemoryError("Could not allocate stream") + + # Set up codec context and parameters + ctx: cython.pointer[lib.AVCodecContext] = cython.NULL + if codec != cython.NULL: + ctx = lib.avcodec_alloc_context3(codec) + if ctx == cython.NULL: + raise MemoryError("Could not allocate codec context") + + # Some formats want stream headers to be separate + if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER: + ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER + + # Initialize stream codec parameters + err_check(lib.avcodec_parameters_from_context(stream.codecpar, ctx)) + else: + # No codec available - set basic parameters for data stream + stream.codecpar.codec_type = lib.AVMEDIA_TYPE_DATA + if codec_descriptor != cython.NULL: + stream.codecpar.codec_id = codec_descriptor.id + + # Construct the user-land stream + py_codec_context: CodecContext | None = None + if ctx != cython.NULL: + py_codec_context = wrap_codec_context(ctx, codec, None) + + py_stream: Stream = wrap_stream(self, stream, py_codec_context) + self.streams.add_stream(py_stream) + + if options: + py_stream.options.update(options) + + return py_stream + + @cython.ccall + def start_encoding(self): + """Write the file header! Called automatically.""" + if self._myflag & 4: # started + return + + # TODO: This does NOT handle options coming from 3 sources. + # This is only a rough approximation of what would be cool to do. + used_options: set = set() + stream: Stream + + # Finalize and open all streams. + for stream in self.streams: + ctx = stream.codec_context + if ctx is not None and not ctx.is_open: + for k, v in self.options.items(): + ctx.options.setdefault(k, v) + + if not (ctx._ctxflags & 1): # template_initialized + ctx.open() + + # Track option consumption. + for k in self.options: + if k not in ctx.options: + used_options.add(k) + + stream._finalize_for_output() + + # Open the output file, if needed. + name_obj: bytes = os.fsencode(self.name if self.file is None else "") + name: cython.p_char = name_obj + if self.ptr.pb == cython.NULL and not self.ptr.oformat.flags & lib.AVFMT_NOFILE: + err_check( + lib.avio_open(cython.address(self.ptr.pb), name, lib.AVIO_FLAG_WRITE) + ) + + # Copy the metadata dict. + dict_to_avdict( + cython.address(self.ptr.metadata), + self.metadata, + encoding=self.metadata_encoding, + errors=self.metadata_errors, + ) + + all_options: Dictionary = Dictionary(self.options, self.container_options) + options: Dictionary = all_options.copy() + self.err_check(lib.avformat_write_header(self.ptr, cython.address(options.ptr))) + + # Track option usage... + for k in all_options: + if k not in options: + used_options.add(k) + + # ... and warn if any weren't used. + unused_options = { + k: v for k, v in self.options.items() if k not in used_options + } + if unused_options: + import logging + + log = logging.getLogger(__name__) + log.warning(f"Some options were not used: {unused_options}") + + self._myflag |= 4 + + @property + def supported_codecs(self): + """ + Returns a set of all codecs this format supports. + """ + result: set = set() + codec: cython.pointer[cython.const[lib.AVCodec]] = cython.NULL + opaque: cython.p_void = cython.NULL + + while True: + codec = lib.av_codec_iterate(cython.address(opaque)) + if codec == cython.NULL: + break + + if ( + lib.avformat_query_codec( + self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL + ) + == 1 + ): + result.add(codec.name) + + return result + + @property + def default_video_codec(self): + """ + Returns the default video codec this container recommends. + """ + return lib.avcodec_get_name(self.format.optr.video_codec) + + @property + def default_audio_codec(self): + """ + Returns the default audio codec this container recommends. + """ + return lib.avcodec_get_name(self.format.optr.audio_codec) + + @property + def default_subtitle_codec(self): + """ + Returns the default subtitle codec this container recommends. + """ + return lib.avcodec_get_name(self.format.optr.subtitle_codec) + + def close(self): + close_output(self) + + def mux(self, packets): + # We accept either a Packet, or a sequence of packets. This should smooth out + # the transition to the new encode API which returns a sequence of packets. + if isinstance(packets, Packet): + self.mux_one(packets) + else: + for packet in packets: + self.mux_one(packet) + + def mux_one(self, packet: Packet): + if not (self._myflag & 4) and self._buffer_for_extradata(packet): + return + + self._mux_one(packet) + + @cython.cfunc + def _mux_one(self, packet: Packet): + self.start_encoding() + + # Assert the packet is in stream time. + if ( + packet.ptr.stream_index < 0 + or cython.cast(cython.uint, packet.ptr.stream_index) >= self.ptr.nb_streams + ): + raise ValueError("Bad Packet stream_index.") + + stream: cython.pointer[lib.AVStream] = self.ptr.streams[packet.ptr.stream_index] + packet._rebase_time(stream.time_base) + + # Make another reference to the packet, as `av_interleaved_write_frame()` + # takes ownership of the reference. + self.err_check(lib.av_packet_ref(self.packet_ptr, packet.ptr)) + + with cython.nogil: + ret: cython.int = lib.av_interleaved_write_frame(self.ptr, self.packet_ptr) + self.err_check(ret) + + @cython.cfunc + def _buffer_for_extradata(self, packet: Packet): + """Buffer ``packet`` until extradata is known for all mux streams that + need it. Returns True if the packet was buffered (caller should stop).""" + if not (self._myflag & 16): # extradata_planned + self._myflag |= 16 + if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER: + stream: Stream + for stream in self.streams: + if ( + stream.codec_context is not None + or stream.ptr.codecpar.extradata != cython.NULL + ): + continue + try: + bsf = BitStreamFilterContext( + "extract_extradata", in_stream=stream + ) + except Exception: + continue # Codec does not support extradata extraction. + self._extradata_bsfs[stream.ptr.index] = bsf + + if not self._extradata_bsfs: + return False # Nothing to wait for; mux normally. + + self._try_extract_extradata(packet) + self._buffered_packets.append(packet) + if self._extradata_bsfs: + return True # Still waiting on some stream's extradata. + + # All extradata is resolved: write the header and flush buffered packets. + buffered: list = self._buffered_packets + self._buffered_packets = [] + buffered_packet: Packet + for buffered_packet in buffered: + self._mux_one(buffered_packet) + return True + + @cython.cfunc + def _try_extract_extradata(self, packet: Packet): + idx: cython.int = packet.ptr.stream_index + if idx not in self._extradata_bsfs: + return + + bsf_wrapper: BitStreamFilterContext = self._extradata_bsfs[idx] + bsf: cython.pointer[lib.AVBSFContext] = bsf_wrapper.ptr + + tmp: cython.pointer[lib.AVPacket] = lib.av_packet_alloc() + if tmp == cython.NULL: + raise MemoryError("Could not allocate packet") + + size: cython.size_t = 0 + sd: cython.pointer[uint8_t] + try: + # Clone the packet so the filter does not consume the caller's data. + if lib.av_packet_ref(tmp, packet.ptr) < 0: + return + + if lib.av_bsf_send_packet(bsf, tmp) < 0: + lib.av_packet_unref(tmp) # send failed; we still own the ref + return + + # The filter rejects packets that are already length-prefixed rather + # than annex-b, returning an error here; treat that and EOF/EAGAIN + # alike as "no in-band extradata". + while lib.av_bsf_receive_packet(bsf, tmp) == 0: + sd = lib.av_packet_get_side_data( + tmp, lib.AV_PKT_DATA_NEW_EXTRADATA, cython.address(size) + ) + if sd != cython.NULL and size > 0: + _set_codecpar_extradata( + self.ptr.streams[idx], sd, cython.cast(cython.int, size) + ) + lib.av_packet_unref(tmp) + break + lib.av_packet_unref(tmp) + finally: + lib.av_packet_free(cython.address(tmp)) + # A stream's first packet is the only reliable place to find in-band + # parameter sets, so stop waiting on this stream regardless of the + # result, falling back to the muxer's default behavior. + del self._extradata_bsfs[idx] diff --git a/.venv/lib/python3.12/site-packages/av/container/output.pyi b/.venv/lib/python3.12/site-packages/av/container/output.pyi new file mode 100644 index 0000000000000000000000000000000000000000..961e7ad2dfb6c7ecf98afb412d4df06ca16f48eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/output.pyi @@ -0,0 +1,79 @@ +from collections.abc import Sequence +from fractions import Fraction +from typing import TypeVar, overload + +from av.audio import _AudioCodecName +from av.audio.stream import AudioStream +from av.codec.hwaccel import HWAccel +from av.packet import Packet +from av.stream import AttachmentStream, DataStream, Stream +from av.subtitles import _SubtitleCodecName +from av.subtitles.stream import SubtitleStream +from av.video import _VideoCodecName +from av.video.stream import VideoStream + +from .core import Container + +_StreamT = TypeVar("_StreamT", bound=Stream) + +class OutputContainer(Container): + @overload + def add_stream( + self, + codec_name: _AudioCodecName, + rate: int | None = None, + options: dict[str, str] | None = None, + **kwargs, + ) -> AudioStream: ... + @overload + def add_stream( + self, + codec_name: _VideoCodecName, + rate: Fraction | int | None = None, + options: dict[str, str] | None = None, + hwaccel: HWAccel | None = None, + **kwargs, + ) -> VideoStream: ... + @overload + def add_stream( + self, + codec_name: _SubtitleCodecName, + rate: Fraction | int | None = None, + options: dict[str, str] | None = None, + **kwargs, + ) -> SubtitleStream: ... + @overload + def add_stream( + self, + codec_name: str, + rate: Fraction | int | None = None, + options: dict[str, str] | None = None, + hwaccel: HWAccel | None = None, + **kwargs, + ) -> VideoStream | AudioStream | SubtitleStream: ... + def add_mux_stream( + self, + codec_name: str, + rate: Fraction | int | None = None, + **kwargs, + ) -> Stream: ... + def add_stream_from_template( + self, template: _StreamT, opaque: bool | None = None, **kwargs + ) -> _StreamT: ... + def add_attachment( + self, name: str, mimetype: str, data: bytes + ) -> AttachmentStream: ... + def add_data_stream( + self, codec_name: str | None = None, options: dict[str, str] | None = None + ) -> DataStream: ... + def start_encoding(self) -> None: ... + def mux(self, packets: Packet | Sequence[Packet]) -> None: ... + def mux_one(self, packet: Packet) -> None: ... + @property + def default_video_codec(self) -> str: ... + @property + def default_audio_codec(self) -> str: ... + @property + def default_subtitle_codec(self) -> str: ... + @property + def supported_codecs(self) -> set[str]: ... diff --git a/.venv/lib/python3.12/site-packages/av/container/pyio.abi3.so b/.venv/lib/python3.12/site-packages/av/container/pyio.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..2ec54ecb7556d0f1c2eee4b8528731ca3c8db1af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/pyio.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b27d43e3d2e9189850019d0ca4ecb7a5ce75e182c7b5ca8b8c88932ce3e0383 +size 380041 diff --git a/.venv/lib/python3.12/site-packages/av/container/pyio.pxd b/.venv/lib/python3.12/site-packages/av/container/pyio.pxd new file mode 100644 index 0000000000000000000000000000000000000000..c1f91b7b627756b4662a2e3ba52e12bf8e62e467 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/pyio.pxd @@ -0,0 +1,24 @@ +cimport libav as lib +from libc.stdint cimport int64_t, uint8_t + + +cdef int pyio_read(void *opaque, uint8_t *buf, int buf_size) noexcept nogil +cdef int pyio_write(void *opaque, const uint8_t *buf, int buf_size) noexcept nogil +cdef int64_t pyio_seek(void *opaque, int64_t offset, int whence) noexcept nogil +cdef int pyio_close_gil(lib.AVIOContext *pb) +cdef int pyio_close_custom_gil(lib.AVIOContext *pb) + +cdef class PyIOFile: + # File-like source. + cdef readonly object file + cdef object fread + cdef object fwrite + cdef object fseek + cdef object ftell + cdef object fclose + + # Custom IO for above. + cdef lib.AVIOContext *iocontext + cdef unsigned char *buffer + cdef int64_t pos + cdef bint pos_is_valid diff --git a/.venv/lib/python3.12/site-packages/av/container/pyio.py b/.venv/lib/python3.12/site-packages/av/container/pyio.py new file mode 100644 index 0000000000000000000000000000000000000000..0f7af6eb73491f704dde085130fb904e3fe3202b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/pyio.py @@ -0,0 +1,204 @@ +# type: ignore +import cython +from cython import NULL +from cython.cimports import libav as lib +from cython.cimports.av.error import stash_exception +from cython.cimports.libc.stdint import int64_t, uint8_t +from cython.cimports.libc.string import memcpy + +Buf = cython.typedef(cython.pointer[uint8_t]) +BufC = cython.typedef(cython.pointer[cython.const[uint8_t]]) + +seek_func_t = cython.typedef( + "int64_t (*seek_func_t)(void *opaque, int64_t offset, int whence) noexcept nogil" +) + + +@cython.final +@cython.cclass +class PyIOFile: + def __cinit__(self, file, buffer_size, writeable=None): + self.file = file + + seek_func: seek_func_t = NULL + + readable = getattr(self.file, "readable", None) + writable = getattr(self.file, "writable", None) + seekable = getattr(self.file, "seekable", None) + self.fread = getattr(self.file, "read", None) + self.fwrite = getattr(self.file, "write", None) + self.fseek = getattr(self.file, "seek", None) + self.ftell = getattr(self.file, "tell", None) + self.fclose = getattr(self.file, "close", None) + + # To be seekable, the file object must have `seek` and `tell` methods. + # If it also has a `seekable` method, it must return True. + if ( + self.fseek is not None + and self.ftell is not None + and (seekable is None or seekable()) + ): + seek_func = pyio_seek + + if writeable is None: + writeable = self.fwrite is not None + + if writeable: + if self.fwrite is None or (writable is not None and not writable()): + raise ValueError( + "File object has no write() method, or writable() returned False." + ) + else: + if self.fread is None or (readable is not None and not readable()): + raise ValueError( + "File object has no read() method, or readable() returned False." + ) + + self.pos = 0 + self.pos_is_valid = True + + # This is effectively the maximum size of reads. + self.buffer = cython.cast(cython.p_uchar, lib.av_malloc(buffer_size)) + + self.iocontext = lib.avio_alloc_context( + self.buffer, + buffer_size, + writeable, + cython.cast(cython.p_void, self), # User data. + pyio_read, + pyio_write, + seek_func, + ) + + if seek_func: + self.iocontext.seekable = lib.AVIO_SEEKABLE_NORMAL + self.iocontext.max_packet_size = buffer_size + + def __dealloc__(self): + with cython.nogil: + # FFmpeg will not release custom input, so it's up to us to free it. + # Do not touch our original buffer as it may have been freed and replaced. + if self.iocontext: + lib.av_freep(cython.address(self.iocontext.buffer)) + lib.av_freep(cython.address(self.iocontext)) + + # We likely errored badly if we got here, and so we are still responsible. + else: + lib.av_freep(cython.address(self.buffer)) + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def pyio_read(opaque: cython.p_void, buf: Buf, buf_size: cython.int) -> cython.int: + with cython.gil: + return pyio_read_gil(opaque, buf, buf_size) + + +@cython.cfunc +@cython.exceptval(check=False) +def pyio_read_gil(opaque: cython.p_void, buf: Buf, buf_size: cython.int) -> cython.int: + self: PyIOFile + res: bytes + try: + self = cython.cast(PyIOFile, opaque) + res = self.fread(buf_size) + memcpy( + buf, cython.cast(cython.p_void, cython.cast(cython.p_char, res)), len(res) + ) + self.pos += len(res) + if not res: + return lib.AVERROR_EOF + return cython.cast(cython.int, len(res)) + except Exception: + return stash_exception() + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def pyio_write(opaque: cython.p_void, buf: BufC, buf_size: cython.int) -> cython.int: + with cython.gil: + return pyio_write_gil(opaque, buf, buf_size) + + +@cython.cfunc +@cython.exceptval(check=False) +def pyio_write_gil( + opaque: cython.p_void, buf: BufC, buf_size: cython.int +) -> cython.int: + self: PyIOFile + bytes_to_write: bytes + bytes_written: cython.int + try: + self = cython.cast(PyIOFile, opaque) + bytes_to_write = buf[:buf_size] + ret_value = self.fwrite(bytes_to_write) + bytes_written = ret_value if isinstance(ret_value, int) else buf_size + self.pos += bytes_written + return bytes_written + except Exception: + return stash_exception() + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def pyio_seek(opaque: cython.p_void, offset: int64_t, whence: cython.int) -> int64_t: + # Seek takes the standard flags, but also a ad-hoc one which means that the library + # wants to know how large the file is. We are generally allowed to ignore this. + if whence == lib.AVSEEK_SIZE: + return -1 + with cython.gil: + return pyio_seek_gil(opaque, offset, whence) + + +@cython.cfunc +def pyio_seek_gil( + opaque: cython.p_void, offset: int64_t, whence: cython.int +) -> int64_t: + self: PyIOFile + try: + self = cython.cast(PyIOFile, opaque) + res = self.fseek(offset, whence) + + # Track the position for the user. + if whence == 0: + self.pos = offset + elif whence == 1: + self.pos += offset + else: + self.pos_is_valid = False + if res is None: + if self.pos_is_valid: + res = self.pos + else: + res = self.ftell() + return res + except Exception: + return stash_exception() + + +@cython.cfunc +def pyio_close_gil(pb: cython.pointer[lib.AVIOContext]) -> cython.int: + try: + return lib.avio_close(pb) + except Exception: + return stash_exception() + + +@cython.cfunc +def pyio_close_custom_gil(pb: cython.pointer[lib.AVIOContext]) -> cython.int: + self: PyIOFile + try: + self = cython.cast(PyIOFile, pb.opaque) + + # Flush bytes in the AVIOContext buffers to the custom I/O + lib.avio_flush(pb) + + if self.fclose is not None: + self.fclose() + + return 0 + except Exception: + stash_exception() diff --git a/.venv/lib/python3.12/site-packages/av/container/streams.abi3.so b/.venv/lib/python3.12/site-packages/av/container/streams.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..6a3102e6b25d302a0d05b9eafa62c6d99f879cab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/streams.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb6c098c3aaa8bc3068dc680044e3c81fc00fa7109930cd308603fc475a54c6c +size 655001 diff --git a/.venv/lib/python3.12/site-packages/av/container/streams.pxd b/.venv/lib/python3.12/site-packages/av/container/streams.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d62174992b96e00a330cca7ee9d276e717cf21bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/streams.pxd @@ -0,0 +1,8 @@ +cimport libav as lib + +from av.stream cimport Stream + + +cdef class StreamContainer: + cdef list _streams + cdef void add_stream(self, Stream stream) diff --git a/.venv/lib/python3.12/site-packages/av/container/streams.py b/.venv/lib/python3.12/site-packages/av/container/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1dca00b7fca3f19b50fc26063898f29080d739 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/streams.py @@ -0,0 +1,178 @@ +from collections.abc import Iterator + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.stream import Stream + + +@cython.cfunc +def _get_media_type_enum(type: str) -> lib.AVMediaType: + if type == "video": + return lib.AVMEDIA_TYPE_VIDEO + elif type == "audio": + return lib.AVMEDIA_TYPE_AUDIO + elif type == "subtitle": + return lib.AVMEDIA_TYPE_SUBTITLE + elif type == "attachment": + return lib.AVMEDIA_TYPE_ATTACHMENT + elif type == "data": + return lib.AVMEDIA_TYPE_DATA + else: + raise ValueError(f"Invalid stream type: {type}") + + +@cython.cfunc +@cython.exceptval(check=False) +def _get_best_stream_index( + fmtctx: cython.pointer[lib.AVFormatContext], + enumtype: lib.AVMediaType, + related: Stream | None, +) -> cython.int: + stream_index: cython.int + + if related is None: + stream_index = lib.av_find_best_stream(fmtctx, enumtype, -1, -1, cython.NULL, 0) + else: + stream_index = lib.av_find_best_stream( + fmtctx, enumtype, -1, related.ptr.index, cython.NULL, 0 + ) + + return stream_index + + +@cython.final +@cython.cclass +class StreamContainer: + """ + + A tuple-like container of :class:`Stream`. + + :: + + # There are a few ways to pulling out streams. + first = container.streams[0] + video = container.streams.video[0] + audio = container.streams.get(audio=(0, 1)) + + + """ + + def __cinit__(self): + self._streams = [] + + @cython.cfunc + def add_stream(self, stream: Stream) -> cython.void: + assert stream.ptr.index == len(self._streams) + self._streams.append(stream) + + # Basic tuple interface. + def __len__(self): + return len(self._streams) + + def __iter__(self): + return iter(self._streams) + + def __getitem__(self, index): + if isinstance(index, int): + return self.get(index)[0] + else: + return self.get(index) + + @property + def video(self): + return tuple(s for s in self._streams if s.type == "video") + + @property + def audio(self): + return tuple(s for s in self._streams if s.type == "audio") + + @property + def subtitles(self): + return tuple(s for s in self._streams if s.type == "subtitle") + + @property + def data(self): + return tuple(s for s in self._streams if s.type == "data") + + @property + def attachments(self): + return tuple(s for s in self._streams if s.type == "attachment") + + def _get_streams(self, x) -> Iterator[Stream]: + if x is None: + pass + elif isinstance(x, Stream): + yield x + elif isinstance(x, int): + yield self._streams[x] + elif isinstance(x, (tuple, list)): + for item in x: + yield from self._get_streams(item) + elif isinstance(x, dict): + for type_, indices in x.items(): + # For compatibility with the pseudo signature + streams = self._streams if type_ == "streams" else getattr(self, type_) + if not isinstance(indices, (tuple, list)): + indices = [indices] + for i in indices: + yield streams[i] + else: + raise TypeError("Argument must be Stream or int.", type(x)) + + def get(self, *args, **kwargs): + """get(streams=None, video=None, audio=None, subtitles=None, data=None) + + Get a selection of :class:`.Stream` as a ``list``. + + Positional arguments may be ``int`` (which is an index into the streams), + or ``list`` or ``tuple`` of those:: + + # Get the first channel. + streams.get(0) + + # Get the first two audio channels. + streams.get(audio=(0, 1)) + + Keyword arguments (or dicts as positional arguments) as interpreted + as ``(stream_type, index_value_or_set)`` pairs:: + + # Get the first video channel. + streams.get(video=0) + # or + streams.get({'video': 0}) + + :class:`.Stream` objects are passed through untouched. + + If nothing is selected, then all streams are returned. + + """ + selection = list(self._get_streams(args)) + if kwargs: + selection.extend(self._get_streams(kwargs)) + + return selection or self._streams[:] + + def best(self, type: str, /, related: Stream | None = None): + """best(type: Literal["video", "audio", "subtitle", "attachment", "data"], /, related: Stream | None) + Finds the "best" stream in the file. Wraps :ffmpeg:`av_find_best_stream`. Example:: + + stream = container.streams.best("video") + + :param type: The type of stream to find + :param related: A related stream to use as a reference (optional) + :return: The best stream of the specified type + :rtype: Stream | None + """ + if len(self._streams) == 0: + return None + + first_stream: Stream = cython.cast(Stream, self._streams[0]) + container: cython.pointer[lib.AVFormatContext] = first_stream.container.ptr + stream_index: cython.int = _get_best_stream_index( + container, _get_media_type_enum(type), related + ) + + if stream_index < 0: + return None + + return self._streams[stream_index] diff --git a/.venv/lib/python3.12/site-packages/av/container/streams.pyi b/.venv/lib/python3.12/site-packages/av/container/streams.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bdab1ea541970e8b8dcfa6bf93c6240c3eb4a8b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/container/streams.pyi @@ -0,0 +1,35 @@ +from collections.abc import Iterator +from typing import Literal, overload + +from av.audio.stream import AudioStream +from av.stream import AttachmentStream, DataStream, Stream +from av.subtitles.stream import SubtitleStream +from av.video.stream import VideoStream + +class StreamContainer: + video: tuple[VideoStream, ...] + audio: tuple[AudioStream, ...] + subtitles: tuple[SubtitleStream, ...] + attachments: tuple[AttachmentStream, ...] + data: tuple[DataStream, ...] + + def __init__(self) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[Stream]: ... + @overload + def __getitem__(self, index: int) -> Stream: ... + @overload + def __getitem__(self, index: slice) -> list[Stream]: ... + @overload + def __getitem__(self, index: int | slice) -> Stream | list[Stream]: ... + def get( + self, + *args: int | Stream | dict[str, int | tuple[int, ...]], + **kwargs: int | tuple[int, ...], + ) -> list[Stream]: ... + def best( + self, + type: Literal["video", "audio", "subtitle", "data", "attachment"], + /, + related: Stream | None = None, + ) -> Stream | None: ... diff --git a/.venv/lib/python3.12/site-packages/av/datasets.py b/.venv/lib/python3.12/site-packages/av/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..8547c150721585e488967ce6035734a180f0c41c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/datasets.py @@ -0,0 +1,119 @@ +import errno +import logging +import os +import shutil +import sys +from collections.abc import Iterator +from urllib.request import urlopen + +log = logging.getLogger(__name__) + + +def iter_data_dirs(check_writable: bool = False) -> Iterator[str]: + try: + yield os.environ["PYAV_TESTDATA_DIR"] + except KeyError: + pass + + if os.name == "nt": + yield os.path.join(sys.prefix, "pyav", "datasets") + return + + bases = [ + "/usr/local/share", + "/usr/local/lib", + "/usr/share", + "/usr/lib", + ] + + # Prefer the local virtualenv. + if hasattr(sys, "real_prefix"): + bases.insert(0, sys.prefix) + + for base in bases: + dir_ = os.path.join(base, "pyav", "datasets") + if check_writable: + if os.path.exists(dir_): + if not os.access(dir_, os.W_OK): + continue + else: + if not os.access(base, os.W_OK): + continue + yield dir_ + + yield os.path.join(os.path.expanduser("~"), ".pyav", "datasets") + + +def cached_download(url: str, name: str) -> str: + """Download the data at a URL, and cache it under the given name. + + The file is stored under `pyav/test` with the given name in the directory + :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of: + + - the current virtualenv + - ``/usr/local/share`` + - ``/usr/local/lib`` + - ``/usr/share`` + - ``/usr/lib`` + - the user's home + + """ + + clean_name = os.path.normpath(name) + if clean_name != name: + raise ValueError(f"{name} is not normalized.") + + for dir_ in iter_data_dirs(): + path = os.path.join(dir_, name) + if os.path.exists(path): + return path + + dir_ = next(iter_data_dirs(True)) + path = os.path.join(dir_, name) + + log.info(f"Downloading {url} to {path}") + + response = urlopen(url) + if response.getcode() != 200: + raise ValueError(f"HTTP {response.getcode()}") + + dir_ = os.path.dirname(path) + try: + os.makedirs(dir_) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + tmp_path = path + ".tmp" + with open(tmp_path, "wb") as fh: + shutil.copyfileobj(response, fh) + + os.rename(tmp_path, path) + + return path + + +def fate(name: str) -> str: + """Download and return a path to a sample from the FFmpeg test suite. + + Data is handled by :func:`cached_download`. + + See the `FFmpeg Automated Test Environment `_ + + """ + return cached_download( + "http://fate.ffmpeg.org/fate-suite/" + name, + os.path.join("fate-suite", name.replace("/", os.path.sep)), + ) + + +def curated(name: str) -> str: + """Download and return a path to a sample that is curated by the PyAV developers. + + Data is handled by :func:`cached_download`. + + """ + return cached_download( + "https://pyav.org/datasets/" + name, + os.path.join("pyav-curated", name.replace("/", os.path.sep)), + ) diff --git a/.venv/lib/python3.12/site-packages/av/device.abi3.so b/.venv/lib/python3.12/site-packages/av/device.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..34e5e5c7c3316ebabbb9c0701deed14b0dca9811 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/device.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbf0b5906c921383dd0547d0e3d1d4597b5154682d8fe2700afd520e52a5272b +size 585585 diff --git a/.venv/lib/python3.12/site-packages/av/device.py b/.venv/lib/python3.12/site-packages/av/device.py new file mode 100644 index 0000000000000000000000000000000000000000..b5d5d110c6d250b272d649fcddd6b96d3a5f0318 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/device.py @@ -0,0 +1,187 @@ +import re + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.error import err_check + + +class DeviceInfo: + """Information about an input or output device. + + :param str name: The device identifier, for use as the first argument to :func:`av.open`. + :param str description: Human-readable description of the device. + :param bool is_default: Whether this is the default device. + :param list media_types: Media types this device provides, e.g. ``["video"]``, ``["audio"]``, + or ``["video", "audio"]``. + + """ + + name: str + description: str + is_default: bool + media_types: list[str] + + def __init__( + self, + name: str, + description: str, + is_default: bool, + media_types: list[str], + ) -> None: + self.name = name + self.description = description + self.is_default = is_default + self.media_types = media_types + + def __repr__(self) -> str: + default = " (default)" if self.is_default else "" + return f"" + + +@cython.cfunc +def _build_device_list(device_list: cython.pointer[lib.AVDeviceInfoList]) -> list: + devices: list = [] + i: cython.int + j: cython.int + device_info: cython.pointer[lib.AVDeviceInfo] + mt: lib.AVMediaType + s: cython.p_const_char + + for i in range(device_list.nb_devices): + device_info = device_list.devices[i] + + media_types: list = [] + for j in range(device_info.nb_media_types): + mt = device_info.media_types[j] + s = lib.av_get_media_type_string(mt) + if s: + media_types.append(s) + + devices.append( + DeviceInfo( + name=cython.cast(bytes, device_info.device_name).decode() + if device_info.device_name + else "", + description=cython.cast(bytes, device_info.device_description).decode() + if device_info.device_description + else "", + is_default=(i == device_list.default_device), + media_types=media_types, + ) + ) + + return devices + + +def _enumerate_via_log_fallback(format_name: str) -> list[DeviceInfo]: + """Fallback for formats (e.g. avfoundation) that log devices instead of + implementing get_device_list. Opens the format with list_devices=1 and + parses the INFO log output.""" + from av import logging as avlogging + + fmt: cython.pointer[cython.const[lib.AVInputFormat]] = lib.av_find_input_format( + format_name + ) + + opts: cython.pointer[lib.AVDictionary] = cython.NULL + lib.av_dict_set(cython.address(opts), b"list_devices", b"1", 0) + + ctx: cython.pointer[lib.AVFormatContext] = cython.NULL + + # Temporarily enable INFO logging so Capture receives device list messages. + old_level = avlogging.get_level() + avlogging.set_level(avlogging.INFO) + devices: list[DeviceInfo] = [] + try: + with avlogging.Capture() as logs: + lib.avformat_open_input(cython.address(ctx), b"", fmt, cython.address(opts)) + if ctx: + lib.avformat_close_input(cython.address(ctx)) + + current_media_type = "video" + for _level, _name, message in logs: + message = message.strip() + if "video devices" in message.lower(): + current_media_type = "video" + elif "audio devices" in message.lower(): + current_media_type = "audio" + else: + m = re.match(r"\[(\d+)\] (.+)", message) + if m: + devices.append( + DeviceInfo( + name=m.group(1), + description=m.group(2), + is_default=False, + media_types=[current_media_type], + ) + ) + finally: + avlogging.set_level(old_level) + lib.av_dict_free(cython.address(opts)) + + return devices + + +def enumerate_input_devices(format_name: str) -> list[DeviceInfo]: + """List the available input devices for a given format. + + :param str format_name: The format name, e.g. ``"avfoundation"``, ``"dshow"``, ``"v4l2"``. + :rtype: list[DeviceInfo] + :raises ValueError: If *format_name* is not a known input format. + :raises av.FFmpegError: If the device does not support enumeration. + + Example:: + + for device in av.enumerate_input_devices("avfoundation"): + print(device.name, device.description) + + """ + fmt: cython.pointer[cython.const[lib.AVInputFormat]] = lib.av_find_input_format( + format_name + ) + if not fmt: + raise ValueError(f"no such input format: {format_name!r}") + + device_list: cython.pointer[lib.AVDeviceInfoList] = cython.NULL + try: + err_check( + lib.avdevice_list_input_sources( + fmt, cython.NULL, cython.NULL, cython.address(device_list) + ) + ) + return _build_device_list(device_list) + except NotImplementedError: + # Format doesn't implement get_device_list (e.g. avfoundation). + # Fall back to opening with list_devices=1 and parsing the log output. + return _enumerate_via_log_fallback(format_name) + finally: + lib.avdevice_free_list_devices(cython.address(device_list)) + + +def enumerate_output_devices(format_name: str) -> list[DeviceInfo]: + """List the available output devices for a given format. + + :param str format_name: The format name, e.g. ``"audiotoolbox"``. + :rtype: list[DeviceInfo] + :raises ValueError: If *format_name* is not a known output format. + :raises av.FFmpegError: If the device does not support enumeration. + + """ + fmt: cython.pointer[cython.const[lib.AVOutputFormat]] = lib.av_guess_format( + format_name, cython.NULL, cython.NULL + ) + if not fmt: + raise ValueError(f"no such output format: {format_name!r}") + + device_list: cython.pointer[lib.AVDeviceInfoList] = cython.NULL + err_check( + lib.avdevice_list_output_sinks( + fmt, cython.NULL, cython.NULL, cython.address(device_list) + ) + ) + + try: + return _build_device_list(device_list) + finally: + lib.avdevice_free_list_devices(cython.address(device_list)) diff --git a/.venv/lib/python3.12/site-packages/av/device.pyi b/.venv/lib/python3.12/site-packages/av/device.pyi new file mode 100644 index 0000000000000000000000000000000000000000..33c55699445b2f6f6bb239125bf584db674e45d3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/device.pyi @@ -0,0 +1,19 @@ +__all__ = ("DeviceInfo", "enumerate_input_devices", "enumerate_output_devices") + +class DeviceInfo: + name: str + description: str + is_default: bool + media_types: list[str] + + def __init__( + self, + name: str, + description: str, + is_default: bool, + media_types: list[str], + ) -> None: ... + def __repr__(self) -> str: ... + +def enumerate_input_devices(format_name: str) -> list[DeviceInfo]: ... +def enumerate_output_devices(format_name: str) -> list[DeviceInfo]: ... diff --git a/.venv/lib/python3.12/site-packages/av/dictionary.abi3.so b/.venv/lib/python3.12/site-packages/av/dictionary.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..c82270296b32034933584fead3b5c66db069ea60 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/dictionary.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a1213a656516c619797ee4273b4169d12215717ec39e669437fed5b77a4acad +size 474817 diff --git a/.venv/lib/python3.12/site-packages/av/dictionary.pxd b/.venv/lib/python3.12/site-packages/av/dictionary.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d1eb3c9d19b7750bc32cbbe93a67d9dc6fdab37f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/dictionary.pxd @@ -0,0 +1,8 @@ +cimport libav as lib + + +cdef class Dictionary: + cdef lib.AVDictionary *ptr + cpdef Dictionary copy(self) + +cdef Dictionary wrap_dictionary(lib.AVDictionary *input_) diff --git a/.venv/lib/python3.12/site-packages/av/dictionary.py b/.venv/lib/python3.12/site-packages/av/dictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bd76acbaafc7f78b1b372a5b4a29d73cf390e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/dictionary.py @@ -0,0 +1,78 @@ +import cython +from cython.cimports.av.error import err_check + + +@cython.final +@cython.cclass +class Dictionary: + def __cinit__(self, *args, **kwargs): + for arg in args: + self.update(arg) + if kwargs: + self.update(kwargs) + + def __dealloc__(self): + if self.ptr != cython.NULL: + lib.av_dict_free(cython.address(self.ptr)) + + def __getitem__(self, key: cython.str): + element: cython.pointer[lib.AVDictionaryEntry] = lib.av_dict_get( + self.ptr, key, cython.NULL, 0 + ) + if element == cython.NULL: + raise KeyError(key) + return element.value + + def __setitem__(self, key: cython.str, value: cython.str): + err_check(lib.av_dict_set(cython.address(self.ptr), key, value, 0)) + + def __delitem__(self, key: cython.str): + err_check(lib.av_dict_set(cython.address(self.ptr), key, cython.NULL, 0)) + + def __len__(self): + return err_check(lib.av_dict_count(self.ptr)) + + def __iter__(self): + element: cython.pointer[lib.AVDictionaryEntry] = cython.NULL + while True: + element = lib.av_dict_get(self.ptr, "", element, lib.AV_DICT_IGNORE_SUFFIX) + if element == cython.NULL: + break + yield element.key + + def __repr__(self): + return f"av.Dictionary({dict(self)!r})" + + def keys(self): + return list(self) + + def copy(self): + other: Dictionary = Dictionary() + lib.av_dict_copy(cython.address(other.ptr), self.ptr, 0) + return other + + def pop(self, key: str): + value = self[key] + del self[key] + return value + + def update(self, other=(), /, **kwds): + if isinstance(other, Dictionary): + lib.av_dict_copy( + cython.address(self.ptr), cython.cast(Dictionary, other).ptr, 0 + ) + elif hasattr(other, "keys"): + for key in other.keys(): + self[key] = other[key] + else: + for key, value in other: + self[key] = value + for key, value in kwds.items(): + self[key] = value + + +@cython.cfunc +def wrap_dictionary(input_: cython.pointer[lib.AVDictionary]) -> Dictionary: + output: Dictionary = Dictionary() + output.ptr = input_ + return output diff --git a/.venv/lib/python3.12/site-packages/av/dictionary.pyi b/.venv/lib/python3.12/site-packages/av/dictionary.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f68003c6a934532ebc22669d723fbb43c88f6ca3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/dictionary.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable, Iterator, Mapping + +class Dictionary: + def __getitem__(self, key: str) -> str: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __repr__(self) -> str: ... + def keys(self) -> Iterable[str]: ... + def copy(self) -> Dictionary: ... + def pop(self, key: str) -> str: ... + def update( + self, + other: Mapping[str, str] | Iterable[tuple[str, str]] = (), + /, + **kwds: str, + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/error.abi3.so b/.venv/lib/python3.12/site-packages/av/error.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..1ed4241b0cec71a155f2ee295bd8951c87b3ef80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/error.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b42e9eb27814246869e04a4dfba9b9b1ef03ae568b809035e2642123aaef420 +size 946041 diff --git a/.venv/lib/python3.12/site-packages/av/error.pxd b/.venv/lib/python3.12/site-packages/av/error.pxd new file mode 100644 index 0000000000000000000000000000000000000000..17c37f609f16bcc5dbee4b1666387c6c4170c6ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/error.pxd @@ -0,0 +1,2 @@ +cdef int stash_exception(exc_info=*) +cpdef int err_check(int res, filename=*) except -1 diff --git a/.venv/lib/python3.12/site-packages/av/error.py b/.venv/lib/python3.12/site-packages/av/error.py new file mode 100644 index 0000000000000000000000000000000000000000..941dfcbb8c1b12b27a8611e99d50d4ef3a463b3b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/error.py @@ -0,0 +1,356 @@ +import enum +import errno +import os +import sys +import traceback +from threading import local + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.logging import get_last_error +from cython.cimports.libc.stdio import fprintf, stderr +from cython.cimports.libc.stdlib import free, malloc + +# Will get extended with all the exceptions. +__all__ = [ + "ErrorType", + "FFmpegError", + "LookupError", + "HTTPError", + "HTTPClientError", + "UndefinedError", +] + + +@cython.ccall +def code_to_tag(code: cython.int) -> bytes: + """Convert an integer error code into 4-byte tag. + + >>> code_to_tag(1953719668) + b'test' + + """ + return bytes( + ( + code & 0xFF, + (code >> 8) & 0xFF, + (code >> 16) & 0xFF, + (code >> 24) & 0xFF, + ) + ) + + +@cython.ccall +def tag_to_code(tag: bytes) -> cython.int: + """Convert a 4-byte error tag into an integer code. + + >>> tag_to_code(b'test') + 1953719668 + + """ + if len(tag) != 4: + raise ValueError("Error tags are 4 bytes.") + return (tag[0]) + (tag[1] << 8) + (tag[2] << 16) + (tag[3] << 24) + + +class FFmpegError(Exception): + """Exception class for errors from within FFmpeg. + + .. attribute:: errno + + FFmpeg's integer error code. + + .. attribute:: strerror + + FFmpeg's error message. + + .. attribute:: filename + + The filename that was being operated on (if available). + + .. attribute:: log + + The tuple from :func:`av.logging.get_last_log`, or ``None``. + + """ + + def __init__(self, code, message, filename=None, log=None): + args = [code, message] + if filename or log: + args.append(filename) + if log: + args.append(log) + super().__init__(*args) + + self.errno = code + self.strerror = message + self.args = tuple(args) + + @property + def filename(self): + try: + return self.args[2] + except IndexError: + pass + + @property + def log(self): + try: + return self.args[3] + except IndexError: + pass + + def __str__(self): + msg = "" + if self.errno is not None: + msg = f"{msg}[Errno {self.errno}] " + if self.strerror is not None: + msg = f"{msg}{self.strerror}" + if self.filename: + msg = f"{msg}: {self.filename!r}" + if self.log: + msg = ( + f"{msg}; last error log: [{self.log[1].strip()}] {self.log[2].strip()}" + ) + + return msg + + +# Our custom error, used in callbacks. +c_PYAV_STASHED_ERROR = cython.declare(cython.int, tag_to_code(b"PyAV")) +PYAV_STASHED_ERROR_message = cython.declare(str, "Error in PyAV callback") + + +# Bases for the FFmpeg-based exceptions. +class LookupError(FFmpegError, LookupError): + pass + + +class HTTPError(FFmpegError): + pass + + +class HTTPClientError(FFmpegError): + pass + + +# Tuples of (enum_name, enum_value, exc_name, exc_base). +# tuple[str, int, str | None, Exception | none] +# fmt: off +_ffmpeg_specs = ( + ("BSF_NOT_FOUND", -lib.AVERROR_BSF_NOT_FOUND, "BSFNotFoundError", LookupError), + ("BUG", -lib.AVERROR_BUG, None, RuntimeError), + ("BUFFER_TOO_SMALL", -lib.AVERROR_BUFFER_TOO_SMALL, None, ValueError), + ("DECODER_NOT_FOUND", -lib.AVERROR_DECODER_NOT_FOUND, None, LookupError), + ("DEMUXER_NOT_FOUND", -lib.AVERROR_DEMUXER_NOT_FOUND, None, LookupError), + ("ENCODER_NOT_FOUND", -lib.AVERROR_ENCODER_NOT_FOUND, None, LookupError), + ("EOF", -lib.AVERROR_EOF, "EOFError", EOFError), + ("EXIT", -lib.AVERROR_EXIT, None, None), + ("EXTERNAL", -lib.AVERROR_EXTERNAL, None, None), + ("FILTER_NOT_FOUND", -lib.AVERROR_FILTER_NOT_FOUND, None, LookupError), + ("INVALIDDATA", -lib.AVERROR_INVALIDDATA, "InvalidDataError", ValueError), + ("MUXER_NOT_FOUND", -lib.AVERROR_MUXER_NOT_FOUND, None, LookupError), + ("OPTION_NOT_FOUND", -lib.AVERROR_OPTION_NOT_FOUND, None, LookupError), + ("PATCHWELCOME", -lib.AVERROR_PATCHWELCOME, "PatchWelcomeError", None), + ("PROTOCOL_NOT_FOUND", -lib.AVERROR_PROTOCOL_NOT_FOUND, None, LookupError), + ("UNKNOWN", -lib.AVERROR_UNKNOWN, None, None), + ("EXPERIMENTAL", -lib.AVERROR_EXPERIMENTAL, None, None), + ("INPUT_CHANGED", -lib.AVERROR_INPUT_CHANGED, None, None), + ("OUTPUT_CHANGED", -lib.AVERROR_OUTPUT_CHANGED, None, None), + ("HTTP_BAD_REQUEST", -lib.AVERROR_HTTP_BAD_REQUEST, "HTTPBadRequestError", HTTPClientError), + ("HTTP_UNAUTHORIZED", -lib.AVERROR_HTTP_UNAUTHORIZED, "HTTPUnauthorizedError", HTTPClientError), + ("HTTP_FORBIDDEN", -lib.AVERROR_HTTP_FORBIDDEN, "HTTPForbiddenError", HTTPClientError), + ("HTTP_NOT_FOUND", -lib.AVERROR_HTTP_NOT_FOUND, "HTTPNotFoundError", HTTPClientError), + ("HTTP_TOO_MANY_REQUESTS", -lib.AVERROR_HTTP_TOO_MANY_REQUESTS, "HTTPTooManyRequestsError", HTTPClientError), + ("HTTP_OTHER_4XX", -lib.AVERROR_HTTP_OTHER_4XX, "HTTPOtherClientError", HTTPClientError), + ("HTTP_SERVER_ERROR", -lib.AVERROR_HTTP_SERVER_ERROR, "HTTPServerError", HTTPError), + ("PYAV_CALLBACK", c_PYAV_STASHED_ERROR, "PyAVCallbackError", RuntimeError), +) +# fmt: on + + +ErrorType = enum.IntEnum( + "ErrorType", + [(name, value) for name, value, *_ in _ffmpeg_specs], + module=__name__, +) +ErrorType.__doc__ = "An enumeration of FFmpeg's error types." + + +def _error_type_tag(self) -> bytes: + """The FFmpeg byte tag for the error.""" + return code_to_tag(self.value) + + +def _error_type_strerror(self) -> str: + """The error message that would be returned.""" + if self.value == c_PYAV_STASHED_ERROR: + return PYAV_STASHED_ERROR_message + return lib.av_err2str(-self.value) + + +ErrorType.tag = property(_error_type_tag) +ErrorType.strerror = property(_error_type_strerror) + +classes: dict = {} + + +def _extend_builtin(name, codes): + base = getattr(__builtins__, name, OSError) + cls = type(name, (FFmpegError, base), {"__module__": __name__}) + + # Register in builder. + for code in codes: + classes[code] = cls + + # Register in module. + globals()[name] = cls + __all__.append(name) + + return cls + + +_extend_builtin("PermissionError", (errno.EACCES, errno.EPERM)) +_extend_builtin( + "BlockingIOError", + (errno.EAGAIN, errno.EALREADY, errno.EINPROGRESS, errno.EWOULDBLOCK), +) +_extend_builtin("ChildProcessError", (errno.ECHILD,)) +_extend_builtin("ConnectionAbortedError", (errno.ECONNABORTED,)) +_extend_builtin("ConnectionRefusedError", (errno.ECONNREFUSED,)) +_extend_builtin("ConnectionResetError", (errno.ECONNRESET,)) +_extend_builtin("FileExistsError", (errno.EEXIST,)) +_extend_builtin("InterruptedError", (errno.EINTR,)) +_extend_builtin("IsADirectoryError", (errno.EISDIR,)) +_extend_builtin("FileNotFoundError", (errno.ENOENT,)) +_extend_builtin("NotADirectoryError", (errno.ENOTDIR,)) +_extend_builtin("BrokenPipeError", (errno.EPIPE, errno.ESHUTDOWN)) +_extend_builtin("ProcessLookupError", (errno.ESRCH,)) +_extend_builtin("TimeoutError", (errno.ETIMEDOUT,)) +_extend_builtin("MemoryError", (errno.ENOMEM,)) +_extend_builtin("NotImplementedError", (errno.ENOSYS,)) +_extend_builtin("OverflowError", (errno.ERANGE,)) +_extend_builtin("OSError", [code for code in errno.errorcode if code not in classes]) + + +class ArgumentError(FFmpegError, ValueError): + def __str__(self): + msg = "" + if self.strerror is not None: + msg = f"{msg}{self.strerror}" + if self.filename: + msg = f"{msg}: {self.filename!r}" + if self.errno is not None: + msg = f"{msg} returned {self.errno}" + if self.log: + msg = ( + f"{msg}; last error log: [{self.log[1].strip()}] {self.log[2].strip()}" + ) + + return msg + + +class UndefinedError(FFmpegError): + """Fallback exception type in case FFmpeg returns an error we don't know about.""" + + pass + + +classes[errno.EINVAL] = ArgumentError +globals()["ArgumentError"] = ArgumentError +__all__.append("ArgumentError") + + +# Classes for the FFmpeg errors. +for enum_name, code, name, base in _ffmpeg_specs: + name = name or enum_name.title().replace("_", "") + "Error" + + if base is None: + bases = (FFmpegError,) + elif issubclass(base, FFmpegError): + bases = (base,) + else: + bases = (FFmpegError, base) + + cls = type(name, bases, {"__module__": __name__}) + + # Register in builder. + classes[code] = cls + + # Register in module. + globals()[name] = cls + __all__.append(name) + +del _ffmpeg_specs + + +# Storage for stashing. +_local = cython.declare(object, local()) +_err_count = cython.declare(cython.int, 0) +_last_log_count = cython.declare(cython.int, 0) + + +@cython.cfunc +def stash_exception(exc_info=None) -> cython.int: + global _err_count + + existing = getattr(_local, "exc_info", None) + if existing is not None: + fprintf(stderr, "PyAV library exception being dropped:\n") + traceback.print_exception(*existing) + _err_count -= 1 # Balance out the +=1 that is coming. + + exc_info = exc_info or sys.exc_info() + _local.exc_info = exc_info + if exc_info: + _err_count += 1 + + return -c_PYAV_STASHED_ERROR + + +@cython.ccall +@cython.exceptval(-1, check=False) +def err_check(res: cython.int, filename=None) -> cython.int: + """Raise appropriate exceptions from library return code.""" + + global _err_count + global _last_log_count + + # Check for stashed exceptions. + if _err_count: + exc_info = getattr(_local, "exc_info", None) + if exc_info is not None: + _err_count -= 1 + _local.exc_info = None + raise exc_info[1].with_traceback(exc_info[2]) + + if res >= 0: + return res + + # Grab details from the last log. + log_count, last_log = get_last_error() + if log_count > _last_log_count: + _last_log_count = log_count + log = last_log + else: + log = None + + code: cython.int = -res + error_buffer: cython.p_char = cython.cast( + cython.p_char, malloc(lib.AV_ERROR_MAX_STRING_SIZE * cython.sizeof(char)) + ) + if error_buffer == cython.NULL: + raise MemoryError() + + try: + if code == c_PYAV_STASHED_ERROR: + message = PYAV_STASHED_ERROR_message + else: + lib.av_strerror(res, error_buffer, lib.AV_ERROR_MAX_STRING_SIZE) + # Fallback to OS error string if no message + message = error_buffer or os.strerror(code) + + cls = classes.get(code, UndefinedError) + raise cls(code, message, filename, log) + finally: + free(error_buffer) diff --git a/.venv/lib/python3.12/site-packages/av/error.pyi b/.venv/lib/python3.12/site-packages/av/error.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1191d962f6cf8fb4594a39ebf8568c0e03ca8c8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/error.pyi @@ -0,0 +1,72 @@ +import builtins + +classes: dict[int, Exception] + +def code_to_tag(code: int) -> bytes: ... +def tag_to_code(tag: bytes) -> int: ... +def err_check(res: int, filename: str | None = None) -> int: ... + +class FFmpegError(Exception): + errno: int | None + strerror: str | None + filename: str + log: tuple[int, tuple[int, str, str] | None] + + def __init__( + self, + code: int, + message: str, + filename: str | None = None, + log: tuple[int, tuple[int, str, str] | None] | None = None, + ) -> None: ... + +class LookupError(FFmpegError): ... +class HTTPError(FFmpegError): ... +class HTTPClientError(FFmpegError): ... +class UndefinedError(FFmpegError): ... +class InvalidDataError(FFmpegError, builtins.ValueError): ... +class BugError(FFmpegError, builtins.RuntimeError): ... +class BufferTooSmallError(FFmpegError, builtins.ValueError): ... +class BSFNotFoundError(LookupError): ... +class DecoderNotFoundError(LookupError): ... +class DemuxerNotFoundError(LookupError): ... +class EncoderNotFoundError(LookupError): ... +class ExitError(FFmpegError): ... +class ExternalError(FFmpegError): ... +class FilterNotFoundError(LookupError): ... +class MuxerNotFoundError(LookupError): ... +class OptionNotFoundError(LookupError): ... +class PatchWelcomeError(FFmpegError): ... +class ProtocolNotFoundError(LookupError): ... +class UnknownError(FFmpegError): ... +class ExperimentalError(FFmpegError): ... +class InputChangedError(FFmpegError): ... +class OutputChangedError(FFmpegError): ... +class HTTPBadRequestError(HTTPClientError): ... +class HTTPUnauthorizedError(HTTPClientError): ... +class HTTPForbiddenError(HTTPClientError): ... +class HTTPNotFoundError(HTTPClientError): ... +class HTTPTooManyRequestsError(HTTPClientError): ... +class HTTPOtherClientError(HTTPClientError): ... +class HTTPServerError(HTTPError): ... +class PyAVCallbackError(FFmpegError, builtins.RuntimeError): ... +class BrokenPipeError(FFmpegError, builtins.BrokenPipeError): ... +class ChildProcessError(FFmpegError, builtins.ChildProcessError): ... +class ConnectionAbortedError(FFmpegError, builtins.ConnectionAbortedError): ... +class ConnectionRefusedError(FFmpegError, builtins.ConnectionRefusedError): ... +class ConnectionResetError(FFmpegError, builtins.ConnectionResetError): ... +class BlockingIOError(FFmpegError, builtins.BlockingIOError): ... +class EOFError(FFmpegError, builtins.EOFError): ... +class FileExistsError(FFmpegError, builtins.FileExistsError): ... +class FileNotFoundError(FFmpegError, builtins.FileNotFoundError): ... +class InterruptedError(FFmpegError, builtins.InterruptedError): ... +class IsADirectoryError(FFmpegError, builtins.IsADirectoryError): ... +class MemoryError(FFmpegError, builtins.MemoryError): ... +class NotADirectoryError(FFmpegError, builtins.NotADirectoryError): ... +class NotImplementedError(FFmpegError, builtins.NotImplementedError): ... +class OverflowError(FFmpegError, builtins.OverflowError): ... +class OSError(FFmpegError, builtins.OSError): ... +class PermissionError(FFmpegError, builtins.PermissionError): ... +class ProcessLookupError(FFmpegError, builtins.ProcessLookupError): ... +class TimeoutError(FFmpegError, builtins.TimeoutError): ... +class ArgumentError(FFmpegError): ... diff --git a/.venv/lib/python3.12/site-packages/av/filter/__init__.pxd b/.venv/lib/python3.12/site-packages/av/filter/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/filter/__init__.py b/.venv/lib/python3.12/site-packages/av/filter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cffc49e7ddfc7bc3924a1cf8145c3b31e0f7031a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/__init__.py @@ -0,0 +1,3 @@ +from .filter import Filter, filters_available +from .graph import Graph as Graph +from .loudnorm import stats as stats diff --git a/.venv/lib/python3.12/site-packages/av/filter/__init__.pyi b/.venv/lib/python3.12/site-packages/av/filter/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5be1326c99efab97108a8dba6887cda669b6996a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/__init__.pyi @@ -0,0 +1,4 @@ +from .context import * +from .filter import * +from .graph import * +from .loudnorm import * diff --git a/.venv/lib/python3.12/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f0b3de2b9082353060d003a467c7dbb7cd4b021 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/filter/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ec496271a9b4c6ba41b6f3a082ac8b71f14fabd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/filter/__pycache__/filter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e35351183af32a12003634332802de34b2fcdfb9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/filter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/filter/__pycache__/graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f216692a08a58e11c61840bb7967faa69015cf41 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/filter/__pycache__/link.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/link.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..498495da5e8de81761d9352d6420acf219e9c655 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/link.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/filter/__pycache__/loudnorm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/loudnorm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6098b8b9eb3c07f05ebf37658252e559bf64ee97 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/filter/__pycache__/loudnorm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/filter/context.abi3.so b/.venv/lib/python3.12/site-packages/av/filter/context.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..71b6028154a4d6754c7853a7ba56ff9a7004f510 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/context.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1daa475a28c56bbd5f1f290d6048bba259097a1cfde2891b2452bc630339ee30 +size 1638961 diff --git a/.venv/lib/python3.12/site-packages/av/filter/context.pxd b/.venv/lib/python3.12/site-packages/av/filter/context.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d67e7e1e7d5663fc9efbe4e12a078b181b334761 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/context.pxd @@ -0,0 +1,17 @@ +cimport libav as lib + +from av.filter.filter cimport Filter +from av.filter.graph cimport Graph + + +cdef class FilterContext: + cdef lib.AVFilterContext *ptr + cdef readonly object _graph + cdef readonly Filter filter + cdef object _inputs + cdef object _outputs + cdef bint inited + cdef unsigned char _kind + + +cdef FilterContext wrap_filter_context(Graph graph, Filter filter, lib.AVFilterContext *ptr) diff --git a/.venv/lib/python3.12/site-packages/av/filter/context.py b/.venv/lib/python3.12/site-packages/av/filter/context.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfd6e7a4bbafbccd6d7ba407053d39beff624f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/context.py @@ -0,0 +1,206 @@ +import weakref + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.audio.frame import alloc_audio_frame +from cython.cimports.av.dictionary import Dictionary +from cython.cimports.av.error import err_check +from cython.cimports.av.filter.link import alloc_filter_pads +from cython.cimports.av.frame import Frame +from cython.cimports.av.utils import avrational_to_fraction +from cython.cimports.av.video.frame import alloc_video_frame + +_cinit_sentinel = cython.declare(object, object()) + +_KIND_OTHER = cython.declare(cython.uchar, 0) +_KIND_SOURCE = cython.declare(cython.uchar, 1) # buffer / abuffer +_KIND_VIDEO_SINK = cython.declare(cython.uchar, 2) # buffersink +_KIND_AUDIO_SINK = cython.declare(cython.uchar, 3) # abuffersink + + +@cython.cfunc +def wrap_filter_context( + graph: Graph, filter: Filter, ptr: cython.pointer[lib.AVFilterContext] +) -> FilterContext: + self: FilterContext = FilterContext(_cinit_sentinel) + self._graph = weakref.ref(graph) + self.filter = filter + self.ptr = ptr + + name: str = filter.name + if name == "buffer" or name == "abuffer": + self._kind = _KIND_SOURCE + elif name == "buffersink": + self._kind = _KIND_VIDEO_SINK + elif name == "abuffersink": + self._kind = _KIND_AUDIO_SINK + else: + self._kind = _KIND_OTHER + return self + + +@cython.final +@cython.cclass +class FilterContext: + def __cinit__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot construct FilterContext") + + def __repr__(self): + if self.ptr != cython.NULL: + name = repr(self.ptr.name) if self.ptr.name != cython.NULL else "" + else: + name = "None" + + parent = ( + self.filter.ptr.name + if self.filter and self.filter.ptr != cython.NULL + else None + ) + return f"" + + @property + def name(self): + if self.ptr.name != cython.NULL: + return self.ptr.name + + @property + def inputs(self): + if self._inputs is None: + self._inputs = alloc_filter_pads( + self.filter, self.ptr.input_pads, True, self + ) + return self._inputs + + @property + def outputs(self): + if self._outputs is None: + self._outputs = alloc_filter_pads( + self.filter, self.ptr.output_pads, False, self + ) + return self._outputs + + def init(self, args=None, **kwargs): + if self.inited: + raise ValueError("already inited") + if args and kwargs: + raise ValueError("cannot init from args and kwargs") + + dict_: Dictionary = None + c_args: cython.p_char = cython.NULL + if args or not kwargs: + if args: + c_args = args + err_check(lib.avfilter_init_str(self.ptr, c_args)) + else: + dict_ = Dictionary(kwargs) + err_check(lib.avfilter_init_dict(self.ptr, cython.address(dict_.ptr))) + + self.inited = True + if dict_: + raise ValueError(f"unused config: {', '.join(sorted(dict_))}") + + def link_to( + self, + input_: FilterContext, + output_idx: cython.int = 0, + input_idx: cython.int = 0, + ): + err_check(lib.avfilter_link(self.ptr, output_idx, input_.ptr, input_idx)) + + @property + def graph(self): + if graph := self._graph(): + return graph + else: + raise RuntimeError("graph is unallocated") + + def push(self, frame: Frame | None): + res: cython.int + + if frame is None: + with cython.nogil: + res = lib.av_buffersrc_write_frame(self.ptr, cython.NULL) + err_check(res) + return + elif self._kind == _KIND_SOURCE: + with cython.nogil: + res = lib.av_buffersrc_write_frame(self.ptr, frame.ptr) + err_check(res) + return + + # Delegate to the input. + if len(self.inputs) != 1: + raise ValueError( + f"cannot delegate push without single input; found {len(self.inputs)}" + ) + if not self.inputs[0].link: + raise ValueError("cannot delegate push without linked input") + self.inputs[0].linked.context.push(frame) + + def pull(self): + frame: Frame + res: cython.int + if self._kind == _KIND_VIDEO_SINK: + frame = alloc_video_frame() + elif self._kind == _KIND_AUDIO_SINK: + frame = alloc_audio_frame() + else: + # Delegate to the output. + if len(self.outputs) != 1: + raise ValueError( + f"cannot delegate pull without single output; found {len(self.outputs)}" + ) + if not self.outputs[0].link: + raise ValueError("cannot delegate pull without linked output") + return self.outputs[0].linked.context.pull() + + self.graph.configure() + + with cython.nogil: + res = lib.av_buffersink_get_frame(self.ptr, frame.ptr) + err_check(res) + + frame._init_user_attributes() + frame.time_base = avrational_to_fraction( + cython.address(self.ptr.inputs[0].time_base) + ) + return frame + + def process_command( + self, cmd, arg=None, res_len: cython.int = 1024, flags: cython.int = 0 + ): + if not cmd: + raise ValueError("Invalid cmd") + + c_arg: cython.p_char = cython.NULL + c_cmd: cython.p_char = cmd + if arg is not None: + c_arg = arg + + c_res: cython.p_char = cython.NULL + ret: cython.int + res_buf: bytearray = None + view: cython.uchar[:] + b: bytes + nul: cython.int + + if res_len > 0: + res_buf = bytearray(res_len) + view = res_buf + c_res = cython.cast(cython.p_char, cython.address(view[0])) + + with cython.nogil: + ret = lib.avfilter_process_command( + self.ptr, c_cmd, c_arg, c_res, res_len, flags + ) + err_check(ret) + + if res_buf is not None: + b = bytes(res_buf) + nul = b.find(b"\x00") + if nul >= 0: + b = b[:nul] + if b: + return b.decode("utf-8", "strict") + return None diff --git a/.venv/lib/python3.12/site-packages/av/filter/context.pyi b/.venv/lib/python3.12/site-packages/av/filter/context.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2350019f3aae5f3c7e554e56f3c0a5903528d56c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/context.pyi @@ -0,0 +1,17 @@ +from av.filter import Graph +from av.frame import Frame + +class FilterContext: + name: str | None + + def init(self, args: str | None = None, **kwargs: str | None) -> None: ... + def link_to( + self, input_: FilterContext, output_idx: int = 0, input_idx: int = 0 + ) -> None: ... + @property + def graph(self) -> Graph: ... + def push(self, frame: Frame | None) -> None: ... + def pull(self) -> Frame: ... + def process_command( + self, cmd: str, arg: str | None = None, res_len: int = 1024, flags: int = 0 + ) -> str | None: ... diff --git a/.venv/lib/python3.12/site-packages/av/filter/filter.abi3.so b/.venv/lib/python3.12/site-packages/av/filter/filter.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..fe17727da61a57211f5c695e9373e0ad63dfaf85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/filter.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60891e6c00fe2aca521708586dd81487d89006d8c0446dbf78651b199af22b50 +size 224129 diff --git a/.venv/lib/python3.12/site-packages/av/filter/filter.pxd b/.venv/lib/python3.12/site-packages/av/filter/filter.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d74065a199f4d3df11a364a7537bb60a962a0c6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/filter.pxd @@ -0,0 +1,10 @@ +cimport libav as lib + + +cdef class Filter: + cdef const lib.AVFilter *ptr + cdef object _inputs + cdef object _outputs + + +cdef Filter wrap_filter(const lib.AVFilter *ptr) diff --git a/.venv/lib/python3.12/site-packages/av/filter/filter.py b/.venv/lib/python3.12/site-packages/av/filter/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..acbbc111a35791572f3cf10769335f16c744593a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/filter.py @@ -0,0 +1,67 @@ +import cython +from cython.cimports import libav as lib +from cython.cimports.av.filter.link import alloc_filter_pads + +_cinit_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def wrap_filter(ptr: cython.pointer[cython.const[lib.AVFilter]]) -> Filter: + filter_: Filter = Filter(_cinit_sentinel) + filter_.ptr = ptr + return filter_ + + +@cython.final +@cython.cclass +class Filter: + def __cinit__(self, name): + if name is _cinit_sentinel: + return + if not isinstance(name, str): + raise TypeError("takes a filter name as a string") + + self.ptr = lib.avfilter_get_by_name(name) + if not self.ptr: + raise ValueError(f"no filter {name}") + + @property + def name(self): + return self.ptr.name + + @property + def description(self): + return self.ptr.description + + @property + def flags(self): + return self.ptr.flags + + @property + def inputs(self): + if self._inputs is None: + self._inputs = alloc_filter_pads(self, self.ptr.inputs, True) + return self._inputs + + @property + def outputs(self): + if self._outputs is None: + self._outputs = alloc_filter_pads(self, self.ptr.outputs, False) + return self._outputs + + +@cython.cfunc +def get_filter_names() -> set: + names: set = set() + ptr: cython.pointer[cython.const[lib.AVFilter]] + opaque: cython.p_void = cython.NULL + while True: + ptr = lib.av_filter_iterate(cython.address(opaque)) + if ptr: + names.add(ptr.name) + else: + break + return names + + +filters_available = get_filter_names() diff --git a/.venv/lib/python3.12/site-packages/av/filter/filter.pyi b/.venv/lib/python3.12/site-packages/av/filter/filter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..090d4f1d0ee9e2fd913bcd596bda82f09627cf73 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/filter.pyi @@ -0,0 +1,8 @@ +class Filter: + name: str + description: str + flags: int + + def __init__(self, name: str) -> None: ... + +filters_available: set[str] diff --git a/.venv/lib/python3.12/site-packages/av/filter/graph.abi3.so b/.venv/lib/python3.12/site-packages/av/filter/graph.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..2cf6d4d5f72c09a23d1e5db93012535537880e8c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/graph.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0943e6dc597ce22e44a7605be8394087cfffecb97f5a8f8dc420e886902f89c0 +size 847633 diff --git a/.venv/lib/python3.12/site-packages/av/filter/graph.pxd b/.venv/lib/python3.12/site-packages/av/filter/graph.pxd new file mode 100644 index 0000000000000000000000000000000000000000..f67053016017d0500ee22543f8f86f781f574a37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/graph.pxd @@ -0,0 +1,24 @@ +cimport libav as lib + +from av.filter.context cimport FilterContext + + +cdef class Graph: + cdef object __weakref__ + + cdef lib.AVFilterGraph *ptr + + cdef readonly bint configured + cpdef configure(self, bint auto_buffer=*, bint force=*) + + cdef dict _name_counts + cdef str _get_unique_name(self, str name) + cdef list[FilterContext] _get_context_by_type(self, str type) + + cdef _register_context(self, FilterContext) + cdef _auto_register(self) + cdef int _nb_filters_seen + cdef dict[size_t, FilterContext] _context_by_ptr + cdef dict[str, list[FilterContext]] _context_by_type + cdef list[FilterContext] _video_sources + cdef list[FilterContext] _audio_sources diff --git a/.venv/lib/python3.12/site-packages/av/filter/graph.py b/.venv/lib/python3.12/site-packages/av/filter/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4898ab60ec827ce7b908bc0812cb5e01002292 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/graph.py @@ -0,0 +1,306 @@ +import warnings +from fractions import Fraction + +import cython +from cython.cimports.av.audio.format import AudioFormat +from cython.cimports.av.audio.frame import AudioFrame +from cython.cimports.av.audio.layout import AudioLayout +from cython.cimports.av.error import err_check +from cython.cimports.av.filter.context import FilterContext, wrap_filter_context +from cython.cimports.av.filter.filter import Filter, wrap_filter +from cython.cimports.av.video.format import VideoFormat +from cython.cimports.av.video.frame import VideoFrame + + +@cython.final +@cython.cclass +class Graph: + def __cinit__(self): + self.ptr = lib.avfilter_graph_alloc() + self.configured = False + self._name_counts = {} + self._nb_filters_seen = 0 + self._context_by_ptr = {} + self._context_by_type = {} + self._video_sources = [] + self._audio_sources = [] + + def __dealloc__(self): + if self.ptr: + # This frees the graph, filter contexts, links, etc.. + lib.avfilter_graph_free(cython.address(self.ptr)) + + @property + def threads(self): + """Maximum number of threads used by filters in this graph. + + Set to 0 for automatic thread count. Must be set before adding any + filters to the graph. + + Wraps :ffmpeg:`AVFilterGraph.nb_threads`. + """ + return self.ptr.nb_threads + + @threads.setter + def threads(self, value: cython.int): + if self.ptr.nb_filters: + raise RuntimeError("Cannot change threads after filters have been added.") + self.ptr.nb_threads = value + + @cython.cfunc + def _get_unique_name(self, name: str) -> str: + count = self._name_counts.get(name, 0) + self._name_counts[name] = count + 1 + if count: + return f"{name}_{count}" + else: + return name + + @cython.cfunc + @cython.inline + def _get_context_by_type(self, type_: str) -> list[FilterContext]: + return self._context_by_type.get(type_, []) + + @cython.ccall + def configure(self, auto_buffer: cython.bint = True, force: cython.bint = False): + if self.configured and not force: + return + + err_check(lib.avfilter_graph_config(self.ptr, cython.NULL)) + self.configured = True + + # We get auto-inserted stuff here. + self._auto_register() + + def link_nodes(self, *nodes): + """ + Links nodes together for simple filter graphs. + """ + for c, n in zip(nodes, nodes[1:]): + c.link_to(n) + return self + + def add(self, filter, args=None, **kwargs): + cy_filter: Filter + if isinstance(filter, str): + cy_filter = Filter(filter) + elif isinstance(filter, Filter): + cy_filter = filter + else: + raise TypeError("filter must be a string or Filter") + + name: str = self._get_unique_name(kwargs.pop("name", None) or cy_filter.name) + ptr: cython.pointer[lib.AVFilterContext] = lib.avfilter_graph_alloc_filter( + self.ptr, cy_filter.ptr, name + ) + if not ptr: + raise RuntimeError("Could not allocate AVFilterContext") + + # Manually construct this context (so we can return it). + ctx: FilterContext = wrap_filter_context(self, cy_filter, ptr) + ctx.init(args, **kwargs) + self._register_context(ctx) + + # There might have been automatic contexts added (e.g. resamplers, + # fifos, and scalers). It is more likely to see them after the graph + # is configured, but we want to be safe. + self._auto_register() + + return ctx + + @cython.cfunc + def _register_context(self, ctx: FilterContext): + name: str = ctx.filter.ptr.name + self._context_by_ptr[cython.cast(cython.size_t, ctx.ptr)] = ctx + self._context_by_type.setdefault(name, []).append(ctx) + if name == "buffer": + self._video_sources.append(ctx) + elif name == "abuffer": + self._audio_sources.append(ctx) + + @cython.cfunc + def _auto_register(self): + i: cython.int + c_ctx: cython.pointer[lib.AVFilterContext] + filter_: Filter + py_ctx: FilterContext + # We assume that filters are never removed from the graph. At this + # point we don't expose that in the API, so we should be okay... + for i in range(self._nb_filters_seen, self.ptr.nb_filters): + c_ctx = self.ptr.filters[i] + if cython.cast(cython.size_t, c_ctx) in self._context_by_ptr: + continue + filter_ = wrap_filter(c_ctx.filter) + py_ctx = wrap_filter_context(self, filter_, c_ctx) + self._register_context(py_ctx) + self._nb_filters_seen = self.ptr.nb_filters + + def add_buffer( + self, + template=None, + width=None, + height=None, + format=None, + name=None, + time_base=None, + ): + if template is not None: + if width is None: + width = template.width + if height is None: + height = template.height + if format is None: + format = template.format + if time_base is None: + time_base = template.time_base + + if width is None: + raise ValueError("missing width") + if height is None: + raise ValueError("missing height") + if format is None: + raise ValueError("missing format") + if time_base is None: + warnings.warn( + "missing time_base. Guessing 1/1000 time base. " + "This is deprecated and may be removed in future releases.", + DeprecationWarning, + ) + time_base = Fraction(1, 1000) + + return self.add( + "buffer", + name=name, + video_size=f"{width}x{height}", + pix_fmt=str(int(VideoFormat(format))), + time_base=str(time_base), + pixel_aspect="1/1", + ) + + def add_abuffer( + self, + template=None, + sample_rate=None, + format=None, + layout=None, + channels=None, + name=None, + time_base=None, + ): + """ + Convenience method for adding `abuffer `_. + """ + + if template is not None: + if sample_rate is None: + sample_rate = template.sample_rate + if format is None: + format = template.format + if layout is None: + layout = template.layout.name + if channels is None: + channels = template.channels + if time_base is None: + time_base = template.time_base + + if sample_rate is None: + raise ValueError("missing sample_rate") + if format is None: + raise ValueError("missing format") + if layout is None and channels is None: + raise ValueError("missing layout or channels") + if time_base is None: + time_base = Fraction(1, sample_rate) + + kwargs = { + "sample_rate": f"{sample_rate}", + "sample_fmt": AudioFormat(format).name, + "time_base": f"{time_base}", + } + if layout: + kwargs["channel_layout"] = AudioLayout(layout).name + if channels: + kwargs["channels"] = f"{channels}" + + return self.add("abuffer", name=name, **kwargs) + + def set_audio_frame_size(self, frame_size): + """ + Set the audio frame size for the graphs `abuffersink`. + See `av_buffersink_set_frame_size `_. + """ + if not self.configured: + raise ValueError("graph not configured") + sinks = self._get_context_by_type("abuffersink") + if not sinks: + raise ValueError("missing abuffersink filter") + for sink in sinks: + lib.av_buffersink_set_frame_size( + cython.cast(FilterContext, sink).ptr, frame_size + ) + + def push(self, frame, at: cython.int = -1): + """Push a frame into the graph's buffer source(s). + + :param frame: An :class:`.AudioFrame` or :class:`.VideoFrame` to push into + the matching buffer sources, or ``None`` to signal end of stream to + every buffer source. + :param int at: Index of a single buffer source to push to, for graphs with + multiple inputs (e.g. ``overlay``). The default of ``-1`` pushes to + every buffer source matching the frame's type. + """ + if frame is None: + contexts = self._video_sources + self._audio_sources + elif isinstance(frame, VideoFrame): + contexts = self._video_sources + elif isinstance(frame, AudioFrame): + contexts = self._audio_sources + else: + raise ValueError( + f"can only AudioFrame, VideoFrame or None; got {type(frame)}" + ) + + if at >= 0: + if at >= len(contexts): + raise IndexError( + f"buffer source index {at} out of range; found {len(contexts)}" + ) + contexts[at].push(frame) + return + + for ctx in contexts: + ctx.push(frame) + + def vpush(self, frame: VideoFrame | None, at: cython.int = -1): + """Like :meth:`push`, but only for :class:`.VideoFrame`.""" + contexts = self._video_sources + if at >= 0: + if at >= len(contexts): + raise IndexError( + f"buffer source index {at} out of range; found {len(contexts)}" + ) + contexts[at].push(frame) + return + + for ctx in contexts: + ctx.push(frame) + + # TODO: Test complex filter graphs, add `at: int = 0` arg to pull() and vpull(). + def pull(self): + vsinks = self._get_context_by_type("buffersink") + asinks = self._get_context_by_type("abuffersink") + + nsinks = len(vsinks) + len(asinks) + if nsinks != 1: + raise ValueError(f"can only auto-pull with single sink; found {nsinks}") + + return (vsinks or asinks)[0].pull() + + def vpull(self): + """Like `pull`, but only for VideoFrames.""" + vsinks = self._get_context_by_type("buffersink") + nsinks = len(vsinks) + if nsinks != 1: + raise ValueError(f"can only auto-pull with single sink; found {nsinks}") + + return vsinks[0].pull() diff --git a/.venv/lib/python3.12/site-packages/av/filter/graph.pyi b/.venv/lib/python3.12/site-packages/av/filter/graph.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8f3231fc2963d8bb54dc8a0bf2b93f32d246643b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/graph.pyi @@ -0,0 +1,48 @@ +from fractions import Fraction +from typing import Any + +from av.audio.format import AudioFormat +from av.audio.frame import AudioFrame +from av.audio.layout import AudioLayout +from av.audio.stream import AudioStream +from av.video.format import VideoFormat +from av.video.frame import VideoFrame +from av.video.stream import VideoStream + +from .context import FilterContext +from .filter import Filter + +class Graph: + configured: bool + threads: int + + def __init__(self) -> None: ... + def configure(self, auto_buffer: bool = True, force: bool = False) -> None: ... + def link_nodes(self, *nodes: FilterContext) -> Graph: ... + def add( + self, filter: str | Filter, args: Any = None, **kwargs: str + ) -> FilterContext: ... + def add_buffer( + self, + template: VideoStream | None = None, + width: int | None = None, + height: int | None = None, + format: VideoFormat | None = None, + name: str | None = None, + time_base: Fraction | None = None, + ) -> FilterContext: ... + def add_abuffer( + self, + template: AudioStream | None = None, + sample_rate: int | None = None, + format: AudioFormat | str | None = None, + layout: AudioLayout | str | None = None, + channels: int | None = None, + name: str | None = None, + time_base: Fraction | None = None, + ) -> FilterContext: ... + def set_audio_frame_size(self, frame_size: int) -> None: ... + def push(self, frame: None | AudioFrame | VideoFrame, at: int = -1) -> None: ... + def pull(self) -> VideoFrame | AudioFrame: ... + def vpush(self, frame: VideoFrame | None, at: int = -1) -> None: ... + def vpull(self) -> VideoFrame: ... diff --git a/.venv/lib/python3.12/site-packages/av/filter/link.abi3.so b/.venv/lib/python3.12/site-packages/av/filter/link.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..e27b00f024f0ec85562b2d4309e2622a27efd8fc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/link.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e680207d7bf1389eb7c3c082f477c17ff645d57c9e4f87260a4a5c8f95d21bd +size 425225 diff --git a/.venv/lib/python3.12/site-packages/av/filter/link.pxd b/.venv/lib/python3.12/site-packages/av/filter/link.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7f6aad2aa2a3b5c1a5edcfb323075733d521c846 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/link.pxd @@ -0,0 +1,32 @@ +cimport libav as lib + +from av.filter.context cimport FilterContext +from av.filter.filter cimport Filter +from av.filter.graph cimport Graph +from av.filter.link cimport FilterContextPad, FilterLink + + +cdef class FilterLink: + cdef object _graph + cdef lib.AVFilterLink *ptr + + cdef FilterContextPad _input + cdef FilterContextPad _output + + +cdef FilterLink wrap_filter_link(Graph graph, lib.AVFilterLink *ptr) + +cdef class FilterPad: + cdef readonly Filter filter + cdef readonly FilterContext context + cdef readonly bint is_input + cdef readonly int index + + cdef const lib.AVFilterPad *base_ptr + + +cdef class FilterContextPad(FilterPad): + cdef FilterLink _link + + +cdef tuple alloc_filter_pads(Filter, const lib.AVFilterPad *ptr, bint is_input, FilterContext context=?) diff --git a/.venv/lib/python3.12/site-packages/av/filter/link.py b/.venv/lib/python3.12/site-packages/av/filter/link.py new file mode 100644 index 0000000000000000000000000000000000000000..2b687e194d1aa55b5b007fffd34765605fa51d4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/link.py @@ -0,0 +1,159 @@ +import weakref + +import cython +import cython.cimports.libav as lib +from cython.cimports.av.filter.graph import Graph + +_cinit_sentinel = cython.declare(object, object()) + + +@cython.final +@cython.cclass +class FilterLink: + def __cinit__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot instantiate FilterLink") + + @property + def graph(self) -> Graph: + if g := self._graph(): + return g + else: + raise RuntimeError("graph is unallocated") + + @property + def input(self): + if self._input: + return self._input + cctx: cython.pointer[lib.AVFilterContext] = self.ptr.src + i: cython.Py_ssize_t + for i in range(cctx.nb_outputs): + if self.ptr == cctx.outputs[i]: + break + else: # nobreak + raise RuntimeError("could not find link in context") + graph: Graph = self.graph + ctx = graph._context_by_ptr[cython.cast(cython.size_t, cctx)] + self._input = ctx.outputs[i] + return self._input + + @property + def output(self): + if self._output: + return self._output + cctx: cython.pointer[lib.AVFilterContext] = self.ptr.dst + i: cython.Py_ssize_t + for i in range(cctx.nb_inputs): + if self.ptr == cctx.inputs[i]: + break + else: + raise RuntimeError("could not find link in context") + try: + graph: Graph = self.graph + ctx = graph._context_by_ptr[cython.cast(cython.size_t, cctx)] + except KeyError: + raise RuntimeError( + "could not find context in graph", (cctx.name, cctx.filter.name) + ) + self._output = ctx.inputs[i] + return self._output + + +@cython.cfunc +def wrap_filter_link(graph: Graph, ptr: cython.pointer[lib.AVFilterLink]) -> FilterLink: + link: FilterLink = FilterLink(_cinit_sentinel) + link._graph = weakref.ref(graph) + link.ptr = ptr + return link + + +@cython.cclass +class FilterPad: + def __cinit__(self, sentinel): + if sentinel is not _cinit_sentinel: + raise RuntimeError("cannot construct FilterPad") + + def __repr__(self): + _filter = self.filter.name + _io = "inputs" if self.is_input else "outputs" + + return ( + f"" + ) + + @property + def is_output(self): + return not self.is_input + + @property + def name(self): + return lib.avfilter_pad_get_name(self.base_ptr, self.index) + + +@cython.final +@cython.cclass +class FilterContextPad(FilterPad): + def __repr__(self): + _filter = self.filter.name + _io = "inputs" if self.is_input else "outputs" + context = self.context.name + + return f"" + + @property + def link(self): + if self._link: + return self._link + links: cython.pointer[cython.pointer[lib.AVFilterLink]] = ( + self.context.ptr.inputs if self.is_input else self.context.ptr.outputs + ) + link: cython.pointer[lib.AVFilterLink] = links[self.index] + if not link: + return + self._link = wrap_filter_link(self.context.graph, link) + return self._link + + @property + def linked(self): + link: FilterLink = self.link + if link: + return link.input if self.is_input else link.output + + +@cython.cfunc +def alloc_filter_pads( + filter: Filter, + ptr: cython.pointer[cython.const[lib.AVFilterPad]], + is_input: cython.bint, + context: FilterContext | None = None, +) -> tuple: + if not ptr: + return () + + pads: list = [] + + # We need to be careful and check our bounds if we know what they are, + # since the arrays on a AVFilterContext are not NULL terminated. + i: cython.int = 0 + count: cython.int + if context is None: + count = lib.avfilter_filter_pad_count(filter.ptr, not is_input) + else: + count = context.ptr.nb_inputs if is_input else context.ptr.nb_outputs + + pad: FilterPad + while i < count: + pad = ( + FilterPad(_cinit_sentinel) + if context is None + else FilterContextPad(_cinit_sentinel) + ) + pads.append(pad) + pad.filter = filter + pad.context = context + pad.is_input = is_input + pad.base_ptr = ptr + pad.index = i + i += 1 + + return tuple(pads) diff --git a/.venv/lib/python3.12/site-packages/av/filter/link.pyi b/.venv/lib/python3.12/site-packages/av/filter/link.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9d199a2722ae62461a7b6249424a7853ba6c17c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/link.pyi @@ -0,0 +1,2 @@ +class FilterLink: + pass diff --git a/.venv/lib/python3.12/site-packages/av/filter/loudnorm.abi3.so b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..ba68da39879aba1d3ac53511f7ee0bd3aa249673 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:773e8c870f1d23c575f226e2ceeedbc89fe512fc105b7cb9f1387bd5534c014d +size 306665 diff --git a/.venv/lib/python3.12/site-packages/av/filter/loudnorm.pxd b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2729dd8be0e2d4d53d64c5348f4cf909f161be2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.pxd @@ -0,0 +1,19 @@ +from av.audio.stream cimport AudioStream + + +cdef extern from "libavcodec/avcodec.h": + ctypedef struct AVCodecContext: + pass + +cdef extern from "libavformat/avformat.h": + ctypedef struct AVFormatContext: + pass + +cdef extern from "loudnorm_impl.h": + char* loudnorm_get_stats( + AVFormatContext* fmt_ctx, + int audio_stream_index, + const char* loudnorm_args + ) nogil + +cpdef bytes stats(str loudnorm_args, AudioStream stream) diff --git a/.venv/lib/python3.12/site-packages/av/filter/loudnorm.py b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..0be991ab6b17c5ef7050abcb69f55387f003a48d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.py @@ -0,0 +1,48 @@ +import cython +from cython.cimports.av.audio.stream import AudioStream +from cython.cimports.av.container.core import Container +from cython.cimports.libc.stdlib import free + +from av.logging import get_level, set_level + + +@cython.ccall +def stats(loudnorm_args: str, stream: AudioStream) -> bytes: + """ + Get loudnorm statistics for an audio stream. + + Args: + loudnorm_args (str): Arguments for the loudnorm filter (e.g. "i=-24.0:lra=7.0:tp=-2.0") + stream (AudioStream): Input audio stream to analyze + + Returns: + bytes: JSON string containing the loudnorm statistics + """ + + if "print_format=json" not in loudnorm_args: + loudnorm_args = loudnorm_args + ":print_format=json" + + container: Container = stream.container + format_ptr: cython.pointer[AVFormatContext] = container.ptr + container.ptr = cython.NULL # Prevent double-free + + stream_index: cython.int = stream.index + py_args: bytes = loudnorm_args.encode("utf-8") + c_args: cython.p_const_char = py_args + result: cython.p_char + + # Save log level since C function overwrite it. + level = get_level() + + with cython.nogil: + result = loudnorm_get_stats(format_ptr, stream_index, c_args) + + if result == cython.NULL: + raise RuntimeError("Failed to get loudnorm stats") + + py_result = result[:] # Make a copy of the string + free(result) # Free the C string + + set_level(level) + + return py_result diff --git a/.venv/lib/python3.12/site-packages/av/filter/loudnorm.pyi b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c680f638d43a8908438d81c56c07387524488412 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/loudnorm.pyi @@ -0,0 +1,3 @@ +from av.audio.stream import AudioStream + +def stats(loudnorm_args: str, stream: AudioStream) -> bytes: ... diff --git a/.venv/lib/python3.12/site-packages/av/filter/loudnorm_impl.c b/.venv/lib/python3.12/site-packages/av/filter/loudnorm_impl.c new file mode 100644 index 0000000000000000000000000000000000000000..5d43c28b8a5e6226de51e479a866ff5ff68d3d71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/loudnorm_impl.c @@ -0,0 +1,166 @@ +#include +#include +#include +#include +#include +#include +#include + +static char json_buffer[2048] = {0}; +static int json_captured = 0; + +// Custom logging callback. The loudnorm filter prints its stats as a JSON line. +static void logging_callback(void *ptr, int level, const char *fmt, va_list vl) { + char line[2048]; + vsnprintf(line, sizeof(line), fmt, vl); + + const char *json_start = strstr(line, "{"); + if (json_start) { + size_t len = strnlen(json_start, sizeof(json_buffer) - 1); + memcpy(json_buffer, json_start, len); + json_buffer[len] = '\0'; + json_captured = 1; + } +} + +char* loudnorm_get_stats( + AVFormatContext* fmt_ctx, + int audio_stream_index, + const char* loudnorm_args +) { + char* result = NULL; + + // Bail out cleanly if FFmpeg was built without a filter we depend on, + // instead of dereferencing a NULL filter context further down. The caller + // turns a NULL return into a Python exception. + if (!avfilter_get_by_name("abuffer") || + !avfilter_get_by_name("abuffersink") || + !avfilter_get_by_name("loudnorm")) { + av_log(NULL, AV_LOG_ERROR, + "loudnorm: a required filter (abuffer/abuffersink/loudnorm) is not " + "available in this FFmpeg build\n"); + avformat_close_input(&fmt_ctx); + return NULL; + } + + json_captured = 0; // Reset the captured flag + memset(json_buffer, 0, sizeof(json_buffer)); // Clear the buffer + + av_log_set_callback(logging_callback); + + AVFilterGraph *filter_graph = NULL; + AVFilterContext *src_ctx = NULL, *sink_ctx = NULL, *loudnorm_ctx = NULL; + + AVCodec *codec = NULL; + AVCodecContext *codec_ctx = NULL; + AVPacket *packet = NULL; + AVFrame *frame = NULL, *filt_frame = NULL; + int ret; + int graph_configured = 0; + + AVCodecParameters *codecpar = fmt_ctx->streams[audio_stream_index]->codecpar; + codec = (AVCodec *)avcodec_find_decoder(codecpar->codec_id); + codec_ctx = avcodec_alloc_context3(codec); + avcodec_parameters_to_context(codec_ctx, codecpar); + avcodec_open2(codec_ctx, codec, NULL); + + char ch_layout_str[64]; + av_channel_layout_describe(&codecpar->ch_layout, ch_layout_str, sizeof(ch_layout_str)); + + filter_graph = avfilter_graph_alloc(); + + char args[512]; + snprintf(args, sizeof(args), + "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=%s", + fmt_ctx->streams[audio_stream_index]->time_base.num, + fmt_ctx->streams[audio_stream_index]->time_base.den, + codecpar->sample_rate, + av_get_sample_fmt_name(codec_ctx->sample_fmt), + ch_layout_str); + + if (avfilter_graph_create_filter(&src_ctx, avfilter_get_by_name("abuffer"), + "src", args, NULL, filter_graph) < 0 || + avfilter_graph_create_filter(&sink_ctx, avfilter_get_by_name("abuffersink"), + "sink", NULL, NULL, filter_graph) < 0 || + avfilter_graph_create_filter(&loudnorm_ctx, avfilter_get_by_name("loudnorm"), + "loudnorm", loudnorm_args, NULL, filter_graph) < 0) { + goto end; + } + + if (avfilter_link(src_ctx, 0, loudnorm_ctx, 0) < 0 || + avfilter_link(loudnorm_ctx, 0, sink_ctx, 0) < 0 || + avfilter_graph_config(filter_graph, NULL) < 0) { + goto end; + } + graph_configured = 1; + + packet = av_packet_alloc(); + frame = av_frame_alloc(); + filt_frame = av_frame_alloc(); + + while ((ret = av_read_frame(fmt_ctx, packet)) >= 0) { + if (packet->stream_index != audio_stream_index) { + av_packet_unref(packet); + continue; + } + + ret = avcodec_send_packet(codec_ctx, packet); + if (ret < 0) { + av_packet_unref(packet); + continue; + } + + while (ret >= 0) { + ret = avcodec_receive_frame(codec_ctx, frame); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; + if (ret < 0) goto end; + + ret = av_buffersrc_add_frame_flags(src_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF); + if (ret < 0) goto end; + + while (1) { + ret = av_buffersink_get_frame(sink_ctx, filt_frame); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; + if (ret < 0) goto end; + av_frame_unref(filt_frame); + } + } + av_packet_unref(packet); + } + + // Flush decoder + avcodec_send_packet(codec_ctx, NULL); + while (avcodec_receive_frame(codec_ctx, frame) >= 0) { + ret = av_buffersrc_add_frame(src_ctx, frame); + if (ret < 0) goto end; + } + + // Flush filter + ret = av_buffersrc_add_frame(src_ctx, NULL); + if (ret < 0) goto end; + while (av_buffersink_get_frame(sink_ctx, filt_frame) >= 0) { + av_frame_unref(filt_frame); + } + +end: + // Freeing the graph uninits the loudnorm filter, which is what makes it + // emit its JSON stats through our log callback. This happens synchronously + // on this thread, so json_buffer is populated by the time the call returns. + avfilter_graph_free(&filter_graph); + avcodec_free_context(&codec_ctx); + avformat_close_input(&fmt_ctx); + av_frame_free(&filt_frame); + av_frame_free(&frame); + av_packet_free(&packet); + + if (graph_configured && json_captured) { +#ifdef _WIN32 + result = _strdup(json_buffer); +#else + result = strdup(json_buffer); +#endif + } + + av_log_set_callback(av_log_default_callback); + return result; +} diff --git a/.venv/lib/python3.12/site-packages/av/filter/loudnorm_impl.h b/.venv/lib/python3.12/site-packages/av/filter/loudnorm_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..7357e46689d5cbd5795ce00c5864f40e197e09dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/filter/loudnorm_impl.h @@ -0,0 +1,12 @@ +#ifndef AV_FILTER_LOUDNORM_H +#define AV_FILTER_LOUDNORM_H + +#include + +char* loudnorm_get_stats( + AVFormatContext* fmt_ctx, + int audio_stream_index, + const char* loudnorm_args +); + +#endif // AV_FILTER_LOUDNORM_H \ No newline at end of file diff --git a/.venv/lib/python3.12/site-packages/av/format.abi3.so b/.venv/lib/python3.12/site-packages/av/format.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..4d670500aa729127aa2e4a964e9ab18e3f4d8629 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/format.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1770b5ea01cf8aed51f35f4ce1d1ac6809149ba4f4060c8b70e4a298f7dc63ec +size 310425 diff --git a/.venv/lib/python3.12/site-packages/av/format.pxd b/.venv/lib/python3.12/site-packages/av/format.pxd new file mode 100644 index 0000000000000000000000000000000000000000..4109f325c19d9e4f6bbbd9f804e16e991a2a161e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/format.pxd @@ -0,0 +1,12 @@ +cimport libav as lib + + +cdef class ContainerFormat: + + cdef readonly str name + + cdef const lib.AVInputFormat *iptr + cdef const lib.AVOutputFormat *optr + + +cdef ContainerFormat build_container_format(const lib.AVInputFormat*, const lib.AVOutputFormat*) diff --git a/.venv/lib/python3.12/site-packages/av/format.py b/.venv/lib/python3.12/site-packages/av/format.py new file mode 100644 index 0000000000000000000000000000000000000000..fec69f7a0730901329c63897f16d9749ed904611 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/format.py @@ -0,0 +1,168 @@ +from enum import Flag + +import cython +import cython.cimports.libav as lib + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def build_container_format( + iptr: cython.pointer[cython.const[lib.AVInputFormat]], + optr: cython.pointer[cython.const[lib.AVOutputFormat]], +) -> ContainerFormat: + if not iptr and not optr: + raise ValueError("needs input format or output format") + format: ContainerFormat = ContainerFormat.__new__( + ContainerFormat, _cinit_bypass_sentinel + ) + format.iptr = iptr + format.optr = optr + format.name = optr.name if optr else iptr.name + return format + + +# fmt: off +class Flags(Flag): + no_file = lib.AVFMT_NOFILE + need_number: "Needs '%d' in filename." = lib.AVFMT_NEEDNUMBER + show_ids: "Show format stream IDs numbers." = lib.AVFMT_SHOW_IDS + global_header: "Format wants global header." = lib.AVFMT_GLOBALHEADER + no_timestamps: "Format does not need / have any timestamps." = lib.AVFMT_NOTIMESTAMPS + generic_index: "Use generic index building code." = lib.AVFMT_GENERIC_INDEX + ts_discont: "Format allows timestamp discontinuities" = lib.AVFMT_TS_DISCONT + variable_fps: "Format allows variable fps." = lib.AVFMT_VARIABLE_FPS + no_dimensions: "Format does not need width/height" = lib.AVFMT_NODIMENSIONS + no_streams: "Format does not require any streams" = lib.AVFMT_NOSTREAMS + no_bin_search: "Format does not allow to fall back on binary search via read_timestamp" = lib.AVFMT_NOBINSEARCH + no_gen_search: "Format does not allow to fall back on generic search" = lib.AVFMT_NOGENSEARCH + no_byte_seek: "Format does not allow seeking by bytes" = lib.AVFMT_NO_BYTE_SEEK + ts_nonstrict: "Format does not require strictly increasing timestamps, but they must still be monotonic." = lib.AVFMT_TS_NONSTRICT + ts_negative: "Format allows muxing negative timestamps." = lib.AVFMT_TS_NEGATIVE + # If not set the timestamp will be shifted in `av_write_frame()` and `av_interleaved_write_frame()` + # so they start from 0. The user or muxer can override this through AVFormatContext.avoid_negative_ts + seek_to_pts: "Seeking is based on PTS" = lib.AVFMT_SEEK_TO_PTS +# fmt: on + + +@cython.final +@cython.cclass +class ContainerFormat: + """Descriptor of a container format. + + :param str name: The name of the format. + :param str mode: ``'r'`` or ``'w'`` for input and output formats; defaults + to None which will grab either. + + """ + + def __cinit__(self, name, mode=None): + if name is _cinit_bypass_sentinel: + return + + # We need to hold onto the original name because AVInputFormat.name is + # actually comma-separated, and so we need to remember which one this was. + self.name = name + + # Searches comma-separated names. + if mode is None or mode == "r": + self.iptr = lib.av_find_input_format(name) + + if mode is None or mode == "w": + self.optr = lib.av_guess_format(name, cython.NULL, cython.NULL) + + if not self.iptr and not self.optr: + raise ValueError(f"no container format {name!r}") + + def __repr__(self): + return f"" + + @property + def input(self): + """An input-only view of this format.""" + if self.iptr == cython.NULL: + return None + elif self.optr == cython.NULL: + return self + else: + return build_container_format(self.iptr, cython.NULL) + + @property + def output(self): + """An output-only view of this format.""" + if self.optr == cython.NULL: + return None + elif self.iptr == cython.NULL: + return self + else: + return build_container_format(cython.NULL, self.optr) + + @property + def is_input(self): + return self.iptr != cython.NULL + + @property + def is_output(self): + return self.optr != cython.NULL + + @property + def long_name(self): + # We prefer the output names since the inputs may represent + # multiple formats. + return self.optr.long_name if self.optr else self.iptr.long_name + + @property + def extensions(self): + exts: set = set() + if self.iptr and self.iptr.extensions: + exts.update(self.iptr.extensions.split(",")) + if self.optr and self.optr.extensions: + exts.update(self.optr.extensions.split(",")) + return exts + + @property + def flags(self): + """ + Get the flags bitmask for the format. + + :rtype: int + """ + return (self.iptr.flags if self.iptr else 0) | ( + self.optr.flags if self.optr else 0 + ) + + @property + def no_file(self): + return bool(self.flags & lib.AVFMT_NOFILE) + + +@cython.cfunc +def get_output_format_names() -> set: + names: set = set() + ptr: cython.pointer[cython.const[lib.AVOutputFormat]] + opaque: cython.p_void = cython.NULL + while True: + ptr = lib.av_muxer_iterate(cython.address(opaque)) + if ptr: + names.add(ptr.name) + else: + break + return names + + +@cython.cfunc +def get_input_format_names() -> set: + names: set = set() + ptr: cython.pointer[cython.const[lib.AVInputFormat]] + opaque: cython.p_void = cython.NULL + while True: + ptr = lib.av_demuxer_iterate(cython.address(opaque)) + if ptr: + names.add(ptr.name) + else: + break + return names + + +formats_available = get_output_format_names() +formats_available.update(get_input_format_names()) diff --git a/.venv/lib/python3.12/site-packages/av/format.pyi b/.venv/lib/python3.12/site-packages/av/format.pyi new file mode 100644 index 0000000000000000000000000000000000000000..81c5c42ca3e582a88d9dba128d08dbd0f2b4b92b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/format.pyi @@ -0,0 +1,42 @@ +__all__ = ("Flags", "ContainerFormat", "formats_available") + +from enum import Flag +from typing import ClassVar, Literal, cast + +class Flags(Flag): + no_file = cast(ClassVar[Flags], ...) + need_number = cast(ClassVar[Flags], ...) + show_ids = cast(ClassVar[Flags], ...) + global_header = cast(ClassVar[Flags], ...) + no_timestamps = cast(ClassVar[Flags], ...) + generic_index = cast(ClassVar[Flags], ...) + ts_discont = cast(ClassVar[Flags], ...) + variable_fps = cast(ClassVar[Flags], ...) + no_dimensions = cast(ClassVar[Flags], ...) + no_streams = cast(ClassVar[Flags], ...) + no_bin_search = cast(ClassVar[Flags], ...) + no_gen_search = cast(ClassVar[Flags], ...) + no_byte_seek = cast(ClassVar[Flags], ...) + allow_flush = cast(ClassVar[Flags], ...) + ts_nonstrict = cast(ClassVar[Flags], ...) + ts_negative = cast(ClassVar[Flags], ...) + seek_to_pts = cast(ClassVar[Flags], ...) + +class ContainerFormat: + def __init__(self, name: str, mode: Literal["r", "w"] | None = None) -> None: ... + @property + def name(self) -> str: ... + @property + def long_name(self) -> str: ... + @property + def is_input(self) -> bool: ... + @property + def is_output(self) -> bool: ... + @property + def extensions(self) -> set[str]: ... + @property + def flags(self) -> int: ... + @property + def no_file(self) -> bool: ... + +formats_available: set[str] diff --git a/.venv/lib/python3.12/site-packages/av/frame.abi3.so b/.venv/lib/python3.12/site-packages/av/frame.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..d3fd5b23dd18057dba42665b27b17630a49c260c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/frame.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee00956bec17f12ee08234ab9493466d168964783ad5c0708945bf34a5b0ff40 +size 367761 diff --git a/.venv/lib/python3.12/site-packages/av/frame.pxd b/.venv/lib/python3.12/site-packages/av/frame.pxd new file mode 100644 index 0000000000000000000000000000000000000000..6d7214b7caf4edae8f59075a32c805574ccdc514 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/frame.pxd @@ -0,0 +1,14 @@ +cimport libav as lib + +from av.packet cimport Packet +from av.sidedata.sidedata cimport _SideDataContainer + + +cdef class Frame: + cdef lib.AVFrame *ptr + # We define our own time. + cdef lib.AVRational _time_base + cdef _rebase_time(self, lib.AVRational) + cdef _SideDataContainer _side_data + cdef _copy_internal_attributes(self, Frame source, bint data_layout=?) + cdef _init_user_attributes(self) diff --git a/.venv/lib/python3.12/site-packages/av/frame.py b/.venv/lib/python3.12/site-packages/av/frame.py new file mode 100644 index 0000000000000000000000000000000000000000..7c54ae2e21ee2610c451074e29565e1aeb7730d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/frame.py @@ -0,0 +1,210 @@ +import cython +from cython.cimports.av.error import err_check +from cython.cimports.av.opaque import opaque_container +from cython.cimports.av.utils import ( + avdict_to_dict, + avrational_to_fraction, + to_avrational, +) + +from av.sidedata.sidedata import SideDataContainer + + +@cython.cclass +class Frame: + """ + Base class for audio and video frames. + + See also :class:`~av.audio.frame.AudioFrame` and :class:`~av.video.frame.VideoFrame`. + """ + + def __cinit__(self, *args, **kwargs): + with cython.nogil: + self.ptr = lib.av_frame_alloc() + + def __dealloc__(self): + with cython.nogil: + lib.av_frame_free(cython.address(self.ptr)) + + def __repr__(self): + return f"" + + @cython.cfunc + def _copy_internal_attributes(self, source: Frame, data_layout: cython.bint = True): + # Mimic another frame + self._time_base = source._time_base + lib.av_frame_copy_props(self.ptr, source.ptr) + if data_layout: + # TODO: Assert we don't have any data yet. + self.ptr.format = source.ptr.format + self.ptr.width = source.ptr.width + self.ptr.height = source.ptr.height + self.ptr.ch_layout = source.ptr.ch_layout + + @cython.cfunc + def _init_user_attributes(self): + pass # Dummy to match the API of the others. + + @cython.cfunc + def _rebase_time(self, dst: lib.AVRational): + if not dst.num: + raise ValueError("Cannot rebase to zero time.") + + if not self._time_base.num: + self._time_base = dst + return + + if self._time_base.num == dst.num and self._time_base.den == dst.den: + return + + if self.ptr.pts != lib.AV_NOPTS_VALUE: + self.ptr.pts = lib.av_rescale_q(self.ptr.pts, self._time_base, dst) + + if self.ptr.duration != 0: + self.ptr.duration = lib.av_rescale_q( + self.ptr.duration, self._time_base, dst + ) + + self._time_base = dst + + @property + def dts(self): + """ + The decoding timestamp copied from the :class:`~av.packet.Packet` that triggered returning this frame in :attr:`time_base` units. + + (if frame threading isn't used) This is also the Presentation time of this frame calculated from only :attr:`.Packet.dts` values without pts values. + + :type: int | None + """ + if self.ptr.pkt_dts == lib.AV_NOPTS_VALUE: + return None + return self.ptr.pkt_dts + + @dts.setter + def dts(self, value): + if value is None: + self.ptr.pkt_dts = lib.AV_NOPTS_VALUE + else: + self.ptr.pkt_dts = value + + @property + def pts(self): + """ + The presentation timestamp in :attr:`time_base` units for this frame. + + This is the time at which the frame should be shown to the user. + + :type: int | None + """ + if self.ptr.pts == lib.AV_NOPTS_VALUE: + return None + return self.ptr.pts + + @pts.setter + def pts(self, value): + if value is None: + self.ptr.pts = lib.AV_NOPTS_VALUE + else: + self.ptr.pts = value + + @property + def duration(self): + """ + The duration of the frame in :attr:`time_base` units + + :type: int + """ + return self.ptr.duration + + @duration.setter + def duration(self, value): + self.ptr.duration = value + + @property + @cython.cdivision(True) + def time(self): + """ + The presentation time in seconds for this frame. + + This is the time at which the frame should be shown to the user. + + :type: float | None + """ + if self.ptr.pts == lib.AV_NOPTS_VALUE: + return None + return float(self.ptr.pts) * self._time_base.num / self._time_base.den + + @property + def time_base(self): + """ + The unit of time (in fractional seconds) in which timestamps are expressed. + + :type: fractions.Fraction | None + """ + if self._time_base.num: + return avrational_to_fraction(cython.address(self._time_base)) + + @time_base.setter + def time_base(self, value): + to_avrational(value, cython.address(self._time_base)) + + @property + def is_corrupt(self): + """ + Is this frame corrupt? + + :type: bool + """ + return self.ptr.decode_error_flags != 0 or bool( + self.ptr.flags & lib.AV_FRAME_FLAG_CORRUPT + ) + + @property + def key_frame(self): + """Is this frame a key frame? + + Wraps :ffmpeg:`AVFrame.key_frame`. + + """ + return bool(self.ptr.flags & lib.AV_FRAME_FLAG_KEY) + + @key_frame.setter + def key_frame(self, v): + # PyAV makes no guarantees this does anything. + if v: + self.ptr.flags |= lib.AV_FRAME_FLAG_KEY + else: + self.ptr.flags &= ~lib.AV_FRAME_FLAG_KEY + + @property + def side_data(self): + if self._side_data is None: + self._side_data = SideDataContainer(self) + return self._side_data + + @property + def metadata(self): + """Metadata attached to the frame by FFmpeg.""" + return avdict_to_dict(self.ptr.metadata, "utf-8", "strict") + + def make_writable(self): + """ + Ensures that the frame data is writable. Copy the data to new buffer if it is not. + This is a wrapper around :ffmpeg:`av_frame_make_writable`. + """ + ret: cython.int = lib.av_frame_make_writable(self.ptr) + err_check(ret) + + @property + def opaque(self): + if self.ptr.opaque_ref is not cython.NULL: + return opaque_container.get( + cython.cast(cython.p_char, self.ptr.opaque_ref.data) + ) + + @opaque.setter + def opaque(self, v): + lib.av_buffer_unref(cython.address(self.ptr.opaque_ref)) + + if v is not None: + self.ptr.opaque_ref = opaque_container.add(v) diff --git a/.venv/lib/python3.12/site-packages/av/frame.pyi b/.venv/lib/python3.12/site-packages/av/frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..caed23482413da56191e7284b6a365abedd3d6c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/frame.pyi @@ -0,0 +1,24 @@ +from fractions import Fraction +from typing import TypedDict + +from av.sidedata.motionvectors import MotionVectors + +class SideData(TypedDict, total=False): + MOTION_VECTORS: MotionVectors + +class Frame: + dts: int | None + pts: int | None + duration: int + time_base: Fraction | None + side_data: SideData + opaque: object + @property + def metadata(self) -> dict[str, str]: ... + @property + def time(self) -> float | None: ... + @property + def is_corrupt(self) -> bool: ... + @property + def key_frame(self) -> bool: ... + def make_writable(self) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/index.abi3.so b/.venv/lib/python3.12/site-packages/av/index.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..b1bfc474ab0e680d9386b2eb153ec673dfab146c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/index.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d12504dcf4b141eb3c7189a55c623fa795da3244f3b57b6750448bcfa1152d67 +size 552721 diff --git a/.venv/lib/python3.12/site-packages/av/index.pxd b/.venv/lib/python3.12/site-packages/av/index.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d7098c2f0518c1c9a76daaf86ddc84f0806c0c0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/index.pxd @@ -0,0 +1,12 @@ +cimport libav as lib + + +cdef class IndexEntry: + cdef const lib.AVIndexEntry *ptr + cdef _init(self, const lib.AVIndexEntry *ptr) + +cdef class IndexEntries: + cdef lib.AVStream *stream_ptr + cdef _init(self, lib.AVStream *ptr) + +cdef IndexEntries wrap_index_entries(lib.AVStream *ptr) diff --git a/.venv/lib/python3.12/site-packages/av/index.py b/.venv/lib/python3.12/site-packages/av/index.py new file mode 100644 index 0000000000000000000000000000000000000000..b652bfdc13f0036b65a98d7a40bf8cb99e856545 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/index.py @@ -0,0 +1,149 @@ +import cython +import cython.cimports.libav as lib +from cython.cimports.libc.stdint import int64_t + +_cinit_bypass_sentinel = cython.declare(object, object()) + + +@cython.cfunc +def wrap_index_entry(ptr: cython.pointer[cython.const[lib.AVIndexEntry]]) -> IndexEntry: + obj: IndexEntry = IndexEntry(_cinit_bypass_sentinel) + obj._init(ptr) + return obj + + +@cython.final +@cython.cclass +class IndexEntry: + """A single entry from a stream's index. + + This is a thin wrapper around FFmpeg's ``AVIndexEntry``. + + The exact meaning of the fields depends on the container/demuxer. + """ + + def __cinit__(self, sentinel): + if sentinel is not _cinit_bypass_sentinel: + raise RuntimeError("cannot manually instantiate IndexEntry") + + @cython.cfunc + def _init(self, ptr: cython.pointer[cython.const[lib.AVIndexEntry]]): + self.ptr = ptr + + def __repr__(self): + return ( + f"" + ) + + @property + def pos(self): + return self.ptr.pos + + @property + def timestamp(self): + return self.ptr.timestamp + + @property + def flags(self): + return self.ptr.flags + + @property + def is_keyframe(self): + return bool(self.ptr.flags & lib.AVINDEX_KEYFRAME) + + @property + def is_discard(self): + return bool(self.ptr.flags & lib.AVINDEX_DISCARD_FRAME) + + @property + def size(self): + return self.ptr.size + + @property + def min_distance(self): + return self.ptr.min_distance + + +@cython.cfunc +def wrap_index_entries(ptr: cython.pointer[lib.AVStream]) -> IndexEntries: + obj: IndexEntries = IndexEntries(_cinit_bypass_sentinel) + obj._init(ptr) + return obj + + +@cython.final +@cython.cclass +class IndexEntries: + """A sequence-like view of FFmpeg's per-stream index entries. + + Exposed as :attr:`~av.stream.Stream.index_entries`. + + The index is provided by the demuxer and may be empty or incomplete depending + on the container format. This is useful for fast multi-seek loops (e.g., decoding + at a lower-than-native framerate). + """ + + def __cinit__(self, sentinel): + if sentinel is _cinit_bypass_sentinel: + return + raise RuntimeError("cannot manually instantiate IndexEntries") + + @cython.cfunc + def _init(self, ptr: cython.pointer[lib.AVStream]): + self.stream_ptr = ptr + + def __repr__(self): + return f"" + + def __len__(self) -> int: + with cython.nogil: + return lib.avformat_index_get_entries_count(self.stream_ptr) + + def __iter__(self): + for i in range(len(self)): + yield self[i] + + def __getitem__(self, index): + if isinstance(index, int): + n = len(self) + if index < 0: + index += n + if index < 0 or index >= n: + raise IndexError(f"Index entries {index} out of bounds for size {n}") + + c_idx: cython.int = index + entry: cython.pointer[cython.const[lib.AVIndexEntry]] + with cython.nogil: + entry = lib.avformat_index_get_entry(self.stream_ptr, c_idx) + if entry == cython.NULL: + raise IndexError("index entry not found") + + return wrap_index_entry(entry) + elif isinstance(index, slice): + start, stop, step = index.indices(len(self)) + return [self[i] for i in range(start, stop, step)] + else: + raise TypeError("Index must be an integer or a slice") + + def search_timestamp( + self, timestamp, *, backward: bool = True, any_frame: bool = False + ): + """Search the underlying index for ``timestamp``. + + This wraps FFmpeg's ``av_index_search_timestamp``. + + Returns an index into this object, or ``-1`` if no match is found. + """ + c_timestamp: int64_t = timestamp + flags: cython.int = 0 + + if backward: + flags |= lib.AVSEEK_FLAG_BACKWARD + if any_frame: + flags |= lib.AVSEEK_FLAG_ANY + + with cython.nogil: + idx = lib.av_index_search_timestamp(self.stream_ptr, c_timestamp, flags) + + return idx diff --git a/.venv/lib/python3.12/site-packages/av/index.pyi b/.venv/lib/python3.12/site-packages/av/index.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1ccec7a663f5639f5e550786f844b91807f86620 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/index.pyi @@ -0,0 +1,22 @@ +from collections.abc import Iterator +from typing import overload + +class IndexEntry: + pos: int + timestamp: int + flags: int + is_keyframe: bool + is_discard: bool + size: int + min_distance: int + +class IndexEntries: + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[IndexEntry]: ... + @overload + def __getitem__(self, index: int) -> IndexEntry: ... + @overload + def __getitem__(self, index: slice) -> list[IndexEntry]: ... + def search_timestamp( + self, timestamp, *, backward: bool = True, any_frame: bool = False + ) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/av/logging.abi3.so b/.venv/lib/python3.12/site-packages/av/logging.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..92f577639b86eb65ad1ce49891f89ded1a89a9a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/logging.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06923d81aa6fbccc297fc8dd0087ef96453076c61c0baba5dec467aa8d797411 +size 646969 diff --git a/.venv/lib/python3.12/site-packages/av/logging.pxd b/.venv/lib/python3.12/site-packages/av/logging.pxd new file mode 100644 index 0000000000000000000000000000000000000000..b5a99be02805f7b71972e3baaa4761209ea44ba5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/logging.pxd @@ -0,0 +1,12 @@ +cimport libav as lib + + +cdef extern from "Python.h" nogil: + void PyErr_PrintEx(int set_sys_last_vars) + int Py_IsInitialized() + void PyErr_Display(object, object, object) + +cdef extern from "stdio.h" nogil: + cdef int vsnprintf(char *output, int n, const char *format, lib.va_list args) + +cpdef get_last_error() diff --git a/.venv/lib/python3.12/site-packages/av/logging.py b/.venv/lib/python3.12/site-packages/av/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1d484b679ceeb4858ac91ca780c592f9b5f02ab2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/logging.py @@ -0,0 +1,382 @@ +# type: ignore +""" +FFmpeg has a logging system that it uses extensively. It's very noisy, so PyAV turns it +off by default. This unfortunately has the effect of making raised errors have less +detailed messages. It's therefore recommended to use VERBOSE when developing. + +.. _enable_logging: + +Enabling Logging +~~~~~~~~~~~~~~~~~ + +You can hook into the logging system with Python by setting the log level:: + + import av + + av.logging.set_level(av.logging.VERBOSE) + + +PyAV hooks into that system to translate FFmpeg logs into Python's +`logging system `_. + +If you are not already using Python's logging system, you can initialize it +quickly with:: + + import logging + logging.basicConfig() + + +Note that handling logs with Python sometimes doesn't play nicely with multi-threaded workflows. +An alternative is :func:`restore_default_callback`. + +This restores FFmpeg's default logging system, which prints to the terminal. +Like with setting the log level to ``None``, this may also result in raised errors +having less detailed messages. + + +API Reference +~~~~~~~~~~~~~ + +""" + +import logging +import sys +from threading import Lock, get_ident + +import cython +from cython.cimports.libc.stdio import fprintf, stderr +from cython.cimports.libc.stdlib import free, malloc + +# Library levels. +PANIC = lib.AV_LOG_PANIC # 0 +FATAL = lib.AV_LOG_FATAL # 8 +ERROR = lib.AV_LOG_ERROR +WARNING = lib.AV_LOG_WARNING +INFO = lib.AV_LOG_INFO +VERBOSE = lib.AV_LOG_VERBOSE +DEBUG = lib.AV_LOG_DEBUG +TRACE = lib.AV_LOG_TRACE + +# Mimicking stdlib. +CRITICAL = FATAL + + +@cython.ccall +def adapt_level(level: cython.int): + """Convert a library log level to a Python log level.""" + if level <= lib.AV_LOG_FATAL: # Includes PANIC + return 50 # logging.CRITICAL + elif level <= lib.AV_LOG_ERROR: + return 40 # logging.ERROR + elif level <= lib.AV_LOG_WARNING: + return 30 # logging.WARNING + elif level <= lib.AV_LOG_INFO: + return 20 # logging.INFO + elif level <= lib.AV_LOG_VERBOSE: + return 10 # logging.DEBUG + elif level <= lib.AV_LOG_DEBUG: + return 5 # Lower than any logging constant. + else: # lib.AV_LOG_TRACE + return 1 + + +level_threshold = cython.declare(object, None) +c_level_threshold = cython.declare(cython.int, lib.AV_LOG_QUIET) + +# ... but lets limit ourselves to WARNING (assuming nobody already did this). +if "libav" not in logging.Logger.manager.loggerDict: + logging.getLogger("libav").setLevel(logging.WARNING) + + +def get_level(): + """Returns the current log level. See :func:`set_level`.""" + return level_threshold + + +def set_level(level): + """set_level(level) + + Sets PyAV's log level. It can be set to constants available in this + module: ``PANIC``, ``FATAL``, ``ERROR``, ``WARNING``, ``INFO``, + ``VERBOSE``, ``DEBUG``, or ``None`` (the default). + + PyAV defaults to totally ignoring all ffmpeg logs. This has the side effect of + making certain Exceptions have no messages. It's therefore recommended to use: + + av.logging.set_level(av.logging.VERBOSE) + + When developing your application. + """ + global level_threshold + global c_level_threshold + + if level is None: + level_threshold = level + lib.av_log_set_callback(nolog_callback) + elif type(level) is int: + level_threshold = level + c_level_threshold = level + lib.av_log_set_callback(log_callback) + else: + raise ValueError("level must be: int | None") + + +def set_libav_level(level): + """Set libav's log level. It can be set to constants available in this + module: ``PANIC``, ``FATAL``, ``ERROR``, ``WARNING``, ``INFO``, + ``VERBOSE``, ``DEBUG``. + + When PyAV logging is disabled, setting this will change the level of + the logs printed to the terminal. + """ + lib.av_log_set_level(level) + + +def restore_default_callback(): + """Revert back to FFmpeg's log callback, which prints to the terminal.""" + lib.av_log_set_callback(lib.av_log_default_callback) + + +skip_repeated = cython.declare(cython.bint, True) +skip_lock = cython.declare(object, Lock()) +last_log = cython.declare(object, None) +skip_count = cython.declare(cython.int, 0) + + +def get_skip_repeated(): + """Will identical logs be emitted?""" + return skip_repeated + + +def set_skip_repeated(v): + """Set if identical logs will be emitted""" + global skip_repeated + skip_repeated = bool(v) + + +# For error reporting. +last_error = cython.declare(object, None) +error_count = cython.declare(cython.int, 0) + + +@cython.ccall +def get_last_error(): + """Get the last log that was at least ``ERROR``.""" + if error_count: + with skip_lock: + return error_count, last_error + else: + return 0, None + + +global_captures = cython.declare(list, []) +thread_captures = cython.declare(dict, {}) + + +@cython.final +@cython.cclass +class Capture: + """A context manager for capturing logs. + + :param bool local: Should logs from all threads be captured, or just one + this object is constructed in? + + e.g.:: + + with Capture() as logs: + # Do something. + for log in logs: + print(log.message) + + """ + + logs = cython.declare(list, visibility="readonly") + captures = cython.declare(list, visibility="private") + + def __init__(self, local: cython.bint = True): + self.logs = [] + if local: + self.captures = thread_captures.setdefault(get_ident(), []) + else: + self.captures = global_captures + + def __enter__(self): + self.captures.append(self.logs) + return self.logs + + def __exit__(self, type_, value, traceback): + self.captures.pop() + + +log_context = cython.struct( + class_=cython.pointer[lib.AVClass], + name=cython.p_char, +) + +item_name_func = cython.typedef("const char *(*item_name_func)(void *) noexcept nogil") + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def log_context_name(ptr: cython.p_void) -> cython.p_char: + obj: cython.pointer[log_context] = cython.cast(cython.pointer[log_context], ptr) + return obj.name + + +log_class = cython.declare(lib.AVClass) +log_class.item_name = cython.cast(item_name_func, log_context_name) + + +@cython.ccall +def log(level: cython.int, name: str, message: str): + """Send a log through the library logging system. + + This is mostly for testing. + """ + obj: cython.pointer[log_context] = cython.cast( + cython.pointer[log_context], malloc(cython.sizeof(log_context)) + ) + obj.class_ = cython.address(log_class) + obj.name = name + message_bytes: bytes = message.encode("utf-8") + + lib.av_log( + cython.cast(cython.p_void, obj), + level, + "%s", + cython.cast(cython.p_char, message_bytes), + ) + free(obj) + + +@cython.cfunc +def log_callback_gil( + level: cython.int, c_name: cython.p_const_char, c_message: cython.p_char +): + global error_count + global skip_count + global last_log + global last_error + + name = cython.cast(str, c_name) if c_name is not cython.NULL else "" + message = cython.cast(bytes, c_message).decode("utf8", "backslashreplace") + log = (level, name, message) + + # We have to filter it ourselves, but we will still process it in general so + # it is available to our error handling. + # Note that FFmpeg's levels are backwards from Python's. + is_interesting: cython.bint = level <= level_threshold + + # Skip messages which are identical to the previous. + # TODO: Be smarter about threads. + is_repeated: cython.bint = False + repeat_log: object = None + + with skip_lock: + if is_interesting: + is_repeated = skip_repeated and last_log == log + + if is_repeated: + skip_count += 1 + + elif skip_count: + # Now that we have hit the end of the repeat cycle, tally up how many. + if skip_count == 1: + repeat_log = last_log + else: + repeat_log = ( + last_log[0], + last_log[1], + f"{last_log[2]} (repeated {skip_count} more times)", + ) + skip_count = 0 + + last_log = log + + # Hold onto errors for err_check. + if level == lib.AV_LOG_ERROR: + error_count += 1 + last_error = log + + if repeat_log is not None: + log_callback_emit(repeat_log) + + if is_interesting and not is_repeated: + log_callback_emit(log) + + +@cython.cfunc +def log_callback_emit(log): + lib_level, name, message = log + + captures = thread_captures.get(get_ident()) or global_captures + if captures: + captures[-1].append(log) + return + + py_level = adapt_level(lib_level) + + logger_name = "libav." + name if name else "libav.generic" + logger = logging.getLogger(logger_name) + logger.log(py_level, message.strip()) + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def log_callback( + ptr: cython.p_void, + level: cython.int, + format: cython.p_const_char, + args: lib.va_list, +) -> cython.void: + inited: cython.bint = Py_IsInitialized() + if not inited: + return + if level > c_level_threshold and level != lib.AV_LOG_ERROR: + return + + # Format the message. + message: cython.char[1024] + vsnprintf(message, 1023, format, args) + + # Get the name. + name: cython.p_const_char = cython.NULL + cls: cython.pointer[lib.AVClass] = ( + cython.cast(cython.pointer[cython.pointer[lib.AVClass]], ptr)[0] + if ptr + else cython.NULL + ) + if cls and cls.item_name: + name = cls.item_name(ptr) + + with cython.gil: + try: + log_callback_gil(level, name, message) + except Exception: + fprintf( + stderr, + "av.logging: exception while handling %s[%d]: %s\n", + name, + level, + message, + ) + # For some reason PyErr_PrintEx(0) won't work. + exc, type_, tb = sys.exc_info() + PyErr_Display(exc, type_, tb) + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def nolog_callback( + ptr: cython.p_void, + level: cython.int, + format: cython.p_const_char, + args: lib.va_list, +) -> cython.void: + pass + + +lib.av_log_set_callback(nolog_callback) diff --git a/.venv/lib/python3.12/site-packages/av/logging.pyi b/.venv/lib/python3.12/site-packages/av/logging.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6193ad7b8d5c28fad10d139d84fd78e5d5b489ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/logging.pyi @@ -0,0 +1,34 @@ +from collections.abc import Callable +from typing import Any + +PANIC: int +FATAL: int +ERROR: int +WARNING: int +INFO: int +VERBOSE: int +DEBUG: int +TRACE: int +CRITICAL: int + +def adapt_level(level: int) -> int: ... +def get_level() -> int | None: ... +def set_level(level: int | None) -> None: ... +def set_libav_level(level: int) -> None: ... +def restore_default_callback() -> None: ... +def get_skip_repeated() -> bool: ... +def set_skip_repeated(v: bool) -> None: ... +def get_last_error() -> tuple[int, tuple[int, str, str] | None]: ... +def log(level: int, name: str, message: str) -> None: ... + +class Capture: + logs: list[tuple[int, str, str]] + + def __init__(self, local: bool = True) -> None: ... + def __enter__(self) -> list[tuple[int, str, str]]: ... + def __exit__( + self, + type_: type | None, + value: Exception | None, + traceback: Callable[..., Any] | None, + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/opaque.abi3.so b/.venv/lib/python3.12/site-packages/av/opaque.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..00afdaf9e0c1147f0d3f544f712ea544b77da314 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/opaque.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdf6c4f1f87423f1162e672948c720fbb1f538576a5c566a82d836aaa03487ab +size 220081 diff --git a/.venv/lib/python3.12/site-packages/av/opaque.pxd b/.venv/lib/python3.12/site-packages/av/opaque.pxd new file mode 100644 index 0000000000000000000000000000000000000000..998e1339745fc93ab61197bdc8bd03b17905282e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/opaque.pxd @@ -0,0 +1,11 @@ +cimport libav as lib + + +cdef class OpaqueContainer: + cdef dict _objects + cdef lib.AVBufferRef *add(self, object v) + cdef object get(self, char *name) + cdef object pop(self, char *name) + + +cdef OpaqueContainer opaque_container diff --git a/.venv/lib/python3.12/site-packages/av/opaque.py b/.venv/lib/python3.12/site-packages/av/opaque.py new file mode 100644 index 0000000000000000000000000000000000000000..28103325886afd8ec4e97b51e14df32be60ead00 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/opaque.py @@ -0,0 +1,58 @@ +# type:ignore +import cython +import cython.cimports.libav as lib +from cython import NULL, sizeof +from cython.cimports.libc.stdint import uint8_t, uintptr_t +from cython.cimports.libc.string import memcpy + +u8ptr = cython.typedef(cython.pointer[uint8_t]) + + +@cython.cfunc +@cython.exceptval(check=False) +@cython.nogil +def key_free(opaque: cython.p_void, data: u8ptr) -> cython.void: + name: cython.p_char = cython.cast(cython.p_char, data) + with cython.gil: + opaque_container.pop(name) + lib.av_free(data) + + +@cython.final +@cython.cclass +class OpaqueContainer: + def __cinit__(self): + self._objects = {} + + @cython.cfunc + def add(self, v: object) -> cython.pointer[lib.AVBufferRef]: + # Use object's memory address as key + key: uintptr_t = cython.cast(uintptr_t, id(v)) + self._objects[key] = v + + data: u8ptr = cython.cast(u8ptr, lib.av_malloc(sizeof(uintptr_t))) + if data == NULL: + raise MemoryError("Failed to allocate memory for key") + + memcpy(data, cython.address(key), sizeof(uintptr_t)) + + # Create the buffer with our free callback + buffer_ref: cython.pointer[lib.AVBufferRef] = lib.av_buffer_create( + data, sizeof(uintptr_t), key_free, NULL, 0 + ) + + if buffer_ref == NULL: + raise MemoryError("Failed to create AVBufferRef") + + return buffer_ref + + def get(self, name) -> object: + key: uintptr_t = cython.cast(cython.pointer[uintptr_t], name)[0] + return self._objects.get(key) + + def pop(self, name) -> object: + key: uintptr_t = cython.cast(cython.pointer[uintptr_t], name)[0] + return self._objects.pop(key, None) + + +opaque_container = OpaqueContainer() diff --git a/.venv/lib/python3.12/site-packages/av/packet.abi3.so b/.venv/lib/python3.12/site-packages/av/packet.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..d4cb3ca3f8f434bf5207cbb842a877cf708abf92 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/packet.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbae5660ce74bc4f6c2eceb0c042423122a6522598818e0667fef04994f6857e +size 905273 diff --git a/.venv/lib/python3.12/site-packages/av/packet.pxd b/.venv/lib/python3.12/site-packages/av/packet.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1546a1315aa35ae9f2599e9e6f79e4e8cef2e1a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/packet.pxd @@ -0,0 +1,23 @@ +from cython.cimports.libc.stdint import uint8_t + +cimport libav as lib + +from av.buffer cimport Buffer, ByteSource +from av.stream cimport Stream + + +cdef class PacketSideData(Buffer): + cdef uint8_t *data + cdef size_t size + cdef lib.AVPacketSideDataType dtype + + cdef size_t _buffer_size(self) + cdef void* _buffer_ptr(self) + cdef bint _buffer_writable(self) + +cdef class Packet(Buffer): + cdef lib.AVPacket* ptr + cdef Stream _stream + cdef _rebase_time(self, lib.AVRational) + cdef size_t _buffer_size(self) + cdef void* _buffer_ptr(self) diff --git a/.venv/lib/python3.12/site-packages/av/packet.py b/.venv/lib/python3.12/site-packages/av/packet.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb7d4f4c8c41b5348dd970e253903aaba938952 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/packet.py @@ -0,0 +1,517 @@ +from collections.abc import Iterator +from typing import Literal, get_args + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.buffer import Buffer, ByteSource, bytesource +from cython.cimports.av.error import err_check +from cython.cimports.av.opaque import opaque_container +from cython.cimports.av.utils import avrational_to_fraction, to_avrational +from cython.cimports.cpython.ref import Py_DECREF, Py_INCREF +from cython.cimports.libc.stdint import uint8_t +from cython.cimports.libc.string import memcpy + +from av.rational import AVRational + +# Check https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/packet.h#L41 +# for new additions in the future ffmpeg releases +# Note: the order must follow that of the AVPacketSideDataType enum def +PktSideDataT = Literal[ + "palette", + "new_extradata", + "param_change", + "h263_mb_info", + "replay_gain", + "display_matrix", + "stereo_3d", + "audio_service_type", + "quality_stats", + "fallback_track", + "cpb_properties", + "skip_samples", + "jp_dual_mono", + "strings_metadata", + "subtitle_position", + "matroska_block_additional", + "webvtt_identifier", + "webvtt_settings", + "metadata_update", + "mpegts_stream_id", + "mastering_display_metadata", + "spherical", + "content_light_level", + "a53_cc", + "encryption_init_info", + "encryption_info", + "afd", + "prft", + "icc_profile", + "dovi_conf", + "s12m_timecode", + "dynamic_hdr10_plus", + "iamf_mix_gain_param", + "iamf_info_param", + "iamf_recon_gain_info_param", + "ambient_viewing_environment", + "frame_cropping", + "lcevc", + "3d_reference_displays", + "rtcp_sr", +] + + +def packet_sidedata_type_to_literal(dtype: lib.AVPacketSideDataType) -> PktSideDataT: + return get_args(PktSideDataT)[cython.cast(int, dtype)] + + +def packet_sidedata_type_from_literal(dtype: PktSideDataT) -> lib.AVPacketSideDataType: + return get_args(PktSideDataT).index(dtype) + + +@cython.final +@cython.cclass +class PacketSideData(Buffer): + @staticmethod + def from_packet(packet: Packet, data_type: PktSideDataT) -> PacketSideData: + """create new PacketSideData by copying an existing packet's side data + + :param packet: Source packet + :type packet: :class:`~av.packet.Packet` + :param data_type: side data type + :return: newly created copy of the side data if the side data of the + requested type is found in the packet, else an empty object + :rtype: :class:`~av.packet.PacketSideData` + """ + + dtype = packet_sidedata_type_from_literal(data_type) + return _packet_sidedata_from_packet(packet.ptr, dtype) + + def __cinit__(self, dtype: lib.AVPacketSideDataType, size: cython.size_t): + self.dtype = dtype + with cython.nogil: + if size: + self.data = cython.cast(cython.p_uchar, lib.av_malloc(size)) + if self.data == cython.NULL: + raise MemoryError("Failed to allocate memory") + else: + self.data = cython.NULL + self.size = size + + def __dealloc__(self): + with cython.nogil: + lib.av_freep(cython.address(self.data)) + + def to_packet(self, packet: Packet, move: cython.bint = False): + """copy or move side data to the specified packet + + :param packet: Target packet + :type packet: :class:`~av.packet.Packet` + :param move: True to move the data from this object to the packet, + defaults to False. + :type move: bool + """ + if self.size == 0: + # nothing to add, should clear existing side_data in packet? + return + + data = self.data + + with cython.nogil: + if not move: + data = cython.cast(cython.p_uchar, lib.av_malloc(self.size)) + if data == cython.NULL: + raise MemoryError("Failed to allocate memory") + memcpy(data, self.data, self.size) + + res = lib.av_packet_add_side_data(packet.ptr, self.dtype, data, self.size) + err_check(res) + + if move: + self.data = cython.NULL + self.size = 0 + + @property + def data_type(self) -> str: + """ + The type of this packet side data. + + :type: str + """ + return packet_sidedata_type_to_literal(self.dtype) + + @property + def data_desc(self) -> str: + """ + The description of this packet side data type. + + :type: str + """ + + return lib.av_packet_side_data_name(self.dtype) + + @property + def data_size(self) -> int: + """ + The size in bytes of this packet side data. + + :type: int + """ + return self.size + + # Buffer protocol implementation + @cython.cfunc + def _buffer_size(self) -> cython.size_t: + return self.size + + @cython.cfunc + def _buffer_ptr(self) -> cython.p_void: + return self.data + + @cython.cfunc + def _buffer_writable(self) -> cython.bint: + return True + + def __bool__(self) -> bool: + """ + True if this object holds side data. + + :type: bool + """ + return self.data != cython.NULL + + +@cython.cfunc +def _packet_sidedata_from_packet( + packet: cython.pointer[lib.AVPacket], dtype: lib.AVPacketSideDataType +) -> PacketSideData: + with cython.nogil: + c_ptr = lib.av_packet_side_data_get( + packet.side_data, packet.side_data_elems, dtype + ) + found: cython.bint = c_ptr != cython.NULL + + sdata = PacketSideData(dtype, c_ptr.size if found else 0) + + with cython.nogil: + if found: + memcpy(sdata.data, c_ptr.data, c_ptr.size) + + return sdata + + +@cython.cfunc +@cython.nogil +@cython.exceptval(check=False) +def _python_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)) + + +@cython.final +@cython.cclass +class Packet(Buffer): + """A packet of encoded data within a :class:`~av.format.Stream`. + + This may, or may not include a complete object within a stream. + :meth:`decode` must be called to extract encoded data. + """ + + def __cinit__(self, input=None): + with cython.nogil: + self.ptr = lib.av_packet_alloc() + + def __dealloc__(self): + with cython.nogil: + lib.av_packet_free(cython.address(self.ptr)) + + def __init__(self, input=None): + size: cython.size_t = 0 + source: ByteSource = None + buf: cython.pointer[lib.AVBufferRef] + + if input is None: + return + + if isinstance(input, int): + size = input + if size: + err_check(lib.av_new_packet(self.ptr, cython.cast(cython.int, size))) + else: + source = bytesource(input) + size = source.length + if size: + # Create a buffer that references the source data directly. + Py_INCREF(source) + buf = lib.av_buffer_create( + source.ptr, + size, + _python_free, + cython.cast(cython.p_void, source), + 0, + ) + if buf == cython.NULL: + Py_DECREF(source) + raise MemoryError("Could not allocate AVBufferRef") + self.ptr.buf = buf + self.ptr.data = source.ptr + self.ptr.size = cython.cast(cython.int, size) + + def __repr__(self): + stream = self._stream.index if self._stream else 0 + return ( + f"av.{self.__class__.__name__} of #{stream}, dts={self.dts}," + f" pts={self.pts}; {self.ptr.size} bytes at 0x{id(self):x}>" + ) + + # Buffer protocol. + @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 _rebase_time(self, dst: lib.AVRational): + if not dst.num: + raise ValueError("Cannot rebase to zero time.") + + if not self.ptr.time_base.num: + self.ptr.time_base = dst + return + + if self.ptr.time_base.num == dst.num and self.ptr.time_base.den == dst.den: + return + + lib.av_packet_rescale_ts(self.ptr, self.ptr.time_base, dst) + self.ptr.time_base = dst + + def rescale_ts(self, time_base): + """Rescale the packet timestamps to a new time base. + + This rescales :attr:`pts`, :attr:`dts`, and :attr:`duration`, then updates + :attr:`time_base`. If the current time base is unset, the timestamp values + are unchanged and the new time base is assigned. + + :meth:`~av.container.OutputContainer.mux` already performs this operation + automatically when necessary. + + Wraps :ffmpeg:`av_packet_rescale_ts`. + """ + if not isinstance(time_base, AVRational): + raise TypeError("time_base must be an AVRational") + + dst: lib.AVRational + to_avrational(time_base, cython.address(dst)) + self._rebase_time(dst) + + def decode(self): + """ + Send the packet's data to the decoder and return a list of + :class:`.AudioFrame`, :class:`.VideoFrame` or :class:`.SubtitleSet`. + """ + return self._stream.decode(self) + + @property + def stream_index(self): + return self.ptr.stream_index + + @property + def stream(self): + """ + The :class:`Stream` this packet was demuxed from. + """ + return self._stream + + @stream.setter + def stream(self, stream: Stream): + self._stream = stream + self.ptr.stream_index = stream.ptr.index + + @property + def time_base(self): + """ + The unit of time (in fractional seconds) in which timestamps are expressed. + + :type: fractions.Fraction + """ + return avrational_to_fraction(cython.address(self.ptr.time_base)) + + @time_base.setter + def time_base(self, value): + to_avrational(value, cython.address(self.ptr.time_base)) + + @property + def pts(self): + """ + The presentation timestamp in :attr:`time_base` units for this packet. + + This is the time at which the packet should be shown to the user. + + :type: int | None + """ + if self.ptr.pts != lib.AV_NOPTS_VALUE: + return self.ptr.pts + + @pts.setter + def pts(self, v): + if v is None: + self.ptr.pts = lib.AV_NOPTS_VALUE + else: + self.ptr.pts = v + + @property + def dts(self): + """ + The decoding timestamp in :attr:`time_base` units for this packet. + + :type: int | None + """ + if self.ptr.dts != lib.AV_NOPTS_VALUE: + return self.ptr.dts + + @dts.setter + def dts(self, v): + if v is None: + self.ptr.dts = lib.AV_NOPTS_VALUE + else: + self.ptr.dts = v + + @property + def pos(self): + """ + The byte position of this packet within the :class:`.Stream`. + + Returns `None` if it is not known. + + :type: int | None + """ + if self.ptr.pos != -1: + return self.ptr.pos + + @property + def size(self): + """ + The size in bytes of this packet's data. + + :type: int + """ + return self.ptr.size + + @property + def duration(self): + """ + The duration in :attr:`time_base` units for this packet. + + Returns `None` if it is not known. + + :type: int + """ + if self.ptr.duration != lib.AV_NOPTS_VALUE: + return self.ptr.duration + + @duration.setter + def duration(self, v): + if v is None: + self.ptr.duration = lib.AV_NOPTS_VALUE + else: + self.ptr.duration = v + + @property + def is_keyframe(self): + return bool(self.ptr.flags & lib.AV_PKT_FLAG_KEY) + + @is_keyframe.setter + def is_keyframe(self, v): + if v: + self.ptr.flags |= lib.AV_PKT_FLAG_KEY + else: + self.ptr.flags &= ~(lib.AV_PKT_FLAG_KEY) + + @property + def is_corrupt(self): + return bool(self.ptr.flags & lib.AV_PKT_FLAG_CORRUPT) + + @is_corrupt.setter + def is_corrupt(self, v): + if v: + self.ptr.flags |= lib.AV_PKT_FLAG_CORRUPT + else: + self.ptr.flags &= ~(lib.AV_PKT_FLAG_CORRUPT) + + @property + def is_discard(self): + return bool(self.ptr.flags & lib.AV_PKT_FLAG_DISCARD) + + @property + def is_trusted(self): + return bool(self.ptr.flags & lib.AV_PKT_FLAG_TRUSTED) + + @property + def is_disposable(self): + return bool(self.ptr.flags & lib.AV_PKT_FLAG_DISPOSABLE) + + @property + def opaque(self): + if self.ptr.opaque_ref is not cython.NULL: + return opaque_container.get( + cython.cast(cython.p_char, self.ptr.opaque_ref.data) + ) + + @opaque.setter + def opaque(self, v): + lib.av_buffer_unref(cython.address(self.ptr.opaque_ref)) + + if v is None: + return + self.ptr.opaque_ref = opaque_container.add(v) + + def has_sidedata(self, dtype: str) -> bool: + """True if this packet has the specified side data + + :param dtype: side data type + :type dtype: str + """ + + dtype2 = packet_sidedata_type_from_literal(dtype) + return ( + lib.av_packet_side_data_get( + self.ptr.side_data, self.ptr.side_data_elems, dtype2 + ) + != cython.NULL + ) + + def get_sidedata(self, dtype: str) -> PacketSideData: + """get a copy of the side data + + :param dtype: side data type (:meth:`~av.packet.PacketSideData.sidedata_types` for the full list of options) + :type dtype: str + :return: newly created copy of the side data if the side data of the + requested type is found in the packet, else an empty object + :rtype: :class:`~av.packet.PacketSideData` + """ + return PacketSideData.from_packet(self, dtype) + + def set_sidedata(self, sidedata: PacketSideData, move: cython.bint = False): + """copy or move side data to this packet + + :param sidedata: Source packet side data + :type sidedata: :class:`~av.packet.PacketSideData` + :param move: If True, move the data from `sidedata` object, defaults to False + :type move: bool + """ + sidedata.to_packet(self, move) + + def iter_sidedata(self) -> Iterator[PacketSideData]: + """iterate over side data of this packet. + + :yield: :class:`~av.packet.PacketSideData` object + """ + + for i in range(self.ptr.side_data_elems): + yield _packet_sidedata_from_packet(self.ptr, self.ptr.side_data[i].type) diff --git a/.venv/lib/python3.12/site-packages/av/packet.pyi b/.venv/lib/python3.12/site-packages/av/packet.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1f005bf27be36d0fff89aed0a000a5f1e586dae6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/packet.pyi @@ -0,0 +1,114 @@ +from collections.abc import Iterator +from fractions import Fraction +from typing import Generic, Literal, TypeVar, overload + +from av.audio.frame import AudioFrame +from av.audio.stream import AudioStream +from av.rational import AVRational +from av.stream import Stream +from av.subtitles.stream import SubtitleStream +from av.subtitles.subtitle import AssSubtitle, BitmapSubtitle +from av.video.frame import VideoFrame +from av.video.stream import VideoStream + +from .buffer import Buffer +from .stream import Stream + +# Sync with definition in 'packet.py' +PktSideDataT = Literal[ + "palette", + "new_extradata", + "param_change", + "h263_mb_info", + "replay_gain", + "display_matrix", + "stereo_3d", + "audio_service_type", + "quality_stats", + "fallback_track", + "cpb_properties", + "skip_samples", + "jp_dual_mono", + "strings_metadata", + "subtitle_position", + "matroska_block_additional", + "webvtt_identifier", + "webvtt_settings", + "metadata_update", + "mpegts_stream_id", + "mastering_display_metadata", + "spherical", + "content_light_level", + "a53_cc", + "encryption_init_info", + "encryption_info", + "afd", + "prft", + "icc_profile", + "dovi_conf", + "s12m_timecode", + "dynamic_hdr10_plus", + "iamf_mix_gain_param", + "iamf_info_param", + "iamf_recon_gain_info_param", + "ambient_viewing_environment", + "frame_cropping", + "lcevc", + "3d_reference_displays", + "rtcp_sr", +] + +class PacketSideData(Buffer): + @staticmethod + def from_packet(packet: Packet[Stream], dtype: PktSideDataT) -> PacketSideData: ... + def to_packet(self, packet: Packet[Stream], move: bool = False): ... + @property + def data_type(self) -> str: ... + @property + def data_desc(self) -> str: ... + @property + def data_size(self) -> int: ... + def __bool__(self) -> bool: ... + +def packet_sidedata_type_to_literal(dtype: int) -> PktSideDataT: ... +def packet_sidedata_type_from_literal(dtype: PktSideDataT) -> int: ... + +# TypeVar for stream types - bound to Stream so it can be any stream type +StreamT = TypeVar("StreamT", bound=Stream) + +class Packet(Buffer, Generic[StreamT]): + stream: StreamT + stream_index: int + time_base: Fraction + pts: int | None + dts: int | None + pos: int | None + size: int + duration: int | None + opaque: object + is_keyframe: bool + is_corrupt: bool + is_discard: bool + is_trusted: bool + is_disposable: bool + + def __init__(self: Packet[Stream], input: int | bytes | None = None) -> None: ... + def rescale_ts(self, time_base: AVRational) -> None: ... + + # Overloads that return the same type as the stream's decode method + @overload + def decode(self: Packet[VideoStream]) -> list[VideoFrame]: ... + @overload + def decode(self: Packet[AudioStream]) -> list[AudioFrame]: ... + @overload + def decode( + self: Packet[SubtitleStream], + ) -> list[AssSubtitle] | list[BitmapSubtitle]: ... + @overload + def decode( + self, + ) -> list[VideoFrame | AudioFrame | AssSubtitle | BitmapSubtitle]: ... + def has_sidedata(self, dtype: PktSideDataT) -> bool: ... + def get_sidedata(self, dtype: PktSideDataT) -> PacketSideData: ... + def set_sidedata(self, sidedata: PacketSideData, move: bool = False) -> None: ... + def iter_sidedata(self) -> Iterator[PacketSideData]: ... diff --git a/.venv/lib/python3.12/site-packages/av/plane.abi3.so b/.venv/lib/python3.12/site-packages/av/plane.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..eb6abbbcc703200670efdae19654f46c00765eec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/plane.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6afad19d4879dba3f50d570bacf2833e0d303a5bb276b31da735a85e8ab6676c +size 297817 diff --git a/.venv/lib/python3.12/site-packages/av/plane.pxd b/.venv/lib/python3.12/site-packages/av/plane.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2066bfea89d6214dcaaee80ee0c54773ccb05976 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/plane.pxd @@ -0,0 +1,9 @@ +from av.buffer cimport Buffer +from av.frame cimport Frame + + +cdef class Plane(Buffer): + cdef Frame frame + cdef int index + cdef size_t _buffer_size(self) + cdef void* _buffer_ptr(self) diff --git a/.venv/lib/python3.12/site-packages/av/plane.py b/.venv/lib/python3.12/site-packages/av/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..f84a99c3da2eb487be3fb180f8a0051851ac0281 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/plane.py @@ -0,0 +1,24 @@ +import cython + + +@cython.cclass +class Plane(Buffer): + """ + Base class for audio and video planes. + + See also :class:`~av.audio.plane.AudioPlane` and :class:`~av.video.plane.VideoPlane`. + """ + + def __cinit__(self, frame: Frame, index: cython.int): + self.frame = frame + self.index = index + + def __repr__(self): + return ( + f"" + ) + + @cython.cfunc + def _buffer_ptr(self) -> cython.p_void: + return self.frame.ptr.extended_data[self.index] diff --git a/.venv/lib/python3.12/site-packages/av/plane.pyi b/.venv/lib/python3.12/site-packages/av/plane.pyi new file mode 100644 index 0000000000000000000000000000000000000000..99594d11a23d021fb0181b6bfe5ecc1bcbc43c1b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/plane.pyi @@ -0,0 +1,8 @@ +from .buffer import Buffer +from .frame import Frame + +class Plane(Buffer): + frame: Frame + index: int + + def __init__(self, frame: Frame, index: int) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/av/py.typed b/.venv/lib/python3.12/site-packages/av/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/rational.abi3.so b/.venv/lib/python3.12/site-packages/av/rational.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..50342429447824e9f5015011a9c91652c110d987 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/rational.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16c5b959d0d6a57c1f6e9487a51bd8b7c7b1ec354db0b4d8bb0577d05997ec90 +size 519337 diff --git a/.venv/lib/python3.12/site-packages/av/rational.pxd b/.venv/lib/python3.12/site-packages/av/rational.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a416fea4963a907d1c0709a21d9822f6cf473330 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/rational.pxd @@ -0,0 +1,11 @@ +cimport libav as lib + + +cdef class AVRational: + cdef readonly int num + cdef readonly int den + + cdef lib.AVRational _q(self) + + +cdef AVRational from_avrational(lib.AVRational q) diff --git a/.venv/lib/python3.12/site-packages/av/rational.py b/.venv/lib/python3.12/site-packages/av/rational.py new file mode 100644 index 0000000000000000000000000000000000000000..87ce7ade983a09970e79f5d85f583be28f031cc0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/rational.py @@ -0,0 +1,156 @@ +# type: ignore +from fractions import Fraction +from numbers import Rational + +import cython +from cython.cimports import libav as lib + +_INT32_MAX: cython.longlong = 2147483647 + + +@cython.cclass +class AVRational: + """ + An exact rational number stored as two int32s, mirroring FFmpeg's + ``AVRational``. + + Values are always reduced to lowest terms with a positive denominator. + Arithmetic between two :class:`AVRational` uses FFmpeg's ``av_mul_q`` + family: intermediates are computed in int64, then reduced back to int32, + **approximating** the result if it does not fit. Arithmetic with other + numeric types promotes to :class:`fractions.Fraction` (exact). + + Following FFmpeg, a zero denominator is allowed: ``1/0``, ``-1/0`` + (infinities) and ``0/0`` (undefined) exist and, like the unset value + ``AVRational(0, 1)``, are falsy — so ``if rate:`` covers every + not-a-real-value case that used to be ``None``. + + Every PyAV setter that accepts a :class:`fractions.Fraction` (e.g. + ``stream.time_base``, ``codec_context.framerate``) also accepts an + :class:`AVRational`. + """ + + def __init__(self, num=0, den=1): + if den == 1 and isinstance(num, Rational): + num, den = num.numerator, num.denominator + n64: cython.longlong = num + d64: cython.longlong = den + n: cython.int + d: cython.int + if not lib.av_reduce( + cython.address(n), cython.address(d), n64, d64, _INT32_MAX + ): + raise OverflowError(f"{num}/{den} cannot be reduced to fit in int32") + self.num = n + self.den = d + + @cython.cfunc + def _q(self) -> lib.AVRational: + q: lib.AVRational + q.num = self.num + q.den = self.den + return q + + @property + def numerator(self): + return self.num + + @property + def denominator(self): + return self.den + + def __repr__(self): + return f"AVRational({self.num}, {self.den})" + + def __str__(self): + return f"{self.num}/{self.den}" + + def __bool__(self): + return self.num != 0 and self.den != 0 + + def __float__(self): + if self.den == 0: + return float("nan") if self.num == 0 else self.num * float("inf") + return self.num / self.den + + def __hash__(self): + if self.den == 0: + return hash((self.num, 0)) + return hash(Fraction(self.num, self.den)) + + def __reduce__(self): + return (AVRational, (self.num, self.den)) + + def __eq__(self, other): + if isinstance(other, AVRational): + o: AVRational = other + return self.num == o.num and self.den == o.den + if self.den == 0: + return False + return Fraction(self.num, self.den) == other + + def __lt__(self, other): + return Fraction(self.num, self.den) < other + + def __le__(self, other): + return Fraction(self.num, self.den) <= other + + def __gt__(self, other): + return Fraction(self.num, self.den) > other + + def __ge__(self, other): + return Fraction(self.num, self.den) >= other + + def __neg__(self): + return AVRational(-self.num, self.den) + + def __mul__(self, other): + if isinstance(other, AVRational): + o: AVRational = other + return from_avrational(lib.av_mul_q(self._q(), o._q())) + return Fraction(self.num, self.den) * other + + def __rmul__(self, other): + return other * Fraction(self.num, self.den) + + def __truediv__(self, other): + if isinstance(other, AVRational): + o: AVRational = other + if o.num == 0: + raise ZeroDivisionError(f"{self} / {other}") + return from_avrational(lib.av_div_q(self._q(), o._q())) + return Fraction(self.num, self.den) / other + + def __rtruediv__(self, other): + return other / Fraction(self.num, self.den) + + def __add__(self, other): + if isinstance(other, AVRational): + o: AVRational = other + return from_avrational(lib.av_add_q(self._q(), o._q())) + return Fraction(self.num, self.den) + other + + def __radd__(self, other): + return other + Fraction(self.num, self.den) + + def __sub__(self, other): + if isinstance(other, AVRational): + o: AVRational = other + return from_avrational(lib.av_sub_q(self._q(), o._q())) + return Fraction(self.num, self.den) - other + + def __rsub__(self, other): + return other - Fraction(self.num, self.den) + + +@cython.cfunc +def from_avrational(q: lib.AVRational) -> AVRational: + obj: AVRational = AVRational.__new__(AVRational) + # FFmpeg does not guarantee reduced form; our invariant requires it. + lib.av_reduce( + cython.address(obj.num), cython.address(obj.den), q.num, q.den, _INT32_MAX + ) + return obj + + +Rational.register(AVRational) diff --git a/.venv/lib/python3.12/site-packages/av/rational.pyi b/.venv/lib/python3.12/site-packages/av/rational.pyi new file mode 100644 index 0000000000000000000000000000000000000000..12716ca04c0500944947dd182a6267492a052fdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/rational.pyi @@ -0,0 +1,29 @@ +from fractions import Fraction +from numbers import Rational +from typing import Any + +class AVRational: + num: int + den: int + def __init__(self, num: int | Rational = 0, den: int = 1) -> None: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def __bool__(self) -> bool: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __eq__(self, other: Any) -> bool: ... + def __lt__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... + def __neg__(self) -> AVRational: ... + def __mul__(self, other: Any) -> AVRational | Fraction | float: ... + def __rmul__(self, other: Any) -> Fraction | float: ... + def __truediv__(self, other: Any) -> AVRational | Fraction | float: ... + def __rtruediv__(self, other: Any) -> Fraction | float: ... + def __add__(self, other: Any) -> AVRational | Fraction | float: ... + def __radd__(self, other: Any) -> Fraction | float: ... + def __sub__(self, other: Any) -> AVRational | Fraction | float: ... + def __rsub__(self, other: Any) -> Fraction | float: ... diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/__init__.pxd b/.venv/lib/python3.12/site-packages/av/sidedata/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/__init__.py b/.venv/lib/python3.12/site-packages/av/sidedata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2de01d879b2a548fe9278bbdf26c4f91eb34f568 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/encparams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/encparams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0dabb0c5c6bc4414587e333bdf28d043bfa358f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/encparams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/motionvectors.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/motionvectors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca26359f8c494d7bb99744488fa8404469d8e51a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/motionvectors.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/sidedata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/sidedata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6b40323df740c46f58235407b77000812ed3893 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/av/sidedata/__pycache__/sidedata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/encparams.abi3.so b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..270d8ee2ef90168f81410e606715b1e4303619aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:868d77195b376005bf6ca40944eedd8c903d0cb3ab680cefe400bd88c8ae38e2 +size 511201 diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/encparams.pxd b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.pxd new file mode 100644 index 0000000000000000000000000000000000000000..031b59a421978dfa21091ffa19d97dec91f1dec5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.pxd @@ -0,0 +1,11 @@ +cimport libav as lib + +from av.sidedata.sidedata cimport SideData + + +cdef class VideoEncParams(SideData): + pass + + +cdef class VideoBlockParams: + cdef lib.AVVideoBlockParams *ptr diff --git a/.venv/lib/python3.12/site-packages/av/sidedata/encparams.py b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e78e8a126d20cabdb1970a9f3b6dc6b50089c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/av/sidedata/encparams.py @@ -0,0 +1,186 @@ +from enum import IntEnum + +import cython +from cython.cimports import libav as lib +from cython.cimports.av.sidedata.sidedata import SideData +from cython.cimports.libc.stdint import uint8_t + + +class VideoEncParamsType(IntEnum): + NONE = lib.AV_VIDEO_ENC_PARAMS_NONE + VP9 = lib.AV_VIDEO_ENC_PARAMS_VP9 + H264 = lib.AV_VIDEO_ENC_PARAMS_H264 + MPEG2 = lib.AV_VIDEO_ENC_PARAMS_MPEG2 + + +@cython.final +@cython.cclass +class VideoEncParams(SideData): + def __repr__(self): + return f"" + + @property + def nb_blocks(self): + """ + Number of blocks in the array + May be 0, in which case no per-block information is present. In this case + the values of blocks_offset / block_size are unspecified and should not + be accessed. + """ + return cython.cast( + cython.pointer[lib.AVVideoEncParams], self.ptr.data + ).nb_blocks + + @property + def blocks_offset(self): + """ + Offset in bytes from the beginning of this structure at which the array of blocks starts. + """ + return cython.cast( + cython.pointer[lib.AVVideoEncParams], self.ptr.data + ).blocks_offset + + @property + def block_size(self): + """ + Size of each block in bytes. May not match sizeof(AVVideoBlockParams). + """ + return cython.cast( + cython.pointer[lib.AVVideoEncParams], self.ptr.data + ).block_size + + @property + def codec_type(self): + """ + Type of the parameters (the codec they are used with). + """ + t: lib.AVVideoEncParamsType = cython.cast( + cython.pointer[lib.AVVideoEncParams], self.ptr.data + ).type + return VideoEncParamsType(cython.cast(cython.int, t)) + + @property + def qp(self): + """ + Base quantisation parameter for the frame. The final quantiser for a + given block in a given plane is obtained from this value, possibly + combined with `delta_qp` and the per-block delta in a manner + documented for each type. + """ + return cython.cast(cython.pointer[lib.AVVideoEncParams], self.ptr.data).qp + + @property + def delta_qp(self): + """ + Quantisation parameter offset from the base (per-frame) qp for a given + plane (first index) and AC/DC coefficients (second index). + """ + p: cython.pointer[lib.AVVideoEncParams] = cython.cast( + cython.pointer[lib.AVVideoEncParams], self.ptr.data + ) + return [[p.delta_qp[i][j] for j in range(2)] for i in range(4)] + + def block_params(self, idx): + """ + Get the encoding parameters for a given block + """ + # Validate given index + if idx < 0 or idx >= self.nb_blocks: + raise ValueError("Expected idx in range [0, nb_blocks)") + + return VideoBlockParams(self, idx) + + def qp_map(self): + """ + Convenience method that creates a 2-D map with the quantization parameters per macroblock. + Only for MPEG2 and H264 encoded videos. + """ + import numpy as np + + mb_h: cython.int = (self.frame.ptr.height + 15) // 16 + mb_w: cython.int = (self.frame.ptr.width + 15) // 16 + nb_mb: cython.int = mb_h * mb_w + block_idx, x, y = cython.declare(cython.int) + block: VideoBlockParams + + if self.nb_blocks != nb_mb: + raise RuntimeError( + "Expected frame size to match number of blocks in side data" + ) + + type: lib.AVVideoEncParamsType = cython.cast( + cython.pointer[lib.AVVideoEncParams], self.ptr.data + ).type + if ( + type != lib.AVVideoEncParamsType.AV_VIDEO_ENC_PARAMS_MPEG2 + and type != lib.AVVideoEncParamsType.AV_VIDEO_ENC_PARAMS_H264 + ): + raise ValueError("Expected MPEG2 or H264") + + # Create a 2-D map with the number of macroblocks + map = np.empty((mb_h, mb_w), dtype=np.int32) + + # Fill map with quantization parameter per macroblock + for block_idx in range(nb_mb): + block = VideoBlockParams(self, block_idx) + y = block.src_y // 16 + x = block.src_x // 16 + map[y, x] = self.qp + block.delta_qp + + return map + + +@cython.final +@cython.cclass +class VideoBlockParams: + def __init__(self, video_enc_params: VideoEncParams, idx: cython.int) -> None: + base: cython.pointer[uint8_t] = cython.cast( + cython.pointer[uint8_t], video_enc_params.ptr.data + ) + offset: cython.Py_ssize_t = ( + video_enc_params.blocks_offset + idx * video_enc_params.block_size + ) + self.ptr = cython.cast(cython.pointer[lib.AVVideoBlockParams], base + offset) + + def __repr__(self): + return f"" + + @property + def src_x(self): + """ + Horizontal distance in luma pixels from the top-left corner of the visible frame + to the top-left corner of the block. + Can be negative if top/right padding is present on the coded frame. + """ + return self.ptr.src_x + + @property + def src_y(self): + """ + Vertical distance in luma pixels from the top-left corner of the visible frame + to the top-left corner of the block. + Can be negative if top/right padding is present on the coded frame. + """ + return self.ptr.src_y + + @property + def w(self): + """ + Width of the block in luma pixels + """ + return self.ptr.w + + @property + def h(self): + """ + Height of the block in luma pixels + """ + return self.ptr.h + + @property + def delta_qp(self): + """ + Difference between this block's final quantization parameter and the + corresponding per-frame value. + """ + return self.ptr.delta_qp