Debian Codegraph @

tests/test_filters.py

raw
1 import errno
2 from fractions import Fraction
3
4 import numpy as np
5
6 import av
7 from av import AudioFrame, VideoFrame
8 from av.audio.frame import format_dtypes
9 from av.filter import Filter, Graph
10
11 from .common import TestCase, has_pillow
12
13
14 def generate_audio_frame(
15 frame_num: int,
16 input_format: str = "s16",
17 layout: str = "stereo",
18 sample_rate: int = 44100,
19 frame_size: int = 1024,
20 ) -> AudioFrame:
21 """
22 Generate audio frame representing part of the sinusoidal wave
23 """
24 frame = AudioFrame(format=input_format, layout=layout, samples=frame_size)
25 frame.sample_rate = sample_rate
26 frame.pts = frame_num * frame_size
27
28 for i in range(frame.layout.nb_channels):
29 data = np.zeros(frame_size, dtype=format_dtypes[input_format])
30 for j in range(frame_size):
31 data[j] = np.sin(2 * np.pi * (frame_num + j) * (i + 1) / float(frame_size))
32 frame.planes[i].update(data) # type: ignore
33
34 return frame
35
36
37 def pull_until_blocked(graph: Graph) -> list[av.VideoFrame]:
38 frames: list[av.VideoFrame] = []
39 while True:
40 try:
41 frames.append(graph.vpull())
42 except av.FFmpegError as e:
43 if e.errno != errno.EAGAIN:
44 raise
45 return frames
46
47
48 class TestFilters(TestCase):
49 def test_filter_descriptor(self) -> None:
50 f = Filter("testsrc")
51 assert f.name == "testsrc"
52 assert f.description == "Generate test pattern."
53
54 def test_generator_graph(self):
55 graph = Graph()
56 src = graph.add("testsrc")
57 lutrgb = graph.add(
58 "lutrgb",
59 "r=maxval+minval-val:g=maxval+minval-val:b=maxval+minval-val",
60 name="invert",
61 )
62 sink = graph.add("buffersink")
63 src.link_to(lutrgb)
64 lutrgb.link_to(sink)
65
66 # pads and links
67 assert src.outputs[0].link.output is lutrgb.inputs[0]
68 assert lutrgb.inputs[0].link.input is src.outputs[0]
69
70 frame = sink.pull()
71 assert isinstance(frame, VideoFrame)
72
73 if has_pillow:
74 frame.to_image().save(self.sandboxed("mandelbrot2.png"))
75
76 def test_auto_find_sink(self) -> None:
77 graph = Graph()
78 src = graph.add("testsrc")
79 src.link_to(graph.add("buffersink"))
80 graph.configure()
81
82 frame = graph.vpull()
83
84 if has_pillow:
85 frame.to_image().save(self.sandboxed("mandelbrot3.png"))
86
87 def test_delegate_sink(self) -> None:
88 graph = Graph()
89 src = graph.add("testsrc")
90 src.link_to(graph.add("buffersink"))
91 graph.configure()
92
93 frame = src.pull()
94 assert isinstance(frame, av.VideoFrame)
95
96 if has_pillow:
97 frame.to_image().save(self.sandboxed("mandelbrot4.png"))
98
99 def test_audio_buffer_sink(self):
100 graph = Graph()
101 audio_buffer = graph.add_abuffer(
102 format="fltp",
103 sample_rate=48000,
104 layout="stereo",
105 time_base=Fraction(1, 48000),
106 )
107 audio_buffer.link_to(graph.add("abuffersink"))
108 graph.configure()
109
110 try:
111 graph.pull()
112 except OSError as e:
113 # we haven't pushed any input so expect no frames / EAGAIN
114 if e.errno != errno.EAGAIN:
115 raise
116
117 def test_audio_buffer_resample(self) -> None:
118 graph = Graph()
119 graph.link_nodes(
120 graph.add_abuffer(
121 format="fltp",
122 sample_rate=48000,
123 layout="stereo",
124 time_base=Fraction(1, 48000),
125 ),
126 graph.add(
127 "aformat", "sample_fmts=s16:sample_rates=44100:channel_layouts=stereo"
128 ),
129 graph.add("abuffersink"),
130 ).configure()
131
132 graph.push(
133 generate_audio_frame(
134 0, input_format="fltp", layout="stereo", sample_rate=48000
135 )
136 )
137 out_frame = graph.pull()
138 assert isinstance(out_frame, av.AudioFrame)
139 assert out_frame.format.name == "s16"
140 assert out_frame.layout.name == "stereo"
141 assert out_frame.sample_rate == 44100
142
143 def test_audio_buffer_frame_size(self):
144 graph = Graph()
145 graph.link_nodes(
146 graph.add_abuffer(
147 format="fltp",
148 sample_rate=48000,
149 layout="stereo",
150 time_base=Fraction(1, 48000),
151 ),
152 graph.add("abuffersink"),
153 ).configure()
154 graph.set_audio_frame_size(256)
155 graph.push(
156 generate_audio_frame(
157 0,
158 input_format="fltp",
159 layout="stereo",
160 sample_rate=48000,
161 frame_size=1024,
162 )
163 )
164 out_frame = graph.pull()
165 assert out_frame.sample_rate == 48000
166 assert out_frame.samples == 256
167
168 def test_audio_buffer_volume_filter(self):
169 graph = Graph()
170 graph.link_nodes(
171 graph.add_abuffer(
172 format="fltp",
173 sample_rate=48000,
174 layout="stereo",
175 time_base=Fraction(1, 48000),
176 ),
177 graph.add("volume", volume="0.5"),
178 graph.add("abuffersink"),
179 ).configure()
180
181 input_frame = generate_audio_frame(
182 0, input_format="fltp", layout="stereo", sample_rate=48000
183 )
184 graph.push(input_frame)
185
186 out_frame = graph.pull()
187 assert out_frame.format.name == "fltp"
188 assert out_frame.layout.name == "stereo"
189 assert out_frame.sample_rate == 48000
190
191 input_data = input_frame.to_ndarray()
192 output_data = out_frame.to_ndarray()
193
194 assert np.allclose(input_data * 0.5, output_data)
195
196 def _test_video_buffer(self, graph):
197 input_container = av.open(format="lavfi", file="color=c=pink:duration=1:r=30")
198 input_video_stream = input_container.streams.video[0]
199
200 buffer = graph.add_buffer(template=input_video_stream)
201 bwdif = graph.add("bwdif", "send_field:tff:all")
202 buffersink = graph.add("buffersink")
203 buffer.link_to(bwdif)
204 bwdif.link_to(buffersink)
205 graph.configure()
206
207 for frame in input_container.decode():
208 assert frame.time_base == Fraction(1, 30)
209 graph.vpush(frame)
210 filtered_frames = pull_until_blocked(graph)
211
212 if frame.pts == 0:
213 # no output for the first input frame
214 assert len(filtered_frames) == 0
215 else:
216 # we expect two filtered frames per input frame
217 assert len(filtered_frames) == 2
218
219 assert filtered_frames[0].pts == (frame.pts - 1) * 2
220 assert filtered_frames[0].time_base == Fraction(1, 60)
221
222 assert filtered_frames[1].pts == (frame.pts - 1) * 2 + 1
223 assert filtered_frames[1].time_base == Fraction(1, 60)
224
225 def test_video_buffer(self):
226 self._test_video_buffer(av.filter.Graph())
227
228 def test_video_buffer_threading(self):
229 graph = av.filter.Graph()
230 graph.threads = 4
231 self._test_video_buffer(graph)
232
233 def test_EOF(self) -> None:
234 input_container = av.open(format="lavfi", file="color=c=pink:duration=1:r=30")
235 video_stream = input_container.streams.video[0]
236
237 graph = av.filter.Graph()
238 video_in = graph.add_buffer(template=video_stream)
239 palette_gen_filter = graph.add("palettegen")
240 video_out = graph.add("buffersink")
241 video_in.link_to(palette_gen_filter)
242 palette_gen_filter.link_to(video_out)
243 graph.configure()
244
245 for frame in input_container.decode(video=0):
246 graph.vpush(frame)
247
248 graph.vpush(None)
249
250 # if we do not push None, we get a BlockingIOError
251 palette_frame = graph.vpull()
252
253 assert isinstance(palette_frame, av.VideoFrame)
254 assert palette_frame.width == 16
255 assert palette_frame.height == 16
256
257 def test_graph_threads(self) -> None:
258 graph = Graph()
259 assert graph.threads == 0
260
261 graph.threads = 4
262 assert graph.threads == 4
263
264 graph.add("testsrc")
265
266 with self.assertRaises(RuntimeError):
267 graph.threads = 2