Debian Codegraph @

av/audio/frame.py

raw
1 import cython
2 from cython.cimports.av.audio.format import get_audio_format
3 from cython.cimports.av.audio.layout import get_audio_layout
4 from cython.cimports.av.audio.plane import AudioPlane
5 from cython.cimports.av.error import err_check
6 from cython.cimports.av.utils import check_ndarray
7
8 _cinit_bypass_sentinel = cython.declare(object, object())
9
10
11 @cython.cfunc
12 def alloc_audio_frame() -> AudioFrame:
13 return AudioFrame(_cinit_bypass_sentinel)
14
15
16 format_dtypes = {
17 "dbl": "f8",
18 "dblp": "f8",
19 "flt": "f4",
20 "fltp": "f4",
21 "s16": "i2",
22 "s16p": "i2",
23 "s32": "i4",
24 "s32p": "i4",
25 "u8": "u1",
26 "u8p": "u1",
27 }
28
29
30 @cython.final
31 @cython.cclass
32 class AudioFrame(Frame):
33 """A frame of audio."""
34
35 def __cinit__(self, format="s16", layout="stereo", samples=0, align=1):
36 if format is _cinit_bypass_sentinel:
37 return
38
39 cy_format: AudioFormat = AudioFormat(format)
40 cy_layout: AudioLayout = AudioLayout(layout)
41 self._init(cy_format.sample_fmt, cy_layout.layout, samples, align)
42
43 @cython.cfunc
44 def _init(
45 self,
46 format: lib.AVSampleFormat,
47 layout: lib.AVChannelLayout,
48 nb_samples: cython.uint,
49 align: cython.uint,
50 ):
51 self.ptr.nb_samples = nb_samples
52 self.ptr.format = format
53 self.ptr.ch_layout = layout
54
55 # Sometimes this is called twice. Oh well.
56 self._init_user_attributes()
57
58 if self.layout.nb_channels != 0 and nb_samples:
59 # Cleanup the old buffer.
60 lib.av_freep(cython.address(self._buffer))
61
62 # Get a new one.
63 self._buffer_size = err_check(
64 lib.av_samples_get_buffer_size(
65 cython.NULL, self.layout.nb_channels, nb_samples, format, align
66 )
67 )
68 self._buffer = cython.cast(
69 cython.pointer[uint8_t], lib.av_malloc(self._buffer_size)
70 )
71 if not self._buffer:
72 raise MemoryError("cannot allocate AudioFrame buffer")
73
74 # Connect the data pointers to the buffer.
75 err_check(
76 lib.avcodec_fill_audio_frame(
77 self.ptr,
78 self.layout.nb_channels,
79 cython.cast(lib.AVSampleFormat, self.ptr.format),
80 self._buffer,
81 self._buffer_size,
82 align,
83 )
84 )
85
86 def __dealloc__(self):
87 lib.av_freep(cython.address(self._buffer))
88
89 @cython.cfunc
90 def _init_user_attributes(self):
91 self.layout = get_audio_layout(self.ptr.ch_layout)
92 self.format = get_audio_format(cython.cast(lib.AVSampleFormat, self.ptr.format))
93
94 def __repr__(self):
95 return (
96 f"<av.{self.__class__.__name__} pts={self.pts}, {self.samples} "
97 f"samples at {self.rate}Hz, {self.layout.name}, {self.format.name} at 0x{id(self):x}>"
98 )
99
100 @staticmethod
101 def from_ndarray(array, format="s16", layout="stereo"):
102 """
103 Construct a frame from a numpy array.
104 """
105 import numpy as np
106
107 py_format = format if isinstance(format, AudioFormat) else AudioFormat(format)
108 py_layout = layout if isinstance(layout, AudioLayout) else AudioLayout(layout)
109 format = py_format.name
110
111 # map avcodec type to numpy type
112 try:
113 dtype = np.dtype(format_dtypes[format])
114 except KeyError:
115 raise ValueError(
116 f"Conversion from numpy array with format `{format}` is not yet supported"
117 )
118
119 # check input format
120 nb_channels = py_layout.nb_channels
121 check_ndarray(array, dtype, 2)
122 if py_format.is_planar:
123 if array.shape[0] != nb_channels:
124 raise ValueError(
125 f"Expected planar `array.shape[0]` to equal `{nb_channels}` but got `{array.shape[0]}`"
126 )
127 samples = array.shape[1]
128 else:
129 if array.shape[0] != 1:
130 raise ValueError(
131 f"Expected packed `array.shape[0]` to equal `1` but got `{array.shape[0]}`"
132 )
133 samples = array.shape[1] // nb_channels
134
135 frame = AudioFrame(format=py_format, layout=py_layout, samples=samples)
136 for i, plane in enumerate(frame.planes):
137 plane.update(array[i, :])
138 return frame
139
140 @property
141 def planes(self):
142 """
143 A tuple of :class:`~av.audio.plane.AudioPlane`.
144
145 :type: tuple
146 """
147 plane_count: cython.int = 0
148 while self.ptr.extended_data[plane_count]:
149 plane_count += 1
150
151 return tuple([AudioPlane(self, i) for i in range(plane_count)])
152
153 @property
154 def samples(self):
155 """
156 Number of audio samples (per channel).
157
158 :type: int
159 """
160 return self.ptr.nb_samples
161
162 @property
163 def sample_rate(self):
164 """
165 Sample rate of the audio data, in samples per second.
166
167 :type: int
168 """
169 return self.ptr.sample_rate
170
171 @sample_rate.setter
172 def sample_rate(self, value):
173 self.ptr.sample_rate = value
174
175 @property
176 def rate(self):
177 """Another name for :attr:`sample_rate`."""
178 return self.ptr.sample_rate
179
180 @rate.setter
181 def rate(self, value):
182 self.ptr.sample_rate = value
183
184 def to_ndarray(self):
185 """Get a numpy array of this frame.
186
187 .. note:: Numpy must be installed.
188
189 """
190 import numpy as np
191
192 try:
193 dtype = np.dtype(format_dtypes[self.format.name])
194 except KeyError:
195 raise ValueError(
196 f"Conversion from {self.format.name!r} format to numpy array is not supported."
197 )
198
199 if self.format.is_planar:
200 count = self.samples
201 else:
202 count = self.samples * self.layout.nb_channels
203
204 return np.vstack(
205 [np.frombuffer(x, dtype=dtype, count=count) for x in self.planes]
206 )