o
    ôj‡=  ã                   @   sp  d dl Z d dlZd dlZd dlZd dlZd dlm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 zd dlZej ejj¡ eejjjdƒsWed	ƒZW n eye   ed
ƒZY nw d<dd„Zdefdd„Z d a!da"						d=de#dej$de%de#dee	e#ef  deej$ dee% dee# dee	e#ef  ddfdd„Z&ddde%d e%d!e#d"d#d$e	e#eee'ee'd%f e
e' f  f de
d& fd'd(„Z(d)ej$d*e
d& d+e'd,e%dej$f
d-d.„Z)	 		/	0d>de#d1ee%ef d2eee%ef  d!e#d3e#deej$ej$e	e#ef f fd4d5„Z*dddefd6d7„Z+ddde
e' fd8d9„Z,d?de#d!e#dee
e' ee% f fd:d;„Z-dS )@é    N)ÚFraction)ÚAnyÚDictÚListÚOptionalÚTupleÚUnioné   )Ú_log_api_usage_onceé   )Ú
_video_optÚ	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   úe/var/www/html/academy/tools/voices/clone/sv-venv/lib/python3.10/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ÚoptionsÚaudio_arrayÚ	audio_fpsÚaudio_codecÚaudio_optionsc	                 C   sâ  t j ¡ st j ¡ sttƒ tƒ  t j|t jd� 	¡ }t
|tƒr%t |¡}tj| dd��»}	|	j||d�}
|jd |
_|jd |
_|dkrFdnd	|
_|pLi |
_|d
ur¶dddddddddddœ
}|	j||d�}|pii |_|jd }|dkrvdnd}|	jjd jj}t || ¡}t  |¡ 	¡  |¡}tjj|||d�}||_| |¡D ]}|	  |¡ q¢| ¡ D ]}|	  |¡ q®|D ]}tj!j|d	d�}d|_"|
 |¡D ]}|	  |¡ qÊq¸|
 ¡ D ]}|	  |¡ q×W d
  ƒ d
S 1 sêw   Y  d
S )a|  
    Writes a 4d tensor in [T, H, W, C] format in a video file

    Args:
        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): video frames per second
        video_codec (str): the name of the video codec, i.e. "libx264", "h264", etc.
        options (Dict): dictionary containing options to be passed into the PyAV video stream
        audio_array (Tensor[C, N]): tensor containing the audio, where C is the number of channels
            and N is the number of samples
        audio_fps (Number): audio sample rate, typically 44100 or 48000
        audio_codec (str): the name of the audio codec, i.e. "mp3", "aac", etc.
        audio_options (Dict): dictionary containing options to be passed into the PyAV audio stream
    ©ÚdtypeÚw)Úmode)Úrater	   r   Z
libx264rgbZyuv420pÚrgb24Nz<f8z<f4z<i2z<i4Úu1)
ÚdblZdblpÚfltÚfltpÚs16Zs16pÚs32Zs32pÚu8Zu8pr   ZstereoÚmono)ÚformatÚlayout)r1   ÚNONE)#ÚtorchÚjitÚis_scriptingÚ
is_tracingr
   Úwrite_videor   Ú	as_tensorÚuint8Únumpyr   ÚfloatÚnpÚroundr   ÚopenZ
add_streamÚshapeÚwidthÚheightZpix_fmtr   ÚstreamsÚaudior1   Únamer$   ÚastypeZ
AudioFrameZfrom_ndarrayÚsample_rateÚencodeÚmuxÚ
VideoFramer   )r   r   r   r   r   r   r    r!   r"   Ú	containerÚstreamZaudio_format_dtypesZa_streamÚnum_channelsZaudio_layoutZaudio_sample_fmtZformat_dtypeÚframeÚpacketÚimgr   r   r   r8   5   s^   


ö

ÿÿ"Ñr8   rK   zav.container.ContainerÚstart_offsetÚ
end_offsetÚpts_unitrL   zav.stream.StreamÚstream_name.zav.frame.Framec                    s  t d7 a t t td krt ¡  |dkr3tt ˆd|j  ¡ƒ‰ˆ tdƒkr2tt 	ˆ d|j  ¡ƒ‰ nt
 d¡ i ‰d}d}|jdkrs|jj}|rsd|v rs| d¡}	||	d … }
t d	|
¡}|d u rht d
|
¡}|d urs| d¡dk}ˆ}t|d dƒ}|r…t|| dƒ}z| j|dd|d� W n tjyœ   g  Y S w d}z(t| jdi |¤ŽƒD ]\}}|ˆ|j< |jˆ krÅ|rÃ||k rÃ|d7 }qª nqªW n
 tjyÑ   Y nw ‡ ‡‡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ÚinfzBThe pts_unit 'pts' gives wrong results. Please use pts_unit 'sec'.Té   Úvideos   DivXs   DivX(\d+)Build(\d+)(\w)s   DivX(\d+)b(\d+)(\w)é   ó   pr   F)Z	any_frameÚbackwardrL   c                    s2   g | ]}ˆˆ| j   krˆ krn nˆ| ‘qS r   ©Úpts©Ú.0Úi©rR   ÚframesrQ   r   r   Ú
<listcomp>Ñ   s   2 z%_read_from_stream.<locals>.<listcomp>c                    s   g | ]}|ˆ k r|‘qS r   r   r^   )rQ   r   r   rc   Ö   ó    r   )Ú_CALLED_TIMESÚ_GC_COLLECTION_INTERVALÚgcÚcollectÚintÚmathÚfloorÚ	time_baser<   ÚceilÚwarningsÚwarnÚtypeÚcodec_contextÚ	extradataÚfindÚreÚsearchÚgroupÚmaxÚseekr   ÚAVErrorÚ	enumerateÚdecoder]   ÚsortedÚlenÚinsert)rK   rQ   rR   rS   rL   rT   Zshould_bufferÚmax_buffer_sizerr   ÚposÚdÚoZseek_offsetZbuffer_countÚ_idxrN   ÚresultZpreceding_framesZfirst_frame_ptsr   ra   r   Ú_read_from_stream�   sh   	€


ý

ü€þ"r…   ÚaframesÚaudio_framesÚ	ref_startÚref_endc           
      C   s|   |d j |d j }}| jd }|| d | }d}|}	||k r(t|| | ƒ}||kr4t|| | ƒ}	| d d …||	…f S )Nr   éÿÿÿÿr   )r]   r@   ri   )
r†   r‡   rˆ   r‰   ÚstartÚendZtotal_aframesÚstep_per_aframeÚs_idxÚe_idxr   r   r   Ú_align_audio_framesÝ   s   
r�   r]   ÚTHWCÚ	start_ptsÚend_ptsÚoutput_formatc              	   C   sŒ  t j ¡ st j ¡ sttƒ | ¡ }|dvrtd|› d�ƒ‚ddlm	} |ƒ dkrBt
j | ¡s6td| › �ƒ‚t | |||¡\}}}nòtƒ  |du rMtd	ƒ}||k r[td
|› d|› �ƒ‚i }g }	g }
tj}zdtj| dd��S}|jjrx|jjd j}|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Âw   Y  W n
 tjyÒ   Y nw dd„ |	D ƒ}dd„ |
D ƒ}|rìt  t |¡¡}nt j dt j!d�}|�r,t "|d¡}t  |¡}|dk�r$t#t$ %|d|  ¡ƒ}|td	ƒk�r$t#t$ &|d|  ¡ƒ}t'||
||ƒ}nt j dt j(d�}|dk�rA| )dddd¡}|||fS )aF  
    Reads a video from a file, returning both the video frames and the audio frames

    Args:
        filename (str): path to the video file. If using the pyav backend, this can be whatever ``av.open`` accepts.
        start_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):
            The start presentation time of the video
        end_pts (int if pts_unit = 'pts', 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'.
        output_format (str, optional): The format of the output video tensors. Can be either "THWC" (default) or "TCHW".

    Returns:
        vframes (Tensor[T, H, W, C] or Tensor[T, C, H, W]): 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‘   ÚTCHWz5output_format should be either 'THWC' or 'TCHW', got Ú.r   ©Úget_video_backendÚpyavzFile not found: NrV   z7end_pts should be larger than start_pts, got start_pts=z and end_pts=Úignore©Zmetadata_errorsrX   Ú	video_fpsrD   r    c                 S   s   g | ]}|  ¡  ¡ ‘qS r   )Úto_rgbÚ
to_ndarray©r_   rN   r   r   r   rc   C  rd   zread_video.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   )rž   rŸ   r   r   r   rc   D  ó    )r   r   r   rY   r#   r   rU   )r   r   r•   rY   r	   )*r4   r5   r6   r7   r
   Ú
read_videoÚupperÚ
ValueErrorÚtorchvisionr˜   ÚosÚpathÚexistsÚRuntimeErrorr   Ú_read_videor   r<   Údefault_timebaser   r?   rC   rD   rl   rX   r…   Úaverage_rater'   ry   r9   r=   ÚstackÚemptyr:   Úconcatenateri   rj   rk   rm   r�   Úfloat32Úpermute)r   r’   r“   rS   r”   r˜   Úvframesr†   ÚinfoZvideo_framesr‡   Úaudio_timebaserK   rœ   Zvframes_listZaframes_listr   r   r   r¡   ì   sŒ   
ÿ
ú
ú€æ€þ



r¡   c                 C   s*   | j d jj}|d u rdS d|v rdS dS )Nr   Fs   LavcT)rC   rq   rr   )rK   rr   r   r   r   Ú!_can_read_timestamps_from_packets]  s   r´   c                 C   s4   t | ƒrdd„ | jdd�D ƒS dd„ | jdd�D ƒS )Nc                 S   ó   g | ]
}|j d ur|j ‘qS r   r\   ©r_   Úxr   r   r   rc   i  ó    z,_decode_video_timestamps.<locals>.<listcomp>r   )rX   c                 S   rµ   r   r\   r¶   r   r   r   rc   k  r¸   )r´   Údemuxr{   )rK   r   r   r   Ú_decode_video_timestampsf  s   rº   c           	   
      sB  t j ¡ st j ¡ sttƒ ddlm} |ƒ dkrt 	| |¡S t
ƒ  d}g }zDtj| dd��3}|jjrZ|jjd }|j‰ zt|ƒ}W n tjyT   t d| › �¡ Y nw t|jƒ}W d  ƒ n1 sdw   Y  W n! tjy‹ } zd| › d	|› �}t |t¡ W Y d}~nd}~ww | ¡  |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.

    Args:
        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   r—   r™   Nrš   r›   z Failed decoding frames for file zFailed to open container for z; Caught error: rU   c                    s   g | ]}|ˆ  ‘qS r   r   r¶   ©Úvideo_time_baser   r   rc   œ  r    z)read_video_timestamps.<locals>.<listcomp>)r4   r5   r6   r7   r
   Úread_video_timestampsr¤   r˜   r   Ú_read_video_timestampsr   r   r?   rC   rX   rl   rº   ry   rn   ro   r<   r«   ÚRuntimeWarningÚsort)	r   rS   r˜   rœ   r]   rK   Zvideo_streamÚeÚmsgr   r»   r   r½   n  s>   
ÿ
€ø€	€þr½   )r   N)r   NNNNN)r   Nr]   r‘   r\   ).rg   rj   r¥   rt   rn   Ú	fractionsr   Útypingr   r   r   r   r   r   r;   r=   r4   Úutilsr
   Ú r   r   ÚloggingZ	set_levelÚERRORÚhasattrrX   rN   rJ   ÚImportErrorr   Úboolr   re   rf   ÚstrÚTensorr<   r8   ri   r…   r�   r¡   r´   rº   r½   r   r   r   r   Ú<module>   sÊ     ÿ€	ÿÿ

÷ÿþýüûúùø	÷

öXÿþýüû$ú
ùPÿÿÿÿ
þûÿ
þýüû
úq	,