Debian Codegraph @

av/video/frame.py

raw
1 import sys
2 from enum import IntEnum
3
4 import cython
5 import cython.cimports.libav as lib
6 from cython.cimports.av.dictionary import Dictionary
7 from cython.cimports.av.error import err_check
8 from cython.cimports.av.sidedata.sidedata import get_display_rotation
9 from cython.cimports.av.utils import check_ndarray
10 from cython.cimports.av.video.format import get_pix_fmt, get_video_format
11 from cython.cimports.av.video.plane import DLManagedTensor, VideoPlane, kCPU, kCuda
12 from cython.cimports.cpython.exc import PyErr_Clear
13 from cython.cimports.cpython.pycapsule import (
14 PyCapsule_GetPointer,
15 PyCapsule_IsValid,
16 PyCapsule_SetName,
17 )
18 from cython.cimports.cpython.ref import Py_DECREF, Py_INCREF
19 from cython.cimports.libc.stdint import int64_t, uint8_t
20
21
22 @cython.final
23 @cython.cclass
24 class CudaContext:
25 def __cinit__(self, device_id: cython.int = 0, primary_ctx: cython.bint = True):
26 self.device_id = device_id
27 self.primary_ctx = primary_ctx
28 self._device_ref = cython.NULL
29 self._frames_cache = {}
30
31 def __dealloc__(self):
32 ref: cython.pointer[lib.AVBufferRef]
33
34 for v in self._frames_cache.values():
35 ref = cython.cast(
36 cython.pointer[lib.AVBufferRef],
37 cython.cast(cython.size_t, v),
38 )
39 lib.av_buffer_unref(cython.address(ref))
40 self._frames_cache.clear()
41
42 ref = self._device_ref
43 if ref != cython.NULL:
44 lib.av_buffer_unref(cython.address(ref))
45 self._device_ref = cython.NULL
46
47 @cython.cfunc
48 def _get_device_ref(self) -> cython.pointer[lib.AVBufferRef]:
49 device_ref: cython.pointer[lib.AVBufferRef] = self._device_ref
50 if device_ref != cython.NULL:
51 return device_ref
52
53 device_ref = cython.NULL
54 device_bytes = f"{self.device_id}".encode()
55 c_device: cython.p_char = device_bytes
56 options: Dictionary = Dictionary(
57 {"primary_ctx": "1" if self.primary_ctx else "0"}
58 )
59 err_check(
60 lib.av_hwdevice_ctx_create(
61 cython.address(device_ref),
62 lib.AV_HWDEVICE_TYPE_CUDA,
63 c_device,
64 options.ptr,
65 0,
66 )
67 )
68 self._device_ref = device_ref
69 return device_ref
70
71 @cython.cfunc
72 def get_frames_ctx(
73 self,
74 sw_fmt: lib.AVPixelFormat,
75 width: cython.int,
76 height: cython.int,
77 ) -> cython.pointer[lib.AVBufferRef]:
78 key = (int(sw_fmt), int(width), int(height))
79 cached = self._frames_cache.get(key)
80 cached_ref: cython.pointer[lib.AVBufferRef]
81 out_ref: cython.pointer[lib.AVBufferRef]
82
83 if cached is not None:
84 cached_ref = cython.cast(
85 cython.pointer[lib.AVBufferRef],
86 cython.cast(cython.size_t, cached),
87 )
88 out_ref = lib.av_buffer_ref(cached_ref)
89 if out_ref == cython.NULL:
90 raise MemoryError("av_buffer_ref() failed")
91 return out_ref
92
93 device_ref = self._get_device_ref()
94
95 frames_ref: cython.pointer[lib.AVBufferRef] = lib.av_hwframe_ctx_alloc(
96 device_ref
97 )
98 if frames_ref == cython.NULL:
99 raise MemoryError("av_hwframe_ctx_alloc() failed")
100
101 try:
102 frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast(
103 cython.pointer[lib.AVHWFramesContext], frames_ref.data
104 )
105 frames_ctx.format = get_pix_fmt(b"cuda")
106 frames_ctx.sw_format = sw_fmt
107 frames_ctx.width = int(width)
108 frames_ctx.height = int(height)
109 err_check(lib.av_hwframe_ctx_init(frames_ref))
110 except Exception:
111 lib.av_buffer_unref(cython.address(frames_ref))
112 raise
113
114 out_ref = lib.av_buffer_ref(frames_ref)
115 if out_ref == cython.NULL:
116 lib.av_buffer_unref(cython.address(frames_ref))
117 raise MemoryError("av_buffer_ref() failed")
118
119 self._frames_cache[key] = cython.cast(cython.size_t, frames_ref)
120 return out_ref
121
122
123 @cython.cfunc
124 def _consume_dlpack(obj: object, stream: object) -> cython.pointer[DLManagedTensor]:
125 capsule: object
126 managed: cython.pointer[DLManagedTensor]
127
128 if hasattr(obj, "__dlpack__"):
129 capsule = obj.__dlpack__() if stream is None else obj.__dlpack__(stream=stream)
130 else:
131 capsule = obj
132
133 if not PyCapsule_IsValid(capsule, b"dltensor"):
134 PyErr_Clear()
135 raise TypeError(
136 "expected a DLPack capsule or an object implementing __dlpack__"
137 )
138
139 managed = cython.cast(
140 cython.pointer[DLManagedTensor],
141 PyCapsule_GetPointer(capsule, b"dltensor"),
142 )
143 if managed == cython.NULL:
144 raise ValueError("PyCapsule_GetPointer returned NULL")
145
146 if PyCapsule_SetName(capsule, b"used_dltensor") != 0:
147 raise RuntimeError("PyCapsule_SetName failed")
148
149 return managed
150
151
152 @cython.cfunc
153 @cython.nogil
154 @cython.exceptval(check=False)
155 def _dlpack_avbuffer_free(
156 opaque: cython.p_void,
157 data: cython.pointer[uint8_t],
158 ) -> cython.void:
159 managed: cython.pointer[DLManagedTensor] = cython.cast(
160 cython.pointer[DLManagedTensor], opaque
161 )
162 if managed != cython.NULL:
163 managed.deleter(managed)
164
165
166 @cython.cfunc
167 @cython.nogil
168 @cython.exceptval(check=False)
169 def _numpy_avbuffer_free(
170 opaque: cython.p_void,
171 data: cython.pointer[uint8_t],
172 ) -> cython.void:
173 if opaque != cython.NULL:
174 with cython.gil:
175 Py_DECREF(cython.cast(object, opaque))
176
177
178 _cinit_bypass_sentinel = cython.declare(object, object())
179
180 # `pix_fmt`s supported by Frame.to_ndarray() and Frame.from_ndarray()
181 supported_np_pix_fmts = {
182 "abgr",
183 "argb",
184 "bayer_bggr16be",
185 "bayer_bggr16le",
186 "bayer_bggr8",
187 "bayer_gbrg16be",
188 "bayer_gbrg16le",
189 "bayer_gbrg8",
190 "bayer_grbg16be",
191 "bayer_grbg16le",
192 "bayer_grbg8",
193 "bayer_rggb16be",
194 "bayer_rggb16le",
195 "bayer_rggb8",
196 "bgr24",
197 "bgr48be",
198 "bgr48le",
199 "bgr8",
200 "bgra",
201 "bgra64be",
202 "bgra64le",
203 "gbrap",
204 "gbrap10be",
205 "gbrap10le",
206 "gbrap12be",
207 "gbrap12le",
208 "gbrap14be",
209 "gbrap14le",
210 "gbrap16be",
211 "gbrap16le",
212 "gbrapf32be",
213 "gbrapf32le",
214 "gbrp",
215 "gbrp10be",
216 "gbrp10le",
217 "gbrp12be",
218 "gbrp12le",
219 "gbrp14be",
220 "gbrp14le",
221 "gbrp16be",
222 "gbrp16le",
223 "gbrp9be",
224 "gbrp9le",
225 "gbrpf32be",
226 "gbrpf32le",
227 "gray",
228 "gray10be",
229 "gray10le",
230 "gray12be",
231 "gray12le",
232 "gray14be",
233 "gray14le",
234 "gray16be",
235 "gray16le",
236 "gray8",
237 "gray9be",
238 "gray9le",
239 "grayf32be",
240 "grayf32le",
241 "nv12",
242 "pal8",
243 "rgb24",
244 "rgb48be",
245 "rgb48le",
246 "rgb8",
247 "rgba",
248 "rgba64be",
249 "rgba64le",
250 "rgbaf16be",
251 "rgbaf16le",
252 "rgbaf32be",
253 "rgbaf32le",
254 "rgbf32be",
255 "rgbf32le",
256 "yuv420p",
257 "yuv422p10le",
258 "yuv444p",
259 "yuv444p16be",
260 "yuv444p16le",
261 "yuva444p16be",
262 "yuva444p16le",
263 "yuvj420p",
264 "yuvj444p",
265 "yuyv422",
266 }
267
268 # Mapping from format name to (itemsize, dtype) for formats where planes
269 # are simply concatenated into shape (height, width, channels).
270 _np_pix_fmt_dtypes = cython.declare(
271 dict[str, tuple[cython.uint, str]],
272 {
273 "abgr": (4, "uint8"),
274 "argb": (4, "uint8"),
275 "bayer_bggr8": (1, "uint8"),
276 "bayer_gbrg8": (1, "uint8"),
277 "bayer_grbg8": (1, "uint8"),
278 "bayer_rggb8": (1, "uint8"),
279 "bayer_bggr16le": (2, "uint16"),
280 "bayer_bggr16be": (2, "uint16"),
281 "bayer_gbrg16le": (2, "uint16"),
282 "bayer_gbrg16be": (2, "uint16"),
283 "bayer_grbg16le": (2, "uint16"),
284 "bayer_grbg16be": (2, "uint16"),
285 "bayer_rggb16le": (2, "uint16"),
286 "bayer_rggb16be": (2, "uint16"),
287 "bgr24": (3, "uint8"),
288 "bgr48be": (6, "uint16"),
289 "bgr48le": (6, "uint16"),
290 "bgr8": (1, "uint8"),
291 "bgra": (4, "uint8"),
292 "bgra64be": (8, "uint16"),
293 "bgra64le": (8, "uint16"),
294 "gbrap": (1, "uint8"),
295 "gbrap10be": (2, "uint16"),
296 "gbrap10le": (2, "uint16"),
297 "gbrap12be": (2, "uint16"),
298 "gbrap12le": (2, "uint16"),
299 "gbrap14be": (2, "uint16"),
300 "gbrap14le": (2, "uint16"),
301 "gbrap16be": (2, "uint16"),
302 "gbrap16le": (2, "uint16"),
303 "gbrapf32be": (4, "float32"),
304 "gbrapf32le": (4, "float32"),
305 "gbrp": (1, "uint8"),
306 "gbrp10be": (2, "uint16"),
307 "gbrp10le": (2, "uint16"),
308 "gbrp12be": (2, "uint16"),
309 "gbrp12le": (2, "uint16"),
310 "gbrp14be": (2, "uint16"),
311 "gbrp14le": (2, "uint16"),
312 "gbrp16be": (2, "uint16"),
313 "gbrp16le": (2, "uint16"),
314 "gbrp9be": (2, "uint16"),
315 "gbrp9le": (2, "uint16"),
316 "gbrpf32be": (4, "float32"),
317 "gbrpf32le": (4, "float32"),
318 "gray": (1, "uint8"),
319 "gray10be": (2, "uint16"),
320 "gray10le": (2, "uint16"),
321 "gray12be": (2, "uint16"),
322 "gray12le": (2, "uint16"),
323 "gray14be": (2, "uint16"),
324 "gray14le": (2, "uint16"),
325 "gray16be": (2, "uint16"),
326 "gray16le": (2, "uint16"),
327 "gray8": (1, "uint8"),
328 "gray9be": (2, "uint16"),
329 "gray9le": (2, "uint16"),
330 "grayf32be": (4, "float32"),
331 "grayf32le": (4, "float32"),
332 "rgb24": (3, "uint8"),
333 "rgb48be": (6, "uint16"),
334 "rgb48le": (6, "uint16"),
335 "rgb8": (1, "uint8"),
336 "rgba": (4, "uint8"),
337 "rgba64be": (8, "uint16"),
338 "rgba64le": (8, "uint16"),
339 "rgbaf16be": (8, "float16"),
340 "rgbaf16le": (8, "float16"),
341 "rgbaf32be": (16, "float32"),
342 "rgbaf32le": (16, "float32"),
343 "rgbf32be": (12, "float32"),
344 "rgbf32le": (12, "float32"),
345 "yuv444p": (1, "uint8"),
346 "yuv444p16be": (2, "uint16"),
347 "yuv444p16le": (2, "uint16"),
348 "yuva444p16be": (2, "uint16"),
349 "yuva444p16le": (2, "uint16"),
350 "yuvj444p": (1, "uint8"),
351 "yuyv422": (2, "uint8"),
352 },
353 )
354
355
356 @cython.cfunc
357 def alloc_video_frame() -> VideoFrame:
358 """Get a mostly uninitialized VideoFrame.
359
360 You MUST call VideoFrame._init(...) or VideoFrame._init_user_attributes()
361 before exposing to the user.
362
363 """
364 return VideoFrame(_cinit_bypass_sentinel)
365
366
367 class PictureType(IntEnum):
368 NONE = lib.AV_PICTURE_TYPE_NONE # Undefined
369 I = lib.AV_PICTURE_TYPE_I # Intra
370 P = lib.AV_PICTURE_TYPE_P # Predicted
371 B = lib.AV_PICTURE_TYPE_B # Bi-directional predicted
372 S = lib.AV_PICTURE_TYPE_S # S(GMC)-VOP MPEG-4
373 SI = lib.AV_PICTURE_TYPE_SI # Switching intra
374 SP = lib.AV_PICTURE_TYPE_SP # Switching predicted
375 BI = lib.AV_PICTURE_TYPE_BI # BI type
376
377
378 _is_big_endian = cython.declare(cython.bint, sys.byteorder == "big")
379
380
381 @cython.cfunc
382 @cython.inline
383 def byteswap_array(array, big_endian: cython.bint):
384 if _is_big_endian != big_endian:
385 return array.byteswap()
386 return array
387
388
389 @cython.cfunc
390 def copy_bytes_to_plane(
391 img_bytes,
392 plane: VideoPlane,
393 bytes_per_pixel: cython.uint,
394 flip_horizontal: cython.bint,
395 flip_vertical: cython.bint,
396 ):
397 i_buf: cython.const[uint8_t][:] = img_bytes
398 i_pos: cython.size_t = 0
399 i_stride: cython.size_t = plane.width * bytes_per_pixel
400
401 o_buf: uint8_t[:] = plane
402 o_pos: cython.size_t = 0
403 o_stride: cython.size_t = abs(plane.line_size)
404
405 start_row, end_row, step = cython.declare(cython.int)
406 if flip_vertical:
407 start_row = plane.height - 1
408 end_row = -1
409 step = -1
410 else:
411 start_row = 0
412 end_row = plane.height
413 step = 1
414
415 for row in range(start_row, end_row, step):
416 i_pos = row * i_stride
417 if flip_horizontal:
418 i: cython.Py_ssize_t
419 for i in range(0, i_stride, bytes_per_pixel):
420 j: cython.Py_ssize_t
421 for j in range(bytes_per_pixel):
422 o_buf[o_pos + i + j] = i_buf[
423 i_pos + i_stride - i - bytes_per_pixel + j
424 ]
425 else:
426 o_buf[o_pos : o_pos + i_stride] = i_buf[i_pos : i_pos + i_stride]
427 o_pos += o_stride
428
429
430 @cython.cfunc
431 def copy_array_to_plane(array, plane: VideoPlane, bytes_per_pixel: cython.uint):
432 imgbytes: bytes = array.tobytes()
433 copy_bytes_to_plane(imgbytes, plane, bytes_per_pixel, False, False)
434
435
436 @cython.cfunc
437 @cython.inline
438 def useful_array(
439 plane: VideoPlane, bytes_per_pixel: cython.uint = 1, dtype: str = "uint8"
440 ):
441 """
442 Return the useful part of the VideoPlane as a strided array.
443
444 We are simply creating a view that discards any padding which was added for
445 alignment.
446 """
447 import numpy as np
448
449 dtype_obj = np.dtype(dtype)
450 line_size = plane.frame.ptr.linesize[plane.index]
451 total_line_size = abs(line_size)
452 itemsize = dtype_obj.itemsize
453 channels = bytes_per_pixel // itemsize
454
455 if channels == 1:
456 shape = (plane.height, plane.width)
457 strides = (total_line_size, itemsize)
458 else:
459 shape = (plane.height, plane.width, channels)
460 strides = (total_line_size, bytes_per_pixel, itemsize)
461
462 if line_size < 0:
463 offset = (plane.height - 1) * total_line_size
464 strides = (-total_line_size, *strides[1:])
465 return np.ndarray(
466 shape, dtype=dtype_obj, buffer=plane, offset=offset, strides=strides
467 )
468
469 return np.ndarray(shape, dtype=dtype_obj, buffer=plane, strides=strides)
470
471
472 @cython.cfunc
473 def check_ndarray_shape(array: object, ok: cython.bint):
474 if not ok:
475 raise ValueError(f"Unexpected numpy array shape `{array.shape}`")
476
477
478 @cython.final
479 @cython.cclass
480 class VideoFrame(Frame):
481 def __cinit__(self, width=0, height=0, format="yuv420p"):
482 if width is _cinit_bypass_sentinel:
483 return
484
485 c_format: lib.AVPixelFormat = get_pix_fmt(format)
486 self._init(c_format, width, height)
487
488 @cython.cfunc
489 def _init(self, format: lib.AVPixelFormat, width: cython.uint, height: cython.uint):
490 res: cython.int = 0
491
492 with cython.nogil:
493 self.ptr.width = width
494 self.ptr.height = height
495 self.ptr.format = format
496
497 # We enforce aligned buffers, otherwise `sws_scale_frame` can perform
498 # poorly or even cause out-of-bounds reads and writes.
499 if width and height:
500 res = lib.av_frame_get_buffer(self.ptr, 16)
501
502 if res:
503 err_check(res)
504
505 self._init_user_attributes()
506
507 @cython.cfunc
508 def _init_user_attributes(self):
509 self.format = get_video_format(
510 cython.cast(lib.AVPixelFormat, self.ptr.format),
511 self.ptr.width,
512 self.ptr.height,
513 )
514
515 def __dealloc__(self):
516 lib.av_frame_unref(self.ptr)
517
518 def __repr__(self):
519 return (
520 f"<av.{self.__class__.__name__}, pts={self.pts} {self.format.name} "
521 f"{self.width}x{self.height} at 0x{id(self):x}>"
522 )
523
524 @property
525 def planes(self):
526 """
527 A tuple of :class:`.VideoPlane` objects.
528 """
529 # We need to detect which planes actually exist, but also constrain ourselves to
530 # the maximum plane count (as determined only by VideoFrames so far), in case
531 # the library implementation does not set the last plane to NULL.
532 fmt = self.format
533 if self.ptr.hw_frames_ctx:
534 frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast(
535 cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data
536 )
537 fmt = get_video_format(
538 frames_ctx.sw_format, self.ptr.width, self.ptr.height
539 )
540
541 max_plane_count: cython.int = 0
542 for i in range(fmt.ptr.nb_components):
543 count = fmt.ptr.comp[i].plane + 1
544 if max_plane_count < count:
545 max_plane_count = count
546 if fmt.name == "pal8":
547 max_plane_count = 2
548
549 plane_count: cython.int = 0
550 while plane_count < max_plane_count and self.ptr.extended_data[plane_count]:
551 plane_count += 1
552 if plane_count == 1:
553 return (VideoPlane(self, 0),)
554 return tuple([VideoPlane(self, i) for i in range(plane_count)])
555
556 @property
557 def width(self):
558 """Width of the image, in pixels."""
559 return self.ptr.width
560
561 @property
562 def height(self):
563 """Height of the image, in pixels."""
564 return self.ptr.height
565
566 @property
567 def rotation(self):
568 """The rotation component of the `DISPLAYMATRIX` transformation matrix.
569
570 Returns:
571 int: The angle (in degrees) by which the transformation rotates the frame
572 counterclockwise. The angle will be in range [-180, 180].
573 """
574 return get_display_rotation(self)
575
576 @property
577 def interlaced_frame(self):
578 """Is this frame an interlaced or progressive?"""
579
580 return bool(self.ptr.flags & lib.AV_FRAME_FLAG_INTERLACED)
581
582 @property
583 def pict_type(self):
584 """Returns an integer that corresponds to the PictureType enum.
585
586 Wraps :ffmpeg:`AVFrame.pict_type`
587
588 :type: int
589 """
590 return self.ptr.pict_type
591
592 @pict_type.setter
593 def pict_type(self, value):
594 self.ptr.pict_type = value
595
596 @property
597 def colorspace(self):
598 """Colorspace of frame.
599
600 Wraps :ffmpeg:`AVFrame.colorspace`.
601
602 """
603 return self.ptr.colorspace
604
605 @colorspace.setter
606 def colorspace(self, value):
607 self.ptr.colorspace = value
608
609 @property
610 def color_range(self):
611 """Color range of frame.
612
613 Wraps :ffmpeg:`AVFrame.color_range`.
614
615 """
616 return self.ptr.color_range
617
618 @color_range.setter
619 def color_range(self, value):
620 self.ptr.color_range = value
621
622 @property
623 def color_trc(self):
624 """Transfer characteristic of frame.
625
626 Wraps :ffmpeg:`AVFrame.color_trc`.
627
628 """
629 return self.ptr.color_trc
630
631 @color_trc.setter
632 def color_trc(self, value):
633 self.ptr.color_trc = value
634
635 @property
636 def color_primaries(self):
637 """Color primaries of frame.
638
639 Wraps :ffmpeg:`AVFrame.color_primaries`.
640
641 """
642 return self.ptr.color_primaries
643
644 @color_primaries.setter
645 def color_primaries(self, value):
646 self.ptr.color_primaries = value
647
648 def reformat(self, *args, **kwargs):
649 """reformat(width=None, height=None, format=None, src_colorspace=None, dst_colorspace=None, interpolation=None, threads=None)
650
651 Create a new :class:`VideoFrame` with the given width/height/format/colorspace.
652
653 .. seealso:: :meth:`.VideoReformatter.reformat` for arguments.
654
655 """
656 if not self.reformatter:
657 self.reformatter = VideoReformatter()
658 return self.reformatter.reformat(self, *args, **kwargs)
659
660 def to_rgb(self, **kwargs):
661 """Get an RGB version of this frame.
662
663 Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`.
664
665 >>> frame = VideoFrame(1920, 1080)
666 >>> frame.format.name
667 'yuv420p'
668 >>> frame.to_rgb().format.name
669 'rgb24'
670
671 """
672 return self.reformat(format="rgb24", **kwargs)
673
674 @cython.ccall
675 def save(self, filepath: object):
676 """Save a VideoFrame as a JPG or PNG.
677
678 :param filepath: str | Path
679 """
680 is_jpg: cython.bint
681
682 if filepath.endswith(".png"):
683 is_jpg = False
684 elif filepath.endswith(".jpg") or filepath.endswith(".jpeg"):
685 is_jpg = True
686 else:
687 raise ValueError("filepath must end with png or jpg.")
688
689 encoder: str = "mjpeg" if is_jpg else "png"
690 pix_fmt: str = "yuvj420p" if is_jpg else "rgb24"
691
692 from av.container.core import open
693
694 with open(filepath, "w", options={"update": "1"}) as output:
695 output_stream = output.add_stream(encoder, pix_fmt=pix_fmt)
696 output_stream.width = self.width
697 output_stream.height = self.height
698
699 output.mux(output_stream.encode(self.reformat(format=pix_fmt)))
700 output.mux(output_stream.encode(None))
701
702 def to_image(self, **kwargs):
703 """Get an RGB ``PIL.Image`` of this frame.
704
705 Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`.
706
707 .. note:: PIL or Pillow must be installed.
708
709 """
710 from PIL import Image
711
712 plane: VideoPlane = self.reformat(format="rgb24", **kwargs).planes[0]
713
714 i_buf: cython.const[uint8_t][:] = plane
715 line_size: cython.int = plane.line_size
716 i_stride: cython.size_t = abs(line_size)
717
718 o_pos: cython.size_t = 0
719 o_stride: cython.size_t = plane.width * 3
720 o_size: cython.size_t = plane.height * o_stride
721 o_buf: bytearray = bytearray(o_size)
722
723 # For bottom-up frames (negative line_size) the buffer protocol exposes
724 # rows from the lowest address, so the top display row is at the far end.
725 i_pos: cython.size_t = (plane.height - 1) * i_stride if line_size < 0 else 0
726
727 while o_pos < o_size:
728 o_buf[o_pos : o_pos + o_stride] = i_buf[i_pos : i_pos + o_stride]
729 if line_size < 0:
730 i_pos -= i_stride
731 else:
732 i_pos += i_stride
733 o_pos += o_stride
734
735 return Image.frombytes(
736 "RGB", (plane.width, plane.height), bytes(o_buf), "raw", "RGB", 0, 1
737 )
738
739 def to_ndarray(self, channel_last=False, **kwargs):
740 """Get a numpy array of this frame.
741
742 Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`.
743
744 The array returned is generally of dimension (height, width, channels).
745
746 :param bool channel_last: If True, the shape of array will be
747 (height, width, channels) rather than (channels, height, width) for
748 the "yuv444p" and "yuvj444p" formats.
749
750 .. note:: Numpy must be installed.
751
752 .. note:: For formats which return an array of ``uint16``, ``float16`` or ``float32``,
753 the samples will be in the system's native byte order.
754
755 .. note:: For ``pal8``, an ``(image, palette)`` tuple will be returned,
756 with the palette being in ARGB (PyAV will swap bytes if needed).
757
758 .. note:: For ``gbrp`` formats, channels are flipped to RGB order.
759
760 """
761 if self.ptr.hw_frames_ctx and "format" not in kwargs:
762 frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast(
763 cython.pointer[lib.AVHWFramesContext], self.ptr.hw_frames_ctx.data
764 )
765 kwargs = dict(kwargs)
766 kwargs["format"] = get_video_format(
767 frames_ctx.sw_format, self.ptr.width, self.ptr.height
768 ).name
769
770 frame: VideoFrame = self.reformat(**kwargs) if len(kwargs) > 0 else self
771 if frame.ptr.hw_frames_ctx:
772 raise ValueError("Cannot convert a hardware frame to numpy directly.")
773
774 import numpy as np
775
776 # check size
777 format_name = frame.format.name
778 planes: tuple[VideoPlane, ...] = frame.planes
779 # cases planes are simply concatenated in shape (height, width, channels)
780 if format_name in _np_pix_fmt_dtypes:
781 if format_name == "yuyv422":
782 assert frame.ptr.width % 2 == 0, "width has to be even for yuyv422"
783 assert frame.ptr.height % 2 == 0, "height has to be even for yuyv422"
784 itemsize: cython.uint
785 itemsize, dtype = _np_pix_fmt_dtypes[format_name]
786 num_planes: cython.size_t = len(planes)
787 if num_planes == 1: # shortcut, avoid memory copy
788 array = useful_array(planes[0], itemsize, dtype)
789 else: # general case
790 array = np.empty(
791 (frame.ptr.height, frame.ptr.width, num_planes), dtype=dtype
792 )
793 if format_name.startswith("gbr"):
794 plane_indices = (2, 0, 1, *range(3, num_planes))
795 else:
796 plane_indices = range(num_planes)
797 for i, p_idx in enumerate(plane_indices):
798 array[:, :, i] = useful_array(planes[p_idx], itemsize, dtype)
799 array = byteswap_array(array, format_name.endswith("be"))
800 if not channel_last and format_name in {"yuv444p", "yuvj444p"}:
801 array = np.moveaxis(array, 2, 0)
802 return array
803
804 # special cases
805 if format_name in {"yuv420p", "yuvj420p", "yuv422p"}:
806 assert frame.ptr.width % 2 == 0, "width has to be even for this format"
807 assert frame.ptr.height % 2 == 0, "height has to be even for this format"
808 return np.hstack(
809 [
810 useful_array(planes[0]).reshape(-1),
811 useful_array(planes[1]).reshape(-1),
812 useful_array(planes[2]).reshape(-1),
813 ]
814 ).reshape(-1, frame.ptr.width)
815 if format_name == "yuv422p10le":
816 assert frame.ptr.width % 2 == 0, "width has to be even for this format"
817 assert frame.ptr.height % 2 == 0, "height has to be even for this format"
818 # Read planes as uint16 at their original width
819 y = useful_array(planes[0], 2, "uint16")
820 u = useful_array(planes[1], 2, "uint16")
821 v = useful_array(planes[2], 2, "uint16")
822
823 # Double the width of U and V by repeating each value
824 u_full = np.repeat(u, 2, axis=1)
825 v_full = np.repeat(v, 2, axis=1)
826 if channel_last:
827 return np.stack([y, u_full, v_full], axis=2)
828 return np.stack([y, u_full, v_full], axis=0)
829 if format_name == "pal8":
830 image = useful_array(planes[0])
831 palette = (
832 np.frombuffer(planes[1], "i4")
833 .astype(">i4")
834 .reshape(-1, 1)
835 .view(np.uint8)
836 )
837 return image, palette
838 if format_name == "nv12":
839 return np.hstack(
840 [
841 useful_array(planes[0]).reshape(-1),
842 useful_array(planes[1], 2).reshape(-1),
843 ]
844 ).reshape(-1, frame.ptr.width)
845
846 raise ValueError(
847 f"Conversion to numpy array with format `{format_name}` is not yet supported"
848 )
849
850 def set_image(self, img):
851 """
852 Update content from a ``PIL.Image``.
853 """
854 if img.mode != "RGB":
855 img = img.convert("RGB")
856
857 copy_array_to_plane(img, self.planes[0], 3)
858
859 @staticmethod
860 def from_image(img):
861 """
862 Construct a frame from a ``PIL.Image``.
863 """
864 frame: VideoFrame = VideoFrame(img.size[0], img.size[1], "rgb24")
865 frame.set_image(img)
866
867 return frame
868
869 @staticmethod
870 def from_numpy_buffer(array, format="rgb24", width=0):
871 """
872 Construct a frame from a numpy buffer.
873
874 :param int width: optional width of actual image, if different from the array width.
875
876 .. note:: For formats which expect an array of ``uint16``, ``float16`` or ``float32``,
877 the samples must be in the system's native byte order.
878
879 .. note:: for ``gbrp`` formats, channels are assumed to be given in RGB order.
880
881 .. note:: For formats where width of the array is not the same as the width of the image,
882 for example with yuv420p images the UV rows at the bottom have padding bytes in the middle of the
883 row as well as at the end. To cope with these, callers need to be able to pass the actual width.
884 """
885 import numpy as np
886
887 height = array.shape[0]
888 if not width:
889 width = array.shape[1]
890
891 if format in {"rgb24", "bgr24"}:
892 check_ndarray(array, "uint8", 3)
893 check_ndarray_shape(array, array.shape[2] == 3)
894 if array.strides[1:] != (3, 1):
895 raise ValueError("provided array does not have C_CONTIGUOUS rows")
896 linesizes = (array.strides[0],)
897 elif format in {"rgb48le", "rgb48be", "bgr48le", "bgr48be"}:
898 check_ndarray(array, "uint16", 3)
899 check_ndarray_shape(array, array.shape[2] == 3)
900 if array.strides[1:] != (6, 2):
901 raise ValueError("provided array does not have C_CONTIGUOUS rows")
902 linesizes = (array.strides[0],)
903 elif format in {"rgbf32le", "rgbf32be"}:
904 check_ndarray(array, "float32", 3)
905 check_ndarray_shape(array, array.shape[2] == 3)
906 if array.strides[1:] != (12, 4):
907 raise ValueError("provided array does not have C_CONTIGUOUS rows")
908 linesizes = (array.strides[0],)
909 elif format in {"rgba", "bgra", "argb", "abgr"}:
910 check_ndarray(array, "uint8", 3)
911 check_ndarray_shape(array, array.shape[2] == 4)
912 if array.strides[1:] != (4, 1):
913 raise ValueError("provided array does not have C_CONTIGUOUS rows")
914 linesizes = (array.strides[0],)
915 elif format in {"rgba64le", "rgba64be", "bgra64le", "bgra64be"}:
916 check_ndarray(array, "uint16", 3)
917 check_ndarray_shape(array, array.shape[2] == 4)
918 if array.strides[1:] != (8, 2):
919 raise ValueError("provided array does not have C_CONTIGUOUS rows")
920 linesizes = (array.strides[0],)
921 elif format in {"rgbaf16le", "rgbaf16be"}:
922 check_ndarray(array, "float16", 3)
923 check_ndarray_shape(array, array.shape[2] == 4)
924 if array.strides[1:] != (8, 2):
925 raise ValueError("provided array does not have C_CONTIGUOUS rows")
926 linesizes = (array.strides[0],)
927 elif format in {"rgbaf32le", "rgbaf32be"}:
928 check_ndarray(array, "float32", 3)
929 check_ndarray_shape(array, array.shape[2] == 4)
930 if array.strides[1:] != (16, 4):
931 raise ValueError("provided array does not have C_CONTIGUOUS rows")
932 linesizes = (array.strides[0],)
933 elif format in {
934 "gray",
935 "gray8",
936 "rgb8",
937 "bgr8",
938 "bayer_bggr8",
939 "bayer_gbrg8",
940 "bayer_grbg8",
941 "bayer_rggb8",
942 }:
943 check_ndarray(array, "uint8", 2)
944 if array.strides[1] != 1:
945 raise ValueError("provided array does not have C_CONTIGUOUS rows")
946 linesizes = (array.strides[0],)
947 elif format in {
948 "gray9be",
949 "gray9le",
950 "gray10be",
951 "gray10le",
952 "gray12be",
953 "gray12le",
954 "gray14be",
955 "gray14le",
956 "gray16be",
957 "gray16le",
958 "bayer_bggr16be",
959 "bayer_bggr16le",
960 "bayer_gbrg16be",
961 "bayer_gbrg16le",
962 "bayer_grbg16be",
963 "bayer_grbg16le",
964 "bayer_rggb16be",
965 "bayer_rggb16le",
966 }:
967 check_ndarray(array, "uint16", 2)
968 if array.strides[1] != 2:
969 raise ValueError("provided array does not have C_CONTIGUOUS rows")
970 linesizes = (array.strides[0],)
971 elif format in {"grayf32le", "grayf32be"}:
972 check_ndarray(array, "float32", 2)
973 if array.strides[1] != 4:
974 raise ValueError("provided array does not have C_CONTIGUOUS rows")
975 linesizes = (array.strides[0],)
976 elif format in {"gbrp"}:
977 check_ndarray(array, "uint8", 3)
978 check_ndarray_shape(array, array.shape[2] == 3)
979 if array.strides[1:] != (3, 1):
980 raise ValueError("provided array does not have C_CONTIGUOUS rows")
981 linesizes = (
982 array.strides[0] // 3,
983 array.strides[0] // 3,
984 array.strides[0] // 3,
985 )
986 elif format in {
987 "gbrp9be",
988 "gbrp9le",
989 "gbrp10be",
990 "gbrp10le",
991 "gbrp12be",
992 "gbrp12le",
993 "gbrp14be",
994 "gbrp14le",
995 "gbrp16be",
996 "gbrp16le",
997 }:
998 check_ndarray(array, "uint16", 3)
999 check_ndarray_shape(array, array.shape[2] == 3)
1000 if array.strides[1:] != (6, 2):
1001 raise ValueError("provided array does not have C_CONTIGUOUS rows")
1002 linesizes = (
1003 array.strides[0] // 3,
1004 array.strides[0] // 3,
1005 array.strides[0] // 3,
1006 )
1007 elif format in {"gbrpf32be", "gbrpf32le"}:
1008 check_ndarray(array, "float32", 3)
1009 check_ndarray_shape(array, array.shape[2] == 3)
1010 if array.strides[1:] != (12, 4):
1011 raise ValueError("provided array does not have C_CONTIGUOUS rows")
1012 linesizes = (
1013 array.strides[0] // 3,
1014 array.strides[0] // 3,
1015 array.strides[0] // 3,
1016 )
1017 elif format in {"gbrap"}:
1018 check_ndarray(array, "uint8", 3)
1019 check_ndarray_shape(array, array.shape[2] == 4)
1020 if array.strides[1:] != (4, 1):
1021 raise ValueError("provided array does not have C_CONTIGUOUS rows")
1022 linesizes = (
1023 array.strides[0] // 4,
1024 array.strides[0] // 4,
1025 array.strides[0] // 4,
1026 array.strides[0] // 4,
1027 )
1028 elif format in {
1029 "gbrap10be",
1030 "gbrap10le",
1031 "gbrap12be",
1032 "gbrap12le",
1033 "gbrap14be",
1034 "gbrap14le",
1035 "gbrap16be",
1036 "gbrap16le",
1037 }:
1038 check_ndarray(array, "uint16", 3)
1039 check_ndarray_shape(array, array.shape[2] == 4)
1040 if array.strides[1:] != (8, 2):
1041 raise ValueError("provided array does not have C_CONTIGUOUS rows")
1042 linesizes = (
1043 array.strides[0] // 4,
1044 array.strides[0] // 4,
1045 array.strides[0] // 4,
1046 array.strides[0] // 4,
1047 )
1048 elif format in {"gbrapf32be", "gbrapf32le"}:
1049 check_ndarray(array, "float32", 3)
1050 check_ndarray_shape(array, array.shape[2] == 4)
1051 if array.strides[1:] != (16, 4):
1052 raise ValueError("provided array does not have C_CONTIGUOUS rows")
1053 linesizes = (
1054 array.strides[0] // 4,
1055 array.strides[0] // 4,
1056 array.strides[0] // 4,
1057 array.strides[0] // 4,
1058 )
1059 elif format in {"yuv420p", "yuvj420p", "nv12"}:
1060 check_ndarray(array, "uint8", 2)
1061 check_ndarray_shape(array, array.shape[0] % 3 == 0)
1062 check_ndarray_shape(array, array.shape[1] % 2 == 0)
1063 height = height // 6 * 4
1064 if array.strides[1] != 1:
1065 raise ValueError("provided array does not have C_CONTIGUOUS rows")
1066 if format in {"yuv420p", "yuvj420p"}:
1067 # For YUV420 planar formats, the UV plane stride is always half the Y stride.
1068 linesizes = (
1069 array.strides[0],
1070 array.strides[0] // 2,
1071 array.strides[0] // 2,
1072 )
1073 else:
1074 # Planes where U and V are interleaved have the same stride as Y.
1075 linesizes = (array.strides[0], array.strides[0])
1076 else:
1077 raise ValueError(
1078 f"Conversion from numpy array with format `{format}` is not yet supported"
1079 )
1080
1081 if format.startswith("gbrap"): # rgba -> gbra
1082 array = np.ascontiguousarray(np.moveaxis(array[..., [1, 2, 0, 3]], -1, 0))
1083 elif format.startswith("gbrp"): # rgb -> gbr
1084 array = np.ascontiguousarray(np.moveaxis(array[..., [1, 2, 0]], -1, 0))
1085
1086 frame = VideoFrame(_cinit_bypass_sentinel)
1087 frame._image_fill_pointers_numpy(array, width, height, linesizes, format)
1088 return frame
1089
1090 def _image_fill_pointers_numpy(self, buffer, width, height, linesizes, format):
1091 # If you want to use the numpy notation, then you need to include the following lines at the top of the file:
1092 # cimport numpy as cnp
1093 # cnp.import_array()
1094
1095 # And add the numpy include directories to the setup.py files
1096 # hint np.get_include()
1097 # cdef cnp.ndarray[
1098 # dtype=cnp.uint8_t, ndim=1,
1099 # negative_indices=False, mode='c'] c_buffer
1100 # c_buffer = buffer.reshape(-1)
1101 # c_ptr = &c_buffer[0]
1102 # c_ptr = <uint8_t*> (<void*>(buffer.ctypes.data))
1103
1104 # Using buffer.ctypes.data helps avoid any kind of usage of the c-api from
1105 # numpy, which avoid the need to add numpy as a compile time dependency.
1106
1107 c_data: cython.Py_ssize_t = buffer.ctypes.data
1108 c_ptr: cython.pointer[uint8_t] = cython.cast(cython.pointer[uint8_t], c_data)
1109 c_format: lib.AVPixelFormat = get_pix_fmt(format)
1110 lib.av_frame_unref(self.ptr)
1111
1112 # Hold on to a reference for the numpy buffer so that it doesn't get accidentally garbage collected
1113 self.ptr.format = c_format
1114 self.ptr.width = width
1115 self.ptr.height = height
1116 for i, linesize in enumerate(linesizes):
1117 self.ptr.linesize[i] = linesize
1118
1119 required = err_check(
1120 lib.av_image_fill_pointers(
1121 self.ptr.data,
1122 cython.cast(lib.AVPixelFormat, self.ptr.format),
1123 self.ptr.height,
1124 c_ptr,
1125 self.ptr.linesize,
1126 )
1127 )
1128
1129 py_buf = cython.cast(object, buffer)
1130 Py_INCREF(py_buf)
1131
1132 self.ptr.buf[0] = lib.av_buffer_create(
1133 c_ptr,
1134 required,
1135 _numpy_avbuffer_free,
1136 cython.cast(cython.p_void, py_buf),
1137 0,
1138 )
1139 if self.ptr.buf[0] == cython.NULL:
1140 Py_DECREF(py_buf)
1141 raise MemoryError("av_buffer_create failed")
1142
1143 self._init_user_attributes()
1144
1145 @staticmethod
1146 def from_ndarray(array, format="rgb24", channel_last=False):
1147 """
1148 Construct a frame from a numpy array.
1149
1150 :param bool channel_last: If False (default), the shape for the yuv444p and yuvj444p
1151 is given by (channels, height, width) rather than (height, width, channels).
1152
1153 .. note:: For formats which expect an array of ``uint16``, ``float16`` or ``float32``,
1154 the samples must be in the system's native byte order.
1155
1156 .. note:: for ``pal8``, an ``(image, palette)`` pair must be passed. `palette` must
1157 have shape (256, 4) and is given in ARGB format (PyAV will swap bytes if needed).
1158
1159 .. note:: for ``gbrp`` formats, channels are assumed to be given in RGB order.
1160
1161 """
1162 import numpy as np
1163
1164 # case layers are concatenated
1165 channels, itemsize, dtype = {
1166 "bayer_bggr16be": (1, 2, "uint16"),
1167 "bayer_bggr16le": (1, 2, "uint16"),
1168 "bayer_bggr8": (1, 1, "uint8"),
1169 "bayer_gbrg16be": (1, 2, "uint16"),
1170 "bayer_gbrg16le": (1, 2, "uint16"),
1171 "bayer_gbrg8": (1, 1, "uint8"),
1172 "bayer_grbg16be": (1, 2, "uint16"),
1173 "bayer_grbg16le": (1, 2, "uint16"),
1174 "bayer_grbg8": (1, 1, "uint8"),
1175 "bayer_rggb16be": (1, 2, "uint16"),
1176 "bayer_rggb16le": (1, 2, "uint16"),
1177 "bayer_rggb8": (1, 1, "uint8"),
1178 "bgr8": (1, 1, "uint8"),
1179 "gbrap": (4, 1, "uint8"),
1180 "gbrap10be": (4, 2, "uint16"),
1181 "gbrap10le": (4, 2, "uint16"),
1182 "gbrap12be": (4, 2, "uint16"),
1183 "gbrap12le": (4, 2, "uint16"),
1184 "gbrap14be": (4, 2, "uint16"),
1185 "gbrap14le": (4, 2, "uint16"),
1186 "gbrap16be": (4, 2, "uint16"),
1187 "gbrap16le": (4, 2, "uint16"),
1188 "gbrapf32be": (4, 4, "float32"),
1189 "gbrapf32le": (4, 4, "float32"),
1190 "gbrp": (3, 1, "uint8"),
1191 "gbrp10be": (3, 2, "uint16"),
1192 "gbrp10le": (3, 2, "uint16"),
1193 "gbrp12be": (3, 2, "uint16"),
1194 "gbrp12le": (3, 2, "uint16"),
1195 "gbrp14be": (3, 2, "uint16"),
1196 "gbrp14le": (3, 2, "uint16"),
1197 "gbrp16be": (3, 2, "uint16"),
1198 "gbrp16le": (3, 2, "uint16"),
1199 "gbrp9be": (3, 2, "uint16"),
1200 "gbrp9le": (3, 2, "uint16"),
1201 "gbrpf32be": (3, 4, "float32"),
1202 "gbrpf32le": (3, 4, "float32"),
1203 "gray": (1, 1, "uint8"),
1204 "gray10be": (1, 2, "uint16"),
1205 "gray10le": (1, 2, "uint16"),
1206 "gray12be": (1, 2, "uint16"),
1207 "gray12le": (1, 2, "uint16"),
1208 "gray14be": (1, 2, "uint16"),
1209 "gray14le": (1, 2, "uint16"),
1210 "gray16be": (1, 2, "uint16"),
1211 "gray16le": (1, 2, "uint16"),
1212 "gray8": (1, 1, "uint8"),
1213 "gray9be": (1, 2, "uint16"),
1214 "gray9le": (1, 2, "uint16"),
1215 "grayf32be": (1, 4, "float32"),
1216 "grayf32le": (1, 4, "float32"),
1217 "rgb8": (1, 1, "uint8"),
1218 "yuv444p": (3, 1, "uint8"),
1219 "yuv444p16be": (3, 2, "uint16"),
1220 "yuv444p16le": (3, 2, "uint16"),
1221 "yuva444p16be": (4, 2, "uint16"),
1222 "yuva444p16le": (4, 2, "uint16"),
1223 "yuvj444p": (3, 1, "uint8"),
1224 }.get(format, (None, None, None))
1225 if channels is not None:
1226 if array.ndim == 2: # (height, width) -> (height, width, 1)
1227 array = array[:, :, None]
1228 check_ndarray(array, dtype, 3)
1229 if not channel_last and format in {"yuv444p", "yuvj444p"}:
1230 array = np.moveaxis(array, 0, 2) # (channels, h, w) -> (h, w, channels)
1231 check_ndarray_shape(array, array.shape[2] == channels)
1232 array = byteswap_array(array, format.endswith("be"))
1233 frame = VideoFrame(array.shape[1], array.shape[0], format)
1234 if frame.format.name.startswith("gbr"): # rgb -> gbr
1235 array = np.concatenate(
1236 [ # not inplace to avoid bad surprises
1237 array[:, :, 1:3],
1238 array[:, :, 0:1],
1239 array[:, :, 3:],
1240 ],
1241 axis=2,
1242 )
1243 for i in range(channels):
1244 copy_array_to_plane(array[:, :, i], frame.planes[i], itemsize)
1245 return frame
1246
1247 # other cases
1248 if format == "pal8":
1249 array, palette = array
1250 check_ndarray(array, "uint8", 2)
1251 check_ndarray(palette, "uint8", 2)
1252 check_ndarray_shape(palette, palette.shape == (256, 4))
1253
1254 frame = VideoFrame(array.shape[1], array.shape[0], format)
1255 copy_array_to_plane(array, frame.planes[0], 1)
1256 frame.planes[1].update(palette.view(">i4").astype("i4").tobytes())
1257 return frame
1258 elif format in {"yuv420p", "yuvj420p"}:
1259 check_ndarray(array, "uint8", 2)
1260 check_ndarray_shape(array, array.shape[0] % 3 == 0)
1261 check_ndarray_shape(array, array.shape[1] % 2 == 0)
1262
1263 frame = VideoFrame(array.shape[1], (array.shape[0] * 2) // 3, format)
1264 u_start = frame.width * frame.height
1265 v_start = 5 * u_start // 4
1266 flat = array.reshape(-1)
1267 copy_array_to_plane(flat[0:u_start], frame.planes[0], 1)
1268 copy_array_to_plane(flat[u_start:v_start], frame.planes[1], 1)
1269 copy_array_to_plane(flat[v_start:], frame.planes[2], 1)
1270 return frame
1271 elif format == "yuv422p":
1272 check_ndarray(array, "uint8", 2)
1273 check_ndarray_shape(array, array.shape[0] % 4 == 0)
1274 check_ndarray_shape(array, array.shape[1] % 2 == 0)
1275
1276 frame = VideoFrame(array.shape[1], array.shape[0] // 2, format)
1277 u_start = frame.width * frame.height
1278 v_start = u_start + u_start // 2
1279 flat = array.reshape(-1)
1280 copy_array_to_plane(flat[0:u_start], frame.planes[0], 1)
1281 copy_array_to_plane(flat[u_start:v_start], frame.planes[1], 1)
1282 copy_array_to_plane(flat[v_start:], frame.planes[2], 1)
1283 return frame
1284 elif format == "yuv422p10le":
1285 if not isinstance(array, np.ndarray) or array.dtype != np.uint16:
1286 raise ValueError("Array must be uint16 type")
1287
1288 # Convert to channel-first if needed
1289 if channel_last and array.shape[2] == 3:
1290 array = np.moveaxis(array, 2, 0)
1291 elif not (array.shape[0] == 3):
1292 raise ValueError(
1293 "Array must have shape (3, height, width) or (height, width, 3)"
1294 )
1295
1296 height, width = array.shape[1:]
1297 if width % 2 != 0 or height % 2 != 0:
1298 raise ValueError("Width and height must be even")
1299
1300 frame = VideoFrame(width, height, format)
1301 copy_array_to_plane(array[0], frame.planes[0], 2)
1302 # Subsample U and V by taking every other column
1303 u = array[1, :, ::2].copy() # Need copy to ensure C-contiguous
1304 v = array[2, :, ::2].copy() # Need copy to ensure C-contiguous
1305 copy_array_to_plane(u, frame.planes[1], 2)
1306 copy_array_to_plane(v, frame.planes[2], 2)
1307 return frame
1308 elif format == "yuyv422":
1309 check_ndarray(array, "uint8", 3)
1310 check_ndarray_shape(array, array.shape[0] % 2 == 0)
1311 check_ndarray_shape(array, array.shape[1] % 2 == 0)
1312 check_ndarray_shape(array, array.shape[2] == 2)
1313 elif format in {"rgb24", "bgr24"}:
1314 check_ndarray(array, "uint8", 3)
1315 check_ndarray_shape(array, array.shape[2] == 3)
1316 elif format in {"argb", "rgba", "abgr", "bgra"}:
1317 check_ndarray(array, "uint8", 3)
1318 check_ndarray_shape(array, array.shape[2] == 4)
1319 elif format in {"rgb48be", "rgb48le", "bgr48be", "bgr48le"}:
1320 check_ndarray(array, "uint16", 3)
1321 check_ndarray_shape(array, array.shape[2] == 3)
1322 frame = VideoFrame(array.shape[1], array.shape[0], format)
1323 copy_array_to_plane(
1324 byteswap_array(array, format.endswith("be")), frame.planes[0], 6
1325 )
1326 return frame
1327 elif format in {"rgbf32be", "rgbf32le"}:
1328 check_ndarray(array, "float32", 3)
1329 check_ndarray_shape(array, array.shape[2] == 3)
1330 frame = VideoFrame(array.shape[1], array.shape[0], format)
1331 copy_array_to_plane(
1332 byteswap_array(array, format.endswith("be")), frame.planes[0], 12
1333 )
1334 return frame
1335 elif format in {"rgba64be", "rgba64le", "bgra64be", "bgra64le"}:
1336 check_ndarray(array, "uint16", 3)
1337 check_ndarray_shape(array, array.shape[2] == 4)
1338 frame = VideoFrame(array.shape[1], array.shape[0], format)
1339 copy_array_to_plane(
1340 byteswap_array(array, format.endswith("be")), frame.planes[0], 8
1341 )
1342 return frame
1343 elif format in {"rgbaf16be", "rgbaf16le"}:
1344 check_ndarray(array, "float16", 3)
1345 check_ndarray_shape(array, array.shape[2] == 4)
1346 frame = VideoFrame(array.shape[1], array.shape[0], format)
1347 copy_array_to_plane(
1348 byteswap_array(array, format.endswith("be")), frame.planes[0], 8
1349 )
1350 return frame
1351 elif format in {"rgbaf32be", "rgbaf32le"}:
1352 check_ndarray(array, "float32", 3)
1353 check_ndarray_shape(array, array.shape[2] == 4)
1354 frame = VideoFrame(array.shape[1], array.shape[0], format)
1355 copy_array_to_plane(
1356 byteswap_array(array, format.endswith("be")), frame.planes[0], 16
1357 )
1358 return frame
1359 elif format == "nv12":
1360 check_ndarray(array, "uint8", 2)
1361 check_ndarray_shape(array, array.shape[0] % 3 == 0)
1362 check_ndarray_shape(array, array.shape[1] % 2 == 0)
1363
1364 frame = VideoFrame(array.shape[1], (array.shape[0] * 2) // 3, format)
1365 uv_start = frame.width * frame.height
1366 flat = array.reshape(-1)
1367 copy_array_to_plane(flat[:uv_start], frame.planes[0], 1)
1368 copy_array_to_plane(flat[uv_start:], frame.planes[1], 2)
1369 return frame
1370 else:
1371 raise ValueError(
1372 f"Conversion from numpy array with format `{format}` is not yet supported"
1373 )
1374
1375 frame = VideoFrame(array.shape[1], array.shape[0], format)
1376 copy_array_to_plane(
1377 array, frame.planes[0], 1 if array.ndim == 2 else array.shape[2]
1378 )
1379
1380 return frame
1381
1382 @staticmethod
1383 def from_bytes(
1384 img_bytes: bytes,
1385 width: int,
1386 height: int,
1387 format="rgba",
1388 flip_horizontal=False,
1389 flip_vertical=False,
1390 ):
1391 frame = VideoFrame(width, height, format)
1392 if format == "rgba":
1393 copy_bytes_to_plane(
1394 img_bytes, frame.planes[0], 4, flip_horizontal, flip_vertical
1395 )
1396 elif format in {
1397 "bayer_bggr8",
1398 "bayer_rggb8",
1399 "bayer_gbrg8",
1400 "bayer_grbg8",
1401 "bayer_bggr16le",
1402 "bayer_rggb16le",
1403 "bayer_gbrg16le",
1404 "bayer_grbg16le",
1405 "bayer_bggr16be",
1406 "bayer_rggb16be",
1407 "bayer_gbrg16be",
1408 "bayer_grbg16be",
1409 }:
1410 copy_bytes_to_plane(
1411 img_bytes,
1412 frame.planes[0],
1413 1 if format.endswith("8") else 2,
1414 flip_horizontal,
1415 flip_vertical,
1416 )
1417 else:
1418 raise NotImplementedError(f"Format '{format}' is not supported.")
1419 return frame
1420
1421 @staticmethod
1422 def from_dlpack(
1423 planes,
1424 format: str = "nv12",
1425 width: int = 0,
1426 height: int = 0,
1427 stream=None,
1428 device_id: int | None = None,
1429 primary_ctx: bool = True,
1430 cuda_context=None,
1431 ):
1432 if not isinstance(planes, (tuple, list)):
1433 planes = (planes,)
1434
1435 if len(planes) != 2:
1436 raise ValueError(
1437 "from_dlpack currently supports 2-plane formats only (nv12/p010le/p016le)"
1438 )
1439
1440 sw_fmt: lib.AVPixelFormat = get_pix_fmt(format)
1441 nv12 = get_pix_fmt(b"nv12")
1442 p010le = get_pix_fmt(b"p010le")
1443 p016le = get_pix_fmt(b"p016le")
1444
1445 if sw_fmt not in (nv12, p010le, p016le):
1446 raise NotImplementedError("from_dlpack supports nv12, p010le, p016le only")
1447
1448 expected_bits = 8 if sw_fmt == nv12 else 16
1449 itemsize = 1 if expected_bits == 8 else 2
1450
1451 m0: cython.pointer[DLManagedTensor] = cython.NULL
1452 m1: cython.pointer[DLManagedTensor] = cython.NULL
1453 frame: VideoFrame = None
1454
1455 try:
1456 m0 = _consume_dlpack(planes[0], stream)
1457 m1 = _consume_dlpack(planes[1], stream)
1458
1459 dev_type0 = m0.dl_tensor.device_type
1460 dev_type1 = m1.dl_tensor.device_type
1461 if dev_type0 != dev_type1:
1462 raise ValueError("plane tensors must have the same device_type")
1463 if dev_type0 not in (kCuda, kCPU):
1464 raise NotImplementedError(
1465 "only CPU and CUDA DLPack tensors are supported"
1466 )
1467
1468 dev0 = m0.dl_tensor.device_id
1469 dev1 = m1.dl_tensor.device_id
1470 if dev0 != dev1:
1471 raise ValueError("plane tensors must be on the same CUDA device")
1472 if dev_type0 == kCuda:
1473 if device_id is None:
1474 device_id = dev0
1475 elif device_id != dev0:
1476 raise ValueError(
1477 "device_id does not match the DLPack tensor device_id"
1478 )
1479 else:
1480 if device_id not in (None, 0):
1481 raise ValueError("device_id must be 0 for CPU tensors")
1482 device_id = 0
1483 if dev_type0 == kCPU and (dev0 != 0 or dev1 != 0):
1484 raise ValueError("CPU DLPack tensors must have device_id == 0")
1485
1486 if (
1487 m0.dl_tensor.dtype.code != 1
1488 or m0.dl_tensor.dtype.bits != expected_bits
1489 or m0.dl_tensor.dtype.lanes != 1
1490 ):
1491 raise TypeError("unexpected dtype for plane 0")
1492 if (
1493 m1.dl_tensor.dtype.code != 1
1494 or m1.dl_tensor.dtype.bits != expected_bits
1495 or m1.dl_tensor.dtype.lanes != 1
1496 ):
1497 raise TypeError("unexpected dtype for plane 1")
1498
1499 if m0.dl_tensor.ndim != 2:
1500 raise ValueError("plane 0 must be 2D (H, W)")
1501
1502 y_h = cython.cast(int64_t, m0.dl_tensor.shape[0])
1503 y_w = cython.cast(int64_t, m0.dl_tensor.shape[1])
1504
1505 if width == 0 and height == 0:
1506 width = cython.cast(int, y_w)
1507 height = cython.cast(int, y_h)
1508 elif width == 0 or height == 0:
1509 raise ValueError("either specify both width/height or neither")
1510 else:
1511 if y_w != width or y_h != height:
1512 raise ValueError("plane 0 shape does not match width/height")
1513
1514 if width % 2 or height % 2:
1515 raise ValueError("width/height must be even for nv12/p010le/p016le")
1516
1517 if m0.dl_tensor.strides != cython.NULL:
1518 if m0.dl_tensor.strides[1] != 1:
1519 raise ValueError("plane 0 must be contiguous in the last dimension")
1520 y_pitch_elems = cython.cast(int64_t, m0.dl_tensor.strides[0])
1521 else:
1522 y_pitch_elems = cython.cast(int64_t, width)
1523
1524 y_linesize = cython.cast(int, y_pitch_elems * itemsize)
1525 y_size = cython.cast(int, y_linesize * height)
1526
1527 uv_ndim = m1.dl_tensor.ndim
1528 uv_h_expected = height // 2
1529
1530 if uv_ndim == 2:
1531 uv_h = cython.cast(int, m1.dl_tensor.shape[0])
1532 uv_w = cython.cast(int, m1.dl_tensor.shape[1])
1533 if uv_h != uv_h_expected or uv_w != width:
1534 raise ValueError("plane 1 must have shape (H/2, W) for 2D UV")
1535 if m1.dl_tensor.strides != cython.NULL:
1536 if m1.dl_tensor.strides[1] != 1:
1537 raise ValueError(
1538 "plane 1 must be contiguous in the last dimension"
1539 )
1540 uv_pitch_elems = cython.cast(int64_t, m1.dl_tensor.strides[0])
1541 else:
1542 uv_pitch_elems = cython.cast(int64_t, uv_w)
1543 elif uv_ndim == 3:
1544 uv_h = cython.cast(int, m1.dl_tensor.shape[0])
1545 uv_w2 = cython.cast(int, m1.dl_tensor.shape[1])
1546 uv_c = cython.cast(int, m1.dl_tensor.shape[2])
1547 if uv_h != uv_h_expected or uv_w2 != (width // 2) or uv_c != 2:
1548 raise ValueError("plane 1 must have shape (H/2, W/2, 2) for 3D UV")
1549 if m1.dl_tensor.strides != cython.NULL:
1550 if m1.dl_tensor.strides[2] != 1 or m1.dl_tensor.strides[1] != 2:
1551 raise ValueError(
1552 "unexpected UV plane strides for (H/2, W/2, 2)"
1553 )
1554 uv_pitch_elems = cython.cast(int64_t, m1.dl_tensor.strides[0])
1555 else:
1556 uv_pitch_elems = cython.cast(int64_t, width)
1557 else:
1558 raise ValueError("plane 1 must be 2D or 3D")
1559
1560 uv_linesize = cython.cast(int, uv_pitch_elems * itemsize)
1561 uv_size = cython.cast(int, uv_linesize * (height // 2))
1562
1563 frame = alloc_video_frame()
1564 frame.ptr.width = width
1565 frame.ptr.height = height
1566 if dev_type0 == kCuda:
1567 ctx: CudaContext
1568 frames_ref: cython.pointer[lib.AVBufferRef]
1569 if cuda_context is None:
1570 ctx = CudaContext(device_id=device_id, primary_ctx=primary_ctx)
1571 else:
1572 if not isinstance(cuda_context, CudaContext):
1573 raise TypeError("cuda_context must be a CudaContext")
1574 if int(cuda_context.device_id) != int(device_id):
1575 raise ValueError(
1576 "cuda_context.device_id does not match the DLPack tensor device_id"
1577 )
1578 if bool(cuda_context.primary_ctx) != bool(primary_ctx):
1579 raise ValueError(
1580 "cuda_context.primary_ctx does not match primary_ctx"
1581 )
1582 ctx = cython.cast(CudaContext, cuda_context)
1583
1584 frames_ref = ctx.get_frames_ctx(sw_fmt, width, height)
1585 frame.ptr.format = get_pix_fmt(b"cuda")
1586 frame.ptr.hw_frames_ctx = frames_ref
1587 frame._device_id = device_id
1588 frame._cuda_ctx = ctx
1589 else:
1590 frame.ptr.format = sw_fmt
1591
1592 y_ptr = cython.cast(
1593 cython.pointer[uint8_t], m0.dl_tensor.data
1594 ) + cython.cast(cython.size_t, m0.dl_tensor.byte_offset)
1595 uv_ptr = cython.cast(
1596 cython.pointer[uint8_t], m1.dl_tensor.data
1597 ) + cython.cast(cython.size_t, m1.dl_tensor.byte_offset)
1598
1599 frame.ptr.buf[0] = lib.av_buffer_create(
1600 y_ptr, y_size, _dlpack_avbuffer_free, cython.cast(cython.p_void, m0), 0
1601 )
1602 if frame.ptr.buf[0] == cython.NULL:
1603 raise MemoryError("av_buffer_create failed for plane 0")
1604 frame.ptr.data[0] = y_ptr
1605 frame.ptr.linesize[0] = y_linesize
1606 m0 = cython.NULL
1607
1608 frame.ptr.buf[1] = lib.av_buffer_create(
1609 uv_ptr,
1610 uv_size,
1611 _dlpack_avbuffer_free,
1612 cython.cast(cython.p_void, m1),
1613 0,
1614 )
1615 if frame.ptr.buf[1] == cython.NULL:
1616 raise MemoryError("av_buffer_create failed for plane 1")
1617 frame.ptr.data[1] = uv_ptr
1618 frame.ptr.linesize[1] = uv_linesize
1619 m1 = cython.NULL
1620
1621 frame._init_user_attributes()
1622 return frame
1623
1624 except Exception:
1625 if frame is not None:
1626 lib.av_frame_unref(frame.ptr)
1627 if m0 != cython.NULL:
1628 m0.deleter(m0)
1629 if m1 != cython.NULL:
1630 m1.deleter(m1)
1631 raise