a
    âñhIC ã                   @   sô  d dl Z d dlmZmZ d dlZd dlZd dlmZ g d¢Zeeeeeeee	 e
edœ	dd„Zeeeeee	e
ee	ee e
edœd	d
„Zd²ee	e	e	ee	 edœdd„Zee	e	edœdd„Zd³ee	e	eeee edœdd„Zeeee edœdd„Zeeedœdd„Zeeedœdd„Zd´ee	edœdd „Zeed!œd"d#„Zdµee	eeef dœd$d%„Zee	eed&œd'd(„Zd¶eeee
ed*œd+d,„Zee	e	e	e	e	e	ed-œd.d/„Ze	e	d0œd1d2„Zd·eee	e	ed4œd5d6„Zd¸eee	e	ed4œd7d8„Zd¹eee	e	ed9œd:d;„Zdºeee	e	e
ed=œd>d?„Zd»eee	e	ed9œd@dA„Zd¼eee	e	e	edBœdCdD„Z d½eee	e	e
edEœdFdG„Z!d¾eee	e	e	edIœdJdK„Z"d¿eee	e	e	edIœdMdN„Z#eeedOœdPdQ„Z$eeedOœdRdS„Z%dÀee	edUœdVdW„Z&dÁee	ee	 edXœdYdZ„Z'dÂee	e	ed\œd]d^„Z(dÃeee	e	e	e	e	e
edcœ	ddde„Z)eeee	e	e	ej*edfœdgdh„Z+dÄeee	e	e	e	e	e	eeedoœdpdq„Z,eee	eedrœdsdt„Z-eee	eeduœdvdw„Z.dÅeeeedzœd{d|„Z/dÆee	ed}œd~d„Z0eeed€œd�d‚„Z1dÇeeed„œd…d†„Z2dÈeee
ed‡œdˆd‰„Z3eee	eedŠœd‹dŒ„Z4dÉeeef eeef e	eeef dŽœd�d�„Z5eeeed‘œd’d“„Z6eeed”œd•d–„Z7dÊeee	eeeed›œdœd�„Z8dËeeee
e
edŸœd d¡„Z9eeeeeeeeeee	e	e	e	eee	d¢œd£d¤„Z:dÌeee	e	e	e	e	e	e	e	e	e	ee	 e	e	e	e	e	ed¯œd°d±„Z;dS )Íé    N)ÚOptionalÚTuple)ÚTensor)!ÚspectrogramÚ
griffinlimÚamplitude_to_DBÚcreate_fb_matrixÚ
create_dctÚmu_law_encodingÚmu_law_decodingÚcomplex_normÚangleÚmagphaseÚphase_vocoderÚlfilterÚlowpass_biquadÚhighpass_biquadÚallpass_biquadÚbandpass_biquadÚbandreject_biquadÚequalizer_biquadÚband_biquadÚtreble_biquadÚbass_biquadÚdeemph_biquadÚriaa_biquadÚbiquadÚcontrastÚdcshiftÚ	overdriveÚphaserÚflangerÚmask_along_axisÚmask_along_axis_iidÚsliding_window_cmnÚvad)	ÚwaveformÚpadÚwindowÚn_fftÚ
hop_lengthÚ
win_lengthÚpowerÚ
normalizedÚreturnc           
      C   s¢   |dkrt jj | ||fd¡} |  ¡ }|  d|d ¡} t  | ||||dddd¡	}	|	 |dd… |	jdd…  ¡}	|rŠ|	| d	¡ 	¡  
¡  }	|duržt|	|d
�}	|	S )aº  Create a spectrogram or a batch of spectrograms from a raw audio signal.
    The spectrogram can be either magnitude-only or complex.

    Args:
        waveform (Tensor): Tensor of audio of dimension (..., time)
        pad (int): Two sided padding of signal
        window (Tensor): Window tensor that is applied/multiplied to each frame/window
        n_fft (int): Size of FFT
        hop_length (int): Length of hop between STFT windows
        win_length (int): Window size
        power (float or None): 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.
        normalized (bool): Whether to normalize by magnitude after stft

    Returns:
        Tensor: Dimension (..., freq, time), freq is
        ``n_fft // 2 + 1`` and ``n_fft`` is the number of
        Fourier bins, and time is the number of window hops (n_frame).
    r   ÚconstantéÿÿÿÿTÚreflectFNéýÿÿÿç       @©r,   )ÚtorchÚnnÚ
functionalr'   ÚsizeÚreshapeÚstftÚshapeÚpowÚsumÚsqrtr   )
r&   r'   r(   r)   r*   r+   r,   r-   r;   Zspec_f© r?   úU/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchaudio/functional.pyr   /   s    ÿ r   )Úspecgramr(   r)   r*   r+   r,   r-   Ún_iterÚmomentumÚlengthÚ	rand_initr.   c                 C   s¢  |dk sJ d  |¡ƒ‚|dks,J d  |¡ƒ‚|  ¡ }|  dgt|dd… ƒ ¡} |  d| ¡} |  ¡ \}}}|
rŠdtj t |||¡ }nt 	|||¡}tj
| ¡ | ¡ gdd	�j| j| jd
�}|  d¡ |¡} t d¡}t|ƒD ]€}|}tj| | |||||	d� ¡ }t |||||dddd¡	}|}|�rB|| |d|  ¡ }| t|ƒ d¡ d¡ |¡¡}qâtj| | |||||	d�}| |dd… |jdd…  ¡}|S )uñ  Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.
        Implementation ported from `librosa`.

    .. [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.

    Args:
        specgram (Tensor): A magnitude-only STFT spectrogram of dimension (..., freq, frames)
            where freq is ``n_fft // 2 + 1``.
        window (Tensor): Window tensor that is applied/multiplied to each frame/window
        n_fft (int): Size of FFT, creates ``n_fft // 2 + 1`` bins
        hop_length (int): Length of hop between STFT windows. (
            Default: ``win_length // 2``)
        win_length (int): Window size. (Default: ``n_fft``)
        power (float): Exponent for the magnitude spectrogram,
            (must be > 0) e.g., 1 for energy, 2 for power, etc.
        normalized (bool): Whether to normalize by magnitude after stft.
        n_iter (int): Number of iteration for phase recovery process.
        momentum (float): 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.
        length (int or None): Array length of the expected output.
        rand_init (bool): Initializes phase randomly if True, to zero otherwise.

    Returns:
        torch.Tensor: waveform of (..., time), where time equals the ``length`` parameter if given.
    é   zmomentum={} > 1 can be unstabler   zmomentum={} < 0r0   éþÿÿÿNé   ©Údim©ÚdtypeÚdeviceç        )r)   r*   r+   r(   rD   Tr1   Fg¼‰Ø—²Òœ<)Úformatr8   r9   Úlistr<   ÚmathÚpir5   ÚrandÚzerosÚstackÚcosÚsinÚtorL   rM   Ú	unsqueezeZ	expand_asÚtensorÚrangeZistftÚfloatr:   Úmul_Údivr   Úaddr;   )rA   r(   r)   r*   r+   r,   r-   rB   rC   rD   rE   r;   ÚbatchÚfreqÚframesZanglesZrebuiltÚ_ZtprevZinverser&   r?   r?   r@   r   f   sN    2ÿ

û
ÿ"
û r   )ÚxÚ
multiplierÚaminÚdb_multiplierÚtop_dbr.   c                 C   sH   |t  t j| |d�¡ }||| 8 }|durD|j| ¡  ¡ | d�}|S )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:
        x (Tensor): Input tensor before being converted to decibel scale
        multiplier (float): Use 10. for power and 20. for amplitude
        amin (float): Number to clamp ``x``
        db_multiplier (float): Log10(max(reference value and amin))
        top_db (float or None, optional): Minimum negative cut-off in decibels. A reasonable number
            is 80. (Default: ``None``)

    Returns:
        Tensor: Output tensor in decibel scale
    ©ÚminN)r5   Úlog10ÚclampÚmaxÚitem)rd   re   rf   rg   rh   Zx_dbr?   r?   r@   r   Ò   s
    r   )rd   Úrefr,   r.   c                 C   s   |t  t  dd|  ¡|¡ S )a—  Turn a tensor from the decibel scale to the power/amplitude scale.

    Args:
        x (Tensor): Input tensor before being converted to power/amplitude scale.
        ref (float): Reference which the output will be scaled by.
        power (float): If power equals 1, will compute DB to power. If 0.5, will compute DB to amplitude.

    Returns:
        Tensor: Output tensor in power/amplitude scale.
    g      $@çš™™™™™¹?)r5   r<   )rd   ro   r,   r?   r?   r@   ÚDB_to_amplitudeó   s    rq   )Ún_freqsÚf_minÚf_maxÚn_melsÚsample_rateÚnormr.   c                 C   s€  |dur|dkrt dƒ‚t d|d | ¡}dt d|d  ¡ }dt d|d  ¡ }t |||d ¡}	dd	|	d  d  }
|
d
d… |
dd…  }|
 d¡| d
¡ }t d
¡}d|dd…dd…f  |dd…  }|dd…dd…f |d
d…  }t |t ||¡¡}|du�rL|dk�rLd|
d|d … |
d|…   }|| d¡9 }|jdd�j	dk 
¡ �r|t d|› d| › d�¡ |S )aW  Create a frequency bin conversion matrix.

    Args:
        n_freqs (int): Number of frequencies to highlight/apply
        f_min (float): Minimum frequency (Hz)
        f_max (float): Maximum frequency (Hz)
        n_mels (int): Number of mel filterbanks
        sample_rate (int): Sample rate of the audio waveform
        norm (Optional[str]): If 'slaney', divide the triangular mel weights by the width of the mel band
        (area normalization). (Default: ``None``)

    Returns:
        Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_mels``)
        meaning number of frequencies to highlight/apply to x the number of filterbanks.
        Each column is a filterbank so that assuming there is a matrix A of
        size (..., ``n_freqs``), the applied result would be
        ``A * create_fb_matrix(A.size(-1), ...)``.
    NZslaneyz$norm must be one of None or 'slaney'r   rH   g     F¤@ç      ð?g     à…@é
   rF   r0   ç      ð¿rG   r3   rI   rN   zIAt least one mel filterbank has all zero values. The value for `n_mels` (z4) may be set too high. Or, the value for `n_freqs` (z) may be set too low.)Ú
ValueErrorr5   ZlinspacerQ   rk   rY   rT   rm   rj   ÚvaluesÚanyÚwarningsÚwarn)rr   rs   rt   ru   rv   rw   Z	all_freqsZm_minZm_maxZm_ptsZf_ptsZf_diffZslopesZzeroZdown_slopesZ	up_slopesZfbZenormr?   r?   r@   r     s2    
$  ÿþÿr   )Ún_mfccru   rw   r.   c                 C   s˜   t  t|ƒ¡}t  t| ƒ¡ d¡}t  tjt|ƒ |d  | ¡}|du rT|d9 }n<|dks`J ‚|d  dt d¡ 9  < |t dt|ƒ ¡9 }| ¡ S )a°  Create a DCT transformation matrix with shape (``n_mels``, ``n_mfcc``),
    normalized depending on norm.

    Args:
        n_mfcc (int): Number of mfc coefficients to retain
        n_mels (int): Number of mel filterbanks
        norm (str or None): Norm to use (either 'ortho' or None)

    Returns:
        Tensor: The transformation matrix, to be right-multiplied to
        row-wise data of size (``n_mels``, ``n_mfcc``).
    rF   ç      à?Nr3   Zorthor   rx   )	r5   Úaranger\   rY   rV   rQ   rR   r>   Út)r€   ru   rw   ÚnÚkÚdctr?   r?   r@   r	   F  s     
r	   )rd   Úquantization_channelsr.   c                 C   st   |d }|   ¡ s|  tj¡} tj|| jd�}t | ¡t |t | ¡ ¡ t |¡ }|d d | d  tj	¡}|S )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:
        x (Tensor): Input tensor
        quantization_channels (int): Number of channels

    Returns:
        Tensor: Input after mu-law encoding
    rx   ©rL   rF   rH   r�   )
Úis_floating_pointrX   r5   r\   rZ   rL   ÚsignÚlog1pÚabsÚint64)rd   r‡   ÚmuÚx_mur?   r?   r@   r
   d  s    (r
   )r�   r‡   r.   c                 C   sl   |d }|   ¡ s|  tj¡} tj|| jd�}| | d d }t |¡t t |¡t 	|¡ ¡d  | }|S )a§  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:
        x_mu (Tensor): Input tensor
        quantization_channels (int): Number of channels

    Returns:
        Tensor: Input after mu-law decoding
    rx   rˆ   rH   )
r‰   rX   r5   r\   rZ   rL   rŠ   ÚexprŒ   r‹   )r�   r‡   rŽ   rd   r?   r?   r@   r   ~  s    ,r   rx   )Úcomplex_tensorr,   r.   c                 C   s   |   d¡ d¡  d| ¡S )a  Compute the norm of complex tensor input.

    Args:
        complex_tensor (Tensor): Tensor shape of `(..., complex=2)`
        power (float): Power of the norm. (Default: `1.0`).

    Returns:
        Tensor: Power of the normed input tensor. Shape of `(..., )`
    r3   r0   r�   )r<   r=   )r‘   r,   r?   r?   r@   r   ˜  s    r   )r‘   r.   c                 C   s   t  | d | d ¡S )zÉCompute the angle of complex tensor input.

    Args:
        complex_tensor (Tensor): Tensor shape of `(..., complex=2)`

    Return:
        Tensor: Angle of a complex tensor. Shape of `(..., )`
    ).rF   ).r   )r5   Úatan2)r‘   r?   r?   r@   r   «  s    r   c                 C   s   t | |ƒ}t| ƒ}||fS )a>  Separate a complex-valued spectrogram with shape `(..., 2)` into its magnitude and phase.

    Args:
        complex_tensor (Tensor): Tensor shape of `(..., complex=2)`
        power (float): Power of the norm. (Default: `1.0`)

    Returns:
        (Tensor, Tensor): The magnitude and phase of the complex tensor
    )r   r   )r‘   r,   ÚmagÚphaser?   r?   r@   r   ¹  s    
r   )Úcomplex_specgramsÚrateÚphase_advancer.   c                 C   s’  |   ¡ }|  dgt|dd… ƒ ¡} tjd|   d¡|| j| jd�}|d }t| ddd	…dd…f ƒ}tjj	 
| g d
¢¡} |  d| ¡ ¡}|  d|d	  ¡ ¡}t|ƒ}	t|ƒ}
tj|ddd�}tj|ddd�}|
|	 | }|dtj t |dtj  ¡  }|| }tj||ddd…f gdd�}t |d¡}|| d	| |  }|t |¡ }|t |¡ }tj||gdd�}| |dd… |jd	d…  ¡}|S )a}  Given a STFT tensor, speed up in time without modifying pitch by a
    factor of ``rate``.

    Args:
        complex_specgrams (Tensor): Dimension of `(..., freq, time, complex=2)`
        rate (float): Speed-up factor
        phase_advance (Tensor): Expected phase advance in each bin. Dimension of (freq, 1)

    Returns:
        Tensor: Complex Specgrams Stretch with dimension of `(..., freq, ceil(time/rate), complex=2)`

    Example
        >>> freq, hop_length = 1025, 512
        >>> # (channel, freq, time, complex=2)
        >>> complex_specgrams = torch.randn(2, freq, 300, 2)
        >>> rate = 1.3 # Speed up by 30%
        >>> phase_advance = torch.linspace(
        >>>    0, math.pi * hop_length, freq)[..., None]
        >>> x = phase_vocoder(complex_specgrams, rate, phase_advance)
        >>> x.shape # with 231 == ceil(300 / 1.3)
        torch.Size([2, 1025, 231, 2])
    r0   r2   Nr   rG   ©rM   rL   rx   .rF   )r   r   r   rH   rH   ©ÚprJ   rI   )r8   r9   rP   r5   r‚   rM   rL   r   r6   r7   r'   Zindex_selectÚlongrw   rQ   rR   ÚroundÚcatÚcumsumrV   rW   rU   r;   )r•   r–   r—   r;   Z
time_stepsÚalphasZphase_0Zcomplex_specgrams_0Zcomplex_specgrams_1Zangle_0Zangle_1Znorm_0Znorm_1r”   Z	phase_accr“   Zreal_stretchZimag_stretchZcomplex_specgrams_stretchr?   r?   r@   r   Ë  s8    ü" r   T)r&   Úa_coeffsÚb_coeffsrl   r.   c                 C   s(  |   ¡ }|  d|d ¡} |  d¡|  d¡ks0J ‚t|   ¡ ƒdksDJ ‚| j|jksTJ ‚|j|jksdJ ‚| j}| j}|   ¡ \}}|  d¡}	||	 d }
|	dksžJ ‚tj||
||d�}| |dd…|	d d…f< tj||
||d�}| d¡}| d¡}tj||d� 	d¡tj|	|d� 	d¡ }| 
|dd¡}|tj||d� 	d¡ 	d¡|
 7 }| ¡ }t |t ||¡¡}| |d ¡ | |d ¡ t| ¡ ƒD ]J\}}|dd…|||	 …f }|j||dd� ||dd…||	 d f< �qŠ|dd…|	d d…f }|�rtj|d	d
d�}| |dd… |jdd…  ¡}|S )aÅ  Perform an IIR filter by evaluating difference equation.

    Args:
        waveform (Tensor): audio waveform of dimension of ``(..., time)``.  Must be normalized to -1 to 1.
        a_coeffs (Tensor): denominator coefficients of difference equation of dimension of ``(n_order + 1)``.
                                Lower delays coefficients are first, e.g. ``[a0, a1, a2, ...]``.
                                Must be same size as b_coeffs (pad with 0's as necessary).
        b_coeffs (Tensor): numerator coefficients of difference equation of dimension of ``(n_order + 1)``.
                                 Lower delays coefficients are first, e.g. ``[b0, b1, b2, ...]``.
                                 Must be same size as a_coeffs (pad with 0's as necessary).
        clamp (bool, optional): If ``True``, clamp the output signal to be in the range [-1, 1] (Default: ``True``)

    Returns:
        Tensor: Waveform with dimension of ``(..., time)``.
    r0   r   rH   rF   rK   N©rM   )Úalpharz   rx   ©rj   rm   )r8   r9   ÚlenrM   rL   r5   rT   Zflipr‚   rY   Úrepeatr›   ÚmatmulZtakeZdiv_Ú	enumeraterƒ   Zaddmv_rl   r;   )r&   r    r¡   rl   r;   rM   rL   Z	n_channelZn_sampleZn_orderZn_sample_paddedZpadded_waveformZpadded_output_waveformZa_coeffs_flippedZb_coeffs_flippedZwindow_idxsZinput_signal_windowsZi_sampleZo0Zwindowed_output_signalÚoutputr?   r?   r@   r     sB    


(" r   )r&   Úb0Úb1Úb2Úa0Úa1Úa2r.   c           
      C   s@   | j }| j}t| tj|||g||d�tj|||g||d�ƒ}	|	S )aÑ  Perform a biquad filter of input tensor.  Initial conditions set to 0.
    https://en.wikipedia.org/wiki/Digital_biquad_filter

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        b0 (float): numerator coefficient of current input, x[n]
        b1 (float): numerator coefficient of input one time step ago x[n-1]
        b2 (float): numerator coefficient of input two time steps ago x[n-2]
        a0 (float): denominator coefficient of current output y[n], typically 1
        a1 (float): denominator coefficient of current output y[n-1]
        a2 (float): denominator coefficient of current output y[n-2]

    Returns:
        Tensor: Waveform with dimension of `(..., time)`
    rK   )rM   rL   r   r5   rZ   )
r&   rª   r«   r¬   r­   r®   r¯   rM   rL   Úoutput_waveformr?   r?   r@   r   `  s    ýr   )rd   r.   c                 C   s   t  | t  d¡ d ¡S )Nry   ç      4@)rQ   r�   Úlog)rd   r?   r?   r@   Ú
_dB2Linear„  s    r³   ç9´Èv¾Ÿæ?)r&   rv   Úcutoff_freqÚQr.   c                 C   sz   dt j | | }t  |¡d | }dt  |¡ d }dt  |¡ }|}d| }	dt  |¡ }
d| }t| ||||	|
|ƒS )aÆ  Design biquad highpass filter and perform filtering.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        cutoff_freq (float): filter cutoff frequency
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``)

    Returns:
        Tensor: Waveform dimension of `(..., time)`
    rH   r3   rF   r0   rG   ©rQ   rR   rW   rV   r   ©r&   rv   rµ   r¶   Úw0r£   rª   r«   r¬   r­   r®   r¯   r?   r?   r@   r   ˆ  s    r   c                 C   sz   dt j | | }t  |¡d | }dt  |¡ d }dt  |¡ }|}d| }	dt  |¡ }
d| }t| ||||	|
|ƒS )aÎ  Design biquad lowpass filter and perform filtering.  Similar to SoX implementation.

    Args:
        waveform (torch.Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        cutoff_freq (float): filter cutoff frequency
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`
    rH   rF   rG   r·   r¸   r?   r?   r@   r   ¥  s    r   )r&   rv   Úcentral_freqr¶   r.   c                 C   st   dt j | | }t  |¡d | }d| }dt  |¡ }d| }d| }	dt  |¡ }
d| }t| ||||	|
|ƒS )a;  Design two-pole all-pass filter.  Similar to SoX implementation.

    Args:
        waveform(torch.Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        central_freq (float): central frequency (in Hz)
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rH   rF   rG   r·   ©r&   rv   rº   r¶   r¹   r£   rª   r«   r¬   r­   r®   r¯   r?   r?   r@   r   Â  s    r   F)r&   rv   rº   r¶   Úconst_skirt_gainr.   c                 C   sz   dt j | | }t  |¡d | }|r6t  |¡d n|}|}d}	| }
d| }dt  |¡ }d| }t| ||	|
|||ƒS )aê  Design two-pole band-pass filter.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        central_freq (float): central frequency (in Hz)
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``)
        const_skirt_gain (bool, optional) : If ``True``, uses a constant skirt gain (peak gain = Q).
            If ``False``, uses a constant 0dB peak gain. (Default: ``False``)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rH   rN   rF   rG   r·   )r&   rv   rº   r¶   r¼   r¹   r£   Útemprª   r«   r¬   r­   r®   r¯   r?   r?   r@   r   ã  s    r   c                 C   sl   dt j | | }t  |¡d | }d}dt  |¡ }d}d| }	dt  |¡ }
d| }t| ||||	|
|ƒS )a9  Design two-pole band-reject filter.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        central_freq (float): central frequency (in Hz)
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rH   rx   rG   rF   r·   r»   r?   r?   r@   r     s    r   )r&   rv   Úcenter_freqÚgainr¶   r.   c                 C   sœ   dt j | | }t  |d t  d¡ ¡}t  |¡d | }d||  }dt  |¡ }	d||  }
d||  }dt  |¡ }d||  }t| ||	|
|||ƒS )a  Design biquad peaking equalizer filter and perform filtering.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        center_freq (float): filter's central frequency
        gain (float): desired gain at the boost (or attenuation) in dB
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`
    rH   ç      D@ry   rF   rG   )rQ   rR   r�   r²   rW   rV   r   )r&   rv   r¾   r¿   r¶   r¹   ÚAr£   rª   r«   r¬   r­   r®   r¯   r?   r?   r@   r   )  s    r   )r&   rv   rº   r¶   Únoiser.   c                 C   sÌ   dt j | | }|| }d}t  dt j | | ¡}d| d|  t  |¡ }	t  d|	|	 d|   ¡d|  }
|r°t  d| d|  |	|	  d|  d|  ¡|
 }|
|9 }
d}d}t| |
||||	|ƒS )a-  Design two-pole band filter.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        central_freq (float): central frequency (in Hz)
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``).
        noise (bool, optional) : If ``True``, uses the alternate mode for un-pitched audio (e.g. percussion).
            If ``False``, uses mode oriented to pitched audio, i.e. voice, singing,
            or instrumental music (Default: ``False``).

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rH   rx   rG   éüÿÿÿrF   é   rN   )rQ   rR   r�   rV   r>   r   )r&   rv   rº   r¶   rÂ   r¹   Zbw_Hzr­   r¯   r®   rª   Úmultr«   r¬   r?   r?   r@   r   I  s    "2r   é¸  )r&   rv   r¿   rº   r¶   r.   c                 C   sò   dt j | | }t  |¡d | }t  |d t  d¡ ¡}dt  |¡ | }|d t  |¡ }	|d t  |¡ }
||d |	 |  }d| |d |
  }||d |	 |  }|d |	 | }d|d |
  }|d |	 | }t| ||||||ƒS )a¢  Design a treble tone-control effect.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        gain (float): desired gain at the boost (or attenuation) in dB.
        central_freq (float, optional): central frequency (in Hz). (Default: ``3000``)
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``).

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rH   é(   ry   rF   rG   ©rQ   rR   rW   r�   r²   r>   rV   r   ©r&   rv   r¿   rº   r¶   r¹   r£   rÁ   Útemp1Útemp2Útemp3rª   r«   r¬   r­   r®   r¯   r?   r?   r@   r   u  s    r   éd   c              	   C   s
  dt j | | }t  |¡d | }t  |d t  d¡ ¡}dt  |¡ | }|d t  |¡ }	|d t  |¡ }
||d |	 |  }d| |d |
  }||d |	 |  }|d |	 | }d|d |
  }|d |	 | }t| || || || || || || ƒS )aŸ  Design a bass tone-control effect.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        gain (float): desired gain at the boost (or attenuation) in dB.
        central_freq (float, optional): central frequency (in Hz). (Default: ``100``)
        Q (float, optional): https://en.wikipedia.org/wiki/Q_factor (Default: ``0.707``).

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rH   rÇ   ry   rF   rG   rÈ   rÉ   r?   r?   r@   r   ž  s    r   )r&   rv   r.   c                 C   sD  |dkrd}d}d}n|dkr,d}d}d}nt d	ƒ‚d
tj | | }t |d t d¡ ¡}t |¡d
 t |d|  d| d  d
 ¡ }d
t |¡ | }|d t |¡ }	|d t |¡ }
||d |	 |  }d| |d |
  }||d |	 |  }|d |	 | }d
|d |
  }|d |	 | }t| ||||||ƒS )aÓ  Apply ISO 908 CD de-emphasis (shelving) IIR filter.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, Allowed sample rate ``44100`` or ``48000``

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    éD¬  i£  g5^ºIß?gNbX9ô"Àé€»  iì  g-²�ï§Þ?g=
×£p=#Àz3Sample rate must be 44100 (audio-CD) or 48000 (DAT)rH   rÀ   ry   rF   rG   )	r{   rQ   rR   r�   r²   rW   r>   rV   r   )r&   rv   rº   Zwidth_sloper¿   r¹   rÁ   r£   rÊ   rË   rÌ   rª   r«   r¬   r­   r®   r¯   r?   r?   r@   r   Ç  s,    0r   c                 C   s´  |dkrddg}ddg}nV|dkr4ddg}d	d
g}n<|dkrNddg}ddg}n"|dkrhddg}ddg}nt dƒ‚d}|d |d   }|d |d  }d}|d |d   }|d |d  }	dtj d | }
||t |
 ¡  |t d|
 ¡  }||t |
 ¡  |	t d|
 ¡  }|t |
 ¡ |t d|
 ¡  }|t |
 ¡ |	t d|
 ¡  }dt |d |d  |d |d   ¡ }||9 }||9 }||9 }t| ||||||	ƒS )aþ  Apply RIAA vinyl playback equalisation.  Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz).
            Allowed sample rates in Hz : ``44100``,``48000``,``88200``,``96000``

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        https://www.w3.org/2011/audio/audio-eq-cookbook.html#APF
    rÎ   g^!½òjÊÉ¿gßávhXŒí?gÔŸX„ªæ?gã˜ºÐÁï?rÏ   g”¼ß›Æ¿gŒ�u?Ôí?g	áÑÆ«ç?gþ�rÛ¾Çï?iˆX gÛàDôkë½¿gI"E®åßî?g ×Du}ë?gŸJ¬‚âï?i w gýYâ·×8½¿g€Îœ?÷î?g“ôzAUÖë?g“1ãìäï?z-Sample rate must be 44.1k, 48k, 88.2k, or 96krx   r   rF   rH   éè  rG   )r{   rQ   rR   rV   rW   r>   r   )r&   rv   rT   Zpolesrª   r«   r¬   r­   r®   r¯   ÚyZb_reZa_reZb_imZa_imÚgr?   r?   r@   r   ö  s:    



&&""*r   ç     ÀR@)r&   Úenhancement_amountr.   c                 C   sX   d|  krdksn t dƒ‚|d }| tjd  }|t |d ¡ }t || ¡}|S )aX  Apply contrast effect.  Similar to SoX implementation.
    Comparable with compression, this effect modifies an audio signal to make it sound louder

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        enhancement_amount (float): controls the amount of the enhancement
            Allowed range of values for enhancement_amount : 0-100
            Note that enhancement_amount = 0 still gives a significant contrast enhancement

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
    r   rÍ   z6Allowed range of values for enhancement_amount : 0-100g     p‡@rH   rÄ   )r{   rQ   rR   r5   rW   )r&   rÔ   r   rÊ   rË   r°   r?   r?   r@   r   5  s    r   )r&   ÚshiftÚlimiter_gainr.   c                 C   s
  | }d}|dur dt |ƒ|  }|durˆ|dkrˆ| |k}| | | | d|  }|| | j|d�||< | |  | jddd�|| < n~|durô|dk rô| | k }| | | | d|  }|| | j| d	�||< | |  | jddd�|| < n| | jddd�}|S )
a¤  Apply a DC shift to the audio. Similar to SoX implementation.
    This can be useful to remove a DC offset
    (caused perhaps by a hardware problem in the recording chain) from the audio

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        shift (float): indicates the amount to shift the audio
            Allowed range of values for shift : -2.0 to +2.0
        limiter_gain (float): It is used only on peaks to prevent clipping
            It should have a value much less than 1 (e.g. 0.05 or 0.02)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
    rN   Nrx   r   rF   )rm   r0   r¤   ri   )rŒ   rl   )r&   rÕ   rÖ   r°   Zlimiter_thresholdÚmaskr½   r?   r?   r@   r   U  s      
 r   é   )r&   r¿   Úcolourr.   c                 C   s`  | j }| j| j }}|  d|d ¡} t|ƒ}|d }tj| j dd… ||d�}tj| j dd… ||d�}| | | }|dk }	tjd||d�||	< |dk}
tjd||d�||
< |	 |
 @ }|| || d d	  ||< tj| ||d�}t	| j d ƒD ]X}|dd…|f | d
|  }|dd…|f }| dd…|f d |d  |dd…|f< qò|j
ddd� |¡S )am  Apply a overdrive effect to the audio. Similar to SoX implementation.
    This effect applies a non linear distortion to the audio signal.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        gain (float): desired gain at the boost (or attenuation) in dB
            Allowed range of values are 0 to 100
        colour (float):  controls the amount of even harmonic content in the over-driven output
            Allowed range of values are 0 to 100

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
    r0   éÈ   NrK   gUUUUUUå¿rF   gUUUUUUå?é   gUUUUUUÕ?g×£p=
×ï?r�   g      è?r¤   )r;   rM   rL   Úviewr³   r5   rT   rZ   Ú
zeros_liker[   rl   )r&   r¿   rÙ   Úactual_shaperM   rL   Zlast_inZlast_outr½   Zmask1Zmask2Zmask3r°   Úir?   r?   r@   r   �  s(    *r   çš™™™™™Ù?ç®Gáz®ç?ç      @r�   )	r&   rv   Úgain_inÚgain_outÚdelay_msÚdecayÚ	mod_speedÚ
sinusoidalr.   c              	      sœ  ˆj }ˆjˆj }	}
ˆ d|d ¡‰t|d | d ƒ}tjˆj d ||
|	d�‰ t|| d ƒ}|rjd}nd}t|d|d	t|ƒt	j
d
 |	d�‰d}d}g }ˆ| ‰ˆ | ‰ ‡fdd„tˆ d¡ƒD ƒ}‡ fdd„tˆ  d¡ƒD ƒ}‡fdd„tˆ d¡ƒD ƒ}tˆj d ƒD ]X}t|||  | ƒ}|d | }|d | }|| ||  }|| ||< | |¡ �qtj|dd�j|
|	d�}| |¡ |jddd� |¡S )aù  Apply a phasing effect to the audio. Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., time)`
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        gain_in (float): desired input gain at the boost (or attenuation) in dB
            Allowed range of values are 0 to 1
        gain_out (float): desired output gain at the boost (or attenuation) in dB
            Allowed range of values are 0 to 1e9
        delay_ms (float): desired delay in milli seconds
            Allowed range of values are 0 to 5.0
        decay (float):  desired decay relative to gain-in
            Allowed range of values are 0 to 0.99
        mod_speed (float):  modulation speed in Hz
            Allowed range of values are 0.1 to 2
        sinusoidal (bool):  If ``True``, uses sinusoidal modulation (preferable for multiple instruments)
            If ``False``, uses triangular modulation (gives single instruments a sharper phasing effect)
            (Default: ``True``)

    Returns:
        Tensor: Waveform of dimension of `(..., time)`

    References:
        http://sox.sourceforge.net/sox.html
        Scott Lehman, Effects Explained, http://harmony-central.com/Effects/effects-explained.html
    r0   gü©ñÒMbP?r�   r   rK   ÚSINEÚTRIANGLEÚINTrx   rH   ©Ú	wave_typeÚ	data_typeÚ
table_sizerj   rm   r”   rM   c                    s   g | ]}ˆ d d …|f ‘qS ©Nr?   ©Ú.0rß   )r&   r?   r@   Ú
<listcomp>ú  ó    zphaser.<locals>.<listcomp>rF   c                    s   g | ]}ˆ d d …|f ‘qS rð   r?   rñ   )Ú	delay_bufr?   r@   ró   û  rô   c                    s   g | ]}ˆ | ‘qS r?   r?   rñ   )Úmod_bufr?   r@   ró   ü  rô   rI   r¤   )r;   rM   rL   rÜ   Úintr5   rT   Ú_generate_wave_tabler\   rQ   rR   r[   r8   ÚappendrU   rX   r]   rl   )r&   rv   rã   rä   rå   ræ   rç   rè   rÞ   rM   rL   Zdelay_buf_lenZmod_buf_lenrí   Z	delay_posZmod_posZoutput_waveform_pre_gain_listZwaveform_listZdelay_buf_listZmod_buf_listrß   Úidxr½   r°   r?   )rõ   rö   r&   r@   r    ¸  sF    $ú
r    )rí   rî   rï   rj   rm   r”   rM   r.   c                 C   st  t |tj d | d ƒ}tj||tjd�}|| | }	tj|	|tjd�}
| dkr|t |	 	tj¡| d tj ¡d d }
nŠ| dk�r|	 	tj¡d | }
d|	 | }|
|dk d |
|dk< d	|
|dk  |
|dk< d	|
|dk  |
|dk< |
|d
k d	 |
|d
k< |
||  | }
|dk�rZ|
dk }|
| d |
|< |
|  d |
| < |
 	tj¡}
n|dk�rp|
 	tj
¡}
|
S )aî  A helper fucntion for phaser. Generates a table with given parameters

    Args:
        wave_type (str): SINE or TRIANGULAR
        data_type (str): desired data_type ( `INT` or `FLOAT` )
        table_size (int): desired table size
        min (float): desired min value
        max (float): desired max value
        phase (float): desired phase
        device (torch.device): Torch device on which table must be generated
    Returns:
        Tensor: A 1D tensor with wave table values
    rH   r�   r˜   ré   rF   rê   rÄ   r   g      ø?rÛ   rë   ÚFLOAT)r÷   rQ   rR   r5   r‚   Úint32rÝ   Úfloat64rW   rX   Úfloat32)rí   rî   rï   rj   rm   r”   rM   Zphase_offsetrƒ   ZpointÚdÚvaluer×   r?   r?   r@   rø     s,    *


rø   rN   r3   ç     ÀQ@ç      9@rè   Úlinear)r&   rv   ÚdelayÚdepthÚregenÚwidthÚspeedr”   Ú
modulationÚinterpolationr.   c
           ,   	   C   sL  |dvrt dƒ‚|	dvr t dƒ‚| j}
| j| j }}|
d dkrHt dƒ‚|  d|
d |
d ¡} |d	 }|d	 }|d	 }|d
 }|d
 }| jd }|dkržd}nd}dd|  }|d|  }|dt|ƒ  }t|| | d ƒ}|d }tj| jd ||||d�}tj| jd |||d�}t|| ƒ}t	 
|| d ¡}|d }t|d|t|ƒt|ƒdt	j d |d�}tj| ||d�}d}d}tjd||d�}t| jd ƒD �]˜} || d | }|| | d  tj¡}!|||! |  }"t |"¡}#t 
|"¡}"|" tj¡}$| dd…dd…| f }%|%||  |dd…dd…|f< |dd…|||$ | f }&|$d }$|dd…|||$ | f }'|$d }$|	dk�rŽ|&|'|& |#  }(nb|dd…|||$ | f })|$d }$|)|& })|'|& }'|)d |' }*|'d |)d  }+|&|*|# |+ |#  }(|(}| dd…dd…| f | |(|  |dd…dd…| f< |d | }�qœ|jddd� |
¡S )a•  Apply a flanger effect to the audio. Similar to SoX implementation.

    Args:
        waveform (Tensor): audio waveform of dimension of `(..., channel, time)` .
            Max 4 channels allowed
        sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
        delay (float): desired delay in milliseconds(ms)
            Allowed range of values are 0 to 30
        depth (float): desired delay depth in milliseconds(ms)
            Allowed range of values are 0 to 10
        regen (float): desired regen(feeback gain) in dB
            Allowed range of values are -95 to 95
        width (float):  desired width(delay gain) in dB
            Allowed range of values are 0 to 100
        speed (float):  modulation speed in Hz
            Allowed range of values are 0.1 to 10
        phase (float):  percentage phase-shift for multi-channel
            Allowed range of values are 0 to 100
        modulation (str):  Use either "sinusoidal" or "triangular" modulation. (Default: ``sinusoidal``)
        interpolation (str): Use either "linear" or "quadratic" for delay-line interpolation. (Default: ``linear``)

    Returns:
        Tensor: Waveform of dimension of `(..., channel, time)`

    References:
        http://sox.sourceforge.net/sox.html

        Scott Lehman, Effects Explained,
        https://web.archive.org/web/20051125072557/http://www.harmony-central.com/Effects/effects-explained.html
    )rè   Ú
triangularz4Only 'sinusoidal' or 'triangular' modulation allowed)r  Z	quadraticz2Only 'linear' or 'quadratic' interpolation allowedrG   rÄ   zMax 4 channels allowedr0   rÍ   rÐ   rè   ré   rê   rx   rF   r�   rH   r   rK   r3   rû   rÛ   rì   r¢   Nr  r¤   )r{   r;   rM   rL   rÜ   rŒ   r÷   r5   rT   rQ   Úfloorrø   r\   rR   rÝ   r‚   r[   rX   r�   Úfracrl   ),r&   rv   r  r  r  r  r  r”   r	  r
  rÞ   rM   rL   Zfeedback_gainZ
delay_gainZchannel_phaseZ	delay_minZdelay_depthÚ
n_channelsrí   Zin_gainZdelay_buf_lengthZ
delay_bufsZ
delay_lastZ
lfo_lengthZ	table_minZ	table_maxZlfor°   Zdelay_buf_posZlfo_posZchannel_idxsrß   Zcur_channel_phaseZdelay_tensorZ
frac_delayZ	int_delayr½   Z	delayed_0Z	delayed_1ZdelayedZ	delayed_2ÚaÚbr?   r?   r@   r!   B  s„    +
ú


4r!   )Ú	specgramsÚ
mask_paramÚ
mask_valueÚaxisr.   c                 C   sÊ   |dkr|dkrt dƒ‚| j}| j}tj| jdd… ||d�| }tj| jdd… ||d�|  |¡|  }|d }|| d }	tjd|  |¡||d�}
|  |d¡} |  	|
|k|
|	k @ |¡ |  |d¡} | S )	aj  
    Apply a mask along ``axis``. Mask will be applied from indices ``[v_0, v_0 + v)``, where
    ``v`` is sampled from ``uniform(0, mask_param)``, and ``v_0`` from ``uniform(0, max_v - v)``.

    Args:
        specgrams (Tensor): Real spectrograms (batch, channel, freq, time)
        mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param]
        mask_value (float): Value to assign to the masked columns
        axis (int): Axis to apply masking on (2 -> frequency, 3 -> time)

    Returns:
        Tensor: Masked spectrograms of dimensions (batch, channel, freq, time)
    rH   rÛ   ú-Only Frequency and Time masking are supportedNr˜   ).NNr   r0   )
r{   rM   rL   r5   rS   r;   r8   r‚   Z	transposeZmasked_fill_)r  r  r  r  rM   rL   r   Ú	min_valueÚ
mask_startÚmask_endr×   r?   r?   r@   r#   ×  s    (r#   )rA   r  r  r  r.   c           	      C   sè   |   ¡ }|  dgt|dd… ƒ ¡} t d¡| }t d¡|   |¡|  }| ¡  ¡ }| ¡ | ¡   ¡ }|| |k szJ ‚|dkr˜|| dd…||…f< n,|dkr¼|| dd…dd…||…f< ntdƒ‚|  |dd… | jdd…  ¡} | S )aŒ  
    Apply a mask along ``axis``. Mask will be applied from indices ``[v_0, v_0 + v)``, where
    ``v`` is sampled from ``uniform(0, mask_param)``, and ``v_0`` from ``uniform(0, max_v - v)``.
    All examples will have the same mask interval.

    Args:
        specgram (Tensor): Real spectrogram (channel, freq, time)
        mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param]
        mask_value (float): Value to assign to the masked columns
        axis (int): Axis to apply masking on (1 -> frequency, 2 -> time)

    Returns:
        Tensor: Masked spectrogram of dimensions (channel, freq, time)
    r0   rG   NrF   rH   r  )	r8   r9   rP   r5   rS   r›   Úsqueezer{   r;   )	rA   r  r  r  r;   r   r  r  r  r?   r?   r@   r"     s     r"   é   Ú	replicate)rA   r+   Úmoder.   c           
      C   sÈ   | j }| j}|  ¡ }|  dd|d ¡} |dks2J ‚|d d }||d  d| d  d }tjjj| ||f|d�} tj| |d d||d� 	| j
d dd¡}tjjj| || j
d d�| }	|	 |¡}	|	S )aC  Compute delta coefficients of a tensor, usually a spectrogram:

    .. math::
       d_t = \frac{\sum_{n=1}^{\text{N}} n (c_{t+n} - c_{t-n})}{2 \sum_{n=1}^{\text{N}} n^2}

    where :math:`d_t` is the deltas at time :math:`t`,
    :math:`c_t` is the spectrogram coeffcients at time :math:`t`,
    :math:`N` is ``(win_length-1)//2``.

    Args:
        specgram (Tensor): Tensor of audio of dimension (..., freq, time)
        win_length (int, optional): The window length used for computing delta (Default: ``5``)
        mode (str, optional): Mode parameter passed to padding (Default: ``"replicate"``)

    Returns:
        Tensor: Tensor of deltas of dimension (..., freq, time)

    Example
        >>> specgram = torch.randn(1, 40, 1000)
        >>> delta = compute_deltas(specgram)
        >>> delta2 = compute_deltas(delta)
    rF   r0   rÛ   rH   )r  r˜   )Úgroups)rM   rL   r8   r9   r5   r6   r7   r'   r‚   r¦   r;   Zconv1d)
rA   r+   r  rM   rL   r;   r„   ZdenomÚkernelr©   r?   r?   r@   Úcompute_deltas.  s    *
r  )r&   Úgain_dbr.   c                 C   s    |dkr| S d|d  }| | S )a)  Apply amplification or attenuation to the whole waveform.

    Args:
       waveform (Tensor): Tensor of audio of dimension (..., time).
       gain_db (float, optional) Gain adjustment in decibels (dB) (Default: ``1.0``).

    Returns:
       Tensor: the whole waveform amplified by gain_db.
    r   ry   rØ   r?   )r&   r   Zratior?   r?   r@   r¿   c  s    r¿   )Údithered_waveformr&   r.   c           
      C   s¸   |  ¡ }| d|d ¡}|   ¡ }|  d|d ¡} | | }tjd|j|jd�}t|  ¡ d ƒD ]2}|| }t ||f¡}|d|  ¡ d … ||< q\| | }	|	 |dd… |	jdd…  ¡S )z‹Noise shaping is calculated by error:
    error[n] = dithered[n] - original[n]
    noise_shaped_waveform[n] = dithered[n] + error[n-1]
    r0   rF   rK   r   N)	r8   r9   r5   rT   rL   rM   r[   r�   r;   )
r!  r&   Zwf_shapeZdithered_shapeÚerrorrT   ÚindexÚerrZerror_offsetZnoise_shapedr?   r?   r@   Ú_add_noise_shapingx  s    r%  ÚTPDF)r&   Údensity_functionr.   c                 C   s˜  |   ¡ }|  d|d ¡} |   ¡ d d }|   ¡ d d }|dkrVtt |dg¡ ¡ ƒnd}|dkrxtt |dg¡ ¡ ƒnd}d}d|d  d }| | }	d|d  }
| }|dkrÊ| | | d }|	| }nœ|dk�r6d	}| | | }||g D ]<}tt |dg¡ ¡ ƒ}|| | tt |dg¡ ¡ ƒ 7 }qî|	| }n0tj|d |	j|	jd
�}| 	|d d¡}|	| }t 
|¡}||
 }| |dd… |jdd…  ¡S )aY  Apply a probability distribution function on a waveform.

    Triangular probability density function (TPDF) dither noise has a
    triangular distribution; values in the center of the range have a higher
    probability of occurring.

    Rectangular probability density function (RPDF) dither noise has a
    uniform distribution; any value in the specified range has the same
    probability of occurring.

    Gaussian probability density function (GPDF) has a normal distribution.
    The relationship of probabilities of results follows a bell-shaped,
    or Gaussian curve, typical of dither generated by analog sources.
    Args:
        waveform (Tensor): Tensor of audio of dimension (..., time)
        probability_density_function (str, optional): The density function of a
           continuous random variable (Default: ``"TPDF"``)
           Options: Triangular Probability Density Function - `TPDF`
                    Rectangular Probability Density Function - `RPDF`
                    Gaussian Probability Density Function - `GPDF`
    Returns:
        Tensor: waveform dithered with TPDF
    r0   r   rF   é   rH   ÚRPDFr�   ZGPDFé   rK   N)r8   r9   r÷   r5   Úrandintrn   Zbartlett_windowrL   rM   r¦   rœ   r;   )r&   r'  r;   Zchannel_sizeZ	time_sizeZrandom_channelZrandom_timeZnumber_of_bitsZ
up_scalingZsignal_scaledZdown_scalingZsignal_scaled_disr)  Znum_rand_variablesZgaussianÚwsZ	rand_chanr&  Zquantised_signal_scaledZquantised_signalr?   r?   r@   Ú_apply_probability_distribution“  s6    ""

$

r-  )r&   r'  Únoise_shapingr.   c                 C   s"   t | |d�}|rt|| ƒS |S dS )a4  Dither increases the perceived dynamic range of audio stored at a
    particular bit-depth by eliminating nonlinear truncation distortion
    (i.e. adding minimally perceived noise to mask distortion caused by quantization).
    Args:
       waveform (Tensor): Tensor of audio of dimension (..., time)
       density_function (str, optional): The density function of a continuous random variable (Default: ``"TPDF"``)
           Options: Triangular Probability Density Function - `TPDF`
                    Rectangular Probability Density Function - `RPDF`
                    Gaussian Probability Density Function - `GPDF`
       noise_shaping (bool, optional): a filtering process that shapes the spectral
           energy of quantisation error (Default: ``False``)

    Returns:
       Tensor: waveform dithered
    )r'  N)r-  r%  )r&   r'  r.  Zditheredr?   r?   r@   ÚditherÝ  s    
r/  )r&   rv   Ú
frame_timeÚfreq_lowr.   c                 C   s>  d}t t || ¡ƒ}t t || ¡ƒ}|  ¡ d }t t || ¡ƒ}|||  | }	tjj | d|	f¡} g }
td|d ƒD ]°}| dd| …f  	d||¡dd|…dd…f }| d|d…f  	d||¡dd|…dd…f }||  
d¡|tj|ddd�  d¡ |tj|ddd�  d¡ }|
 | d¡¡ q|t |
d¡}|S )	a¹  
    Compute Normalized Cross-Correlation Function (NCCF).

    .. math::
        \phi_i(m) = \frac{\sum_{n=b_i}^{b_i + N-1} w(n) w(m+n)}{\sqrt{E(b_i) E(m+b_i)}},

    where
    :math:`\phi_i(m)` is the NCCF at frame :math:`i` with lag :math:`m`,
    :math:`w` is the waveform,
    :math:`N` is the length of a frame,
    :math:`b_i` is the beginning of frame :math:`i`,
    :math:`E(j)` is the energy :math:`\sum_{n=j}^{j+N-1} w^2(n)`.
    ç•Ö&è.>r0   r   rF   .NrH   r™   )r÷   rQ   Úceilr8   r5   r6   r7   r'   r[   Úunfoldr=   rw   r<   rù   rY   r�   )r&   rv   r0  r1  ÚEPSILONZlagsÚ
frame_sizeZwaveform_lengthZnum_of_framesrš   Z
output_lagZlagÚs1Ús2Zoutput_framesÚnccfr?   r?   r@   Ú_compute_nccfù  s(    .,ÿþÿr:  ç®Gáz®ï?)r  r  Úthreshr.   c                 C   sP   | d ||d  k}|| d  | |d   }|| d  | |d   }||fS )zb
    Take value from first if bigger than a multiplicative factor of the second, elementwise.
    r   rF   r?   )r  r  r<  r×   r|   Úindicesr?   r?   r@   Ú_combine_max-  s    r>  )r9  rv   Ú	freq_highr.   c                 C   sv   t t || ¡ƒ}t | d|d…f d¡}| jd d }t | d||…f d¡}t||ƒ}|d }||7 }|d7 }|S )zè
    For each frame, take the highest value of NCCF,
    apply centered median smoothing, and convert to frequency.

    Note: If the max among all the lags is very close
    to the first half of lags, then the latter is taken.
    .Nr0   rH   rF   )r÷   rQ   r3  r5   rm   r;   r>  )r9  rv   r?  Zlag_minÚbestZ	half_sizeZhalfr=  r?   r?   r@   Ú_find_max_per_frame;  s    
rA  )r=  r+   r.   c                 C   sv   |d d }t jjj| |dfddd�} t j|| d|f  d¡g dd	�| dd
|…f< |  d|d¡}t  |d¡\}}|S )zH
    Apply median smoothing to the 1D tensor over the given window.
    rF   rH   r   r/   rN   )r  r   .r0   rI   N)r5   r6   r7   r'   r�   rY   r4  Zmedian)r=  r+   Z
pad_lengthZrollr|   rc   r?   r?   r@   Ú_median_smoothing\  s    	ÿ.rB  ç{®Gáz„?é   éU   éH  )r&   rv   r0  r+   r1  r?  r.   c                 C   sˆ   t |  ¡ ƒ}|  dg|dd…  ¡} t| |||ƒ}t|||ƒ}t||ƒ}d}	||	| tj¡  }
|
 |dd… t |
j	dd… ƒ ¡}
|
S )aÞ  Detect pitch frequency.

    It is implemented using normalized cross-correlation function and median smoothing.

    Args:
        waveform (Tensor): Tensor of audio of dimension (..., freq, time)
        sample_rate (int): The sample rate of the waveform (Hz)
        frame_time (float, optional): Duration of a frame (Default: ``10 ** (-2)``).
        win_length (int, optional): The window length for median smoothing (in number of frames) (Default: ``30``).
        freq_low (int, optional): Lowest frequency that can be detected (Hz) (Default: ``85``).
        freq_high (int, optional): Highest frequency that can be detected (Hz) (Default: ``3400``).

    Returns:
        Tensor: Tensor of freq of dimension (..., frame)
    r0   Nr2  )
rP   r8   r9   r:  rA  rB  rX   r5   r\   r;   )r&   rv   r0  r+   r1  r?  r;   r9  r=  r5  ra   r?   r?   r@   Údetect_pitch_frequencys  s    
$rG  éX  )r&   Ú
cmn_windowÚmin_cmn_windowÚcenterÚ	norm_varsr.   c                 C   sà  | j }|dd… \}}|  d||¡} | j d }| j}	| j}
d }}tj|||	|
d�}tj|||	|
d�}tj||||	|
d�}t|ƒD �]$}d}d}|rª||d  }|| }n|| }|d }|dk rÎ||8 }d}|sè||krèt|d |ƒ}||k�r||| 8 }|}|dk �rd}|dk�rv| dd…||| …dd…f }|t |d¡7 }|�rê|t 	|d d¡dd…ddd…f 7 }nt||k�r°| dd…|dd…f }||8 }|�r°||d 8 }||k�rê| dd…|dd…f }||7 }|�rê||d 7 }|| }|}|}| dd…|dd…f ||  |dd…|dd…f< |r‚|dk�r^tj|||	|
d�|dd…|dd…f< q‚|}|| }||d |d  8 }t 
|d¡}|dd…|dd…f  |9  < q‚| |dd… ||f ¡}t|ƒdk�rÜ| d¡}|S )	af  
    Apply sliding-window cepstral mean (and optionally variance) normalization per utterance.

    Args:
        waveform (Tensor): Tensor of audio of dimension (..., freq, time)
        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)

    Returns:
        Tensor: Tensor of freq of dimension (..., frame)
    rG   Nr0   r   rK   rH   rF   g      à¿)r;   rÜ   rL   rM   r5   rT   r[   rm   r=   rž   r<   r¥   r  )r&   rI  rJ  rK  rL  Zinput_shapeZ
num_framesZ	num_featsZnum_channelsrL   rM   Zlast_window_startZlast_window_endZcur_sumZ	cur_sumsqZcmn_waveformrƒ   Zwindow_startZ
window_endZ
input_partZframe_to_removeZframe_to_addZwindow_framesZvariancer?   r?   r@   r$   œ  s€    

ÿ



(

0
ÿ 
r$   )Úmeasure_len_wsÚsamplesÚspectrumÚnoise_spectrumÚspectrum_windowÚspectrum_startÚspectrum_endÚcepstrum_windowÚcepstrum_startÚcepstrum_endÚnoise_reduction_amountÚmeasure_smooth_time_multÚnoise_up_time_multÚnoise_down_time_multÚindex_nsÚ
boot_countr.   c              
      s  |  ¡ d |  ¡ d ksJ ‚|  ¡ d ‰|  ¡ d }t |¡}t ˆ g‡ ‡fdd„td| ƒD ƒ ¡}|| |d | …  |d | …< || |…  ¡  t |d¡}|d |…  ¡  |dkrÀ|d|  n|}t|||… ƒ}|||…  |¡ 	|d|  ¡ |||… d }t || ¡}|dk�r |n$t 
||||… kt |¡t |¡¡}|||…  |¡ 	|d|  ¡ t t |||
|||…   ¡¡}t |d? ¡}|| |||…< |||d? …  ¡  t |d¡}tt t|||	… dd	�¡ƒ}|dk�r t ||	|  ¡ntj }tdd
| ƒS )Nr0   c                    s   g | ]}ˆ | ˆ ‘qS r?   r?   rñ   ©r[  ÚsamplesLen_nsr?   r@   ró     s   ÿz_measure.<locals>.<listcomp>rF   r   rx   rH   r3   r4   é   )r8   r5   rT   rZ   r[   Zzero_Zrfftr   r]   Zadd_Úwherer>   rm   r\   r=   rQ   r²   Úinf)rM  rN  rO  rP  rQ  rR  rS  rT  rU  rV  rW  rX  rY  rZ  r[  r\  Ú
dft_len_wsZdftBufZ	_index_nsZ_dftBufrÅ   Z_dZ_zerosZ_multZ_cepstrum_BufÚresultr?   r]  r@   Ú_measure÷  sd    
þ
ÿ
ÿþ ÿýþ þÿ
þÿÿýrd  ç      @ç      Ð?çffffffÖ?rp   çš™™™™™õ?r±   ç      I@ç     p·@ç     Àb@ç     @Ÿ@)r&   rv   Útrigger_levelÚtrigger_timeÚsearch_timeÚallowed_gapÚpre_trigger_timeÚ	boot_timeÚnoise_up_timeÚnoise_down_timerW  Úmeasure_freqÚmeasure_durationÚmeasure_smooth_timeÚhp_filter_freqÚlp_filter_freqÚhp_lifter_freqÚlp_lifter_freqr.   c           ?      C   sš  |du rd| n|}t || d ƒ}|}d}||k r>|d9 }q,t || d ƒ}t || ¡}|| }t || d ƒ}t || d ƒ}|| | }t |¡}t|ƒD ]}dt t|ƒ¡ ||< q¢|tj|tjd�9 }t || | d ƒ}t	|dƒ}t || | d ƒ}t
||d ƒ}t || ¡}t|| ƒD ] }dt t|ƒ| ¡ ||< �q,|tj|| tjd�9 }t |d | ¡} t |d | ¡}!t
|!|d ƒ}!|!| k�s¦J ‚t d	||  ¡}"t d	|	|  ¡}#t d	||  ¡}$t d	||  ¡}%t || d ƒ}&|}'d
 }( }) }*}+|  ¡ },|  d|,d ¡} |  ¡ \}-}.t |-¡}/t |-|¡}0t |-|¡}1t |-|¡}2t |-|¡}3d}4d
}5d
}6|6|.k �r^|4�s^|'d8 }'t|-ƒD �]@}| ||6f |0||+f< |'d
k�rœ|+| | | }7t||0| |1| |2| ||||| |!|
|$|"|#|7|(d�}8|8|3||)f< |/| |% |8d|%   |/|< |4�p<|/| |k}4|4�rœ|}9|)}:|9};|9}<d
}=t|9ƒD ]`}=|3||:f |k�rŽ|=|;| k�rŽ|= }<};n |3||:f d
k�r®|;|<k�r®|=}<|:|9 d |9 }:�q`t
|=|<ƒ}=t
t	|5|=ƒ|9ƒ}5�qœ|+d7 }+|6d7 }6|+|k�rþd
}+|'d
k�r<|}'|)d7 })|)| })|(d
k�r<|(|&k�r4dn|(d }(|4�r|||5 | }*|+|* | }+�q|| dd…|6| |* d…f }>|> |,dd… |>jdd…  ¡S )uP  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:
        waveform (Tensor): Tensor of audio of dimension `(..., time)`
        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)

    Returns:
        Tensor: Tensor of audio of dimension (..., time).

    References:
        http://sox.sourceforge.net/sox.html
    Nr3   r�   r(  rH   rˆ   rF   rÄ   rz   r   r0   F)rM  rN  rO  rP  rQ  rR  rS  rT  rU  rV  rW  rX  rY  rZ  r[  r\  rx   )r÷   rQ   r3  r5   rT   r[   r>   r\   Zhann_windowrm   rj   r  r�   r8   rÜ   rd  r;   )?r&   rv   rm  rn  ro  rp  rq  rr  rs  rt  rW  ru  rv  rw  rx  ry  rz  r{  rM  Zmeasure_len_nsrb  Zmeasure_period_nsZmeasures_lenZsearch_pre_trigger_len_nsZgap_lenZfixed_pre_trigger_len_nsr^  rQ  rß   rR  rS  rT  rU  rV  rY  rZ  rX  Ztrigger_meas_time_multZboot_count_maxZmeasure_timer_nsr\  Zmeasures_indexZflushedLen_nsZsamplesIndex_nsr;   r  ZilenZ	mean_measrN  rO  rP  ZmeasuresZhas_triggeredZnum_measures_to_flushÚposr[  Zmeasr„   r…   ZjTriggerZjZeroÚjÚresr?   r?   r@   r%   J  sÔ    Mÿ
þ




ÿð 




r%   )N)N)rx   )rx   )T)r´   )r´   )r´   )r´   F)r´   )r´   )r´   F)rÆ   r´   )rÍ   r´   )rÓ   )N)rØ   rØ   )rà   rá   râ   rà   r�   T)rN   r3   rN   r  r�   r  rè   r  )r  r  )rx   )r&  )r&  F)r;  )rC  rD  rE  rF  )rH  rÍ   FF)re  rf  rx   rf  rN   rg  rp   rC  rh  r±   Nrà   ri  rj  rk  rl  )<rQ   Útypingr   r   r~   r5   r   Ú__all__r÷   r\   Úboolr   r   r   rq   Ústrr   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    rM   rø   r!   r#   r"   r  r¿   r%  r-  r/  r:  r>  rA  rB  rG  r$   rd  r%   r?   r?   r?   r@   Ú<module>   s.  &÷8ôq ûú"ü úùBüýý þýþ þ
ýüO üûKø$ üû! üû! üû%  ûú) üû& ûú$  ûú0  ûú-  ûú*ý0ýA þý# ýü.  ýü:      ø÷Uø9        öõ û+û/  ýü7 þýý þýL  ýüû7 ý


üü"ý    úù+    ûú\ïV                íì