
    khG                        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 ddlmZ 	 d dlZej0                  j3                  ej0                  j4                          eej8                  j:                  j<                  d	      s ed
      Z	 ej@                  Z d1dZ#de$fdZ%d a&da'	 	 	 	 	 	 d2de(dejR                  de*de(dee	e(ef      deejR                     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jR                  d&e
d#   d'e,d(e*dejR                  f
d)Z.	 	 	 	 d3de(d*ee*ef   d+eee*ef      de(d,e(deejR                  ejR                  e	e(ef   f   fd-Z/ddde$fd.Z0ddde
e,   fd/Z1d4de(de(dee
e,   ee*   f   fd0Z2y# e!$ r ejD                  Z Y )w xY w# e$ r  ed      ZY =w xY w)5    N)Fraction)AnyDictListOptionalTuple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                  8    t        t        t              rt        y N
isinstanceav	Exception     P/var/www/teggl/fontify/venv/lib/python3.12/site-packages/torchvision/io/video.py_check_av_availabler   ,   s    "i  !r   c                  ,    t        t        t               S r   r   r   r   r   _av_availabler   1   s    "i(((r   
   filenamevideo_arrayfpsvideo_codecoptionsaudio_array	audio_fpsaudio_codecaudio_optionsc	                 (   t                t        j                  j                         s-t        j                  j	                         st        t               t                t        j                  |t        j                        j                  d      }t        |t              rt        j                  |      }t        j                   | d      5 }	|	j#                  ||      }
|j$                  d   |
_        |j$                  d   |
_        |d	k7  rd
nd|
_        |xs i |
_        |2ddddddddddd
}|	j#                  ||      }|xs i |_        |j$                  d   }|dkD  rdnd}|	j.                  j0                  d   j2                  j4                  }t        j6                  ||         }t        j                  |      j                  d      j9                  |      }t        j:                  j=                  |||      }||_        |jA                  |      D ]  }|	jC                  |        |jA                         D ]  }|	jC                  |        |D ]R  }t        jD                  j=                  |d      }	 d|_#        |
jA                  |      D ]  }|	jC                  |        T |
jA                         D ]  }|	jC                  |        	 ddd       y# tH        $ r ddl%m&} |jN                  |_#        Y {w xY w# 1 sw Y   yxY w)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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.framerA   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imgrA   s                        r   rF   rF   :   s   j %&99!!#EII,@,@,BK(//+U[[AGGdGSK #uhhsm		$ 6"	%%k%<"((+#))!,&1\&Aw B"# !++Ki+HH,2H&,,Q/L'3a'78VL(0066q9@@EE88$78H$IJL//+6<<4<HOOP\]KMM..{CS\h.iE )E"//%0 &f%& #//+ &f%&  
	&CMM..s7.CE3"( !--. &f%&
	& mmo 	"FMM&!	"k6" 6"X  36"-"2"23Y6" 6"s2   F0LK"	AL" LLLLL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(  rkt	        t        j                  |d|j                  z  z              }|t        d      k7  rDt	        t        j                  |d|j                  z  z              }nt        j                  d       i }d}d}|j                  dk(  rv|j                  j                  }	|	r^d|	v rZ|	j                  d      }
|	|
d  }t!        j"                  d	|      }|t!        j"                  d
|      }||j%                  d      dk(  }|}t'        |dz
  d      }|rt'        ||z
  d      }	 | j)                  |dd|       d}	 t-         | j.                  di |      D ]2  \  }}|||j0                  <   |j0                  |k\  s%|r||k  r|dz  }2 n t3        |      D cg c]#  }|||   j0                  cxk  r|k  sn n||   % }}t5        |      dkD  rL|dkD  rG||vrC|D cg c]
  }||k  s	| }}t5        |      dkD  r t'        |      }|j7                  d||          |S # t*        $ r g cY S w xY w# t*        $ r Y w xY wc c}w c c}w )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`   r   )_CALLED_TIMES_GC_COLLECTION_INTERVALgccollectintmathfloor	time_baserJ   ceilwarningswarntypecodec_context	extradatafindresearchgroupmaxseekFFmpegError	enumeratedecodeptssortedleninsert)r_   rj   rk   rl   r`   rm   framesshould_buffermax_buffer_sizer   posdoseek_offsetbuffer_count_idxrg   iresultpreceding_framesfirst_frame_ptss                        r   _read_from_streamr      s    QM..2IA2MM


5 4::la&:J:J6J&KLMu%TYYzQ9I9I5I'JKLJZ[FMO{{g ((22	 I-..)C#$A		5q9AyII5q9} !
d 2KkAoq)K +7;{ed6R
 L
$%5Y%5%5%D%DE 	KD% %F599yyJ& \O%C A%L	 "(_A<6!9==3^T^3^fQi_F_
6{Q<!+F0J (.B!\1AABB 1$!"23OMM!VO45M5   	   `
 CsB   (I#  ?I4  I4 J;
J"
J-J#I10I14	J ?J aframesaudio_frames	ref_startref_endc                     |d   j                   |d   j                   }}| j                  d   }||z
  dz   |z  }d}|}	||k  rt        ||z
  |z        }||kD  rt        ||z
  |z        }	| d d ||	f   S )Nr   r   )r   rO   r{   )
r   r   r   r   startendtotal_aframesstep_per_aframes_idxe_idxs
             r   _align_audio_framesr     s     a$$l2&6&:&:3EMM!$MU{Q-7OEEyY&/9:
W}Ws]o561eEk>""r   	start_ptsend_ptsoutput_formatc           
         t                t        j                  j                         s-t        j                  j	                         st        t               |j                         }|dvrt        d| d      ddl	m
}  |       dk7  rKt        j                  j                  |       st        d|        t        j                   | |||      \  }}}nt#                |t%        d	      }||k  rt        d
| d|       i }g }	g }
t        j&                  }	 t)        j*                  | d      5 }|j,                  j.                  r#|j,                  j.                  d   j0                  }|j,                  j2                  r\t5        |||||j,                  j2                  d   ddi      }	|j,                  j2                  d   j6                  }|t%        |      |d<   |j,                  j.                  rOt5        |||||j,                  j.                  d   ddi      }
|j,                  j.                  d   j8                  |d<   ddd       |	D cg c]   }|j=                         j?                         " }}|
D cg c]  }|j?                          }}|r)t        j@                  tC        jD                  |            }n%t        jF                  dt        jH                        }|rtC        jJ                  |d      }t        j@                  |      }|dk(  rVtM        tO        jP                  |d|z  z              }|t%        d	      k7  r$tM        tO        jR                  |d|z  z              }tU        ||
||      }n%t        jF                  dt        jV                        }|dk(  r|jY                  dddd      }|||fS # 1 sw Y   |xY w# t:        $ r Y w xY wc c}w c c}w )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)
    )THWCTCHWz5output_format should be either 'THWC' or 'TCHW', got .r   get_video_backendpyavzFile not found: Nrp   z7end_pts should be larger than start_pts, got start_pts=z and end_pts=ignoremetadata_errorsrr   	video_fpsrT   r$   )r   r   r   rs   r(   r   ro   )r   r   r   rs   r
   )-r   rB   rC   rD   rE   r   
read_videoupper
ValueErrortorchvisionr   ospathexistsRuntimeErrorr   _read_videor   rJ   default_timebaser   rM   rS   rT   r~   rr   r   average_rater-   r   to_rgb
to_ndarrayrG   rK   stackemptyrH   concatenater{   r|   r}   r   r   float32permute)r   r   r   rl   r   r   vframesr   infovideo_framesr   audio_timebaser_   r   rg   vframes_listaframes_lists                    r   r   r     s   @ %&99!!#EII,@,@,BJ'!'')M,,PQ^P__`abb-f$ww~~h'!1(<==!+!7!7)WV^!_$?ElGYI)Tabiajk  #44	8< H	$$**%.%6%6%<%<Q%?%I%IN$$**#4!! !))//2 !$L !* 1 1 7 7 : G GI ,,1),<[)$$**#4!! !))//2 !$L )2(9(9(?(?(B(G(GD%5H@ BNN113NN8DEu((*EEoobhh|&<=Gkk,ekkBGnn\15Goog.G5 

9N8J+K LM	eEl*!$))Gq>7I,J"KLG)'<GTGkk&>G//!Q1-GT!!oH H8  		 OEs7   O /DN: O %O7O:O?O 	OOc                 Z    | j                   d   j                  j                  }|yd|v ryy)Nr   Fs   LavcT)rS   r   r   )r_   r   s     r   !_can_read_timestamps_from_packetsr     s5    !!!$22<<I)r   c                    t        |       r7| j                  d      D cg c]  }|j                  |j                   c}S | j                  d      D cg c]  }|j                  |j                   c}S c c}w c c}w )Nr   )rr   )r   demuxr   r   )r_   xs     r   _decode_video_timestampsr     sh    (3(Q7M!155;LMM(//a/8N!AEE<MNN NNs   A:A:A?)A?c                 D   t                t        j                  j                         s-t        j                  j	                         st        t               ddlm}  |       dk7  rt        j                  | |      S t                d}g }	 t        j                  | d      5 }|j                  j                  rF|j                  j                  d   }|j                   }	 t#        |      }t+        |j,                        }ddd       |j1                          |d
k(  r|D 
cg c]  }
|
z  	 }}
||fS # t$        $ r t'        j(                  d|         Y kw xY w# 1 sw Y   [xY w# t$        $ r,}d|  d	| }	t'        j(                  |	t.               Y d}~d}~ww xY wc c}
w )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: ro   )r   rB   rC   rD   rE   r   read_video_timestampsr   r   r   _read_video_timestampsr   r   rM   rS   rr   r~   r   r   r   r   rJ   r   RuntimeWarningsort)r   rl   r   r   r   r_   video_streamvideo_time_baseemsgr   s              r   r   r     st   0 %&99!!#EII,@,@,B12-f$008DDI
C+WWXx8 	=I  &&(0066q9"."8"8Q29=C ",";";<		= HHJ5,/0qq?"00	> # QMM$DXJ"OPQ	= 	=  +-hZ7GsKc>**+ 1sZ   E% "<ED2*E?E%  F2!EEEEE"E% %	F."FF)r   N)libx264NNNNN)r   Nr   r   )r   )3ry   r|   r   r   r   	fractionsr   typingr   r   r   r   r   r	   rI   rK   rB   utilsr    r   _video_deprecation_warningr   r   logging	set_levelERRORhasattrrr   rg   r\   ImportErrorr   AttributeErrorAVErrorr   boolr   rw   rx   strTensorrJ   rF   r{   r   r   r   r   r   r   r   r   r   <module>r      s+   	  	 	   : :   '  HJJ))*288>>,,k:
!nn
)t )
   !(,*.!%!%.2v"v"v" 
v" 	v"
 d38n%v" %,,'v" v" #v" DcN+v" 
v"rM'MM M 	M
 M c8E#uS#XS	*I$JKKLM 

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