o
    ]ôjŒ%  ã                   @   sª   d Z ddlZddlmZ ddlZddlmZ ddlm	Z	 ddl
mZ G dd	„ d	ejjƒZ		ddejdededededee defdd„Zdd„ Zddd„Zddd„ZdS )a  
Differentiable, Pytorch based resampling.
Implementation of Julius O. Smith algorithm for resampling.
See https://ccrma.stanford.edu/~jos/resample/ for details.
This implementation is specially optimized for when new_sr / old_sr is a fraction
with a small numerator and denominator when removing the gcd (e.g. new_sr = 700, old_sr = 500).

Very similar to [bmcfee/resampy](https://github.com/bmcfee/resampy) except this implementation
is optimized for the case mentioned before, while resampy is slower but more general.

é    N)ÚOptional)Ú
functionalé   )Úsinc©Úsimple_reprc                	       sb   e Zd ZdZddedededef‡ fdd	„Zd
d„ Zddej	de
e defdd„Zdd„ Z‡  ZS )ÚResampleFracz?
    Resampling from the sample rate `old_sr` to `new_sr`.
    é   ç=
×£p=î?Úold_srÚnew_srÚzerosÚrolloffc                    s^   t ƒ  ¡  t|tƒrt|tƒstdƒ‚t ||¡}|| | _|| | _|| _	|| _
|  ¡  dS )a©  
        Args:
            old_sr (int): sample rate of the input signal x.
            new_sr (int): sample rate of the output.
            zeros (int): number of zero crossing to keep in the sinc filter.
            rolloff (float): use a lowpass filter that is `rolloff * new_sr / 2`,
                to ensure sufficient margin due to the imperfection of the FIR filter used.
                Lowering this value will reduce anti-aliasing, but will reduce some of the
                highest frequencies.

        Shape:

            - Input: `[*, T]`
            - Output: `[*, T']` with `T' = int(new_sr * T / old_sr)


        .. caution::
            After dividing `old_sr` and `new_sr` by their GCD, both should be small
            for this implementation to be fast.

        >>> import torch
        >>> resample = ResampleFrac(4, 5)
        >>> x = torch.randn(1000)
        >>> print(len(resample(x)))
        1250
        z$old_sr and new_sr should be integersN)ÚsuperÚ__init__Ú
isinstanceÚintÚ
ValueErrorÚmathÚgcdr   r   r   r   Ú_init_kernels)Úselfr   r   r   r   r   ©Ú	__class__© ú`/var/www/html/academy/tools/voices/clone/sv-venv/lib/python3.10/site-packages/julius/resample.pyr      s   


zResampleFrac.__init__c                 C   s  | j | jkrd S g }t| j| j ƒ}|| j9 }t | j| j  | ¡| _t 	| j | j| j  ¡ 
¡ }t| jƒD ];}| | j || j   | }| | j | j¡}|tj9 }t || j d ¡d }t|ƒ| }| | ¡ ¡ | |¡ q5|  dt |¡ | jdd¡¡ d S )Né   Úkernelr   éÿÿÿÿ)r   r   Úminr   r   Úceilr   Ú_widthÚtorchÚarangeÚfloatÚrangeÚclamp_ÚpiÚcosr   Údiv_ÚsumÚappendÚregister_bufferÚstackÚview)r   ÚkernelsÚsrÚidxÚiÚtÚwindowr   r   r   r   r   C   s    

"zResampleFrac._init_kernelsNFÚxÚoutput_lengthÚfullc                 C   s  | j | jkr|S |j}|jd }| d|¡}tj|dd…df | j| j| j  fdd�}tj|| j| j d�}| 	dd¡ t
|dd… ƒdg ¡}t | j| | j  ¡}t |¡ ¡ }	t |¡ ¡ }
|du rk|rh|	n|
}n|dk ss||	krztd	|	› �ƒ‚t |¡}|r…td
ƒ‚|dd|…f S )a  
        Resample x.
        Args:
            x (Tensor): signal to resample, time should be the last dimension
            output_length (None or int): This can be set to the desired output length
                (last dimension). Allowed values are between 0 and
                ceil(length * new_sr / old_sr). When None (default) is specified, the
                floored output length will be used. In order to select the largest possible
                size, use the `full` argument.
            full (bool): return the longest possible output from the input. This can be useful
                if you chain resampling operations, and want to give the `output_length` only
                for the last one, while passing `full=True` to all the other ones.
        r   NÚ	replicate)Úmode)Ústrider   r   r   z$output_length must be between 0 and z0You cannot pass both full=True and output_length.)r   r   ÚshapeÚreshapeÚFÚpadr!   Úconv1dr   Ú	transposeÚlistr"   Ú	as_tensorr    ÚlongÚfloorr   Útensor)r   r5   r6   r7   r;   ÚlengthÚysÚyZfloat_output_lengthZmax_output_lengthZdefault_output_lengthZapplied_output_lengthr   r   r   Úforwardr   s&   
*$
zResampleFrac.forwardc                 C   s   t | ƒS )Nr   )r   r   r   r   Ú__repr__—   s   zResampleFrac.__repr__)r	   r
   )NF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r$   r   r   r"   ÚTensorr   ÚboolrI   rJ   Ú__classcell__r   r   r   r   r      s     &/%r   r	   r
   Fr5   r   r   r   r   r6   r7   c                 C   s   t ||||ƒ | ¡| ||ƒS )aR  
    Functional version of `ResampleFrac`, refer to its documentation for more information.

    ..warning::
        If you call repeatidly this functions with the same sample rates, then the
        resampling kernel will be recomputed everytime. For best performance, you should use
        and cache an instance of `ResampleFrac`.
    )r   Úto)r5   r   r   r   r   r6   r7   r   r   r   Úresample_frac›   s   rS   c                 C   sd   t jd|  d dd�}|dd d… }t  |  d | d d|  ¡}|tj9 }t|ƒ|  ddd¡}|S )Né   r   F)Úperiodicr   ç      à?r   )r"   Úhann_windowÚlinspacer   r'   r   r.   )r   ÚwinZwinoddr3   r   r   r   r   Ú_kernel_upsample2_downsample2¬   s   
rZ   c                 C   sv   | j �^ }}t|ƒ | ¡}tj|  dd|¡||d�ddd…f jg |¢|‘R Ž }tj| |gdd�}|jg |¢d‘R Ž S )aœ  
    Upsample x by a factor of two. The output will be exactly twice as long as the input.
    Args:
        x (Tensor): signal to upsample, time should be the last dimension
        zeros (int): number of zero crossing to keep in the sinc filter.

    This function is kept only for reference, you should use the more generic `resample_frac`
    one. This function does not perform anti-aliasing filtering.
    r   r   ©Úpadding.N)Údim)r;   rZ   rR   r=   r?   r.   r"   r-   )r5   r   ÚotherÚtimer   ÚoutrH   r   r   r   Ú
_upsample2·   s
   
6ra   c                 C   s°   | j d d dkrt | d¡} | dddd…f }| dddd…f }|j �^ }}t|ƒ | ¡}|tj| dd|¡||d�ddd…f jg |¢|‘R Ž  }|jg |¢d‘R Ž  d	¡S )
a™  
    Downsample x by a factor of two. The output length is half of the input, ceiled.
    Args:
        x (Tensor): signal to downsample, time should be the last dimension
        zeros (int): number of zero crossing to keep in the sinc filter.

    This function is kept only for reference, you should use the more generic `resample_frac`
    one. This function does not perform anti-aliasing filtering.
    r   r   r   )r   r   .Nr   r[   rV   )r;   r=   r>   rZ   rR   r?   r.   Úmul)r5   r   ZxevenZxoddr^   r_   r   r`   r   r   r   Ú_downsample2È   s   
*ÿ
ÿrc   )r	   r
   NF)r	   )rN   r   Útypingr   r"   Útorch.nnr   r=   Úcorer   Úutilsr   ÚnnÚModuler   rO   r   r$   rP   rS   rZ   ra   rc   r   r   r   r   Ú<module>   s.    þÿÿþ
þ
