
    ڧg-                     N   d dl Z d dlZd dlmZmZmZ d dlZddlmZ ddl	m
Z
 e
rdefdZndefd	Z	 d dlZej                            ej        j                    eej        j        j        d
          s ed          Zn# e$ r  ed          ZY nw xY w G d d          ZdS )    N)AnyDictIterator   )_log_api_usage_once   )_HAS_CPU_VIDEO_DECODERreturnc                      dS )NT r       W/var/www/html/ai-engine/env/lib/python3.11/site-packages/torchvision/io/video_reader.py_has_video_optr      s    tr   c                      dS )NFr   r   r   r   r   r      s    ur   	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.
c            	           e Zd ZdZ	 	 ddedededdfd	Zdeeef         fd
Z	de
eeef                  fdZddededd fdZdeeef         fdZdedefdZdS )VideoReadera  
    Fine-grained video-reading API.
    Supports frame-by-frame reading of various streams from a single video
    container. Much like previous video_reader API it supports the following
    backends: video_reader, pyav, and cuda.
    Backends can be set via `torchvision.set_video_backend` function.

    .. warning::

        In the near future, we intend to centralize PyTorch's video decoding
        capabilities within the `torchcodec
        <https://github.com/pytorch/torchcodec>`_ project. We encourage you to
        try it out and share your feedback, as the torchvision video decoders
        will eventually be deprecated.

    .. betastatus:: VideoReader class

    Example:
        The following examples creates a :mod:`VideoReader` object, seeks into 2s
        point, and returns a single frame::

            import torchvision
            video_path = "path_to_a_test_video"
            reader = torchvision.io.VideoReader(video_path, "video")
            reader.seek(2.0)
            frame = next(reader)

        :mod:`VideoReader` implements the iterable API, which makes it suitable to
        using it in conjunction with :mod:`itertools` for more advanced reading.
        As such, we can use a :mod:`VideoReader` instance inside for loops::

            reader.seek(2)
            for frame in reader:
                frames.append(frame['data'])
            # additionally, `seek` implements a fluent API, so we can do
            for frame in reader.seek(2):
                frames.append(frame['data'])

        With :mod:`itertools`, we can read all frames between 2 and 5 seconds with the
        following code::

            for frame in itertools.takewhile(lambda x: x['pts'] <= 5, reader.seek(2)):
                frames.append(frame['data'])

        and similarly, reading 10 frames after the 2s timestamp can be achieved
        as follows::

            for frame in itertools.islice(reader.seek(2), 10):
                frames.append(frame['data'])

    .. note::

        Each stream descriptor consists of two parts: stream type (e.g. 'video') and
        a unique stream id (which are determined by the video encoding).
        In this way, if the video container contains multiple
        streams of the same type, users can access the one they want.
        If only stream type is passed, the decoder auto-detects first stream of that type.

    Args:
        src (string, bytes object, or tensor): The media source.
            If string-type, it must be a file path supported by FFMPEG.
            If bytes, should be an in-memory representation of a file supported by FFMPEG.
            If Tensor, it is interpreted internally as byte buffer.
            It must be one-dimensional, of type ``torch.uint8``.

        stream (string, optional): descriptor of the required stream, followed by the stream id,
            in the format ``{stream_type}:{stream_id}``. Defaults to ``"video:0"``.
            Currently available options include ``['video', 'audio']``

        num_threads (int, optional): number of threads used by the codec to decode video.
            Default value (0) enables multithreading with codec-dependent heuristic. The performance
            will depend on the version of FFMPEG codecs supported.
    videor   srcstreamnum_threadsr
   Nc                 T   t          |            ddlm}  |            | _        t	          |t
                    r|st          d          nt	          |t                    r| j        dv rt          d          | j        dk    rt          j
        |          }nt          j                    5  t          j        dd	           t          j        |t          j        
          }d d d            n# 1 swxY w Y   nRt	          |t          j                  r| j        dv rt          d          nt          dt%          |                     | j        dk    r@t          j        d          }t          j        j                            ||          | _        d S | j        dk    rt	          |t
                    r-t          j        j                            |||          | _        d S t	          |t          j                  rIt          j        j                            ddd          | _        | j                            |||           d S d S | j        dk    rt5          j        |d          | _        |                    d          d         }t=          |                    d                    dk    rdn't?          |                    d          d                   }||i| _          | j        j!        di | j         | _        d S t          d"                    | j                            )Nr   )get_video_backendzsrc cannot be empty)cudazTVideoReader cannot be initialized from bytes object when using cuda or pyav backend.pyavignorez The given buffer is not writable)message)dtype)r   r   zUVideoReader cannot be initialized from Tensor object when using cuda or pyav backend.z7src must be either string, Tensor or bytes object. Got r   video_reader r   )metadata_errors:r   zUnknown video backend: {}r   )#r   r    r   backend
isinstancestr
ValueErrorbytesRuntimeErrorioBytesIOwarningscatch_warningsfilterwarningstorch
frombufferuint8Tensortypedeviceclassestorchvision
GPUDecoder_cVideoinit_from_memoryavopen	containersplitlenintpyav_streamdecodeformat)selfr   r   r   r   r3   stream_type	stream_ids           r   __init__zVideoReader.__init__z   sf    	D!!!((((((((**c3 	d 8 !67778U## 	d|x''"j   ''joo,.. C C+H>`aaaa*3ekBBBCC C C C C C C C C C C C C C C U\** 	d|///"k   0
 bW[\_W`W`bbccc<6!!\&))Fm/::3GGDGGG\^++#s## C-399#v{SSC.. C-399"b!DD((fkBBBBBC C \V##WS(CCCDN ,,s++A.K c!2!233q88c&,,sBSBSTUBV>W>WI +Y7D+dn+??d.>??DGGG
 :AA$,OOPPPs   -7C00C47C4c                    | j         dk    r=| j                                        }|                                dk    rt          |ddS | j         dk    r| j                                        \  }}n	 t          | j                  }t          |j        |j        z            }d| j        v rNt          j
        |                                                                                              ddd          }nFd	| j        v r;t          j
        |                                                              dd          }nd}n# t          j        j        $ r t          w xY w|                                dk    rt          ||dS )
a  Decodes and returns the next frame of the current stream.
        Frames are encoded as a dict with mandatory
        data and pts fields, where data is a tensor, and pts is a
        presentation timestamp of the frame expressed in seconds
        as a float.

        Returns:
            (dict): a dictionary and containing decoded frame (``data``)
            and corresponding timestamp (``pts``) in seconds

        r   r   N)dataptsr   r   r   r   audio)r#   r7   nextnumelStopIterationfloatrI   	time_baser@   r.   	as_tensorto_rgb
to_ndarraypermuter:   errorEOFError)rC   framerI   s      r   __next__zVideoReader.__next__   si    <6!!GLLNNE{{}}!!##!$///\^++JE33
$TWEI788d...!OELLNN,E,E,G,GHHPPQRTUWXYYEE 000!OE,<,<,>,>??GG1MMEE E8$ $ $ $##$ ;;==Ac***s   2CE   Ec                     | S )Nr   )rC   s    r   __iter__zVideoReader.__iter__   s    r   Ftime_skeyframes_onlyc                    | j         dv r| j                            ||           n|dk     rd} | j        j        j        di | j        d         }t          t          ||j	        z                      }|st          j        d           | j                            |dd|            | j        j        di | j        | _        | S )a  Seek within current stream.

        Args:
            time_s (float): seek time in seconds
            keyframes_only (bool): allow to seek only to keyframes

        .. note::
            Current implementation is the so-called precise seek. This
            means following seek, call to :mod:`next()` will return the
            frame with the exact timestamp if it exists or
            the first frame with timestamp larger than ``time_s``.
        )r   r   r   z1Accurate seek is not implemented for pyav backendTF)backward	any_framer   r   )r#   r7   seekr<   streamsgetr@   r?   roundrO   r+   warnrA   )rC   rZ   r[   temp_stroffsets        r   r_   zVideoReader.seek   s     <333GLL0000 zz1t~-1EED4DEEaHHv(::;;<<F! SQRRRNxXXX+dn+??d.>??DGr   c                    | j         dk    ri }| j        j        D ]}|j        |vr|j        dk    rd}nd}|g dg i||j        <   t	          |dd          p|j        }||j                 d                             t          |j        |j	        z                       ||j                 |                             t          |                     |S | j
                                        S )zReturns video metadata

        Returns:
            (dict): dictionary containing duration and frame rate for every stream
        r   r   fps	frameratedurationaverage_rateN)r#   r<   r`   r2   getattrsample_rateappendrN   ri   rO   r7   get_metadata)rC   metadatar   rate_nrates        r   rn   zVideoReader.get_metadata   s     <6!!H.0 B B;h..{g--!&!,-3RR,HHV[)v~t<<R@R%j188vQWQa?a9b9bccc%f-44U4[[AAAAOw##%%%r   c                    | j         dk    rt          j        d           | j         dk    r|                    d          d         }t	          |                    d                    dk    rdn't          |                    d          d                   }||i| _         | j        j        di | j        | _	        dS | j	        
                    |          S )	a  Set current stream.
        Explicitly define the stream we are operating on.

        Args:
            stream (string): descriptor of the required stream. Defaults to ``"video:0"``
                Currently available stream types include ``['video', 'audio']``.
                Each descriptor consists of two parts: stream type (e.g. 'video') and
                a unique stream id (which are determined by video encoding).
                In this way, if the video container contains multiple
                streams of the same type, users can access the one they want.
                If only stream type is passed, the decoder auto-detects first stream
                of that type and returns it.

        Returns:
            (bool): True on success, False otherwise
        r   z*GPU decoding only works with video stream.r   r"   r   r   Tr   )r#   r+   rc   r=   r>   r?   r@   r<   rA   r7   set_current_stream)rC   r   rD   rE   s       r   rs   zVideoReader.set_current_stream  s    " <6!!MFGGG<6!! ,,s++A.K c!2!233q88c&,,sBSBSTUBV>W>WI +Y7D+dn+??d.>??DG4w))&111r   )r   r   )F)__name__
__module____qualname____doc__r%   r?   rF   r   r   rW   r   rY   rN   boolr_   rn   rs   r   r   r   r   r   /   s1       H HZ 	7Q 7Q7Q 7Q 	7Q
 
7Q 7Q 7Q 7Qr#+$sCx. #+ #+ #+ #+J(4S>2     5 $ =    6&d38n & & & &.2 2 2 2 2 2 2 2r   r   )r)   r+   typingr   r   r   r.   utilsr   
_video_optr	   rx   r   r:   logging	set_levelERRORhasattrr   rV   
VideoFrameImportErrorr   r   r   r   <module>r      ss   				  & & & & & & & & & &  ' ' ' ' ' ' . . . . . . D     
D    IIIJ)***728>,k:: 	
[
 
    		
 
BBBw2 w2 w2 w2 w2 w2 w2 w2 w2 w2s   AB BB