1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
|
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 = 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.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,
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"<av.{self.__class__.__name__} pts={self.pts}, {self.samples} "
f"samples at {self.rate}Hz, {self.layout.name}, {self.format.name} at 0x{id(self):x}>"
)
@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]
)
|