
    CZj             '          U d Z dZddlZddlZddlZddlm	Z	 ddl
mZ ddlmZmZmZ ddlmZmZmZmZmZ ddlZddlmZ dd	lmZ eez  ez  ej        e         z  Zee d
<   ej!        e"edf         ej#        ej$        ej%        z  ej&        z  ej'        z           f         Z(ee d<   ej!        e"eef         ej#        ej$        ej%        z  ej&        z  ej'        z           f         Z)ee d<   ed         Z*ee d<   ee d<   ee d<   ddddddddddd
Z+ee,eef                  e d<   i ddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdI	Z-ee,eef                  e dJ<   i dKddLddMddNddOddPddQddRddSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcddi dedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddZ.ee,eef                  e d<   dddddZ/ee,eef                  e d<   i ddLd dLd"dLd&dLd(dLd*dLd,dLd.dLd0dLd2dQd4dQd6dLd8dsd:dLd<dLd>dLddLdLdLdLdSdudLdLddZ0ee,eef                  e d<   dddddZ1ee,eef                  e d<   ddddZ2ee,eef                  e d<   	 ej3        dk    rddl3m4Z5 d e5            z   dz   Z6nej3        dk    r<ddl7Z8 e8j9                    Z:e:dk    rdZ6n\e:dk    rdZ6nSe:dk    rdZ6nJ e;de:           ej3        dk    r&ddl3m4Z5  e5            dv rdZ6nd e5            z   dz   Z6n e;d          ddl<Z<ej=        >                    e<j?                  Z@ej=        A                    e@e6          ZB ejC        eB          ZDn# e;eEeFf$ r 	  ed          ZGeG e;d           ejC        eG          ZDn# e;$ r ej3        dk    rdZHnej3        dk    rdZHnej3        dk    rdZHn ddl3m4Z5 ej3        dk    rV e5            dk    rHej=        I                    d          rdndZJ ejC        ej=        A                    eJeH                    ZDn ejC        eH          ZDY nw xY wY nw xY w ejK        eDL                                          M                    dd          ZNeNO                    d          reN ePd          d         ZN	 	 	 	 ddededededz  de*deQdeRdz  de(e)z  dz  dedz  dedz  dedz  dedz  dedz  deQde"e(e)z  ef         fdńZS	 	 	 	 ddede(dededz  dedz  dedz  deQdeRdz  dedz  ddfdɄZT	 	 	 	 	 	 	 	 ddededz  dededededz  de*deQdeRdz  de(e)z  dz  dedz  dedz  dedz  dedz  dedz  deQde	e(ddf         e	e)ddf         z  f"d̄ZU G d̈́ dΦ          ZVddedeQdeVfdЄZWde,eef         fdфZXddedz  de,eef         fd҄ZY	 	 ddededz  dedz  deQfdӄZZdededz  fdԄZ[ G dՄ d֦          Z\dd؄Z]dل Z^dڄ Z_dۄ Z`d܄ Zad݄ ZbeDjc        fdބZdd߄ Zed Zfd Zg G d deh          Zi G d deiej          Zk G d dek          Zld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.14.0    N)	Generator)find_library)SEEK_CURSEEK_ENDSEEK_SET)AnyBinaryIOFinalLiteral	TypeAlias)Self)ffiFileDescriptorOrPath.	AudioDataAudioData_2d)float64float32int32int16	dtype_str_snd_ffi                        	      )
title	copyrightsoftwareartistcommentdatealbumlicensetracknumbergenre
_str_typesWAVi   AIFFi   AUi   RAWi   PAFi   SVXi   NISTi   VOCi   IRCAMi  
 W64i   MAT4i   MAT5i   PVFi   XIi   HTKi   SDSi   AVRi   i   i   i   i   i   i    i  ! i  " i  # )	WAVEXSD2FLACCAFWVEOGGMPC2KRF64MP3_formatsPCM_S8PCM_16PCM_24PCM_32PCM_U8FLOATDOUBLEULAWALAW   	IMA_ADPCM   MS_ADPCM   GSM610    	VOX_ADPCM!   NMS_ADPCM_16"   NMS_ADPCM_24#   NMS_ADPCM_32$   G721_320   G723_241   G723_402   DWVW_12@   DWVW_16A   DWVW_24B   DWVW_NC   DPCM_8P   DPCM_16Q   VORBIS`   OPUSd   ALAC_16p   ALAC_20q   ALAC_24r   ALAC_32s   MPEG_LAYER_I   MPEG_LAYER_II   MPEG_LAYER_III   	_subtypesi   i    i   0)FILELITTLEBIGCPU_endiansr?   )r@   rA   rB   rC   rD   rE   rF   rG   _default_subtypesdoublefloatintshort
_ffi_types)CONSTANTAVERAGEVARIABLE_bitrate_modesdarwin)machinelibsndfile_z.dylibwin32z	win-arm64zlibsndfile_arm64.dllz	win-amd64zlibsndfile_x64.dllzlibsndfile_x86.dllz no packaged library for Windows linux)aarch64
aarch64_bearmv8barmv8lzlibsndfile_arm64.soz.soz%no packaged library for this platformsndfilez8sndfile library not found using ctypes.util.find_libraryzlibsndfile.dylibzlibsndfile.dllzlibsndfile.soarm64z/opt/homebrew/lib/z/usr/local/lib/utf-8replacezlibsndfile-r   FTfileframesstartstopdtype	always_2d
fill_valueout
sampleratechannelsformatsubtypeendianclosefdreturnc           
          t          | d||	|||
|          5 }|                    |||          }|                    |||||          }ddd           n# 1 swxY 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readr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   fdatas                   U/Users/jameslopez/projects/MentorCore/.venv/lib/python3.11/site-packages/soundfile.pyr   r      s    p 
4j(FFG
5 
5 A89f55vvfeY
C@@A A A A A A A A A A A A A A A s   1AAAr   compression_levelbitrate_modec	                     ddl }	|	                    |          }|j        dk    rd}
n|j        d         }
t	          | d||
||||||
  
        5 }|                    |           ddd           dS # 1 swxY w 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, compression_level, bitrate_mode
        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shaper   write)r   r   r   r   r   r   r   r   r   npr   r   s               r   r   r   A  s    ` ::dDyA~~:a=	4j(FFG$l
4 
4 78	                 s   A00A47A4	blocksizeoverlapc           
   #      K   t          | d|
|||||          5 }|                    |||          }|                    |||||||	          E d{V  ddd           dS # 1 swxY w 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'

    r   N)r   r   blocks)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                    r   r   r   |  s      n 
4j(FFG
5 
5 [89f5588Iwy*VYZZZZZZZZZ[ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [s   9AA#&A#c                   4    e Zd ZdZd Zed             Zd ZdS )_SoundFileInfozInformation about a SoundFilec                    || _         t          |          5 }|j        | _        |j        | _        |j        | _        |j        | _        t          | j                  |j        z  | _        |j        | _        |j	        | _	        |j
        | _
        |j        | _        |j        | _        |j        | _        |j        | _        d d d            d S # 1 swxY w Y   d S N)verboser   namer   r   r   r   durationr   r   r   format_infosubtype_infosections
extra_info)selfr   r   r   s       r   __init__z_SoundFileInfo.__init__  s    $t__ 	0)*DI#$<DO!"DM xDK#(#5#5al#BDM xDK !	DL xDK$%MD%&^D!"DM#$<DO	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0s   B&C

CCc                     t          | j        d          \  }}t          |d          \  }}|dk    r|dd|dd|dd}n)|dk    r|dd|dd	}n|dk    r| j        d
d}n|dd}|S )Ni  <   r   z.0g:z02.0gz05.3fz hz mindz samplesz.3fz s)divmodr   r   )r   hoursrestminutessecondsr   s         r   _duration_strz_SoundFileInfo._duration_str  s    T]D11t!$++A::GGGgGGGgGGGGHH\\!==='====HH\\+1111HH!))))H    c                    d                     | j         d| j         dd| j         d| j         d| j         d| j         dd	| j         d| j         dg          }| j	        rfd
                     | j
                            d                    }|d                     d| j         d| j         d| j         dd| dg          z  }|S )N
zsamplerate: z Hzz
channels: z
duration: zformat: z []z	subtype: z
    z	
endian: z
sections: zframes: zextra_info: """z    z""")joinr   r   r   r   r   r   r   r   r   r   splitr   r   r   )r   infoindented_extra_infos      r   __repr__z_SoundFileInfo.__repr__  s   yy	^0DO000)$-)).$,..:(::DK:::=*==dl===?@ @ < 	3#-"3"3DO4I4I$4O4O"P"PDII+dk++-dm--)DK))"0+000	23 3 3D r   N)__name__
__module____qualname____doc__r   propertyr   r    r   r   r   r     sS        ''0 0 0    X    r   r   r   c                 "    t          | |          S )zReturns an object with information about a `SoundFile`.

    Parameters
    ----------
    verbose : bool
        Whether to print additional information.
    )r   )r   r   s     r   r   r     s     $(((r   c                  d    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_helperr   SFC_GET_FORMAT_MAJOR_COUNTSFC_GET_FORMAT_MAJORr   r   r   available_formatsr     s3    " )$*I*.*CE E F F Fr   c                 h     t          t          j        t          j                  } f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                 @    i | ]\  }}t          |          ||S r   )check_format).0r   r   r   s      r   
<dictcomp>z&available_subtypes.<locals>.<dictcomp>   s<     D D Dmgt>\&'%B%B> T!>>r   )r   r   SFC_GET_FORMAT_SUBTYPE_COUNTSFC_GET_FORMAT_SUBTYPE)r   subtypess   ` r   available_subtypesr     sS    " ))J)-)DF FHD D D Dx D D D Dr   c                 p    	 t          t          | ||                    S # t          t          f$ r Y dS w xY w)zCheck 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   s      r   r   r   $  sH    K88999	"   uus     55c                 x    t          |            t                              |                                           S )zReturn the default subtype for a given format.

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

    )_check_formatr   getupper)r   s    r   default_subtyper  7  s.     &  000r   c                      e Zd ZdZ	 	 	 	 	 	 dVdededz  dedz  dedz  d	edz  d
edz  dedz  dededz  dedz  ddfdZ	 e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	  e
d           Z	 e
d              ZdZdefd!ZdWd"Zdefd#Zd$e ddfd%Z!d&ed'e ddfd(Z"d&ede fd)Z#defd*Z$defd+Z%defd,Z&defd-Z'e(fd.ed/edefd0Z)defd1Z*	 	 	 dXd.ed5e+d6ed7edz  d8e,e-z  dz  de,e-z  fd9Z.dYd.ed5e+dz  de/fd:Z0d;e1e/z  e z  d5e+defd<Z2d=e,ddfd>Z3d=e4d5e+ddfd?Z5	 	 	 	 dZdAedz  dBed.ed5e+d6ed7edz  d8e,e-z  dz  de6e,ddf         e6e-ddf         z  fdCZ7d[d.edz  ddfdDZ8dWdEZ9dWdFZ: e;j<                    Z=dG Z>dH Z?dI Z@dJ ZAdK ZBdL ZCdM ZDdN ZEdO ZFdP ZGdQ ZHdR ZIdeJeef         fdSZKdT ZLdU ZMdS )\r   zA sound file.

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

    r   NTr   moder   r   r   r   r   r   r   r   r   c           	         t          |t          j                  rt          j        |          }|| _        |"t          |dd          }|t          d          t          |          }|| _        |	| _	        |
| _
        t          |||||||          | _        |                     |||          | _        t          |                              d          r)|                                 r|                     d           t&                              | j        t&          j        t,          j        t&          j                   | j	        =|                     | j	                   | j
        |                     | j
                   dS dS 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.
        compression_level : float, optional
            The compression level on 'write()'. The compression level
            should be between 0.0 (minimum compression level) and 1.0
            (highest compression level).
            See `libsndfile document <https://github.com/libsndfile/libsndfile/blob/c81375f070f3c6764969a738eacded64f53a076e/docs/command.md>`__.
        bitrate_mode : {'CONSTANT', 'AVERAGE', 'VARIABLE'}, optional
            The bitrate mode on 'write()'.
            See `libsndfile document <https://github.com/libsndfile/libsndfile/blob/c81375f070f3c6764969a738eacded64f53a076e/docs/command.md>`__.

        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

        Nr	  z6Can not get `mode` from file. provided `mode` is None.zr+r   )
isinstance_osPathLikefspath_namegetattrr  _check_mode_mode_compression_level_bitrate_mode_create_info_struct_info_open_fileset
issupersetseekableseekr   
sf_commandSFC_SET_CLIPPINGr   NULLSF_TRUE_set_compression_level_set_bitrate_mode)r   r   r	  r   r   r   r   r   r   r   r   mode_ints               r   r   zSoundFile.__init__O  sp   P dCL)) 	$:d##D
<4..D| XYYYt$$
"3)(tZ)/&B B
ZZh88
t99%% 	$--// 	IIaLLL
D$949	& 	& 	& ".''(?@@@!-&&t'9:::::	 /. .-r   c                     | j         S r   )r  r   s    r   <lambda>zSoundFile.<lambda>       r   c                     | j         S r   )r  r%  s    r   r&  zSoundFile.<lambda>  r'  r   c                     | j         j        S r   )r  r   r%  s    r   r&  zSoundFile.<lambda>  s    tz'< r   c                     | j         j        S r   r  r   r%  s    r   r&  zSoundFile.<lambda>  s    4:#4 r   c                     | j         j        S r   )r  r   r%  s    r   r&  zSoundFile.<lambda>      TZ%8 r   c                 N    t          | j        j        t          j        z            S r   )_format_strr  r   r   SF_FORMAT_TYPEMASKr%  s    r   r&  zSoundFile.<lambda>  s    [!2T5L!LMM r   c                 N    t          | j        j        t          j        z            S r   )r/  r  r   r   SF_FORMAT_SUBMASKr%  s    r   r&  zSoundFile.<lambda>      [!2T5K!KLL r   c                 N    t          | j        j        t          j        z            S r   )r/  r  r   r   SF_FORMAT_ENDMASKr%  s    r   r&  zSoundFile.<lambda>  r3  r   c                 Z    t          | j        j        t          j        z            d         S Nr   )_format_infor  r   r   r0  r%  s    r   r&  zSoundFile.<lambda>  s*    \$*"3"&"9#: ; ;;<> r   c                 Z    t          | j        j        t          j        z            d         S r7  )r8  r  r   r   r2  r%  s    r   r&  zSoundFile.<lambda>  s*    \$*"3"&"8#9 : ::;= r   c                     | j         j        S r   )r  r   r%  s    r   r&  zSoundFile.<lambda>  r-  r   c                     | j         d u S r   )r  r%  s    r   r&  zSoundFile.<lambda>  s    4:#5 r   c                 @    t                               | j                  S r   )r   sf_errorr  r%  s    r   r&  zSoundFile.<lambda>  s    t}}TZ'@'@ r   c                     | j         S r   )r  r%  s    r   r&  zSoundFile.<lambda>  s	    d.E r   c                     | j         S r   )r  r%  s    r   r&  zSoundFile.<lambda>  s	    ); r   c                     t          j        dd          }t                              | j        t          j        |t          j        |                     t          j        |                              dd          S )z8Retrieve the log string generated when opening the file.zchar[]i @  r   r   )	r   newr   r  r  SFC_GET_LOG_INFOsizeofstringdecode)r   r   s     r   r   zSoundFile.extra_info  sc     x%((
D$9dk$//	1 	1 	1{4  '';;;r   c                     | j         
d| j          nd}|| j        d| j         dndz  }d| j        d| j        d| j         d| j         d	| j        d
| j        d| j        | dS )Nz, compression_level= z, bitrate_mode=''z
SoundFile(z, mode=z, samplerate=z, channels=z	, format=z
, subtype=z	, endian=))	r   r   r   r	  r   r   r   r   r   )r   compression_settings     r   r   zSoundFile.__repr__  s    "&"8"D  Od6LNNNJL 	#'#4#@ !H43D G G G GFH	J@TY @ @ @ @"o@ @:>-@ @+@ @37<@ @ +@ *=@ @ @ 	Ar   c                 .    |                                   d S r   closer%  s    r   __del__zSoundFile.__del__      

r   c                     | S r   r   r%  s    r   	__enter__zSoundFile.__enter__  s    r   argsc                 .    |                                   d S r   rL  )r   rR  s     r   __exit__zSoundFile.__exit__  rO  r   r   valuec                    |t           v rc|                                  t                              | j        t           |         |                                          }t          |           dS t                              | ||           dS )z:Write text meta-data in the sound file through properties.N)	r-   _check_if_closedr   sf_set_stringr  encode_error_checkobject__setattr__)r   r   rU  errs       r   r\  zSoundFile.__setattr__  s|    :!!###$$TZD1A%*\\^^5 5CtT511111r   c                    |t           v rk|                                  t                              | j        t           |                   }|r(t          j        |                              dd          ndS t          d|          )z9Read text meta-data in the sound file through properties.r   r   rG  z$'SoundFile' object has no attribute )	r-   rW  r   sf_get_stringr  r   rD  rE  AttributeError)r   r   r   s      r   __getattr__zSoundFile.__getattr__   s    :!!###%%dj*T2BCCDCGO4;t$$++GY???RO ?t??A A Ar   c                     | j         j        S r   r+  r%  s    r   __len__zSoundFile.__len__*  s     z  r   c                     dS )NTr   r%  s    r   __bool__zSoundFile.__bool__/  s	     tr   c                 *    |                                  S r   )re  r%  s    r   __nonzero__zSoundFile.__nonzero__4  s     }}r   c                 6    | j         j        t          j        k    S )z)Return True if the file supports seeking.)r  r  r   r   r%  s    r   r  zSoundFile.seekable9  s    z"dl22r   r   whencec                     |                                   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

        )rW  r   sf_seekr  rZ  
_errorcode)r   r   ri  positions       r   r  zSoundFile.seek=  sC    H 	<<
FF;;T_%%%r   c                 8    |                      dt                    S )z'Return the current read/write position.r   )r  r   r%  s    r   tellzSoundFile.tellf  s    yyH%%%r   r   r   Fr   r   r   r   c                 2   |.|                      ||          }|                     |||          }n(|dk     s|t          |          k    rt          |          }|                     d||          }t          |          |k    r||d|         }n|||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   r   )_check_frames_create_empty_arraylen	_array_io)r   r   r   r   r   r   s         r   r   zSoundFile.readk  s    b ;''
;;F**69eDDCCzzVc#hh..SV44s88f!'6'l)FGG
r   c                    |                      |d          }|                     |          }t          j        |dz   || j        z            }|                     d|||          }||k    sJ t          j        |          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)r   z[]r   )rq  _check_dtyper   rA  r   	_cdata_iobuffer)r   r   r   ctypecdataread_framess         r   buffer_readzSoundFile.buffer_read  s    8 ##Ft#<<!!%((v'=>>nnVUE6BBf$$$${5!!!r   rx  c                     |                      |          }|                     ||          \  }}|                     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

        r   )rv  _check_bufferrw  )r   rx  r   ry  rz  r   s         r   buffer_read_intozSoundFile.buffer_read_into  sL    8 !!%((**6599vuf==r   r   c                     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   ascontiguousarrayrt  rs  _update_frames)r   r   r   writtens       r   r   zSoundFile.write  sr    \ 	 ##D))..$D		::#d))####G$$$$$r   c                     |                      |          }|                     ||          \  }}|                     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)rv  r~  rw  r  )r   r   r   ry  rz  r   r  s          r   buffer_writezSoundFile.buffer_writeE  sr    * !!%((**477v..%??&    G$$$$$r   r   r   r   c           	   #     K   ddl }d| j        vrd| j        vrt          d          |                     ||          }|?|t	          d          ||nt          ||          }	|                     |	||          }d}
n"|t	          d          t          |          }d	}
d}|dk    r|d}nt          |          }||d|<   t          ||z
  |          }|                     ||||||d                    |r1||	                    || d                   }n|| d         |dd<   |||z   k    r||d||z            }n|}|
r|	                    |          n|V  ||z  }|dk    d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   Nr   +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	  SoundFileRuntimeErrorrq  r  minrr  rs  r   copy)r   r   r   r   r   r   r   r   r   out_sizecopy_outoverlap_memoryoutput_offsettoreadblocks                  r   r   zSoundFile.blocks`  s     h 	diCty$8$8'(TUUU##FJ77;  KLLL$.$:yyIv@V@VH**8YFFCHH$CE E ECIHqjj% ! #N 3 3&4N]N#]2F;;FIIfeY
C<OPPP 7!)%'WWS'^%<%<NN(+WHIIN111%6G+++
0B-Vg--.$,7"''%...%777fF+ qjjjjjjr   c                 N   ||                                  }t                              | j        t          j        t          j        d|          t          j        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*
sf_count_tzError truncating the file)ro  r   r  r  SFC_FILE_TRUNCATEr   rA  rC  r=  LibsndfileErrorr  r   )r   r   r]  s      r   truncatezSoundFile.truncate  s     >YY[[Foodj$*@"h}f=="k,779 9  	D--
++C!#'BCCC"
r   c                 l    |                                   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)rW  r   sf_write_syncr  r%  s    r   flushzSoundFile.flush  s2     	4:&&&&&r   c                     | j         sK|                                  t                              | j                  }d| _        t          |           dS dS )z.Close the file.  Can be called multiple times.N)closedr  r   sf_closer  rZ  )r   r]  s     r   rM  zSoundFile.close  sQ    { 	JJLLL--
++CDJ	 	r   c                 
    t          |t          t          f          r	t          j                            |          rd j        v rt          d j                  t           j                  
                    d          r>t          j        t          j        |t          j        t          j        z                       t          j        }t          |t                    rCt"          j        dk    rt          j        }no|                    t#          j                              }nHt          |t,                    rfd}n-t/          ||          r fd}nt1          d j                   j        5   ||| j                  }|t6          j        k    r4t                              |          }t=          |d j        d	
          	 ddd           n# 1 swxY w Y   |t          j        k    rd j        _         |S )z9Call the appropriate sf_open*() function from libsndfile.xzFile exists: zw+r   c                 >    t                               | ||          S r   )r   
sf_open_fd)r   r#  r   r   s      r   r&  z!SoundFile._open.<locals>.<lambda>  s    hX\^e8f8f r   c                 x    t                                                   |           ||t          j                  S r   )r   sf_open_virtual_init_virtual_ior   r  )r   r#  r   r   s      r   r&  z!SoundFile._open.<locals>.<lambda>  s3    8L8LTMbMbcgMhMh,4dDI9G 9G r   zInvalid file: zError opening z: prefixNr   )!r  strbytesr  pathisfiler	  OSErrorr   r  r  rM  openO_WRONLYO_TRUNCr   sf_open_sysplatformsf_wchar_openrY  getfilesystemencodingr   _has_virtual_io_attrsr  _sf_error_lockr  r   r  r=  r  	SFM_WRITEr   )r   r   r#  r   openfunctionfile_ptrr]  s   `  `   r   r  zSoundFile._open  s<   dS%L)) 	<xt$$ J$)##!"?$)"?"?@@@^^..t44 JIchtS\CK-GHHIII<L$$$ E=G++#'#5LL;;t'A'C'CDDDc"" 	<ffffLL"422 	<G G G GLL :TY::;;;  	T 	T#|D(DJ??H49$$mmH--%c2R492R2R2RSSSS %	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T
 t~%% !"DJ s   8AGG #G c                    t          j        d          fd            }t          j        d          fd            }t          j        d          fd            }t          j        d          fd            }t          j        d	          fd
            }|||||d| _        t          j        d| j                  S )z4Initialize callback functions for sf_open_virtual().sf_vio_get_filelenc                                                      }                    dt                                                      }                    |t                     |S Nr   )ro  r  r   r   )	user_datacurrsizer   s      r   vio_get_filelenz3SoundFile._init_virtual_io.<locals>.vio_get_filelen  sJ    99;;DIIa"""99;;DIIdH%%%Kr   sf_vio_seekc                 X                         | |                                           S r   )r  ro  )offsetri  r  r   s      r   vio_seekz,SoundFile._init_virtual_io.<locals>.vio_seek$  s%    IIff%%%99;;r   sf_vio_readc                     	 t          j        | |          }                    |          }nP# t          $ rC                     |          }t          |          }t          j        | |          }||d|<   Y nw xY w|S r  )r   rx  readintor`  r   rs  )ptrcountr  buf	data_readr   r   s         r   vio_readz,SoundFile._init_virtual_io.<locals>.vio_read)  s    (k#u-- MM#..		! ( ( (yy''II	k#y11#'AiK   	(
 s   *. A
A;:A;sf_vio_writec                 x    t          j        | |          }|d d          }                    |          }||}|S r   )r   rx  r   )r  r  r  r  r   r  r   s         r   	vio_writez-SoundFile._init_virtual_io.<locals>.vio_write6  sA    +c5))Cqqq6Djj&&GNr   sf_vio_tellc                 ,                                     S r   )ro  )r  r   s    r   vio_tellz,SoundFile._init_virtual_io.<locals>.vio_tell@  s    99;;r   )get_filelenr  r   r   ro  zSF_VIRTUAL_IO*)r   callback_virtual_iorA  )r   r   r  r  r  r  r  s    `     r   r  zSoundFile._init_virtual_io  s*   	+	,	,	 	 	 	 
-	,	 
}	%	%	 	 	 	 
&	%	 
}	%	%
	 
	 
	 
	 
&	%
	 
~	&	&	 	 	 	 
'	&	 
}	%	%	 	 	 	 
&	%	 ,;$,$,%.$,	. . x($*:;;;r   c                     t           S )zReturn all attributes used in __setattr__ and __getattr__.

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

        )r-   r%  s    r   _getAttributeNameszSoundFile._getAttributeNamesM  s
     r   c                 2    | j         rt          d          dS )zCheck 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%  s    r   rW  zSoundFile._check_if_closedU  s*     ; 	H'(FGGG	H 	Hr   c                     |                                  r-| j        |                                 z
  }|dk     s||k    r||}n|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  r   ro  r  )r   r   r   remaining_framess       r   rq  zSoundFile._check_frames^  se    ==?? 	P#{TYY[[8zzf'777(0)aZZNOOOr   c                 ,   |t                                           v sJ t          |t                    st	          j        |          }t          t          |          | j        t	          j	        |          z            \  }}|rt          d          ||fS )z1Convert buffer to cdata and check for valid size.z*Data size must be a multiple of frame size)r   valuesr  r  r   from_bufferr   rs  r   rC  r  )r   r   ry  r   	remainders        r   r~  zSoundFile._check_bufferi  s    
))++++++$&& 	*#D))D"3t99#'=4;u3E3E#EG G	 	KIJJJV|r   c                 n    ddl }|s| j        dk    r
|| j        f}n|f}|                    ||d          S )z-Create an empty array with appropriate shape.r   Nr   C)order)r   r   empty)r   r   r   r   r   r   s         r   rr  zSoundFile._create_empty_arrayt  sO     	))DM)EEGExxuCx000r   c                     	 t           |         S # t          $ r: t          dt          t                                                     d|          w xY w)z7Check if dtype string is valid and return ctype string.zdtype must be one of z	 and not )r   KeyErrorr  sortedkeys)r   r   s     r   rv  zSoundFile._check_dtype}  sd    	fe$$ 	f 	f 	fdVJOO<M<M5N5Ndd[`ddeee	fs
    AAc           	      2   |j         dvr(t          d|j        d|j         dk     rdnd d          |j         dk    rdn|j        d         }|| j        k    r#t          d|j        d| j         d	| d          |j        j        st          d
          |                     |j        j                  }|j        j	        t          j        |          k    sJ t          j        |dz   |j        d         d                   }|                     ||||          S )z+Check array and call low-level IO function.)r   r   zInvalid shape: z (r   z0 dimensions not supportedztoo many dimensionsrI  z (Expected z channels, got zData must be C-contiguous*r   r   )r   r  r   r   flagsc_contiguousrv  r   r   itemsizer   rC  cast__array_interface__rw  )r   actionarrayr   array_channelsry  rz  s          r   rt  zSoundFile._array_io  sK   :U""  Mu{  M  M`e`jmn`n`n@\@\  uJ  M  M  M  N  N  N#jAoo5;q>T]**xu{xxxxguxxxyyy{' 	:8999!!%+"233{#t{5'9'99999	%#+u'@'H'KLL~~feUF;;;r   c                    |t                                           v sJ |                                  d}|                                 r|                                 }t          t          d|z   dz   |z             } || j        ||          }t          | j	                   |                                 r| 
                    ||z   t                     |S )z.Call one of libsndfile's read/write functions.r   sf_f_)r   r  rW  r  ro  r  r   r  rZ  rl  r  r   )r   r  r   ry  r   r  funcs          r   rw  zSoundFile._cdata_io  s    
))++++++==?? 	99;;DtUV^d2U:;;dj$//T_%%%==?? 	/IIdVmX...r   c                    |                                  rV|                                 }|                     dt                    | j        _        |                     |t                     dS | j        xj        |z  c_        dS )z!Update self.frames after writing.r   N)r  ro  r  r   r  r   r   )r   r  r  s      r   r  zSoundFile._update_frames  sm    ==?? 	)99;;D $		!X 6 6DJIIdH%%%%%J(r   c                 b   |dk    r#|                                  st          d          |dk    r|t          d          t          ||                              | j                  \  }}}||k     r|}|dk     r||z
  }|                                  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indicesr   r  r   )r   r   r   r   _s        r   r   zSoundFile._prepare_read  s    A::dmmoo:GHHHQ;;4+DEEEud++33DK@@tQ%<<DA::E\F==?? 	'IIeX&&&r   c                     i }t                                           D ]R\  }}t                              | j        |          }|r+t          j        |                              dd          ||<   S|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'.
        r   r   )r-   itemsr   r_  r  r   rD  rE  )r   strsstrtypestridr   s        r   copy_metadatazSoundFile.copy_metadata  ss     (..00 	M 	MNGU%%dj%88D M $D 1 1 8 8) L LWr   c                 d   |t           v sJ t          j        d          }t           |         |d<   t                              | j        t          j        |t          j        |                    }|t          j        k    r2t          	                    | j                  }t          |d|           dS )z,Call libsndfile's set bitrate mode function.zint[1]r   zError set bitrate mode N)r   r   rA  r   r  r  SFC_SET_BITRATE_MODErC  r   r=  r  )r   r   pointer_bitrate_moder]  s       r   r"  zSoundFile._set_bitrate_mode  s    ~----#x11"0">Qoodj$*CEY[_[fg{[|[|}}$,--
++C!#'O'O'OPPP r   c                 t   d|cxk    rdk    sn t          d          t          j        d          }||d<   t                              | j        t          j        |t          j        |                    }|t          j        k    r2t          	                    | j                  }t          |d|           dS )z1Call libsndfile's set compression level function.r   r   z)Compression level must be in range [0..1]z	double[1]zError set compression level N)r  r   rA  r   r  r  SFC_SET_COMPRESSION_LEVELrC  r   r=  r  )r   r   pointer_compression_levelr]  s       r   r!  z SoundFile._set_compression_level  s    &++++!++++HIII$(H[$9$9!'8!!$oodj$*HJceiep  rK  fL  fL  M  M$,--
++C!#'YFW'Y'YZZZ r   )	r   NNNNNTNN)r   N)r   r   FNN)r   N)Nr   r   r   FNNr   )Nr   r   r   r   r   r  r   r   r   r   r   r   r	  r   r   r   r   r   r   r   r   r   r  rl  r   r   r   r  r   rN  r   rQ  r   rT  r\  ra  rc  re  rg  r  r   r  ro  r   r   r   r   
memoryviewr|  	bytearrayr  r   r  r  r   r   r  r  rM  
_threadingLockr  r  r  r  rW  rq  r~  rr  rv  rt  rw  r  r   r   r  r"  r!  r   r   r   r   r   G  s?         GJGKBF<@37,0A; A;1 A;t A; 4ZA;:=*A;*A;584ZA; tA; 6:A; %*DL	A;
  #TzA;
 6:A; A; A; A;F 8++,,D*8++,,D7<<==J,X4455F1x8899H3XMMO OF-hLLN NG4XLLN NF8(	> 	>? ?K ?8	= 	=> >L :x8899H3X5566F2@@AAJ' !E!EFF,8;;<<L'< < X< EA# A A A A   4    c d    2 2C 2D 2 2 2 2A A A A A A! ! ! ! !
$    
T    
3$ 3 3 3 3 /7 ' '3 ' '3 ' ' ' 'R&c & & & &
 9B@D37] ]3 ]I ]]16]\)D0]<E<T] ] ] ]@!" !"# !"9t3C !"z !" !" !" !"Fy:'='C I Z]    B4%) 4% 4% 4% 4% 4%l% %y %T % % % %6 CD4=CG6:] ]d
 ]C ]](1]]49DL] ,t3] @ITXZ^I^?_bklxz~  AE  mE  cF  @F] ] ] ]~# #sTz #T # # # #0' ' ' '    %Z_&&N# # #J1< 1< 1<f  H H H	 	 		 	 	1 1 1f f f< < <  ) ) )   tCH~    $	Q 	Q 	Q
[ 
[ 
[ 
[ 
[r   r   rG  c                 4    | dk    rt          | |          dS )z+Raise LibsndfileError if there is an error.r   r  N)r  )r]  r  s     r   rZ  rZ    s%    
axxc&1111 xr   c                    t          |           }|$t          |           }|t          d|           n't          |t                    st          d|          	 |t
          |                                         z  }n # t          $ r t          d|          w xY w|d}n't          |t                    st          d|          	 |t          |                                         z  }n # t          $ r t          d|          w xY wt          j        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 zInvalid subtype: zUnknown subtype: r   zInvalid endian-ness: zUnknown endian-ness: SF_INFO*r   z1Invalid combination of format, subtype and endian)r  r  r  r  r  r   r  r  r  r   r   rA  r   r   r   sf_format_checkSF_FALSE)r   r   r   resultr   s        r   r   r     s   6""F!&))?AvAAC C C  %% 97G77888:)GMMOO,, : : :8W88999:~$$ <:::;;;=(6<<>>** = = =;;;<<<= 8JDDKDMD!!T]22?A A 	AMs   "B B"C1 1Dc                    t          | t                    st          d|           t          |           }|                    d          s t          |           t          |          k    rt          d|           t          |                    d                    dk    rt          d          d|v rt          j	        }nd|v rt          j
        }nt          j        }|S )z=Check if mode is valid and return its integer representation.zInvalid mode: zxrwb+xrwr   z&mode must contain exactly one of 'xrw'r  r   )r  r  r  r  
differencers  r  intersectionr   SFM_RDWRSFM_READr  )r	  mode_setr#  s      r   r  r  
  s    dC   31112224yyH7## 4s4yy3x=='@'@2$22333
8  ''((A--ABBB
h=	=>Or   c                    |}|(t          | |          }t          |t                    sJ nt          |           t	          j        d          }d|vs|                                dk    rG|t          d          ||_        |t          d          ||_	        t          |||          |_        n-t          d |||||fD                       rt          d          |S )	z*Check arguments and create SF_INFO struct.Nr
  r   r1   zsamplerate must be specifiedzchannels must be specifiedc              3      K   | ]}|d uV  	d S r   r   )r   args     r   	<genexpr>z&_create_info_struct.<locals>.<genexpr>1  s>       I I3s$ I I I I I Ir   z\Not allowed for existing files (except 'RAW'): samplerate, channels, format, subtype, endian)_get_format_from_filenamer  r  r  r   rA  r  r  r   r   r   r   any)	r   r	  r   r   r   r   r   original_formatr   s	            r   r  r    s    O~*466&#&&&&&&f8JD
$&,,..E11:;;;$8999 !&'6:: I IHow+H I I I I I 	M L M M MKr   c                 8   d}t          | d|           } 	 t          j                            |           d         dd         }|                    dd          }n# t
          $ r Y nw xY w|                                t          vrd|vrt          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).

    rG  r   r   r   Nr   r   r   zBNo format specified and unable to get format from file extension: )	r  r  r  splitextrE  	Exceptionr  rH   r  )r   r	  r   s      r   r  r  8  s     F4&&D""4((,QRR0w	22   ||~~X%%#T// 4+/4 4 5 5 	5Ms   AA 
A&%A&c                     t           t          t          fD ](}|                                D ]\  }}|| k    r|c c S )dS )z;Return the string representation of a given numeric format.zn/a)rH   r   r   r  )
format_int
dictionarykvs       r   r/  r/  P  s^    	83  
$$&& 	 	DAqJ 	 ur   c                 8   t          j        d          }| |_        t                              t           j        ||t          j        d                     |j        }t          |j                  |r(t          j	        |          
                    dd          ndfS )z6Return the ID and short description of a given format.zSF_FORMAT_INFO*SF_FORMAT_INFOr   r   rG  )r   rA  r   r   r  r  rC  r   r/  rD  rE  )r   format_flagr   r   s       r   r8  r8  Z  s    (,--K#KOODI{KK 0113 3 3D*++<@HDK$$Wi888bJ Jr   c              #      K   t          j        d          }t                              t           j        | |t          j        d                     t          |d                   D ]}t          ||          V  dS )z8Helper for available_formats() and available_subtypes().zint*r   r   N)r   rA  r   r  r  rC  ranger8  )
count_flagr&  r  r   s       r   r   r   e  su      HVEOODIz5$+e2D2DEEEE!Hoo 4 4
:{3333334 4r   c                     t          | t                    st          d|           	 t          |                                          }n # t
          $ r t          d|           w xY w|S )z4Check if `format_str` is valid and return format ID.zInvalid format: zUnknown format: )r  r  r  rH   r  r  r  )
format_strr   s     r   r  r  m  s    j#&& ;9:99:::<j..001

 < < <:J::;;;<s   A	 	A&c           	          |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  ro  r   r   r  )r   r  r  allhasattr)r   r#  readonly	writeonlys       r   r  r  x  s~    4=(HDN*Iffg*(fGz!:!:Gi	   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   r2  r2    s        77Dr   r2  c                       e Zd ZdZdS )r  zKsoundfile module runtime error.

    Errors that used to be `RuntimeError`.Nr3  r   r   r   r  r    s        . . 	Dr   r  c                   P    e Zd ZdZd
dededdfdZedefd            Zdefd	Z	dS )r  zjlibsndfile errors.


    Attributes
    ----------
    code
        libsndfile internal error number.
    rG  coder  r   Nc                 Z    t                               | ||           || _        || _        d S r   )r  r   r6  r  )r   r6  r  s      r   r   zLibsndfileError.__init__  s,    &&tT6:::	r   c                     | j         rGt                              | j                   }t          j        |                              dd          S dS )zRaw libsndfile error message.r   r   z'(Garbled error message from libsndfile))r6  r   sf_error_numberr   rD  rE  )r   err_strs     r   error_stringzLibsndfileError.error_string  sK     9 	=**4955G;w''..w	BBB
 =<r   c                      | j         | j        z   S r   )r  r;  r%  s    r   __str__zLibsndfileError.__str__  s    {T...r   rG  )
r   r   r   r   r   r  r   r   r;  r=  r   r   r   r  r    s          S # t    
 	=c 	= 	= 	= X	=/ / / / / / /r   r  )r   r   Nr   FNNNNNNNT)NNNTNN)Nr   r   r   Nr   FNNNNNNNT)Fr   )NNr>  )mr   __version__osr  sysr  	threadingr  collections.abcr   ctypes.utilr   _find_libraryr   r   r   typingr   r	   r
   r   r   r   typing_extensionsr   
_soundfiler   r   r  r   r  r   __annotations__ndarraytupler   r   r   r   r   r   r   r   r-   r   rH   r   r   r   r   r   r  r   _machine_packaged_libname	sysconfig
_sysconfigget_platform_win_machiner  _soundfile_datar  dirname__file___pathr   
_full_pathdlopenr   ImportErrorr  _libname_explicit_libnameisdir_hbrew_pathrD  sf_version_stringrE  __libsndfile_version__
startswithrs  r   r   r   r   r   r   r   r   r   r   r  r   rZ  r   r  r  r  r/  SFC_GET_FORMAT_INFOr8  r   r  r  r  r2  RuntimeErrorr  r  r   r   r   <module>rb     s  	 	 	              % % % % % % 5 5 5 5 5 5 + + + + + + + + + + ; ; ; ; ; ; ; ; ; ; ; ; ; ;  " " " " " " " " " " " ""%)h"6c9J"J i J J J}U38_ek%-RWR_B_bgbmBmpup{B{6|%|}	9 } } }-c3hU]UZUbEbejepEpsxs~E~9(  Ai  A  A  AEF	9 F F F								 % %
E$sCx.!   #	X#
X# 	X# 
X	#
 
X# 
X# X# 
X# X# 
X# X# X# 
X# 	X# 
X#  
X!#" 
X##$ 5# # #%S#X
   :#$f#$f#$ f#$ f	#$
 f#$ f#$ f#$ f#$ f#$ f#$ f#$ f#$ f#$ f#$ f#$  f!#$" f##$ #$$ f%#$& f'#$( f)#$* f+#$, f-#$. f/#$0 f1#$2 f3#$4 f5#$6 f7#$8 f9#$: f;#$< f=#$> f?#$@ fA#$B fC#$D fE#$ #$	5c3h  # # #L 	# #%S#X
   ,	X,
X, 	X,
 
X, 
X, X, 
X, X, 
X, X, X, 
X, 	Y, 
X,  
X!," 
X#,$ X%,& 5, , , 5c3h(   < 	% %
E$sCx.!    ) )d38n%   82}  000000)HHJJ6A	'	!	!&&&&.z.00;&& 6[(( 4W$$ 4'K\KKLLL	'	!	!0000008::FFF 5 -

 :U Bg=>>>H_566Eu&788J4;z""DDi( 2 2 22 =++'TUUUt{8$$ 2 2 2=H$$ 2]g%% 0]g%% / 	100000=H$$w)>)>25(..AU2V2V '..& 4;sx}}[:KLLMMDD4;011D'228 %T%;%;%=%=>>EEgyYY $$]33 I3CC4F4F4G4GH t}imuy37\ \# \S \c \SSWZ \gp \\-2T\\GPS_G_bfGf\$J\14t\LORVJ\hknrhr\ d
\ -1\ =B)lBZ\_B_<`\ \ \ \B <@59,0%)	9 9$ 9I 93 9:9.1Dj9*9.29 #T\9 d
	9 /3	9 9 9 9v @D<=7@?CQU=A<@:[ :[% :[#* :[:[%(:[69:[t:[+4:[ :[ 16:[ L(4/	:[ EH$J	:[
 4Z:[
 14d
:[ $J:[ 03Tz:[ :[ %.it.C$DyQ]_ceiQiGj$j:[ :[ :[ :[z1 1 1 1 1 1 1 1h) )# )d )~ ) ) ) )F4S> F F F F*D DsTz DT#s(^ D D D D. 59&*  sTz t/3   &1C 1C$J 1 1 1 1 Z[ Z[ Z[ Z[ Z[ Z[ Z[ Z[z2 2 2 2  @  &  6  0   *.)A J J J J4 4 4  	 	 		 	 	 	 	Y 	 	 		 	 	 	 	NL 	 	 	/ / / / /+ / / / / /s8   C3N Q((N87Q(8B'Q"Q(!Q""Q('Q(