Debian Codegraph @

av/audio/fifo.py

raw
1 import cython
2 from cython.cimports.av.audio.frame import alloc_audio_frame
3 from cython.cimports.av.error import err_check
4
5
6 @cython.final
7 @cython.cclass
8 class AudioFifo:
9 """A simple audio sample FIFO (First In First Out) buffer."""
10
11 def __repr__(self):
12 try:
13 result = (
14 f"<av.{self.__class__.__name__} {self.samples} samples of "
15 f"{self.sample_rate}hz {self.layout} {self.format} at 0x{id(self):x}>"
16 )
17 except AttributeError:
18 result = (
19 f"<av.{self.__class__.__name__} uninitialized, use fifo.write(frame),"
20 f" at 0x{id(self):x}>"
21 )
22 return result
23
24 def __dealloc__(self):
25 if self.ptr:
26 lib.av_audio_fifo_free(self.ptr)
27
28 @cython.ccall
29 def write(self, frame: AudioFrame | None):
30 """write(frame)
31
32 Push a frame of samples into the queue.
33
34 :param AudioFrame frame: The frame of samples to push.
35
36 The FIFO will remember the attributes from the first frame, and use those
37 to populate all output frames.
38
39 If there is a :attr:`~.Frame.pts` and :attr:`~.Frame.time_base` and
40 :attr:`~.AudioFrame.sample_rate`, then the FIFO will assert that the incoming
41 timestamps are continuous.
42
43 """
44
45 if frame is None:
46 raise TypeError("AudioFifo must be given an AudioFrame.")
47
48 if not frame.ptr.nb_samples:
49 return
50
51 if not self.ptr:
52 # Hold onto a copy of the attributes of the first frame to populate
53 # output frames with.
54 self.template = alloc_audio_frame()
55 self.template._copy_internal_attributes(frame)
56 self.template._init_user_attributes()
57
58 # Figure out our "time_base".
59 if frame._time_base.num and frame.ptr.sample_rate:
60 self.pts_per_sample = frame._time_base.den / float(frame._time_base.num)
61 self.pts_per_sample /= frame.ptr.sample_rate
62 else:
63 self.pts_per_sample = 0
64
65 self.ptr = lib.av_audio_fifo_alloc(
66 cython.cast(lib.AVSampleFormat, frame.ptr.format),
67 frame.layout.nb_channels,
68 frame.ptr.nb_samples
69 * 2, # Just a default number of samples; it will adjust.
70 )
71
72 if not self.ptr:
73 raise RuntimeError("Could not allocate AVAudioFifo.")
74
75 # Make sure nothing changed.
76 elif (
77 frame.ptr.format != self.template.ptr.format
78 or frame.ptr.sample_rate != self.template.ptr.sample_rate
79 or (
80 frame._time_base.num
81 and self.template._time_base.num
82 and (
83 frame._time_base.num != self.template._time_base.num
84 or frame._time_base.den != self.template._time_base.den
85 )
86 )
87 ):
88 raise ValueError("Frame does not match AudioFifo parameters.")
89
90 # Assert that the PTS are what we expect.
91 expected_pts = cython.declare(int64_t)
92 if self.pts_per_sample and frame.ptr.pts != lib.AV_NOPTS_VALUE:
93 expected_pts = cython.cast(
94 int64_t, self.pts_per_sample * self.samples_written
95 )
96 if frame.ptr.pts != expected_pts:
97 raise ValueError(
98 "Frame.pts (%d) != expected (%d); fix or set to None."
99 % (frame.ptr.pts, expected_pts)
100 )
101
102 err_check(
103 lib.av_audio_fifo_write(
104 self.ptr,
105 cython.cast(cython.pointer[cython.p_void], frame.ptr.extended_data),
106 frame.ptr.nb_samples,
107 )
108 )
109
110 self.samples_written += frame.ptr.nb_samples
111
112 @cython.ccall
113 def read(self, samples: cython.int = 0, partial: cython.bint = False):
114 """read(samples=0, partial=False)
115
116 Read samples from the queue.
117
118 :param int samples: The number of samples to pull; 0 gets all.
119 :param bool partial: Allow returning less than requested.
120 :returns: New :class:`AudioFrame` or ``None`` (if empty).
121
122 If the incoming frames had valid a :attr:`~.Frame.time_base`,
123 :attr:`~.AudioFrame.sample_rate` and :attr:`~.Frame.pts`, the returned frames
124 will have accurate timing.
125
126 """
127
128 if not self.ptr:
129 return
130
131 buffered_samples: cython.int = lib.av_audio_fifo_size(self.ptr)
132 if buffered_samples < 1:
133 return
134
135 samples = samples or buffered_samples
136
137 if buffered_samples < samples:
138 if partial:
139 samples = buffered_samples
140 else:
141 return
142
143 frame: AudioFrame = alloc_audio_frame()
144 frame._copy_internal_attributes(self.template)
145 frame._init(
146 cython.cast(lib.AVSampleFormat, self.template.ptr.format),
147 cython.cast(lib.AVChannelLayout, self.template.ptr.ch_layout),
148 samples,
149 1, # Align?
150 )
151
152 err_check(
153 lib.av_audio_fifo_read(
154 self.ptr,
155 cython.cast(cython.pointer[cython.p_void], frame.ptr.extended_data),
156 samples,
157 )
158 )
159
160 if self.pts_per_sample:
161 frame.ptr.pts = cython.cast(
162 uint64_t, self.pts_per_sample * self.samples_read
163 )
164 else:
165 frame.ptr.pts = lib.AV_NOPTS_VALUE
166
167 self.samples_read += samples
168 return frame
169
170 @cython.ccall
171 def read_many(self, samples: cython.int, partial: cython.bint = False):
172 """read_many(samples, partial=False)
173
174 Read as many frames as we can.
175
176 :param int samples: How large for the frames to be.
177 :param bool partial: If we should return a partial frame.
178 :returns: A ``list`` of :class:`AudioFrame`.
179
180 """
181
182 frame: AudioFrame
183 frames: list = []
184 while True:
185 frame = self.read(samples, partial=partial)
186 if frame is not None:
187 frames.append(frame)
188 else:
189 break
190
191 return frames
192
193 @property
194 def format(self):
195 """The :class:`.AudioFormat` of this FIFO."""
196 if not self.ptr:
197 raise AttributeError(
198 f"'{__name__}.AudioFifo' object has no attribute 'format'"
199 )
200 return self.template.format
201
202 @property
203 def layout(self):
204 """The :class:`.AudioLayout` of this FIFO."""
205 if not self.ptr:
206 raise AttributeError(
207 f"'{__name__}.AudioFifo' object has no attribute 'layout'"
208 )
209 return self.template.layout
210
211 @property
212 def sample_rate(self):
213 if not self.ptr:
214 raise AttributeError(
215 f"'{__name__}.AudioFifo' object has no attribute 'sample_rate'"
216 )
217 return self.template.sample_rate
218
219 @property
220 def samples(self):
221 """Number of audio samples (per channel) in the buffer."""
222 return lib.av_audio_fifo_size(self.ptr) if self.ptr else 0