
    YhG                        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
 d dlZd dlZddlmZ ddlmZ ddlmZ 	 d dlZej                            ej        j                    eej        j        j        d	          s ed
          Z	 ej        Zn# e$ r
 ej        ZY nw xY wn# e$ r  ed          ZY nw xY wd4dZ de!fdZ"d a#da$	 	 	 	 	 	 d5d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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%Z-d&ej&        d'e,d$         d(e*d)e'dej&        f
d*Z.	 	 	 	 d6de%d-e
e'ef         d.e	e
e'ef                  de%d/e%de+ej&        ej&        e(e%ef         f         fd0Z/ddde!fd1Z0ddde,e*         fd2Z1d7de%de%de+e,e*         e	e'         f         fd3Z2dS )8    N)Fraction)AnyOptionalUnion   )_log_api_usage_once   )
_video_opt) _raise_video_deprecation_warning	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.
zPyAV 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                  H    t          t          t                    rt          d S N
isinstanceav	Exception     f/var/www/tools.fuzzalab.pt/emblema-extractor/venv/lib/python3.11/site-packages/torchvision/io/video.py_check_av_availabler   ,   s#    "i    r   c                  8    t          t          t                     S r   r   r   r   r   _av_availabler   1   s    "i((((r   
   libx264filenamevideo_arrayfpsvideo_codecoptionsaudio_array	audio_fpsaudio_codecaudio_optionsc	                    t                       t          j                                        s2t          j                                        st          t                     t                       t          j        |t          j	                  
                    d          }t          |t                    r!t          t          j        |                    }t!          j        | d          5 }	|	                    ||          }
|j        d         |
_        |j        d         |
_        |d	k    rd
nd|
_        |pi |
_        |7ddddddddddd
}|	                    ||          }|pi |_        |j        d         }|dk    rdnd}|	j        j        d         j        j        }t          j        ||                   }t          j        |          
                    d                              |          }t           j                            |||          }||_         |!                    |          D ]}|	"                    |           |!                                D ]}|	"                    |           |D ]{}t           j#                            |d          }	 d|_$        n"# tJ          $ r ddl&m'} |j(        |_$        Y nw xY w|
!                    |          D ]}|	"                    |           ||
!                                D ]}|	"                    |           	 ddd           dS # 1 swxY w Y   dS )a~  
    [DEPRECATED] Writes a 4d tensor in [T, H, W, C] format in a video file.

    .. warning::

        DEPRECATED: All the video decoding and encoding capabilities of torchvision
        are deprecated from version 0.22 and will be removed in version 0.24.  We
        recommend that you migrate to
        `TorchCodec <https://github.com/pytorch/torchcodec>`__, where we'll
        consolidate the future decoding/encoding capabilities of PyTorch

    This function relies on PyAV (therefore, ultimately FFmpeg) to encode
    videos, you can get more fine-grained control by referring to the other
    options at your disposal within `the FFMpeg wiki
    <http://trac.ffmpeg.org/wiki#Encoding>`_.

    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.
            The list of options is codec-dependent and can all
            be found from `the FFMpeg wiki <http://trac.ffmpeg.org/wiki#Encoding>`_.
        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.
            The list of options is codec-dependent and can all
            be found from `the FFMpeg wiki <http://trac.ffmpeg.org/wiki#Encoding>`_.

    Examples::
        >>> # Creating libx264 video with CRF 17, for visually lossless footage:
        >>>
        >>> from torchvision.io import write_video
        >>> # 1000 frames of 100x100, 3-channel image.
        >>> vid = torch.randn(1000, 100, 100, 3, dtype = torch.uint8)
        >>> write_video("video.mp4", options = {"crf": "17"})

    dtypeT)forcew)mode)rater   r	   
libx264rgbyuv420prgb24Nz<f8z<f4z<i2z<i4u1)
dbldblpfltfltps16s16ps32s32pu8u8pr   stereomono)formatlayout)r<   NONE)PictureType))r   torchjitis_scripting
is_tracingr   write_videor   	as_tensoruint8numpyr   floatintnproundr   open
add_streamshapewidthheightpix_fmtr    streamsaudior<   namer'   astype
AudioFramefrom_ndarraysample_rateencodemux
VideoFramer   	TypeErrorav.video.framer?   r>   )r   r   r   r   r    r!   r"   r#   r$   	containerstreamaudio_format_dtypesa_streamnum_channelsaudio_layoutaudio_sample_fmtformat_dtypeframepacketimgr?   s                        r   rD   rD   :   s   j %&&&9!!## )EI,@,@,B,B )K(((/+U[AAAGGdGSSK #u !"(3--  		$	$	$ 6"	%%k%<<"(+#)!,&1\&A&Aw B"# # !++Ki+HHH,2H&,Q/L'3a'7'788VL(06q9@E8$78H$IJJL/+66<<4<HHOOP\]]KM..{CS\h.iiE )E"//%00 & &f%%%%"//++ & &f%%%% 
	& 
	&CM..s7.CCE3"( 3 3 3666666"-"23
 !--.. & &f%%%%& mmoo 	" 	"FMM&!!!!	"k6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6" 6"s8   -F3L3!J)(L3)KL3KAL33L7:L7r^   zav.container.Containerstart_offset
end_offsetpts_unitr_   zav.stream.Streamstream_name.zav.frame.Framec                    t           dz  a t           t          z  t          dz
  k    rt          j                     |dk    rlt	          t          j        d|j        z  z                      t          d          k    r,t	          t          j	        d|j        z  z                      nt          j        d           i d}d}|j        dk    rx|j        j        }|rjd|v rf|                    d          }	||	d          }
t!          j        d	|
          }|t!          j        d
|
          }||                    d          dk    }}t'          |dz
  d          }|rt'          ||z
  d          }	 |                     |dd|           n# t*          $ r g cY S w xY wd}	 t-           | j        di |          D ]*\  }}||j        <   |j        k    r|r||k     r|dz  }( n+n# t*          $ r Y nw xY wfdt3                    D             }t5                    dk    rVdk    rPvrLfdD             }t5          |          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)	any_framebackwardr_   c                 V    g | ]%}|         j         cxk    rk    n n|         &S r   pts).0irj   framesri   s     r   
<listcomp>z%_read_from_stream.<locals>.<listcomp>   sE    ___A<6!9=3^3^3^3^T^3^3^3^3^3^fQi3^3^3^r   c                      g | ]
}|k     |S r   r   )ry   rz   ri   s     r   r|   z%_read_from_stream.<locals>.<listcomp>   s#    BBB!\1A1AA1A1A1Ar   r   )_CALLED_TIMES_GC_COLLECTION_INTERVALgccollectrI   mathfloor	time_baserH   ceilwarningswarntypecodec_context	extradatafindresearchgroupmaxseekFFmpegError	enumeratedecoderx   sortedleninsert)r^   ri   rj   rk   r_   rl   should_buffermax_buffer_sizer   posdoseek_offsetbuffer_count_idxrf   resultpreceding_framesfirst_frame_ptsr{   s    ``                @r   _read_from_streamr      s    QM..2IA2MMM

5 4:la&:J6J&KLLMMu%%TYzQ9I5I'JKKLLJZ[[[FMO{g (2	  	3I--..))C#$$A	5q99AyI5q99} !

d 2KkAoq))K < +7;;{ed6RRRR    			 L
$%5Y%5%D%D%D%DEE 	 	KD% %F59yJ&&  \O%C%C A%L	 '
     `________F
6{{Q<!++F0J0J CBBBvBBB  1$$!"233OMM!VO4555Ms%   6F FF%AG+ +
G87G8aframesaudio_frames	ref_startref_endc                     |d         j         |d         j         }}| j        d         }||z
  dz   |z  }d}|}	||k     rt          ||z
  |z            }||k    rt          ||z
  |z            }	| d d ||	f         S )Nr   r	   )rx   rN   rI   )
r   r   r   r   startendtotal_aframesstep_per_aframes_idxe_idxs
             r   _align_audio_framesr     s     a$l2&6&:3EM!$MU{Q-7OEEyY&/9::
W}}Ws]o566111eEk>""r   rx   THWC	start_ptsend_ptsoutput_formatc           
         t                       t          j                                        s2t          j                                        st          t                     |                                }|dvrt          d| d          ddl	m
}  |            dk    rNt          j                            |           st          d|            t          j        | |||          \  }}}n~t#                       |t%          d	          }||k     rt          d
| d|           i }g }	g }
t          j        }	 t)          j        | d          5 }|j        j        r|j        j        d         j        }|j        j        rQt5          |||||j        j        d         ddi          }	|j        j        d         j        }|t%          |          |d<   |j        j        r@t5          |||||j        j        d         ddi          }
|j        j        d         j        |d<   ddd           n# 1 swxY w Y   n# t:          $ r Y nw xY wd |	D             }d |
D             }|r't          j        t?          j         |                    }n t          j!        dt          j"                  }|rt?          j#        |d          }t          j        |          }|dk    ratI          tK          j&        |d|z  z                      }|t%          d	          k    r'tI          tK          j'        |d|z  z                      }tQ          ||
||          }n t          j!        dt          j)                  }|dk    r|*                    dddd          }|||fS )a  [DEPRECATED] Reads a video from a file, returning both the video frames and the audio frames

    .. warning::

        DEPRECATED: All the video decoding and encoding capabilities of torchvision
        are deprecated from version 0.22 and will be removed in version 0.24.  We
        recommend that you migrate to
        `TorchCodec <https://github.com/pytorch/torchcodec>`__, where we'll
        consolidate the future decoding/encoding capabilities of PyTorch

    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: Nro   z7end_pts should be larger than start_pts, got start_pts=z and end_pts=ignoremetadata_errorsrq   	video_fpsrS   r"   c                 Z    g | ](}|                                                                 )S r   )to_rgb
to_ndarrayry   rf   s     r   r|   zread_video.<locals>.<listcomp>q  s,    NNN1133NNNr   c                 6    g | ]}|                                 S r   )r   r   s     r   r|   zread_video.<locals>.<listcomp>r  s$    EEEu((**EEEr   )r   r	   r	   rr   r&   r	   rn   )r	   r   r   rr   r   )+r   r@   rA   rB   rC   r   
read_videoupper
ValueErrortorchvisionr   ospathexistsRuntimeErrorr
   _read_videor   rH   default_timebaser   rL   rR   rS   r   rq   r   average_rater+   r   rE   rJ   stackemptyrF   concatenaterI   r   r   r   r   float32permute)r   r   r   rk   r   r   vframesr   infovideo_framesr   audio_timebaser^   r   vframes_listaframes_lists                   r   r   r     s#   @ %&&&9!!## (EI,@,@,B,B (J'''!''))M,,,aQ^aaabbb------f$$w~~h'' 	><(<<===!+!7)WV^!_!_$$?EllGYk)kkbikk   #4	8<<< H	$* J%.%6%<Q%?%IN$* =#4!! !)/2 !$ $L !* 1 7 : GI ,,1),<,<[)$* 	H#4!! !)/2 !$ $L )2(9(?(B(GD%5H H H H H H H H H H H H H H H8  	 	 	D	 ONNNNEEEEE 	Cobh|&<&<==GGk,ekBBBG 		?n\155Gog..G5  
9N8J+K L LMM	eEll**!$)Gq>7I,J"K"KLLG)'<GTTGGk&>>>G//!Q1--GT!!s7   9H4 CH(H4 (H,,H4 /H,0H4 4
I Ic                 H    | j         d         j        j        }|dS d|v rdS dS )Nr   Fs   LavcT)rR   r   r   )r^   r   s     r   !_can_read_timestamps_from_packetsr     s5    !!$2<Iu)t5r   c                     t          |           r d |                     d          D             S d |                     d          D             S )Nc                 *    g | ]}|j         	|j         S r   rw   ry   xs     r   r|   z,_decode_video_timestamps.<locals>.<listcomp>  s!    MMM!15;L;L;L;Lr   r   )rq   c                 *    g | ]}|j         	|j         S r   rw   r   s     r   r|   z,_decode_video_timestamps.<locals>.<listcomp>  s!    NNN!AE<M<M<M<Mr   )r   demuxr   )r^   s    r   _decode_video_timestampsr     sZ    (33 OMMyQ77MMMMNNy//a/88NNNNr   c                 B  	 t                       t          j                                        s2t          j                                        st          t                     ddlm}  |            dk    rt          j
        | |          S t                       d}g }	 t          j        | d          5 }|j        j        re|j        j        d         }|j        		 t#          |          }n'# t$          $ r t'          j        d|             Y nw xY wt+          |j                  }ddd           n# 1 swxY w Y   n9# t$          $ r,}d|  d	| }t'          j        |t.                     Y d}~nd}~ww xY w|                                 |d
k    r	fd|D             }||fS )a  [DEPREACTED] List the video frames timestamps.

    .. warning::

        DEPRECATED: All the video decoding and encoding capabilities of torchvision
        are deprecated from version 0.22 and will be removed in version 0.24.  We
        recommend that you migrate to
        `TorchCodec <https://github.com/pytorch/torchcodec>`__, where we'll
        consolidate the future decoding/encoding capabilities of PyTorch

    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: rn   c                     g | ]}|z  S r   r   )ry   r   video_time_bases     r   r|   z)read_video_timestamps.<locals>.<listcomp>  s    000qq?"000r   )r   r@   rA   rB   rC   r   read_video_timestampsr   r   r
   _read_video_timestampsr   r   rL   rR   rq   r   r   r   r   r   rH   r   RuntimeWarningsort)
r   rk   r   r   rx   r^   video_streamemsgr   s
            @r   r   r     s$   0 %&&&9!!## 3EI,@,@,B,B 31222------f$$08DDDI
C+WXx888 	=I & =(06q9"."8Q29==CC" Q Q QM"OX"O"OPPPPPQ!,";<<		= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	=  + + +KhKKKKc>********+ HHJJJ50000C000	>s`   D< 2&D0C)(D0)!D
D0DD0$D< 0D44D< 7D48D< <
E2"E--E2)r   N)r   NNNNN)r   Nrx   r   rw   )3r   r   r   r   r   	fractionsr   typingr   r   r   rG   rJ   r@   utilsr    r
   _video_deprecation_warningr   r   logging	set_levelERRORhasattrrq   rf   r[   ImportErrorr   AttributeErrorAVErrorr   boolr   r~   r   strTensorrH   dictrD   rI   tuplelistr   r   r   r   r   r   r   r   r   <module>r      s   				  				 				        ' ' ' ' ' ' ' ' ' '      ' ' ' ' ' '       H H H H H HIIIJ)***728>,k:: 	
[
 
!n ! ! !j!   		
 
BBB   
)t ) ) ) )
   !(,*.!%!%.2v" v"v"v" 
v" 	v"
 d38n%v" %,'v" v" #v" DcN+v" 
v" v" v" v"rM'MM M 	M
 M c8E#uS#XS	*I$JKKLM 

M M M M`#\#)-.>)?#LO#Z_#
\# # # #" )*04v" v"v"UH_%v" eE8O,-v" 	v"
 v" 5<tCH~56v" v" v" v"r1I d    O(@ OT#Y O O O O8 8C 83 85cT\]bTcIcCd 8 8 8 8 8 8s7    AB* B B* B&#B* %B&&B* *B=<B=