a
    âñhØª  ã                   @   sä  d dl Z d dlmZmZ d dlmZ d dlZd dlmZ d dlm	Z
 d dlmZ g d¢ZG dd	„ d	ejjƒZG d
d„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG dd„ dejjƒZG d d!„ d!ejjƒZG d"d#„ d#ejjƒZG d$d%„ d%ejjƒZG d&d'„ d'eƒZG d(d)„ d)eƒZ G d*d+„ d+ejjƒZ!G d,d-„ d-ejjƒZ"G d.d/„ d/ejjƒZ#dS )0é    N)ÚCallableÚOptional)Úwarn)ÚTensor)Ú
functional)Úkaldi)ÚSpectrogramÚ
GriffinLimÚAmplitudeToDBÚMelScaleÚInverseMelScaleÚMelSpectrogramÚMFCCÚMuLawEncodingÚMuLawDecodingÚResampleÚComplexNormÚTimeStretchÚFadeÚFrequencyMaskingÚTimeMaskingÚSlidingWindowCmnÚVadc                       sz   e Zd ZdZg d¢Zddddejdddfeee ee ee	de
f ee eee dd	œ	‡ fd
d„Ze
e
dœdd„Z‡  ZS )r   a  Create a spectrogram from a audio signal.

    Args:
        n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
        win_length (int or None, optional): Window size. (Default: ``n_fft``)
        hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
        pad (int, optional): Two sided padding of signal. (Default: ``0``)
        window_fn (Callable[..., Tensor], optional): A function to create a window tensor
            that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
        power (float or None, optional): Exponent for the magnitude spectrogram,
            (must be > 0) e.g., 1 for energy, 2 for power, etc.
            If None, then the complex spectrum is returned instead. (Default: ``2``)
        normalized (bool, optional): Whether to normalize by magnitude after stft. (Default: ``False``)
        wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
    )Ún_fftÚ
win_lengthÚ
hop_lengthÚpadÚpowerÚ
normalizedé�  Nr   ç       @F.)	r   r   r   r   Ú	window_fnr   r   ÚwkwargsÚreturnc	           
         s„   t t| ƒ ¡  || _|d ur |n|| _|d ur2|n| jd | _|d u rP|| jƒn|| jfi |¤Ž}	|  d|	¡ || _|| _|| _	d S )Né   Úwindow)
Úsuperr   Ú__init__r   r   r   Úregister_bufferr   r   r   )
Úselfr   r   r   r   r!   r   r   r"   r%   ©Ú	__class__© úU/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchaudio/transforms.pyr'   4   s    	$zSpectrogram.__init__©Úwaveformr#   c              
   C   s&   t  || j| j| j| j| j| j| j¡S )a<  
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: Dimension (..., freq, time), where freq is
            ``n_fft // 2 + 1`` where ``n_fft`` is the number of
            Fourier bins, and time is the number of window hops (n_frame).
        )	ÚFÚspectrogramr   r%   r   r   r   r   r   ©r)   r/   r,   r,   r-   ÚforwardI   s    
ÿzSpectrogram.forward©Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__constants__ÚtorchÚhann_windowÚintr   r   r   ÚfloatÚboolÚdictr'   r3   Ú__classcell__r,   r,   r*   r-   r   "   s*   ø
ør   c                       s†   e Zd ZdZg d¢Zddddejdddddd	feeee ee e	d
e
f eeee eee eddœ‡ fdd„Ze
e
dœdd„Z‡  ZS )r	   u	  Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.

    Implementation ported from ``librosa`` [1]_, [2]_, [3]_.

    Args:
        n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
        n_iter (int, optional): Number of iteration for phase recovery process. (Default: ``32``)
        win_length (int or None, optional): Window size. (Default: ``n_fft``)
        hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
        window_fn (Callable[..., Tensor], optional): A function to create a window tensor
            that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
        power (float, optional): Exponent for the magnitude spectrogram,
            (must be > 0) e.g., 1 for energy, 2 for power, etc. (Default: ``2``)
        normalized (bool, optional): Whether to normalize by magnitude after stft. (Default: ``False``)
        wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
        momentum (float, optional): The momentum parameter for fast Griffin-Lim.
            Setting this to 0 recovers the original Griffin-Lim method.
            Values near 1 can lead to faster convergence, but above 1 may not converge. (Default: ``0.99``)
        length (int, optional): Array length of the expected output. (Default: ``None``)
        rand_init (bool, optional): Initializes phase randomly if True and to zero otherwise. (Default: ``True``)

    References:
        .. [1]
           | McFee, Brian, Colin Raffel, Dawen Liang, Daniel PW Ellis, Matt McVicar, Eric Battenberg,
             and Oriol Nieto.
           | "librosa: Audio and music signal analysis in python."
           | In Proceedings of the 14th python in science conference, pp. 18-25. 2015.

        .. [2]
           | Perraudin, N., Balazs, P., & SÃ¸ndergaard, P. L.
           | "A fast Griffin-Lim algorithm,"
           | IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (pp. 1-4),
           | Oct. 2013.

        .. [3]
           | D. W. Griffin and J. S. Lim,
           | "Signal estimation from modified short-time Fourier transform,"
           | IEEE Trans. ASSP, vol.32, no.2, pp.236â€“243, Apr. 1984.
    )	r   Ún_iterr   r   r   r   ÚlengthÚmomentumÚ	rand_initr   é    Nr    Fg®Gáz®ï?T.)r   rA   r   r   r!   r   r   r"   rC   rB   rD   r#   c                    sÊ   t t| ƒ ¡  |	dk s$J d |	¡ƒ‚|	dks:J d |	¡ƒ‚|| _|| _|d urR|n|| _|d urd|n| jd | _|d u r‚|| jƒn|| jfi |¤Ž}|  d|¡ || _	|
| _
|| _|	d|	  | _|| _d S )Né   zmomentum={} > 1 can be unstabler   zmomentum={} < 0r$   r%   )r&   r	   r'   Úformatr   rA   r   r   r(   r   rB   r   rC   rD   )r)   r   rA   r   r   r!   r   r   r"   rC   rB   rD   r%   r*   r,   r-   r'   ‚   s    $zGriffinLim.__init__©Úspecgramr#   c                 C   s2   t  || j| j| j| j| j| j| j| j	| j
| j¡S )a/  
        Args:
            specgram (Tensor):
                A magnitude-only STFT spectrogram of dimension (..., freq, frames)
                where freq is ``n_fft // 2 + 1``.

        Returns:
            Tensor: waveform of (..., time), where time equals the ``length`` parameter if given.
        )r0   Z
griffinlimr%   r   r   r   r   r   rA   rC   rB   rD   ©r)   rI   r,   r,   r-   r3   Ÿ   s    
ÿzGriffinLim.forwardr4   r,   r,   r*   r-   r	   W   s6   'õ
õr	   c                       sH   e Zd ZdZg d¢Zdeee ddœ‡ fdd„Ze	e	dœd	d
„Z
‡  ZS )r
   a(  Turn a tensor from the power/amplitude scale to the decibel scale.

    This output depends on the maximum value in the input tensor, and so
    may return different values for an audio clip split into snippets vs. a
    a full clip.

    Args:
        stype (str, optional): scale of input tensor ('power' or 'magnitude'). The
            power being the elementwise square of the magnitude. (Default: ``'power'``)
        top_db (float, optional): minimum negative cut-off in decibels.  A reasonable number
            is 80. (Default: ``None``)
    )Ú
multiplierÚaminÚ	ref_valueÚdb_multiplierr   N)ÚstypeÚtop_dbr#   c                    sj   t t| ƒ ¡  || _|d ur,|dk r,tdƒ‚|| _|dkr>dnd| _d| _d| _t	 
t| j| jƒ¡| _d S )Nr   ztop_db must be positive valuer   g      $@ç      4@g»½×Ùß|Û=ç      ð?)r&   r
   r'   rO   Ú
ValueErrorrP   rK   rL   rM   ÚmathÚlog10ÚmaxrN   )r)   rO   rP   r*   r,   r-   r'   ¼   s    zAmplitudeToDB.__init__©Úxr#   c                 C   s   t  || j| j| j| j¡S )a*  Numerically stable implementation from Librosa.

        https://librosa.org/doc/latest/generated/librosa.amplitude_to_db.html

        Args:
            x (Tensor): Input tensor before being converted to decibel scale.

        Returns:
            Tensor: Output tensor in decibel scale.
        )r0   Úamplitude_to_DBrK   rL   rN   rP   ©r)   rX   r,   r,   r-   r3   Ç   s    zAmplitudeToDB.forward)r   N)r5   r6   r7   r8   r9   Ústrr   r=   r'   r   r3   r@   r,   r,   r*   r-   r
   ­   s   r
   c                       sR   e Zd ZdZg d¢Zdeeeee ee ddœ‡ fdd	„Ze	e	d
œdd„Z
‡  ZS )r   aÏ  Turn a normal STFT into a mel frequency STFT, using a conversion
    matrix.  This uses triangular filter banks.

    User can control which device the filter bank (`fb`) is (e.g. fb.to(spec_f.device)).

    Args:
        n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
        sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
        f_min (float, optional): Minimum frequency. (Default: ``0.``)
        f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``)
        n_stft (int, optional): Number of bins in STFT. Calculated from first input
            if None is given.  See ``n_fft`` in :class:`Spectrogram`. (Default: ``None``)
    )Ún_melsÚsample_rateÚf_minÚf_maxé€   é€>  ç        N)r\   r]   r^   r_   Ún_stftr#   c                    s’   t t| ƒ ¡  || _|| _|d ur&|n
t|d ƒ| _|| _|| jksVJ d || j¡ƒ‚|d u rht	 
d¡nt || j| j| j| j¡}|  d|¡ d S )Nr$   úRequire f_min: {} < f_max: {}r   Úfb)r&   r   r'   r\   r]   r=   r_   r^   rG   r:   Úemptyr0   Úcreate_fb_matrixr(   )r)   r\   r]   r^   r_   rc   re   r*   r,   r-   r'   å   s    ÿzMelScale.__init__rH   c                 C   sª   |  ¡ }| d|d |d ¡}| j ¡ dkrht |  d¡| j| j| j| j	¡}| j 
|  ¡ ¡ | j |¡ t | dd¡| j¡ dd¡}| |dd… |jdd…  ¡}|S )zÊ
        Args:
            specgram (Tensor): A spectrogram STFT of dimension (..., freq, time).

        Returns:
            Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time).
        éÿÿÿÿéþÿÿÿr   rF   r$   N)ÚsizeÚreshapere   Znumelr0   rg   r^   r_   r\   r]   Zresize_Zcopy_r:   ÚmatmulÚ	transposeÚshape)r)   rI   rn   Ztmp_fbÚmel_specgramr,   r,   r-   r3   ÷   s    
  zMelScale.forward)r`   ra   rb   NN)r5   r6   r7   r8   r9   r<   r=   r   r'   r   r3   r@   r,   r,   r*   r-   r   Õ   s        ûûr   c                       sZ   e Zd ZdZg d¢Zdeeeeee eeeee dd
œ
‡ fdd„Z	e
e
dœdd„Z‡  ZS )r   aS  Solve for a normal STFT from a mel frequency STFT, using a conversion
    matrix.  This uses triangular filter banks.

    It minimizes the euclidian norm between the input mel-spectrogram and the product between
    the estimated spectrogram and the filter banks using SGD.

    Args:
        n_stft (int): Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`.
        n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
        sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
        f_min (float, optional): Minimum frequency. (Default: ``0.``)
        f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``)
        max_iter (int, optional): Maximum number of optimization iterations. (Default: ``100000``)
        tolerance_loss (float, optional): Value of loss to stop optimization at. (Default: ``1e-5``)
        tolerance_change (float, optional): Difference in losses to stop optimization at. (Default: ``1e-8``)
        sgdargs (dict or None, optional): Arguments for the SGD optimizer. (Default: ``None``)
    )	rc   r\   r]   r^   r_   Úmax_iterÚtolerance_lossÚtolerance_changeÚsgdargsr`   ra   rb   Né † çñhãˆµøä>ç:Œ0âŽyE>)
rc   r\   r]   r^   r_   rp   rq   rr   rs   r#   c
                    sš   t t| ƒ ¡  || _|| _|p(t|d ƒ| _|| _|| _|| _	|| _
|	pPdddœ| _|| jkspJ d || j¡ƒ‚t || j| j| j| j¡}
|  d|
¡ d S )Nr$   çš™™™™™¹?gÍÌÌÌÌÌì?)ÚlrrC   rd   re   )r&   r   r'   r\   r]   r=   r_   r^   rp   rq   rr   rs   rG   r0   rg   r(   )r)   rc   r\   r]   r^   r_   rp   rq   rr   rs   re   r*   r,   r-   r'   )  s    
zInverseMelScale.__init__)Úmelspecr#   c                 C   sf  |  ¡ }| d|d |d ¡}|d |d  }}| j  ¡ \}}| dd¡}| j|ksXJ ‚tj|  ¡ d ||d|j|jd�}tj	j
|gfi | j¤Ž}tdƒ}	t| jƒD ]„}| ¡  || | j¡ }
|
 d¡jdd� ¡ }| ¡  | ¡  |jjdd	�|_| ¡ }|| jk �st|	| ƒ| jk �r$ �q*|}	q¤| d
¡ |jdd	� dd¡}| |dd… ||f ¡}|S )zÏ
        Args:
            melspec (Tensor): A Mel frequency spectrogram of dimension (..., ``n_mels``, time)

        Returns:
            Tensor: Linear scale spectrogram of size (..., freq, time)
        rh   ri   r   T)Zrequires_gradÚdtypeÚdeviceÚinfr$   )Úaxis)ÚminFN)rj   Úviewre   rm   r\   r:   Zrandrz   r{   ÚoptimZSGDrs   r=   Úrangerp   Z	zero_gradrl   ÚpowÚsumÚmeanZbackwardÚstepÚdataÚclampÚitemrq   Úabsrr   Zrequires_grad_)r)   ry   rn   r\   ÚtimeÚfreqÚ_rI   r€   ZlossÚdiffZnew_lossr,   r,   r-   r3   B  s4    	ÿ 
zInverseMelScale.forward)r`   ra   rb   Nrt   ru   rv   N)r5   r6   r7   r8   r9   r<   r=   r   r?   r'   r   r3   r@   r,   r,   r*   r-   r     s,           ÷÷r   c                       sŽ   e Zd ZdZg d¢Zddddddddejd	d
dfeeee ee e	ee	 eee
def ee	 eee ddœ‡ fdd„Zeedœdd„Z‡  ZS )r   aü  Create MelSpectrogram for a raw audio signal. This is a composition of Spectrogram
    and MelScale.

    Sources
        * https://gist.github.com/kastnerkyle/179d6e9a88202ab0a2fe
        * https://timsainb.github.io/spectrograms-mfccs-and-inversion-in-python.html
        * http://haythamfayek.com/2016/04/21/speech-processing-for-machine-learning.html

    Args:
        sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
        win_length (int or None, optional): Window size. (Default: ``n_fft``)
        hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
        n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
        f_min (float, optional): Minimum frequency. (Default: ``0.``)
        f_max (float or None, optional): Maximum frequency. (Default: ``None``)
        pad (int, optional): Two sided padding of signal. (Default: ``0``)
        n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
        window_fn (Callable[..., Tensor], optional): A function to create a window tensor
            that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
        wkwargs (Dict[..., ...] or None, optional): Arguments for window function. (Default: ``None``)

    Example
        >>> waveform, sample_rate = torchaudio.load('test.wav', normalization=True)
        >>> mel_specgram = transforms.MelSpectrogram(sample_rate)(waveform)  # (channel, n_mels, time)
    )r]   r   r   r   r   r\   r^   ra   r   Nrb   r   r`   r    F.)r]   r   r   r   r^   r_   r   r\   r!   r   r   r"   r#   c              
      s¶   t t| ƒ ¡  || _|| _|d ur&|n|| _|d ur8|n| jd | _|| _|
| _|| _	|| _
|| _|| _t| j| j| j| j|	| j| j	|d�| _t| j
| j| j| j| jd d ƒ| _d S )Nr$   )r   r   r   r   r!   r   r   r"   rF   )r&   r   r'   r]   r   r   r   r   r   r   r\   r_   r^   r   r1   r   Ú	mel_scale)r)   r]   r   r   r   r^   r_   r   r\   r!   r   r   r"   r*   r,   r-   r'   Œ  s"    

ýzMelSpectrogram.__init__r.   c                 C   s   |   |¡}|  |¡}|S )zÁ
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time).
        )r1   rŽ   )r)   r/   rI   ro   r,   r,   r-   r3   ª  s    

zMelSpectrogram.forward)r5   r6   r7   r8   r9   r:   r;   r<   r   r=   r   r   r>   r?   r'   r3   r@   r,   r,   r*   r-   r   p  s:   ô
ôr   c                	       sP   e Zd ZdZg d¢Zdeeeeeee	 dd	œ‡ fd
d„Z
eedœdd„Z‡  ZS )r   aÛ  Create the Mel-frequency cepstrum coefficients from an audio signal.

    By default, this calculates the MFCC on the DB-scaled Mel spectrogram.
    This is not the textbook implementation, but is implemented here to
    give consistency with librosa.

    This output depends on the maximum value in the input spectrogram, and so
    may return different values for an audio clip split into snippets vs. a
    a full clip.

    Args:
        sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
        n_mfcc (int, optional): Number of mfc coefficients to retain. (Default: ``40``)
        dct_type (int, optional): type of DCT (discrete cosine transform) to use. (Default: ``2``)
        norm (str, optional): norm to use. (Default: ``'ortho'``)
        log_mels (bool, optional): whether to use log-mel spectrograms instead of db-scaled. (Default: ``False``)
        melkwargs (dict or None, optional): arguments for MelSpectrogram. (Default: ``None``)
    )r]   Ún_mfccÚdct_typerP   Úlog_melsra   é(   r$   ÚorthoFN)r]   r�   r�   Únormr‘   Ú	melkwargsr#   c           	         sÆ   t t| ƒ ¡  dg}||vr*td |¡ƒ‚|| _|| _|| _|| _d| _	t
d| j	ƒ| _|d urvtf d| ji|¤Ž| _nt| jd�| _| j| jjkrštdƒ‚t | j| jj| j¡}|  d|¡ || _d S )	Nr$   zDCT type not supported: {}g      T@r   r]   )r]   z4Cannot select more MFCC coefficients than # mel binsÚdct_mat)r&   r   r'   rS   rG   r]   r�   r�   r”   rP   r
   rY   r   r\   r0   Z
create_dctr(   r‘   )	r)   r]   r�   r�   r”   r‘   r•   Zsupported_dct_typesr–   r*   r,   r-   r'   Ì  s$    zMFCC.__init__r.   c                 C   sˆ   |  ¡ }| d|d ¡}|  |¡}| jr<d}t || ¡}n
|  |¡}t | dd¡| j	¡ dd¡}| |dd… |j
dd…  ¡}|S )z·
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: specgram_mel_db of size (..., ``n_mfcc``, time).
        rh   g�íµ ÷Æ°>rF   r$   Nri   )rj   rk   r   r‘   r:   ÚlogrY   rl   rm   r–   rn   )r)   r/   rn   ro   Z
log_offsetZmfccr,   r,   r-   r3   é  s    


 zMFCC.forward)ra   r’   r$   r“   FN)r5   r6   r7   r8   r9   r<   r[   r>   r   r?   r'   r   r3   r@   r,   r,   r*   r-   r   ·  s"         úúr   c                       s@   e Zd ZdZdgZdeddœ‡ fdd„Zeedœd	d
„Z‡  Z	S )r   aŽ  Encode signal based on mu-law companding.  For more info see the
    `Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_

    This algorithm assumes the signal has been scaled to between -1 and 1 and
    returns a signal encoded with values from 0 to quantization_channels - 1

    Args:
        quantization_channels (int, optional): Number of channels. (Default: ``256``)
    Úquantization_channelsé   N©r˜   r#   c                    s   t t| ƒ ¡  || _d S ©N)r&   r   r'   r˜   ©r)   r˜   r*   r,   r-   r'     s    zMuLawEncoding.__init__rW   c                 C   s   t  || j¡S )z‡
        Args:
            x (Tensor): A signal to be encoded.

        Returns:
            x_mu (Tensor): An encoded signal.
        )r0   Zmu_law_encodingr˜   rZ   r,   r,   r-   r3     s    zMuLawEncoding.forward)r™   ©
r5   r6   r7   r8   r9   r<   r'   r   r3   r@   r,   r,   r*   r-   r     s   	r   c                       s@   e Zd ZdZdgZdeddœ‡ fdd„Zeedœd	d
„Z‡  Z	S )r   ag  Decode mu-law encoded signal.  For more info see the
    `Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_

    This expects an input with values between 0 and quantization_channels - 1
    and returns a signal scaled between -1 and 1.

    Args:
        quantization_channels (int, optional): Number of channels. (Default: ``256``)
    r˜   r™   Nrš   c                    s   t t| ƒ ¡  || _d S r›   )r&   r   r'   r˜   rœ   r*   r,   r-   r'   -  s    zMuLawDecoding.__init__)Úx_mur#   c                 C   s   t  || j¡S )zŸ
        Args:
            x_mu (Tensor): A mu-law encoded signal which needs to be decoded.

        Returns:
            Tensor: The signal decoded.
        )r0   Zmu_law_decodingr˜   )r)   rž   r,   r,   r-   r3   1  s    zMuLawDecoding.forward)r™   r�   r,   r,   r*   r-   r   !  s   	r   c                       s>   e Zd ZdZdeeeddœ‡ fdd„Zeedœd	d
„Z‡  Z	S )r   ax  Resample a signal from one frequency to another. A resampling method can be given.

    Args:
        orig_freq (float, optional): The original frequency of the signal. (Default: ``16000``)
        new_freq (float, optional): The desired frequency. (Default: ``16000``)
        resampling_method (str, optional): The resampling method. (Default: ``'sinc_interpolation'``)
    ra   Úsinc_interpolationN)Ú	orig_freqÚnew_freqÚresampling_methodr#   c                    s$   t t| ƒ ¡  || _|| _|| _d S r›   )r&   r   r'   r    r¡   r¢   )r)   r    r¡   r¢   r*   r,   r-   r'   E  s    zResample.__init__r.   c                 C   sl   | j dkrX| ¡ }| d|d ¡}t || j| j¡}| |dd… |jdd…  ¡}|S td 	| j ¡ƒ‚dS )z®
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: Output signal of dimension (..., time).
        rŸ   rh   NzInvalid resampling method: {})
r¢   rj   r   r   Zresample_waveformr    r¡   rn   rS   rG   )r)   r/   rn   r,   r,   r-   r3   N  s    
 zResample.forward)ra   ra   rŸ   )
r5   r6   r7   r8   r<   r[   r'   r   r3   r@   r,   r,   r*   r-   r   <  s   	   ýý	r   c                       s@   e Zd ZdZdgZdeddœ‡ fdd„Zeedœd	d
„Z‡  Z	S )r   zƒCompute the norm of complex tensor input.

    Args:
        power (float, optional): Power of the norm. (Default: to ``1.0``)
    r   rR   N)r   r#   c                    s   t t| ƒ ¡  || _d S r›   )r&   r   r'   r   )r)   r   r*   r,   r-   r'   n  s    zComplexNorm.__init__)Úcomplex_tensorr#   c                 C   s   t  || j¡S )z´
        Args:
            complex_tensor (Tensor): Tensor shape of `(..., complex=2)`.

        Returns:
            Tensor: norm of the input tensor, shape of `(..., )`.
        )r0   Zcomplex_normr   )r)   r£   r,   r,   r-   r3   r  s    zComplexNorm.forward)rR   )
r5   r6   r7   r8   r9   r=   r'   r   r3   r@   r,   r,   r*   r-   r   f  s   r   c                       sB   e Zd ZdZdgZdeeddœ‡ fdd„Zeed	œd
d„Z	‡  Z
S )ÚComputeDeltasa8  Compute delta coefficients of a tensor, usually a spectrogram.

    See `torchaudio.functional.compute_deltas` for more details.

    Args:
        win_length (int): The window length used for computing delta. (Default: ``5``)
        mode (str): Mode parameter passed to padding. (Default: ``'replicate'``)
    r   é   Ú	replicateN)r   Úmoder#   c                    s   t t| ƒ ¡  || _|| _d S r›   )r&   r¤   r'   r   r§   )r)   r   r§   r*   r,   r-   r'   ˆ  s    zComputeDeltas.__init__rH   c                 C   s   t j|| j| jd�S )z½
        Args:
            specgram (Tensor): Tensor of audio of dimension (..., freq, time).

        Returns:
            Tensor: Tensor of deltas of dimension (..., freq, time).
        )r   r§   )r0   Zcompute_deltasr   r§   rJ   r,   r,   r-   r3   �  s    zComputeDeltas.forward)r¥   r¦   )r5   r6   r7   r8   r9   r<   r[   r'   r   r3   r@   r,   r,   r*   r-   r¤   }  s   r¤   c                       sT   e Zd ZdZdgZdee eee ddœ‡ fdd„Zde	ee e	dœd	d
„Z
‡  ZS )r   aÂ  Stretch stft in time without modifying pitch for a given rate.

    Args:
        hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
        n_freq (int, optional): number of filter banks from stft. (Default: ``201``)
        fixed_rate (float or None, optional): rate to speed up or slow down by.
            If None is provided, rate must be passed to the forward method. (Default: ``None``)
    Ú
fixed_rateNéÉ   )r   Ún_freqr¨   r#   c                    sX   t t| ƒ ¡  || _|d d }|d ur,|n|d }|  dt dtj| |¡d ¡ d S )NrF   r$   Úphase_advancer   ).N)	r&   r   r'   r¨   r(   r:   ÚlinspacerT   Úpi)r)   r   rª   r¨   r   r*   r,   r-   r'   £  s
    zTimeStretch.__init__)Úcomplex_specgramsÚoverriding_rater#   c                 C   sV   |  d¡dksJ dƒ‚|du r6| j}|du r:tdƒ‚n|}|dkrF|S t ||| j¡S )a–  
        Args:
            complex_specgrams (Tensor): complex spectrogram (..., freq, time, complex=2).
            overriding_rate (float or None, optional): speed up to apply to this batch.
                If no rate is passed, use ``self.fixed_rate``. (Default: ``None``)

        Returns:
            Tensor: Stretched complex spectrogram of dimension (..., freq, ceil(time/rate), complex=2).
        rh   r$   zDcomplex_specgrams should be a complex tensor, shape (..., complex=2)NzLIf no fixed_rate is specified, must pass a valid rate to the forward method.rR   )rj   r¨   rS   r0   Zphase_vocoderr«   )r)   r®   r¯   Zrater,   r,   r-   r3   ¯  s    

zTimeStretch.forward)Nr©   N)N)r5   r6   r7   r8   r9   r   r<   r=   r'   r   r3   r@   r,   r,   r*   r-   r   ˜  s      ýýr   c                       s^   e Zd ZdZdeeeddœ‡ fdd„Zeedœd	d
„Zeedœdd„Z	eedœdd„Z
‡  ZS )r   a™  Add a fade in and/or fade out to an waveform.

    Args:
        fade_in_len (int, optional): Length of fade-in (time frames). (Default: ``0``)
        fade_out_len (int, optional): Length of fade-out (time frames). (Default: ``0``)
        fade_shape (str, optional): Shape of fade. Must be one of: "quarter_sine",
            "half_sine", "linear", "logarithmic", "exponential". (Default: ``"linear"``)
    r   ÚlinearN)Úfade_in_lenÚfade_out_lenÚ
fade_shaper#   c                    s$   t t| ƒ ¡  || _|| _|| _d S r›   )r&   r   r'   r±   r²   r³   )r)   r±   r²   r³   r*   r,   r-   r'   Ò  s    zFade.__init__r.   c                 C   s6   |  ¡ d }|j}|  |¡ |¡|  |¡ |¡ | S )ú°
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: Tensor of audio of dimension (..., time).
        rh   )rj   r{   Ú_fade_inÚtoÚ	_fade_out)r)   r/   Úwaveform_lengthr{   r,   r,   r-   r3   Û  s    ÿÿzFade.forward)r¸   r#   c                 C   sÈ   t  dd| j¡}t  || j ¡}| jdkr.|}| jdkrLt  d|d ¡| }| jdkrht  d| ¡d }| jdkr†t  |tj	 d ¡}| jd	kr²t  |tj	 tj	d  ¡d d
 }t  
||f¡ dd¡S )Nr   rF   r°   Úexponentialr$   Úlogarithmicrw   Úquarter_sineÚ	half_sineç      à?)r:   r¬   r±   Úonesr³   r‚   rU   ÚsinrT   r­   ÚcatÚclamp_©r)   r¸   Zfader¾   r,   r,   r-   rµ   è  s    




"zFade._fade_inc                 C   sÚ   t  dd| j¡}t  || j ¡}| jdkr4| d }| jdkrTt  d| ¡d|  }| jdkrpt  d| ¡d }| jdkr˜t  |tj	 d tj	d  ¡}| jd	krÄt  |tj	 tj	d  ¡d d
 }t  
||f¡ dd¡S )Nr   rF   r°   r¹   r$   rº   gš™™™™™ñ?r»   r¼   r½   )r:   r¬   r²   r¾   r³   r‚   rU   r¿   rT   r­   rÀ   rÁ   rÂ   r,   r,   r-   r·   ý  s    





"zFade._fade_out)r   r   r°   )r5   r6   r7   r8   r<   r[   r'   r   r3   rµ   r·   r@   r,   r,   r*   r-   r   É  s   	   ýý	r   c                       sH   e Zd ZdZg d¢Zeeeddœ‡ fdd„Zdee	edœd	d
„Z
‡  ZS )Ú_AxisMaskingaM  Apply masking to a spectrogram.

    Args:
        mask_param (int): Maximum possible length of the mask.
        axis (int): What dimension the mask is applied on.
        iid_masks (bool): Applies iid masks to each of the examples in the batch dimension.
            This option is applicable only when the input tensor is 4D.
    )Ú
mask_paramr}   Ú	iid_masksN)rÄ   r}   rÅ   r#   c                    s$   t t| ƒ ¡  || _|| _|| _d S r›   )r&   rÃ   r'   rÄ   r}   rÅ   )r)   rÄ   r}   rÅ   r*   r,   r-   r'     s    z_AxisMasking.__init__rb   )rI   Ú
mask_valuer#   c                 C   sB   | j r*| ¡ dkr*t || j|| jd ¡S t || j|| j¡S dS )zþ
        Args:
            specgram (Tensor): Tensor of dimension (..., freq, time).
            mask_value (float): Value to assign to the masked columns.

        Returns:
            Tensor: Masked spectrogram of dimensions (..., freq, time).
        é   rF   N)rÅ   Zdimr0   Zmask_along_axis_iidrÄ   r}   Zmask_along_axis)r)   rI   rÆ   r,   r,   r-   r3   %  s    
z_AxisMasking.forward)rb   )r5   r6   r7   r8   r9   r<   r>   r'   r   r=   r3   r@   r,   r,   r*   r-   rÃ     s   rÃ   c                       s,   e Zd ZdZdeeddœ‡ fdd„Z‡  ZS )r   a   Apply masking to a spectrogram in the frequency domain.

    Args:
        freq_mask_param (int): maximum possible length of the mask.
            Indices uniformly sampled from [0, freq_mask_param).
        iid_masks (bool, optional): whether to apply different masks to each
            example/channel in the batch. (Default: ``False``)
            This option is applicable only when the input tensor is 4D.
    FN)Úfreq_mask_paramrÅ   r#   c                    s   t t| ƒ |d|¡ d S )NrF   )r&   r   r'   )r)   rÈ   rÅ   r*   r,   r-   r'   ?  s    zFrequencyMasking.__init__)F©r5   r6   r7   r8   r<   r>   r'   r@   r,   r,   r*   r-   r   5  s   	r   c                       s,   e Zd ZdZdeeddœ‡ fdd„Z‡  ZS )r   a›  Apply masking to a spectrogram in the time domain.

    Args:
        time_mask_param (int): maximum possible length of the mask.
            Indices uniformly sampled from [0, time_mask_param).
        iid_masks (bool, optional): whether to apply different masks to each
            example/channel in the batch. (Default: ``False``)
            This option is applicable only when the input tensor is 4D.
    FN)Útime_mask_paramrÅ   r#   c                    s   t t| ƒ |d|¡ d S )Nr$   )r&   r   r'   )r)   rÊ   rÅ   r*   r,   r-   r'   M  s    zTimeMasking.__init__)FrÉ   r,   r,   r*   r-   r   C  s   	r   c                       s:   e Zd ZdZd	eedœ‡ fdd„Zeedœdd„Z‡  Z	S )
ÚVolaÊ  Add a volume to an waveform.

    Args:
        gain (float): Interpreted according to the given gain_type:
            If ``gain_type`` = ``amplitude``, ``gain`` is a positive amplitude ratio.
            If ``gain_type`` = ``power``, ``gain`` is a power (voltage squared).
            If ``gain_type`` = ``db``, ``gain`` is in decibels.
        gain_type (str, optional): Type of gain. One of: ``amplitude``, ``power``, ``db`` (Default: ``amplitude``)
    Ú	amplitude)ÚgainÚ	gain_typec                    s6   t t| ƒ ¡  || _|| _|dv r2|dk r2tdƒ‚d S )N)rÌ   r   r   z9If gain_type = amplitude or power, gain must be positive.)r&   rË   r'   rÍ   rÎ   rS   )r)   rÍ   rÎ   r*   r,   r-   r'   \  s
    zVol.__init__r.   c                 C   s\   | j dkr|| j }| j dkr,t || j¡}| j dkrNt |dt | j¡ ¡}t |dd¡S )r´   rÌ   Údbr   é
   rh   rF   )rÎ   rÍ   r0   rT   rU   r:   r‡   r2   r,   r,   r-   r3   d  s    



zVol.forward)rÌ   )
r5   r6   r7   r8   r=   r[   r'   r   r3   r@   r,   r,   r*   r-   rË   Q  s   
rË   c                       s@   e Zd ZdZdeeeeddœ‡ fdd„Zeed	œd
d„Z‡  Z	S )r   aÕ  
    Apply sliding-window cepstral mean (and optionally variance) normalization per utterance.

    Args:
        cmn_window (int, optional): Window in frames for running average CMN computation (int, default = 600)
        min_cmn_window (int, optional):  Minimum CMN window used at start of decoding (adds latency only at start).
            Only applicable if center == false, ignored if center==true (int, default = 100)
        center (bool, optional): If true, use a window centered on the current frame
            (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false)
        norm_vars (bool, optional): If true, normalize variance to one. (bool, default = false)
    éX  éd   FN)Ú
cmn_windowÚmin_cmn_windowÚcenterÚ	norm_varsr#   c                    s&   t ƒ  ¡  || _|| _|| _|| _d S r›   )r&   r'   rÓ   rÔ   rÕ   rÖ   )r)   rÓ   rÔ   rÕ   rÖ   r*   r,   r-   r'   …  s
    
zSlidingWindowCmn.__init__r.   c                 C   s   t  || j| j| j| j¡}|S )r´   )r0   Zsliding_window_cmnrÓ   rÔ   rÕ   rÖ   )r)   r/   Zcmn_waveformr,   r,   r-   r3   �  s    ÿzSlidingWindowCmn.forward)rÑ   rÒ   FF)
r5   r6   r7   r8   r<   r>   r'   r   r3   r@   r,   r,   r*   r-   r   x  s       üür   c                       s^   e Zd ZdZdeeeeeeeeeeeee eeeeeddœ‡ fdd„Zeedœdd„Z	‡  Z
S )r   uÂ  Voice Activity Detector. Similar to SoX implementation.
    Attempts to trim silence and quiet background sounds from the ends of recordings of speech.
    The algorithm currently uses a simple cepstral power measurement to detect voice,
    so may be fooled by other things, especially music.

    The effect can trim only from the front of the audio,
    so in order to trim from the back, the reverse effect must also be used.

    Args:
        sample_rate (int): Sample rate of audio signal.
        trigger_level (float, optional): The measurement level used to trigger activity detection.
            This may need to be cahnged depending on the noise level, signal level,
            and other characteristics of the input audio. (Default: 7.0)
        trigger_time (float, optional): The time constant (in seconds)
            used to help ignore short bursts of sound. (Default: 0.25)
        search_time (float, optional): The amount of audio (in seconds)
            to search for quieter/shorter bursts of audio to include prior
            to the detected trigger point. (Default: 1.0)
        allowed_gap (float, optional): The allowed gap (in seconds) between
            quiteter/shorter bursts of audio to include prior
            to the detected trigger point. (Default: 0.25)
        pre_trigger_time (float, optional): The amount of audio (in seconds) to preserve
            before the trigger point and any found quieter/shorter bursts. (Default: 0.0)
        boot_time (float, optional) The algorithm (internally) uses adaptive noise
            estimation/reduction in order to detect the start of the wanted audio.
            This option sets the time for the initial noise estimate. (Default: 0.35)
        noise_up_time (float, optional) Time constant used by the adaptive noise estimator
            for when the noise level is increasing. (Default: 0.1)
        noise_down_time (float, optional) Time constant used by the adaptive noise estimator
            for when the noise level is decreasing. (Default: 0.01)
        noise_reduction_amount (float, optional) Amount of noise reduction to use in
            the detection algorithm (e.g. 0, 0.5, ...). (Default: 1.35)
        measure_freq (float, optional) Frequency of the algorithmâ€™s
            processing/measurements. (Default: 20.0)
        measure_duration: (float, optional) Measurement duration.
            (Default: Twice the measurement period; i.e. with overlap.)
        measure_smooth_time (float, optional) Time constant used to smooth
            spectral measurements. (Default: 0.4)
        hp_filter_freq (float, optional) "Brick-wall" frequency of high-pass filter applied
            at the input to the detector algorithm. (Default: 50.0)
        lp_filter_freq (float, optional) "Brick-wall" frequency of low-pass filter applied
            at the input to the detector algorithm. (Default: 6000.0)
        hp_lifter_freq (float, optional) "Brick-wall" frequency of high-pass lifter used
            in the detector algorithm. (Default: 150.0)
        lp_lifter_freq (float, optional) "Brick-wall" frequency of low-pass lifter used
            in the detector algorithm. (Default: 2000.0)

    References:
        http://sox.sourceforge.net/sox.html
    ç      @ç      Ð?rR   rb   çffffffÖ?rw   ç{®Gáz„?çš™™™™™õ?rQ   Nçš™™™™™Ù?ç      I@ç     p·@ç     Àb@ç     @Ÿ@)r]   Útrigger_levelÚtrigger_timeÚsearch_timeÚallowed_gapÚpre_trigger_timeÚ	boot_timeÚnoise_up_timeÚnoise_down_timeÚnoise_reduction_amountÚmeasure_freqÚmeasure_durationÚmeasure_smooth_timeÚhp_filter_freqÚlp_filter_freqÚhp_lifter_freqÚlp_lifter_freqr#   c                    st   t ƒ  ¡  || _|| _|| _|| _|| _|| _|| _|| _	|| _
|
| _|| _|| _|| _|| _|| _|| _|| _d S r›   )r&   r'   r]   rá   râ   rã   rä   rå   ræ   rç   rè   ré   rê   rë   rì   rí   rî   rï   rð   )r)   r]   rá   râ   rã   rä   rå   ræ   rç   rè   ré   rê   rë   rì   rí   rî   rï   rð   r*   r,   r-   r'   Ñ  s$    
zVad.__init__r.   c                 C   sP   t j|| j| j| j| j| j| j| j| j	| j	| j
| j| j| j| j| j| j| jd�S )za
        Args:
            waveform (Tensor): Tensor of audio of dimension `(..., time)`
        )r/   r]   rá   râ   rã   rä   rå   ræ   rç   rè   ré   rê   rë   rì   rí   rî   rï   rð   )r0   Zvadr]   rá   râ   rã   rä   rå   ræ   rç   ré   rê   rë   rì   rí   rî   rï   rð   r2   r,   r,   r-   r3   ÷  s(    îzVad.forward)r×   rØ   rR   rØ   rb   rÙ   rw   rÚ   rÛ   rQ   NrÜ   rÝ   rÞ   rß   rà   )r5   r6   r7   r8   r<   r=   r   r'   r   r3   r@   r,   r,   r*   r-   r   �  sJ   5                ïï&r   )$rT   Útypingr   r   Úwarningsr   r:   r   Z
torchaudior   r0   Ztorchaudio.compliancer   Ú__all__ÚnnÚModuler   r	   r
   r   r   r   r   r   r   r   r   r¤   r   r   rÃ   r   r   rË   r   r   r,   r,   r,   r-   Ú<module>   s6   5V(?\GO*1J"'%