Debian Codegraph @

tests/test_dlpack.py

raw
1 import gc
2
3 import numpy
4 import pytest
5
6 import av
7 from av import VideoFrame
8 from av.codec.hwaccel import HWAccel
9
10 from .common import assertNdarraysEqual, fate_png
11
12
13 def _make_u8(shape: tuple[int, ...]) -> numpy.ndarray:
14 return numpy.arange(int(numpy.prod(shape)), dtype=numpy.uint8).reshape(shape)
15
16
17 def _make_u16(shape: tuple[int, ...]) -> numpy.ndarray:
18 return numpy.arange(int(numpy.prod(shape)), dtype=numpy.uint16).reshape(shape)
19
20
21 def _plane_to_2d(plane, height: int, width: int, dtype) -> numpy.ndarray:
22 itemsize = numpy.dtype(dtype).itemsize
23 assert plane.line_size % itemsize == 0
24 pitch_elems = plane.line_size // itemsize
25 arr = numpy.frombuffer(memoryview(plane), dtype=dtype).reshape(height, pitch_elems)
26 return arr[:, :width]
27
28
29 def _get_cuda_backend():
30 try:
31 import cupy # type: ignore
32
33 try:
34 if cupy.cuda.runtime.getDeviceCount() > 0:
35 return ("cupy", cupy)
36 except Exception:
37 pass
38 except Exception:
39 pass
40
41 try:
42 import torch # type: ignore
43
44 if torch.cuda.is_available():
45 return ("torch", torch)
46 except Exception:
47 pass
48
49 return None
50
51
52 def test_hwaccel_validation_and_primary_ctx() -> None:
53 hw = HWAccel(device_type="cuda")
54 assert hw.is_hw_owned == False
55 assert "primary_ctx" not in hw.options
56
57 hw = HWAccel(device_type="cuda", is_hw_owned=True)
58 assert hw.is_hw_owned == True
59 assert hw.options.get("primary_ctx") == "1"
60
61 hw = HWAccel(device_type="cuda", is_hw_owned=True, options={"primary_ctx": "0"})
62 assert hw.options.get("primary_ctx") == "0"
63
64
65 def test_video_frame_from_dlpack_nv12_cpu_basic_zero_copy_and_lifetime() -> None:
66 width, height = 64, 48
67 y = _make_u8((height, width))
68 uv = _make_u8((height // 2, width // 2, 2))
69
70 frame = VideoFrame.from_dlpack((y, uv), format="nv12")
71
72 assert frame.format.name == "nv12"
73 assert frame.width == width
74 assert frame.height == height
75 assert len(frame.planes) == 2
76 assert frame.planes[0].width == width
77 assert frame.planes[0].height == height
78 assert frame.planes[1].width == width // 2
79 assert frame.planes[1].height == height // 2
80 assert frame.planes[0].line_size == width
81 assert frame.planes[1].line_size == width
82
83 y_plane = _plane_to_2d(frame.planes[0], height, width, numpy.uint8)
84 uv_plane = _plane_to_2d(frame.planes[1], height // 2, width, numpy.uint8)
85 assertNdarraysEqual(y_plane, y)
86 assertNdarraysEqual(uv_plane, uv.reshape(height // 2, width))
87
88 y[0, 0] = 123
89 uv[0, 0, 0] = 11
90 uv[0, 0, 1] = 22
91
92 expected_y_bytes = y.tobytes()
93 expected_uv_bytes = uv.reshape(height // 2, width).tobytes()
94
95 assert memoryview(frame.planes[0])[0] == 123
96 assert memoryview(frame.planes[1])[0] == 11
97 assert memoryview(frame.planes[1])[1] == 22
98
99 del y
100 del uv
101 gc.collect()
102
103 assert bytes(frame.planes[0]) == expected_y_bytes
104 assert bytes(frame.planes[1]) == expected_uv_bytes
105
106
107 def test_video_frame_from_dlpack_nv12_cpu_with_pitch_and_dlpack_export() -> None:
108 width, height = 64, 48
109 pad = 16
110
111 y_base = _make_u8((height, width + pad))
112 y = y_base[:, :width]
113 uv_base = _make_u8((height // 2, (width + pad) // 2, 2))
114 uv = uv_base[:, : width // 2, :]
115
116 frame = VideoFrame.from_dlpack((y, uv), format="nv12")
117
118 assert frame.planes[0].line_size == width + pad
119 assert frame.planes[1].line_size == width + pad
120 assert frame.planes[0].buffer_size == (width + pad) * height
121 assert frame.planes[1].buffer_size == (width + pad) * (height // 2)
122
123 y_plane = _plane_to_2d(frame.planes[0], height, width, numpy.uint8)
124 uv_plane = _plane_to_2d(frame.planes[1], height // 2, width, numpy.uint8)
125 assertNdarraysEqual(y_plane, y)
126 assertNdarraysEqual(uv_plane, uv.reshape(height // 2, width))
127
128 assert frame.planes[0].__dlpack_device__() == (1, 0)
129
130 y_dl = numpy.from_dlpack(frame.planes[0])
131 uv_dl = numpy.from_dlpack(frame.planes[1])
132
133 assert y_dl.shape == (height, width)
134 assert y_dl.dtype == numpy.uint8
135 assert y_dl.strides == (width + pad, 1)
136 assertNdarraysEqual(y_dl, y)
137
138 assert uv_dl.shape == (height // 2, width // 2, 2)
139 assert uv_dl.dtype == numpy.uint8
140 assert uv_dl.strides == (width + pad, 2, 1)
141 assertNdarraysEqual(uv_dl, uv)
142
143 expected_y = numpy.array(y, copy=True)
144 expected_uv = numpy.array(uv, copy=True)
145
146 del frame
147 del y
148 del uv
149 del y_base
150 del uv_base
151 gc.collect()
152
153 assertNdarraysEqual(y_dl, expected_y)
154 assertNdarraysEqual(uv_dl, expected_uv)
155
156
157 def test_video_frame_from_dlpack_nv12_cpu_accepts_uv_2d() -> None:
158 width, height = 64, 48
159 y = _make_u8((height, width))
160 uv2d = _make_u8((height // 2, width))
161
162 frame = VideoFrame.from_dlpack((y, uv2d), format="nv12")
163
164 uv_plane = _plane_to_2d(frame.planes[1], height // 2, width, numpy.uint8)
165 assertNdarraysEqual(uv_plane, uv2d)
166
167 uv_dl = numpy.from_dlpack(frame.planes[1])
168 assert uv_dl.shape == (height // 2, width // 2, 2)
169 assertNdarraysEqual(uv_dl, uv2d.reshape(height // 2, width // 2, 2))
170
171
172 def test_video_frame_from_dlpack_accepts_video_plane_objects() -> None:
173 width, height = 64, 48
174 y = _make_u8((height, width))
175 uv = _make_u8((height // 2, width // 2, 2))
176
177 frame1 = VideoFrame.from_dlpack((y, uv), format="nv12")
178 frame2 = VideoFrame.from_dlpack((frame1.planes[0], frame1.planes[1]), format="nv12")
179
180 assert bytes(frame2.planes[0]) == bytes(frame1.planes[0])
181 assert bytes(frame2.planes[1]) == bytes(frame1.planes[1])
182
183
184 @pytest.mark.parametrize("fmt", ["p010le", "p016le"])
185 def test_video_frame_from_dlpack_p010_p016_cpu(fmt: str) -> None:
186 width, height = 64, 48
187 y = _make_u16((height, width))
188 uv = _make_u16((height // 2, width // 2, 2))
189
190 frame = VideoFrame.from_dlpack((y, uv), format=fmt)
191
192 assert frame.format.name == fmt
193 assert len(frame.planes) == 2
194 assert frame.planes[0].line_size == width * 2
195 assert frame.planes[1].line_size == width * 2
196
197 y_plane = _plane_to_2d(frame.planes[0], height, width, numpy.uint16)
198 uv_plane = _plane_to_2d(frame.planes[1], height // 2, width, numpy.uint16)
199 assertNdarraysEqual(y_plane, y)
200 assertNdarraysEqual(uv_plane, uv.reshape(height // 2, width))
201
202 y_dl = numpy.from_dlpack(frame.planes[0])
203 uv_dl = numpy.from_dlpack(frame.planes[1])
204
205 assert y_dl.dtype == numpy.uint16
206 assert y_dl.shape == (height, width)
207 assert y_dl.strides == (width * 2, 2)
208 assertNdarraysEqual(y_dl, y)
209
210 assert uv_dl.dtype == numpy.uint16
211 assert uv_dl.shape == (height // 2, width // 2, 2)
212 assert uv_dl.strides == (width * 2, 4, 2)
213 assertNdarraysEqual(uv_dl, uv)
214
215
216 def test_video_plane_dlpack_export_keeps_frame_alive_after_gc() -> None:
217 container = av.open(fate_png())
218 frame = next(container.decode(video=0))
219 frame_nv12 = frame.reformat(format="nv12")
220
221 width = frame_nv12.width
222 height = frame_nv12.height
223 line_size = frame_nv12.planes[0].line_size
224 expected = _plane_to_2d(frame_nv12.planes[0], height, width, numpy.uint8).copy()
225
226 y_dl = numpy.from_dlpack(frame_nv12.planes[0])
227 assert y_dl.shape == (height, width)
228 assert y_dl.strides == (line_size, 1)
229
230 del frame_nv12
231 del frame
232 del container
233 gc.collect()
234
235 assertNdarraysEqual(y_dl, expected)
236
237
238 def test_video_plane_dlpack_unsupported_format_raises() -> None:
239 rgb = numpy.zeros((16, 16, 3), dtype=numpy.uint8)
240 frame = VideoFrame.from_ndarray(rgb, format="rgb24")
241 assert frame.planes[0].__dlpack_device__() == (1, 0)
242
243 with pytest.raises(
244 NotImplementedError, match="unsupported sw_format for DLPack export"
245 ):
246 frame.planes[0].__dlpack__()
247
248
249 def test_video_frame_from_dlpack_requires_two_planes() -> None:
250 y = numpy.zeros((4, 4), dtype=numpy.uint8)
251 with pytest.raises(ValueError, match="2-plane"):
252 VideoFrame.from_dlpack(y, format="nv12")
253
254
255 def test_video_frame_from_dlpack_rejects_unsupported_format() -> None:
256 width, height = 64, 48
257 y = numpy.zeros((height, width), dtype=numpy.uint8)
258 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
259
260 with pytest.raises(NotImplementedError, match="supports nv12, p010le, p016le only"):
261 VideoFrame.from_dlpack((y, uv), format="yuv420p")
262
263
264 def test_video_frame_from_dlpack_rejects_device_id_for_cpu() -> None:
265 width, height = 64, 48
266 y = numpy.zeros((height, width), dtype=numpy.uint8)
267 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
268
269 with pytest.raises(ValueError, match="device_id must be 0 for CPU tensors"):
270 VideoFrame.from_dlpack((y, uv), format="nv12", device_id=1)
271
272
273 def test_video_frame_from_dlpack_requires_both_width_height_or_neither() -> None:
274 width, height = 64, 48
275 y = numpy.zeros((height, width), dtype=numpy.uint8)
276 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
277
278 with pytest.raises(ValueError, match="either specify both width/height or neither"):
279 VideoFrame.from_dlpack((y, uv), format="nv12", width=width, height=0)
280
281
282 def test_video_frame_from_dlpack_rejects_plane0_shape_mismatch_with_width_height() -> (
283 None
284 ):
285 width, height = 64, 48
286 y = numpy.zeros((height, width), dtype=numpy.uint8)
287 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
288
289 with pytest.raises(ValueError, match="plane 0 shape does not match width/height"):
290 VideoFrame.from_dlpack((y, uv), format="nv12", width=width + 2, height=height)
291
292
293 def test_video_frame_from_dlpack_rejects_odd_dimensions() -> None:
294 width, height = 63, 48
295 y = numpy.zeros((height, width), dtype=numpy.uint8)
296 uv = numpy.zeros((height // 2, width), dtype=numpy.uint8)
297
298 with pytest.raises(ValueError, match="width/height must be even"):
299 VideoFrame.from_dlpack((y, uv), format="nv12")
300
301
302 def test_video_frame_from_dlpack_rejects_noncontiguous_plane0_last_dim() -> None:
303 width, height = 64, 48
304 y_full = numpy.zeros((height, width * 2), dtype=numpy.uint8)
305 y = y_full[:, ::2]
306 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
307
308 with pytest.raises(
309 ValueError, match="plane 0 must be contiguous in the last dimension"
310 ):
311 VideoFrame.from_dlpack((y, uv), format="nv12")
312
313
314 def test_video_frame_from_dlpack_rejects_noncontiguous_uv_plane_last_dim_2d() -> None:
315 width, height = 64, 48
316 y = numpy.zeros((height, width), dtype=numpy.uint8)
317 uv_full = numpy.zeros((height // 2, width * 2), dtype=numpy.uint8)
318 uv = uv_full[:, ::2]
319
320 with pytest.raises(
321 ValueError, match="plane 1 must be contiguous in the last dimension"
322 ):
323 VideoFrame.from_dlpack((y, uv), format="nv12")
324
325
326 def test_video_frame_from_dlpack_rejects_unexpected_uv_strides_3d() -> None:
327 width, height = 64, 48
328 y = numpy.zeros((height, width), dtype=numpy.uint8)
329 uv_full = numpy.zeros((height // 2, width // 2, 4), dtype=numpy.uint8)
330 uv = uv_full[:, :, :2]
331
332 with pytest.raises(ValueError, match="unexpected UV plane strides"):
333 VideoFrame.from_dlpack((y, uv), format="nv12")
334
335
336 def test_video_frame_from_dlpack_rejects_wrong_dtype_plane0() -> None:
337 width, height = 64, 48
338 y = numpy.zeros((height, width), dtype=numpy.uint16)
339 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
340
341 with pytest.raises(TypeError, match="unexpected dtype for plane 0"):
342 VideoFrame.from_dlpack((y, uv), format="nv12")
343
344
345 def test_video_frame_from_dlpack_rejects_wrong_dtype_plane1() -> None:
346 width, height = 64, 48
347 y = numpy.zeros((height, width), dtype=numpy.uint8)
348 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint16)
349
350 with pytest.raises(TypeError, match="unexpected dtype for plane 1"):
351 VideoFrame.from_dlpack((y, uv), format="nv12")
352
353
354 def test_video_frame_from_dlpack_p010le_requires_uint16() -> None:
355 width, height = 64, 48
356 y = numpy.zeros((height, width), dtype=numpy.uint8)
357 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
358
359 with pytest.raises(TypeError, match="unexpected dtype for plane 0"):
360 VideoFrame.from_dlpack((y, uv), format="p010le")
361
362
363 def test_video_frame_from_dlpack_rejects_plane0_ndim_not_2() -> None:
364 y = numpy.zeros((4, 4, 1), dtype=numpy.uint8)
365 uv = numpy.zeros((2, 4), dtype=numpy.uint8)
366
367 with pytest.raises(ValueError, match="plane 0 must be 2D"):
368 VideoFrame.from_dlpack((y, uv), format="nv12", width=4, height=4)
369
370
371 def test_video_frame_from_dlpack_rejects_plane1_ndim_not_2_or_3() -> None:
372 width, height = 64, 48
373 y = numpy.zeros((height, width), dtype=numpy.uint8)
374 uv = numpy.zeros((height // 2, width, 1, 1), dtype=numpy.uint8)
375
376 with pytest.raises(ValueError, match="plane 1 must be 2D or 3D"):
377 VideoFrame.from_dlpack((y, uv), format="nv12")
378
379
380 def test_video_frame_from_dlpack_reusing_capsule_raises_typeerror() -> None:
381 width, height = 64, 48
382 y = numpy.zeros((height, width), dtype=numpy.uint8)
383 uv = numpy.zeros((height // 2, width // 2, 2), dtype=numpy.uint8)
384
385 cap0 = y.__dlpack__()
386 cap1 = uv.__dlpack__()
387
388 VideoFrame.from_dlpack((cap0, cap1), format="nv12", width=width, height=height)
389
390 with pytest.raises(TypeError, match="expected a DLPack capsule"):
391 VideoFrame.from_dlpack((cap0, cap1), format="nv12", width=width, height=height)
392
393
394 def test_video_frame_from_dlpack_invalid_plane_object_raises_typeerror() -> None:
395 with pytest.raises(TypeError, match="expected a DLPack capsule"):
396 VideoFrame.from_dlpack((object(), object()), format="nv12", width=64, height=48)
397
398
399 def test_video_frame_from_dlpack_cuda_hw_frame_behavior_if_available() -> None:
400 backend = _get_cuda_backend()
401 if backend is None:
402 pytest.skip("CUDA backend (cupy/torch) not available.")
403
404 width, height = 64, 48
405 name, mod = backend
406
407 try:
408 if name == "cupy":
409 try:
410 ndev = int(mod.cuda.runtime.getDeviceCount())
411 except Exception:
412 ndev = 1
413
414 device_id = 1 if ndev > 1 else 0
415 with mod.cuda.Device(device_id):
416 y = mod.arange(height * width, dtype=mod.uint8).reshape(height, width)
417 uv = mod.arange(
418 (height // 2) * (width // 2) * 2, dtype=mod.uint8
419 ).reshape(height // 2, width // 2, 2)
420 expected_device = y.__dlpack_device__()
421 frame = VideoFrame.from_dlpack((y, uv), format="nv12")
422
423 assert frame.format.name == "cuda"
424 assert len(frame.planes) == 2
425
426 with pytest.raises(
427 TypeError, match="Hardware frame planes do not support"
428 ):
429 memoryview(frame.planes[0])
430
431 assert frame.planes[0].__dlpack_device__() == expected_device
432
433 cap_y = frame.planes[0].__dlpack__()
434 if hasattr(mod, "fromDlpack"):
435 y2 = mod.fromDlpack(cap_y)
436 else:
437 y2 = mod.from_dlpack(cap_y)
438
439 assert y2.shape == y.shape
440 assert mod.all(y2 == y).item()
441
442 with pytest.raises(
443 ValueError,
444 match="Cannot convert a hardware frame to numpy directly",
445 ):
446 frame.to_ndarray(format="cuda")
447
448 else:
449 try:
450 ndev = int(mod.cuda.device_count())
451 except Exception:
452 ndev = 1
453
454 device_id = 1 if ndev > 1 else 0
455 device = f"cuda:{device_id}"
456
457 y = mod.arange(height * width, device=device, dtype=mod.uint8).reshape(
458 height, width
459 )
460 uv = mod.arange(
461 (height // 2) * (width // 2) * 2, device=device, dtype=mod.uint8
462 ).reshape(height // 2, width // 2, 2)
463
464 expected_device = y.__dlpack_device__()
465 frame = VideoFrame.from_dlpack((y, uv), format="nv12")
466
467 assert frame.format.name == "cuda"
468 assert len(frame.planes) == 2
469
470 with pytest.raises(TypeError, match="Hardware frame planes do not support"):
471 memoryview(frame.planes[0])
472
473 assert frame.planes[0].__dlpack_device__() == expected_device
474
475 cap_y = frame.planes[0].__dlpack__()
476 y2 = mod.utils.dlpack.from_dlpack(cap_y)
477
478 assert tuple(y2.shape) == tuple(y.shape)
479 assert mod.equal(y2, y)
480
481 with pytest.raises(
482 ValueError, match="Cannot convert a hardware frame to numpy directly"
483 ):
484 frame.to_ndarray(format="cuda")
485 except av.FFmpegError as e:
486 pytest.skip(f"CUDA hwcontext not available in this build/runtime: {e}")