o
    2jv                     @   s\  d dl Z d dlmZ d dlZd dlm  mZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZmZ d dlmZmZmZmZ d d	lmZ d d
lmZmZmZ d dlmZm Z  d dl!m"Z"m#Z# ej$ej%G dd dZ&ej'de(de(dej)e fddZ*ej'ej+ej,dddej-dej)e# dej.fddZ/ej'ej+ej,dddej-dej)e# dej.fddZ0e1e(e( Z2h dZ3e1e4e5e6ej7e5f f i ddddd d!d"d!d#d!d$d!d%d&d'd&d(d&d)d&d*d&d+d&d,d&d-d&d.d/d0d1d2d1i d3d!d4dd5d6d7d6d8d!d9d&d:d&d;d&d<d&d=d&d>d&d?d&d@d&dAdBdCdBdDd!dEd&i dFd&dGd&dHd&dId&dJd&dKd&dLd&dMd&dNd&dOdBdPdBdQd!dRd&dSd&dTd&dUd&dVd&i dWd&dXd&dYd&dZd!d[d&d\d&d]dBd^dBd_d/d`d1dad1dbd!dcdddd6ded6dfdgdhdgdididjdjd!d&d&d&d&d!dkdlZ8ej'de9fdmdnZ:G dodp dpeZ;e1ej<e j=dqkZ>ej'ej?drej<fdsdtZ@ej'duedvej7dwej<dxej<fdydzZAej'duedvej7fd{d|ZBej'ej?	~d!duedvej7de5fddZCej'de(dej<fddZDej$ej%G dd deEZ9dS )    N)IntEnum)
Dictionary)	err_checkget_display_rotation)check_ndarray)get_pix_fmtget_video_format)DLManagedTensor
VideoPlanekCPUkCuda)PyErr_Clear)PyCapsule_GetPointerPyCapsule_IsValidPyCapsule_SetName)	Py_DECREF	Py_INCREF)int64_tuint8_tc                
   @   sv   e Zd ZddejdejfddZdd Zejd	ej	e
j fd
dZejde
jdejdejd	ej	e
j fddZdS )CudaContextr   T	device_idprimary_ctxc                 C   s   || _ || _tj| _i | _d S N)r   r   cythonNULL_device_ref_frames_cache)selfr   r    r   I/var/www/html/whisper/venv/lib/python3.10/site-packages/av/video/frame.py	__cinit__   s   
zCudaContext.__cinit__c                 C   sx   | j  D ]}ttjtj ttj|}tt	| q| j 
  | j}|tjkr:tt	| tj| _d S d S r   )r   valuesr   castpointerlibAVBufferRefsize_tav_buffer_unrefaddressclearr   r   )r   vrefr   r   r    __dealloc__   s   


zCudaContext.__dealloc__returnc                 C   sj   | j }|tjkr
|S tj}| j  }|}td| jrdndi}tt	t
|tj||jd || _ |S )Nr   10r   )r   r   r   r   encoder   r   r   r%   av_hwdevice_ctx_creater)   AV_HWDEVICE_TYPE_CUDAptr)r   
device_refdevice_bytesc_deviceoptionsr   r   r    _get_device_ref/   s(   
	zCudaContext._get_device_refsw_fmtwidthheightc                 C   s>  t |t |t |f}| j|}|d ur4ttjtj ttj|}t	|}|tj
kr2td|S |  }t|}	|	tj
krFtdz&ttjtj |	j}
td|
_||
_t ||
_t ||
_tt|	 W n ty|   tt|	  w t	|	}|tj
krtt|	 tdttj|	| j|< |S )Nzav_buffer_ref() failedzav_hwframe_ctx_alloc() failed   cuda)intr   getr   r#   r$   r%   r&   r'   av_buffer_refr   MemoryErrorr9   av_hwframe_ctx_allocAVHWFramesContextdatar   format	sw_formatr;   r<   r   av_hwframe_ctx_init	Exceptionr(   r)   )r   r:   r;   r<   keycached
cached_refout_refr5   
frames_ref
frames_ctxr   r   r    get_frames_ctxG   sH   








zCudaContext.get_frames_ctxN)r   T)__name__
__module____qualname__r   r>   bintr!   r-   cfuncr$   r%   r&   r9   AVPixelFormatrO   r   r   r   r    r      s    
r   objstreamr.   c                 C   s   t | dr|d u r|  n| j|d}n| }t|ds"t  tdttjt t	|d}|tj
kr7tdt|ddkrBtd|S )	N
__dlpack__)rW   s   dltensorz>expected a DLPack capsule or an object implementing __dlpack__z"PyCapsule_GetPointer returned NULLs   used_dltensorr   zPyCapsule_SetName failed)hasattrrX   r   r   	TypeErrorr   r#   r$   r
   r   r   
ValueErrorr   RuntimeError)rV   rW   capsulemanagedr   r   r    _consume_dlpack{   s"   


r_   F)checkopaquerD   c                 C   s.   t t jt | }|t jkr|| d S d S r   )r   r#   r$   r
   r   deleter)ra   rD   r^   r   r   r    _dlpack_avbuffer_free   s   

rc   c                 C   sJ   | t jkr#t j tt t|  W d    d S 1 sw   Y  d S d S r   )r   r   gilr   r#   object)ra   rD   r   r   r    _numpy_avbuffer_free   s
   
"rf   >T   abgrargbbgr8bgragbrpgraynv12pal8rgb8rgbabgr24gbrapgray8rgb24bgr48bebgr48legbrp9begbrp9legray9begray9lergb48bergb48leyuv420pyuv444pyuyv422bgra64bebgra64legbrp10begbrp10legbrp12begbrp12legbrp14begbrp14legbrp16begbrp16legray10begray10legray12begray12legray14begray14legray16begray16lergba64bergba64lergbf32bergbf32leyuvj420pyuvj444p	gbrap10be	gbrap10le	gbrap12be	gbrap12le	gbrap14be	gbrap14le	gbrap16be	gbrap16le	gbrpf32be	gbrpf32le	grayf32be	grayf32le	rgbaf16be	rgbaf16le	rgbaf32be	rgbaf32le
gbrapf32be
gbrapf32lebayer_bggr8bayer_gbrg8bayer_grbg8bayer_rggb8yuv422p10leyuv444p16beyuv444p16leyuva444p16beyuva444p16lebayer_bggr16bebayer_bggr16lebayer_gbrg16bebayer_gbrg16lebayer_grbg16bebayer_grbg16lebayer_rggb16bebayer_rggb16lerg   )   uint8rh   r   )   r   r   r   r   r   )   uint16r   r   r   r   r   r   r   rq   )   r   ru   )   r   rv   ri   rj   r   )   r   r   rr   r   r   r   r   r   r   r   r   r   )r   float32r   rk   r   r   r   r   r   r   r   r   rw   rx   r   r   rl   r   r   r   r   r   r   r   r   rs   ry   rz   r   r   rt   r{   r|   ro   rp   r   r   r   )r   float16r   )   r   )   r   )r   r   )r   r   r   r   r~   r   r   r   r   r   r   c                   C   s   t tS )zGet a mostly uninitialized VideoFrame.

    You MUST call VideoFrame._init(...) or VideoFrame._init_user_attributes()
    before exposing to the user.

    )
VideoFrame_cinit_bypass_sentinelr   r   r   r    alloc_video_framed     r   c                   @   s<   e Zd ZejZejZejZ	ej
ZejZejZejZejZdS )PictureTypeN)rP   rQ   rR   r%   AV_PICTURE_TYPE_NONENONEAV_PICTURE_TYPE_IIAV_PICTURE_TYPE_PPAV_PICTURE_TYPE_BBAV_PICTURE_TYPE_SSAV_PICTURE_TYPE_SISIAV_PICTURE_TYPE_SPSPAV_PICTURE_TYPE_BIBIr   r   r   r    r   o  s    
r   big
big_endianc                 C   s   t |kr|  S | S r   )_is_big_endianbyteswap)arrayr   r   r   r    byteswap_array}  s   r   planebytes_per_pixelflip_horizontalflip_verticalc                 C   s   | }d}|j | }|}d}	t|j}
ttj\}}}|r'|jd }d}d}nd}|j}d}t|||D ]=}|| }|r_td||D ]}t|D ]}||| | | |  ||	| | < qHqBn||||  ||	|	| < |	|
7 }	q4d S )Nr   r   )r;   abs	line_sizer   declarer>   r<   range)	img_bytesr   r   r   r   i_bufi_posi_strideo_bufo_poso_stride	start_rowend_rowsteprowijr   r   r    copy_bytes_to_plane  s6   



r   c                 C   s   |   }t|||dd d S )NF)tobytesr   )r   r   r   imgbytesr   r   r    copy_array_to_plane  s   r   r   r   dtypec                 C   s   ddl }||}| jjj| j }t|}|j}|| }|dkr+| j| j	f}	||f}
n| j| j	|f}	|||f}
|dk rW| jd | }| g|
dd R }
|j
|	|| ||
dS |j
|	|| |
dS )z
    Return the useful part of the VideoPlane as a strided array.

    We are simply creating a view that discards any padding which was added for
    alignment.
    r   Nr   )r   bufferoffsetstrides)r   r   r   )numpyr   framer4   linesizeindexr   itemsizer<   r;   ndarray)r   r   r   np	dtype_objr   total_line_sizer  channelsshaper   r   r   r   r    useful_array  s$   



r  r   okc                 C   s   |st d| j dd S )NzUnexpected numpy array shape ``)r[   r
  )r   r  r   r   r    check_ndarray_shape  s   r  c                   @   s  e Zd ZdKddZejdejdejdejfdd	Z	ejd
d Z
dd Zdd Zedd Zedd Zedd Zedd Zedd Zedd Zejdd Zedd Zejdd Zed d! Zejd"d! Zed#d$ Zejd%d$ Zed&d' Zejd(d' Zd)d* Zd+d, Zejd-efd.d/Zd0d1 ZdLd3d4Zd5d6 Z e!d7d8 Z"e!dMd:d;Z#d<d= Z$e!dNd>d?Z%e!	@	2	2dOdAe&de'de'fdBdCZ(e!	D			E	E	F	EdPde)de'de'dGe'dEB dHe*f
dIdJZ+dES )Qr   r   r}   c                 C   s&   |t u rd S t|}| ||| d S r   )r   r   _init)r   r;   r<   rE   c_formatr   r   r    r!     s   zVideoFrame.__cinit__rE   r;   r<   c                 C   sp   d}t j || j_|| j_|| j_|r|rt| jd}W d    n1 s'w   Y  |r2t| | 	  d S )Nr   r   )
r   nogilr4   r;   r<   rE   r%   av_frame_get_bufferr   _init_user_attributes)r   rE   r;   r<   resr   r   r    r    s   
zVideoFrame._initc                 C   s(   t ttj| jj| jj| jj| _d S r   )	r	   r   r#   r%   rU   r4   rE   r;   r<   r   r   r   r    r    s
   
z VideoFrame._init_user_attributesc                 C   s   t | j d S r   )r%   av_frame_unrefr4   r  r   r   r    r-     s   zVideoFrame.__dealloc__c                 C   s>   d| j j d| j d| jj d| j d| j dt| ddS )Nz<av.z, pts= xz at 0x>)	__class__rP   ptsrE   namer;   r<   idr  r   r   r    __repr__  s   zVideoFrame.__repr__c                    s    j } jjrttjtj  jjj}t	|j
 jj jj}d}t|jjD ]}|jj| jd }||k r8|}q'|jdkr@d}d}||k rZ jj| rZ|d7 }||k rZ jj| sL|dkrdt dfS t fddt|D S )z:
        A tuple of :class:`.VideoPlane` objects.
        r   r   rn   r   c                    s   g | ]}t  |qS r   )r   ).0r   r  r   r    
<listcomp>*  s    z%VideoFrame.planes.<locals>.<listcomp>)rE   r4   hw_frames_ctxr   r#   r$   r%   rC   rD   r	   rF   r;   r<   r   nb_componentscompr   r  extended_datar   tuple)r   fmtrN   max_plane_countr   countplane_countr   r  r    planes  s.   
zVideoFrame.planesc                 C      | j jS )zWidth of the image, in pixels.)r4   r;   r  r   r   r    r;   ,     zVideoFrame.widthc                 C   r+  )zHeight of the image, in pixels.)r4   r<   r  r   r   r    r<   1  r,  zVideoFrame.heightc                 C   s   t | S )zThe rotation component of the `DISPLAYMATRIX` transformation matrix.

        Returns:
            int: The angle (in degrees) by which the transformation rotates the frame
                counterclockwise. The angle will be in range [-180, 180].
        r   r  r   r   r    rotation6  r   zVideoFrame.rotationc                 C   s   t | jjtj@ S )z+Is this frame an interlaced or progressive?)boolr4   flagsr%   AV_FRAME_FLAG_INTERLACEDr  r   r   r    interlaced_frame@  s   zVideoFrame.interlaced_framec                 C   r+  )zReturns an integer that corresponds to the PictureType enum.

        Wraps :ffmpeg:`AVFrame.pict_type`

        :type: int
        r4   	pict_typer  r   r   r    r3  F  r   zVideoFrame.pict_typec                 C      || j _d S r   r2  r   valuer   r   r    r3  P     c                 C   r+  )zKColorspace of frame.

        Wraps :ffmpeg:`AVFrame.colorspace`.

        r4   
colorspacer  r   r   r    r9  T     zVideoFrame.colorspacec                 C   r4  r   r8  r5  r   r   r    r9  ]  r7  c                 C   r+  )zMColor range of frame.

        Wraps :ffmpeg:`AVFrame.color_range`.

        r4   color_ranger  r   r   r    r<  a  r:  zVideoFrame.color_rangec                 C   r4  r   r;  r5  r   r   r    r<  j  r7  c                 C   r+  )zWTransfer characteristic of frame.

        Wraps :ffmpeg:`AVFrame.color_trc`.

        r4   	color_trcr  r   r   r    r>  n  r:  zVideoFrame.color_trcc                 C   r4  r   r=  r5  r   r   r    r>  w  r7  c                 C   r+  )zUColor primaries of frame.

        Wraps :ffmpeg:`AVFrame.color_primaries`.

        r4   color_primariesr  r   r   r    r@  {  r:  zVideoFrame.color_primariesc                 C   r4  r   r?  r5  r   r   r    r@    r7  c                 O   s(   | j st | _ | j j| g|R i |S )a%  reformat(width=None, height=None, format=None, src_colorspace=None, dst_colorspace=None, interpolation=None, threads=None)

        Create a new :class:`VideoFrame` with the given width/height/format/colorspace.

        .. seealso:: :meth:`.VideoReformatter.reformat` for arguments.

        )reformatterVideoReformatterreformat)r   argskwargsr   r   r    rC    s   zVideoFrame.reformatc                 K   s   | j dddi|S )a
  Get an RGB version of this frame.

        Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`.

        >>> frame = VideoFrame(1920, 1080)
        >>> frame.format.name
        'yuv420p'
        >>> frame.to_rgb().format.name
        'rgb24'

        rE   rt   Nr   )rC  )r   rE  r   r   r    to_rgb  s   zVideoFrame.to_rgbfilepathc                 C   s   | drd}n| ds| drd}ntd|rdnd}|r#d	nd
}ddlm} ||dddid,}|j||d}| j|_| j|_||| j	|d ||d W d   dS 1 scw   Y  dS )zPSave a VideoFrame as a JPG or PNG.

        :param filepath: str | Path
        z.pngFz.jpgz.jpegTz"filepath must end with png or jpg.mjpegpngr   rt   r   )openwupdater/   )r8   )pix_fmt)rE   N)
endswithr[   av.container.corerJ  
add_streamr;   r<   muxr1   rC  )r   rG  is_jpgencoderrM  rJ  outputoutput_streamr   r   r    save  s   
"zVideoFrame.savec              	   K   s   ddl m} | jd
ddi|jd }|}|j}t|}d}|jd }|j| }	t|	}
|dk r7|jd | nd}||	k r`||||  |
||| < |dk rT||8 }n||7 }||7 }||	k s=|	d|j|jft
|
ddddS )zGet an RGB ``PIL.Image`` of this frame.

        Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`.

        .. note:: PIL or Pillow must be installed.

        r   )ImagerE   rt   r   r   RGBrawNr   )PILrW  rC  r*  r   r   r;   r<   	bytearray	frombytesbytes)r   rE  rW  r   r   r   r   r   r   o_sizer   r   r   r   r    to_image  s(   


zVideoFrame.to_imageFc                 K   s|  | j jr'd|vr'ttjtj | j jj}t|}t	|j
| j j| j jj|d< t|dkr5| jdi |n| }|j jr?tdddl}|jj}|j}|tv r|dkrj|j jd dks^J d|j jd dksjJ dt| \}}	t|}
|
d	krt|d ||	}n=|j|j j|j j|
f|	d
}|drddd	gtd|
R }nt|
}t|D ]\}}t|| ||	|dddd|f< qt||d}|s|dv r||dd}|S |dv r|j jd dksJ d|j jd dksJ d|t|d dt|d	 dt|d dgd|j jS |dkrs|j jd dks'J d|j jd dks4J dt|d dd}t|d	 dd}t|d dd}|j|dd	d}|j|dd	d}|ri|j |||gddS |j |||gddS |dkrt|d }|!|d	 d"ddd	#|j$}||fS |dkr|t|d dt|d	 ddgd|j jS td| d)aI  Get a numpy array of this frame.

        Any ``**kwargs`` are passed to :meth:`.VideoReformatter.reformat`.

        The array returned is generally of dimension (height, width, channels).

        :param bool channel_last: If True, the shape of array will be
            (height, width, channels) rather than (channels, height, width) for
            the "yuv444p" and "yuvj444p" formats.

        .. note:: Numpy must be installed.

        .. note:: For formats which return an array of ``uint16``, ``float16`` or ``float32``,
            the samples will be in the system's native byte order.

        .. note:: For ``pal8``, an ``(image, palette)`` tuple will be returned,
            with the palette being in ARGB (PyAV will swap bytes if needed).

        .. note:: For ``gbrp`` formats, channels are flipped to RGB order.

        rE   r   z2Cannot convert a hardware frame to numpy directly.Nr   r   z width has to be even for yuyv422z!height has to be even for yuyv422r   )r   gbrr   be   r~   r   >   r}   yuv422pr   z$width has to be even for this formatz%height has to be even for this formatr   r   r   axisrn   i4>i4rm   z'Conversion to numpy array with format `` is not yet supportedr   )%r4   r!  r   r#   r$   r%   rC   rD   dictr	   rF   r;   r<   r  lenrC  r[   r   rE   r*  _np_pix_fmt_dtypesr  empty
startswithr   	enumerater   rN  moveaxishstackreshaperepeatstack
frombufferastypeviewr   )r   channel_lastrE  rN   r  r  format_namer*  r  r   
num_planesr   plane_indicesr   p_idxyur+   u_fullv_fullimagepaletter   r   r    
to_ndarray  s    
$




zVideoFrame.to_ndarrayc                 C   s*   |j dkr
|d}t|| jd d dS )z6
        Update content from a ``PIL.Image``.
        rX  r   r   N)modeconvertr   r*  )r   imgr   r   r    	set_imageR  s   

zVideoFrame.set_imagec                 C   s&   t | jd | jd d}||  |S )z9
        Construct a frame from a ``PIL.Image``.
        r   r   rt   )r   sizer  )r  r  r   r   r    
from_image[  s   
zVideoFrame.from_imagert   c                 C   s   ddl }| jd }|s| jd }|dv r9t| dd t| | jd dk | jdd dkr1td	| jd f}n|d
v rbt| dd t| | jd dk | jdd dkrZtd	| jd f}n|dv rt| dd t| | jd dk | jdd dkrtd	| jd f}n|dv rt| dd t| | jd dk | jdd dkrtd	| jd f}n|dv rt| dd t| | jd dk | jdd dkrtd	| jd f}nw|dv rt| dd t| | jd dk | jdd dkrtd	| jd f}nM|dv r2t| dd t| | jd dk | jdd dkr*td	| jd f}n"|dv rQt| dd | jd dkrItd	| jd f}n|dv rpt| dd | jd dkrhtd	| jd f}n|dv rt| dd | jd dkrtd	| jd f}n|dv rt| dd t| | jd dk | jdd dkrtd	| jd d | jd d | jd d f}n|dv rt| dd t| | jd dk | jdd dkrtd	| jd d | jd d | jd d f}nS|dv r:t| dd t| | jd dk | jdd dkr$td	| jd d | jd d | jd d f}n|dv rxt| dd t| | jd dk | jdd dkr]td	| jd d | jd d | jd d | jd d f}n|d v rt| dd t| | jd dk | jdd dkrtd	| jd d | jd d | jd d | jd d f}n|d!v rt| dd t| | jd dk | jdd dkrtd	| jd d | jd d | jd d | jd d f}n`|d"v rLt| dd t| | jd d dk t| | jd d dk |d# d }| jd dkr)td	|d$v rA| jd | jd d | jd d f}n| jd | jd f}ntd%| d&|d'rk||| d(g d)f d*d} n|d+r||| d(g d,f d*d} t	t
}|| |||| |S )-a  
        Construct a frame from a numpy buffer.

        :param int width: optional width of actual image, if different from the array width.

        .. note:: For formats which expect an array of ``uint16``, ``float16`` or ``float32``,
            the samples must be in the system's native byte order.

        .. note:: for ``gbrp`` formats, channels are assumed to be given in RGB order.

        .. note:: For formats where width of the array is not the same as the width of the image,
        for example with yuv420p images the UV rows at the bottom have padding bytes in the middle of the
        row as well as at the end. To cope with these, callers need to be able to pass the actual width.
        r   Nr      rq   rt   r   r   r   )r   r   z.provided array does not have C_CONTIGUOUS rows   ru   rv   r{   r|   r   )r   r      r   r   r   )r   r      rg   rh   rj   rp   r   )r   r      r   r   r   r   )r   r      r   r   r      r   r   )r   r   >   ri   rl   ro   rs   r   r   r   r   >   ry   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   >   r   r   >   rk   >
   rw   rx   r   r   r   r   r   r   r   r   >   r   r   >   rr   >   r   r   r   r   r   r   r   r   >   r   r   >   rm   r}   r   r      r}   r   )Conversion from numpy array with format `rh  rr   .)r   r   r   r   r   rk   )r   r   r   )r   r
  r   r  r   r[   rm  ascontiguousarrayro  r   r   _image_fill_pointers_numpy)r   rE   r;   r  r<   	linesizesr  r   r   r    from_numpy_buffere  s  

















" zVideoFrame.from_numpy_bufferc              	   C   s   |j j}ttjt |}t|}t| j	 || j	_
|| j	_|| j	_t|D ]
\}	}
|
| j	j|	< q'tt| j	jttj| j	j
| j	j|| j	j}tt|}t| t||tttj|d| j	jd< | j	jd tjkrwt| td|   d S )Nr   zav_buffer_create failed)ctypesrD   r   r#   r$   r   r   r%   r  r4   rE   r;   r<   rn  r  r   av_image_fill_pointersrU   re   r   av_buffer_createrf   p_voidbufr   r   rA   r  )r   r   r;   r<   r  rE   c_datac_ptrr  r   r  requiredpy_bufr   r   r    r  B  s>   
z%VideoFrame._image_fill_pointers_numpyc              	   C   s	  ddl }i ddddddddd	dd
dddddddddddddddddddddddi ddddddddddddddd d!d"d#d$d#d%d#d&d#d'd#d(d#d)d#d*d#d+d#i d,d#d-d.d/d.d0dd1dd2dd3dd4dd5dd6dd7dd8dd9dd:dd;dd<d=d>d=dd!d#d#ddd!d?|d@\}}}|durI| jdAkr| dddddf } t| |dB |s|dCv r|| ddA} t| | jdA |k t| |dD} t	| jdE | jd |}|j
jdFr-|j| dddddEdBf | ddddddEf | dddddBdf gdAdG} t|D ]}t| dddd|f |j| | q1|S |dHkr| \} }	t| dIdA t|	dIdA t|	|	jdJk t	| jdE | jd |}t| |jd dE |jdE |	dKdL  |S |dMv rt| dIdA t| | jd dB dk t| | jdE dA dk t	| jdE | jd dA dB |}|j|j }
dN|
 dO }| dP}t|d|
 |jd dE t||
| |jdE dE t||d |jdA dE |S |dQkret| dIdA t| | jd dO dk t| | jdE dA dk t	| jdE | jd dA |}|j|j }
|
|
dA  }| dP}t|d|
 |jd dE t||
| |jdE dE t||d |jdA dE |S |dRkrt| |jrx| j|jkr|tdS|r| jdA dBkr|| dAd} n| jd dBkstdT| jdEd \}}|dA dks|dA dkrtdUt	|||}t| d |jd dA | dEdddddAf  }| dAdddddAf  }t||jdE dA t||jdA dA |S |dVkr&t| dIdB t| | jd dA dk t| | jdE dA dk t| | jdA dAk n|dWv r=t| dIdB t| | jdA dBk ns|dXv rTt| dIdB t| | jdA dOk n\|dYv rt| dZdB t| | jdA dBk t	| jdE | jd |}tt| |dD|jd d[ |S |d\v rt| d]dB t| | jdA dBk t	| jdE | jd |}tt| |dD|jd d^ |S |d_v rt| dZdB t| | jdA dOk t	| jdE | jd |}tt| |dD|jd d` |S |dav rt| dbdB t| | jdA dOk t	| jdE | jd |}tt| |dD|jd d` |S |dcv rNt| d]dB t| | jdA dOk t	| jdE | jd |}tt| |dD|jd dd |S |dekrt| dIdA t| | jd dB dk t| | jdE dA dk t	| jdE | jd dA dB |}|j|j }| dP}t|d| |jd dE t||d |jdE dA |S tdf| dgt	| jdE | jd |}t| |jd | jdAkrdE |S | jdA  |S )ha  
        Construct a frame from a numpy array.

        :param bool channel_last: If False (default), the shape for the yuv444p and yuvj444p
            is given by (channels, height, width) rather than (height, width, channels).

        .. note:: For formats which expect an array of ``uint16``, ``float16`` or ``float32``,
            the samples must be in the system's native byte order.

        .. note:: for ``pal8``, an ``(image, palette)`` pair must be passed. `palette` must
            have shape (256, 4) and is given in ARGB format (PyAV will swap bytes if needed).

        .. note:: for ``gbrp`` formats, channels are assumed to be given in RGB order.

        r   Nr   )r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   ri   rr   )r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   rk   )r   r   r   r   )r   r   r   r   r   r   r   r   r   r   rw   rx   r   )r   r   r   r   rl   r   r   r   r   r   r   r   r   rs   ry   rz   r   )r   r   r   r   )ro   r~   r   r   r   r   r   )NNNr   r   rb  ra  r   r`  rd  rn   r   )   r   rg  rf  r     r   r   rc  r   zArray must be uint16 typez>Array must have shape (3, height, width) or (height, width, 3)zWidth and height must be evenr   r  r  r  r   r   r  r   r   r  r   r  r   r  r   rm   r  rh  )r   r?   ndimr   ro  r  r
  r   rN  r   rE   r  rm  concatenater   r   r*  rL  rv  ru  r   r;   r<   rq  
isinstancer  r   r   r[   copy)r   rE   rw  r  r	  r  r   r  r   r  u_startv_startflatr<   r;   r}  r+   uv_startr   r   r    from_ndarrayy  s  	
 !"#$%&'()*+,-./01234;
<
(
 
 












 

zVideoFrame.from_ndarrayrp   r   c                 C   sn   t |||}|dkrt| |jd d|| |S |dv r/t| |jd |dr(dnd|| |S td| d	)
Nrp   r   r   >   r   r   r   r   r   r   r   r   r   r   r   r   8r   r   zFormat 'z' is not supported.)r   r   r*  rN  NotImplementedError)r   r;   r<   rE   r   r   r  r   r   r    
from_bytesf  s    		zVideoFrame.from_bytesrm   NTr   r   c           '   	   C   s  t | ttfs
| f} t| dkrtdt|}td}	td}
td}||	|
|fvr/td||	kr5dnd}|dkr=d	nd}tj}tj}d }zt	| d
 |}t	| d	 |}|j
j}|j
j}||krgtd|ttfvrqtd|j
j}|j
j}||krtd|tkr|d u r|}n||krtdn
|dvrtdd
}|tkr|d
ks|d
krtd|j
jjd	ks|j
jj|ks|j
jjd	krtd|j
jjd	ks|j
jj|ks|j
jjd	krtd|j
jdkrtdtt|j
jd
 }tt|j
jd	 }|d
kr|d
krtt|}tt|}n|d
ks |d
kr$td||ks.||kr2td|d s<|d r@td|j
jtjkr`|j
jd	 d	krUtdtt|j
jd
 }ntt|}tt|| }tt|| }|j
j}|d }|dkrtt|j
jd
 }tt|j
jd	 }||ks||krtd|j
jtjkr|j
jd	 d	krtdtt|j
jd
 }nstt|}nl|dkr4tt|j
jd
 }tt|j
jd	 }tt|j
jd } ||ks ||d ks | dkrtd|j
jtjkr-|j
jd d	ks|j
jd	 dkr"tdtt|j
jd
 }ntt|}ntdtt|| }!tt|!|d  }"t }||j_||j_|tkr|d u rft||d}#n,t |tsptd t|jt|kr~td!t|j t|krtd"tt|}#|#!|||}$td#|j_"|$|j_#||_$|#|_%n||j_"ttj&t' |j
j(ttj)|j
j* }%ttj&t' |j
j(ttj)|j
j* }&t+,|%|t-ttj.|d
|jj/d
< |jj/d
 tjkrt0d$|%|jj(d
< ||jj1d
< tj}t+,|&|"t-ttj.|d
|jj/d	< |jj/d	 tjkr%t0d%|&|jj(d	< |!|jj1d	< tj}|2  |W S  t3yd   |d urMt+4|j |tjkrX|5| |tjkrc|5|  w )&Nr   zHfrom_dlpack currently supports 2-plane formats only (nv12/p010le/p016le)s   nv12s   p010les   p016lez.from_dlpack supports nv12, p010le, p016le onlyr   r   r   r   z,plane tensors must have the same device_typez.only CPU and CUDA DLPack tensors are supportedz-plane tensors must be on the same CUDA devicez4device_id does not match the DLPack tensor device_id)Nr   z#device_id must be 0 for CPU tensorsz+CPU DLPack tensors must have device_id == 0zunexpected dtype for plane 0zunexpected dtype for plane 1zplane 0 must be 2D (H, W)z+either specify both width/height or neitherz)plane 0 shape does not match width/heightz0width/height must be even for nv12/p010le/p016lez0plane 0 must be contiguous in the last dimensionz*plane 1 must have shape (H/2, W) for 2D UVz0plane 1 must be contiguous in the last dimensionr   z/plane 1 must have shape (H/2, W/2, 2) for 3D UVz-unexpected UV plane strides for (H/2, W/2, 2)zplane 1 must be 2D or 3D)r   r   z"cuda_context must be a CudaContextzAcuda_context.device_id does not match the DLPack tensor device_idz3cuda_context.primary_ctx does not match primary_ctxr=   z#av_buffer_create failed for plane 0z#av_buffer_create failed for plane 1)6r  r%  listrj  r[   r   r  r   r   r_   	dl_tensordevice_typer   r   r   r   codebitslanesrZ   r  r#   r   r
  r>   r   r   r4   r;   r<   r   r.  r   rO   rE   r!  
_device_id	_cuda_ctxr$   r   rD   r'   byte_offsetr%   r  rc   r  r  rA   r  r  rH   r  rb   )'r*  rE   r;   r<   rW   r   r   cuda_contextr:   rm   p010lep016leexpected_bitsr  m0m1r  	dev_type0	dev_type1dev0dev1y_hy_wy_pitch_elems
y_linesizey_sizeuv_ndimuv_h_expecteduv_huv_wuv_pitch_elemsuv_w2uv_cuv_linesizeuv_sizectxrM   y_ptruv_ptrr   r   r    from_dlpack  sN  

"$




zVideoFrame.from_dlpack)r   r   r}   )F)rt   r   )rt   F)rp   FF)rm   r   r   NNTN),rP   rQ   rR   r!   r   rT   r%   rU   uintr  r  r-   r  propertyr*  r;   r<   r-  r1  r3  setterr9  r<  r>  r@  rC  rF  ccallre   rV  r_  r  r  staticmethodr  r  r  r  r]  r>   r  strr.  r  r   r   r   r    r     s    





	

	









%o	
	 ]7 m&r   )Fsysenumr   r   cython.cimports.libavcimportslibavr%   cython.cimports.av.dictionaryr   cython.cimports.av.errorr   $cython.cimports.av.sidedata.sidedatar   cython.cimports.av.utilsr   cython.cimports.av.video.formatr   r	   cython.cimports.av.video.planer
   r   r   r   cython.cimports.cpython.excr   !cython.cimports.cpython.pycapsuler   r   r   cython.cimports.cpython.refr   r   cython.cimports.libc.stdintr   r   finalcclassr   rT   re   r$   r_   r  	exceptvalr  voidrc   rf   r   r   supported_np_pix_fmtsri  r  r%  r  rk  r   r   r   rS   	byteorderr   inliner   r   r   r  r  Framer   r   r   r    <module>   s   c

	Y	
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEV
("