o
    پi7                     @   s   d Z ddlmZ ddlZddlZddlZddlmZm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ejZG dd deZed dS )zAudio Reader.    )absolute_importN   )c_arrayc_str)	_init_api)DECORDContext)DECORDError)ndarray)cpugpu)
bridge_outc                   @   s   e Zd ZdZedddfddZdd Zd	d
 Zdd Zdd Z	e
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS ) AudioReadera4  Individual audio reader with convenient indexing function.

    Parameters
    ----------
    uri: str
        Path of file.
    ctx: decord.Context
        The context to decode the file, can be decord.cpu() or decord.gpu().
    sample_rate: int, default is -1
        Desired output sample rate of the audio, unchanged if `-1` is specified.
    mono: bool, default is True
        Desired output channel layout of the audio. 
        Setting `True` will return the audio as mono layout. 
        Setting `False` will return the audio channel layout intact.

    r   Tc                 C   s   d | _ t|ts
J |rdnd}t|dr/t| }dt|}t||j	|j
|d|| _ nt||j	|j
|d|| _ | j d u rHtd| d t| j | _| j | _t| j | _t| j | _t| j | _|| _d | _d S )Nr   r   readz{} bytes   zError reading z...)_handle
isinstancer   hasattr	bytearrayr   formatlen_CAPI_AudioReaderGetAudioReaderdevice_type	device_idRuntimeError_CAPI_AudioReaderGetNDArray_arrayasnumpy_CAPI_AudioReaderGetDuration	_duration(_CAPI_AudioReaderGetNumSamplesPerChannel_num_samples_per_channel_CAPI_AudioReaderGetNumChannels_num_channelssample_rate_num_padding)selfurictxr$   monois_monoba r,   G/home/ubuntu/.local/lib/python3.10/site-packages/decord/audio_reader.py__init__$   s*   


zAudioReader.__init__c                 C   s
   | j d S )zGet length of the audio. The length refer to the shape's first dimension. In this case,
        the length is the number of channels.
        Returns
        -------
        int
            The number of channels in the audio track.
        r   )shaper&   r,   r,   r-   __len__:   s   
zAudioReader.__len__c                 C   s   | j r
t| j  d S d S )N)r   _CAPI_AudioReaderFreer0   r,   r,   r-   __del__D   s   zAudioReader.__del__c                 C   s   | j dusJ t|tr| t|| j S |dk r || j7 }|| jks)|dk r2td|| jt	t
| jdd|f S )a  Get sample at `idx`. idx is the index of resampled audio, unit is sample.

        Parameters
        ----------
        idx : int or slice
            The sample index, can be negative which means it will index backwards,
            or slice of sample indices.

        Returns
        -------
        ndarray
            Samples of shape CxS,
            where C is the number of channels, S is the number of samples of the index or slice.
        Nr   zIndex: {} out of bound: {})r   r   slice	get_batchrangeindicesr!   
IndexErrorr   r   _ndarrayr   )r&   idxr,   r,   r-   __getitem__H   s   

zAudioReader.__getitem__c                 C   s<   | j dusJ | |}t|}tt| jdd|f S )a  Get entire batch of samples.

        Parameters
        ----------
        indices : list of integers
            A list of frame indices. If negative indices detected, the indices will be indexed from backward
        Returns
        -------
        ndarray
            Samples of shape CxS,
            where C is the number of channels, S is the number of samples of the slice.

        N)r   _validate_indiceslistr   r9   r:   r   r&   r7   r,   r,   r-   r5   `   s   
zAudioReader.get_batchc                 C   s   | j | jfS )zGet shape of the entire audio samples.

        Returns
        -------
        (int, int)
            The number of channels, and the number of samples in each channel.

        )r#   r!   r0   r,   r,   r-   r/   s   s   
zAudioReader.shapec                 C   s   | j S )zGet duration of the audio.

        Returns
        -------
        double
            Duration of the audio in secs.

        )r   r0   r,   r,   r-   duration   s   	zAudioReader.durationc                 C   s   | j du rt| j| _ | j S )zAGet number of samples needed to pad the audio to start at time 0.N)r%   %_CAPI_AudioReaderGetNumPaddingSamplesr   r0   r,   r,   r-   __get_num_padding   s   
zAudioReader.__get_num_paddingc                 C   sB   t j| jd|  dffddd| _|  j|  | j 7  _|  S )zPad the audio samples so that it starts at time 0.

        Returns
        -------
        int
            Number of samples padded

        )r   r   r   constant)constant_values)nppadr   _AudioReader__get_num_paddingr   r$   r0   r,   r,   r-   add_padding   s   "	zAudioReader.add_paddingc                 C   s   t | j dS )z.Log out the basic info about the audio stream.N)_CAPI_AudioReaderGetInfor   r0   r,   r,   r-   get_info   s   zAudioReader.get_infoc                 C   s   t || j S )z'Convert time in seconds to sample index)mathceilr$   )r&   	timestampr,   r,   r-   _time_to_sample   s   zAudioReader._time_to_samplec                    s    fdd|D S )z*Convert times in seconds to sample indicesc                    s   g | ]}  |qS r,   )rN   ).0rM   r0   r,   r-   
<listcomp>   s    z1AudioReader._times_to_samples.<locals>.<listcomp>r,   )r&   
timestampsr,   r0   r-   _times_to_samples   s   zAudioReader._times_to_samplesc                 C   s   | j dusJ tj|tjd}||dk   | j7  < |dk s.td||dk  | j || jk  sAtd||| jk |S )zTValidate int64 integers and convert negative integers to positive by backward searchN)dtyper   zInvalid negative indices: {}zOut of bound indices: {})r   rE   r:   int64r!   allr8   r   r?   r,   r,   r-   r=      s   zAudioReader._validate_indicesN)__name__
__module____qualname____doc__r
   r.   r1   r3   r<   r5   propertyr/   r@   rG   rH   rJ   rN   rR   r=   r,   r,   r,   r-   r      s     

r   zdecord.audio_reader)rY   
__future__r   ctypesnumpyrE   rK   	_ffi.baser   r   _ffi.functionr   _ffi.ndarrayr   baser    r	   r9   r
   r   bridger   c_void_pAudioReaderHandleobjectr   r,   r,   r,   r-   <module>   s      %