o
    ]iU                  	   @   sF  d dl Z d dlmZ d dl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 d dlmZ e Zh d	Zejd
efddZG dd deZejdejfddZejdedejdejdejfddZejdedejfddZej	d%dedejdefddZejded ejfd!d"Zej G d#d$ d$e!ZdS )&    N)IntEnum)	err_checkget_display_rotation)check_ndarray)get_pix_fmtget_video_format
VideoPlane)uint8_t>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_rggb16lereturnc                   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_sentinel rc   rc   B/home/ubuntu/.local/lib/python3.10/site-packages/av/video/frame.pyalloc_video_frameg      re   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)__name__
__module____qualname__lib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BIrc   rc   rc   rd   rg   r   s    
rg   
big_endianc                 C   s   t jdk|kr|  S | S )Nbig)sys	byteorderbyteswap)arrayr|   rc   rc   rd   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      )widthabs	line_sizecythondeclareintheight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jrc   rc   rd   copy_bytes_to_plane   s6   



r   c                 C   s   |   }t|||dd d S )NF)tobytesr   )r   r   r   imgbytesrc   rc   rd   copy_array_to_plane   s   r   r   uint8dtypec                 C   sd   ddl }t| j}| j| }|| |j}||kr*|d|ddd|f d}|||S )z
    Return the useful part of the VideoPlane as a single dimensional array.

    We are simply discarding any padding which was added for alignment.
    r   Nr   )	numpyr   r   r   
frombufferr   reshapeviewr   )r   r   r   nptotal_line_sizeuseful_line_sizearrrc   rc   rd   useful_array   s   	

"r   r   okc                 C   s   |st d| j dd S )NzUnexpected numpy array shape ``)
ValueErrorshape)r   r   rc   rc   rd   check_ndarray_shape   s   r   c                   @   sp  e Zd Zd?d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d#d$ Zd%d& Zejd'efd(d)Zd*d+ Zd@d-d.Zd/d0 Zed1d2 Z edAd4d5Z!d6d7 Z"edBd8d9Z#e	:	,	,dCd;e$de%de%fd<d=Z&d>S )Dra   r   r"   c                 C   s&   |t u rd S t|}| ||| d S N)rb   r   _init)selfr   r   formatc_formatrc   rc   rd   	__cinit__   s   zVideoFrame.__cinit__r   r   r   c              	   C   s   d}t j- || j_|| j_|| j_|r+|r+t| jj| jj	|||d}| jjd | _
W d    n1 s5w   Y  |r@t| |   d S )Nr      )r   nogilptrr   r   r   rk   av_image_allocdatalinesize_bufferr   _init_user_attributes)r   r   r   r   resrc   rc   rd   r      s   zVideoFrame._initc                 C   s(   t ttj| jj| jj| jj| _d S r   )	r   r   castrk   AVPixelFormatr   r   r   r   r   rc   rc   rd   r      s
   
z VideoFrame._init_user_attributesc                 C   s   t t| j d | _d S r   )rk   av_freepr   addressr   
_np_bufferr   rc   rc   rd   __dealloc__   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__rh   ptsr   namer   r   idr   rc   rc   rd   __repr__   s   zVideoFrame.__repr__c                    s   d}t  jjjD ]} jjj| jd }||k r|}q	 jjdkr$d}d}||k r> jj| r>|d7 }||k r> jj| s0t fddt |D S )z:
        A tuple of :class:`.VideoPlane` objects.
        r   r   r      c                    s   g | ]}t  |qS rc   r	   ).0r   r   rc   rd   
<listcomp>  s    z%VideoFrame.planes.<locals>.<listcomp>)	r   r   r   nb_componentscompr   r   extended_datatuple)r   max_plane_countr   countplane_countrc   r   rd   planes   s   zVideoFrame.planesc                 C      | j jS )zWidth of the image, in pixels.)r   r   r   rc   rc   rd   r        zVideoFrame.widthc                 C   r   )zHeight of the image, in pixels.)r   r   r   rc   rc   rd   r     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   rc   rc   rd   rotation  rf   zVideoFrame.rotationc                 C   s   t | jjtj@ S )z+Is this frame an interlaced or progressive?)boolr   flagsrk   AV_FRAME_FLAG_INTERLACEDr   rc   rc   rd   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
        r   	pict_typer   rc   rc   rd   r   -  rf   zVideoFrame.pict_typec                 C      || j _d S r   r   r   valuerc   rc   rd   r   7     c                 C   r   )zKColorspace of frame.

        Wraps :ffmpeg:`AVFrame.colorspace`.

        r   
colorspacer   rc   rc   rd   r   ;     zVideoFrame.colorspacec                 C   r   r   r   r   rc   rc   rd   r   D  r   c                 C   r   )zMColor range of frame.

        Wraps :ffmpeg:`AVFrame.color_range`.

        r   color_ranger   rc   rc   rd   r   H  r   zVideoFrame.color_rangec                 C   r   r   r   r   rc   rc   rd   r   Q  r   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)

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

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

        )reformatterVideoReformatterreformat)r   argskwargsrc   rc   rd   r   U  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'

        r   r   Nrc   )r   )r   r   rc   rc   rd   to_rgba  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;   r   r   )openwupdate1)options)pix_fmt)r   N)
endswithr   av.container.corer   
add_streamr   r   muxencoder   )r   r   is_jpgencoderr   r   outputoutput_streamrc   rc   rd   saveo  s   
"zVideoFrame.savec              	   K   s   ddl m} | jd
ddi|jd }|}d}|j}d}|jd }|j| }	t|	}
||	k rH||||  |
||| < ||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   )Imager   r      RGBrawr   Nrc   )
PILr  r   r   r   r   r   	bytearray	frombytesbytes)r   r   r  r   r   r   r   r   r   o_sizer   rc   rc   rd   to_image  s"   

zVideoFrame.to_imageFc                    s  | j dii |ddl}jjdv r(jd dksJ djd dks(J 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 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 d0dd1dd2dd3dd4dd5dd6dd7dd8dd9d,d:d,d;dd<dd=dd>dd?dd@di dAddBddCddDddEddFddGd,dHd,dIddJddKddLddMddNd dOd dPdQdRdQdSdSdTdTdddddddUdVjjdW\ dur fdXdYjD }t|dZkr/|d }n|j	|dd[}t
|jjd\}|jd dZkrM|dS jjd]r|dddddf  }|dddddf |dddddf< |dddddZf |dddddf< ||dddddZf< |sjjd^v r||dd}|S jjd_v r|tjd tjdZ tjd gd`jS jjdakr*tjd ddbjj}tjdZ ddbjjd }tjd ddbjjd }	|j|ddZd[}
|j|	ddZd[}|r |j||
|gdd[S |j||
|gdd[S jjdckrVtjd jj}|jdZ ddded`dZ|j}||fS jjdfkrt|tjd tjdZ dgd`jS tdgjj dh)jaI  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.

        r   N>   r"   yuv422pr$   r;   rS   r   z.the width has to be even for this pixel formatz/the height has to be even for this pixel formatr   )   r   r   rO   r   r   rP   rQ   rR   rY   )r   uint16rX   r[   rZ   r]   r\   r_   r^   r   )r  r   r   )   r  r   r   r   r%   )   r  r&   r   r=   r>   r?   r@   rA   rB   rC   rD   rM   )r  float32rN   r   r'   r(   r)   r*   r+   r,   r-   r.   r   r   rE   rF   r   r/   r0   r1   r2   r3   r4   r5   r6   r   r   r   rG   rH   r   r    r!   r   r   r7   r8   rI   )r  float16rJ   )r   r  )   r  )r   r   )rK   rL   r9   r:   r#   rT   rU   rV   rW   r<   r$   )NNc                    s&   g | ]}t | jjd qS )r   )r   r   r   r   )r   planr   frameitemsizerc   rd   r   %  s    
z)VideoFrame.to_ndarray.<locals>.<listcomp>r   axisbegbr   r#   r<   >   r"   r  r;   r   rS   r  r   i4>i4r   z'Conversion to numpy array with format `` is not yet supportedrc   )r   r   r   r   r   r   getr   lenconcatenater   r   r   squeeze
startswithcopymoveaxishstackr   r   repeatstackr   astyper   r   r   )r   channel_lastr   r   layersr   bufferyuvu_fullv_fullimagepaletterc   r  rd   
to_ndarray  s  	
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEP
Q

((

zVideoFrame.to_ndarrayc                 C   s*   |j dkr
|d}t|| jd d dS )z6
        Update content from a ``PIL.Image``.
        r  r   r  N)modeconvertr   r   )r   imgrc   rc   rd   	set_imagek  s   

zVideoFrame.set_imagec                 C   s&   t | jd | jd d}||  |S )z9
        Construct a frame from a ``PIL.Image``.
        r   r   r   )ra   sizer>  )r=  r  rc   rc   rd   
from_imaget  s   
zVideoFrame.from_imager   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      r   r   r   r  r   )r  r   z.provided array does not have C_CONTIGUOUS rows   r   r   r    r!   r  )r  r      r9   r:   r  )r  r     r   r   r   r   r  )r  r      r%   r&   r7   r8   )r  r      rI   rJ   r     rK   rL   )r   r  >   r   r   r   r   rO   rP   rQ   rR   >   r   r   r/   r0   r1   r2   r3   r4   r5   r6   rX   rY   rZ   r[   r\   r]   r^   r_   >   rG   rH   >   r   >
   r   r   r'   r(   r)   r*   r+   r,   r-   r.   >   rE   rF   >   r   >   r=   r>   r?   r@   rA   rB   rC   rD   >   rM   rN   >   r   r"   r;   r     r"   r;   )Conversion from numpy array with format `r$  r   .)r   r   r   r  r   r   )r   r   r   )r   r   r   r   stridesr   r)  ascontiguousarrayr+  ra   rb   _image_fill_pointers_numpy)r   r   r   r   r   	linesizesr  rc   rc   rd   from_numpy_buffer~  s  

















" zVideoFrame.from_numpy_bufferc                 C   s   |j j}ttjt |}t|}tt	| j
 || _|| j_|| j_|| j_t|D ]
\}	}
|
| jj|	< q-t| jjttj| jj| jj|| jj}|rTt| |   d S r   )ctypesr   r   r   pointerr   r   rk   r   r   r   r   r   r   r   r   	enumerater   av_image_fill_pointersr   r   r   )r   r2  r   r   rM  r   c_datac_ptrr   r   r   r   rc   rc   rd   rL  [  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   NrX   )r   r   r  rY   rO   )r   r   r   rZ   r[   rP   r\   r]   rQ   r^   r_   rR   r   r   )r  r   r   r=   )r  r   r  r>   r?   r@   rA   rB   rC   rD   rM   )r  r  r  rN   r   )r  r   r   r'   )r  r   r  r(   r)   r*   r+   r,   r-   r.   r   r   rE   )r  r  r  rF   r   r/   r0   r1   r2   r3   r4   r5   r6   r   r   r   rG   )r   r  r  rH   )r   r#   rT   rU   rV   rW   r<   )NNNr   r  r!  r  r   r   r  r   r   )   r  r#  r"  rH     r  r   r  rS   zArray must be uint16 typez>Array must have shape (3, height, width) or (height, width, 3)zWidth and height must be evenr$   rA  rD  rB  r  r  rC  r  r  rE  r  rF  r  rG  r   r   rI  r$  )r   r%  ndimr   r+  r   r   r   r   ra   r   r   r)  r'  r   r   r   r   r   r/  r   r   r   r   
isinstancendarrayr   r  r   r*  )r   r   r0  r   channelsr  r   r  r   r9  u_startv_startflatr   r   r4  r5  uv_startrc   rc   rd   from_ndarray  s  	
 !"#$%&'()*+,-./01234;
<
(
 
 












 

zVideoFrame.from_ndarrayr   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	)
Nr   r   r  >   rO   rP   rQ   rR   rX   rY   rZ   r[   r\   r]   r^   r_   8r   r   zFormat 'z' is not supported.)ra   r   r   r   NotImplementedError)r   r   r   r   r   r   r  rc   rc   rd   
from_bytesv  s    		zVideoFrame.from_bytesN)r   r   r"   )F)r   r   )r   F)r   FF)'rh   ri   rj   r   r   cfuncrk   r   uintr   r   r   r   propertyr   r   r   r   r   r   setterr   r   r   r   ccallobjectr  r  r:  r>  staticmethodr@  rN  rL  r_  r  r   rb  rc   rc   rc   rd   ra      st    





	

	





 C	
	 ]. mra   r  )"r~   enumr   r   cython.cimports.av.errorr   $cython.cimports.av.sidedata.sidedatar   cython.cimports.av.utilsr   cython.cimports.av.video.formatr   r   cython.cimports.av.video.planer
   cython.cimports.libc.stdintr   rh  rb   supported_np_pix_fmtsrc  ra   re   rg   bintr   rd  r   r   strr   r   cclassFramerc   rc   rc   rd   <module>   sR    X
&