U
    CŒÑhó3  ã                   @   sô   d dl Z d dlmZ d dlmZmZmZmZmZm	Z	 d dl
Z
d dlmZ d dlmZ d dlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ edƒeeee f dœdd„ƒZedœdd„Zdd„ Z dd„ Z!dd„ Z"dS )é    N)Ú	lru_cache)ÚBinaryIOÚDictÚOptionalÚTupleÚTypeÚUnion)Úlazy_import_sox_ext)ÚCodecConfig)Úlazy_import_ffmpeg_exté   )Úsoundfile_backend)ÚBackend)ÚAudioMetaData)ÚFFmpegBackend)ÚSoundfileBackend)Ú
SoXBackend)Úreturnc                  C   s:   i } t ƒ  ¡ rt| d< tƒ  ¡ r(t| d< tjr6t| d< | S )NÚffmpegÚsoxÚ	soundfile)r   Zis_availabler   r	   r   r   Z_IS_SOUNDFILE_AVAILABLEr   )Zbackend_specs© r   úG/tmp/user/2202/pip-unpacked-wheel-p89lpdx5/torchaudio/_backend/utils.pyÚget_available_backends   s    

r   c                 C   s8   |  | ¡ }r|S td| › d�dt| ¡ ƒ› d�ƒ‚d S )NzUnsupported backend 'z' specified; zplease select one of z	 instead.)ÚgetÚ
ValueErrorÚlistÚkeys)Úbackend_nameÚbackendsÚbackendr   r   r   Úget_backend    s    
þr!   c                     sf   t ƒ ‰ ttttjf tt tt tdœ‡ fdd„‰dttttjf tt ttt t	dœ‡fdd„} | S )	N©ÚuriÚformatr   r   c                    sN   |d k	rt |ˆ ƒS ˆ  ¡ D ]}| | |¡r|  S qtd| › d|› d�ƒ‚d S ©Nz0Couldn't find appropriate backend to handle uri z and format Ú.©r!   ÚvaluesZ
can_decodeÚRuntimeError©r#   r$   r   r    ©r   r   r   Ú
dispatcher-   s    

z!get_info_func.<locals>.dispatcheré   )r#   r$   Úbuffer_sizer    r   c                    s   ˆ | ||ƒ}|  | ||¡S )a­  Get signal information of an audio file.

        Note:
            When the input type is file-like object, this function cannot
            get the correct length (``num_samples``) for certain formats,
            such as ``vorbis``.
            In this case, the value of ``num_samples`` is ``0``.

        Args:
            uri (path-like object or file-like object):
                Source of audio data. The following types are accepted:

                * ``path-like``: File path or URL.
                * ``file-like``: Object with ``read(size: int) -> bytes`` method,
                  which returns byte string of at most ``size`` length.

            format (str or None, optional):
                If not ``None``, interpreted as hint that may allow backend to override the detected format.
                (Default: ``None``)

            buffer_size (int, optional):
                Size of buffer to use when processing file-like objects, in bytes. (Default: ``4096``)

            backend (str or None, optional):
                I/O backend to use.
                If ``None``, function selects backend given input and available backends.
                Otherwise, must be one of [``"ffmpeg"``, ``"sox"``, ``"soundfile"``],
                with the corresponding backend available.
                (Default: ``None``)

                .. seealso::
                   :ref:`backend`

        Returns:
            AudioMetaData
        ©Úinfo)r#   r$   r.   r    ©r,   r   r   r0   8   s    *zget_info_func.<locals>.info)Nr-   N)
r   r   r   ÚstrÚosÚPathLiker   r   Úintr   r/   r   ©r   r,   r   Úget_info_func*   s"      þ   üû-r7   c                     sx   t ƒ ‰ ttttjf tt tt tdœ‡ fdd„‰dttttjf ttt	t	tt ttt t
tjtf dœ	‡fd	d
„} | S )Nr"   c                    sN   |d k	rt |ˆ ƒS ˆ  ¡ D ]}| | |¡r|  S qtd| › d|› d�ƒ‚d S r%   r'   r*   r+   r   r   r,   k   s    

z!get_load_func.<locals>.dispatcherr   éÿÿÿÿTr-   )	r#   Úframe_offsetÚ
num_framesÚ	normalizeÚchannels_firstr$   r.   r    r   c              	      s"   ˆ | ||ƒ}|  | ||||||¡S )a  Load audio data from source.

        By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with
        ``float32`` dtype, and the shape of `[channel, time]`.

        Note:
            The formats this function can handle depend on the availability of backends.
            Please use the following functions to fetch the supported formats.

            - FFmpeg: :py:func:`torchaudio.utils.ffmpeg_utils.get_audio_decoders`
            - Sox: :py:func:`torchaudio.utils.sox_utils.list_read_formats`
            - SoundFile: Refer to `the official document <https://pysoundfile.readthedocs.io/>`__.

        .. warning::

            ``normalize`` argument does not perform volume normalization.
            It only converts the sample type to `torch.float32` from the native sample
            type.

            When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit
            signed integer, 24-bit signed integer, and 8-bit unsigned integer, by providing ``normalize=False``,
            this function can return integer Tensor, where the samples are expressed within the whole range
            of the corresponding dtype, that is, ``int32`` tensor for 32-bit signed PCM,
            ``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM. Since torch does not
            support ``int24`` dtype, 24-bit signed PCM are converted to ``int32`` tensors.

            ``normalize`` argument has no effect on 32-bit floating-point WAV and other formats, such as
            ``flac`` and ``mp3``.

            For these formats, this function always returns ``float32`` Tensor with values.


        Args:
            uri (path-like object or file-like object):
                Source of audio data.
            frame_offset (int, optional):
                Number of frames to skip before start reading data.
            num_frames (int, optional):
                Maximum number of frames to read. ``-1`` reads all the remaining samples,
                starting from ``frame_offset``.
                This function may return the less number of frames if there is not enough
                frames in the given file.
            normalize (bool, optional):
                When ``True``, this function converts the native sample type to ``float32``.
                Default: ``True``.

                If input file is integer WAV, giving ``False`` will change the resulting Tensor type to
                integer type.
                This argument has no effect for formats other than integer WAV type.

            channels_first (bool, optional):
                When True, the returned Tensor has dimension `[channel, time]`.
                Otherwise, the returned Tensor's dimension is `[time, channel]`.

            format (str or None, optional):
                If not ``None``, interpreted as hint that may allow backend to override the detected format.
                (Default: ``None``)

            buffer_size (int, optional):
                Size of buffer to use when processing file-like objects, in bytes. (Default: ``4096``)

            backend (str or None, optional):
                I/O backend to use.
                If ``None``, function selects backend given input and available backends.
                Otherwise, must be one of [``"ffmpeg"``, ``"sox"``, ``"soundfile"``],
                with the corresponding backend being available. (Default: ``None``)

                .. seealso::
                   :ref:`backend`

        Returns:
            (torch.Tensor, int): Resulting Tensor and sample rate.
                If the input file has integer wav format and normalization is off, then it has
                integer type, else ``float32`` type. If ``channels_first=True``, it has
                `[channel, time]` else `[time, channel]`.
        ©Úload)r#   r9   r:   r;   r<   r$   r.   r    r1   r   r   r>   v   s    Vzget_load_func.<locals>.load)r   r8   TTNr-   N)r   r   r   r2   r3   r4   r   r   r5   Úboolr   ÚtorchÚTensorr=   r   r6   r   Úget_load_funch   s2      þ       ø÷YrB   c                     sˆ   t ƒ ‰ ttttjf tt tt tdœ‡ fdd„‰d	ttttjf tj	t
ttt tt tt
 t
tt ttttt
f  dœ
‡fdd„} | S )
Nr"   c                    sN   |d k	rt |ˆ ƒS ˆ  ¡ D ]}| | |¡r|  S qtd| › d|› d�ƒ‚d S r%   )r!   r(   Z
can_encoder)   r*   r+   r   r   r,   Õ   s    

z!get_save_func.<locals>.dispatcherTr-   ©
r#   ÚsrcZsample_rater<   r$   ÚencodingZbits_per_sampler.   r    Úcompressionc
           
         s&   ˆ | ||ƒ}|  | ||||||||	¡	S )ad  Save audio data to file.

        Note:
            The formats this function can handle depend on the availability of backends.
            Please use the following functions to fetch the supported formats.

            - FFmpeg: :py:func:`torchaudio.utils.ffmpeg_utils.get_audio_encoders`
            - Sox: :py:func:`torchaudio.utils.sox_utils.list_write_formats`
            - SoundFile: Refer to `the official document <https://pysoundfile.readthedocs.io/>`__.

        Args:
            uri (str or pathlib.Path): Path to audio file.
            src (torch.Tensor): Audio data to save. must be 2D tensor.
            sample_rate (int): sampling rate
            channels_first (bool, optional): If ``True``, the given tensor is interpreted as `[channel, time]`,
                otherwise `[time, channel]`.
            format (str or None, optional): Override the audio format.
                When ``uri`` argument is path-like object, audio format is
                inferred from file extension. If the file extension is missing or
                different, you can specify the correct format with this argument.

                When ``uri`` argument is file-like object,
                this argument is required.

                Valid values are ``"wav"``, ``"ogg"``, and ``"flac"``.
            encoding (str or None, optional): Changes the encoding for supported formats.
                This argument is effective only for supported formats, i.e.
                ``"wav"`` and ``""flac"```. Valid values are

                - ``"PCM_S"`` (signed integer Linear PCM)
                - ``"PCM_U"`` (unsigned integer Linear PCM)
                - ``"PCM_F"`` (floating point PCM)
                - ``"ULAW"`` (mu-law)
                - ``"ALAW"`` (a-law)

            bits_per_sample (int or None, optional): Changes the bit depth for the
                supported formats.
                When ``format`` is one of ``"wav"`` and ``"flac"``,
                you can change the bit depth.
                Valid values are ``8``, ``16``, ``24``, ``32`` and ``64``.

            buffer_size (int, optional):
                Size of buffer to use when processing file-like objects, in bytes. (Default: ``4096``)

            backend (str or None, optional):
                I/O backend to use.
                If ``None``, function selects backend given input and available backends.
                Otherwise, must be one of [``"ffmpeg"``, ``"sox"``, ``"soundfile"``],
                with the corresponding backend being available.
                (Default: ``None``)

                .. seealso::
                   :ref:`backend`

            compression (CodecConfig, float, int, or None, optional):
                Compression configuration to apply.

                If the selected backend is FFmpeg, an instance of :py:class:`CodecConfig` must be provided.

                Otherwise, if the selected backend is SoX, a float or int value corresponding to option ``-C`` of the
                ``sox`` command line interface must be provided. For instance:

                ``"mp3"``
                    Either bitrate (in ``kbps``) with quality factor, such as ``128.2``, or
                    VBR encoding with quality factor such as ``-4.2``. Default: ``-4.5``.

                ``"flac"``
                    Whole number from ``0`` to ``8``. ``8`` is default and highest compression.

                ``"ogg"``, ``"vorbis"``
                    Number from ``-1`` to ``10``; ``-1`` is the highest compression
                    and lowest quality. Default: ``3``.

                Refer to http://sox.sourceforge.net/soxformat.html for more details.

        ©ÚsaverC   r1   r   r   rH   à   s    X        ÿzget_save_func.<locals>.save)TNNNr-   NN)r   r   r   r2   r3   r4   r   r   r@   rA   r5   r?   r
   ÚfloatrG   r   r6   r   Úget_save_funcÒ   s4      þ       öö]rJ   )#r3   Ú	functoolsr   Útypingr   r   r   r   r   r   r@   Ztorchaudio._extensionr	   Ztorchaudio.ior
   Ztorio._extensionr   Ú r   r    r   Úcommonr   r   r   r   r   r   r   r2   r   r!   r7   rB   rJ   r   r   r   r   Ú<module>   s$    
>j