
    ,}h:=                        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Zej,                  j/                  ej,                  j0                          eej4                  j6                  j8                  d      s ed	      Zd0dZdefdZ d a!da"	 	 	 	 	 	 d1de#dejH                  de%de#dee	e#ef      deejH                     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jH                  d%e
d"   d&e'd'e%dejH                  f
d(Z)	 	 	 	 d2de#d)ee%ef   d*eee%ef      de#d+e#deejH                  ejH                  e	e#ef   f   fd,Z*dddefd-Z+ddde
e'   fd.Z,d3de#de#dee
e'   ee%   f   fd/Z-y# e$ r  ed
      ZY %w xY w)4    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.
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     S/var/www/html/test/engine/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   ,   s    "i(((r   
   filenamevideo_arrayfpsvideo_codecoptionsaudio_array	audio_fpsaudio_codecaudio_optionsc	                    t         j                  j                         s-t         j                  j                         st	        t
               t                t        j                  |t         j                        j                         }t        |t              rt        j                  |      }t        j                  | d      5 }	|	j!                  ||      }
|j"                  d   |
_        |j"                  d   |
_        |dk7  rdnd	|
_        |xs i |
_        |0ddddddddddd
}|	j!                  ||      }|xs i |_        |j"                  d   }|dkD  rdnd}|	j,                  j.                  d   j0                  j2                  }t        j4                  ||         }t        j                  |      j                         j7                  |      }t        j8                  j;                  |||      }||_        |j?                  |      D ]  }|	jA                  |        |j?                         D ]  }|	jA                  |        |D ]Q  }t        jB                  j;                  |d	      }d|_"        |
j?                  |      D ]  }|	jA                  |        S |
j?                         D ]  }|	jA                  |        	 d
d
d
       y
# 1 sw Y   y
xY w)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   
libx264rgbyuv420prgb24Nz<f8z<f4z<i2z<i4u1)
dbldblpfltfltps16s16ps32s32pu8u8pr   stereomono)formatlayout)r<   NONE)#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   )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imgs                       r   rC   rC   5   s   6 99!!#EII,@,@,BK(//+U[[AGGIK #uhhsm		$ 0"	%%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<<>EElSKMM..{CS\h.iE )E"//%0 &f%& #//+ &f%&  	&CMM..s7.CE$EO --. &f%&	& mmo 	"FMM&!	"_0" 0" 0"s   HKKrZ   zav.container.Containerstart_offset
end_offsetpts_unitr[   zav.stream.Streamstream_name.zav.frame.Framec                 B   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/         | j0                  di |      D ]2  \  }}|||j2                  <   |j2                  |k\  s%|r||k  r|dz  }2 n t5        |      D cg c]#  }|||   j2                  cxk  r|k  sn n||   % }}t7        |      dkD  rL|dkD  rG||vrC|D cg c]
  }||k  s	| }}t7        |      dkD  r t'        |      }|j9                  d||          |S # t*        j,                  $ r g cY S w xY w# t*        j,                  $ 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_baserG   ceilwarningswarntypecodec_context	extradatafindresearchgroupmaxseekr   AVError	enumeratedecodeptssortedleninsert)rZ   re   rf   rg   r[   rh   framesshould_buffermax_buffer_sizer   posdoseek_offsetbuffer_count_idxrb   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#  ?I>  I> J;
J"
J-J#I;:I;>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   rL   rv   )
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         j                  j                         s-t         j                  j                         st	        t
               |j                         }|dvrt        d| d      ddlm	} t        j                  j                  |       st        d|         |       dk7  r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   j.                  }|j*                  j0                  r\t3        |||||j*                  j0                  d   ddi      }	|j*                  j0                  d   j4                  }|t#        |      |d<   |j*                  j,                  rOt3        |||||j*                  j,                  d   ddi      }
|j*                  j,                  d   j6                  |d<   ddd       |	D cg c]   }|j;                         j=                         " }}|
D cg c]  }|j=                          }}|r)t        j>                  tA        jB                  |            }n%t        jD                  dt         jF                        }|rtA        jH                  |d      }t        j>                  |      }|dk(  rVtK        tM        jN                  |d|z  z              }|t#        d	      k7  r$tK        tM        jP                  |d|z  z              }tS        ||
||      }n%t        jD                  dt         jT                        }|dk(  r|jW                  dddd      }|||fS # 1 sw Y   |xY w# t&        j8                  $ r Y w xY wc c}w c c}w )a   
    Reads a video from a file, returning both the video frames and the audio frames

    Args:
        filename (str): path to the video file
        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_backendzFile not found: pyavNrk   z7end_pts should be larger than start_pts, got start_pts=z and end_pts=ignoremetadata_errorsrm   	video_fpsrQ   r#   )r   r   r   rn   r'   r   rj   )r   r   r   rn   r
   ),r?   r@   rA   rB   r   
read_videoupper
ValueErrortorchvisionr   ospathexistsRuntimeErrorr   _read_videor   rG   default_timebaser   rJ   rP   rQ   ry   rm   r   average_rater+   r   to_rgb
to_ndarrayrD   rH   stackemptyrE   concatenaterv   rw   rx   rz   r   float32permute)r   r   r   rg   r   r   vframesr   infovideo_framesr   audio_timebaserZ   r   rb   vframes_listaframes_lists                    r   r   r      s}   2 99!!#EII,@,@,BJ'!'')M,,PQ^P__`abb-77>>(#-hZ899f$!+!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 zz 		 OEs7   N= %DN06N= %O-O0N:5N= =OOc                 Z    | j                   d   j                  j                  }|yd|v ryy)Nr   Fs   LavcT)rP   r~   r   )rZ   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   )rm   )r   demuxr   r   )rZ   xs     r   _decode_video_timestampsr   g  sh    (3(Q7M!155;LMM(//a/8N!AEE<MNN NNs   A:A:A?)A?c                 X   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       |j/                          |d
k(  r|D 
cg c]  }
|
z  	 }}
||fS # t        j"                  $ r t%        j&                  d|         Y uw xY w# 1 sw Y   exY w# t        j"                  $ r,}d|  d	| }	t%        j&                  |	t,               Y d}~d}~ww xY wc c}
w )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: rj   )r?   r@   rA   rB   r   read_video_timestampsr   r   r   _read_video_timestampsr   r   rJ   rP   rm   ry   r   r   r{   r|   rG   r   RuntimeWarningsort)r   rg   r   r   r   rZ   video_streamvideo_time_baseemsgr   s              r   r   r   o  sv   " 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	> zz QMM$DXJ"OPQ	= 	= :: +-hZ7GsKc>**+ 1sZ   E% <ED( E5E% F'(+EEEEE"E% %F$8"FF$)r   N)libx264NNNNN)r   Nr   r   )r   ).rt   rw   r   r   r{   	fractionsr   typingr   r   r   r   r   r	   rF   rH   r?   utilsr    r   r   logging	set_levelERRORhasattrrm   rb   rY   ImportErrorr   boolr   rr   rs   strTensorrG   rC   rv   r   r   r   r   r   r   r   r   r   <module>r      s   	  	 	   : :   ' JJ))*288>>,,k:
&
)t )
   !(,*.!%!%.2U"U"U" 
U" 	U"
 d38n%U" %,,'U" U" #U" DcN+U" 
U"pM'MM M 	M
 M c8E#uS#XS	*I$JKKLM 

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