a
    áñhu/  ã                   @   sà  d dl Z d dlZd dlZd dlZd dlmZmZmZmZm	Z	m
Z
 d dlZd dlZddlmZ ddlmZ z4d dlZej ejj¡ eejjjdƒsšedƒZW n ey¶   edƒZY n0 dd	œd
d„Zed	œdd„Zd adad)eej e!eeeeef  ddœdd„Z"de!e!edeeee
e#e	e#df ee# f  f ed dœdd„Z$ej ed e#e!ej dœdd„Z%d*ee#ee! ee	ej ej eeef f dœdd „Z&ded!œd"d#„Z'dee# d!œd$d%„Z(d+eee	ee# ee! f d&œd'd(„Z)dS ),é    N)ÚAnyÚDictÚListÚOptionalÚTupleÚUnioné   )Ú
_video_opt)ÚVideoMetaDataÚ	pict_typea+  Your version of PyAV is too old for the necessary video operations in torchvision.
If you are on Python 3.5, you will have to build from source (the conda-forge
packages are not up-to-date).  See
https://github.com/mikeboers/PyAV#installation for instructions on how to
install PyAV on your system.
z¼PyAV is not installed, and is necessary for the video operations in torchvision.
See https://github.com/mikeboers/PyAV#installation for instructions on how to
install PyAV on your system.
)Úreturnc                   C   s   t ttƒrt‚d S ©N©Ú
isinstanceÚavÚ	Exception© r   r   úT/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/io/video.pyÚ_check_av_available&   s    
r   c                   C   s   t ttƒ S r   r   r   r   r   r   Ú_av_available+   s    r   é
   Úlibx264)ÚfilenameÚvideo_arrayÚfpsÚvideo_codecÚoptionsr   c           
      C   sô   t ƒ  tj|tjd� ¡ }t|tƒr.t |¡}t	j
| dd��¤}|j||d�}|jd |_|jd |_|dkrpdnd	|_|p|i |_|D ]4}t	jj|d	d
�}d|_| |¡D ]}	| |	¡ q¨q„| ¡ D ]}	| |	¡ qÂW d  ƒ n1 sæ0    Y  dS )aJ  
    Writes a 4d tensor in [T, H, W, C] format in a video file

    Parameters
    ----------
    filename : str
        path where the video will be saved
    video_array : Tensor[T, H, W, C]
        tensor containing the individual frames, as a uint8 tensor in [T, H, W, C] format
    fps : Number
        frames per second
    ©ZdtypeÚw)Úmode)Úrateé   r   Z
libx264rgbZyuv420pZrgb24)ÚformatÚNONEN)r   ÚtorchÚ	as_tensorÚuint8Únumpyr   ÚfloatÚnpÚroundr   ÚopenZ
add_streamÚshapeÚwidthÚheightZpix_fmtr   Ú
VideoFrameZfrom_ndarrayr   ÚencodeZmux)
r   r   r   r   r   Ú	containerÚstreamÚimgÚframeÚpacketr   r   r   Úwrite_video4   s"    


r6   zav.container.Containerzav.stream.Stream.zav.frame.Frame)r1   Ústart_offsetÚ
end_offsetÚpts_unitr2   Ústream_namer   c                    s.  t d7 a t t td kr t ¡  |dkrftt ˆd|j  ¡ƒ‰ˆ tdƒkrptt 	ˆ d|j  ¡ƒ‰ n
t
 d¡ i ‰d}d}|jdkræ|jj}|ræd|v ræ| d¡}	||	d … }
t d	|
¡}|d u rÐt d
|
¡}|d uræ| d¡dk}ˆ}t|d dƒ}|�rt|| dƒ}z| j|dd|d� W n tj�y<   g  Y S 0 d}z\t| jf i |¤ŽƒD ]B\}}|ˆ|j< |jˆ k�rX|�r’||k �r’|d7 }�qX �qœ�qXW n tj�y´   Y n0 ‡ ‡‡fdd„tˆƒD ƒ}tˆƒdk�r*ˆdk�r*ˆˆv�r*‡fdd„ˆD ƒ}t|ƒdk�r*t|ƒ}| dˆ| ¡ |S )Nr   ÚsecÚinfzmThe pts_unit 'pts' gives wrong results and will be removed in a follow-up version. Please use pts_unit 'sec'.Té   Úvideos   DivXs   DivX(\d+)Build(\d+)(\w)s   DivX(\d+)b(\d+)(\w)é   ó   pr   F)Z	any_frameZbackwardr2   c                    s2   g | ]*}ˆˆ| j   kr"ˆ krn qˆ| ‘qS r   ©Úpts©Ú.0Úi©r8   Úframesr7   r   r   Ú
<listcomp>¦   s   z%_read_from_stream.<locals>.<listcomp>c                    s   g | ]}|ˆ k r|‘qS r   r   rC   )r7   r   r   rH   ­   ó    )Ú_CALLED_TIMESÚ_GC_COLLECTION_INTERVALÚgcZcollectÚintÚmathÚfloorÚ	time_baser(   ÚceilÚwarningsÚwarnÚtypeÚcodec_contextÚ	extradataÚfindÚreÚsearchÚgroupÚmaxÚseekr   ÚAVErrorÚ	enumerateÚdecoderB   ÚsortedÚlenÚinsert)r1   r7   r8   r9   r2   r:   Zshould_bufferÚmax_buffer_sizerV   ÚposÚdÚoZseek_offsetZbuffer_countZ_idxr4   ÚresultZpreceding_framesZfirst_frame_ptsr   rF   r   Ú_read_from_streama   sf    	ÿ



ÿ"rh   )ÚaframesÚaudio_framesÚ	ref_startÚref_endr   c           
      C   s|   |d j |d j  }}| jd }|| d | }d}|}	||k rPt|| | ƒ}||krht|| | ƒ}	| d d …||	…f S )Nr   éÿÿÿÿr   )rB   r,   rM   )
ri   rj   rk   rl   ÚstartÚendZtotal_aframesZstep_per_aframeZs_idxZe_idxr   r   r   Ú_align_audio_frames´   s    
rp   rB   )r   Ú	start_ptsÚend_ptsr9   r   c              	   C   s¶  ddl m} |ƒ dkr&t | |||¡S tƒ  |du r<tdƒ}||k rTtd ||¡ƒ‚i }g }g }z´tj	| dd���}|j
jrºt|||||j
jd d	diƒ}|j
jd j}	|	durºt|	ƒ|d
< |j
jròt|||||j
jd ddiƒ}|j
jd j|d< W d  ƒ n1 �s0    Y  W n tj�y*   Y n0 dd„ |D ƒ}
dd„ |D ƒ}|
�r`t t |
¡¡}ntjdtjd�}|�rœt |d¡}t |¡}t||||ƒ}ntjdtjd�}|||fS )a¾  
    Reads a video from a file, returning both the video frames as well as
    the audio frames

    Parameters
    ----------
    filename : str
        path to the video file
    start_pts : int if pts_unit = 'pts', optional
        float / Fraction if pts_unit = 'sec', optional
        the start presentation time of the video
    end_pts : int if pts_unit = 'pts', optional
        float / Fraction if pts_unit = 'sec', optional
        the end presentation time
    pts_unit : str, optional
        unit in which start_pts and end_pts values will be interpreted, either 'pts' or 'sec'. Defaults to 'pts'.

    Returns
    -------
    vframes : Tensor[T, H, W, C]
        the `T` video frames
    aframes : Tensor[K, L]
        the audio frames, where `K` is the number of channels and `L` is the
        number of points
    info : Dict
        metadata for the video and audio. Can contain the fields video_fps (float)
        and audio_fps (int)
    r   ©Úget_video_backendÚpyavNr<   zHend_pts should be larger than start_pts, got start_pts={} and end_pts={}Úignore©Zmetadata_errorsr>   Ú	video_fpsÚaudioZ	audio_fpsc                 S   s   g | ]}|  ¡  ¡ ‘qS r   )Zto_rgbÚ
to_ndarray©rD   r4   r   r   r   rH     rI   zread_video.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   )rz   r{   r   r   r   rH     rI   )r   r   r   r?   r   r   )r   r   )Útorchvisionrt   r	   Z_read_videor   r(   Ú
ValueErrorr"   r   r+   Ústreamsr>   rh   Úaverage_ratery   r    r]   r$   r%   r)   ÚstackÚemptyr&   Zconcatenaterp   Úfloat32)r   rq   rr   r9   rt   ÚinfoZvideo_framesrj   r1   rx   Zvframes_listZaframes_listZvframesri   r   r   r   Ú
read_videoÃ   sh     
ÿÿ
ú
ú6
r„   )r1   r   c                 C   s*   | j d jj}|d u rdS d|v r&dS dS )Nr   Fs   LavcT)r~   rU   rV   )r1   rV   r   r   r   Ú!_can_read_timestamps_from_packets(  s    r…   c                 C   s8   t | ƒrdd„ | jdd�D ƒS dd„ | jdd�D ƒS d S )Nc                 S   s   g | ]}|j d ur|j ‘qS r   rA   ©rD   Úxr   r   r   rH   4  rI   z,_decode_video_timestamps.<locals>.<listcomp>r   )r>   c                 S   s   g | ]}|j d ur|j ‘qS r   rA   r†   r   r   r   rH   6  rI   )r…   Zdemuxr_   )r1   r   r   r   Ú_decode_video_timestamps1  s    rˆ   )r   r9   r   c              	      sø   ddl m} |ƒ dkr"t | |¡S tƒ  d}g }zˆtj| dd��f}|jjr˜|jjd }|j	‰ zt
|ƒ}W n$ tjyŒ   t d| › �¡ Y n0 t|jƒ}W d  ƒ n1 s¬0    Y  W n tjyÌ   Y n0 | ¡  |dkrð‡ fd	d
„|D ƒ}||fS )a:  
    List the video frames timestamps.

    Note that the function decodes the whole video frame-by-frame.

    Parameters
    ----------
    filename : str
        path to the video file
    pts_unit : str, optional
        unit in which timestamp values will be returned either 'pts' or 'sec'. Defaults to 'pts'.

    Returns
    -------
    pts : List[int] if pts_unit = 'pts'
        List[Fraction] if pts_unit = 'sec'
        presentation timestamps for each one of the frames in the video.
    video_fps : float, optional
        the frame rate for the video

    r   rs   ru   Nrv   rw   z Failed decoding frames for file r;   c                    s   g | ]}|ˆ  ‘qS r   r   r†   ©Zvideo_time_baser   r   rH   j  rI   z)read_video_timestamps.<locals>.<listcomp>)r|   rt   r	   Z_read_video_timestampsr   r   r+   r~   r>   rP   rˆ   r]   rR   rS   r(   r   Úsort)r   r9   rt   rx   rB   r1   Zvideo_streamr   r‰   r   Úread_video_timestamps9  s,    
,r‹   )r   N)r   NrB   )rB   )*rL   rN   rX   rR   Útypingr   r   r   r   r   r   r'   r)   r$   Ú r	   r
   r   ÚloggingZ	set_levelÚERRORÚhasattrr>   r4   r/   ÚImportErrorr   Úboolr   rJ   rK   ÚstrZTensorr(   r6   rM   rh   rp   r„   r…   rˆ   r‹   r   r   r   r   Ú<module>   sh    ÿ	ÿ
	  ûú.$ùTþ ÿþe	