
    hhڱ                       S r SrSSKrSSKrSSKrSSKr	SSK
Jr  SSKJr   S H  r\" \5      r\c  M    O
   \" S5      e\R$                  " \5      r\R:                  \R<                  \R>                  \R@                  \RB                  \RD                  S.r#Sq$Sq%SVS jr&  SWS jr'  SWS jr(SXS jr)SXS jr*S r+S r,SYS jr-SZS jr.  S[S jr/  S[S jr0S r1S r2 " S S5      r3 " S  S!\35      r4 " S" S#\45      r5 " S$ S%\35      r6 " S& S'\65      r7 " S( S)\5\75      r8 " S* S+\45      r9 " S, S-\65      r: " S. S/\9\:5      r; " S0 S1\<5      r= " S2 S35      r> " S4 S55      r? " S6 S75      r@\A" \S85      (       d  \@" 5       r@ " S9 S:\B5      rC " S; S<\B5      rD " S= S>\B5      rE " S? S@5      rF " SA SB5      rG " SC SD5      rH " SE SF5      rISG rJSH rKSI rLSJ rMSK rNSL rOSM rPSN rQS\SO jrRSP rSS]SQ jrTSR rUSS rVST rW\R                  " \W5        \U" 5         \YSU:X  a  \Z" \-" 5       5        gg! \ a    \R(                  " 5       S:X  a  S	rO\\R(                  " 5       S
:X  aF  S\R*                  ;   a  S\R,                  " 5       S   -   S-   rOS\R,                  " 5       S   -   S-   rOe SSKr\R0                  R3                  \" \" \R8                  5      5      S\5      r\R$                  " \5      r GNf = f)^a  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.5.3    N)find_library)ffi)	portaudiozbin\libportaudio-2.dllzlib/libportaudio.dylibzPortAudio library not foundDarwinzlibportaudio.dylibWindowsSD_ENABLE_ASIOlibportaudioz	-asio.dllz.dllzportaudio-binaries)float32int32int24int16int8uint8c                    ^ [        US9mTR                  XUR                  S5      5      Tl        U4S jnTR                  " [
        UTR                  TR                  Xc4SS0UD6  g)a8	  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                    > [        U 5      U:X  d   eTR                  X05        TR                  U 5        TR                  5         g N)lencallback_enterwrite_outdatacallback_exit)outdataframestimestatusctxs       E/home/james-whalen/.local/lib/python3.13/site-packages/sounddevice.pycallbackplay.<locals>.callback   s=    7|v%%%6+'"    *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/   e   si    H 
%Cvzz(/CDCJ \:s/B/B%%x@E r!   c                    ^	 [        5       m	T	R                  X@X#U5      u  nT	l        U	4S jnT	R                  " [        UT	R
                  T	R                  X40 UD6  U$ )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                    > [        U 5      U:X  d   eTR                  X05        TR                  U 5        TR                  5         g r   )r   r   read_indatar   )indatar   r   r   r   s       r   r   rec.<locals>.callback  s;    6{f$$$6*r!   )r#   	check_outr   r&   InputStreaminput_channelsinput_dtype)
r   r+   channelsdtypeoutr,   r-   r.   r   r   s
            @r   recr<      s_    l 
CmmC'JOC [*c.@.@__hD<BDJr!   c                   ^ [        5       mTR                  XUR                  S5      5      n	Uc  TR                  R                  nTR                  XIX#U5      u  pJX:w  a  [        S5      eU
Tl        U4S jnTR                  " [        UTR                  TR                  4TR                  TR                  4X4SS0UD6  U$ )av  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   zlen(data) != len(out)c                    > [        U 5      [        U5      s=:X  a  U:X  d   e   eTR                  X@5        TR                  U 5        TR                  U5        TR	                  5         g r   )r   r   r2   r   r   )r3   r   r   r   r   r   s        r   r   playrec.<locals>.callbackm  sX    6{c'l4f444446*'"r!   r"   F)r#   r$   r%   r*   r:   r5   
ValueErrorr   r&   Streamr7   r(   r8   r)   )r*   r+   r9   r:   r;   input_mappingoutput_mappingr-   r.   output_framesinput_framesr   r   s               @r   playrecrF     s    N 
CNN4H9MNM}c(&35C$011CJ VZ((#*=*=>oos'7'78 AF	
  Jr!   c                 D    [         (       a  [         R                  U 5      $ g)a<  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   rI   rI   }  s      ~""=11 r!   c                     [         (       a?  [         R                  R                  U 5        [         R                  R                  U 5        gg)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)rH   streamstopcloserJ   s    r   rN   rN     s8     ~ 	""=1##M2	 r!   c                  N    [         (       a  [         R                  $ [        S5      e)zGet 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)rH   r   RuntimeError r!   r   
get_statusrT     !     ~$$$FGGr!   c                  N    [         (       a  [         R                  $ [        S5      e)a$  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.

rQ   )rH   rM   rR   rS   r!   r   
get_streamrW     rU   r!   c                 $   US;  a  [        SU< 35      eU c9  Uc6  [        S [        [        [        R                  5       5      5       5       5      $ [        XSS9n [        R                  U 5      nU(       d  [        SU  35      eUR                  S:X  d   e[        R                  " UR                  5      n UR                  S	5      nUU UR                   UR,                  UR.                  UR0                  UR2                  UR4                  UR6                  UR8                  S.
nU(       a,  USU-   S-      S:  a  [        SR;                  XS   5      5      eU$ ! [         a    [        R                  nUR                   U" [        R"                  5      U" [        R$                  5      4;   a  UR                  S
5      n NUR                   U" [        R&                  5      :X  a&  SSKnUR                  UR+                  5       5      n GNCe f = f)a  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   8   #    U  H  n[        U5      v   M     g 7fr   )query_devices.0is     r   	<genexpr> query_devices.<locals>.<genexpr>7  s       L#Ja (**#J   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}rh   )r@   
DeviceListrange_check_libPa_GetDeviceCount_get_device_idPa_GetDeviceInfoPortAudioErrorstructVersion_ffistringrh   decodeUnicodeDecodeErrorPa_HostApiTypeIdToHostApiIndexhostApipaDirectSoundpaMMEpaASIOlocalegetpreferredencodingmaxInputChannelsmaxOutputChannelsdefaultLowInputLatencydefaultLowOutputLatencydefaultHighInputLatencydefaultHighOutputLatencydefaultSampleRateformat)r   kindinfo
name_bytesrh   api_idxr   device_dicts           r   r]   r]     s   X ,,>$233~$, L#(0F0F0H)I#JL L 	LF>F  (D5fX>??"""TYY'J
   ) <<"33#55%)%@%@&*&B&B&*&B&B'+'D'D"44K FTMK781<$++Df2EFH 	H3  	55<<GD$6$679LMM$$V,D\\WT[[11$$V%@%@%BCD	s   9E A%HAHHc           	         U c6  [        S [        [        [        R	                  5       5      5       5       5      $ [        R                  U 5      nU(       d  [        SU  35      eUR                  S:X  d   e[        R                  " UR                  5      R                  5       [        UR                  5       Vs/ s H  n[        R                  X5      PM     snUR                  UR                  S.$ s  snf )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

c              3   8   #    U  H  n[        U5      v   M     g 7fr   )query_hostapisr^   s     r   ra   !query_hostapis.<locals>.<genexpr>  s       HF $A&&Frc   zError querying host API rt   )rh   devicesdefault_input_devicedefault_output_device)tuplerv   rw   rx   Pa_GetHostApiCountPa_GetHostApiInfor|   r}   r~   r   rh   r   deviceCount"Pa_HostApiDeviceIndexToDeviceIndexdefaultInputDevicedefaultOutputDevice)ri   r   r`   s      r   r   r   a  s    J } H#F4+B+B+D$EFH H 	H!!%(D7w?@@"""DII&--/"4#3#3464 ;;EE46 $ 7 7!%!9!9 6s   :C4c           
          [        SXUSX4S9u  pRpd[        [        R                  U[        R
                  U5      5        g)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`.

rZ   Nr   r9   r:   latencyextra_settingsr+   _get_stream_parametersrw   rx   Pa_IsFormatSupportedr~   NULLr   r9   r:   r   r+   
parameters
samplesizes          r   check_input_settingsr     s=    . 1G%1>-Jz 4$$ZJGHr!   c           
      ~    [        SXUSX4S9u  pRpd[        [        R                  [        R
                  XT5      5        g)zzCheck if given output device settings are supported.

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

r[   Nr   r   r   s          r   check_output_settingsr     s;     1G%%1>-Jz 4$$TYY
GHr!   c                 .    [         R                  U 5        g)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)rx   Pa_Sleep)msecs    r   sleepr     s     	MM$r!   c                      [         R                  5       [        R                  " [         R	                  5       5      R                  5       4$ )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)')

)rx   Pa_GetVersionr~   r   Pa_GetVersionTextr   rS   r!   r   get_portaudio_versionr     s3     T-C-C-E!F!M!M!OOOr!   c                   6   \ rS rSrSr      SS jr\R                  r\	S 5       r
\	S 5       r\	S 5       r\	S 5       r\	S	 5       r\	S
 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       rS rS rS rSS jrSS jrSS jrSrg)_StreamBasei  z5Direct or indirect base class for all stream classes.Nc                 	  ^ ^	^
 US;   d   eUS;   d   eUS:X  a  SSK nU(       d   eUc  [        R                  nUc  [        R                  nUc  [        R                  nUc  [        R
                  nUc  [        R                  n[        R                  nU(       a  U[        R                  -  nU(       a  U[        R                  -  nU(       a  U[        R                  -  nU(       a  U[        R                  -  nUS:X  a  [        U5      u  nn[        U5      u  nn[        U5      u  nn[        U5      u  nn[        U5      u  nn[        SUUUUUU5      u  nnnn[        SUUUUUU5      u  n nn!n"UU4T l        UR                   U R                   4T l        UR$                  U R$                  4T l        UU!4T l        UU":w  a  [+        S	5      eUnOp[        XXVUX5      u  n#T l        T l        nU#R                   T l        U#R$                  T l        [,        R.                  n[,        R.                  n US:X  a  U#nOUS:X  a  U#n [,        R0                  " S
[        R2                  S9n$T	c  [,        R.                  n%OUS:X  a  US:X  a  U$U	U 4S j5       n%OUS:X  a  US:X  a  U$U	U 4S j5       n%O{US:X  a  US:X  a  U$U	U 4S j5       n%ObUS:X  a  US:X  a  U$U	U 4S j5       n%OIUS:X  a  US:X  a  U$U	U 4S j5       n%O0US:X  a  US:X  a  U$U	U 4S j5       n%O[,        R4                  " ST	5      n%U%T l        Uc  [,        R.                  n[,        R8                  " S5      T l        [=        [        R?                  T R:                  UU X#UU%U5      ST R@                  RB                   35        T R:                  S   T l        UT l"        [        RG                  T R:                  5      n&U&(       d  [I        S5      eU&RJ                  T l&        U (       d  U&RN                  T l(        O6U(       d  U&RR                  T l(        OU&RN                  U&RR                  4T l(        T
(       a}  [U        T
[,        RV                  5      (       a  T
T l,        O"U
4S jn'[,        R0                  " SU'5      T l,        [=        [        R[                  T R:                  T RX                  5      5        gg)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 `~Stream.read_available`/`~Stream.read()` and
`~Stream.write_available`/`~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.

)rZ   r[   duplex)arraybufferNr   r   Nr   rZ   r[   z5Input and output device must have the same sampleratePaStreamCallback)errorr   c                 `   > [        XTR                  TR                  5      n[        TXbX45      $ r   _bufferrs   _samplesize_wrap_callback	iptroptrr   r   r   _r*   r   selfs	          r   callback_ptr*_StreamBase.__init__.<locals>.callback_ptrM  *    tT^^T=M=MN%hdKKr!   c                    > [        [        XTR                  TR                  5      TR                  TR                  5      n[        TXbX45      $ r   _arrayr   rs   r   _dtyper   r   s	          r   r   r   T  A    D$..$:J:JKNNDKK1 &hdKKr!   c                 `   > [        XTR                  TR                  5      n[        TXbX45      $ r   r   r   s	          r   r   r   ]  r   r!   c                    > [        [        XTR                  TR                  5      TR                  TR                  5      n[        TXbX45      $ r   r   r   s	          r   r   r   d  r   r!   c                    > TR                   u  pgTR                  u  p[        XXh5      n
[        XXy5      n[        TXX#U5      $ r   )rs   r   r   r   )r   r   r   r   r   r   	ichannels	ochannelsisizeosizeidataodatar   r   s               r   r   r   m  sL    '+~~$	#//i?i?%eF&B Br!   c                    > TR                   u  pgTR                  u  pTR                  u  p[        [	        XXj5      Xh5      n[        [	        XX{5      Xy5      n[        TXX#U5      $ r   )rs   r   r   r   r   r   )r   r   r   r   r   r   r   r   idtypeodtyper   r   r   r   r   r   s                 r   r   r   x  sk    '+~~$	!%#//wtYF(2wtYF(2%eF&B Br!   zPaStreamCallback*z
PaStream**zError opening zCould not obtain stream infoc                    > T" 5       $ r   rS   )r   finished_callbacks    r   finished_callback_wrapper7_StreamBase.__init__.<locals>.finished_callback_wrapper  s    ,..r!   PaStreamFinishedCallback).numpydefault	blocksizeclip_off
dither_offnever_drop_inputr"   rx   paNoFlag	paClipOffpaDitherOffpaNeverDropInput'paPrimeOutputBuffersUsingStreamCallback_splitr   r   r   _devicechannelCountrs   r   r@   r~   r   r   paAbortcast	_callbacknew_ptrrw   Pa_OpenStream	__class____name__
_blocksizePa_GetStreamInfor|   
sampleRate_samplerateinputLatency_latencyoutputLatency
isinstanceCData_finished_callbackPa_SetStreamFinishedCallback)(r   r   r+   r   r   r9   r:   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___StreamBase.__init__  s   Z 4444 9999G# L5))I''H ++J#&775=BB 7 }}DNN*LD,,,LD111L5DHHHL8%f~GW#)(#3 Iy#E]NFF!'Hh#N3NFF6L)VXv73K 7M'9fh73K !&.DK&--{/A/AADL(55{7O7OODN$e|Dk) KM M )
 'tXg'5C BJT%5z &,,DL'44DN))K))Kw(!(}}%7t||L99LW_(!:L L W_'!9L L X-8";L L X-7":L L X-8";B B X-7":	B 	B  99%8(CL &yyHHH\*	t!!$))[+",".:   7 789	; IIaL	#$$TYY/ !?@@?? --DM ..DM --t/A/AADM+TZZ88*;'/ +/--.0I+K'444TYY595L5LN O r!   c                     U R                   $ )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+   _StreamBase.samplerate  s     r!   c                     U R                   $ )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   _StreamBase.blocksize  s     r!   c                     U R                   $ )zIDs of the input/output device.)r   r  s    r   r   _StreamBase.device  s     ||r!   c                     U R                   $ )z$The number of input/output channels.)rs   r  s    r   r9   _StreamBase.channels  s     ~~r!   c                     U R                   $ )zNData type of the audio samples.

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

)r   r  s    r   r:   _StreamBase.dtype  s     {{r!   c                     U R                   $ )z@The size in bytes of a single sample.

See Also
--------
dtype

)r   r  s    r   r   _StreamBase.samplesize  s     r!   c                     U R                   $ )zThe 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   _StreamBase.latency  s     }}r!   c                 |    U R                   (       a  g[        [        R                  U R                  5      5      S:H  $ )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

Frt   )closedrw   rx   Pa_IsStreamActiver   r  s    r   active_StreamBase.active  s-     ;;d,,TYY78A==r!   c                 |    U R                   (       a  g[        [        R                  U R                  5      5      S:H  $ )aD  ``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

Trt   )r&  rw   rx   Pa_IsStreamStoppedr   r  s    r   stopped_StreamBase.stopped
  s-     ;;d--dii89Q>>r!   c                 <    U R                   [        R                  :H  $ )z8``True`` after a call to `close()`, ``False`` otherwise.)r   r~   r   r  s    r   r&  _StreamBase.closed  s     yyDII%%r!   c                 h    [         R                  U R                  5      nU(       d  [        S5      eU$ )aX  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)rx   Pa_GetStreamTimer   r|   )r   r   s     r   r   _StreamBase.time!  s,    & $$TYY/ !<==r!   c                 @    [         R                  U R                  5      $ )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.

)rx   Pa_GetStreamCpuLoadr   r  s    r   cpu_load_StreamBase.cpu_load9  s    * ''		22r!   c                 &    U R                  5         U $ )z9Start  the stream in the beginning of a "with" statement.)startr  s    r   	__enter___StreamBase.__enter__P  s    

r!   c                 D    U R                  5         U R                  5         g)z:Stop and close the stream when exiting a "with" statement.N)rN   rO   )r   argss     r   __exit___StreamBase.__exit__U  s    		

r!   c                     [         R                  U R                  5      nU[         R                  :w  a  [	        US5        gg)z;Commence audio processing.

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

zError starting streamN)rx   Pa_StartStreamr   paStreamIsNotStoppedrw   )r   errs     r   r8  _StreamBase.startZ  s6     !!$)),$+++3/0 ,r!   c                 j    [         R                  U R                  5      nU(       d  [        US5        gg)zTerminate audio processing.

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

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

zError stopping streamN)rx   Pa_StopStreamr   rw   r   rK   rB  s      r   rN   _StreamBase.stopf  s+       +3/0 r!   c                 j    [         R                  U R                  5      nU(       d  [        US5        gg)z}Terminate audio processing immediately.

This does not wait for pending buffers to complete.

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

zError aborting streamN)rx   Pa_AbortStreamr   rw   rF  s      r   abort_StreamBase.abortu  s+     !!$)),3/0 r!   c                     [         R                  U R                  5      n[        R                  U l        U(       d  [        US5        gg)zuClose the stream.

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

zError closing streamN)rx   Pa_CloseStreamr   r~   r   rw   rF  s      r   rO   _StreamBase.close  s6     !!$)),II	3./ r!   )
r   r   rs   r   r   r  r   r   r   r   )NNNNNNNNNNNNNNNT)r   
__module____qualname____firstlineno____doc__r  r~   r   r   propertyr+   r   r   r9   r:   r   r   r(  r,  r&  r   r5  r9  r=  r8  rN   rJ  rO   __static_attributes__rS   r!   r   r   r     s6   ?EIIMAE37<@.2TOn 99D                	 	 > >$ ? ?" & &  . 3 3,


111
0r!   r   c                   .    \ rS rSrSr\S 5       rS rSrg)_InputStreamBasei  z$Base class for input stream classes.c                 R    [        [        R                  U R                  5      5      $ )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.

)rw   rx   Pa_GetStreamReadAvailabler   r  s    r   read_available_InputStreamBase.read_available  s     d44TYY?@@r!   c                 N   [        U R                  5      u  p#[        U R                  5      u  pC[        R                  " SX$-  U-  5      n[
        R                  U R                  XQ5      nU[
        R                  :X  a  SnO[        U5        Sn[        R                  " U5      U4$ )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 `~Stream.samplesize`.
overflowed : bool
    See `Stream.read()`.

zsigned char[]TF)r   rs   r   r~   r   rx   Pa_ReadStreamr   paInputOverflowedrw   r   )r   r   r9   r   r   r*   rB  
overfloweds           r   	_raw_read_InputStreamBase._raw_read  s    0 T^^,t//0
xx)>)GH  D9$(((J3KJ{{4 *,,r!   rS   N)	r   rP  rQ  rR  rS  rT  rZ  r`  rU  rS   r!   r   rW  rW    s    .A A!-r!   rW  c                   D    \ rS rSrSr     SS jr\R                  rSr	g)RawInputStreami  z=Raw stream for recording only.  See __init__() and RawStream.Nc                 Z    [         R                  " U 4SSS.[        [        5       5      D6  g)a  PortAudio input stream (using buffer objects).

This is the same as `InputStream`, except that the *callback*
function and `~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:

    .. code-block:: text

        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

rZ   r   r   r  Nr   r  _remove_selflocalsr   r+   r   r   r9   r:   r   r   r   r   r   r   r   r"   s                 r   r  RawInputStream.__init__  s-    D 	T 	7x 	7+FH5	7r!   rS   NNNNNNNNNNNNN)
r   rP  rQ  rR  rS  r  rW  r`  readrU  rS   r!   r   rc  rc    s'    G26AEGKBF<@	#7J %%Dr!   rc  c                   .    \ rS rSrSr\S 5       rS rSrg)_OutputStreamBasei  z%Base class for output stream classes.c                 R    [        [        R                  U R                  5      5      $ )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.

)rw   rx   Pa_GetStreamWriteAvailabler   r  s    r   write_available!_OutputStreamBase.write_available  s     d55dii@AAr!   c                     [         R                  " U5      n[	        U R
                  5      u  p#[	        U R                  5      u  p$[        [        U5      U5      u  pVU(       a  [        S5      e[        XT5      u  pvU(       a  [        S5      e[        R                  U R                  X5      nU[        R                  :X  a  Sn	U	$ [        U5        Sn	U	$ ! [         a     N[         a     Nf = f)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 `~Stream.samplesize`.

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

z%len(data) not divisible by samplesizez+Number of samples not divisible by channelsTF)r~   from_bufferAttributeError	TypeErrorr   r   rs   divmodr   r@   rx   Pa_WriteStreamr   paOutputUnderflowedrw   )
r   r*   r   r   r9   samples	remainderr   rB  underfloweds
             r   
_raw_write_OutputStreamBase._raw_write  s    0	##D)D
 t//0T^^,#CIz:DEE"75JKK!!$))T:$***K  3KK%  	 		s   C 
C-!	C-,C-rS   N)	r   rP  rQ  rR  rS  rT  rq  r}  rU  rS   r!   r   rn  rn    s    /B B,r!   rn  c                   D    \ rS rSrSr     SS jr\R                  rSr	g)RawOutputStreami(  z<Raw stream for playback only.  See __init__() and RawStream.Nc                 Z    [         R                  " U 4SSS.[        [        5       5      D6  g)a  PortAudio output stream (using buffer objects).

This is the same as `OutputStream`, except that the *callback*
function and `~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:

    .. code-block:: text

        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

r[   r   re  Nrf  ri  s                 r   r  RawOutputStream.__init__+  s-    D 	T 	7 	7+FH5	7r!   rS   rk  )
r   rP  rQ  rR  rS  r  rn  r}  writerU  rS   r!   r   r  r  (  s'    F26AEGKBF<@	#7J ((Er!   r  c                   ,    \ rS rSrSr     SS jrSrg)	RawStreamiS  z7Raw stream for playback and recording.  See __init__().Nc                 Z    [         R                  " U 4SSS.[        [        5       5      D6  g)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 `~Stream.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:

    .. code-block:: text

        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   re  Nrf  ri  s                 r   r  RawStream.__init__V  s-    ^ 	T 	7 	7+FH5	7r!   rS   rk  r   rP  rQ  rR  rS  r  rU  rS   r!   r   r  r  S  s    A26AEGKBF<@	07r!   r  c                   2    \ rS rSrSr     SS jrS rSrg)r6   i  z2Stream for input only.  See __init__() and Stream.Nc                 Z    [         R                  " U 4SSS.[        [        5       5      D6  g)a  PortAudio input stream (using NumPy).

This has the same methods and attributes as `Stream`, except
`~Stream.write()` and `~Stream.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:

    .. code-block:: text

        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

rZ   r   re  Nrf  ri  s                 r   r  InputStream.__init__  s-    @ 	T 	7w 	7+FH5	7r!   c                     [        U R                  5      u  p#[        U R                  5      u  pC[        R	                  X5      u  pV[        XTU5      nXV4$ )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   rs   rW  r`  r   )r   r   r:   r   r9   r*   r_  s          r   rl  InputStream.read  sL    < $++&T^^,+55dCde,r!   rS   rk  )r   rP  rQ  rR  rS  r  rl  rU  rS   r!   r   r6   r6     s    <26AEGKBF<@	!7F" r!   r6   c                   2    \ rS rSrSr     SS jrS rSrg)r'   i  z3Stream for output only.  See __init__() and Stream.Nc                 Z    [         R                  " U 4SSS.[        [        5       5      D6  g)a  PortAudio output stream (using NumPy).

This has the same methods and attributes as `Stream`, except
`~Stream.read()` and `~Stream.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:

    .. code-block:: text

        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

r[   r   re  Nrf  ri  s                 r   r  OutputStream.__init__  s-    @ 	T 	7 	7+FH5	7r!   c                 4   SSK nUR                  U5      n[        U R                  5      u  p4[        U R                  5      u  p5UR
                  S:  a  UR                  SS5      nOUR
                  S:  a  [        S5      eUR                  S   U:w  a  [        S5      eUR                  U:w  a/  [        SR                  UR                  R                  U5      5      eUR                  R                  (       d  [        S	5      e[        R!                  X5      $ )
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   Nrf   rt   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   rs   ndimreshaper@   shaper:   rv  r   rh   flagsc_contiguousrn  r}  )r   r*   npr   r:   r9   s         r   r  OutputStream.write  s    @ 	zz$$++&T^^,99q=<<A&DYY]CDD::a=H$<==:::AA

( ) )zz&&788 ++D77r!   rS   rk  )r   rP  rQ  rR  rS  r  r  rU  rS   r!   r   r'   r'     s    =26AEGKBF<@	!7F/8r!   r'   c                   ,    \ rS rSrSr     SS jrSrg)rA   i,  z-Stream for input and output.  See __init__().Nc                 Z    [         R                  " U 4SSS.[        [        5       5      D6  g)aR,  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:

    .. code-block:: text

        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:

    .. code-block:: text

        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   re  Nrf  ri  s                 r   r  Stream.__init__/  s-    | 	T 	7 	7+FH5	7r!   rS   rk  r  rS   r!   r   rA   rA   ,  s    726AEGKBF<@	7r!   rA   c                   "    \ rS rSrSrSrS rSrg)ru   i1  a   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>`.

rS   c                 b  ^^^^^ [        [        R                  S   S5      m[        [        R                  S   S5      m[        [	        [
        R                  5       S-
  5      5      m[        5        Vs/ s H  oS   PM	     snmUU4S jmSR                  UUU4S jU  5       5      nU$ s  snf )NrZ   r[   rt   rh   c                 &   > SU T:H  SU T:H  -  -      $ )N) ><*rf   rS   )idxidevodevs    r   get_mark%DeviceList.__repr__.<locals>.get_markI  s     'SD[8I(IJJr!   
c              3      >#    U  H5  nS R                  T" US   5      US   TUS   TUS      US   US   S9v   M7     g7f)z6{mark} {idx:{dig}} {name}, {ha} ({ins} in, {outs} out)ri   rh   rj   rk   rl   )markr  digrh   hainsoutsNr   )r_   r   digitsr  hostapi_namess     r   ra   &DeviceList.__repr__.<locals>.<genexpr>L  si      	  EKKd7m,M&\ i1-./0 L 2 s   =A )	rz   r   r   r   strrx   ry   r   join)r   rj   textr  r  r  r  r  s      @@@@@r   __repr__DeviceList.__repr__C  s    gnnW5w?gnnX6AS//1A5678F8HI8HW8HI	K yy 	 	 	  Js   5B,N)r   rP  rQ  rR  rS  	__slots__r  rU  rS   r!   r   ru   ru   1  s     Ir!   ru   c                   *   \ rS rSrSrSrSS jrS rS rS r	S r
\S	 5       r\R                  S
 5       r\S 5       r\R                  S 5       r\S 5       r\R                  S 5       r\S 5       r\R                  S 5       r\S 5       rS rS rSrg)CallbackFlagsiY  a  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>

_flagsc                     Xl         g r   r  r   r  s     r   r  CallbackFlags.__init__  s    r!   c                 6    [        U 5      nU(       d  SnSU S3$ )Nzno flags setz<sounddevice.CallbackFlags: r  )r  r  s     r   r  CallbackFlags.__repr__  s"    D	"E-eWA66r!   c                 L   ^  SR                  U 4S j[        T 5       5       5      $ )N, c              3      >#    U  HB  nUR                  S 5      (       a  M  [        TU5      (       d  M.  UR                  S S5      v   MD     g7f)r   r  N)
startswithgetattrreplace)r_   rh   r   s     r   ra   (CallbackFlags.__str__.<locals>.<genexpr>  sB      NID $ 4 09@t9L 0c3//Is   AAA)r  dirr  s   `r   __str__CallbackFlags.__str__  s(    yy NCI N N 	Nr!   c                 ,    [        U R                  5      $ r   boolr  r  s    r   __bool__CallbackFlags.__bool__  s    DKK  r!   c                 z    [        U[        5      (       d  [        $ U =R                  UR                  -  sl        U $ r   )r  r  NotImplementedr  )r   others     r   __ior__CallbackFlags.__ior__  s,    %//!!u||#r!   c                 @    U R                  [        R                  5      $ )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()`).

)_hasflagrx   paInputUnderflowr  s    r   input_underflowCallbackFlags.input_underflow  s     }}T2233r!   c                 D    U R                  [        R                  U5        g r   )_updateflagrx   r  r   values     r   r  r        ..6r!   c                 @    U R                  [        R                  5      $ )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  rx   paInputOverflowr  s    r   input_overflowCallbackFlags.input_overflow  s     }}T1122r!   c                 D    U R                  [        R                  U5        g r   )r  rx   r  r  s     r   r  r    s    --u5r!   c                 @    U R                  [        R                  5      $ )zOutput 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  rx   paOutputUnderflowr  s    r   output_underflowCallbackFlags.output_underflow  s     }}T3344r!   c                 D    U R                  [        R                  U5        g r   )r  rx   r  r  s     r   r  r    s    //7r!   c                 @    U R                  [        R                  5      $ )zOutput 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  rx   paOutputOverflowr  s    r   output_overflowCallbackFlags.output_overflow  s     }}T2233r!   c                 D    U R                  [        R                  U5        g r   )r  rx   r  r  s     r   r  r    r  r!   c                 @    U R                  [        R                  5      $ )a+  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  rx   paPrimingOutputr  s    r   priming_outputCallbackFlags.priming_output  s     }}T1122r!   c                 2    [        U R                  U-  5      $ )zCheck a given flag.r  )r   flags     r   r  CallbackFlags._hasflag  s    DKK$&''r!   c                 j    U(       a  U =R                   U-  sl         gU =R                   U) -  sl         g)zSet/clear a given flag.Nr  )r   r  r  s      r   r  CallbackFlags._updateflag  s#    KK4KKKD5 Kr!   r  N)r   )r   rP  rQ  rR  rS  r  r  r  r  r  r  rT  r  setterr  r  r  r  r  r  rU  rS   r!   r   r  r  Y  s    &P I7N! 4 4 7 7 3 3  6 6 
5 
5 8 8 4 4 7 7 3 3(!r!   r  c                   :    \ rS rSrSrSSS.rS rS rS rS	 r	S
r
g)_InputOutputPairi  z8Parameter pairs for device, channels, dtype and latency.r   rt   rZ   r[   c                 .    S S /U l         Xl        X l        g r   )_pair_parent_default_attr)r   parentdefault_attrs      r   r  _InputOutputPair.__init__  s    D\
)r!   c                     U R                   R                  X5      nU R                  U   nUc#  [        U R                  U R
                  5      U   nU$ r   )_indexmappingr%   r  r  r   r  r   ri   r  s      r   __getitem___InputOutputPair.__getitem__  sK    ""&&u4

5!=DLL$*<*<=eDEr!   c                 V    U R                   R                  X5      nX R                  U'   g r   )r  r%   r  r  s      r   __setitem___InputOutputPair.__setitem__  s$    ""&&u4!

5r!   c                 $    SR                  U 5      $ )Nz[{0[0]!r}, {0[1]!r}]r  r  s    r   r  _InputOutputPair.__repr__  s    %,,T22r!   )r  r  r   N)r   rP  rQ  rR  rS  r  r  r  r  r  rU  rS   r!   r   r  r    s#    B1-M*
"3r!   r  c                       \ rS rSrSrSrSr S=rr S=r	r
 S=rr S=rr Sr \R"                  r Sr Sr Sr Sr S	 rS
 r\S 5       r\S 5       rS rSrg)r   i  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   r9   r:   r   r   NN)r
   r
   )highr  NFc                 `    U R                    H  n[        U SU-   5      [        U 5      U'   M      g )N	_default_)_pairsr  vars)r   attrs     r   r  default.__init__  s*    KKD/kD6HIDJt  r!   c                     XR                   ;   a"  [        U5      [        X5      R                  SS& gU[	        U 5      ;   a  US:w  a  [
        R                  XU5        g[        S[        U5      -   5      e)z'Only allow setting existing attributes.Nresetz"'default' object has no attribute )	r  r   r  r  r  object__setattr__ru  repr)r   rh   r  s      r   r  default.__setattr__  sb    ;;+1%=GD%%a(SY47?t51 4tDzAC Cr!   c                 R    [         R                  5       [         R                  5       4$ r   )rx   Pa_GetDefaultInputDevicePa_GetDefaultOutputDevicer  s    r   _default_devicedefault._default_device  s$    --/..02 	2r!   c                 <    [        [        R                  5       5      $ )z*Index of the default host API (read-only).)rw   rx   Pa_GetDefaultHostApir  s    r   rj   default.hostapi  s     d//122r!   c                 V    [        U 5      R                  5         U R                  5         g)z0Reset all attributes to their "factory default".N)r  clearr  r  s    r   r  default.reset  s    T
r!   rS   )r   rP  rQ  rR  rS  r  r   r9   _default_channelsr:   _default_dtyper   _default_latencyr   _default_extra_settingsr+   rx   paFramesPerBufferUnspecifiedr   r   r   r   r"   r  r  rT  r!  rj   r  rU  rS   r!   r   r   r     s    $L HF F $.-H  21EN "0/G1/99N, J 11I3H
 J
  27.	J
C 2 2 3 3r!   r   	I_AM_FAKEc                       \ rS rSrSrS rSrg)r|   i  au  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                    U R                   (       a  U R                   S   OSn[        U R                   5      S:  a  U SU R                   S    S3n[        U R                   5      S:  aV  U R                   S   u  p#nU[        R                  :X  a  SnOUS:  a  SU S	3nO[	        U5      S
   nSR                  XXS5      nU$ )Nr    rt   z [PaErrorCode ]rf   z<host API not found>z<error getting host API: r  rh   z{}: '{}' [{} error {}])r<  r   rx   paHostApiNotFoundr   r   )r   errormsghost_apihosterror_codehosterror_texthostnames         r   r  PortAudioError.__str__  s    #'99499Q<"tyy>A">$))A,qAHtyy>A7;yy|4Hn41111A6xjB)(3F;/66(DH r!   rS   N)r   rP  rQ  rR  rS  r  rU  rS   r!   r   r|   r|     s    r!   r|   c                       \ rS rSrSrSrg)CallbackStopi  zException 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, `Stream.stop()`, Stream

rS   Nr   rP  rQ  rR  rS  rU  rS   r!   r   r;  r;        	r!   r;  c                       \ rS rSrSrSrg)CallbackAborti  zException 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, `Stream.abort()`, Stream

rS   Nr<  rS   r!   r   r?  r?    r=  r!   r?  c                       \ rS rSrS rSrg)AsioSettingsi  c                 >   [        U[        5      (       a  [        S5      e[        R                  " SU5      U l        [        R                  " S[        [        R                  " S5      [        R                  S[        R                  U R
                  S95      U l        g)a`  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*PaAsioStreamInfort   )sizehostApiTypeversionr  channelSelectorsN)r  intrv  r~   r   
_selectorsdictsizeofrx   r   paAsioUseChannelSelectors_streaminfo)r   channel_selectorss     r   r  AsioSettings.__init__	  st    L '--GHH((7,=>88$7/000!__:. /r!   )rI  rM  Nr   rP  rQ  rR  r  rU  rS   r!   r   rA  rA    s    //r!   rA  c                   "    \ rS rSr  SS jrSrg)CoreAudioSettingsi3	  Nc           	         [         R                  [         R                  [         R                  [         R                  [         R
                  S.n[        U[        5      (       a  [        S5      e XTR                  5          U l
        U(       a#  U =R                  [         R                   -  sl
        U(       a#  U =R                  [         R"                  -  sl
        [$        R&                  " S5      U l        [         R+                  U R(                  U R                  5        Ub  [$        R&                  " SU5      U l        [/        U R,                  5      S:X  a  [        S5      e[         R1                  U R(                  U R,                  [/        U R,                  5      5        gg! [        [        4 a&  n[        S[        [        U5      5      -   5      UeSnAff = f)	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  maxz#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)rx   paMacCoreConversionQualityMinpaMacCoreConversionQualityLow paMacCoreConversionQualityMediumpaMacCoreConversionQualityHighpaMacCoreConversionQualityMaxr  rH  rv  lowerr  KeyErrorru  r@   r  listpaMacCoreChangeDeviceParameters!paMacCoreFailIfConversionRequiredr~   r   rM  PaMacCore_SetupStreamInfo_channel_mapr   PaMacCore_SetupChannelMap)r   channel_mapchange_device_parametersfail_if_conversion_requiredconversion_qualityconversion_dictes          r   r  CoreAudioSettings.__init__5	  su   l 8888;;9988
 k3''ABB	A)*B*B*DEDK $KK4???K&KK4AAAK  88$:;&&t'7'7E" $[ AD4$$%* ?@@**4+;+;+/+<+<+.t/@/@+AC # .) 	AA!$"789 :?@A	As   0F# #G3!GG)rc  r  rM  )NFFrW  rP  rS   r!   r   rR  rR  3	  s    BGGLWCr!   rR  c                       \ rS rSrSS jrSrg)WasapiSettingsi	  c           
      4   SnU(       a  U[         R                  -  nU(       a  U[         R                  -  nU(       a  U[         R                  -  n[        R
                  " S[        [        R                  " S5      [         R                  SUS95      U l	        g)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``.

explicit_sample_format : bool
    Force explicit sample format and do not allow PortAudio to
    select suitable working format. API will fail if provided
    sample format is not supported by audio hardware in Exclusive
    mode or system mixer in Shared mode. This is required for
    accurate native format detection.

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*PaWasapiStreamInfort   )rD  rE  rF  r  N)
rx   paWinWasapiExclusivepaWinWasapiAutoConvertpaWinWasapiExplicitSampleFormatr~   r   rJ  rK  paWASAPIrM  )r   	exclusiveauto_convertexplicit_sample_formatr  s        r   r  WasapiSettings.__init__	  sx    V T...ET000E!T999E88$9412	<
 r!   )rM  N)FFFrP  rS   r!   r   rm  rm  	  s    7r!   rm  c                       \ rS rSrSrSrSrSrSrS=r	r
S=rrS=rrSrSS jrS rS rS rS	 rS
 rS rS rS rSS jrSrg)r#   i	  z;Helper class for reuse in play()/rec()/playrec() callbacks.Nr   c                     SS K n SS KnU(       d   e Xl        UR	                  5       U l        [        5       U l        g ! [         a  n[        S5      UeS nAff = f)Nr   z2NumPy must be installed for play()/rec()/playrec())	threadingr   ImportErrorr   Eventeventr  r   )r   r   rz  r   rj  s        r   r  _CallbackContext.__init__	  s\    	ML5 	__&
#o  	MDFKLM	Ms   ? 
A	AAc                    SSK nUR                  U5      nUR                  S:  a  UR                  SS5      nOUR                  S:  a  [	        S5      eUR
                  u  pV[        UR                  5      nUSLn[        X&5      u  p&UR
                  S   S:X  a  O'UR
                  S   [        U5      :w  a  [	        S5      eU(       a-  UR                  US/5      (       a  [        US5      S	   S:  a  SnUR                  UR                  U5      U5      n	[        U5      [        U	5      -   U:w  a  [	        S
5      eXl        X`l        Xpl        X l        Xl        U$ )zCheck data and output mapping.r   Nrf   r  rt   z<audio data to be played back must be one- or two-dimensionalz3number of output channels != size of output mappingr[   rl   z,each channel may only appear once in mapping)r   r  r  r  r@   r  _check_dtyper:   _check_mappingr   array_equalr]   	setdiff1daranger*   r(   r)   rC   silent_channels)
r   r*   r,   r   r  r   r9   r:   mapping_is_explicitr  s
             r   r$   _CallbackContext.check_data	  sD   zz$99q=<<A&DYY]NP P::TZZ(%T1*7=::a=AZZ]c'l*EG G  BNN7QC$@$@fh/0EF!KH,,ryy':GDw<#o..(:KLL	'!%.r!   c                    SSK nUcy  Uc  [        S5      eUc  [        R                  S   nUc(  Uc  [        S5      e[	        UR                  U5      5      nUc  [        R                  S   n UR                  X#4USS9nOUR                  u  p#UR                  n[        U5      n[        XS5      u  pSUR                  S   [	        U5      :w  a  [        S5      eXl        X0l        X@l        XPl        X4$ ! [         aE  nSSKJ	n  [        X(5      (       d  [        S	5      Ue[        X85      (       d  [        S
5      UeUeSnAff = f)z5Check out, frames, channels, dtype and input mapping.r   Nzframes must be specifiedrZ   z,Unable to determine number of input channelsC)order)Integralz'frames' must be an integerz'channels' must be an integerrt   z1number of input channels != size of input mapping)r   rv  r   r9   r   
atleast_1dr:   emptynumbersr  r  r  r  r  r@   r;   r7   r8   rB   )	r   r;   r   r9   r:   r,   r  rj  r  s	            r   r5   _CallbackContext.check_out
  sS   ;~ :;;"++G4?#FH H  #2==#9:H}g.hh15hD  #yyFIIEU#*7=99Q<3w<'CE E & ${)  ,!&33#$ABI!(55#$CD!Ks   .C5 5
E?A D??Ec                     U =R                   U-  sl         [        U R                  U R                  -
  [	        U5      5      U l        g)zCheck status and blocksize.N)r   rT  r   framer   r   )r   r   r*   s      r   r   _CallbackContext.callback_enter/
  s/    vT[[4::5s4yAr!   c                     [        U R                  5       HJ  u  p#US U R                  2U4   U R                  U R                  U R                  U R                  -   2U4'   ML     g r   )	enumeraterB   r   r;   r  )r   r3   targetsources       r   r2   _CallbackContext.read_indata4
  s[     ((:(:;NF ./ HHTZZ

T^^ ;;VCD <r!   c                    U R                   U R                  U R                  U R                  -    US U R                  2U R                  4'   SUS U R                  2U R                  4'   U R
                  (       ad  U R                  [        U5      :  aK  SU l        XR                  S  n[        U R                  [        U5      5      U l        U R                  U5        g SXR                  S & g Nr   )
r*   r  r   rC   r  r   r   rT  r   r   )r   r   s     r   r   _CallbackContext.write_outdata?
  s     IIdjjdnn!<= 	!4!4459:!5!55699#g,6DJnno.G c'l;DNw''(GNNO$r!   c                 p    U R                   (       d  [        eU =R                  U R                   -  sl        g r   )r   r?  r  r  s    r   r   _CallbackContext.callback_exitL
  s!    ~~

dnn$
r!   c                     U R                   R                  5         S U l        S U l        S U R                  l        S U R                  l        g r   )r}  setr*   r;   rM   r   r  r  s    r   r   "_CallbackContext.finished_callbackQ
  s6    

	 $)-&r!   c           	          [        5         U" SUUUUU R                  S.UD6U l        U R                  R                  5         U qU(       a  U R                  5         g g )N)r+   r9   r:   r   r   rS   )rN   r   rM   r8  rH   rI   )r   StreamClassr+   r9   r:   r   r-   r.   s           r   r&   _CallbackContext.start_streamZ
  s^    ! ,Z+3(-+3484J4J	,
 %+, 	IIK r!   c                      U R                   R                  5         U R                  R                  U5        U R                  (       a  U R                  $ S$ ! U R                  R                  U5        f = f)zKWait for finished_callback.

Can be interrupted with a KeyboardInterrupt.

N)r}  rI   rM   rO   r   )r   rK   s     r   rI   _CallbackContext.waiti
  sR    	-JJOOKKm,"kkt{{3t3 KKm,s   A A3)r   r*   r}  r  r7   r8   rB   r   r;   r(   r)   rC   r  r   rM   FrO  )r   rP  rQ  rR  rS  r   r*   r;   r  r7   r(   r8   r)   rB   rC   r  r  r$   r5   r   r2   r   r   r   r&   rI   rU  rS   r!   r   r#   r#   	  sq    EID
CE'++N_!%%K,%))MNO
&"H&PB
	0)%
.
4r!   r#   c                 ,    U R                  5       n U S	 U $ )z,Return a copy of d without the 'self' entry.r   copy)ds    r   rg  rg  v
  s    	A	&	Hr!   c                     SSK nU c  UR                  U5      n X4$ UR                  U SS9n UR                  U 5      n U R	                  5       S:  a  [        S5      eU R                  5       nU S-  n X4$ )zCheck mapping, obtain channels.r   NTr  rt   zchannel numbers must not be < 1)r   r  r   r  rT  r@   rW  )r,   r9   r  s      r   r  r  }
  s|    ))H%  ((7(.--(;;=1>??;;=1r!   c                     SSK nUR                  U 5      R                  n U [        ;   a   U $ U S:X  a  Sn U $ [	        S[        U 5      -   5      e)zCheck dtype.r   Nfloat64r
   zUnsupported data type: )r   r:   rh   _sampleformatsrv  r  )r:   r  s     r   r  r  
  sW    HHUO  E
 L	 
)	 L 1DK?@@r!   c                 b   U S;   d   eUc  [         R                  n[        XSS9nUc  [         R                  n[	        X 5      nUc  [         R
                  n[	        X05      nUc  [         R                  n[	        X@5      nUc  [         R                  n[	        XP5      nUc  [         R                  n[        U5      nUc  USU -   S-      n [        R                  S   R                  U5      R                  n [        U   n[#        [$        R'                  U5      5      n
US
;   a  USU-   S-   U -   S-      nUc  US   n[(        R*                  " SXXU(       a  UR,                  O[(        R.                  45      nXX4$ ! [         a     Nf = f! [         a  n	[!        SU -   S	-   5      U	eSn	A	ff = f)z?Get parameters for one direction (input or output) of a stream.r  NTrd   rr   rs   r   zInvalid z sample format)rU  r  default_r   r   rq   zPaStreamParameters*)r   r   rz   r9   _select_input_or_outputr:   r   r   r+   r]   _sysmodulesrh   	Exceptionr  r^  r@   rw   rx   Pa_GetSampleSizer~   r   rM  r   )r   r   r9   r:   r   r   r+   r   sampleformatrj  r   r   s               r   r   r   
  s    &&&&~F>F##&x6H}#E0E//%g4G //,^BN''
 D34W%++E277F%e, --l;<J/!zG+c1D8:EF./
/,&4""$))2E FJ j44    Fd*-==>AEFs*   ,E= 8	F =
F
	F

F.F))F.c                     USS [        US   5      4-   n U " U6   [        R                  $ ! [         a    [        R                  s $ [         a    [        R
                  s $ f = f)z9Invoke callback function and check for custom exceptions.Nr  )r  r;  rx   
paCompleter?  r   
paContinue)r   r<  s     r   r   r   
  sc    9d2h/11D$
 ??	   ||s   , A$A$#A$c                 :    [         R                  " XU-  U-  5      $ )z5Create a buffer object from a pointer to some memory.)r~   r   )ptrr   r9   r   s       r   r   r   
  s    ;;sX-
:;;r!   c                 >    SSK nUR                  XS9nSU4Ul        U$ )z(Create NumPy array from a buffer object.r   N)r:   r  )r   
frombufferr  )r   r9   r:   r  r*   s        r   r   r   
  s%    ===-DXDJKr!   c                     [        U [        [        45      (       a  X 4$  U u  pX4$ ! [         a    U =p X4$ [         a  n[	        SU < 35      UeSnAff = f)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 allowed, not N)r  r  bytesrv  r@   )r  invalueoutvaluerj  s       r   r   r   
  s     %#u&&|O!   #""(   O<UIFHMN	OOs   ' A	AAAc                    U S:  a  U $ [         R                  " [        R                  U 5      5      R	                  5       nU(       a  U SU 3nU [        R
                  :X  a{  [        R                  5       n[        R                  UR                  5      n[         R                  " UR                  5      R	                  5       nXCR                  U4n[        X U5      e[        X 5      e)z0Raise PortAudioError for below-zero error codes.r   z: )r~   r   rx   Pa_GetErrorTextr   paUnanticipatedHostErrorPa_GetLastHostErrorInfor   rE  	errorText	errorCoder|   )rB  msgr4  r   r5  r7  hosterror_infos          r   rw   rw   
  s    
ax
{{4//45<<>H
U"XJ'
d+++
 ++-66t7G7GHT^^4;;=!>>>AXN;;

''r!   c                 @    [        U 5      u  p#US:X  a  U$ US:X  a  U$  e)zBGiven a pair (or a single value for both), select input or output.rZ   r[   )r   )value_or_pairr   ivalueovalues       r   r  r  
  s,    M*NFw		5r!   c                 `   US;   d   eU c  [         R                  n [        U 5      u  p4US:X  a  Un O+US:X  a  Un O"X4:X  a  Un O[        SR	                  U 5      5      e[        U [        5      (       a  U $ / n[        [        5       5       HD  u  pgU(       a  USU-   S-      S:  d  M  [        US   5      nUR                  XgS	   US	   45        MF     U R                  5       n	U	R                  5       n
/ n/ nU H  u  pmnUS
-   U-   nSnU
 H:  nUR                  5       R                  UU5      nUS:  a    M>  U[        U5      -  nM<     UR                  Xo45        XR                  5       UR                  5       4;   d  M  UR                  U5        M     Uc  SnU(       d%  U(       a  [        SU-   S-   [        U 5      -   5      eg[        U5      S:  aU  [        U5      S:X  a  US   $ U(       a9  [        SU-   S-   [        U 5      -   S-   SR!                  S U 5       5      -   5      egUS   S   $ )z2Return device ID given space-separated substrings.rY   rZ   r[   z+Input and output device are different: {!r}rr   rs   r   rj   rh   r  zinput/outputzNo z device matching r  rt   z	Multiple z devices found for z:
r  c              3   6   #    U  H  u  pS U SU 3v   M     g7f)[z] NrS   )r_   idrh   s      r   ra   !_get_device_id.<locals>.<genexpr>O  s'      '@7>82 *+2$b'77>s   )r   r   r   r@   r   r  rH  r  r]   r   appendr]  splitfindr   r  r  )id_or_query_stringr   re   r  r  device_listr  r   hostapi_infoquery_string
substringsmatchesexact_device_matchesdevice_stringhostapi_stringfull_stringpos	substrings                     r   rz   rz     sq   ,,,,!$^^*+JDw!		!<!%J$f%78: : $c**!!Kmo.tFTMK781<)$y/:LL,v2FGH /
 &++-L##%JG-8)>#d*^;#I##%**9c:CQw3y>!C	 $ NNB,- 3 3 5{7H7H7JKK$++B/ .9 |22T:L5MMO O 
7|a#$)'**[4/2GG!"4568=>!YY '@7>'@ @@ A A
 1:a=r!   c                  4   Sn  [         R                  " S5      n [         R                  " [         R                  [         R                  5      n[         R
                  " US5        [         R                  " U5         [        [        R                  5       S5        [        S-  qU b.  [         R
                  " U S5        [         R                  " U 5        gg! [         a     Nff = f! U b.  [         R
                  " U S5        [         R                  " U 5        f f = f)zInitialize 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.

Nrf   zError initializing PortAudiort   )_osdupopendevnullO_WRONLYdup2rO   OSErrorrw   rx   Pa_Initialize_initialized)
old_stderrr  s     r   _initializer  V  s     JWWQZ
((3;;5!		'"t!!#%CD!HHZ#IIj! "   !HHZ#IIj! "s   A6C ;'C$ 
C! C!$3Dc                  R    [        [        R                  5       S5        [        S-  qg)zQTerminate PortAudio.

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

zError terminating PortAudiort   N)rw   rx   Pa_Terminater  rS   r!   r   
_terminater  r  s"     4 =>ALr!   c                      [         S:  d   e[        (       a<  [        R                  R                  5         [        R                  R	                  5         [         (       a  [        5         [         (       a  M  g g r  )r  rH   rM   rN   rO   r  rS   r!   r   _exit_handlerr  }  sN    1 ~ 	""$##%
, ,r!   __main__)NNFF)NNNNNNFrO  r  r   )NNNNN)r1  r  )[rS  __version__atexit_atexitosr  platform	_platformsysr  ctypes.utilr   _find_library_sounddevicer   r~   _libnamer  dlopenrx   systemenvironarchitecture_sounddevice_datapathr  nextiter__path__	paFloat32paInt32paInt24paInt16paInt8paUInt8r  r  rH   r/   r<   rF   rI   rN   rT   rW   r]   r   r   r   r   r   r   rW  rc  rn  r  r  r6   r'   rA   r   ru   r  r  r   hasattrr  r|   r;  r?  rA  rR  rm  r#   rg  r  r  r   r   r   r   r   rw   r  rz   r  r  r  registerr   printrS   r!   r   <module>r     sk  *<      5 $!
 !* 344;;x D" ~~\\\\\\KK\\ Pf <@).aH 9=HM^B2(3H(H(Vr2j <@9=I: =A:>I	Pv0 v0r.-{ .-b(&% (&V9 9x()' ()V37 37lH " H VU8$ U8pB7[, B7J% %Pe! e!P3 32a aH t[!!iGY D
9 

I 
1/ 1/hYC YCx9 9xh4 h4V
*5Z	<
((.?D"8     z	-/ MZ  !X%'				y	(s{{*%	(>(>(@(CCkQH%	(>(>(@(CCfLHxx}}T#,,-.0DhPH;;x D!s   H# H# #CK*)K*