
    VpfO                    r   d Z dZddl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 ]Z ee          Ze n ed           ej        e          Zn# e$ r  ej                    dk    rd	Zn0 ej                    d
k    rd ej                    d         z   dz   Zn ddlZej                             e eej                            de          Z ej        e          ZY nw xY wej        ej        ej        ej        ej         ej!        dZ"da#da$dRdZ%	 	 dSdZ&	 	 dSdZ'dTdZ(dTdZ)d Z*d Z+dUdZ,dVdZ-	 	 dWdZ.	 	 dWdZ/d Z0d Z1 G d d          Z2 G d  d!e2          Z3 G d" d#e2          Z4 G d$ d%e3e4          Z5 G d& d'e3          Z6 G d( d)e4          Z7 G d* d+e6e7          Z8 G d, d-e9          Z: G d. d/          Z; G d0 d1          Z< G d2 d3          Z= e>ed4          s
 e=            Z= G d5 d6e?          Z@ G d7 d8e?          ZA G d9 d:e?          ZB G d; d<          ZC G d= d>          ZD G d? d@          ZE G dA dB          ZFdC ZGdD ZHdE ZIdF ZJdG ZKdH ZLdI ZMdJ ZNdXdLZOdYdMZPdN ZQdO ZRdP ZS ejT        eS            eQ             eUdQk    r eV e,                       dS dS )Za  Play and Record Sound with Python.

API overview:
  * Convenience functions to play and record NumPy arrays:
    `play()`, `rec()`, `playrec()` and the related functions
    `wait()`, `stop()`, `get_status()`, `get_stream()`

  * Functions to get information about the available hardware:
    `query_devices()`, `query_hostapis()`,
    `check_input_settings()`, `check_output_settings()`

  * Module-wide default settings: `default`

  * Platform-specific settings:
    `AsioSettings`, `CoreAudioSettings`, `WasapiSettings`

  * PortAudio streams, using NumPy arrays:
    `Stream`, `InputStream`, `OutputStream`

  * PortAudio streams, using Python buffer objects (NumPy not needed):
    `RawStream`, `RawInputStream`, `RawOutputStream`

  * Miscellaneous functions and classes:
    `sleep()`, `get_portaudio_version()`, `CallbackFlags`,
    `CallbackStop`, `CallbackAbort`

Online documentation:
    https://python-sounddevice.readthedocs.io/

z0.4.7    N)find_library)ffi)	portaudiozbin\libportaudio-2.dllzlib/libportaudio.dylibzPortAudio library not foundDarwinzlibportaudio.dylibWindowslibportaudioz.dllzportaudio-binaries)float32int32int24int16int8uint8Fc                     t          |                              | ||                    d                    _        fd} j        t
          |j        j        ||fddi| dS )a
  Play back a NumPy array containing audio data.

    This is a convenience function for interactive use and for small
    scripts.  It cannot be used for multiple overlapping playbacks.

    This function does the following steps internally:

    * Call `stop()` to terminate any currently running invocation
      of `play()`, `rec()` and `playrec()`.

    * Create an `OutputStream` and a callback function for taking care
      of the actual playback.

    * Start the stream.

    * If ``blocking=True`` was given, wait until playback is done.
      If not, return immediately
      (to start waiting at a later point, `wait()` can be used).

    If you need more control (e.g. block-wise gapless playback, multiple
    overlapping playbacks, ...), you should explicitly create an
    `OutputStream` yourself.
    If NumPy is not available, you can use a `RawOutputStream`.

    Parameters
    ----------
    data : array_like
        Audio data to be played back.  The columns of a two-dimensional
        array are interpreted as channels, one-dimensional arrays are
        treated as mono data.
        The data types *float64*, *float32*, *int32*, *int16*, *int8*
        and *uint8* can be used.
        *float64* data is simply converted to *float32* before passing
        it to PortAudio, because it's not supported natively.
    mapping : array_like, optional
        List of channel numbers (starting with 1) where the columns of
        *data* shall be played back on.  Must have the same length as
        number of channels in *data* (except if *data* is mono, in which
        case the signal is played back on all given output channels).
        Each channel number may only appear once in *mapping*.
    blocking : bool, optional
        If ``False`` (the default), return immediately (but playback
        continues in the background), if ``True``, wait until playback
        is finished.  A non-blocking invocation can be stopped with
        `stop()` or turned into a blocking one with `wait()`.
    loop : bool, optional
        Play *data* in a loop.

    Other Parameters
    ----------------
    samplerate, **kwargs
        All parameters of `OutputStream` -- except *channels*, *dtype*,
        *callback* and *finished_callback* -- can be used.

    Notes
    -----
    If you don't specify the correct sampling rate
    (either with the *samplerate* argument or by assigning a value to
    `default.samplerate`), the audio data will be played back,
    but it might be too slow or too fast!

    See Also
    --------
    rec, playrec

    )loopdevicec                     t          |           |k    sJ                     ||                                |                                             d S N)lencallback_enterwrite_outdatacallback_exit)outdataframestimestatusctxs       K/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/sounddevice.pycallbackzplay.<locals>.callback   s\    7||v%%%%67+++'"""    *prime_output_buffers_using_stream_callbackFN)_CallbackContext
check_datagetr   start_streamOutputStreamoutput_channelsoutput_dtype)data
sampleratemappingblockingr   kwargsr   r   s          @r   playr-   b   s    H 
%
%
%Cgvzz(/C/CDDCJ     C\:s/B%x @E     r   c                    	 t                      		                    || |||          \  }	_        	fd} 	j        t          |	j        	j        ||fi | |S )a  Record audio data into a NumPy array.

    This is a convenience function for interactive use and for small
    scripts.

    This function does the following steps internally:

    * Call `stop()` to terminate any currently running invocation
      of `play()`, `rec()` and `playrec()`.

    * Create an `InputStream` and a callback function for taking care
      of the actual recording.

    * Start the stream.

    * If ``blocking=True`` was given, wait until recording is done.
      If not, return immediately
      (to start waiting at a later point, `wait()` can be used).

    If you need more control (e.g. block-wise gapless recording,
    overlapping recordings, ...), you should explicitly create an
    `InputStream` yourself.
    If NumPy is not available, you can use a `RawInputStream`.

    Parameters
    ----------
    frames : int, sometimes optional
        Number of frames to record.  Not needed if *out* is given.
    channels : int, optional
        Number of channels to record.  Not needed if *mapping* or *out*
        is given.  The default value can be changed with
        `default.channels`.
    dtype : str or numpy.dtype, optional
        Data type of the recording.  Not needed if *out* is given.
        The data types *float64*, *float32*, *int32*, *int16*, *int8*
        and *uint8* can be used.  For ``dtype='float64'``, audio data is
        recorded in *float32* format and converted afterwards, because
        it's not natively supported by PortAudio.  The default value can
        be changed with `default.dtype`.
    mapping : array_like, optional
        List of channel numbers (starting with 1) to record.
        If *mapping* is given, *channels* is silently ignored.
    blocking : bool, optional
        If ``False`` (the default), return immediately (but recording
        continues in the background), if ``True``, wait until recording
        is finished.
        A non-blocking invocation can be stopped with `stop()` or turned
        into a blocking one with `wait()`.

    Returns
    -------
    numpy.ndarray or type(out)
        The recorded data.

        .. note:: By default (``blocking=False``), an array of data is
           returned which is still being written to while recording!
           The returned data is only valid once recording has stopped.
           Use `wait()` to make sure the recording is finished.

    Other Parameters
    ----------------
    out : numpy.ndarray or subclass, optional
        If *out* is specified, the recorded data is written into the
        given array instead of creating a new array.
        In this case, the arguments *frames*, *channels* and *dtype* are
        silently ignored!
        If *mapping* is given, its length must match the number of
        channels in *out*.
    samplerate, **kwargs
        All parameters of `InputStream` -- except *callback* and
        *finished_callback* -- can be used.

    Notes
    -----
    If you don't specify a sampling rate (either with the *samplerate*
    argument or by assigning a value to `default.samplerate`),
    the default sampling rate of the sound device will be used
    (see `query_devices()`).

    See Also
    --------
    play, playrec

    c                     t          |           |k    sJ                     ||                                |                                             d S r   )r   r   read_indatar   )indatar   r   r   r   s       r   r   zrec.<locals>.callback  sZ    6{{f$$$$66***r   )r!   	check_outr   r$   InputStreaminput_channelsinput_dtype)
r   r)   channelsdtypeoutr*   r+   r,   r   r   s
            @r   recr9      s    l 

CmmC5'JJOC     C[*c.@_hD D<BD D DJr   c                 r   t                                          | ||                    d                    }	|j        j        }                    ||	|||          \  }}
|
|	k    rt          d          |
_        fd} j        t          |j
        j        fj        j        f||fddi| |S )aR	  Simultaneous playback and recording of NumPy arrays.

    This function does the following steps internally:

    * Call `stop()` to terminate any currently running invocation
      of `play()`, `rec()` and `playrec()`.

    * Create a `Stream` and a callback function for taking care of the
      actual playback and recording.

    * Start the stream.

    * If ``blocking=True`` was given, wait until playback/recording is
      done.  If not, return immediately
      (to start waiting at a later point, `wait()` can be used).

    If you need more control (e.g. block-wise gapless playback and
    recording, realtime processing, ...),
    you should explicitly create a `Stream` yourself.
    If NumPy is not available, you can use a `RawStream`.

    Parameters
    ----------
    data : array_like
        Audio data to be played back.  See `play()`.
    channels : int, sometimes optional
        Number of input channels, see `rec()`.
        The number of output channels is obtained from *data.shape*.
    dtype : str or numpy.dtype, optional
        Input data type, see `rec()`.
        If *dtype* is not specified, it is taken from *data.dtype*
        (i.e. `default.dtype` is ignored).
        The output data type is obtained from *data.dtype* anyway.
    input_mapping, output_mapping : array_like, optional
        See the parameter *mapping* of `rec()` and `play()`,
        respectively.
    blocking : bool, optional
        If ``False`` (the default), return immediately (but continue
        playback/recording in the background), if ``True``, wait until
        playback/recording is finished.
        A non-blocking invocation can be stopped with `stop()` or turned
        into a blocking one with `wait()`.

    Returns
    -------
    numpy.ndarray or type(out)
        The recorded data.  See `rec()`.

    Other Parameters
    ----------------
    out : numpy.ndarray or subclass, optional
        See `rec()`.
    samplerate, **kwargs
        All parameters of `Stream` -- except *channels*, *dtype*,
        *callback* and *finished_callback* -- can be used.

    Notes
    -----
    If you don't specify the correct sampling rate
    (either with the *samplerate* argument or by assigning a value to
    `default.samplerate`), the audio data will be played back,
    but it might be too slow or too fast!

    See Also
    --------
    play, rec

    r   Nzlen(data) != len(out)c                    t          |           t          |          cxk    r|k    sn J                     ||                                |                                |                                            d S r   )r   r   r0   r   r   )r1   r   r   r   r   r   s        r   r   zplayrec.<locals>.callbackj  s    6{{c'll4444f44444466***'"""r   r    F)r!   r"   r#   r(   r7   r2   
ValueErrorr   r$   Streamr4   r&   r5   r'   )r(   r)   r6   r7   r8   input_mappingoutput_mappingr+   r,   output_framesinput_framesr   r   s               @r   playrecrB     s    N 

CNN4H9M9MNNM}c=(E&35 5C}$$0111CJ     CVZ(#*=>os'78x  AF	
    Jr   Tc                 H    t           rt                               |           S dS )ad  Wait for `play()`/`rec()`/`playrec()` to be finished.

    Playback/recording can be stopped with a `KeyboardInterrupt`.

    Returns
    -------
    CallbackFlags or None
        If at least one buffer over-/underrun happened during the last
        playback/recording, a `CallbackFlags` object is returned.

    See Also
    --------
    get_status

    N)_last_callbackwaitignore_errorss    r   rE   rE   z  s*       2""=1112 2r   c                     t           r@t           j                            |            t           j                            |            dS dS )zStop playback/recording.

    This only stops `play()`, `rec()` and `playrec()`, but has no
    influence on streams created with `Stream`, `InputStream`,
    `OutputStream`, `RawStream`, `RawInputStream`, `RawOutputStream`.

    N)rD   streamstopcloserF   s    r   rJ   rJ     sL      3 	""=111##M22222	3 3r   c                  F    t           rt           j        S t          d          )a  Get info about over-/underflows in `play()`/`rec()`/`playrec()`.

    Returns
    -------
    CallbackFlags
        A `CallbackFlags` object that holds information about the last
        invocation of `play()`, `rec()` or `playrec()`.

    See Also
    --------
    wait

    )play()/rec()/playrec() was not called yet)rD   r   RuntimeError r   r   
get_statusrP     %      H$$FGGGr   c                  F    t           rt           j        S t          d          )aH  Get a reference to the current stream.

    This applies only to streams created by calls to `play()`, `rec()`
    or `playrec()`.

    Returns
    -------
    Stream
        An `OutputStream`, `InputStream` or `Stream` associated with
        the last invocation of `play()`, `rec()` or `playrec()`,
        respectively.

    rM   )rD   rI   rN   rO   r   r   
get_streamrS     rQ   r   c                    |dvrt          d|          | L|Jt          d t          t          t                                                              D                       S t          | |d          } t                              |           }|st          d|            |j	        dk    sJ t          j        |j                  }	 |                    d	          }n# t          $ r t          j        }|j         |t          j                   |t          j                  fv r|                    d
          }nK|j         |t          j                  k    r,ddl}|                    |                                          }n Y nw xY w|| |j        |j        |j        |j        |j        |j        |j        |j        d
}|r;|d|z   dz            dk     r)t          d                    ||d                             |S )a4  Return information about available devices.

    Information and capabilities of PortAudio devices.
    Devices may support input, output or both input and output.

    To find the default input/output device(s), use `default.device`.

    Parameters
    ----------
    device : int or str, optional
        Numeric device ID or device name substring(s).
        If specified, information about only the given *device* is
        returned in a single dictionary.
    kind : {'input', 'output'}, optional
        If *device* is not specified and *kind* is ``'input'`` or
        ``'output'``, a single dictionary is returned with information
        about the default input or output device, respectively.

    Returns
    -------
    dict or DeviceList
        A dictionary with information about the given *device* or -- if
        no arguments were specified -- a `DeviceList` containing one
        dictionary for each available device.
        The dictionaries have the following keys:

        ``'name'``
            The name of the device.
        ``'index'``
            The device index.
        ``'hostapi'``
            The ID of the corresponding host API.  Use
            `query_hostapis()` to get information about a host API.
        ``'max_input_channels'``, ``'max_output_channels'``
            The maximum number of input/output channels supported by the
            device.  See `default.channels`.
        ``'default_low_input_latency'``, ``'default_low_output_latency'``
            Default latency values for interactive performance.
            This is used if `default.latency` (or the *latency* argument
            of `playrec()`, `Stream` etc.) is set to ``'low'``.
        ``'default_high_input_latency'``, ``'default_high_output_latency'``
            Default latency values for robust non-interactive
            applications (e.g. playing sound files).
            This is used if `default.latency` (or the *latency* argument
            of `playrec()`, `Stream` etc.) is set to ``'high'``.
        ``'default_samplerate'``
            The default sampling frequency of the device.
            This is used if `default.samplerate` is not set.

    Notes
    -----
    The list of devices can also be displayed in a terminal:

    .. code-block:: sh

        python3 -m sounddevice

    Examples
    --------
    The returned `DeviceList` can be indexed and iterated over like any
    sequence type (yielding the abovementioned dictionaries), but it
    also has a special string representation which is shown when used in
    an interactive Python session.

    Each available device is listed on one line together with the
    corresponding device ID, which can be assigned to `default.device`
    or used as *device* argument in `play()`, `Stream` etc.

    The first character of a line is ``>`` for the default input device,
    ``<`` for the default output device and ``*`` for the default
    input/output device.  After the device ID and the device name, the
    corresponding host API name is displayed.  In the end of each line,
    the maximum number of input and output channels is shown.

    On a GNU/Linux computer it might look somewhat like this:

    >>> import sounddevice as sd
    >>> sd.query_devices()
       0 HDA Intel: ALC662 rev1 Analog (hw:0,0), ALSA (2 in, 2 out)
       1 HDA Intel: ALC662 rev1 Digital (hw:0,1), ALSA (0 in, 2 out)
       2 HDA Intel: HDMI 0 (hw:0,3), ALSA (0 in, 8 out)
       3 sysdefault, ALSA (128 in, 128 out)
       4 front, ALSA (0 in, 2 out)
       5 surround40, ALSA (0 in, 2 out)
       6 surround51, ALSA (0 in, 2 out)
       7 surround71, ALSA (0 in, 2 out)
       8 iec958, ALSA (0 in, 2 out)
       9 spdif, ALSA (0 in, 2 out)
      10 hdmi, ALSA (0 in, 8 out)
    * 11 default, ALSA (128 in, 128 out)
      12 dmix, ALSA (0 in, 2 out)
      13 /dev/dsp, OSS (16 in, 16 out)

    Note that ALSA provides access to some "real" and some "virtual"
    devices.  The latter sometimes have a ridiculously high number of
    (virtual) inputs and outputs.

    On macOS, you might get something similar to this:

    >>> sd.query_devices()
      0 Built-in Line Input, Core Audio (2 in, 0 out)
    > 1 Built-in Digital Input, Core Audio (2 in, 0 out)
    < 2 Built-in Output, Core Audio (0 in, 2 out)
      3 Built-in Line Output, Core Audio (0 in, 2 out)
      4 Built-in Digital Output, Core Audio (0 in, 2 out)

    inputoutputNzInvalid kind: Nc              3   4   K   | ]}t          |          V  d S r   )query_devices.0is     r   	<genexpr>z query_devices.<locals>.<genexpr>4  sF       L L (** L L L L L Lr   Traise_on_errorzError querying device    zutf-8mbcsr   )
nameindexhostapimax_input_channelsmax_output_channelsdefault_low_input_latencydefault_low_output_latencydefault_high_input_latencydefault_high_output_latencydefault_sampleratemax_	_channels   zNot an {} device: {!r}rb   )r<   
DeviceListrange_check_libPa_GetDeviceCount_get_device_idPa_GetDeviceInfoPortAudioErrorstructVersion_ffistringrb   decodeUnicodeDecodeErrorPa_HostApiTypeIdToHostApiIndexhostApipaDirectSoundpaMMEpaASIOlocalegetpreferredencodingmaxInputChannelsmaxOutputChannelsdefaultLowInputLatencydefaultLowOutputLatencydefaultHighInputLatencydefaultHighOutputLatencydefaultSampleRateformat)r   kindinfo
name_bytesrb   api_idxr   device_dicts           r   rY   rY     sO   X ,,,2$22333~$, L L#(0F0F0H0H)I)I#J#JL L L L L 	LFD>>>F  ((D @>f>>???""""TY''J
   )) 	 	 	5<GGD$6779L9LMMM$$V,,DD\WWT[1111MMM$$V%@%@%B%BCCDD	 <"3#5%)%@&*&B&*&B'+'D"4 K  HFTMK781<<$++D+f2EFFH H 	Hs   C" "B(FFc           	           Jt          d t          t          t                                                              D                       S t                                         }|st          d            |j        dk    sJ t          j	        |j
                                                   fdt          |j                  D             |j        |j        dS )a  Return information about available host APIs.

    Parameters
    ----------
    index : int, optional
        If specified, information about only the given host API *index*
        is returned in a single dictionary.

    Returns
    -------
    dict or tuple of dict
        A dictionary with information about the given host API *index*
        or -- if no *index* was specified -- a tuple containing one
        dictionary for each available host API.
        The dictionaries have the following keys:

        ``'name'``
            The name of the host API.
        ``'devices'``
            A list of device IDs belonging to the host API.
            Use `query_devices()` to get information about a device.
        ``'default_input_device'``, ``'default_output_device'``
            The device ID of the default input/output device of the host
            API.  If no default input/output device exists for the given
            host API, this is -1.

            .. note:: The overall default device(s) -- which can be
                overwritten by assigning to `default.device` -- take(s)
                precedence over `default.hostapi` and the information in
                the abovementioned dictionaries.

    See Also
    --------
    query_devices

    Nc              3   4   K   | ]}t          |          V  d S r   )query_hostapisrZ   s     r   r]   z!query_hostapis.<locals>.<genexpr>  sF       H H $A&& H H H H H Hr   zError querying host API rn   c                 F    g | ]}t                               |          S rO   )rr   "Pa_HostApiDeviceIndexToDeviceIndex)r[   r\   rc   s     r   
<listcomp>z"query_hostapis.<locals>.<listcomp>  s9     6 6 6 ;;E1EE 6 6 6r   )rb   devicesdefault_input_devicedefault_output_device)tuplerp   rq   rr   Pa_GetHostApiCountPa_GetHostApiInforv   rw   rx   ry   rb   rz   deviceCountdefaultInputDevicedefaultOutputDevice)rc   r   s   ` r   r   r   ^  s   J } H H#F4+B+B+D+D$E$EFFH H H H H 	H!!%((D A???@@@""""DI&&--//6 6 6 6"4#3446 6 6 $ 7!%!9  r   c           	          t          d| ||d||          \  }}}}t          t                              |t          j        |                     dS )a%  Check if given input device settings are supported.

    All parameters are optional, `default` settings are used for any
    unspecified parameters.  If the settings are supported, the function
    does nothing; if not, an exception is raised.

    Parameters
    ----------
    device : int or str, optional
        Device ID or device name substring(s), see `default.device`.
    channels : int, optional
        Number of input channels, see `default.channels`.
    dtype : str or numpy.dtype, optional
        Data type for input samples, see `default.dtype`.
    extra_settings : settings object, optional
        This can be used for host-API-specific input settings.
        See `default.extra_settings`.
    samplerate : float, optional
        Sampling frequency, see `default.samplerate`.

    rV   Nr   r6   r7   latencyextra_settingsr)   _get_stream_parametersrq   rr   Pa_IsFormatSupportedrx   NULLr   r6   r7   r   r)   
parameters
samplesizes          r   check_input_settingsr     s\    . 1G%*1> 1> 1>-Jz: 4$$ZJGGHHHHHr   c           	          t          d| ||d||          \  }}}}t          t                              t          j        ||                     dS )zCheck if given output device settings are supported.

    Same as `check_input_settings()`, just for output device
    settings.

    rW   Nr   r   r   s          r   check_output_settingsr     s\     1G(%%*1> 1> 1>-Jz: 4$$TY
JGGHHHHHr   c                 :    t                               |            dS )zPut the caller to sleep for at least *msec* milliseconds.

    The function may sleep longer than requested so don't rely on this
    for accurate musical timing.

    N)rr   Pa_Sleep)msecs    r   sleepr     s     	MM$r   c                      t                                           t          j        t                                                                                     fS )zGet version information for the PortAudio library.

    Returns the release number and a textual description of the current
    PortAudio build, e.g. ::

        (1899, 'PortAudio V19-devel (built Feb 15 2014 23:28:00)')

    )rr   Pa_GetVersionrx   ry   Pa_GetVersionTextrz   rO   r   r   get_portaudio_versionr     s=     T-C-C-E-E!F!F!M!M!O!OOOr   c                   f   e Zd ZdZ	 	 	 	 	 	 ddZej        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 Zd ZddZddZddZdS )_StreamBasez5Direct or indirect base class for all stream classes.Nc                    	
 |dv sJ |dv sJ |dk    rddl }|sJ |t          j        }|t          j        }|t          j        }|t          j        }|t          j        }t          j        }|r|t          j	        z  }|r|t          j
        z  }|r|t          j        z  }|r|t          j        z  }|dk    rt          |          \  }}t          |          \  }}t          |          \  }}t          |          \  }}t          |          \  }}t          d||||||          \  }}}}t          d||||||          \  } }}!}"||f _        |j        | j        f _        |j        | j        f _        ||!f _        ||"k    rt+          d	          |}net          |||||||          \  }# _         _        }|#j         _        |#j         _        |dk    r|#}t,          j        } n|dk    rt,          j        }|#} t-          j        d
t          j                  }$	t,          j        }%n|dk    r|dk    r|$	 fd            }%n|dk    r|dk    r|$	 fd            }%n|dk    r|dk    r|$	 fd            }%nf|dk    r|dk    r|$	 fd            }%nK|dk    r|dk    r|$	 fd            }%n0|dk    r|dk    r|$	 fd            }%nt-          j        d	          }%|% _        |t,          j        }t-          j        d           _        t=          t                               j        || ||||%|          d j         j!                     j        d          _        | _"        t          #                     j                  }&|&stI          d          |&j%         _&        | s|&j'         _(        n"|s|&j)         _(        n|&j'        |&j)        f _(        
rutU          
t,          j+                  r
 _,        n
fd}'t-          j        d|'           _,        t=          t          -                     j         j,                             dS dS )a  Base class for PortAudio streams.

        This class should only be used by library authors who want to
        create their own custom stream classes.
        Most users should use the derived classes
        `Stream`, `InputStream`, `OutputStream`,
        `RawStream`, `RawInputStream` and `RawOutputStream` instead.

        This class has the same properties and methods as `Stream`,
        except for `read_available`/:meth:`~Stream.read` and
        `write_available`/:meth:`~Stream.write`.

        It can be created with the same parameters as `Stream`,
        except that there are three additional parameters
        and the *callback* parameter also accepts a C function pointer.

        Parameters
        ----------
        kind : {'input', 'output', 'duplex'}
            The desired type of stream: for recording, playback or both.
        callback : Python callable or CData function pointer, optional
            If *wrap_callback* is ``None`` this can be a function pointer
            provided by CFFI.
            Otherwise, it has to be a Python callable.
        wrap_callback : {'array', 'buffer'}, optional
            If *callback* is a Python callable, this selects whether
            the audio data is provided as NumPy array (like in `Stream`)
            or as Python buffer object (like in `RawStream`).
        userdata : CData void pointer
            This is passed to the underlying C callback function
            on each call and can only be accessed from a *callback*
            provided as ``CData`` function pointer.

        Examples
        --------
        A usage example of this class can be seen at
        https://github.com/spatialaudio/python-rtmixer.

        )rV   rW   duplex)arraybufferNr   r   Nr   rV   rW   z5Input and output device must have the same sampleratePaStreamCallback)errorr   c                 b    t          | |j        j                  }t          ||||          S r   _bufferrm   _samplesize_wrap_callback	iptroptrr   r   r   _r(   r   selfs	          r   callback_ptrz*_StreamBase.__init__.<locals>.callback_ptrJ  1    tVT^T=MNN%hfdFKKKr   c                     t          t          | |j        j                  j        j                  }t          ||||          S r   _arrayr   rm   r   _dtyper   r   s	          r   r   z*_StreamBase.__init__.<locals>.callback_ptrQ  I    D&$.$:JKKNDK1 1 &hfdFKKKr   c                 b    t          ||j        j                  }t          ||||          S r   r   r   s	          r   r   z*_StreamBase.__init__.<locals>.callback_ptrZ  r   r   c                     t          t          ||j        j                  j        j                  }t          ||||          S r   r   r   s	          r   r   z*_StreamBase.__init__.<locals>.callback_ptra  r   r   c                     j         \  }}j        \  }}	t          | |||          }
t          ||||	          }t          |
||||          S r   )rm   r   r   r   )r   r   r   r   r   r   	ichannels	ochannelsisizeosizeidataodatar   r   s               r   r   z*_StreamBase.__init__.<locals>.callback_ptrj  sc    '+~$	9#/ufi??fi??%eUFD&B B Br   c                     j         \  }}j        \  }}	j        \  }
}t          t	          | |||
          ||          }t          t	          ||||          ||	          }t          |||||          S r   )rm   r   r   r   r   r   )r   r   r   r   r   r   r   r   idtypeodtyper   r   r   r   r   r   s                 r   r   z*_StreamBase.__init__.<locals>.callback_ptru  s    '+~$	9!%#/uwtVYFF(&2 2wtVYFF(&2 2%eUFD&B B Br   zPaStreamCallback*z
PaStream**zError opening zCould not obtain stream infoc                                  S r   rO   )r   finished_callbacks    r   finished_callback_wrapperz7_StreamBase.__init__.<locals>.finished_callback_wrapper  s    ,,...r   PaStreamFinishedCallback).numpydefault	blocksizeclip_off
dither_offnever_drop_inputr    rr   paNoFlag	paClipOffpaDitherOffpaNeverDropInput'paPrimeOutputBuffersUsingStreamCallback_splitr   r   r   _devicechannelCountrm   r   r<   rx   r   r   paAbortcast	_callbacknew_ptrrq   Pa_OpenStream	__class____name__
_blocksizePa_GetStreamInforv   
sampleRate_samplerateinputLatency_latencyoutputLatency
isinstanceCData_finished_callbackPa_SetStreamFinishedCallback)(r   r   r)   r   r   r6   r7   r   r   r   r   r   r   r   r    userdatawrap_callbackr   stream_flagsideviceodevicer   r   r   r   ilatencyolatencyiextraoextraiparametersr   isamplerateoparametersr   osamplerater   ffi_callbackr   r   r   s(   `        ``                             r   __init__z_StreamBase.__init__  s   Z 44444 99999G## LLLLLL)I'H +J#&75=B 7 } 	+DN*L 	-D,,L 	2D11L5 	IDHHL8%f~~GW#)(#3#3 Iy#E]]NFF!'Hh#N33NFF6L)VXv7 73K 7M'9fh7 73K !&.DK&-{/AADL(5{7OODN$e|Dk)) KM M M )

 'tVXug'5zC C BJT%5z &,DL'4DNw("i!!"i(}%7t|LLL9LLW__(!:!:L L L L L \L L W__'!9!9L L L L L \L L X-8";";L L L L L \L L X-7":":L L L L L \L L X-8";";B B B B B \B B X-7":":	B 	B 	B 	B 	B \	B 	B  9%8(CCL &yHH\**	t!!$)[+",i".: : : 799	; 	; 	; IaL	#$$TY// 	A !?@@@? 	B -DMM 	B .DMM -t/AADM 	O+TZ88 	K*;''/ / / / / +/-.0I+K +K'444TY595LN N O O O O O	O 	Or   c                     | j         S )a  The sampling frequency in Hertz (= frames per second).

        In cases where the hardware sampling frequency is inaccurate and
        PortAudio is aware of it, the value of this field may be
        different from the *samplerate* parameter passed to `Stream()`.
        If information about the actual hardware sampling frequency is
        not available, this field will have the same value as the
        *samplerate* parameter passed to `Stream()`.

        )r   r   s    r   r)   z_StreamBase.samplerate  s     r   c                     | j         S )zNumber of frames per block.

        The special value 0 means that the blocksize can change between
        blocks.  See the *blocksize* argument of `Stream`.

        )r   r  s    r   r   z_StreamBase.blocksize  s     r   c                     | j         S )zIDs of the input/output device.)r   r  s    r   r   z_StreamBase.device  s     |r   c                     | j         S )z$The number of input/output channels.)rm   r  s    r   r6   z_StreamBase.channels  s     ~r   c                     | j         S )znData type of the audio samples.

        See Also
        --------
        default.dtype, samplesize

        )r   r  s    r   r7   z_StreamBase.dtype  s     {r   c                     | j         S )z`The size in bytes of a single sample.

        See Also
        --------
        dtype

        )r   r  s    r   r   z_StreamBase.samplesize  s     r   c                     | j         S )a  The input/output latency of the stream in seconds.

        This value provides the most accurate estimate of input/output
        latency available to the implementation.
        It may differ significantly from the *latency* value(s) passed
        to `Stream()`.

        )r   r  s    r   r   z_StreamBase.latency  s     }r   c                 t    | j         rdS t          t                              | j                            dk    S )a  ``True`` when the stream is active, ``False`` otherwise.

        A stream is active after a successful call to `start()`, until
        it becomes inactive either as a result of a call to `stop()` or
        `abort()`, or as a result of an exception raised in the stream
        callback.  In the latter case, the stream is considered inactive
        after the last buffer has finished playing.

        See Also
        --------
        stopped

        Frn   )closedrq   rr   Pa_IsStreamActiver   r  s    r   activez_StreamBase.active  s6     ; 	5d,,TY7788A==r   c                 t    | j         rdS t          t                              | j                            dk    S )a  ``True`` when the stream is stopped, ``False`` otherwise.

        A stream is considered to be stopped prior to a successful call
        to `start()` and after a successful call to `stop()` or
        `abort()`.  If a stream callback is cancelled (by raising an
        exception) the stream is *not* considered to be stopped.

        See Also
        --------
        active

        Trn   )r  rq   rr   Pa_IsStreamStoppedr   r  s    r   stoppedz_StreamBase.stopped  s6     ; 	4d--di8899Q>>r   c                 ,    | j         t          j        k    S )z8``True`` after a call to `close()`, ``False`` otherwise.)r   rx   r   r  s    r   r  z_StreamBase.closed  s     yDI%%r   c                 f    t                               | j                  }|st          d          |S )a  The current stream time in seconds.

        This is according to the same clock used to generate the
        timestamps passed with the *time* argument to the stream
        callback (see the *callback* argument of `Stream`).
        The time values are monotonically increasing and have
        unspecified origin.

        This provides valid time values for the entire life of the
        stream, from when the stream is opened until it is closed.
        Starting and stopping the stream does not affect the passage of
        time as provided here.

        This time may be used for synchronizing other events to the
        audio stream, for example synchronizing audio to MIDI.

        zError getting stream time)rr   Pa_GetStreamTimer   rv   )r   r   s     r   r   z_StreamBase.time  s5    & $$TY// 	> !<===r   c                 @    t                               | j                  S )a  CPU usage information for the stream.

        The "CPU Load" is a fraction of total CPU time consumed by a
        callback stream's audio processing routines including, but not
        limited to the client supplied stream callback. This function
        does not work with blocking read/write streams.

        This may be used in the stream callback function or in the
        application.
        It provides a floating point value, typically between 0.0 and
        1.0, where 1.0 indicates that the stream callback is consuming
        the maximum number of CPU cycles possible to maintain real-time
        operation.  A value of 0.5 would imply that PortAudio and the
        stream callback was consuming roughly 50% of the available CPU
        time.  The value may exceed 1.0.  A value of 0.0 will always be
        returned for a blocking read/write stream, or if an error
        occurs.

        )rr   Pa_GetStreamCpuLoadr   r  s    r   cpu_loadz_StreamBase.cpu_load6  s    * ''	222r   c                 .    |                                   | S )z9Start  the stream in the beginning of a "with" statement.)startr  s    r   	__enter__z_StreamBase.__enter__M  s    

r   c                 V    |                                   |                                  dS )z:Stop and close the stream when exiting a "with" statement.N)rJ   rK   )r   argss     r   __exit__z_StreamBase.__exit__R  s     		

r   c                     t                               | j                  }|t           j        k    rt	          |d           dS dS )z[Commence audio processing.

        See Also
        --------
        stop, abort

        zError starting streamN)rr   Pa_StartStreamr   paStreamIsNotStoppedrq   )r   errs     r   r$  z_StreamBase.startW  sF     !!$),,$+++3/00000 ,+r   Tc                 l    t                               | j                  }|st          |d           dS dS )zTerminate audio processing.

        This waits until all pending audio buffers have been played
        before it returns.

        See Also
        --------
        start, abort

        zError stopping streamN)rr   Pa_StopStreamr   rq   r   rG   r,  s      r   rJ   z_StreamBase.stopc  sB       ++ 	13/00000	1 	1r   c                 l    t                               | j                  }|st          |d           dS dS )zTerminate audio processing immediately.

        This does not wait for pending buffers to complete.

        See Also
        --------
        start, stop

        zError aborting streamN)rr   Pa_AbortStreamr   rq   r/  s      r   abortz_StreamBase.abortr  sB     !!$),, 	13/00000	1 	1r   c                     t                               | j                  }t          j        | _        |st          |d           dS dS )zClose the stream.

        If the audio stream is active any pending buffers are discarded
        as if `abort()` had been called.

        zError closing streamN)rr   Pa_CloseStreamr   rx   r   rq   r/  s      r   rK   z_StreamBase.close  sK     !!$),,I	 	03./////	0 	0r   )NNNNNNNNNNNNNNNT)r   
__module____qualname____doc__r  rx   r   r   propertyr)   r   r   r6   r7   r   r   r  r  r  r   r"  r%  r(  r$  rJ   r2  rK   rO   r   r   r   r     s       ??EIIMAE37<@.2TO TO TO TOn 9D    X    X   X   X   X     X  	 	 X	 > > X>$ ? ? X?" & & X&   X. 3 3 X3,  
  

1 
1 
11 1 1 11 1 1 1
0 
0 
0 
0 
0 
0r   r   c                   @    e Zd ZdZ	 	 	 	 	 ddZed             Zd ZdS )RawInputStreamz=Raw stream for recording only.  See __init__() and RawStream.Nc                 b    t          j        | fdddt          t                                 dS )a}  PortAudio input stream (using buffer objects).

        This is the same as `InputStream`, except that the *callback*
        function and :meth:`~RawStream.read` work on plain Python buffer
        objects instead of on NumPy arrays.
        NumPy is not necessary for using this.

        Parameters
        ----------
        dtype : str
            See `RawStream`.
        callback : callable
            User-supplied function to consume audio data in response to
            requests from an active stream.
            The callback must have this signature::

                callback(indata: buffer, frames: int,
                         time: CData, status: CallbackFlags) -> None

            The arguments are the same as in the *callback* parameter of
            `RawStream`, except that *outdata* is missing.

        See Also
        --------
        RawStream, Stream

        rV   r   r   r   Nr   r  _remove_selflocalsr   r)   r   r   r6   r7   r   r   r   r   r   r   r   r    s                 r   r  zRawInputStream.__init__  sH    @ 	T 	7x 	7 	7+FHH55	7 	7 	7 	7 	7r   c                 Z    t          t                              | j                            S )zThe number of frames that can be read without waiting.

        Returns a value representing the maximum number of frames that
        can be read from the stream without blocking or busy waiting.

        )rq   rr   Pa_GetStreamReadAvailabler   r  s    r   read_availablezRawInputStream.read_available  s"     d44TY??@@@r   c                 J   t          | j                  \  }}t          | j                  \  }}t          j        d||z  |z            }t
                              | j        ||          }|t
          j        k    rd}nt          |           d}t          j
        |          |fS )a  Read samples from the stream into a buffer.

        This is the same as `Stream.read()`, except that it returns
        a plain Python buffer object instead of a NumPy array.
        NumPy is not necessary for using this.

        Parameters
        ----------
        frames : int
            The number of frames to be read.  See `Stream.read()`.

        Returns
        -------
        data : buffer
            A buffer of interleaved samples. The buffer contains
            samples in the format specified by the *dtype* parameter
            used to open the stream, and the number of channels
            specified by *channels*.
            See also `samplesize`.
        overflowed : bool
            See `Stream.read()`.

        zsigned char[]TF)r   rm   r   rx   r   rr   Pa_ReadStreamr   paInputOverflowedrq   r   )r   r   r6   r   r   r(   r,  
overfloweds           r   readzRawInputStream.read  s    0 T^,,!t/00
AxJ)>)GHH  D&99$(((JJ3KKKJ{4  *,,r   NNNNNNNNNNNNN)r   r6  r7  r8  r  r9  rD  rI  rO   r   r   r;  r;    sk        GG26AEGKBF<@	!7 !7 !7 !7F A A XA!- !- !- !- !-r   r;  c                   @    e Zd ZdZ	 	 	 	 	 ddZed             Zd ZdS )RawOutputStreamz<Raw stream for playback only.  See __init__() and RawStream.Nc                 b    t          j        | fdddt          t                                 dS )a  PortAudio output stream (using buffer objects).

        This is the same as `OutputStream`, except that the *callback*
        function and :meth:`~RawStream.write` work on plain Python
        buffer objects instead of on NumPy arrays.
        NumPy is not necessary for using this.

        Parameters
        ----------
        dtype : str
            See `RawStream`.
        callback : callable
            User-supplied function to generate audio data in response to
            requests from an active stream.
            The callback must have this signature::

                callback(outdata: buffer, frames: int,
                         time: CData, status: CallbackFlags) -> None

            The arguments are the same as in the *callback* parameter of
            `RawStream`, except that *indata* is missing.

        See Also
        --------
        RawStream, Stream

        rW   r   r=  Nr>  rA  s                 r   r  zRawOutputStream.__init__  sH    @ 	T 	7 	7 	7+FHH55	7 	7 	7 	7 	7r   c                 Z    t          t                              | j                            S )zThe number of frames that can be written without waiting.

        Returns a value representing the maximum number of frames that
        can be written to the stream without blocking or busy waiting.

        )rq   rr   Pa_GetStreamWriteAvailabler   r  s    r   write_availablezRawOutputStream.write_available  s"     d55di@@AAAr   c                    	 t          j        |          }n# t          $ r Y nt          $ r Y nw xY wt	          | j                  \  }}t	          | j                  \  }}t          t          |          |          \  }}|rt          d          t          ||          \  }}|rt          d          t                              | j        ||          }|t          j        k    rd}	nt          |           d}	|	S )a}  Write samples to the stream.

        This is the same as `Stream.write()`, except that it expects
        a plain Python buffer object instead of a NumPy array.
        NumPy is not necessary for using this.

        Parameters
        ----------
        data : buffer or bytes or iterable of int
            A buffer of interleaved samples.  The buffer contains
            samples in the format specified by the *dtype* argument used
            to open the stream, and the number of channels specified by
            *channels*.  The length of the buffer is not constrained to
            a specific range, however high performance applications will
            want to match this parameter to the *blocksize* parameter
            used when opening the stream.  See also `samplesize`.

        Returns
        -------
        underflowed : bool
            See `Stream.write()`.

        z%len(data) not divisible by samplesizez+Number of samples not divisible by channelsTF)rx   from_bufferAttributeError	TypeErrorr   r   rm   divmodr   r<   rr   Pa_WriteStreamr   paOutputUnderflowedrq   )
r   r(   r   r   r6   samples	remainderr   r,  underfloweds
             r   writezRawOutputStream.write  s   0	#D))DD 	 	 	D 	 	 	D	t/00:T^,,8#CIIz:: 	FDEEE"7H55	 	LJKKK!!$)T6::$***KK3KKKKs    
/	//rJ  )r   r6  r7  r8  r  r9  rP  r[  rO   r   r   rL  rL    sk        FF26AEGKBF<@	!7 !7 !7 !7F B B XB, , , , ,r   rL  c                   $    e Zd ZdZ	 	 	 	 	 ddZdS )	RawStreamz7Raw stream for playback and recording.  See __init__().Nc                 b    t          j        | fdddt          t                                 dS )a  PortAudio input/output stream (using buffer objects).

        This is the same as `Stream`, except that the *callback*
        function and `read()`/`write()` work on plain Python buffer
        objects instead of on NumPy arrays.
        NumPy is not necessary for using this.

        To open a "raw" input-only or output-only stream use
        `RawInputStream` or `RawOutputStream`, respectively.
        If you want to handle audio data as NumPy arrays instead of
        buffer objects, use `Stream`, `InputStream` or `OutputStream`.

        Parameters
        ----------
        dtype : str or pair of str
            The sample format of the buffers provided to the stream
            callback, `read()` or `write()`.
            In addition to the formats supported by `Stream`
            (``'float32'``, ``'int32'``, ``'int16'``, ``'int8'``,
            ``'uint8'``), this also supports ``'int24'``, i.e.
            packed 24 bit format.
            The default value can be changed with `default.dtype`.
            See also `samplesize`.
        callback : callable
            User-supplied function to consume, process or generate audio
            data in response to requests from an active stream.
            The callback must have this signature::

                callback(indata: buffer, outdata: buffer, frames: int,
                         time: CData, status: CallbackFlags) -> None

            The arguments are the same as in the *callback* parameter of
            `Stream`, except that *indata* and *outdata* are plain
            Python buffer objects instead of NumPy arrays.

        See Also
        --------
        RawInputStream, RawOutputStream, Stream

        r   r   r=  Nr>  rA  s                 r   r  zRawStream.__init__C  sH    Z 	T 	7 	7 	7+FHH55	7 	7 	7 	7 	7r   rJ  r   r6  r7  r8  r  rO   r   r   r]  r]  @  s=        AA26AEGKBF<@	.7 .7 .7 .7 .7 .7r   r]  c                   *    e Zd ZdZ	 	 	 	 	 ddZd ZdS )r3   z2Stream for input only.  See __init__() and Stream.Nc                 b    t          j        | fdddt          t                                 dS )a?  PortAudio input stream (using NumPy).

        This has the same methods and attributes as `Stream`, except
        :meth:`~Stream.write` and `write_available`.
        Furthermore, the stream callback is expected to have a different
        signature (see below).

        Parameters
        ----------
        callback : callable
            User-supplied function to consume audio in response to
            requests from an active stream.
            The callback must have this signature::

                callback(indata: numpy.ndarray, frames: int,
                         time: CData, status: CallbackFlags) -> None

            The arguments are the same as in the *callback* parameter of
            `Stream`, except that *outdata* is missing.

        See Also
        --------
        Stream, RawInputStream

        rV   r   r=  Nr>  rA  s                 r   r  zInputStream.__init__w  sG    < 	T 	7w 	7 	7+FHH55	7 	7 	7 	7 	7r   c                     t          | j                  \  }}t          | j                  \  }}t                              | |          \  }}t          |||          }||fS )a  Read samples from the stream into a NumPy array.

        The function doesn't return until all requested *frames* have
        been read -- this may involve waiting for the operating system
        to supply the data (except if no more than `read_available`
        frames were requested).

        This is the same as `RawStream.read()`, except that it
        returns a NumPy array instead of a plain Python buffer object.

        Parameters
        ----------
        frames : int
            The number of frames to be read.  This parameter is not
            constrained to a specific range, however high performance
            applications will want to match this parameter to the
            *blocksize* parameter used when opening the stream.

        Returns
        -------
        data : numpy.ndarray
            A two-dimensional `numpy.ndarray` with one column per
            channel (i.e.  with a shape of ``(frames, channels)``) and
            with a data type specified by `dtype`.
        overflowed : bool
            ``True`` if input data was discarded by PortAudio after the
            previous call and before this call.

        )r   r   rm   r;  rI  r   )r   r   r7   r   r6   r(   rH  s          r   rI  zInputStream.read  s`    < $+&&qT^,,!)..tV<<jdHe,,Zr   rJ  )r   r6  r7  r8  r  rI  rO   r   r   r3   r3   t  sM        <<26AEGKBF<@	7 7 7 7B"  "  "  "  " r   r3   c                   *    e Zd ZdZ	 	 	 	 	 ddZd ZdS )r%   z3Stream for output only.  See __init__() and Stream.Nc                 b    t          j        | fdddt          t                                 dS )aE  PortAudio output stream (using NumPy).

        This has the same methods and attributes as `Stream`, except
        :meth:`~Stream.read` and `read_available`.
        Furthermore, the stream callback is expected to have a different
        signature (see below).

        Parameters
        ----------
        callback : callable
            User-supplied function to generate audio data in response to
            requests from an active stream.
            The callback must have this signature::

                callback(outdata: numpy.ndarray, frames: int,
                         time: CData, status: CallbackFlags) -> None

            The arguments are the same as in the *callback* parameter of
            `Stream`, except that *indata* is missing.

        See Also
        --------
        Stream, RawOutputStream

        rW   r   r=  Nr>  rA  s                 r   r  zOutputStream.__init__  sG    < 	T 	7 	7 	7+FHH55	7 	7 	7 	7 	7r   c                 $   ddl }|                    |          }t          | j                  \  }}t          | j                  \  }}|j        dk     r|                    dd          }n|j        dk    rt          d          |j        d         |k    rt          d          |j	        |k    r-t          d                    |j	        j        |                    |j        j        st          d	          t                              | |          S )
a  Write samples to the stream.

        This function doesn't return until the entire buffer has been
        consumed -- this may involve waiting for the operating system to
        consume the data (except if *data* contains no more than
        `write_available` frames).

        This is the same as `RawStream.write()`, except that it
        expects a NumPy array instead of a plain Python buffer object.

        Parameters
        ----------
        data : array_like
            A two-dimensional array-like object with one column per
            channel (i.e.  with a shape of ``(frames, channels)``) and
            with a data type specified by `dtype`.  A one-dimensional
            array can be used for mono data.  The array layout must be
            C-contiguous (see :func:`numpy.ascontiguousarray`).

            The length of the buffer is not constrained to a specific
            range, however high performance applications will want to
            match this parameter to the *blocksize* parameter used when
            opening the stream.

        Returns
        -------
        underflowed : bool
            ``True`` if additional output data was inserted after the
            previous call and before this call.

        r   Nr`   rn   z$data must be one- or two-dimensionalznumber of channels must matchzdtype mismatch: {!r} vs {!r}zdata must be C-contiguous)r   asarrayr   r   rm   ndimreshaper<   shaper7   rT  r   rb   flagsc_contiguousrL  r[  )r   r(   npr   r7   r6   s         r   r[  zOutputStream.write  s   @ 	zz$$+&&5T^,,89q==<<A&&DDY]]CDDD:a=H$$<===::AA
( ( ) ) )z& 	97888$$T4000r   rJ  )r   r6  r7  r8  r  r[  rO   r   r   r%   r%     sM        ==26AEGKBF<@	7 7 7 7B/1 /1 /1 /1 /1r   r%   c                   $    e Zd ZdZ	 	 	 	 	 ddZdS )r=   z-Stream for input and output.  See __init__().Nc                 b    t          j        | fdddt          t                                 dS )a2  PortAudio stream for simultaneous input and output (using NumPy).

        To open an input-only or output-only stream use `InputStream` or
        `OutputStream`, respectively.  If you want to handle audio data
        as plain buffer objects instead of NumPy arrays, use
        `RawStream`, `RawInputStream` or `RawOutputStream`.

        A single stream can provide multiple channels of real-time
        streaming audio input and output to a client application.  A
        stream provides access to audio hardware represented by one or
        more devices.  Depending on the underlying host API, it may be
        possible to open multiple streams using the same device, however
        this behavior is implementation defined.  Portable applications
        should assume that a device may be simultaneously used by at
        most one stream.

        The arguments *device*, *channels*, *dtype* and *latency* can be
        either single values (which will be used for both input and
        output parameters) or pairs of values (where the first one is
        the value for the input and the second one for the output).

        All arguments are optional, the values for unspecified
        parameters are taken from the `default` object.
        If one of the values of a parameter pair is ``None``, the
        corresponding value from `default` will be used instead.

        The created stream is inactive (see `active`, `stopped`).
        It can be started with `start()`.

        Every stream object is also a
        :ref:`context manager <python:context-managers>`, i.e. it can be
        used in a :ref:`with statement <python:with>` to automatically
        call `start()` in the beginning of the statement and `stop()`
        and `close()` on exit.

        Parameters
        ----------
        samplerate : float, optional
            The desired sampling frequency (for both input and output).
            The default value can be changed with `default.samplerate`.
        blocksize : int, optional
            The number of frames passed to the stream callback function,
            or the preferred block granularity for a blocking read/write
            stream.
            The special value ``blocksize=0`` (which is the default) may
            be used to request that the stream callback will receive an
            optimal (and possibly varying) number of frames based on
            host requirements and the requested latency settings.
            The default value can be changed with `default.blocksize`.

            .. note:: With some host APIs, the use of non-zero
               *blocksize* for a callback stream may introduce an
               additional layer of buffering which could introduce
               additional latency.  PortAudio guarantees that the
               additional latency will be kept to the theoretical
               minimum however, it is strongly recommended that a
               non-zero *blocksize* value only be used when your
               algorithm requires a fixed number of frames per stream
               callback.
        device : int or str or pair thereof, optional
            Device index(es) or query string(s) specifying the device(s)
            to be used.  The default value(s) can be changed with
            `default.device`.
            If a string is given, the device is selected which contains
            all space-separated parts in the right order.  Each device
            string contains the name of the corresponding host API in
            the end.  The string comparison is case-insensitive.
        channels : int or pair of int, optional
            The number of channels of sound to be delivered to the
            stream callback or accessed by `read()` or `write()`.  It
            can range from 1 to the value of ``'max_input_channels'`` or
            ``'max_output_channels'`` in the dict returned by
            `query_devices()`.  By default, the maximum possible number
            of channels for the selected device is used (which may not
            be what you want; see `query_devices()`).  The default
            value(s) can be changed with `default.channels`.
        dtype : str or numpy.dtype or pair thereof, optional
            The sample format of the `numpy.ndarray` provided to the
            stream callback, `read()` or `write()`.
            It may be any of *float32*, *int32*, *int16*, *int8*,
            *uint8*. See `numpy.dtype`.
            The *float64* data type is not supported, this is only
            supported for convenience in `play()`/`rec()`/`playrec()`.
            The packed 24 bit format ``'int24'`` is only supported in
            the "raw" stream classes, see `RawStream`.  The default
            value(s) can be changed with `default.dtype`.
            If NumPy is available, the corresponding `numpy.dtype`
            objects can be used as well.  The floating point
            representations ``'float32'`` and ``'float64'`` use ``+1.0``
            and ``-1.0`` as the maximum and minimum values,
            respectively.  ``'uint8'`` is an unsigned 8 bit format where
            ``128`` is considered "ground".
        latency : float or {'low', 'high'} or pair thereof, optional
            The desired latency in seconds.  The special values
            ``'low'`` and ``'high'`` (latter being the default) select
            the device's default low and high latency, respectively (see
            `query_devices()`).  ``'high'`` is typically more robust
            (i.e. buffer under-/overflows are less likely),
            but the latency may be too large for interactive applications.

            .. note:: Specifying the desired latency as ``'high'`` does
                not *guarantee* a stable audio stream. For reference, by
                default Audacity_ specifies a desired latency of ``0.1``
                seconds and typically achieves robust performance.

            .. _Audacity: https://www.audacityteam.org/

            The default value(s) can be changed with `default.latency`.
            Actual latency values for an open stream can be retrieved
            using the `latency` attribute.
        extra_settings : settings object or pair thereof, optional
            This can be used for host-API-specific input/output
            settings.  See `default.extra_settings`.
        callback : callable, optional
            User-supplied function to consume, process or generate audio
            data in response to requests from an `active` stream.
            When a stream is running, PortAudio calls the stream
            callback periodically.  The callback function is responsible
            for processing and filling input and output buffers,
            respectively.

            If no *callback* is given, the stream will be opened in
            "blocking read/write" mode.  In blocking mode, the client
            can receive sample data using `read()` and write sample
            data using `write()`, the number of frames that may be
            read or written without blocking is returned by
            `read_available` and `write_available`, respectively.

            The callback must have this signature::

                callback(indata: ndarray, outdata: ndarray, frames: int,
                         time: CData, status: CallbackFlags) -> None

            The first and second argument are the input and output
            buffer, respectively, as two-dimensional `numpy.ndarray`
            with one column per channel (i.e.  with a shape of
            ``(frames, channels)``) and with a data type specified by
            `dtype`.
            The output buffer contains uninitialized data and the
            *callback* is supposed to fill it with proper audio data.
            If no data is available, the buffer should be filled with
            zeros (e.g. by using ``outdata.fill(0)``).

            .. note:: In Python, assigning to an identifier merely
               re-binds the identifier to another object, so this *will
               not work* as expected::

                   outdata = my_data  # Don't do this!

               To actually assign data to the buffer itself, you can use
               indexing, e.g.::

                   outdata[:] = my_data

               ... which fills the whole buffer, or::

                   outdata[:, 1] = my_channel_data

               ... which only fills one channel.

            The third argument holds the number of frames to be
            processed by the stream callback.  This is the same as the
            length of the input and output buffers.

            The forth argument provides a CFFI structure with
            timestamps indicating the ADC capture time of the first
            sample in the input buffer (``time.inputBufferAdcTime``),
            the DAC output time of the first sample in the output buffer
            (``time.outputBufferDacTime``) and the time the callback was
            invoked (``time.currentTime``).
            These time values are expressed in seconds and are
            synchronised with the time base used by `time` for the
            associated stream.

            The fifth argument is a `CallbackFlags` instance indicating
            whether input and/or output buffers have been inserted or
            will be dropped to overcome underflow or overflow
            conditions.

            If an exception is raised in the *callback*, it will not be
            called again.  If `CallbackAbort` is raised, the stream will
            finish as soon as possible.  If `CallbackStop` is raised,
            the stream will continue until all buffers generated by the
            callback have been played.  This may be useful in
            applications such as soundfile players where a specific
            duration of output is required.  If another exception is
            raised, its traceback is printed to `sys.stderr`.
            Exceptions are *not* propagated to the main thread, i.e. the
            main Python program keeps running as if nothing had
            happened.

            .. note:: The *callback* must always fill the entire output
               buffer, no matter if or which exceptions are raised.

            If no exception is raised in the *callback*, it
            automatically continues to be called until `stop()`,
            `abort()` or `close()` are used to stop the stream.

            The PortAudio stream callback runs at very high or real-time
            priority.  It is required to consistently meet its time
            deadlines.  Do not allocate memory, access the file system,
            call library functions or call other functions from the
            stream callback that may block or take an unpredictable
            amount of time to complete.  With the exception of
            `cpu_load` it is not permissible to call PortAudio API
            functions from within the stream callback.

            In order for a stream to maintain glitch-free operation the
            callback must consume and return audio data faster than it
            is recorded and/or played.  PortAudio anticipates that each
            callback invocation may execute for a duration approaching
            the duration of *frames* audio frames at the stream's
            sampling frequency.  It is reasonable to expect to be able
            to utilise 70% or more of the available CPU time in the
            PortAudio callback.  However, due to buffer size adaption
            and other factors, not all host APIs are able to guarantee
            audio stability under heavy CPU load with arbitrary fixed
            callback buffer sizes.  When high callback CPU utilisation
            is required the most robust behavior can be achieved by
            using ``blocksize=0``.
        finished_callback : callable, optional
            User-supplied function which will be called when the stream
            becomes inactive (i.e. once a call to `stop()` will not
            block).

            A stream will become inactive after the stream callback
            raises an exception or when `stop()` or `abort()` is called.
            For a stream providing audio output, if the stream callback
            raises `CallbackStop`, or `stop()` is called, the stream
            finished callback will not be called until all generated
            sample data has been played.  The callback must have this
            signature::

                finished_callback() -> None

        clip_off : bool, optional
            See `default.clip_off`.
        dither_off : bool, optional
            See `default.dither_off`.
        never_drop_input : bool, optional
            See `default.never_drop_input`.
        prime_output_buffers_using_stream_callback : bool, optional
            See `default.prime_output_buffers_using_stream_callback`.

        r   r   r=  Nr>  rA  s                 r   r  zStream.__init__  sH    t 	T 	7 	7 	7+FHH55	7 	7 	7 	7 	7r   rJ  r_  rO   r   r   r=   r=     sC        7726AEGKBF<@	{7 {7 {7 {7 {7 {7r   r=   c                       e Zd ZdZdZd ZdS )ro   aH  A list with information about all available audio devices.

    This class is not meant to be instantiated by the user.
    Instead, it is returned by `query_devices()`.
    It contains a dictionary for each available device, holding the keys
    described in `query_devices()`.

    This class has a special string representation that is shown as
    return value of `query_devices()` if used in an interactive
    Python session.  It will also be shown when using the :func:`print`
    function.  Furthermore, it can be obtained with :func:`repr` and
    :class:`str() <str>`.

    rO   c                    t          t          j        d         d          t          t          j        d         d          t          t	          t
                                          dz
                      d t                      D             d                    fdt          |           D                       }|S )NrV   rW   rn   c                     g | ]
}|d          S )rb   rO   )r[   rd   s     r   r   z'DeviceList.__repr__.<locals>.<listcomp>*  s    IIIWIIIr   
c              3      K   | ]U\  }}d                      d|k    d|k    z  z            ||d         |d                  |d         |d                   V  VdS )	z6{mark} {idx:{dig}} {name}, {ha} ({ins} in, {outs} out)) ><*r`   rb   rd   re   rf   )markidxdigrb   hainsoutsNr   )r[   rz  r   digitshostapi_namesidevodevs      r   r]   z&DeviceList.__repr__.<locals>.<genexpr>+  s       	. 	. T EKK)3$;!sd{:K*KL&\ i1-./0 L 2 2	. 	. 	. 	. 	. 	.r   )
rt   r   r   r   strrr   rs   r   join	enumerate)r   textr  r  r  r  s     @@@@r   __repr__zDeviceList.__repr__&  s    gnW5w??gnX6AAS//11A56677II8H8HIIIyy 	. 	. 	. 	. 	. 	. 	. 't__	. 	. 	. 	. 	. r   N)r   r6  r7  r8  	__slots__r  rO   r   r   ro   ro     s4          I    r   ro   c                   0   e Zd ZdZdZddZd Zd Zd Zd Z	e
d	             Zej        d
             Ze
d             Zej        d             Ze
d             Zej        d             Ze
d             Zej        d             Ze
d             Zd Zd ZdS )CallbackFlagsaM  Flag bits for the *status* argument to a stream *callback*.

    If you experience under-/overflows, you can try to increase the
    ``latency`` and/or ``blocksize`` settings.
    You should also avoid anything that could block the callback
    function for a long time, e.g. extensive computations, waiting for
    another thread, reading/writing files, network connections, etc.

    See Also
    --------
    Stream

    Examples
    --------
    This can be used to collect the errors of multiple *status* objects:

    >>> import sounddevice as sd
    >>> errors = sd.CallbackFlags()
    >>> errors |= status1
    >>> errors |= status2
    >>> errors |= status3
    >>> # and so on ...
    >>> errors.input_overflow
    True

    The values may also be set and cleared by the user:

    >>> import sounddevice as sd
    >>> cf = sd.CallbackFlags()
    >>> cf
    <sounddevice.CallbackFlags: no flags set>
    >>> cf.input_underflow = True
    >>> cf
    <sounddevice.CallbackFlags: input underflow>
    >>> cf.input_underflow = False
    >>> cf
    <sounddevice.CallbackFlags: no flags set>

    _flagsr   c                     || _         d S r   r  r   rk  s     r   r  zCallbackFlags.__init__c  s    r   c                 4    t          |           }|sd}d| dS )Nzno flags setz<sounddevice.CallbackFlags: rv  )r  r  s     r   r  zCallbackFlags.__repr__f  s+    D		 	#"E6e6666r   c                 `     d                      fdt                     D                       S )N, c              3      K   | ]?}|                     d           t          |          '|                    d d          V  @dS )r   ru  N)
startswithgetattrreplace)r[   rb   r   s     r   r]   z(CallbackFlags.__str__.<locals>.<genexpr>m  sq       N ND $ 4 4N9@t9L9LNc3// N N N N N Nr   )r  dirr  s   `r   __str__zCallbackFlags.__str__l  sN    yy N N N NCII N N N N N 	Nr   c                 *    t          | j                  S r   boolr  r  s    r   __bool__zCallbackFlags.__bool__p  s    DK   r   c                 h    t          |t                    st          S | xj        |j        z  c_        | S r   )r   r  NotImplementedr  )r   others     r   __ior__zCallbackFlags.__ior__s  s1    %// 	"!!u|#r   c                 @    |                      t          j                  S )a  Input underflow.

        In a stream opened with ``blocksize=0``, indicates that input
        data is all silence (zeros) because no real data is available.
        In a stream opened with a non-zero *blocksize*, it indicates
        that one or more zero samples have been inserted into the input
        buffer to compensate for an input underflow.

        This can only happen in full-duplex streams (including
        `playrec()`).

        )_hasflagrr   paInputUnderflowr  s    r   input_underflowzCallbackFlags.input_underflowy  s     }}T2333r   c                 F    |                      t          j        |           d S r   )_updateflagrr   r  r   values     r   r  zCallbackFlags.input_underflow  !    .66666r   c                 @    |                      t          j                  S )a  Input overflow.

        In a stream opened with ``blocksize=0``, indicates that data
        prior to the first sample of the input buffer was discarded due
        to an overflow, possibly because the stream callback is using
        too much CPU time.  In a stream opened with a non-zero
        *blocksize*, it indicates that data prior to one or more samples
        in the input buffer was discarded.

        This can happen in full-duplex and input-only streams (including
        `playrec()` and `rec()`).

        )r  rr   paInputOverflowr  s    r   input_overflowzCallbackFlags.input_overflow  s     }}T1222r   c                 F    |                      t          j        |           d S r   )r  rr   r  r  s     r   r  zCallbackFlags.input_overflow  s!    -u55555r   c                 @    |                      t          j                  S )a  Output underflow.

        Indicates that output data (or a gap) was inserted, possibly
        because the stream callback is using too much CPU time.

        This can happen in full-duplex and output-only streams
        (including `playrec()` and `play()`).

        )r  rr   paOutputUnderflowr  s    r   output_underflowzCallbackFlags.output_underflow  s     }}T3444r   c                 F    |                      t          j        |           d S r   )r  rr   r  r  s     r   r  zCallbackFlags.output_underflow  s!    /77777r   c                 @    |                      t          j                  S )a,  Output overflow.

        Indicates that output data will be discarded because no room is
        available.

        This can only happen in full-duplex streams (including
        `playrec()`), but only when ``never_drop_input=True`` was
        specified.  See `default.never_drop_input`.

        )r  rr   paOutputOverflowr  s    r   output_overflowzCallbackFlags.output_overflow  s     }}T2333r   c                 F    |                      t          j        |           d S r   )r  rr   r  r  s     r   r  zCallbackFlags.output_overflow  r  r   c                 @    |                      t          j                  S )ac  Priming output.

        Some of all of the output data will be used to prime the stream,
        input data may be zero.

        This will only take place with some of the host APIs, and only
        if ``prime_output_buffers_using_stream_callback=True`` was
        specified.
        See `default.prime_output_buffers_using_stream_callback`.

        )r  rr   paPrimingOutputr  s    r   priming_outputzCallbackFlags.priming_output  s     }}T1222r   c                 0    t          | j        |z            S )zCheck a given flag.r  )r   flags     r   r  zCallbackFlags._hasflag  s    DK$&'''r   c                 P    |r| xj         |z  c_         dS | xj         | z  c_         dS )zSet/clear a given flag.Nr  )r   r  r  s      r   r  zCallbackFlags._updateflag  s4     	!KK4KKKKKKD5 KKKKr   N)r   )r   r6  r7  r8  r  r  r  r  r  r  r9  r  setterr  r  r  r  r  r  rO   r   r   r  r  8  s       & &P I   7 7 7N N N! ! !   4 4 X4 7 7 7 3 3 X3  6 6 6 
5 
5 X
5 8 8 8 4 4 X4 7 7 7 3 3 X3( ( (! ! ! ! !r   r  c                   4    e Zd ZdZdddZd Zd Zd Zd Zd	S )
_InputOutputPairz8Parameter pairs for device, channels, dtype and latency.r   rn   rV   rW   c                 4    d d g| _         || _        || _        d S r   )_pair_parent_default_attr)r   parentdefault_attrs      r   r  z_InputOutputPair.__init__  s"    D\
)r   c                     | j                             ||          }| j        |         }| t          | j        | j                  |         }|S r   )_indexmappingr#   r  r  r  r  r   rc   r  s      r   __getitem__z_InputOutputPair.__getitem__  sI    "&&ue44
5!=DL$*<==eDEr   c                 P    | j                             ||          }|| j        |<   d S r   )r  r#   r  r  s      r   __setitem__z_InputOutputPair.__setitem__  s,    "&&ue44!
5r   c                 ,    d                     |           S )Nz[{0[0]!r}, {0[1]!r}]r  r  s    r   r  z_InputOutputPair.__repr__  s    %,,T222r   N)	r   r6  r7  r8  r  r  r  r  r  rO   r   r   r  r    sc        BB1--M* * *
  " " "3 3 3 3 3r   r  c                       e Zd ZdZdZdZ	 dxZZ	 dxZZ		 dxZ
Z	 dxZZ	 dZ	 ej        Z	 dZ	 dZ	 dZ	 dZ	 d Zd	 Zed
             Zed             Zd ZdS )r   a  Get/set defaults for the *sounddevice* module.

    The attributes `device`, `channels`, `dtype`, `latency` and
    `extra_settings` accept single values which specify the given
    property for both input and output.  However, if the property
    differs between input and output, pairs of values can be used, where
    the first value specifies the input and the second value specifies
    the output.  All other attributes are always single values.

    Examples
    --------
    >>> import sounddevice as sd
    >>> sd.default.samplerate = 48000
    >>> sd.default.dtype
    ['float32', 'float32']

    Different values for input and output:

    >>> sd.default.channels = 1, 2

    A single value sets both input and output at the same time:

    >>> sd.default.device = 5
    >>> sd.default.device
    [5, 5]

    An attribute can be set to the "factory default" by assigning
    ``None``:

    >>> sd.default.samplerate = None
    >>> sd.default.device = None, 4

    Use `reset()` to reset all attributes:

    >>> sd.default.reset()

    )r   r6   r7   r   r   NN)r	   r	   )highr  NFc                 `    | j         D ]%}t          | d|z             t          |           |<   &d S )N	_default_)_pairsr  vars)r   attrs     r   r  zdefault.__init__  sC    K 	J 	JD/kD6HIIDJJt	J 	Jr   c                    || j         v r)t          |          t          | |          j        dd<   dS |t	          |           v r$|dk    rt
                              | ||           dS t          dt          |          z             )z'Only allow setting existing attributes.Nresetz"'default' object has no attribute )	r  r   r  r  r  object__setattr__rS  repr)r   rb   r  s      r   r  zdefault.__setattr__  s    4;+1%==GD$%aaa(((SYY47??tT511111 4tDzzAC C Cr   c                 f    t                                           t                                           fS r   )rr   Pa_GetDefaultInputDevicePa_GetDefaultOutputDevicer  s    r   _default_devicezdefault._default_device  s*    --//..002 	2r   c                 N    t          t                                                    S )z*Index of the default host API (read-only).)rq   rr   Pa_GetDefaultHostApir  s    r   rd   zdefault.hostapi  s     d//11222r   c                 p    t          |                                            |                                  dS )z0Reset all attributes to their "factory default".N)r  clearr  r  s    r   r  zdefault.reset  s+    T

r   )r   r6  r7  r8  r  r   r6   _default_channelsr7   _default_dtyper   _default_latencyr   _default_extra_settingsr)   rr   paFramesPerBufferUnspecifiedr   r   r   r   r    r  r  r9  r  rd   r  rO   r   r   r   r     s(       $ $L HF F
 $.-H  21EN "0/G1/99N, J 1I3H
 J
  27.	J J J
C C C 2 2 X2 3 3 X3    r   r   	I_AM_FAKEc                       e Zd ZdZd ZdS )rv   a  This exception will be raised on PortAudio errors.

    Attributes
    ----------
    args
        A variable length tuple containing the following elements when
        available:

        1) A string describing the error
        2) The PortAudio ``PaErrorCode`` value
        3) A 3-tuple containing the host API index, host error code, and the
           host error message (which may be an empty string)

    c                 t   | j         r| j         d         nd}t          | j                   dk    r| d| j         d          d}t          | j                   dk    r^| j         d         \  }}}|t          j        k    rd}n"|dk     rd| d	}nt	          |          d
         }d                    ||||          }|S )Nr    rn   z [PaErrorCode ]r`   z<host API not found>z<error getting host API: rv  rb   z{}: '{}' [{} error {}])r'  r   rr   paHostApiNotFoundr   r   )r   errormsghost_apihosterror_codehosterror_texthostnames         r   r  zPortAudioError.__str__  s    #'9449Q<<"ty>>A"AA$)A,AAAHty>>A7;y|4Hnn41111ABxBBB)(33F;/66.(ND DH r   N)r   r6  r7  r8  r  rO   r   r   rv   rv     s-             r   rv   c                       e Zd ZdZdS )CallbackStopa  Exception to be raised by the user to stop callback processing.

    If this is raised in the stream callback, the callback will not be
    invoked anymore (but all pending audio buffers will be played).

    See Also
    --------
    CallbackAbort, :meth:`Stream.stop`, Stream

    Nr   r6  r7  r8  rO   r   r   r  r            	 	 	 	r   r  c                       e Zd ZdZdS )CallbackAborta  Exception to be raised by the user to abort callback processing.

    If this is raised in the stream callback, all pending buffers are
    discarded and the callback will not be invoked anymore.

    See Also
    --------
    CallbackStop, :meth:`Stream.abort`, Stream

    Nr  rO   r   r   r  r    r  r   r  c                       e Zd Zd ZdS )AsioSettingsc           
      0   t          |t                    rt          d          t          j        d|          | _        t          j        dt          t          j        d          t          j	        dt          j
        | j                            | _        dS )a8  ASIO-specific input/output settings.

        Objects of this class can be used as *extra_settings* argument
        to `Stream()` (and variants) or as `default.extra_settings`.

        Parameters
        ----------
        channel_selectors : list of int
            Support for opening only specific channels of an ASIO
            device.  *channel_selectors* is a list of integers
            specifying the (zero-based) channel numbers to use.
            The length of *channel_selectors* must match the
            corresponding *channels* parameter of `Stream()` (or
            variants), otherwise a crash may result.
            The values in the *channel_selectors* array must specify
            channels within the range of supported channels.

        Examples
        --------
        Setting output channels when calling `play()`:

        >>> import sounddevice as sd
        >>> asio_out = sd.AsioSettings(channel_selectors=[12, 13])
        >>> sd.play(..., extra_settings=asio_out)

        Setting default output channels:

        >>> sd.default.extra_settings = asio_out
        >>> sd.play(...)

        Setting input channels as well:

        >>> asio_in = sd.AsioSettings(channel_selectors=[8])
        >>> sd.default.extra_settings = asio_in, asio_out
        >>> sd.playrec(..., channels=1, ...)

        z)channel_selectors must be a list or tuplezint[]zPaAsioStreamInfo*PaAsioStreamInforn   )sizehostApiTypeversionrk  channelSelectorsN)r   intrT  rx   r   
_selectorsdictsizeofrr   r   paAsioUseChannelSelectors_streaminfo)r   channel_selectorss     r   r  zAsioSettings.__init__  s    L '-- 	IGHHH(7,=>>8$7/000!_:. :. :. / /r   Nr   r6  r7  r  rO   r   r   r  r    s#        // // // // //r   r  c                       e Zd Z	 	 ddZdS )CoreAudioSettingsNFmaxc           	      v   t           j        t           j        t           j        t           j        t           j        d}t          |t                    rt          d          	 ||	                                         | _
        nF# t          t          f$ r2}t          dt          t          |                    z             |d}~ww xY w|r| xj
        t           j        z  c_
        |r| xj
        t           j        z  c_
        t%          j        d          | _        t                               | j        | j
                   |{t%          j        d|          | _        t/          | j                  dk    rt          d          t                               | j        | j        t/          | j                             dS dS )	a	  Mac Core Audio-specific input/output settings.

        Objects of this class can be used as *extra_settings* argument
        to `Stream()` (and variants) or as `default.extra_settings`.

        Parameters
        ----------
        channel_map : sequence of int, optional
            Support for opening only specific channels of a Core Audio
            device.  Note that *channel_map* is treated differently
            between input and output channels.

            For input devices, *channel_map* is a list of integers
            specifying the (zero-based) channel numbers to use.

            For output devices, *channel_map* must have the same length
            as the number of output channels of the device.  Specify
            unused channels with -1, and a 0-based index for any desired
            channels.

            See the example below.  For additional information, see the
            `PortAudio documentation`__.

            __ https://app.assembla.com/spaces/portaudio/git/source/
               master/src/hostapi/coreaudio/notes.txt
        change_device_parameters : bool, optional
            If ``True``, allows PortAudio to change things like the
            device's frame size, which allows for much lower latency,
            but might disrupt the device if other programs are using it,
            even when you are just querying the device.  ``False`` is
            the default.
        fail_if_conversion_required : bool, optional
            In combination with the above flag, ``True`` causes the
            stream opening to fail, unless the exact sample rates are
            supported by the device.
        conversion_quality : {'min', 'low', 'medium', 'high', 'max'}, optional
            This sets Core Audio's sample rate conversion quality.
            ``'max'`` is the default.

        Example
        -------
        This example assumes a device having 6 input and 6 output
        channels.  Input is from the second and fourth channels, and
        output is to the device's third and fifth channels:

        >>> import sounddevice as sd
        >>> ca_in = sd.CoreAudioSettings(channel_map=[1, 3])
        >>> ca_out = sd.CoreAudioSettings(channel_map=[-1, -1, 0, -1, 1, -1])
        >>> sd.playrec(..., channels=2, extra_settings=(ca_in, ca_out))

        )minlowmediumr  r
  z#channel_map must be a list or tuplez"conversion_quality must be one of NzPaMacCoreStreamInfo*zSInt32[]r   zchannel_map must not be empty)rr   paMacCoreConversionQualityMinpaMacCoreConversionQualityLow paMacCoreConversionQualityMediumpaMacCoreConversionQualityHighpaMacCoreConversionQualityMaxr   r   rT  lowerr  KeyErrorrS  r<   r  listpaMacCoreChangeDeviceParameters!paMacCoreFailIfConversionRequiredrx   r   r  PaMacCore_SetupStreamInfo_channel_mapr   PaMacCore_SetupChannelMap)r   channel_mapchange_device_parametersfail_if_conversion_requiredconversion_qualityconversion_dictes          r   r  zCoreAudioSettings.__init__	  s   l 88;98
 
 k3'' 	CABBB	A)*<*B*B*D*DEDKK.) 	A 	A 	AA!$"7"7889 : :?@A	A $ 	@KK4??KK& 	BKK4AAKK  8$:;;&&t'7EEE" $[ A AD4$%%** ?@@@**4+;+/+<+.t/@+A+AC C C C C #"s    B   C-B>>C)NFFr
  r  rO   r   r   r	  r	  	  s:        BGGLWC WC WC WC WC WCr   r	  c                       e Zd ZddZdS )WasapiSettingsFc           	          d}|r|t           j        z  }n|r|t           j        z  }t          j        dt          t          j        d          t           j        d|                    | _        dS )a  WASAPI-specific input/output settings.

        Objects of this class can be used as *extra_settings* argument
        to `Stream()` (and variants) or as `default.extra_settings`.
        They can also be used in `check_input_settings()` and
        `check_output_settings()`.

        Parameters
        ----------
        exclusive : bool
            Exclusive mode allows to deliver audio data directly to
            hardware bypassing software mixing.

        auto_convert : bool
            Allow WASAPI backend to insert system-level channel matrix
            mixer and sample rate converter to support playback formats
            that do not match the current configured system settings.
            This is in particular required for streams not matching the
            system mixer sample rate.  This only applies in *shared
            mode* and has no effect when *exclusive* is set to ``True``.

        Examples
        --------
        Setting exclusive mode when calling `play()`:

        >>> import sounddevice as sd
        >>> wasapi_exclusive = sd.WasapiSettings(exclusive=True)
        >>> sd.play(..., extra_settings=wasapi_exclusive)

        Setting exclusive mode as default:

        >>> sd.default.extra_settings = wasapi_exclusive
        >>> sd.play(...)

        r   zPaWasapiStreamInfo*PaWasapiStreamInforn   )r  r  r  rk  N)	rr   paWinWasapiExclusivepaWinWasapiAutoConvertrx   r   r  r  paWASAPIr  )r   	exclusiveauto_convertrk  s       r   r  zWasapiSettings.__init__r	  s}    H  	1T..EE 	1T00E8$94122	<
 <
 <
  r   N)FFr  rO   r   r   r#  r#  p	  s(        . . . . . .r   r#  c                   ~    e Zd ZdZdZdZdZdZdxZZ	dxZ
ZdxZZdZddZd Zd Zd Zd	 Zd
 Zd Zd Zd ZddZdS )r!   z<Helper class for re-use in play()/rec()/playrec() callbacks.Nr   Fc                     dd l }	 dd l}|sJ n"# t          $ r}t          d          |d }~ww xY w|| _        |                                | _        t                      | _        d S )Nr   z2NumPy must be installed for play()/rec()/playrec())	threadingr   ImportErrorr   Eventeventr  r   )r   r   r-  r   r!  s        r   r  z_CallbackContext.__init__	  s    	MLLLLLLL 	M 	M 	MDF FKLM	M 	__&&
#oos    
.).c                    ddl }|                    |          }|j        dk     r|                    dd          }n|j        dk    rt	          d          |j        \  }}t          |j                  }|du}t          ||          \  }}|j        d         dk    rn-|j        d         t          |          k    rt	          d          |r3|
                    |dg          rt          |d          d	         dk    rd}|                    |                    |          |          }	t          |          t          |	          z   |k    rt	          d
          || _        || _        || _        || _        |	| _        |S )zCheck data and output mapping.r   Nr`   rf  rn   z<audio data to be played back must be one- or two-dimensionalz3number of output channels != size of output mappingrW   rf   z,each channel may only appear once in mapping)r   rg  rh  ri  r<   rj  _check_dtyper7   _check_mappingr   array_equalrY   	setdiff1daranger(   r&   r'   r?   silent_channels)
r   r(   r*   r   rm  r   r6   r7   mapping_is_explicitr7  s
             r   r"   z_CallbackContext.check_data	  s   zz$9q==<<A&&DDY]]NP P P:TZ((%T1*7H==:a=AZ]c'll**EG G G   	BNN7QC$@$@ 	fh//0EF!KKH,,ryy':':GDDw<<#o...(::KLLL	'!%.r   c                     ddl }||t          d          |t          j        d         }|3|t          d          t	          |                    |                    }|t          j        d         }|                    ||f|d          }n|j        \  }}|j        }t          |          }t          ||          \  }}|j        d         t	          |          k    rt          d	          || _        || _        || _        || _        ||fS )
z5Check out, frames, channels, dtype and input mapping.r   Nzframes must be specifiedrV   z,Unable to determine number of input channelsC)orderrn   z1number of input channels != size of input mapping)r   rT  r   r6   r   
atleast_1dr7   emptyrj  r2  r3  r<   r8   r4   r5   r>   )r   r8   r   r6   r7   r*   rm  s          r   r2   z_CallbackContext.check_out	  s5   ;~ :;;;"+G4?#FH H H  #2==#9#9::H}g.((FH-uC(@@CC"yFHIEU##*7H==9Q<3w<<''CE E E & $F{r   c                     | xj         |z  c_         t          | j        | j        z
  t	          |                    | _        dS )zCheck status and blocksize.N)r   r  r   framer   r   )r   r   r(   s      r   r   z_CallbackContext.callback_enter	  s6    vT[4:5s4yyAAr   c                     t          | j                  D ]4\  }}|d | j        |f         | j        | j        | j        | j        z   |f<   5d S r   )r  r>   r   r8   r?  )r   r1   targetsources       r   r0   z_CallbackContext.read_indata
  se     ((:;; 	0 	0NFF ./ HTZ
T^ ;;VCDD	0 	0r   c                    | j         | j        | j        | j        z            |d | j        | j        f<   d|d | j        | j        f<   | j        rl| j        t          |          k     rTd| _        || j        d          }t          | j        t          |                    | _        | 	                    |           d S d|| j        d <   d S Nr   )
r(   r?  r   r?   r7  r   r   r  r   r   )r   r   s     r   r   z_CallbackContext.write_outdata
  s     Idjdn!<<= 	!4459:!5569 	)#g,,66DJdnoo.G c'll;;DNw''''''(GDNOO$$$r   c                 L    | j         st          | xj        | j         z  c_        d S r   )r   r  r?  r  s    r   r   z_CallbackContext.callback_exit
  s(    ~ 	 

dn$



r   c                     | j                                          d | _        d | _        d | j        _        d | j        _        d S r   )r0  setr(   r8   rI   r   r   r  s    r   r   z"_CallbackContext.finished_callback!
  s<    
	 $)-&&&r   c           	          t                        |d||||| j        d|| _        | j                                         | a|r|                                  d S d S )N)r)   r6   r7   r   r   rO   )rJ   r   rI   r$  rD   rE   )r   StreamClassr)   r6   r7   r   r+   r,   s           r   r$   z_CallbackContext.start_stream*
  s    !k ,Z+3(-+3484J	, ,
 %+, , 	 	IIKKKKK	 	r   Tc                     	 | j                                          | j                            |           n# | j                            |           w xY w| j        r| j        ndS )z[Wait for finished_callback.

        Can be interrupted with a KeyboardInterrupt.

        N)r0  rE   rI   rK   r   )r   rG   s     r   rE   z_CallbackContext.wait9
  sa    	-JOOKm,,,,DKm,,,,"k3t{{t3s	   6 AFr5  )r   r6  r7  r8  r   r(   r8   r?  r4   r&   r5   r'   r>   r?   r7  r  r"   r2   r   r0   r   r   r   r$   rE   rO   r   r   r!   r!   	  s        FFID
CE'++N_!%%K,%))MNO
& 
& 
& 
&" " "H  @B B B
	0 	0 	0) ) )% % %
. . .  
4 
4 
4 
4 
4 
4r   r!   c                 4    |                                  } | d= | S )z,Return a copy of d without the 'self' entry.r   copy)ds    r   r?  r?  F
  s    	A	&	Hr   c                    ddl }| |                    |          } nl|                    | d          } |                    |           } |                                 dk     rt          d          |                                 }| dz  } | |fS )zCheck mapping, obtain channels.r   NTrM  rn   zchannel numbers must not be < 1)r   r6  r   r<  r  r<   r
  )r*   r6   rm  s      r   r3  r3  M
  s    ))H%%((7(..--((;;==1>???;;==1Hr   c                     ddl }|                    |           j        } | t          v rn(| dk    rd} nt	          dt          |           z             | S )zCheck dtype.r   Nfloat64r	   zUnsupported data type: )r   r7   rb   _sampleformatsrT  r  )r7   rm  s     r   r2  r2  \
  s_    HHUOO E	)		1DKK?@@@Lr   c                 2   | dv sJ |t           j        |          }|t           j        |          }|t           j        |          }|t           j        |          }|t           j        |          }|t           j        }t          || d          }t          |          }||d| z   dz            }	 t          j
        d                             |          j        }n# t          $ r Y nw xY w	 t          |         }n(# t          $ r}	t          d| z   d	z             |	d}	~	ww xY wt!          t"                              |                    }
|d
v r|d|z   dz   | z   dz            }||d         }t'          j        d|||||r|j        nt&          j        f          }|||
|fS )z?Get parameters for one direction (input or output) of a stream.r  NTr^   rl   rm   r   zInvalid z sample format)r  r  default_r   r   rk   zPaStreamParameters*)r   r   r6   r7   r   r   r)   rt   rY   _sysmodulesrb   	ExceptionrS  r  r<   rq   rr   Pa_GetSampleSizerx   r   r  r   )r   r   r6   r7   r   r   r)   r   sampleformatr!  r   r   s               r   r   r   i
  s    &&&&&~%#D)}d#/$' /5'
FD>>>F  D34W%++E227   F%e, F F Fd*-==>>AEF--l;;<<J/!!zG+c1D8:EF./
/,&4C""$)2E F FJ uj*44s*   +*C 
C#"C#'C5 5
D?DDc                     |dd         t          |d                   fz   }	  | |  n3# t          $ r t          j        cY S t          $ r t          j        cY S w xY wt          j        S )z9Invoke callback function and check for custom exceptions.Nrf  )r  r  rr   
paCompleter  r   
paContinue)r   r'  s     r   r   r   
  s    9d2h//11D$      |?s   ) AAAc                 8    t          j        | ||z  |z            S )z5Create a buffer object from a pointer to some memory.)rx   r   )ptrr   r6   r   s       r   r   r   
  s    ;sFX-
:;;;r   c                 N    ddl }|                    | |          }d|f|_        |S )z(Create NumPy array from a buffer object.r   N)r7   rf  )r   
frombufferrj  )r   r6   r7   rm  r(   s        r   r   r   
  s3    ==u=--DXDJKr   c                     t          | t          t          f          r| | fS 	 | \  }}n1# t          $ r | x}}Y n!t          $ r}t	          d          |d}~ww xY w||fS )zSplit input/output value into two values.

    This can be useful for generic code that allows using the same value
    for input and output but also a pair of two separate values.

    z(Only single values and pairs are allowedN)r   r  bytesrT  r<   )r  invalueoutvaluer!  s       r   r   r   
  s     %#u&& e|L! # # #""((( L L LCDD!KLHs   ( A	AAAr  c                    | dk    r| S t          j        t                              |                                                     }|r| d| }| t          j        k    r~t                                          }t                              |j                  }t          j        |j	                                                  }||j
        |f}t          || |          t          ||           )z0Raise PortAudioError for below-zero error codes.r   z: )rx   ry   rr   Pa_GetErrorTextrz   paUnanticipatedHostErrorPa_GetLastHostErrorInfor|   r  	errorText	errorCoderv   )r,  msgr  r   r  r  hosterror_infos          r   rq   rq   
  s    
axx
{4//4455<<>>H
 (''X''
d+++
 ++--66t7GHHT^44;;==!4>>AXsN;;;
3
'
''r   c                    |dv sJ | t           j        } t          |           \  }}|dk    r|} n4|dk    r|} n+||k    r|} n"t          d                    |                     t          | t                    r| S g }t          t                                D ]R\  }}|r|d|z   dz            dk    r9t          |d	                   }|
                    ||d
         |d
         f           S|                                 }	|	                                }
g }g }|D ]\  }}}|dz   |z   }d}|
D ]D}|                                                    ||          }|dk     r ni|t          |          z  }E|
                    ||f           |	|                                |                                fv r|
                    |           |d}|s)|r%t          d|z   dz   t          |           z             dS t          |          dk    rgt          |          dk    r|d         S |rHt          d|z   dz   t          |           z   dz   d                    d |D                       z             dS |d         d         S )z2Return device ID given space-separated substrings.rU   NrV   rW   z+Input and output device are different: {!r}rl   rm   r   rd   rb   r  zinput/outputzNo z device matching rf  rn   z	Multiple z devices found for z:
rs  c              3   ,   K   | ]\  }}d | d| V  dS )[z] NrO   )r[   idrb   s      r   r]   z!_get_device_id.<locals>.<genexpr>  sR       '@ '@+32t (82'7'7'7'7 '@ '@ '@ '@ '@ '@r   )r   r   r   r<   r   r   r   r  rY   r   appendr  splitfindr   r  r  )id_or_query_stringr   r_   r  r  device_listrq  r   hostapi_infoquery_string
substringsmatchesexact_device_matchesdevice_stringhostapi_stringfull_stringpos	substrings                     r   rt   rt   
  s5   ,,,,,!$^*++JD$w!			!4<<!%J$f%788: : : $c** "!!Kmoo.. I ID 	ItFTMK781<<)$y/::LDL,v2FGHHH%++--L##%%JG-8 0 0)M>#d*^;# 	0 	0I##%%**9c::CQww3y>>!CCNNB,--- 3 3 5 5{7H7H7J7JKKK$++B///|  	22T:L5M5MMO O O 2
7||a#$$))'** 	[4/2GG!"45568=>!YY '@ '@7>'@ '@ '@ @ @@ A A A
 21:a=r   c                     d} 	 t          j        d          } t          j        t           j        t           j                  }t          j        |d           t          j        |           n# t          $ r Y nw xY w	 t          t          
                                d           t          dz  a| +t          j        | d           t          j        |            dS dS # | *t          j        | d           t          j        |            w w xY w)a  Initialize PortAudio.

    This temporarily forwards messages from stderr to ``/dev/null``
    (where supported).

    In most cases, this doesn't have to be called explicitly, because it
    is automatically called with the ``import sounddevice`` statement.

    Nr`   zError initializing PortAudiorn   )_osdupopendevnullO_WRONLYdup2rK   OSErrorrq   rr   Pa_Initialize_initialized)
old_stderrr  s     r   _initializer    s
    JWQZZ
(3;55!	'   "t!!##%CDDD!HZ###Ij!!!!! "!:!HZ###Ij!!!! "s   A&A+ +
A87A8<1C .D
c                  h    t          t                                          d           t          dz  adS )zYTerminate PortAudio.

    In most cases, this doesn't have to be called explicitly.

    zError terminating PortAudiorn   N)rq   rr   Pa_Terminater  rO   r   r   
_terminater  3  s/     4 =>>>ALLLr   c                      t           dk    sJ t          r<t          j                                         t          j                                         t           rt                       t           d S d S rD  )r  rD   rI   rJ   rK   r  rO   r   r   _exit_handlerr  >  sx    1  & 	""$$$##%%%
       r   __main__)NNFF)NNNNNNFr5  r  r   )NNNNN)r  rK  )Wr8  __version__atexit_atexitosr  platform	_platformsysrV  ctypes.utilr   _find_library_sounddevicer   rx   _libnamer  dlopenrr   systemarchitecture_sounddevice_datapathr  nextiter__path__	paFloat32paInt32paInt24paInt16paInt8paUInt8rS  r  rD   r-   r9   rB   rE   rJ   rP   rS   rY   r   r   r   r   r   r   r;  rL  r]  r3   r%   r=   r   ro   r  r  r   hasattrrX  rv   r  r  r  r	  r#  r!   r?  r3  r2  r   r   r   r   r   rq   rt   r  r  r  registerr   printrO   r   r   <module>r     s  * <                  5 5 5 5 5 5 $ $ $ $ $ $! 	5 	5
 !=**E   g34444;x  DD 
! 
! 
!yX%%'				y	(	(!$:I$:$<$<Q$??&Hx}}TT#,--..0DhP PH4;x  DDD
! ~\\\K\  P P P Pf <@).a a a aH 9=HM^ ^ ^ ^B2 2 2 2(3 3 3 3H H H(H H H(V V V Vr2 2 2 2j <@9=I I I I: =A:>I I I I  	P 	P 	Pv0 v0 v0 v0 v0 v0 v0 v0rQ- Q- Q- Q- Q-[ Q- Q- Q-h\ \ \ \ \k \ \ \~17 17 17 17 17 17 17 17hF  F  F  F  F . F  F  F RS1 S1 S1 S1 S1? S1 S1 S1l~7 ~7 ~7 ~7 ~7[, ~7 ~7 ~7B! ! ! ! ! ! ! !He! e! e! e! e! e! e! e!P3 3 3 3 3 3 3 32c c c c c c c cL wt[!! giiG    Y   D
 
 
 
 
9 
 
 

 
 
 
 
I 
 
 
1/ 1/ 1/ 1/ 1/ 1/ 1/ 1/hYC YC YC YC YC YC YC YCx0 0 0 0 0 0 0 0f`4 `4 `4 `4 `4 `4 `4 `4F    
 
 
&5 &5 &5R	 	 	< < <
    &( ( ( (.? ? ? ?D" " "8          z	E--// s   /A BC'&C'