a
    áñha4  ã                   @   s”   d dl Z d dlZd dlmZ d dlmZ d dlZd dlmZm	Z	m
Z
mZmZ ddlmZ ejfdd„Zdd	d
„ZG dd„ deƒZG dd„ deƒZdS )é    N©ÚFraction)ÚList)Ú_probe_video_from_fileÚ_read_video_from_fileÚ _read_video_timestamps_from_fileÚ
read_videoÚread_video_timestampsé   )Útqdmc                 C   s   t | dƒ| | }||ƒS )zèconvert pts between different time bases
    Args:
        pts: presentation timestamp, float
        timebase_from: original timebase. Fraction
        timebase_to: new timebase. Fraction
        round_func: rounding function.
    r
   r   )ZptsZtimebase_fromZtimebase_toZ
round_funcZnew_pts© r   ú`/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/datasets/video_utils.pyÚpts_convert   s    r   c                 C   st   |   ¡ dksJ ‚|  d¡}|  ¡ }|| || f}|||d  d  | d |f}|d dk rfd|f}t | ||¡S )a   
    similar to tensor.unfold, but with the dilation
    and specialized for 1d tensors

    Returns all consecutive windows of `size` elements, with
    `step` between windows. The distance between each element
    in a window is given by `dilation`.
    r
   r   )ZdimZstrideÚnumelÚtorchZ
as_strided)ZtensorÚsizeÚstepZdilationZo_strider   Z
new_strideZnew_sizer   r   r   Úunfold   s    	
 r   c                   @   s2   e Zd ZdZee dœdd„Zdd„ Zdd„ Zd	S )
Ú_VideoTimestampsDatasetzÙ
    Dataset used to parallelize the reading of the timestamps
    of a list of videos, given their paths in the filesystem.

    Used in VideoClips and defined at top level so it can be
    pickled when forking.
    ©Úvideo_pathsc                 C   s
   || _ d S ©Nr   )Úselfr   r   r   r   Ú__init__:   s    z _VideoTimestampsDataset.__init__c                 C   s
   t | jƒS r   ©Úlenr   ©r   r   r   r   Ú__len__=   s    z_VideoTimestampsDataset.__len__c                 C   s   t | j| ƒS r   )r	   r   )r   Úidxr   r   r   Ú__getitem__@   s    z#_VideoTimestampsDataset.__getitem__N)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ústrr   r   r   r   r   r   r   r   1   s   r   c                   @   s�   e Zd ZdZd"dd„Zdd	„ Zd
d„ Zdd„ Zedd„ ƒZ	dd„ Z
edd„ ƒZd#dd„Zdd„ Zdd„ Zdd„ Zdd„ Zedd„ ƒZd d!„ ZdS )$Ú
VideoClipsaÙ  
    Given a list of video files, computes all consecutive subvideos of size
    `clip_length_in_frames`, where the distance between each subvideo in the
    same video is defined by `frames_between_clips`.
    If `frame_rate` is specified, it will also resample all the videos to have
    the same frame rate, and the clips will refer to this frame rate.

    Creating this instance the first time is time-consuming, as it needs to
    decode all the videos in `video_paths`. It is recommended that you
    cache the results after instantiation of the class.

    Recreating the clips for different clip lengths is fast, and can be done
    with the `compute_clips` method.

    Arguments:
        video_paths (List[str]): paths to the video files
        clip_length_in_frames (int): size of a clip in number of frames
        frames_between_clips (int): step (in frames) between each clip
        frame_rate (int, optional): if specified, it will resample the video
            so that it has `frame_rate`, and then the clips will be defined
            on the resampled video
        num_workers (int): how many subprocesses to use for data loading.
            0 means that the data will be loaded in the main process. (default: 0)
    é   r
   Nr   c                 C   s^   || _ || _|| _|| _|	| _|
| _|| _|| _|d u rB|  ¡  n
|  	|¡ |  
|||¡ d S r   )r   Únum_workersÚ_video_widthÚ_video_heightÚ_video_min_dimensionÚ_video_max_dimensionÚ_audio_samplesÚ_audio_channelsÚ_compute_frame_ptsÚ_init_from_metadataÚcompute_clips)r   r   Zclip_length_in_framesZframes_between_clipsÚ
frame_rateÚ_precomputed_metadatar'   r(   r)   r*   r+   r,   r-   r   r   r   r   ^   s    

zVideoClips.__init__c                 C   s   |S r   r   )r   Úxr   r   r   Ú_collate_fn   s    zVideoClips._collate_fnc                    s´   g | _ g | _dd l‰ ˆ jjjt| jƒd| j| j	d�}t
t|ƒd��^}|D ]H}| d¡ tt|Ž ƒ\}}‡ fdd„|D ƒ}| j  |¡ | j |¡ qHW d   ƒ n1 s¦0    Y  d S )Nr   r&   )Z
batch_sizer'   Z
collate_fn)Útotalr
   c                    s   g | ]}ˆ   |¡‘qS r   )Ú	as_tensor)Ú.0Úc©r   r   r   Ú
<listcomp>•   ó    z1VideoClips._compute_frame_pts.<locals>.<listcomp>)Ú	video_ptsÚ	video_fpsZtorch.utils.dataÚutilsÚdataZ
DataLoaderr   r   r'   r4   r   r   ÚupdateÚlistÚzipÚextend)r   ÚdlZpbarÚbatchÚclipsÚfpsr   r9   r   r.   ‚   s     ü
zVideoClips._compute_frame_ptsc                 C   sV   |d | _ t| j ƒt|d ƒks$J ‚|d | _t| j ƒt|d ƒksHJ ‚|d | _d S )Nr   r<   r=   )r   r   r<   r=   )r   Úmetadatar   r   r   r/   ™   s
    

zVideoClips._init_from_metadatac                 C   s   | j | j| jdœ}|S )N©r   r<   r=   rI   )r   Ú	_metadatar   r   r   rH       s
    ýzVideoClips.metadatac                    sz   ‡ fdd„|D ƒ}‡ fdd„|D ƒ}‡ fdd„|D ƒ}|||dœ}t ˆ ƒ|ˆ jˆ jˆ j|ˆ jˆ jˆ jˆ jˆ jˆ j	ˆ j
d�S )Nc                    s   g | ]}ˆ j | ‘qS r   r   ©r7   Úir   r   r   r:   ª   r;   z%VideoClips.subset.<locals>.<listcomp>c                    s   g | ]}ˆ j | ‘qS r   )r<   rK   r   r   r   r:   «   r;   c                    s   g | ]}ˆ j | ‘qS r   )r=   rK   r   r   r   r:   ¬   r;   rI   )r2   r'   r(   r)   r*   r+   r,   r-   )ÚtypeÚ
num_framesr   r1   r'   r(   r)   r*   r+   r,   r-   )r   Úindicesr   r<   r=   rH   r   r   r   Úsubset©   s*    ýôzVideoClips.subsetc                 C   s†   |d u rd}|d u r|}t | ƒt|ƒ|  }t tt |¡ƒ||¡}| | } t| ||ƒ}t|t	ƒrr|gt |ƒ }nt|||ƒ}||fS )Nr
   )
r   Úfloatr%   Ú_resample_video_idxÚintÚmathÚfloorr   Ú
isinstanceÚslice)r<   rN   r   rG   r1   Ztotal_framesÚidxsrF   r   r   r   Úcompute_clips_for_videoÁ   s    ÿ
z"VideoClips.compute_clips_for_videoc           	      C   sŽ   || _ || _|| _g | _g | _t| j| jƒD ]6\}}|  |||||¡\}}| j 	|¡ | j 	|¡ q,t
 dd„ | jD ƒ¡}| d¡ ¡ | _dS )aR  
        Compute all consecutive sequences of clips from video_pts.
        Always returns clips of size `num_frames`, meaning that the
        last few frames in a video can potentially be dropped.

        Arguments:
            num_frames (int): number of frames for the clip
            step (int): distance between two clips
        c                 S   s   g | ]}t |ƒ‘qS r   )r   )r7   Úvr   r   r   r:   ê   r;   z,VideoClips.compute_clips.<locals>.<listcomp>r   N)rN   r   r1   rF   Úresampling_idxsrB   r<   r=   rY   Úappendr   r6   ZcumsumÚtolistÚcumulative_sizes)	r   rN   r   r1   r<   rG   rF   rX   Zclip_lengthsr   r   r   r0   Õ   s    

ÿzVideoClips.compute_clipsc                 C   s   |   ¡ S r   )Ú	num_clipsr   r   r   r   r   í   s    zVideoClips.__len__c                 C   s
   t | jƒS r   r   r   r   r   r   Ú
num_videosð   s    zVideoClips.num_videosc                 C   s
   | j d S )zJ
        Number of subclips that are available in the video list.
        éÿÿÿÿ)r^   r   r   r   r   r_   ó   s    zVideoClips.num_clipsc                 C   s6   t  | j|¡}|dkr|}n|| j|d   }||fS )zw
        Converts a flattened representation of the indices into a video_idx, clip_idx
        representation.
        r   r
   )ÚbisectÚbisect_rightr^   )r   r   Ú	video_idxÚclip_idxr   r   r   Úget_clip_locationù   s
    zVideoClips.get_clip_locationc                 C   sP   t |ƒ| }| ¡ r(t|ƒ}td d |ƒS tj| tjd�| }| ¡  tj	¡}|S )N)Zdtype)
rQ   Ú
is_integerrS   rW   r   ZarangeÚfloat32rU   ÚtoÚint64)rN   Zoriginal_fpsZnew_fpsr   rX   r   r   r   rR     s    zVideoClips._resample_video_idxc                 C   sD  ||   ¡ kr td ||   ¡ ¡ƒ‚|  |¡\}}| j| }| j| | }ddlm} |ƒ }|dkrº| jdkrrt	dƒ‚| j
dkr„t	dƒ‚| jdkr–t	dƒ‚| jdkr¨t	dƒ‚| jdkrºt	d	ƒ‚|dkrî|d  ¡ }|d
  ¡ }	t|||	ƒ\}
}}nàt|ƒ}|j}d}|d  ¡ }|d
  ¡ }d\}}tddƒ}t|jj|jjƒ}|j�r|t|jj|jjƒ}t|||tjƒ}t|||tjƒ}|j}t|| j| j
| j| j||f|| j| j||f|d�\}
}}d|i}|du�rÎ||d< | jdu�r| j | | }t!|t"j#ƒ�r||d  }|
| }
| j|d< t$|
ƒ| j%k�s8J d |
j&| j%¡ƒ‚|
|||fS )a<  
        Gets a subclip from a list of videos.

        Arguments:
            idx (int): index of the subclip. Must be between 0 and num_clips().

        Returns:
            video (Tensor)
            audio (Tensor)
            info (Dict)
            video_idx (int): index of the video in `video_paths`
        z*Index {} out of range ({} number of clips)r   )Úget_video_backendZpyavz.pyav backend doesn't support _video_width != 0z/pyav backend doesn't support _video_height != 0z6pyav backend doesn't support _video_min_dimension != 0z6pyav backend doesn't support _video_max_dimension != 0z0pyav backend doesn't support _audio_samples != 0ra   N)r   ra   r
   )
Zvideo_widthZvideo_heightZvideo_min_dimensionZvideo_max_dimensionZvideo_pts_rangeÚvideo_timebaseZaudio_samplesZaudio_channelsZaudio_pts_rangeÚaudio_timebaser=   Ú	audio_fpsz{} x {})'r_   Ú
IndexErrorÚformatrf   r   rF   Ztorchvisionrk   r(   Ú
ValueErrorr)   r*   r+   r,   Úitemr   r   r=   r   rl   Ú	numeratorÚdenominatorZ	has_audiorm   r   rT   rU   ÚceilZaudio_sample_rater   r-   r1   r[   rV   r   ZTensorr   rN   Úshape)r   r   rd   re   Z
video_pathZclip_ptsrk   ÚbackendZ	start_ptsZend_ptsÚvideoÚaudioÚinfor=   rn   Zvideo_start_ptsZvideo_end_ptsZaudio_start_ptsZaudio_end_ptsrm   rl   Zresampling_idxr   r   r   Úget_clip  sš    ÿÿ



ÿ
ÿ

ÿÿ
ÿ
ÿõ

ÿzVideoClips.get_clip)r&   r
   NNr   r   r   r   r   r   r   )N)r    r!   r"   r#   r   r4   r.   r/   ÚpropertyrH   rP   ÚstaticmethodrY   r0   r   r`   r_   rf   rR   r{   r   r   r   r   r%   D   s:              ó
!



r%   )r
   )rb   rT   Z	fractionsr   Útypingr   r   Ztorchvision.ior   r   r   r   r	   r>   r   rU   r   r   Úobjectr   r%   r   r   r   r   Ú<module>   s   
