| 1 |
import cython |
| 2 |
from cython.cimports.av.audio.stream import AudioStream |
| 3 |
from cython.cimports.av.container.core import Container |
| 4 |
from cython.cimports.libc.stdlib import free |
| 5 |
|
| 6 |
from av.logging import get_level, set_level |
| 7 |
|
| 8 |
|
| 9 |
@cython.ccall |
| 10 |
def stats(loudnorm_args: str, stream: AudioStream) -> bytes: |
| 11 |
""" |
| 12 |
Get loudnorm statistics for an audio stream. |
| 13 |
|
| 14 |
Args: |
| 15 |
loudnorm_args (str): Arguments for the loudnorm filter (e.g. "i=-24.0:lra=7.0:tp=-2.0") |
| 16 |
stream (AudioStream): Input audio stream to analyze |
| 17 |
|
| 18 |
Returns: |
| 19 |
bytes: JSON string containing the loudnorm statistics |
| 20 |
""" |
| 21 |
|
| 22 |
if "print_format=json" not in loudnorm_args: |
| 23 |
loudnorm_args = loudnorm_args + ":print_format=json" |
| 24 |
|
| 25 |
container: Container = stream.container |
| 26 |
format_ptr: cython.pointer[AVFormatContext] = container.ptr |
| 27 |
container.ptr = cython.NULL # Prevent double-free |
| 28 |
|
| 29 |
stream_index: cython.int = stream.index |
| 30 |
py_args: bytes = loudnorm_args.encode("utf-8") |
| 31 |
c_args: cython.p_const_char = py_args |
| 32 |
result: cython.p_char |
| 33 |
|
| 34 |
# Save log level since C function overwrite it. |
| 35 |
level = get_level() |
| 36 |
|
| 37 |
with cython.nogil: |
| 38 |
result = loudnorm_get_stats(format_ptr, stream_index, c_args) |
| 39 |
|
| 40 |
if result == cython.NULL: |
| 41 |
raise RuntimeError("Failed to get loudnorm stats") |
| 42 |
|
| 43 |
py_result = result[:] # Make a copy of the string |
| 44 |
free(result) # Free the C string |
| 45 |
|
| 46 |
set_level(level) |
| 47 |
|
| 48 |
return py_result |