o
    ÌôjTí  ã                   @   sP  d Z dZddlZddlZddlmZmZmZ ddl	m
Z ddlmZ zeZW n ey1   eZY nw ddd	d
dddddddœ
Zi dd“dd“dd“dd“dd“dd“dd“d d!“d"d#“d$d%“d&d'“d(d)“d*d+“d,d-“d.d/“d0d1“d2d3“d4d5d6d7d8d9d:d;d<d=œ	¥Zi d>d“d?d“d@d	“dAd
“dBd“dCd“dDd“dEd“dFdG“dHdI“dJdK“dLdM“dNdO“dPdQ“dRdS“dTdU“dVdW“i dXdY“dZd[“d\d]“d^d_“d`da“dbdc“ddde“dfdg“dhdi“djdk“dldm“dndo“dpdq“drds“dtdu“dvdw“dxdy“¥Zddzd{d|d}œZi dd?“dd?“dd?“dd?“dd?“dd?“d d?“d"d?“d$d?“d&dD“d(dD“d*d?“d,df“d.d?“d0d?“d2d?“d~d?“d?d?d?dFdhd?d?dxdœ¥Zd€d�d‚dƒd„œZz[ejd…k�rMdd†lmZ d‡eƒ  dˆ Zn.ejd‰k�rcddŠlmZ d‡eƒ d  d‹ ZnejdŒk�rwdd†lmZ d‡eƒ  d� ZnedŽƒ‚ddl Z ej! "e j#¡Z$ej! %e$e¡Z&e 'e&¡Z(W nu ee)e*f�y   zed�ƒZ+e+du �r¬ed�ƒ‚e 'e+¡Z(W nS e�y   ejd…k�rÃd‘Z,nejd‰k�rÌd’Z,n
ejdŒk�rÕd“Z,n‚ dd†lmZ ejd…k�rþeƒ d”k�rþej! -d•¡�rñd•nd–Z.e 'ej! %e.e,¡¡Z(ne 'e,¡Z(Y nw Y nw e /e( 0¡ ¡ 1d—d˜¡Z2e2 3d™¡�r"e2e4d™ƒd… Z2	œ		�dÍdždŸ„Z5		�dÎd d¡„Z6				�dÏd¢d£„Z7G d¤d¥„ d¥e8ƒZ9dÐd¦d§„Z:d¨d©„ Z;dÑdªd«„Z<dÒd¬d­„Z=d®d¯„ Z>G d°d±„ d±e8ƒZ?dÓd³d´„Z@dµd¶„ ZAd·d¸„ ZBd¹dº„ ZCd»d¼„ ZDd½d¾„ ZEe(jFfd¿dÀ„ZGdÁdÂ„ ZHdÃdÄ„ ZIdÅdÆ„ ZJG dÇdÈ„ dÈeKƒZLG dÉdÊ„ dÊeLeMƒZNG dËdÌ„ dÌeNƒZOdS )Ôak  python-soundfile is an audio library based on libsndfile, CFFI and NumPy.

Sound files can be read or written directly using the functions
`read()` and `write()`.
To read a sound file in a block-wise fashion, use `blocks()`.
Alternatively, sound files can be opened as `SoundFile` objects.

For further information, see https://python-soundfile.readthedocs.io/.

z0.12.1é    N)ÚSEEK_SETÚSEEK_CURÚSEEK_END)Úfind_library)Úffié   é   é   é   é   é   é   é   é	   é   )
ÚtitleÚ	copyrightZsoftwareZartistÚcommentÚdateZalbumÚlicenseZtracknumberZgenreÚWAVi   ZAIFFi   ZAUi   ÚRAWi   ZPAFi   ZSVXi   ÚNISTi   ZVOCi   ZIRCAMi  
 ZW64i   ZMAT4i   ZMAT5i   ZPVFi   ZXIi   ZHTKi   ZSDSi   ZAVRi   i   i   i   i   i   i    i  ! i  " i  # )	ÚWAVEXÚSD2ÚFLACÚCAFÚWVEÚOGGÚMPC2KÚRF64ÚMP3ÚPCM_S8ÚPCM_16ÚPCM_24ÚPCM_32ÚPCM_U8ÚFLOATÚDOUBLEÚULAWÚALAWé   Ú	IMA_ADPCMé   ÚMS_ADPCMé   ÚGSM610é    Ú	VOX_ADPCMé!   ZNMS_ADPCM_16é"   ZNMS_ADPCM_24é#   ZNMS_ADPCM_32é$   ÚG721_32é0   ÚG723_24é1   ÚG723_40é2   ÚDWVW_12é@   ÚDWVW_16éA   ÚDWVW_24éB   ÚDWVW_NéC   ÚDPCM_8éP   ÚDPCM_16éQ   ÚVORBISé`   ÚOPUSéd   ÚALAC_16ép   ÚALAC_20éq   ÚALAC_24ér   ÚALAC_32és   ZMPEG_LAYER_Ié€   ZMPEG_LAYER_IIé�   ÚMPEG_LAYER_IIIé‚   i   i    i   0)ÚFILEÚLITTLEÚBIGÚCPUr   )r   r   r   r   r   r   r    r!   ÚdoubleÚfloatÚintÚshort)Úfloat64Úfloat32Úint32Úint16Údarwin)ÚmachineZlibsndfile_z.dylibÚwin32)Úarchitecturez.dllÚlinuxz.soz%no packaged library for this platformZsndfilez8sndfile library not found using ctypes.util.find_libraryzlibsndfile.dylibzlibsndfile.dllzlibsndfile.soZarm64z/opt/homebrew/lib/z/usr/local/lib/úutf-8Úreplacezlibsndfile-éÿÿÿÿra   FTc              	   C   s`   t | d||	|||
|ƒ�}| |||¡}| |||||¡}W d  ƒ n1 s&w   Y  ||jfS )a  Provide audio data from a sound file as NumPy array.

    By default, the whole file is read from the beginning, but the
    position to start reading can be specified with *start* and the
    number of frames to read can be specified with *frames*.
    Alternatively, a range can be specified with *start* and *stop*.

    If there is less data left in the file than requested, the rest of
    the frames are filled with *fill_value*.
    If no *fill_value* is specified, a smaller array is returned.

    Parameters
    ----------
    file : str or int or file-like object
        The file to read from.  See `SoundFile` for details.
    frames : int, optional
        The number of frames to read. If *frames* is negative, the whole
        rest of the file is read.  Not allowed if *stop* is given.
    start : int, optional
        Where to start reading.  A negative value counts from the end.
    stop : int, optional
        The index after the last frame to be read.  A negative value
        counts from the end.  Not allowed if *frames* is given.
    dtype : {'float64', 'float32', 'int32', 'int16'}, optional
        Data type of the returned array, by default ``'float64'``.
        Floating point audio data is typically in the range from
        ``-1.0`` to ``1.0``.  Integer data is in the range from
        ``-2**15`` to ``2**15-1`` for ``'int16'`` and from ``-2**31`` to
        ``2**31-1`` for ``'int32'``.

        .. note:: Reading int values from a float file will *not*
            scale the data to [-1.0, 1.0). If the file contains
            ``np.array([42.6], dtype='float32')``, you will read
            ``np.array([43], dtype='int32')`` for ``dtype='int32'``.

    Returns
    -------
    audiodata : `numpy.ndarray` or type(out)
        A two-dimensional (frames x channels) NumPy array is returned.
        If the sound file has only one channel, a one-dimensional array
        is returned.  Use ``always_2d=True`` to return a two-dimensional
        array anyway.

        If *out* was specified, it is returned.  If *out* has more
        frames than available in the file (or if *frames* is smaller
        than the length of *out*) and no *fill_value* is given, then
        only a part of *out* is overwritten and a view containing all
        valid frames is returned.
    samplerate : int
        The sample rate of the audio file.

    Other Parameters
    ----------------
    always_2d : bool, optional
        By default, reading a mono sound file will return a
        one-dimensional array.  With ``always_2d=True``, audio data is
        always returned as a two-dimensional array, even if the audio
        file has only one channel.
    fill_value : float, optional
        If more frames are requested than available in the file, the
        rest of the output is be filled with *fill_value*.  If
        *fill_value* is not specified, a smaller array is returned.
    out : `numpy.ndarray` or subclass, optional
        If *out* is specified, the data is written into the given array
        instead of creating a new array.  In this case, the arguments
        *dtype* and *always_2d* are silently ignored!  If *frames* is
        not given, it is obtained from the length of *out*.
    samplerate, channels, format, subtype, endian, closefd
        See `SoundFile`.

    Examples
    --------
    >>> import soundfile as sf
    >>> data, samplerate = sf.read('stereo_file.wav')
    >>> data
    array([[ 0.71329652,  0.06294799],
           [-0.26450912, -0.38874483],
           ...
           [ 0.67398441, -0.11516333]])
    >>> samplerate
    44100

    ÚrN)Ú	SoundFileÚ_prepare_readÚreadÚ
samplerate)ÚfileÚframesÚstartÚstopÚdtypeÚ	always_2dÚ
fill_valueÚoutrq   ÚchannelsÚformatÚsubtypeÚendianÚclosefdÚfÚdata© r�   ú\/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/soundfile.pyrp   Ç   s   
Vÿý
rp   c           
   	   C   sr   ddl }| |¡}|jdkrd}n|jd }t| d||||||ƒ�}	|	 |¡ W d  ƒ dS 1 s2w   Y  dS )aú  Write data to a sound file.

    .. note:: If *file* exists, it will be truncated and overwritten!

    Parameters
    ----------
    file : str or int or file-like object
        The file to write to.  See `SoundFile` for details.
    data : array_like
        The data to write.  Usually two-dimensional (frames x channels),
        but one-dimensional *data* can be used for mono files.
        Only the data types ``'float64'``, ``'float32'``, ``'int32'``
        and ``'int16'`` are supported.

        .. note:: The data type of *data* does **not** select the data
                  type of the written file. Audio data will be
                  converted to the given *subtype*. Writing int values
                  to a float file will *not* scale the values to
                  [-1.0, 1.0). If you write the value ``np.array([42],
                  dtype='int32')``, to a ``subtype='FLOAT'`` file, the
                  file will then contain ``np.array([42.],
                  dtype='float32')``.

    samplerate : int
        The sample rate of the audio data.
    subtype : str, optional
        See `default_subtype()` for the default value and
        `available_subtypes()` for all possible values.

    Other Parameters
    ----------------
    format, endian, closefd
        See `SoundFile`.

    Examples
    --------
    Write 10 frames of random data to a new file:

    >>> import numpy as np
    >>> import soundfile as sf
    >>> sf.write('stereo_file.wav', np.random.randn(10, 2), 44100, 'PCM_24')

    r   Nr   Úw)ÚnumpyÚasarrayÚndimÚshapern   Úwrite)
rr   r€   rq   r|   r}   r{   r~   Únprz   r   r�   r�   r‚   rˆ   $  s   -



ÿ"þrˆ   c              
   c   sn   � t | d|
|||||ƒ�!}| |||¡}| |||||||	¡D ]}|V  qW d  ƒ dS 1 s0w   Y  dS )a8  Return a generator for block-wise reading.

    By default, iteration starts at the beginning and stops at the end
    of the file.  Use *start* to start at a later position and *frames*
    or *stop* to stop earlier.

    If you stop iterating over the generator before it's exhausted,
    the sound file is not closed. This is normally not a problem
    because the file is opened in read-only mode. To close the file
    properly, the generator's ``close()`` method can be called.

    Parameters
    ----------
    file : str or int or file-like object
        The file to read from.  See `SoundFile` for details.
    blocksize : int
        The number of frames to read per block.
        Either this or *out* must be given.
    overlap : int, optional
        The number of frames to rewind between each block.

    Yields
    ------
    `numpy.ndarray` or type(out)
        Blocks of audio data.
        If *out* was given, and the requested frames are not an integer
        multiple of the length of *out*, and no *fill_value* was given,
        the last block will be a smaller view into *out*.

    Other Parameters
    ----------------
    frames, start, stop
        See `read()`.
    dtype : {'float64', 'float32', 'int32', 'int16'}, optional
        See `read()`.
    always_2d, fill_value, out
        See `read()`.
    samplerate, channels, format, subtype, endian, closefd
        See `SoundFile`.

    Examples
    --------
    >>> import soundfile as sf
    >>> for block in sf.blocks('stereo_file.wav', blocksize=1024):
    >>>     pass  # do something with 'block'

    rm   N)rn   ro   Úblocks)rr   Ú	blocksizeÚoverlaprs   rt   ru   rv   rw   rx   ry   rq   rz   r{   r|   r}   r~   r   Úblockr�   r�   r‚   rŠ   \  s   €
3ÿ
ÿþ"ýrŠ   c                   @   s,   e Zd ZdZdd„ Zedd„ ƒZdd„ ZdS )	Ú_SoundFileInfozInformation about a SoundFilec                 C   sž   || _ t|ƒ�>}|j| _|j| _|j| _|j| _t| jƒ|j | _|j| _|j	| _	|j
| _
|j| _|j| _|j| _|j| _W d   ƒ d S 1 sHw   Y  d S ©N)Úverbosern   Únamerq   rz   rs   r^   Údurationr{   r|   r}   Úformat_infoÚsubtype_infoÚsectionsÚ
extra_info)Úselfrr   r�   r   r�   r�   r‚   Ú__init__š  s   

"ôz_SoundFileInfo.__init__c                 C   sv   t | jdƒ\}}t |dƒ\}}|dkrd |||¡}|S |dkr(d ||¡}|S |dkr4d | j¡}|S d |¡}|S )Ni  é<   r   z{0:.0g}:{1:02.0g}:{2:05.3f} hz{0:02.0g}:{1:05.3f} minz{0:d} samplesz	{0:.3f} s)Údivmodr’   r{   rs   )r—   ÚhoursÚrestÚminutesÚsecondsr’   r�   r�   r‚   Ú_duration_strª  s   úü
ÿz_SoundFileInfo._duration_strc                 C   sD   d  g d¢¡}| jr|d  g d¢¡7 }d  | j d¡¡}| | |¡S )NÚ
)z{0.name}zsamplerate: {0.samplerate} Hzzchannels: {0.channels}zduration: {0._duration_str}z$format: {0.format_info} [{0.format}]z'subtype: {0.subtype_info} [{0.subtype}])z
endian: {0.endian}zsections: {0.sections}zframes: {0.frames}zextra_info: """z
    {1}"""z
    )Újoinr�   r–   Úsplitr{   )r—   ÚinfoZindented_extra_infor�   r�   r‚   Ú__repr__¸  s   ÿÿz_SoundFileInfo.__repr__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r˜   ÚpropertyrŸ   r¤   r�   r�   r�   r‚   rŽ   —  s    
rŽ   c                 C   s
   t | |ƒS )zŸReturns an object with information about a `SoundFile`.

    Parameters
    ----------
    verbose : bool
        Whether to print additional information.
    )rŽ   )rr   r�   r�   r�   r‚   r£   Ë  s   
r£   c                   C   s   t ttjtjƒƒS )a©  Return a dictionary of available major formats.

    Examples
    --------
    >>> import soundfile as sf
    >>> sf.available_formats()
    {'FLAC': 'FLAC (FLAC Lossless Audio Codec)',
     'OGG': 'OGG (OGG Container format)',
     'WAV': 'WAV (Microsoft)',
     'AIFF': 'AIFF (Apple/SGI)',
     ...
     'WAVEX': 'WAVEX (Microsoft)',
     'RAW': 'RAW (header-less)',
     'MAT5': 'MAT5 (GNU Octave 2.1 / Matlab 5.0)'}

    )ÚdictÚ_available_formats_helperÚ_sndZSFC_GET_FORMAT_MAJOR_COUNTZSFC_GET_FORMAT_MAJORr�   r�   r�   r‚   Úavailable_formatsÖ  s   ÿr­   c                    s$   t tjtjƒ}t‡ fdd„|D ƒƒS )ad  Return a dictionary of available subtypes.

    Parameters
    ----------
    format : str
        If given, only compatible subtypes are returned.

    Examples
    --------
    >>> import soundfile as sf
    >>> sf.available_subtypes('FLAC')
    {'PCM_24': 'Signed 24 bit PCM',
     'PCM_16': 'Signed 16 bit PCM',
     'PCM_S8': 'Signed 8 bit PCM'}

    c                 3   s.   � | ]\}}ˆ d u st ˆ |ƒr||fV  qd S r�   )Úcheck_format)Ú.0r|   r‘   ©r{   r�   r‚   Ú	<genexpr>þ  s   €
 ÿÿz%available_subtypes.<locals>.<genexpr>)r«   r¬   ZSFC_GET_FORMAT_SUBTYPE_COUNTZSFC_GET_FORMAT_SUBTYPErª   )r{   Zsubtypesr�   r°   r‚   Úavailable_subtypesë  s   ÿr²   c              	   C   s,   z	t t| ||ƒƒW S  ttfy   Y dS w )záCheck if the combination of format/subtype/endian is valid.

    Examples
    --------
    >>> import soundfile as sf
    >>> sf.check_format('WAV', 'PCM_24')
    True
    >>> sf.check_format('FLAC', 'VORBIS')
    False

    F)ÚboolÚ_format_intÚ
ValueErrorÚ	TypeError)r{   r|   r}   r�   r�   r‚   r®     s
   ÿr®   c                 C   s   t | ƒ t |  ¡ ¡S )zÍReturn the default subtype for a given format.

    Examples
    --------
    >>> import soundfile as sf
    >>> sf.default_subtype('WAV')
    'PCM_16'
    >>> sf.default_subtype('MAT5')
    'DOUBLE'

    )Ú_check_formatÚ_default_subtypesÚgetÚupperr°   r�   r�   r‚   Údefault_subtype  s   r»   c                   @   s  e Zd ZdZ		d_dd„Zedd„ ƒZ	 ed	d„ ƒZ	 ed
d„ ƒZ	 edd„ ƒZ		 edd„ ƒZ
	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZ	 edd„ ƒZdZdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zefd+d,„Z d-d.„ Z!	1	d`d2d3„Z"dad4d5„Z#d6d7„ Z$d8d9„ Z%d:d;„ Z&	0	dbd=d>„Z'dcd?d@„Z(dAdB„ Z)dCdD„ Z*dEdF„ Z+dGdH„ Z,dIdJ„ Z-dKdL„ Z.dMdN„ Z/dOdP„ Z0dQdR„ Z1dSdT„ Z2dUdV„ Z3dWdX„ Z4dYdZ„ Z5d[d\„ Z6d]d^„ Z7dS )drn   z­A sound file.

    For more documentation see the __init__() docstring (which is also
    used for the online documentation (https://python-soundfile.readthedocs.io/).

    rm   NTc	           
      C   s    t |dƒr	| ¡ n|}|| _|du rt|ddƒ}t|ƒ}	|| _t|||||||ƒ| _|  ||	|¡| _	t
|ƒ d¡rB|  ¡ rB|  d¡ t | j	tjtjtj¡ dS )a{  Open a sound file.

        If a file is opened with `mode` ``'r'`` (the default) or
        ``'r+'``, no sample rate, channels or file format need to be
        given because the information is obtained from the file. An
        exception is the ``'RAW'`` data format, which always requires
        these data points.

        File formats consist of three case-insensitive strings:

        * a *major format* which is by default obtained from the
          extension of the file name (if known) and which can be
          forced with the format argument (e.g. ``format='WAVEX'``).
        * a *subtype*, e.g. ``'PCM_24'``. Most major formats have a
          default subtype which is used if no subtype is specified.
        * an *endian-ness*, which doesn't have to be specified at all in
          most cases.

        A `SoundFile` object is a *context manager*, which means
        if used in a "with" statement, `close()` is automatically
        called when reaching the end of the code block inside the "with"
        statement.

        Parameters
        ----------
        file : str or int or file-like object
            The file to open.  This can be a file name, a file
            descriptor or a Python file object (or a similar object with
            the methods ``read()``/``readinto()``, ``write()``,
            ``seek()`` and ``tell()``).
        mode : {'r', 'r+', 'w', 'w+', 'x', 'x+'}, optional
            Open mode.  Has to begin with one of these three characters:
            ``'r'`` for reading, ``'w'`` for writing (truncates *file*)
            or ``'x'`` for writing (raises an error if *file* already
            exists).  Additionally, it may contain ``'+'`` to open
            *file* for both reading and writing.
            The character ``'b'`` for *binary mode* is implied because
            all sound files have to be opened in this mode.
            If *file* is a file descriptor or a file-like object,
            ``'w'`` doesn't truncate and ``'x'`` doesn't raise an error.
        samplerate : int
            The sample rate of the file.  If `mode` contains ``'r'``,
            this is obtained from the file (except for ``'RAW'`` files).
        channels : int
            The number of channels of the file.
            If `mode` contains ``'r'``, this is obtained from the file
            (except for ``'RAW'`` files).
        subtype : str, sometimes optional
            The subtype of the sound file.  If `mode` contains ``'r'``,
            this is obtained from the file (except for ``'RAW'``
            files), if not, the default value depends on the selected
            `format` (see `default_subtype()`).
            See `available_subtypes()` for all possible subtypes for
            a given `format`.
        endian : {'FILE', 'LITTLE', 'BIG', 'CPU'}, sometimes optional
            The endian-ness of the sound file.  If `mode` contains
            ``'r'``, this is obtained from the file (except for
            ``'RAW'`` files), if not, the default value is ``'FILE'``,
            which is correct in most cases.
        format : str, sometimes optional
            The major format of the sound file.  If `mode` contains
            ``'r'``, this is obtained from the file (except for
            ``'RAW'`` files), if not, the default value is determined
            from the file extension.  See `available_formats()` for
            all possible values.
        closefd : bool, optional
            Whether to close the file descriptor on `close()`. Only
            applicable if the *file* argument is a file descriptor.

        Examples
        --------
        >>> from soundfile import SoundFile

        Open an existing file for reading:

        >>> myfile = SoundFile('existing_file.wav')
        >>> # do something with myfile
        >>> myfile.close()

        Create a new sound file for reading and writing using a with
        statement:

        >>> with SoundFile('new_file.wav', 'x+', 44100, 2) as myfile:
        >>>     # do something with myfile
        >>>     # ...
        >>>     assert not myfile.closed
        >>>     # myfile.close() is called automatically at the end
        >>> assert myfile.closed

        Ú
__fspath__NÚmodezr+r   )Úhasattrr¼   Ú_nameÚgetattrÚ_check_modeÚ_modeÚ_create_info_structÚ_infoÚ_openÚ_fileÚsetÚ
issupersetÚseekableÚseekr¬   Ú
sf_commandZSFC_SET_CLIPPINGÚ_ffiÚNULLÚSF_TRUE)
r—   rr   r½   rq   rz   r|   r}   r{   r~   Úmode_intr�   r�   r‚   r˜   ,  s   ^
ÿ
ÿzSoundFile.__init__c                 C   ó   | j S r�   )r¿   ©r—   r�   r�   r‚   Ú<lambda>™  ó    zSoundFile.<lambda>c                 C   rÐ   r�   )rÂ   rÑ   r�   r�   r‚   rÒ   ›  rÓ   c                 C   ó   | j jS r�   )rÄ   rq   rÑ   r�   r�   r‚   rÒ   �  ó    c                 C   rÔ   r�   ©rÄ   rs   rÑ   r�   r�   r‚   rÒ   Ÿ  rÕ   c                 C   rÔ   r�   )rÄ   rz   rÑ   r�   r�   r‚   rÒ   ¡  rÕ   c                 C   ó   t | jjtj@ ƒS r�   )Ú_format_strrÄ   r{   r¬   ÚSF_FORMAT_TYPEMASKrÑ   r�   r�   r‚   rÒ   ¤  ó    c                 C   r×   r�   )rØ   rÄ   r{   r¬   ÚSF_FORMAT_SUBMASKrÑ   r�   r�   r‚   rÒ   §  rÚ   c                 C   r×   r�   )rØ   rÄ   r{   r¬   ZSF_FORMAT_ENDMASKrÑ   r�   r�   r‚   rÒ   ª  rÚ   c                 C   ó   t | jjtj@ ƒd S ©Nr   )Ú_format_inforÄ   r{   r¬   rÙ   rÑ   r�   r�   r‚   rÒ   ­  ó
    ÿÿc                 C   rÜ   rÝ   )rÞ   rÄ   r{   r¬   rÛ   rÑ   r�   r�   r‚   rÒ   ±  rß   c                 C   rÔ   r�   )rÄ   r•   rÑ   r�   r�   r‚   rÒ   ´  rÕ   c                 C   s
   | j d u S r�   )rÆ   rÑ   r�   r�   r‚   rÒ   ¶  s   
 c                 C   s   t  | j¡S r�   )r¬   Úsf_errorrÆ   rÑ   r�   r�   r‚   rÒ   ¸  s    c                 C   s8   t  dd¡}t | jtj|t  |¡¡ t  |¡ dd¡S )z8Retrieve the log string generated when opening the file.zchar[]i @  rj   rk   )	rÌ   Únewr¬   rË   rÆ   ZSFC_GET_LOG_INFOÚsizeofÚstringÚdecode)r—   r£   r�   r�   r‚   r–   »  s
   
ÿzSoundFile.extra_infoc                 C   s
   d  | ¡S )Nz™SoundFile({0.name!r}, mode={0.mode!r}, samplerate={0.samplerate}, channels={0.channels}, format={0.format!r}, subtype={0.subtype!r}, endian={0.endian!r})r°   rÑ   r�   r�   r‚   r¤   Æ  s   ýzSoundFile.__repr__c                 C   ó   |   ¡  d S r�   ©ÚcloserÑ   r�   r�   r‚   Ú__del__Ì  ó   zSoundFile.__del__c                 C   s   | S r�   r�   rÑ   r�   r�   r‚   Ú	__enter__Ï  s   zSoundFile.__enter__c                 G   rå   r�   ræ   )r—   Úargsr�   r�   r‚   Ú__exit__Ò  ré   zSoundFile.__exit__c                 C   sF   |t v r|  ¡  t | jt | | ¡ ¡}t|ƒ dS t | ||¡ dS )z:Write text meta-data in the sound file through properties.N)	Ú
_str_typesÚ_check_if_closedr¬   Zsf_set_stringrÆ   ÚencodeÚ_error_checkÚobjectÚ__setattr__)r—   r‘   ÚvalueÚerrr�   r�   r‚   rò   Õ  s   ÿzSoundFile.__setattr__c                 C   sJ   |t v r|  ¡  t | jt | ¡}|rt |¡ dd¡S dS td 	|¡ƒ‚)z9Read text meta-data in the sound file through properties.rj   rk   Ú z)'SoundFile' object has no attribute {0!r})
rí   rî   r¬   Úsf_get_stringrÆ   rÌ   rã   rä   ÚAttributeErrorr{   )r—   r‘   r€   r�   r�   r‚   Ú__getattr__ß  s   ÿzSoundFile.__getattr__c                 C   rÔ   r�   rÖ   rÑ   r�   r�   r‚   Ú__len__é  ó   zSoundFile.__len__c                 C   s   dS )NTr�   rÑ   r�   r�   r‚   Ú__bool__î  s   zSoundFile.__bool__c                 C   s   |   ¡ S r�   )rû   rÑ   r�   r�   r‚   Ú__nonzero__ó  rú   zSoundFile.__nonzero__c                 C   s   | j jtjkS )z)Return True if the file supports seeking.)rÄ   rÉ   r¬   rÎ   rÑ   r�   r�   r‚   rÉ   ø  s   zSoundFile.seekablec                 C   s&   |   ¡  t | j||¡}t| jƒ |S )aÜ  Set the read/write position.

        Parameters
        ----------
        frames : int
            The frame index or offset to seek.
        whence : {SEEK_SET, SEEK_CUR, SEEK_END}, optional
            By default (``whence=SEEK_SET``), *frames* are counted from
            the beginning of the file.
            ``whence=SEEK_CUR`` seeks from the current position
            (positive and negative values are allowed for *frames*).
            ``whence=SEEK_END`` seeks from the end (use negative value
            for *frames*).

        Returns
        -------
        int
            The new absolute read/write position in frames.

        Examples
        --------
        >>> from soundfile import SoundFile, SEEK_END
        >>> myfile = SoundFile('stereo_file.wav')

        Seek to the beginning of the file:

        >>> myfile.seek(0)
        0

        Seek to the end of the file:

        >>> myfile.seek(0, SEEK_END)
        44100  # this is the file length

        )rî   r¬   Zsf_seekrÆ   rð   Ú
_errorcode)r—   rs   ÚwhenceÚpositionr�   r�   r‚   rÊ   ü  s   $
zSoundFile.seekc                 C   s   |   dt¡S )z'Return the current read/write position.r   )rÊ   r   rÑ   r�   r�   r‚   Útell%  s   zSoundFile.tellrl   ra   Fc                 C   s‚   |du r|   ||¡}|  |||¡}n|dk s|t|ƒkr t|ƒ}|  d||¡}t|ƒ|kr?|du r9|d|… }|S |||d…< |S )a  Read from the file and return data as NumPy array.

        Reads the given number of frames in the given data format
        starting at the current read/write position.  This advances the
        read/write position by the same number of frames.
        By default, all frames from the current read/write position to
        the end of the file are returned.
        Use `seek()` to move the current read/write position.

        Parameters
        ----------
        frames : int, optional
            The number of frames to read. If ``frames < 0``, the whole
            rest of the file is read.
        dtype : {'float64', 'float32', 'int32', 'int16'}, optional
            Data type of the returned array, by default ``'float64'``.
            Floating point audio data is typically in the range from
            ``-1.0`` to ``1.0``. Integer data is in the range from
            ``-2**15`` to ``2**15-1`` for ``'int16'`` and from
            ``-2**31`` to ``2**31-1`` for ``'int32'``.

            .. note:: Reading int values from a float file will *not*
                scale the data to [-1.0, 1.0). If the file contains
                ``np.array([42.6], dtype='float32')``, you will read
                ``np.array([43], dtype='int32')`` for
                ``dtype='int32'``.

        Returns
        -------
        audiodata : `numpy.ndarray` or type(out)
            A two-dimensional NumPy (frames x channels) array is
            returned. If the sound file has only one channel, a
            one-dimensional array is returned. Use ``always_2d=True``
            to return a two-dimensional array anyway.

            If *out* was specified, it is returned. If *out* has more
            frames than available in the file (or if *frames* is
            smaller than the length of *out*) and no *fill_value* is
            given, then only a part of *out* is overwritten and a view
            containing all valid frames is returned.

        Other Parameters
        ----------------
        always_2d : bool, optional
            By default, reading a mono sound file will return a
            one-dimensional array. With ``always_2d=True``, audio data
            is always returned as a two-dimensional array, even if the
            audio file has only one channel.
        fill_value : float, optional
            If more frames are requested than available in the file,
            the rest of the output is be filled with *fill_value*. If
            *fill_value* is not specified, a smaller array is
            returned.
        out : `numpy.ndarray` or subclass, optional
            If *out* is specified, the data is written into the given
            array instead of creating a new array. In this case, the
            arguments *dtype* and *always_2d* are silently ignored! If
            *frames* is not given, it is obtained from the length of
            *out*.

        Examples
        --------
        >>> from soundfile import SoundFile
        >>> myfile = SoundFile('stereo_file.wav')

        Reading 3 frames from a stereo file:

        >>> myfile.read(3)
        array([[ 0.71329652,  0.06294799],
               [-0.26450912, -0.38874483],
               [ 0.67398441, -0.11516333]])
        >>> myfile.close()

        See Also
        --------
        buffer_read, .write

        Nr   rp   )Ú_check_framesÚ_create_empty_arrayÚlenÚ	_array_io)r—   rs   rv   rw   rx   ry   r�   r�   r‚   rp   )  s   PÿzSoundFile.readc                 C   sT   | j |dd�}|  |¡}t |d || j ¡}|  d|||¡}||ks%J ‚t |¡S )a‘  Read from the file and return data as buffer object.

        Reads the given number of *frames* in the given data format
        starting at the current read/write position.  This advances the
        read/write position by the same number of frames.
        By default, all frames from the current read/write position to
        the end of the file are returned.
        Use `seek()` to move the current read/write position.

        Parameters
        ----------
        frames : int, optional
            The number of frames to read. If ``frames < 0``, the whole
            rest of the file is read.
        dtype : {'float64', 'float32', 'int32', 'int16'}
            Audio data will be converted to the given data type.

        Returns
        -------
        buffer
            A buffer containing the read data.

        See Also
        --------
        buffer_read_into, .read, buffer_write

        N)rx   z[]rp   )r  Ú_check_dtyperÌ   rá   rz   Ú	_cdata_ioÚbuffer)r—   rs   rv   ÚctypeÚcdataZread_framesr�   r�   r‚   Úbuffer_read‡  s   

zSoundFile.buffer_readc                 C   s.   |   |¡}|  ||¡\}}|  d|||¡}|S )a�  Read from the file into a given buffer object.

        Fills the given *buffer* with frames in the given data format
        starting at the current read/write position (which can be
        changed with `seek()`) until the buffer is full or the end
        of the file is reached.  This advances the read/write position
        by the number of frames that were read.

        Parameters
        ----------
        buffer : writable buffer
            Audio frames from the file are written to this buffer.
        dtype : {'float64', 'float32', 'int32', 'int16'}
            The data type of *buffer*.

        Returns
        -------
        int
            The number of frames that were read from the file.
            This can be less than the size of *buffer*.
            The rest of the buffer is not filled with meaningful data.

        See Also
        --------
        buffer_read, .read

        rp   )r  Ú_check_bufferr  )r—   r  rv   r  r	  rs   r�   r�   r‚   Úbuffer_read_intoª  s   
zSoundFile.buffer_read_intoc                 C   sB   ddl }| |¡}|  d|t|ƒ¡}|t|ƒksJ ‚|  |¡ dS )aø  Write audio data from a NumPy array to the file.

        Writes a number of frames at the read/write position to the
        file. This also advances the read/write position by the same
        number of frames and enlarges the file if necessary.

        Note that writing int values to a float file will *not* scale
        the values to [-1.0, 1.0). If you write the value
        ``np.array([42], dtype='int32')``, to a ``subtype='FLOAT'``
        file, the file will then contain ``np.array([42.],
        dtype='float32')``.

        Parameters
        ----------
        data : array_like
            The data to write. Usually two-dimensional (frames x
            channels), but one-dimensional *data* can be used for mono
            files. Only the data types ``'float64'``, ``'float32'``,
            ``'int32'`` and ``'int16'`` are supported.

            .. note:: The data type of *data* does **not** select the
                  data type of the written file. Audio data will be
                  converted to the given *subtype*. Writing int values
                  to a float file will *not* scale the values to
                  [-1.0, 1.0). If you write the value ``np.array([42],
                  dtype='int32')``, to a ``subtype='FLOAT'`` file, the
                  file will then contain ``np.array([42.],
                  dtype='float32')``.

        Examples
        --------
        >>> import numpy as np
        >>> from soundfile import SoundFile
        >>> myfile = SoundFile('stereo_file.wav')

        Write 10 frames of random data to a new file:

        >>> with SoundFile('stereo_file.wav', 'w', 44100, 2, 'PCM_24') as f:
        >>>     f.write(np.random.randn(10, 2))

        See Also
        --------
        buffer_write, .read

        r   Nrˆ   )r„   Úascontiguousarrayr  r  Ú_update_frames)r—   r€   r‰   Úwrittenr�   r�   r‚   rˆ   Ë  s
   .
zSoundFile.writec                 C   sD   |   |¡}|  ||¡\}}|  d|||¡}||ksJ ‚|  |¡ dS )a€  Write audio data from a buffer/bytes object to the file.

        Writes the contents of *data* to the file at the current
        read/write position.
        This also advances the read/write position by the number of
        frames that were written and enlarges the file if necessary.

        Parameters
        ----------
        data : buffer or bytes
            A buffer or bytes object containing the audio data to be
            written.
        dtype : {'float64', 'float32', 'int32', 'int16'}
            The data type of the audio data stored in *data*.

        See Also
        --------
        .write, buffer_read

        rˆ   N)r  r  r  r  )r—   r€   rv   r  r	  rs   r  r�   r�   r‚   Úbuffer_write   s
   
zSoundFile.buffer_writer   c              	   c   s^  � ddl }d| jvrd| jvrtdƒ‚|du r)|du rtdƒ‚|  |||¡}d}	n|dur1tdƒ‚t|ƒ}d	}	d}
|  ||¡}|dkr­|
du rJd}n
t|
ƒ}|
|d|…< t|| |ƒ}|  ||||||d… ¡ |r„|
du ry| 	|| d… ¡}
n|| d… |
dd…< ||| kr—|du r—|d|| … }n|}|	r | 	|¡n|V  ||8 }|dksCdS dS )
aÆ  Return a generator for block-wise reading.

        By default, the generator yields blocks of the given
        *blocksize* (using a given *overlap*) until the end of the file
        is reached; *frames* can be used to stop earlier.

        Parameters
        ----------
        blocksize : int
            The number of frames to read per block. Either this or *out*
            must be given.
        overlap : int, optional
            The number of frames to rewind between each block.
        frames : int, optional
            The number of frames to read.
            If ``frames < 0``, the file is read until the end.
        dtype : {'float64', 'float32', 'int32', 'int16'}, optional
            See `read()`.

        Yields
        ------
        `numpy.ndarray` or type(out)
            Blocks of audio data.
            If *out* was given, and the requested frames are not an
            integer multiple of the length of *out*, and no
            *fill_value* was given, the last block will be a smaller
            view into *out*.


        Other Parameters
        ----------------
        always_2d, fill_value, out
            See `read()`.
        fill_value : float, optional
            See `read()`.
        out : `numpy.ndarray` or subclass, optional
            If *out* is specified, the data is written into the given
            array instead of creating a new array. In this case, the
            arguments *dtype* and *always_2d* are silently ignored!

        Examples
        --------
        >>> from soundfile import SoundFile
        >>> with SoundFile('stereo_file.wav') as f:
        >>>     for block in f.blocks(blocksize=1024):
        >>>         pass  # do something with 'block'

        r   Nrm   ú+z*blocks() is not allowed in write-only modez)One of {blocksize, out} must be specifiedTz-Only one of {blocksize, out} may be specifiedF)
r„   r½   ÚSoundFileRuntimeErrorr¶   r  r  r  Úminrp   Úcopy)r—   r‹   rŒ   rs   rv   rw   rx   ry   r‰   Zcopy_outZoverlap_memoryZoutput_offsetZtoreadr�   r�   r�   r‚   rŠ     sD   €2ÿëzSoundFile.blocksc                 C   sX   |du r|   ¡ }t | jtjt d|¡t d¡¡}|r&t | j¡}t	|dƒ‚|| j
_dS )an  Truncate the file to a given number of frames.

        After this command, the read/write position will be at the new
        end of the file.

        Parameters
        ----------
        frames : int, optional
            Only the data before *frames* is kept, the rest is deleted.
            If not specified, the current read/write position is used.

        Nzsf_count_t*Z
sf_count_tzError truncating the file)r   r¬   rË   rÆ   ZSFC_FILE_TRUNCATErÌ   rá   râ   rà   ÚLibsndfileErrorrÄ   rs   )r—   rs   rô   r�   r�   r‚   Útruncatew  s   
þ
zSoundFile.truncatec                 C   s   |   ¡  t | j¡ dS )aj  Write unwritten data to the file system.

        Data written with `write()` is not immediately written to
        the file system but buffered in memory to be written at a later
        time.  Calling `flush()` makes sure that all changes are
        actually written to the file system.

        This has no effect on files opened in read-only mode.

        N)rî   r¬   Zsf_write_syncrÆ   rÑ   r�   r�   r‚   Úflush�  s   zSoundFile.flushc                 C   s0   | j s|  ¡  t | j¡}d| _t|ƒ dS dS )z.Close the file.  Can be called multiple times.N)Úclosedr  r¬   Zsf_closerÆ   rð   )r—   rô   r�   r�   r‚   rç   �  s   ûzSoundFile.closec                 C   s0  t |ttfƒrOtj |¡r/d| jv rtd | j	¡ƒ‚t
| jƒ d¡r/t t |tjtjB ¡¡ tj}t |tƒrGtjdkr@tj}n| t ¡ ¡}|||| jƒ}n*t |tƒr^t ||| j|¡}nt||ƒrqt |  |¡|| jtj¡}ntd | j	¡ƒ‚|tjkr�t  |¡}t!|d | j	¡d�‚|tj"kr–d| j_#|S )	z9Call the appropriate sf_open*() function from libsndfile.ÚxzFile exists: {0!r}zw+rg   zInvalid file: {0!r}zError opening {0!r}: ©Úprefixr   )$Ú
isinstanceÚ_unicodeÚbytesÚ_osÚpathÚisfiler½   ÚOSErrorr{   r‘   rÇ   rÈ   rç   ÚopenÚO_WRONLYÚO_TRUNCr¬   Zsf_openÚ_sysÚplatformZsf_wchar_openrï   ÚgetfilesystemencodingrÄ   r_   Z
sf_open_fdÚ_has_virtual_io_attrsZsf_open_virtualÚ_init_virtual_iorÌ   rÍ   r¶   rà   r  Ú	SFM_WRITErs   )r—   rr   rÏ   r~   ZopenfunctionZfile_ptrrô   r�   r�   r‚   rÅ   ¦  s2   





ÿ


zSoundFile._openc                    sŽ   t  d¡‡ fdd„ƒ}t  d¡‡ fdd„ƒ}t  d¡‡ fdd	„ƒ}t  d
¡‡ fdd„ƒ}t  d¡‡ fdd„ƒ}|||||dœ| _t  d| j¡S )z4Initialize callback functions for sf_open_virtual().Zsf_vio_get_filelenc                    s,   ˆ   ¡ }ˆ  dt¡ ˆ   ¡ }ˆ  |t¡ |S ©Nr   )r   rÊ   r   r   )Ú	user_dataÚcurrÚsize©rr   r�   r‚   Úvio_get_filelenÌ  s
   z3SoundFile._init_virtual_io.<locals>.vio_get_filelenZsf_vio_seekc                    s   ˆ   | |¡ ˆ  ¡ S r�   )rÊ   r   )Úoffsetrþ   r-  r0  r�   r‚   Úvio_seekÔ  s   z,SoundFile._init_virtual_io.<locals>.vio_seekZsf_vio_readc                    s\   zt  | |¡}ˆ  |¡}W |S  ty-   ˆ  |¡}t|ƒ}t  | |¡}||d|…< Y |S w r,  )rÌ   r  Úreadintor÷   rp   r  )ÚptrÚcountr-  ÚbufZ	data_readr€   r0  r�   r‚   Úvio_readÙ  s   û
ûz,SoundFile._init_virtual_io.<locals>.vio_readZsf_vio_writec                    s2   t  | |¡}|d d … }ˆ  |¡}|d u r|}|S r�   )rÌ   r  rˆ   )r5  r6  r-  r7  r€   r  r0  r�   r‚   Ú	vio_writeæ  s   
z-SoundFile._init_virtual_io.<locals>.vio_writeZsf_vio_tellc                    s   ˆ   ¡ S r�   )r   )r-  r0  r�   r‚   Úvio_tellð  s   z,SoundFile._init_virtual_io.<locals>.vio_tell)Zget_filelenrÊ   rp   rˆ   r   zSF_VIRTUAL_IO*)rÌ   ÚcallbackZ_virtual_iorá   )r—   rr   r1  r3  r8  r9  r:  r�   r0  r‚   r*  Ê  s"   	üzSoundFile._init_virtual_ioc                 C   s   t S )z€Return all attributes used in __setattr__ and __getattr__.

        This is useful for auto-completion (e.g. IPython).

        )rí   rÑ   r�   r�   r‚   Ú_getAttributeNamesý  s   zSoundFile._getAttributeNamesc                 C   s   | j rtdƒ‚dS )z…Check if the file is closed and raise an error if it is.

        This should be used in every method that uses self._file.

        zI/O operation on closed fileN)r  r  rÑ   r�   r�   r‚   rî     s   ÿzSoundFile._check_if_closedc                 C   sJ   |   ¡ r| j|  ¡  }|dk s||kr|du r|}|S |dk r#tdƒ‚|S )z8Reduce frames to no more than are available in the file.r   Nz/frames must be specified for non-seekable files)rÉ   rs   r   rµ   )r—   rs   rx   Zremaining_framesr�   r�   r‚   r    s   þzSoundFile._check_framesc                 C   sV   |t  ¡ v sJ ‚t|tƒst |¡}tt|ƒ| jt 	|¡ ƒ\}}|r't
dƒ‚||fS )z1Convert buffer to cdata and check for valid size.z*Data size must be a multiple of frame size)Ú
_ffi_typesÚvaluesr  r  rÌ   Úfrom_bufferrš   r  rz   râ   rµ   )r—   r€   r  rs   Ú	remainderr�   r�   r‚   r    s   

ÿzSoundFile._check_bufferc                 C   s8   ddl }|s| jdkr|| jf}n|f}|j||dd�S )z-Create an empty array with appropriate shape.r   Nr   ÚC)Úorder)r„   rz   Úempty)r—   rs   rw   rv   r‰   r‡   r�   r�   r‚   r  $  s
   zSoundFile._create_empty_arrayc              	   C   s2   zt | W S  ty   td tt  ¡ ƒ|¡ƒ‚w )z7Check if dtype string is valid and return ctype string.z(dtype must be one of {0!r} and not {1!r})r=  ÚKeyErrorrµ   r{   ÚsortedÚkeys)r—   rv   r�   r�   r‚   r  -  s   
ÿÿzSoundFile._check_dtypec                 C   s¦   |j dvs|j dkr| jdks|j dkr$|jd | jkr$td |j¡ƒ‚|jjs,tdƒ‚|  |jj	¡}|jj
t |¡ks>J ‚t |d |jd d ¡}|  ||||¡S )	z+Check array and call low-level IO function.)r   r   r   r   zInvalid shape: {0!r}zData must be C-contiguousÚ*r€   r   )r†   rz   r‡   rµ   r{   ÚflagsÚc_contiguousr  rv   r‘   ÚitemsizerÌ   râ   ÚcastÚ__array_interface__r  )r—   ÚactionÚarrayrs   r  r	  r�   r�   r‚   r  5  s   
zSoundFile._array_ioc                 C   sr   |t  ¡ v sJ ‚|  ¡  |  ¡ r|  ¡ }ttd| d | ƒ}|| j||ƒ}t| j	ƒ |  ¡ r7|  
|| t¡ |S )z.Call one of libsndfile's read/write functions.Zsf_Úf_)r=  r>  rî   rÉ   r   rÀ   r¬   rÆ   rð   rý   rÊ   r   )r—   rM  r€   r  rs   r.  Úfuncr�   r�   r‚   r  B  s   
zSoundFile._cdata_ioc                 C   sD   |   ¡ r|  ¡ }|  dt¡| j_|  |t¡ dS | j j|7  _dS )z!Update self.frames after writing.r   N)rÉ   r   rÊ   r   rÄ   rs   r   )r—   r  r.  r�   r�   r‚   r  O  s
   zSoundFile._update_framesc                 C   s|   |dkr|   ¡ stdƒ‚|dkr|durtdƒ‚t||ƒ | j¡\}}}||k r*|}|dk r2|| }|   ¡ r<|  |t¡ |S )z)Seek to start frame and calculate length.r   z(start is only allowed for seekable filesNz&Only one of {frames, stop} may be used)rÉ   rµ   r¶   ÚsliceÚindicesrs   rÊ   r   )r—   rt   ru   rs   Ú_r�   r�   r‚   ro   X  s   zSoundFile._prepare_readc                 C   sB   i }t  ¡ D ]\}}t | j|¡}|rt |¡ dd¡||< q|S )a5  Get all metadata present in this SoundFile

        Returns
        -------

        metadata: dict[str, str]
            A dict with all metadata. Possible keys are: 'title', 'copyright',
            'software', 'artist', 'comment', 'date', 'album', 'license',
            'tracknumber' and 'genre'.
        rj   rk   )rí   Úitemsr¬   rö   rÆ   rÌ   rã   rä   )r—   ÚstrsZstrtypeZstridr€   r�   r�   r‚   Úcopy_metadatah  s   €zSoundFile.copy_metadata)rm   NNNNNT)rl   ra   FNN)rl   N)Nr   rl   ra   FNNr�   )8r¥   r¦   r§   r¨   r˜   r©   r‘   r½   rq   rs   rz   r{   r|   r}   r“   r”   r•   r  rý   r–   rÆ   r¤   rè   rê   rì   rò   rø   rù   rû   rü   rÉ   r   rÊ   r   rp   r
  r  rˆ   r  rŠ   r  r  rç   rÅ   r*  r<  rî   r  r  r  r  r  r  r  ro   rV  r�   r�   r�   r‚   rn   $  s¤    
ÿmÿÿÿÿÿ


)
ÿ
^#!5
ÿ
\	$3			rn   rõ   c                 C   s   | dkr
t | |d�‚dS )z+Raise LibsndfileError if there is an error.r   r  N)r  )rô   r  r�   r�   r‚   rð   |  s   ÿrð   c                 C   s  t | ƒ}|du rt| ƒ}|du rtd | ¡ƒ‚nt|ttfƒs&td |¡ƒ‚z
|t| ¡  O }W n t	y>   t
d |¡ƒ‚w |du rFd}nt|ttfƒsTtd |¡ƒ‚z
|t| ¡  O }W n t	yl   t
d |¡ƒ‚w t d¡}||_d	|_t |¡tjkr„t
d
ƒ‚|S )z8Return numeric ID for given format|subtype|endian combo.Nz)No default subtype for major format {0!r}zInvalid subtype: {0!r}zUnknown subtype: {0!r}rY   zInvalid endian-ness: {0!r}zUnknown endian-ness: {0!r}úSF_INFO*r   z1Invalid combination of format, subtype and endian)r·   r»   r¶   r{   r  r  ÚstrÚ	_subtypesrº   rD  rµ   Ú_endiansrÌ   rá   rz   r¬   Zsf_format_checkZSF_FALSE)r{   r|   r}   Úresultr£   r�   r�   r‚   r´   ‚  s@   ÿÿÿÿ
ÿr´   c                 C   s”   t | ttfƒstd | ¡ƒ‚t| ƒ}| d¡st| ƒt|ƒkr&td | ¡ƒ‚t| 	d¡ƒdkr3tdƒ‚d|v r<t
j}|S d|v rEt
j}|S t
j}|S )z=Check if mode is valid and return its integer representation.zInvalid mode: {0!r}zxrwb+Zxrwr   z&mode must contain exactly one of 'xrw'r  rm   )r  r  rX  r¶   r{   rÇ   Ú
differencer  rµ   Úintersectionr¬   ZSFM_RDWRÚSFM_READr+  )r½   Zmode_setrÏ   r�   r�   r‚   rÁ   ¢  s   üÿrÁ   c           	      C   s¶   |}|du rt | |ƒ}t|ttfƒsJ ‚nt|ƒ t d¡}d|vs(| ¡ dkrG|du r0tdƒ‚||_	|du r;tdƒ‚||_
t|||ƒ|_|S tdd„ |||||fD ƒƒrYtd	ƒ‚|S )
z*Check arguments and create SF_INFO struct.NrW  rm   r   zsamplerate must be specifiedzchannels must be specifiedc                 s   s   � | ]}|d uV  qd S r�   r�   )r¯   Úargr�   r�   r‚   r±   É  s   € z&_create_info_struct.<locals>.<genexpr>z\Not allowed for existing files (except 'RAW'): samplerate, channels, format, subtype, endian)Ú_get_format_from_filenamer  r  rX  r·   rÌ   rá   rº   r¶   rq   rz   r´   r{   Úany)	rr   r½   rq   rz   r{   r|   r}   Zoriginal_formatr£   r�   r�   r‚   rÃ   µ  s(   

ü

ÿrÃ   c                 C   sr   d}t | d| ƒ} ztj | ¡d dd… }| dd¡}W n	 ty%   Y nw | ¡ tvr7d|vr7td	 	| ¡ƒ‚|S )
a  Return a format string obtained from file (or file.name).

    If file already exists (= read mode), an empty string is returned on
    error.  If not, an exception is raised.
    The return type will always be str or unicode (even if
    file/file.name is a bytes object).

    rõ   r‘   rl   r   Nrj   rk   rm   zGNo format specified and unable to get format from file extension: {0!r})
rÀ   r  r   Úsplitexträ   Ú	Exceptionrº   Ú_formatsr¶   r{   )rr   r½   r{   r�   r�   r‚   r`  Ð  s   	ÿÿr`  c                 C   s:   t ttfD ]}| ¡ D ]\}}|| kr|    S qqdS )z;Return the string representation of a given numeric format.zn/a)rd  rY  rZ  rT  )Ú
format_intÚ
dictionaryÚkÚvr�   r�   r‚   rØ   è  s   ÿÿrØ   c                 C   sT   t  d¡}| |_t t j||t  d¡¡ |j}t|jƒ|r't  	|¡ 
dd¡fS dfS )z6Return the ID and short description of a given format.zSF_FORMAT_INFO*ZSF_FORMAT_INFOrj   rk   rõ   )rÌ   rá   r{   r¬   rË   rÍ   râ   r‘   rØ   rã   rä   )re  Úformat_flagr“   r‘   r�   r�   r‚   rÞ   ò  s   
ÿÿÿrÞ   c                 c   sF   � t  d¡}t t j| |t  d¡¡ t|d ƒD ]}t||ƒV  qdS )z8Helper for available_formats() and available_subtypes().zint*r_   r   N)rÌ   rá   r¬   rË   rÍ   râ   ÚrangerÞ   )Z
count_flagri  r6  re  r�   r�   r‚   r«   ý  s   €
ÿr«   c                 C   sL   t | ttfƒstd | ¡ƒ‚z	t|  ¡  }W |S  ty%   td | ¡ƒ‚w )z4Check if `format_str` is valid and return format ID.zInvalid format: {0!r}zUnknown format: {0!r})	r  r  rX  r¶   r{   rd  rº   rD  rµ   )Z
format_strre  r�   r�   r‚   r·     s   þÿr·   c                 C   sN   |t jk}|t jk}tt| dƒt| dƒt| dƒp|t| dƒp$t| dƒp$|gƒS )z>Check if file has all the necessary attributes for virtual IO.rÊ   r   rˆ   rp   r4  )r¬   r^  r+  Úallr¾   )rr   rÏ   ÚreadonlyZ	writeonlyr�   r�   r‚   r)    s   

ür)  c                   @   ó   e Zd ZdZdS )ÚSoundFileErrorz-Base class for all soundfile-specific errors.N©r¥   r¦   r§   r¨   r�   r�   r�   r‚   rn    s    rn  c                   @   rm  )r  zKsoundfile module runtime error.

    Errors that used to be `RuntimeError`.Nro  r�   r�   r�   r‚   r     s    r  c                   @   s.   e Zd ZdZd
dd„Zedd„ ƒZdd„ Zd	S )r  zjlibsndfile errors.


    Attributes
    ----------
    code
        libsndfile internal error number.
    rõ   c                 C   s   t  | ||¡ || _|| _d S r�   )r  r˜   Úcoder  )r—   rp  r  r�   r�   r‚   r˜   /  s   
zLibsndfileError.__init__c                 C   s(   | j rt | j ¡}t |¡ dd¡S dS )zRaw libsndfile error message.rj   rk   z'(Garbled error message from libsndfile))rp  r¬   Zsf_error_numberrÌ   rã   rä   )r—   Zerr_strr�   r�   r‚   Úerror_string4  s   zLibsndfileError.error_stringc                 C   s   | j | j S r�   )r  rq  rÑ   r�   r�   r‚   Ú__str__@  ré   zLibsndfileError.__str__N©rõ   )r¥   r¦   r§   r¨   r˜   r©   rq  rr  r�   r�   r�   r‚   r  &  s    

r  )rl   r   Nra   FNNNNNNNT)NNNT)Nr   rl   r   Nra   FNNNNNNNT)Fr�   )NNrs  )Pr¨   Ú__version__Úosr  Úsysr&  r   r   r   Zctypes.utilr   Z_find_libraryZ
_soundfiler   rÌ   Úunicoder  Ú	NameErrorrX  rí   rd  rY  rZ  r¸   r=  r'  rf   Ú_machineZ_packaged_libnamerh   Z_architecturer"  Z_soundfile_datar   ÚdirnameÚ__file__Ú_pathr¡   Z
_full_pathÚdlopenr¬   ÚImportErrorr¶   Z_libnameZ_explicit_libnameÚisdirZ_hbrew_pathrã   Zsf_version_stringrä   Z__libsndfile_version__Ú
startswithr  rp   rˆ   rŠ   rñ   rŽ   r£   r­   r²   r®   r»   rn   rð   r´   rÁ   rÃ   r`  rØ   ZSFC_GET_FORMAT_INFOrÞ   r«   r·   r)  rc  rn  ÚRuntimeErrorr  r  r�   r�   r�   r‚   Ú<module>   s    
ÿöÿþýüûúùø	÷
öõôóòñðïæÿþýüûúùø	÷
öõôóòñðïîíìëêéèçæåäãâá à!ß"Þ&üÿþýûúùø	÷
öõôóòñðïîæü
ÿ
€í€ù
þ]
ÿ8
ý;
4

      
^ 
