a
    âñh°À  ã                   @   s–  d dl mZ d dlZd dlZd dlZd dlmZ g d¢Ze e ej	¡j
¡ZdZdZdZdZd	Zd
ZeeeeegZdd„ Zeedœdd„Zeeeeedœdd„Zeee	ejeedœdd„Zeee	edœdd„Zeee	e	e	ee	eeeeef dœdd„Zeeeeee	eee	e	ee	eeef dœdd„Zeeedœd d!„Zd"d#d$d%d&d'd$d(d)d)d)d*d)d+efee	ee	e	e	e	e	e	eeee	eeeed,œd-d.„Ze	e	d/œd0d1„Z eed/œd2d3„Z!e	e	d4œd5d6„Z"eed4œd7d8„Z#e	e	e	e	e	eed9œd:d;„Z$e	e	e	e	eed<œd=d>„Z%eee	e	e	e	e	e	eeef d?œ	d@dA„Z&d"d#d$d%d&d'd$d+dBd$dCd(d)d)d)d*d)d+d+d)d)dDdEd%efee	ee	e	e	e	e	ee	e	ee	eeee	eeeeee	e	e	eedFœdGdH„Z'eeedIœdJdK„Z(ee	edLœdMdN„Z)d"dOd#d$d%d&d'd$d+dBdPd$dCd(d)d)d)d*d)d+d+dDdEd%efee	e	ee	e	e	e	e	ee	ee	ee	eeee	eeee	e	e	eedQœdRdS„Z*e	e	ee	e	eejeeeef dTœ	dUdV„Z+eeedWœdXdY„Z,ee	e	edZœd[d\„Z-daee	e	eed^œd_d`„Z.dS )bé    )ÚTupleN)ÚTensor)Úget_mel_banksÚinverse_mel_scaleÚinverse_mel_scale_scalarÚ	mel_scaleÚmel_scale_scalarÚspectrogramÚfbankÚmfccÚvtln_warp_freqÚvtln_warp_mel_freqÚresample_waveformgü©ñÒMbP?ZhammingZhanningZpoveyZrectangularZblackmanc                 C   s   t j| |d�S )N©ÚdeviceÚdtype)ÚEPSILONÚtor   © r   ú[/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchaudio/compliance/kaldi.pyÚ_get_epsilon$   s    r   )ÚxÚreturnc                 C   s   | dkrdS d| d   ¡  S )z;Returns the smallest power of 2 that is greater than x
    r   é   é   )Ú
bit_length)r   r   r   r   Ú_next_power_of_2(   s    r   )ÚwaveformÚwindow_sizeÚwindow_shiftÚ
snip_edgesr   c                 C   sò   |   ¡ dksJ ‚|  d¡}||  d¡ |  d¡f}|rd||k rRtjd| j| jd�S d|| |  }nzt | dg¡}||d  | }|d |d  }|}	|dkrÂ|| d… }
tj|
| |	fdd�} ntj| | d… |	fdd�} ||f}|  	||¡S )aÝ  Given a waveform (1D tensor of size ``num_samples``), it returns a 2D tensor (m, ``window_size``)
    representing how the window is shifted along the waveform. Each row is a frame.

    Args:
        waveform (Tensor): Tensor of size ``num_samples``
        window_size (int): Frame length
        window_shift (int): Frame shift
        snip_edges (bool): If True, end effects will be handled by outputting only frames that completely fit
            in the file, and the number of frames depends on the frame_length.  If False, the number of frames
            depends only on the frame_shift, and we reflect the data at the ends.

    Returns:
        Tensor: 2D tensor of size (m, ``window_size``) where each row is a frame
    r   r   )r   r   ©r   r   r   N©Údim)
r#   ÚsizeÚstrideÚtorchÚemptyr   r   ZflipÚcatZ
as_strided)r   r   r   r    Znum_samplesÚstridesÚmZreversed_waveformÚpadZ	pad_rightZpad_leftÚsizesr   r   r   Ú_get_strided.   s"    
r-   )Úwindow_typer   Úblackman_coeffr   r   r   c                 C   sä   | t krtj|d||d�S | tkr8tj|ddd||d�S | tkrXtj|d||d� d¡S | tkrptj|||d�S | t	krÔdt
j |d	  }tj|||d�}|d
t || ¡  d
| t d| | ¡  j||d�S td|  ƒ‚dS )z;Returns a window function with the given type and size
    F)Úperiodicr   r   gHáz®Gá?gq=
×£pÝ?)r0   ÚalphaÚbetar   r   g333333ë?r   r   r   ç      à?zInvalid window type N)ÚHANNINGr&   Zhann_windowÚHAMMINGZhamming_windowÚPOVEYÚpowÚRECTANGULARZonesÚBLACKMANÚmathÚpiÚarangeÚcosr   Ú	Exception)r.   r   r/   r   r   ÚaÚwindow_functionr   r   r   Ú_feature_window_functionX   s"    ÿÿrA   )Ústrided_inputÚepsilonÚenergy_floorr   c                 C   sT   | j | j }}t |  d¡ d¡|¡ ¡ }|dkr6|S t |tjt |¡||d�¡S )zAReturns the log energy of size (m) for a strided_input (m,*)
    r   r   ç        r   )	r   r   r&   Úmaxr7   ÚsumÚlogÚtensorr:   )rB   rC   rD   r   r   Z
log_energyr   r   r   Ú_get_log_energys   s    ÿrJ   )r   ÚchannelÚsample_frequencyÚframe_shiftÚframe_lengthÚround_to_power_of_twoÚpreemphasis_coefficientr   c           
      C   sú   t |dƒ}||  d¡k s.J d ||  d¡¡ƒ‚| |dd…f } t|| t ƒ}t|| t ƒ}|rjt|ƒn|}	d|  kr†t| ƒksœn J d |t| ƒ¡ƒ‚d|k s¬J dƒ‚|	d dksÀJ dƒ‚d|  krÔd	ksÞn J d
ƒ‚|dksîJ dƒ‚| |||	fS )z,Gets the waveform and window properties
    r   zInvalid channel {} for size {}Nr   z'choose a window size {} that is [2, {}]z%`window_shift` must be greater than 0zgthe padded `window_size` must be divisible by two. use `round_to_power_of_two` or change `frame_length`rE   ç      ð?z/`preemphasis_coefficient` must be between [0,1]z,`sample_frequency` must be greater than zero)rF   r$   ÚformatÚintÚMILLISECONDS_TO_SECONDSr   Úlen)
r   rK   rL   rM   rN   rO   rP   r   r   Úpadded_window_sizer   r   r   Ú#_get_waveform_and_window_properties€   s$    	
$ÿÿÿrW   )r   rV   r   r   r.   r/   r    Ú
raw_energyrD   ÚditherÚremove_dc_offsetrP   r   c                 C   s^  | j | j }}t||ƒ}t| |||ƒ}|	dkrzt |tj|j||d�¡}t d| 	¡  ¡t 
dtj | ¡ }|||	  }|
rštj|dd� d¡}|| }|rªt|||ƒ}|dkrîtjjj| d¡dd	d
� d¡}|||dd…dd…f   }t|||||ƒ d¡}|| }||k�rD|| }tjjj| d¡d|fddd� d¡}|�sVt|||ƒ}||fS )z¡Gets a window and its log energy

    Returns:
        (Tensor, Tensor): strided_input of size (m, ``padded_window_size``) and signal_log_energy of size (m)
    rE   r   éþÿÿÿr   r   r"   r   )r   r   Z	replicate)ÚmodeNéÿÿÿÿÚconstant©r\   Úvalue)r   r   r   r-   r&   rF   ZrandÚshapeÚsqrtrH   r=   r:   r;   ÚmeanÚ	unsqueezerJ   ÚnnÚ
functionalr+   ÚsqueezerA   )r   rV   r   r   r.   r/   r    rX   rD   rY   rZ   rP   r   r   rC   rB   r   Z
rand_gaussZ	row_meansÚsignal_log_energyZoffset_strided_inputr@   Zpadding_rightr   r   r   Ú_get_window›   sF    
&ÿÿ
ÿÿ
ÿÿri   )rI   Úsubtract_meanr   c                 C   s$   |r t j| dd� d¡}| | } | S )Nr   r"   )r&   rc   rd   )rI   rj   Z	col_meansr   r   r   Ú_subtract_column_meanÚ   s    rk   gáz®GáÚ?r]   rE   rQ   g      9@g      $@g
×£p=
ï?Tg     @Ï@F)r   r/   rK   rY   rD   rN   rM   Úmin_durationrP   rX   rZ   rO   rL   r    rj   r.   r   c                 C   s¼   | j | j }}t||ƒ}t| ||||||ƒ\} }}}t| ƒ|| k rNt d¡S t| |||||||	|||
|ƒ\}}tj|dddd�}t 	| 
d¡ d¡|¡ ¡ }||dd…df< t||ƒ}|S )a¢
  Create a spectrogram from a raw audio signal. This matches the input/output of Kaldi's
    compute-spectrogram-feats.

    Args:
        waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
        blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
        channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
        dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
            the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
        energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation.  Caution:
            this floor is applied to the zeroth component, representing the total signal energy.  The floor on the
            individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
        frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
        frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
        min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
        preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
        raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
        remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
        round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
            to FFT. (Default: ``True``)
        sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
            specified there) (Default: ``16000.0``)
        snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
            in the file, and the number of frames depends on the frame_length.  If False, the number of frames
            depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
        subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
            it this way.  (Default: ``False``)
        window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
         (Default: ``'povey'``)

    Returns:
        Tensor: A spectrogram identical to what Kaldi would output. The shape is
        (m, ``padded_window_size // 2 + 1``) where m is calculated in _get_strided
    r   r   FT©Ú
normalizedZonesidedr   N)r   r   r   rW   rU   r&   r'   ri   ÚrfftrF   r7   rG   rH   rk   )r   r/   rK   rY   rD   rN   rM   rl   rP   rX   rZ   rO   rL   r    rj   r.   r   r   rC   r   r   rV   rB   rh   ÚfftÚpower_spectrumr   r   r   r	   ã   s     2
ÿ
þ
r	   )Úmel_freqr   c                 C   s   dt  | d ¡d  S ©Nç     à…@ç     œ‘@rQ   )r:   Úexp©rr   r   r   r   r   .  s    r   c                 C   s   d| d   ¡ d  S rs   )rv   rw   r   r   r   r   2  s    r   )Úfreqr   c                 C   s   dt  d| d  ¡ S ©Nru   rQ   rt   )r:   rH   ©rx   r   r   r   r   6  s    r   c                 C   s   dd| d    ¡  S ry   )rH   rz   r   r   r   r   :  s    r   )Úvtln_low_cutoffÚvtln_high_cutoffÚlow_freqÚ	high_freqÚvtln_warp_factorrx   r   c                 C   s  | |ksJ dƒ‚||k s J dƒ‚| t d|ƒ }|td|ƒ }d| }|| }	|| }
||krd||k shJ ‚|	| ||  }||
 ||  }t |¡}t ||¡t ||¡B }t ||¡}t ||¡}t ||¡}|||| |   ||< |||  ||< |||| |   ||< || ||< |S )a*  This computes a VTLN warping function that is not the same as HTK's one,
    but has similar inputs (this function has the advantage of never producing
    empty bins).

    This function computes a warp function F(freq), defined between low_freq
    and high_freq inclusive, with the following properties:
        F(low_freq) == low_freq
        F(high_freq) == high_freq
    The function is continuous and piecewise linear with two inflection
        points.
    The lower inflection point (measured in terms of the unwarped
        frequency) is at frequency l, determined as described below.
    The higher inflection point is at a frequency h, determined as
        described below.
    If l <= f <= h, then F(f) = f/vtln_warp_factor.
    If the higher inflection point (measured in terms of the unwarped
        frequency) is at h, then max(h, F(h)) == vtln_high_cutoff.
        Since (by the last point) F(h) == h/vtln_warp_factor, then
        max(h, h/vtln_warp_factor) == vtln_high_cutoff, so
        h = vtln_high_cutoff / max(1, 1/vtln_warp_factor).
          = vtln_high_cutoff * min(1, vtln_warp_factor).
    If the lower inflection point (measured in terms of the unwarped
        frequency) is at l, then min(l, F(l)) == vtln_low_cutoff
        This implies that l = vtln_low_cutoff / min(1, 1/vtln_warp_factor)
                            = vtln_low_cutoff * max(1, vtln_warp_factor)
    Args:
        vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
        vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
        low_freq (float): Lower frequency cutoffs in mel computation
        high_freq (float): Upper frequency cutoffs in mel computation
        vtln_warp_factor (float): Vtln warp factor
        freq (Tensor): given frequency in Hz

    Returns:
        Tensor: Freq after vtln warp
    z7be sure to set the vtln_low option higher than low_freqzFbe sure to set the vtln_high option lower than high_freq [or negative]rQ   )rF   Úminr&   Z
empty_likeÚltÚgtÚge)r{   r|   r}   r~   r   rx   ÚlÚhZscaleZFlZFhZ
scale_leftZscale_rightÚresZoutside_low_high_freqZbefore_lZbefore_hZafter_hr   r   r   r   >  s(    *
r   )r{   r|   r~   r   rr   r   c              	   C   s   t t| ||||t|ƒƒƒS )a¿  
    Args:
        vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
        vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
        low_freq (float): Lower frequency cutoffs in mel computation
        high_freq (float): Upper frequency cutoffs in mel computation
        vtln_warp_factor (float): Vtln warp factor
        mel_freq (Tensor): Given frequency in Mel

    Returns:
        Tensor: ``mel_freq`` after vtln warp
    )r   r   r   )r{   r|   r}   r~   r   rr   r   r   r   r   ‡  s    ÿr   )	Únum_binsÚwindow_length_paddedÚsample_freqr}   r~   Úvtln_lowÚ	vtln_highr   r   c                 C   sZ  | dksJ dƒ‚|d dks J ‚|d }d| }	|dkr@||	7 }d|  krT|	k rxn n d|  k rl|	krxn n||k sŠJ d  |||	¡ƒ‚|| }
t|ƒ}t|ƒ}|| | d  }|dk rÂ||	7 }|d	k�s||  k râ|k �r
n n$d|  k rü|k �r
n n
||k �sJ d
  ||||¡ƒ‚t | ¡ d¡}|||  }||d	 |  }||d |  }|d	k�ršt||||||ƒ}t||||||ƒ}t||||||ƒ}t|ƒ}t|
t |¡ ƒ d¡}|| ||  }|| ||  }|d	k�r t t 	d¡t 
||¡¡}nRt |¡}t ||¡t ||¡@ }t ||¡t ||¡@ }|| ||< || ||< ||fS )zê
    Returns:
        (Tensor, Tensor): The tuple consists of ``bins`` (which is
        melbank of size (``num_bins``, ``num_fft_bins``)) and ``center_freqs`` (which is
        center frequencies of bins of size (``num_bins``)).
    é   zMust have at least 3 mel binsr   r   r3   rE   zBBad values in options: low-freq {} and high-freq {} vs. nyquist {}r   rQ   zXBad values in options: vtln-low {} and vtln-high {}, versus low-freq {} and high-freq {}ç       @)rR   r   r&   r<   rd   r   r   r   rF   Úzerosr€   Ú
zeros_liker‚   Úler�   )r‡   rˆ   r‰   r}   r~   rŠ   r‹   r   Znum_fft_binsZnyquistZfft_bin_widthZmel_low_freqZmel_high_freqZmel_freq_deltaÚbinZleft_melZ
center_melZ	right_melZcenter_freqsZmelZup_slopeZ
down_slopeZbinsZup_idxZdown_idxr   r   r   r   œ  s\    :ÿ$ÿÿÿÿþ


r   g      4@é   g     @Àg      Y@)r   r/   rK   rY   rD   rN   rM   r~   Ú
htk_compatr}   rl   Únum_mel_binsrP   rX   rZ   rO   rL   r    rj   Ú
use_energyÚuse_log_fbankÚ	use_powerr‹   rŠ   Ú	vtln_warpr.   r   c           %      C   sN  | j | j }}t| ||||||ƒ\} }}}t| ƒ|
| k rJtjd||d�S t| |||||||||||ƒ\}} tj|dddd�}!|! d¡ 	d¡}"|sœ|" d¡}"t
||||	||||ƒ\}#}$|#j||d�}#tjjj|#d	d
dd�}#t |"|#j¡}#|�rt |#t||ƒ¡ ¡ }#|�r@|  d¡} |�r.tj|#| fdd�}#ntj| |#fdd�}#t|#|ƒ}#|#S )ab  Create a fbank from a raw audio signal. This matches the input/output of Kaldi's
    compute-fbank-feats.

    Args:
        waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
        blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
        channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
        dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
            the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
        energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation.  Caution:
            this floor is applied to the zeroth component, representing the total signal energy.  The floor on the
            individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
        frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
        frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
        high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
         (Default: ``0.0``)
        htk_compat (bool, optional): If true, put energy last.  Warning: not sufficient to get HTK compatible features
         (need to change other parameters). (Default: ``False``)
        low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
        min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
        num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
        preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
        raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
        remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
        round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
            to FFT. (Default: ``True``)
        sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
            specified there) (Default: ``16000.0``)
        snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
            in the file, and the number of frames depends on the frame_length.  If False, the number of frames
            depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
        subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
            it this way.  (Default: ``False``)
        use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
        use_log_fbank (bool, optional):If true, produce log-filterbank, else produce linear. (Default: ``True``)
        use_power (bool, optional): If true, use power, else use magnitude. (Default: ``True``)
        vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
            negative, offset from high-mel-freq (Default: ``-500.0``)
        vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
        vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
        window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
         (Default: ``'povey'``)

    Returns:
        Tensor: A fbank identical to what Kaldi would output. The shape is (m, ``num_mel_bins + use_energy``)
        where m is calculated in _get_strided
    r   r   r   FTrm   r   r3   )r   r   r^   r_   r"   )r   r   rW   rU   r&   r'   ri   ro   r7   rG   r   r   re   rf   r+   ÚmmÚTrF   r   rH   rd   r(   rk   )%r   r/   rK   rY   rD   rN   rM   r~   r“   r}   rl   r”   rP   rX   rZ   rO   rL   r    rj   r•   r–   r—   r‹   rŠ   r˜   r.   r   r   r   r   rV   rB   rh   rp   rq   Zmel_energiesÚ_r   r   r   r
   æ  s:    Iÿþ

ÿ

r
   )Únum_cepsr”   r   c                 C   sF   t j ||d¡}t dt|ƒ ¡|d d …df< |d d …d | …f }|S )NZorthor   r   )Ú
torchaudiorf   Z
create_dctr:   rb   Úfloat)rœ   r”   Ú
dct_matrixr   r   r   Ú_get_dct_matrix_  s    r    )rœ   Úcepstral_lifterr   c                 C   s*   t  | ¡}dd| t  tj| | ¡  S )NrQ   r3   )r&   r<   Úsinr:   r;   )rœ   r¡   Úir   r   r   Ú_get_lifter_coeffsl  s    
r¤   g      6@é   )r   r/   r¡   rK   rY   rD   rN   rM   r~   r“   r}   rœ   rl   r”   rP   rX   rZ   rO   rL   r    rj   r•   r‹   rŠ   r˜   r.   r   c           "      C   s`  ||ksJ d||f ƒ‚| j | j }}t| ||||||||	|
||||||||d|dd||||d�}|r |dd…|	rv|ndf }t|	 ƒ}|dd…||| …f }t||ƒj||d�}| |¡}|dkrèt||ƒ d¡} || j||d	�9 }|rü||dd…df< |	�rR|dd…df  d
¡}!|dd…d
d…f }|�s@|!t	 
d¡9 }!tj||!fd
d�}t||ƒ}|S )aM  Create a mfcc from a raw audio signal. This matches the input/output of Kaldi's
    compute-mfcc-feats.

    Args:
        waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
        blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
        cepstral_lifter (float, optional): Constant that controls scaling of MFCCs (Default: ``22.0``)
        channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
        dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
            the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
        energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation.  Caution:
            this floor is applied to the zeroth component, representing the total signal energy.  The floor on the
            individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
        frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
        frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
        high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
         (Default: ``0.0``)
        htk_compat (bool, optional): If true, put energy last.  Warning: not sufficient to get HTK compatible
         features (need to change other parameters). (Default: ``False``)
        low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
        num_ceps (int, optional): Number of cepstra in MFCC computation (including C0) (Default: ``13``)
        min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
        num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
        preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
        raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
        remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
        round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
            to FFT. (Default: ``True``)
        sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
            specified there) (Default: ``16000.0``)
        snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
            in the file, and the number of frames depends on the frame_length.  If False, the number of frames
            depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
        subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
            it this way.  (Default: ``False``)
        use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
        vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
            negative, offset from high-mel-freq (Default: ``-500.0``)
        vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
        vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
        window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
         (Default: ``"povey"``)

    Returns:
        Tensor: A mfcc identical to what Kaldi would output. The shape is (m, ``num_ceps``)
        where m is calculated in _get_strided
    z5num_ceps cannot be larger than num_mel_bins: %d vs %dFT)r   r/   rK   rY   rD   rN   rM   r~   r“   r}   rl   r”   rP   rX   rZ   rO   rL   r    rj   r•   r–   r—   r‹   rŠ   r˜   r.   Nr   r!   rE   r   r   r   r"   )r   r   r
   rS   r    r   Úmatmulr¤   rd   r:   rb   r&   r(   rk   )"r   r/   r¡   rK   rY   rD   rN   rM   r~   r“   r}   rœ   rl   r”   rP   rX   rZ   rO   rL   r    rj   r•   r‹   rŠ   r˜   r.   r   r   Úfeaturerh   Z
mel_offsetrŸ   Zlifter_coeffsZenergyr   r   r   r   t  s>    Jø



r   )	Ú	orig_freqÚnew_freqÚoutput_samples_in_unitÚwindow_widthÚlowpass_cutoffÚlowpass_filter_widthr   r   r   c                 C   sP  |t | |ƒd k sJ ‚tjd|||d�| }|| }	|| }
t |	|  ¡}t |
|  ¡}|| d }| ¡ }tj|||d� d¡}| d¡| }||  | d¡ }t |¡}| ¡  	|¡}ddt 
dtj | | ||  ¡  ||< | d¡}| }||  t dtj | ||  ¡tj||   9  < ||  d| 9  < ||  }||fS )a
  Based on LinearResample::SetIndexesAndWeights where it retrieves the weights for
    resampling as well as the indices in which they are valid. LinearResample (LR) means
    that the output signal is at linearly spaced intervals (i.e the output signal has a
    frequency of ``new_freq``). It uses sinc/bandlimited interpolation to upsample/downsample
    the signal.

    The reason why the same filter is not used for multiple convolutions is because the
    sinc function could sampled at different points in time. For example, suppose
    a signal is sampled at the timestamps (seconds)
    0         16        32
    and we want it to be sampled at the timestamps (seconds)
    0 5 10 15   20 25 30  35
    at the timestamp of 16, the delta timestamps are
    16 11 6 1   4  9  14  19
    at the timestamp of 32, the delta timestamps are
    32 27 22 17 12 8 2    3

    As we can see from deltas, the sinc function is sampled at different points of time
    assuming the center of the sinc function is at 0, 16, and 32 (the deltas [..., 6, 1, 4, ....]
    for 16 vs [...., 2, 3, ....] for 32)

    Example, one case is when the ``orig_freq`` and ``new_freq`` are multiples of each other then
    there needs to be one filter.

    A windowed filter function (i.e. Hanning * sinc) because the ideal case of sinc function
    has infinite support (non-zero for all values) so instead it is truncated and multiplied by
    a window function which gives it less-than-perfect rolloff [1].

    [1] Chapter 16: Windowed-Sinc Filters, https://www.dspguide.com/ch16/1.htm

    Args:
        orig_freq (float): The original frequency of the signal
        new_freq (float): The desired frequency
        output_samples_in_unit (int): The number of output samples in the smallest repeating unit:
            num_samp_out = new_freq / Gcd(orig_freq, new_freq)
        window_width (float): The width of the window which is nonzero
        lowpass_cutoff (float): The filter cutoff in Hz. The filter cutoff needs to be less
            than samp_rate_in_hz/2 and less than samp_rate_out_hz/2.
        lowpass_filter_width (int): Controls the sharpness of the filter, more == sharper but less
            efficient. We suggest around 4 to 10 for normal use

    Returns:
        (Tensor, Tensor): A tuple of ``min_input_index`` (which is the minimum indices
        where the window is valid, size (``output_samples_in_unit``)) and ``weights`` (which is the weights
        which correspond with min_input_index, size (``output_samples_in_unit``, ``max_weight_width``)).
    r   rE   r   r   r   r3   )r€   r&   r<   ÚceilÚfloorrF   rd   r�   Úabsr�   r=   r:   r;   Úeqr¢   )r¨   r©   rª   r«   r¬   r­   r   r   Zoutput_tZmin_tZmax_tZmin_input_indexZmax_input_indexZnum_indicesZmax_weight_widthÚjZinput_indexZdelta_tÚweightsZinside_window_indicesZt_eq_zero_indicesZt_not_eq_zero_indicesr   r   r   Ú_get_LR_indices_and_weightsó  s8    6
ÿÿ
ÿÿr´   )r?   Úbr   c                 C   s   t | | ƒt | |¡ S )N)r°   r:   Úgcd)r?   rµ   r   r   r   Ú_lcmJ  s    r·   )Úinput_num_sampÚsamp_rate_inÚsamp_rate_outr   c           	      C   sf   t |ƒ}t |ƒ}t||ƒ}|| }| | }|dkr6dS || }|| }|| |krZ|d8 }|d }|S )a  Based on LinearResample::GetNumOutputSamples. LinearResample (LR) means that
    the output signal is at linearly spaced intervals (i.e the output signal has a
    frequency of ``new_freq``). It uses sinc/bandlimited interpolation to upsample/downsample
    the signal.

    Args:
        input_num_samp (int): The number of samples in the input
        samp_rate_in (float): The original frequency of the signal
        samp_rate_out (float): The desired frequency

    Returns:
        int: The number of output samples
    r   r   )rS   r·   )	r¸   r¹   rº   Z	tick_freqZticks_per_input_periodZinterval_length_in_ticksZticks_per_output_periodZlast_output_sampZnum_output_sampr   r   r   Ú_get_num_LR_output_samplesN  s    
r»   é   )r   r¨   r©   r­   r   c           !   	   C   sF  | j | j }}|  ¡ dksJ ‚|dkr.|dks2J ‚t||ƒ}d| }|d |ksTJ ‚t t|ƒt|ƒ¡}t|ƒ| }	t|ƒ| }
|d|  }t|||
|||||ƒ\}}| ¡ dks¶J ‚|	}|
}|  ¡ \}}| d¡}t	|||ƒ}t
j||f||d�}t
j|||d� d¡}t| d¡ƒD �]&}| }t||  ¡ ƒ}|dk�rL|d|d	…f }|d |
 }|| | }|| }td|d | ƒ}td| ƒ}|dk�sž|dk�r²t
jj |||f¡}t
jjj| d¡||  |dd¡||d
�}t
jjj|||d� d¡}| d¡} |}td|||   ƒ}t
jj |||f¡dd	|…f }||7 }�q|S )a  Resamples the waveform at the new frequency. This matches Kaldi's OfflineFeatureTpl ResampleWaveform
    which uses a LinearResample (resample a signal at linearly spaced intervals to upsample/downsample
    a signal). LinearResample (LR) means that the output signal is at linearly spaced intervals (i.e
    the output signal has a frequency of ``new_freq``). It uses sinc/bandlimited interpolation to
    upsample/downsample the signal.

    https://ccrma.stanford.edu/~jos/resample/Theory_Ideal_Bandlimited_Interpolation.html
    https://github.com/kaldi-asr/kaldi/blob/master/src/feat/resample.h#L56

    Args:
        waveform (Tensor): The input signal of size (c, n)
        orig_freq (float): The original frequency of the signal
        new_freq (float): The desired frequency
        lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper
            but less efficient. We suggest around 4 to 10 for normal use. (Default: ``6``)

    Returns:
        Tensor: The waveform at the new frequency
    r   rE   g®Gáz®ß?r�   r   r   r   .N)r%   Úgroups)r%   r]   )r   r   r#   r€   r:   r¶   rS   r´   r$   r»   r&   rŽ   Úeyerd   ÚrangeÚitemrF   re   rf   r+   Zconv1dÚrepeatZconv_transpose1drg   )!r   r¨   r©   r­   r   r   Zmin_freqr¬   Z	base_freqZinput_samples_in_unitrª   r«   Zfirst_indicesr³   Zconv_strideZconv_transpose_strideZnum_channelsZwave_lenr   Ztot_output_sampÚoutputr¾   r£   Zwave_to_convZfirst_indexZmax_unit_indexZend_index_of_last_windowZcurrent_wave_lenZright_paddingZleft_paddingZ	conv_waveZdilated_conv_waveZdialated_conv_wave_lenr   r   r   r   |  sn    

þ

ÿ
þÿÿ
ÿ
ÿr   )r¼   )/Útypingr   r:   r&   r�   r   Ú__all__rI   Zfinforž   Zepsr   rT   r5   r4   r6   r8   r9   ÚWINDOWSr   rS   r   Úboolr-   Ústrr   rA   rJ   rW   ri   rk   r	   r   r   r   r   r   r   r   r
   r    r¤   r   r´   r·   r»   r   r   r   r   r   Ú<module>   sÔ  *ûþúõ?
ññKûIüùKççy
ææùWþ1 ýý