1 #ifndef PORTAUDIO_H
2 #define PORTAUDIO_H
3 /*
4  * $Id$
5  * PortAudio Portable Real-Time Audio Library
6  * PortAudio API Header File
7  * Latest version available at: http://www.portaudio.com/
8  *
9  * Copyright (c) 1999-2002 Ross Bencina and Phil Burk
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining
12  * a copy of this software and associated documentation files
13  * (the "Software"), to deal in the Software without restriction,
14  * including without limitation the rights to use, copy, modify, merge,
15  * publish, distribute, sublicense, and/or sell copies of the Software,
16  * and to permit persons to whom the Software is furnished to do so,
17  * subject to the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be
20  * included in all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
25  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
26  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
27  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29  */
30 
31 /*
32  * The text above constitutes the entire PortAudio license; however,
33  * the PortAudio community also makes the following non-binding requests:
34  *
35  * Any person wishing to distribute modifications to the Software is
36  * requested to send the modifications to the original developer so that
37  * they can be incorporated into the canonical version. It is also
38  * requested that these non-binding requests be included along with the
39  * license above.
40  */
41 
42 /** @file
43  @ingroup public_header
44  @brief The portable PortAudio API.
45 */
46 
47 
48 #ifdef __cplusplus
49 extern "C"
50 {
51 #endif /* __cplusplus */
52 
53 /** Retrieve the release number of the currently running PortAudio build.
54  For example, for version "19.5.1" this will return 0x00130501.
55 
56  @see paMakeVersionNumber
57 */
58 int Pa_GetVersion( void );
59 
60 /** Retrieve a textual description of the current PortAudio build,
61  e.g. "PortAudio V19.5.0-devel, revision 1952M".
62  The format of the text may change in the future. Do not try to parse the
63  returned string.
64 
65  @deprecated As of 19.5.0, use Pa_GetVersionInfo()->versionText instead.
66 */
67 const char* Pa_GetVersionText( void );
68 
69 /**
70  Generate a packed integer version number in the same format used
71  by Pa_GetVersion(). Use this to compare a specified version number with
72  the currently running version. For example:
73 
74  @code
75      if( Pa_GetVersion() < paMakeVersionNumber(19,5,1) ) {}
76  @endcode
77 
78  @see Pa_GetVersion, Pa_GetVersionInfo
79  @version Available as of 19.5.0.
80 */
81 #define paMakeVersionNumber(major, minor, subminor) \
82     (((major)&0xFF)<<16 | ((minor)&0xFF)<<8 | ((subminor)&0xFF))
83 
84 
85 /**
86  A structure containing PortAudio API version information.
87  @see Pa_GetVersionInfo, paMakeVersionNumber
88  @version Available as of 19.5.0.
89 */
90 typedef struct PaVersionInfo {
91     int versionMajor;
92     int versionMinor;
93     int versionSubMinor;
94     /**
95      This is currently the Git revision hash but may change in the future.
96      The versionControlRevision is updated by running a script before compiling the library.
97      If the update does not occur, this value may refer to an earlier revision.
98     */
99     const char *versionControlRevision;
100     /** Version as a string, for example "PortAudio V19.5.0-devel, revision 1952M" */
101     const char *versionText;
102 } PaVersionInfo;
103 
104 /** Retrieve version information for the currently running PortAudio build.
105  @return A pointer to an immutable PaVersionInfo structure.
106 
107  @note This function can be called at any time. It does not require PortAudio
108  to be initialized. The structure pointed to is statically allocated. Do not
109  attempt to free it or modify it.
110 
111  @see PaVersionInfo, paMakeVersionNumber
112  @version Available as of 19.5.0.
113 */
114 const PaVersionInfo* Pa_GetVersionInfo( void );
115 
116 
117 /** Error codes returned by PortAudio functions.
118  Note that with the exception of paNoError, all PaErrorCodes are negative.
119 */
120 
121 typedef int PaError;
122 typedef enum PaErrorCode
123 {
124     paNoError = 0,
125 
126     paNotInitialized = -10000,
127     paUnanticipatedHostError,
128     paInvalidChannelCount,
129     paInvalidSampleRate,
130     paInvalidDevice,
131     paInvalidFlag,
132     paSampleFormatNotSupported,
133     paBadIODeviceCombination,
134     paInsufficientMemory,
135     paBufferTooBig,
136     paBufferTooSmall,
137     paNullCallback,
138     paBadStreamPtr,
139     paTimedOut,
140     paInternalError,
141     paDeviceUnavailable,
142     paIncompatibleHostApiSpecificStreamInfo,
143     paStreamIsStopped,
144     paStreamIsNotStopped,
145     paInputOverflowed,
146     paOutputUnderflowed,
147     paHostApiNotFound,
148     paInvalidHostApi,
149     paCanNotReadFromACallbackStream,
150     paCanNotWriteToACallbackStream,
151     paCanNotReadFromAnOutputOnlyStream,
152     paCanNotWriteToAnInputOnlyStream,
153     paIncompatibleStreamHostApi,
154     paBadBufferPtr
155 } PaErrorCode;
156 
157 
158 /** Translate the supplied PortAudio error code into a human readable
159  message.
160 */
161 const char *Pa_GetErrorText( PaError errorCode );
162 
163 
164 /** Library initialization function - call this before using PortAudio.
165  This function initializes internal data structures and prepares underlying
166  host APIs for use.  With the exception of Pa_GetVersion(), Pa_GetVersionText(),
167  and Pa_GetErrorText(), this function MUST be called before using any other
168  PortAudio API functions.
169 
170  If Pa_Initialize() is called multiple times, each successful
171  call must be matched with a corresponding call to Pa_Terminate().
172  Pairs of calls to Pa_Initialize()/Pa_Terminate() may overlap, and are not
173  required to be fully nested.
174 
175  Note that if Pa_Initialize() returns an error code, Pa_Terminate() should
176  NOT be called.
177 
178  @return paNoError if successful, otherwise an error code indicating the cause
179  of failure.
180 
181  @see Pa_Terminate
182 */
183 PaError Pa_Initialize( void );
184 
185 
186 /** Library termination function - call this when finished using PortAudio.
187  This function deallocates all resources allocated by PortAudio since it was
188  initialized by a call to Pa_Initialize(). In cases where Pa_Initialise() has
189  been called multiple times, each call must be matched with a corresponding call
190  to Pa_Terminate(). The final matching call to Pa_Terminate() will automatically
191  close any PortAudio streams that are still open.
192 
193  Pa_Terminate() MUST be called before exiting a program which uses PortAudio.
194  Failure to do so may result in serious resource leaks, such as audio devices
195  not being available until the next reboot.
196 
197  @return paNoError if successful, otherwise an error code indicating the cause
198  of failure.
199 
200  @see Pa_Initialize
201 */
202 PaError Pa_Terminate( void );
203 
204 
205 
206 /** The type used to refer to audio devices. Values of this type usually
207  range from 0 to (Pa_GetDeviceCount()-1), and may also take on the PaNoDevice
208  and paUseHostApiSpecificDeviceSpecification values.
209 
210  @see Pa_GetDeviceCount, paNoDevice, paUseHostApiSpecificDeviceSpecification
211 */
212 typedef int PaDeviceIndex;
213 
214 
215 /** A special PaDeviceIndex value indicating that no device is available,
216  or should be used.
217 
218  @see PaDeviceIndex
219 */
220 #define paNoDevice ((PaDeviceIndex)-1)
221 
222 
223 /** A special PaDeviceIndex value indicating that the device(s) to be used
224  are specified in the host api specific stream info structure.
225 
226  @see PaDeviceIndex
227 */
228 #define paUseHostApiSpecificDeviceSpecification ((PaDeviceIndex)-2)
229 
230 
231 /* Host API enumeration mechanism */
232 
233 /** The type used to enumerate to host APIs at runtime. Values of this type
234  range from 0 to (Pa_GetHostApiCount()-1).
235 
236  @see Pa_GetHostApiCount
237 */
238 typedef int PaHostApiIndex;
239 
240 
241 /** Retrieve the number of available host APIs. Even if a host API is
242  available it may have no devices available.
243 
244  @return A non-negative value indicating the number of available host APIs
245  or, a PaErrorCode (which are always negative) if PortAudio is not initialized
246  or an error is encountered.
247 
248  @see PaHostApiIndex
249 */
250 PaHostApiIndex Pa_GetHostApiCount( void );
251 
252 
253 /** Retrieve the index of the default host API. The default host API will be
254  the lowest common denominator host API on the current platform and is
255  unlikely to provide the best performance.
256 
257  @return A non-negative value ranging from 0 to (Pa_GetHostApiCount()-1)
258  indicating the default host API index or, a PaErrorCode (which are always
259  negative) if PortAudio is not initialized or an error is encountered.
260 */
261 PaHostApiIndex Pa_GetDefaultHostApi( void );
262 
263 
264 /** Unchanging unique identifiers for each supported host API. This type
265  is used in the PaHostApiInfo structure. The values are guaranteed to be
266  unique and to never change, thus allowing code to be written that
267  conditionally uses host API specific extensions.
268 
269  New type ids will be allocated when support for a host API reaches
270  "public alpha" status, prior to that developers should use the
271  paInDevelopment type id.
272 
273  @see PaHostApiInfo
274 */
275 typedef enum PaHostApiTypeId
276 {
277     paInDevelopment=0, /* use while developing support for a new host API */
278     paDirectSound=1,
279     paMME=2,
280     paASIO=3,
281     paSoundManager=4,
282     paCoreAudio=5,
283     paOSS=7,
284     paALSA=8,
285     paAL=9,
286     paBeOS=10,
287     paWDMKS=11,
288     paJACK=12,
289     paWASAPI=13,
290     paAudioScienceHPI=14
291 } PaHostApiTypeId;
292 
293 
294 /** A structure containing information about a particular host API. */
295 
296 typedef struct PaHostApiInfo
297 {
298     /** this is struct version 1 */
299     int structVersion;
300     /** The well known unique identifier of this host API @see PaHostApiTypeId */
301     PaHostApiTypeId type;
302     /** A textual description of the host API for display on user interfaces. */
303     const char *name;
304 
305     /**  The number of devices belonging to this host API. This field may be
306      used in conjunction with Pa_HostApiDeviceIndexToDeviceIndex() to enumerate
307      all devices for this host API.
308      @see Pa_HostApiDeviceIndexToDeviceIndex
309     */
310     int deviceCount;
311 
312     /** The default input device for this host API. The value will be a
313      device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice
314      if no default input device is available.
315     */
316     PaDeviceIndex defaultInputDevice;
317 
318     /** The default output device for this host API. The value will be a
319      device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice
320      if no default output device is available.
321     */
322     PaDeviceIndex defaultOutputDevice;
323 
324 } PaHostApiInfo;
325 
326 
327 /** Retrieve a pointer to a structure containing information about a specific
328  host Api.
329 
330  @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)
331 
332  @return A pointer to an immutable PaHostApiInfo structure describing
333  a specific host API. If the hostApi parameter is out of range or an error
334  is encountered, the function returns NULL.
335 
336  The returned structure is owned by the PortAudio implementation and must not
337  be manipulated or freed. The pointer is only guaranteed to be valid between
338  calls to Pa_Initialize() and Pa_Terminate().
339 */
340 const PaHostApiInfo * Pa_GetHostApiInfo( PaHostApiIndex hostApi );
341 
342 
343 /** Convert a static host API unique identifier, into a runtime
344  host API index.
345 
346  @param type A unique host API identifier belonging to the PaHostApiTypeId
347  enumeration.
348 
349  @return A valid PaHostApiIndex ranging from 0 to (Pa_GetHostApiCount()-1) or,
350  a PaErrorCode (which are always negative) if PortAudio is not initialized
351  or an error is encountered.
352 
353  The paHostApiNotFound error code indicates that the host API specified by the
354  type parameter is not available.
355 
356  @see PaHostApiTypeId
357 */
358 PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type );
359 
360 
361 /** Convert a host-API-specific device index to standard PortAudio device index.
362  This function may be used in conjunction with the deviceCount field of
363  PaHostApiInfo to enumerate all devices for the specified host API.
364 
365  @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)
366 
367  @param hostApiDeviceIndex A valid per-host device index in the range
368  0 to (Pa_GetHostApiInfo(hostApi)->deviceCount-1)
369 
370  @return A non-negative PaDeviceIndex ranging from 0 to (Pa_GetDeviceCount()-1)
371  or, a PaErrorCode (which are always negative) if PortAudio is not initialized
372  or an error is encountered.
373 
374  A paInvalidHostApi error code indicates that the host API index specified by
375  the hostApi parameter is out of range.
376 
377  A paInvalidDevice error code indicates that the hostApiDeviceIndex parameter
378  is out of range.
379 
380  @see PaHostApiInfo
381 */
382 PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi,
383         int hostApiDeviceIndex );
384 
385 
386 
387 /** Structure used to return information about a host error condition.
388 */
389 typedef struct PaHostErrorInfo{
390     PaHostApiTypeId hostApiType;    /**< the host API which returned the error code */
391     long errorCode;                 /**< the error code returned */
392     const char *errorText;          /**< a textual description of the error if available, otherwise a zero-length string */
393 }PaHostErrorInfo;
394 
395 
396 /** Return information about the last host error encountered. The error
397  information returned by Pa_GetLastHostErrorInfo() will never be modified
398  asynchronously by errors occurring in other PortAudio owned threads
399  (such as the thread that manages the stream callback.)
400 
401  This function is provided as a last resort, primarily to enhance debugging
402  by providing clients with access to all available error information.
403 
404  @return A pointer to an immutable structure constraining information about
405  the host error. The values in this structure will only be valid if a
406  PortAudio function has previously returned the paUnanticipatedHostError
407  error code.
408 */
409 const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void );
410 
411 
412 
413 /* Device enumeration and capabilities */
414 
415 /** Retrieve the number of available devices. The number of available devices
416  may be zero.
417 
418  @return A non-negative value indicating the number of available devices or,
419  a PaErrorCode (which are always negative) if PortAudio is not initialized
420  or an error is encountered.
421 */
422 PaDeviceIndex Pa_GetDeviceCount( void );
423 
424 
425 /** Retrieve the index of the default input device. The result can be
426  used in the inputDevice parameter to Pa_OpenStream().
427 
428  @return The default input device index for the default host API, or paNoDevice
429  if no default input device is available or an error was encountered.
430 */
431 PaDeviceIndex Pa_GetDefaultInputDevice( void );
432 
433 
434 /** Retrieve the index of the default output device. The result can be
435  used in the outputDevice parameter to Pa_OpenStream().
436 
437  @return The default output device index for the default host API, or paNoDevice
438  if no default output device is available or an error was encountered.
439 
440  @note
441  On the PC, the user can specify a default device by
442  setting an environment variable. For example, to use device #1.
443 <pre>
444  set PA_RECOMMENDED_OUTPUT_DEVICE=1
445 </pre>
446  The user should first determine the available device ids by using
447  the supplied application "pa_devs".
448 */
449 PaDeviceIndex Pa_GetDefaultOutputDevice( void );
450 
451 
452 /** The type used to represent monotonic time in seconds. PaTime is
453  used for the fields of the PaStreamCallbackTimeInfo argument to the
454  PaStreamCallback and as the result of Pa_GetStreamTime().
455 
456  PaTime values have unspecified origin.
457 
458  @see PaStreamCallback, PaStreamCallbackTimeInfo, Pa_GetStreamTime
459 */
460 typedef double PaTime;
461 
462 
463 /** A type used to specify one or more sample formats. Each value indicates
464  a possible format for sound data passed to and from the stream callback,
465  Pa_ReadStream and Pa_WriteStream.
466 
467  The standard formats paFloat32, paInt16, paInt32, paInt24, paInt8
468  and aUInt8 are usually implemented by all implementations.
469 
470  The floating point representation (paFloat32) uses +1.0 and -1.0 as the
471  maximum and minimum respectively.
472 
473  paUInt8 is an unsigned 8 bit format where 128 is considered "ground"
474 
475  The paNonInterleaved flag indicates that audio data is passed as an array
476  of pointers to separate buffers, one buffer for each channel. Usually,
477  when this flag is not used, audio data is passed as a single buffer with
478  all channels interleaved.
479 
480  @see Pa_OpenStream, Pa_OpenDefaultStream, PaDeviceInfo
481  @see paFloat32, paInt16, paInt32, paInt24, paInt8
482  @see paUInt8, paCustomFormat, paNonInterleaved
483 */
484 typedef unsigned long PaSampleFormat;
485 
486 
487 #define paFloat32        ((PaSampleFormat) 0x00000001) /**< @see PaSampleFormat */
488 #define paInt32          ((PaSampleFormat) 0x00000002) /**< @see PaSampleFormat */
489 #define paInt24          ((PaSampleFormat) 0x00000004) /**< Packed 24 bit format. @see PaSampleFormat */
490 #define paInt16          ((PaSampleFormat) 0x00000008) /**< @see PaSampleFormat */
491 #define paInt8           ((PaSampleFormat) 0x00000010) /**< @see PaSampleFormat */
492 #define paUInt8          ((PaSampleFormat) 0x00000020) /**< @see PaSampleFormat */
493 #define paCustomFormat   ((PaSampleFormat) 0x00010000) /**< @see PaSampleFormat */
494 
495 #define paNonInterleaved ((PaSampleFormat) 0x80000000) /**< @see PaSampleFormat */
496 
497 /** A structure providing information and capabilities of PortAudio devices.
498  Devices may support input, output or both input and output.
499 */
500 typedef struct PaDeviceInfo
501 {
502     int structVersion;  /* this is struct version 2 */
503     const char *name;
504     PaHostApiIndex hostApi; /**< note this is a host API index, not a type id*/
505 
506     int maxInputChannels;
507     int maxOutputChannels;
508 
509     /** Default latency values for interactive performance. */
510     PaTime defaultLowInputLatency;
511     PaTime defaultLowOutputLatency;
512     /** Default latency values for robust non-interactive applications (eg. playing sound files). */
513     PaTime defaultHighInputLatency;
514     PaTime defaultHighOutputLatency;
515 
516     double defaultSampleRate;
517 } PaDeviceInfo;
518 
519 
520 /** Retrieve a pointer to a PaDeviceInfo structure containing information
521  about the specified device.
522  @return A pointer to an immutable PaDeviceInfo structure. If the device
523  parameter is out of range the function returns NULL.
524 
525  @param device A valid device index in the range 0 to (Pa_GetDeviceCount()-1)
526 
527  @note PortAudio manages the memory referenced by the returned pointer,
528  the client must not manipulate or free the memory. The pointer is only
529  guaranteed to be valid between calls to Pa_Initialize() and Pa_Terminate().
530 
531  @see PaDeviceInfo, PaDeviceIndex
532 */
533 const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );
534 
535 
536 /** Parameters for one direction (input or output) of a stream.
537 */
538 typedef struct PaStreamParameters
539 {
540     /** A valid device index in the range 0 to (Pa_GetDeviceCount()-1)
541      specifying the device to be used or the special constant
542      paUseHostApiSpecificDeviceSpecification which indicates that the actual
543      device(s) to use are specified in hostApiSpecificStreamInfo.
544      This field must not be set to paNoDevice.
545     */
546     PaDeviceIndex device;
547 
548     /** The number of channels of sound to be delivered to the
549      stream callback or accessed by Pa_ReadStream() or Pa_WriteStream().
550      It can range from 1 to the value of maxInputChannels in the
551      PaDeviceInfo record for the device specified by the device parameter.
552     */
553     int channelCount;
554 
555     /** The sample format of the buffer provided to the stream callback,
556      a_ReadStream() or Pa_WriteStream(). It may be any of the formats described
557      by the PaSampleFormat enumeration.
558     */
559     PaSampleFormat sampleFormat;
560 
561     /** The desired latency in seconds. Where practical, implementations should
562      configure their latency based on these parameters, otherwise they may
563      choose the closest viable latency instead. Unless the suggested latency
564      is greater than the absolute upper limit for the device implementations
565      should round the suggestedLatency up to the next practical value - ie to
566      provide an equal or higher latency than suggestedLatency wherever possible.
567      Actual latency values for an open stream may be retrieved using the
568      inputLatency and outputLatency fields of the PaStreamInfo structure
569      returned by Pa_GetStreamInfo().
570      @see default*Latency in PaDeviceInfo, *Latency in PaStreamInfo
571     */
572     PaTime suggestedLatency;
573 
574     /** An optional pointer to a host api specific data structure
575      containing additional information for device setup and/or stream processing.
576      hostApiSpecificStreamInfo is never required for correct operation,
577      if not used it should be set to NULL.
578     */
579     void *hostApiSpecificStreamInfo;
580 
581 } PaStreamParameters;
582 
583 
584 /** Return code for Pa_IsFormatSupported indicating success. */
585 #define paFormatIsSupported (0)
586 
587 /** Determine whether it would be possible to open a stream with the specified
588  parameters.
589 
590  @param inputParameters A structure that describes the input parameters used to
591  open a stream. The suggestedLatency field is ignored. See PaStreamParameters
592  for a description of these parameters. inputParameters must be NULL for
593  output-only streams.
594 
595  @param outputParameters A structure that describes the output parameters used
596  to open a stream. The suggestedLatency field is ignored. See PaStreamParameters
597  for a description of these parameters. outputParameters must be NULL for
598  input-only streams.
599 
600  @param sampleRate The required sampleRate. For full-duplex streams it is the
601  sample rate for both input and output
602 
603  @return Returns 0 if the format is supported, and an error code indicating why
604  the format is not supported otherwise. The constant paFormatIsSupported is
605  provided to compare with the return value for success.
606 
607  @see paFormatIsSupported, PaStreamParameters
608 */
609 PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters,
610                               const PaStreamParameters *outputParameters,
611                               double sampleRate );
612 
613 
614 
615 /* Streaming types and functions */
616 
617 
618 /**
619  A single PaStream can provide multiple channels of real-time
620  streaming audio input and output to a client application. A stream
621  provides access to audio hardware represented by one or more
622  PaDevices. Depending on the underlying Host API, it may be possible
623  to open multiple streams using the same device, however this behavior
624  is implementation defined. Portable applications should assume that
625  a PaDevice may be simultaneously used by at most one PaStream.
626 
627  Pointers to PaStream objects are passed between PortAudio functions that
628  operate on streams.
629 
630  @see Pa_OpenStream, Pa_OpenDefaultStream, Pa_OpenDefaultStream, Pa_CloseStream,
631  Pa_StartStream, Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive,
632  Pa_GetStreamTime, Pa_GetStreamCpuLoad
633 
634 */
635 typedef void PaStream;
636 
637 
638 /** Can be passed as the framesPerBuffer parameter to Pa_OpenStream()
639  or Pa_OpenDefaultStream() to indicate that the stream callback will
640  accept buffers of any size.
641 */
642 #define paFramesPerBufferUnspecified  (0)
643 
644 
645 /** Flags used to control the behavior of a stream. They are passed as
646  parameters to Pa_OpenStream or Pa_OpenDefaultStream. Multiple flags may be
647  ORed together.
648 
649  @see Pa_OpenStream, Pa_OpenDefaultStream
650  @see paNoFlag, paClipOff, paDitherOff, paNeverDropInput,
651   paPrimeOutputBuffersUsingStreamCallback, paPlatformSpecificFlags
652 */
653 typedef unsigned long PaStreamFlags;
654 
655 /** @see PaStreamFlags */
656 #define   paNoFlag          ((PaStreamFlags) 0)
657 
658 /** Disable default clipping of out of range samples.
659  @see PaStreamFlags
660 */
661 #define   paClipOff         ((PaStreamFlags) 0x00000001)
662 
663 /** Disable default dithering.
664  @see PaStreamFlags
665 */
666 #define   paDitherOff       ((PaStreamFlags) 0x00000002)
667 
668 /** Flag requests that where possible a full duplex stream will not discard
669  overflowed input samples without calling the stream callback. This flag is
670  only valid for full duplex callback streams and only when used in combination
671  with the paFramesPerBufferUnspecified (0) framesPerBuffer parameter. Using
672  this flag incorrectly results in a paInvalidFlag error being returned from
673  Pa_OpenStream and Pa_OpenDefaultStream.
674 
675  @see PaStreamFlags, paFramesPerBufferUnspecified
676 */
677 #define   paNeverDropInput  ((PaStreamFlags) 0x00000004)
678 
679 /** Call the stream callback to fill initial output buffers, rather than the
680  default behavior of priming the buffers with zeros (silence). This flag has
681  no effect for input-only and blocking read/write streams.
682 
683  @see PaStreamFlags
684 */
685 #define   paPrimeOutputBuffersUsingStreamCallback ((PaStreamFlags) 0x00000008)
686 
687 /** A mask specifying the platform specific bits.
688  @see PaStreamFlags
689 */
690 #define   paPlatformSpecificFlags ((PaStreamFlags)0xFFFF0000)
691 
692 /**
693  Timing information for the buffers passed to the stream callback.
694 
695  Time values are expressed in seconds and are synchronised with the time base used by Pa_GetStreamTime() for the associated stream.
696 
697  @see PaStreamCallback, Pa_GetStreamTime
698 */
699 typedef struct PaStreamCallbackTimeInfo{
700     PaTime inputBufferAdcTime;  /**< The time when the first sample of the input buffer was captured at the ADC input */
701     PaTime currentTime;         /**< The time when the stream callback was invoked */
702     PaTime outputBufferDacTime; /**< The time when the first sample of the output buffer will output the DAC */
703 } PaStreamCallbackTimeInfo;
704 
705 
706 /**
707  Flag bit constants for the statusFlags to PaStreamCallback.
708 
709  @see paInputUnderflow, paInputOverflow, paOutputUnderflow, paOutputOverflow,
710  paPrimingOutput
711 */
712 typedef unsigned long PaStreamCallbackFlags;
713 
714 /** In a stream opened with paFramesPerBufferUnspecified, indicates that
715  input data is all silence (zeros) because no real data is available. In a
716  stream opened without paFramesPerBufferUnspecified, it indicates that one or
717  more zero samples have been inserted into the input buffer to compensate
718  for an input underflow.
719  @see PaStreamCallbackFlags
720 */
721 #define paInputUnderflow   ((PaStreamCallbackFlags) 0x00000001)
722 
723 /** In a stream opened with paFramesPerBufferUnspecified, indicates that data
724  prior to the first sample of the input buffer was discarded due to an
725  overflow, possibly because the stream callback is using too much CPU time.
726  Otherwise indicates that data prior to one or more samples in the
727  input buffer was discarded.
728  @see PaStreamCallbackFlags
729 */
730 #define paInputOverflow    ((PaStreamCallbackFlags) 0x00000002)
731 
732 /** Indicates that output data (or a gap) was inserted, possibly because the
733  stream callback is using too much CPU time.
734  @see PaStreamCallbackFlags
735 */
736 #define paOutputUnderflow  ((PaStreamCallbackFlags) 0x00000004)
737 
738 /** Indicates that output data will be discarded because no room is available.
739  @see PaStreamCallbackFlags
740 */
741 #define paOutputOverflow   ((PaStreamCallbackFlags) 0x00000008)
742 
743 /** Some of all of the output data will be used to prime the stream, input
744  data may be zero.
745  @see PaStreamCallbackFlags
746 */
747 #define paPrimingOutput    ((PaStreamCallbackFlags) 0x00000010)
748 
749 /**
750  Allowable return values for the PaStreamCallback.
751  @see PaStreamCallback
752 */
753 typedef enum PaStreamCallbackResult
754 {
755     paContinue=0,   /**< Signal that the stream should continue invoking the callback and processing audio. */
756     paComplete=1,   /**< Signal that the stream should stop invoking the callback and finish once all output samples have played. */
757     paAbort=2       /**< Signal that the stream should stop invoking the callback and finish as soon as possible. */
758 } PaStreamCallbackResult;
759 
760 
761 /**
762  Functions of type PaStreamCallback are implemented by PortAudio clients.
763  They consume, process or generate audio in response to requests from an
764  active PortAudio stream.
765 
766  When a stream is running, PortAudio calls the stream callback periodically.
767  The callback function is responsible for processing buffers of audio samples
768  passed via the input and output parameters.
769 
770  The PortAudio stream callback runs at very high or real-time priority.
771  It is required to consistently meet its time deadlines. Do not allocate
772  memory, access the file system, call library functions or call other functions
773  from the stream callback that may block or take an unpredictable amount of
774  time to complete.
775 
776  In order for a stream to maintain glitch-free operation the callback
777  must consume and return audio data faster than it is recorded and/or
778  played. PortAudio anticipates that each callback invocation may execute for
779  a duration approaching the duration of frameCount audio frames at the stream
780  sample rate. It is reasonable to expect to be able to utilise 70% or more of
781  the available CPU time in the PortAudio callback. However, due to buffer size
782  adaption and other factors, not all host APIs are able to guarantee audio
783  stability under heavy CPU load with arbitrary fixed callback buffer sizes.
784  When high callback CPU utilisation is required the most robust behavior
785  can be achieved by using paFramesPerBufferUnspecified as the
786  Pa_OpenStream() framesPerBuffer parameter.
787 
788  @param input and @param output are either arrays of interleaved samples or;
789  if non-interleaved samples were requested using the paNonInterleaved sample
790  format flag, an array of buffer pointers, one non-interleaved buffer for
791  each channel.
792 
793  The format, packing and number of channels used by the buffers are
794  determined by parameters to Pa_OpenStream().
795 
796  @param frameCount The number of sample frames to be processed by
797  the stream callback.
798 
799  @param timeInfo Timestamps indicating the ADC capture time of the first sample
800  in the input buffer, the DAC output time of the first sample in the output buffer
801  and the time the callback was invoked.
802  See PaStreamCallbackTimeInfo and Pa_GetStreamTime()
803 
804  @param statusFlags Flags indicating whether input and/or output buffers
805  have been inserted or will be dropped to overcome underflow or overflow
806  conditions.
807 
808  @param userData The value of a user supplied pointer passed to
809  Pa_OpenStream() intended for storing synthesis data etc.
810 
811  @return
812  The stream callback should return one of the values in the
813  ::PaStreamCallbackResult enumeration. To ensure that the callback continues
814  to be called, it should return paContinue (0). Either paComplete or paAbort
815  can be returned to finish stream processing, after either of these values is
816  returned the callback will not be called again. If paAbort is returned the
817  stream will finish as soon as possible. If paComplete is returned, the stream
818  will continue until all buffers generated by the callback have been played.
819  This may be useful in applications such as soundfile players where a specific
820  duration of output is required. However, it is not necessary to utilize this
821  mechanism as Pa_StopStream(), Pa_AbortStream() or Pa_CloseStream() can also
822  be used to stop the stream. The callback must always fill the entire output
823  buffer irrespective of its return value.
824 
825  @see Pa_OpenStream, Pa_OpenDefaultStream
826 
827  @note With the exception of Pa_GetStreamCpuLoad() it is not permissible to call
828  PortAudio API functions from within the stream callback.
829 */
830 typedef int PaStreamCallback(
831     const void *input, void *output,
832     unsigned long frameCount,
833     const PaStreamCallbackTimeInfo* timeInfo,
834     PaStreamCallbackFlags statusFlags,
835     void *userData );
836 
837 
838 /** Opens a stream for either input, output or both.
839 
840  @param stream The address of a PaStream pointer which will receive
841  a pointer to the newly opened stream.
842 
843  @param inputParameters A structure that describes the input parameters used by
844  the opened stream. See PaStreamParameters for a description of these parameters.
845  inputParameters must be NULL for output-only streams.
846 
847  @param outputParameters A structure that describes the output parameters used by
848  the opened stream. See PaStreamParameters for a description of these parameters.
849  outputParameters must be NULL for input-only streams.
850 
851  @param sampleRate The desired sampleRate. For full-duplex streams it is the
852  sample rate for both input and output
853 
854  @param framesPerBuffer The number of frames passed to the stream callback
855  function, or the preferred block granularity for a blocking read/write stream.
856  The special value paFramesPerBufferUnspecified (0) may be used to request that
857  the stream callback will receive an optimal (and possibly varying) number of
858  frames based on host requirements and the requested latency settings.
859  Note: With some host APIs, the use of non-zero framesPerBuffer for a callback
860  stream may introduce an additional layer of buffering which could introduce
861  additional latency. PortAudio guarantees that the additional latency
862  will be kept to the theoretical minimum however, it is strongly recommended
863  that a non-zero framesPerBuffer value only be used when your algorithm
864  requires a fixed number of frames per stream callback.
865 
866  @param streamFlags Flags which modify the behavior of the streaming process.
867  This parameter may contain a combination of flags ORed together. Some flags may
868  only be relevant to certain buffer formats.
869 
870  @param streamCallback A pointer to a client supplied function that is responsible
871  for processing and filling input and output buffers. If this parameter is NULL
872  the stream will be opened in 'blocking read/write' mode. In blocking mode,
873  the client can receive sample data using Pa_ReadStream and write sample data
874  using Pa_WriteStream, the number of samples that may be read or written
875  without blocking is returned by Pa_GetStreamReadAvailable and
876  Pa_GetStreamWriteAvailable respectively.
877 
878  @param userData A client supplied pointer which is passed to the stream callback
879  function. It could for example, contain a pointer to instance data necessary
880  for processing the audio buffers. This parameter is ignored if streamCallback
881  is NULL.
882 
883  @return
884  Upon success Pa_OpenStream() returns paNoError and places a pointer to a
885  valid PaStream in the stream argument. The stream is inactive (stopped).
886  If a call to Pa_OpenStream() fails, a non-zero error code is returned (see
887  PaError for possible error codes) and the value of stream is invalid.
888 
889  @see PaStreamParameters, PaStreamCallback, Pa_ReadStream, Pa_WriteStream,
890  Pa_GetStreamReadAvailable, Pa_GetStreamWriteAvailable
891 */
892 PaError Pa_OpenStream( PaStream** stream,
893                        const PaStreamParameters *inputParameters,
894                        const PaStreamParameters *outputParameters,
895                        double sampleRate,
896                        unsigned long framesPerBuffer,
897                        PaStreamFlags streamFlags,
898                        PaStreamCallback *streamCallback,
899                        void *userData );
900 
901 
902 /** A simplified version of Pa_OpenStream() that opens the default input
903  and/or output devices.
904 
905  @param stream The address of a PaStream pointer which will receive
906  a pointer to the newly opened stream.
907 
908  @param numInputChannels  The number of channels of sound that will be supplied
909  to the stream callback or returned by Pa_ReadStream. It can range from 1 to
910  the value of maxInputChannels in the PaDeviceInfo record for the default input
911  device. If 0 the stream is opened as an output-only stream.
912 
913  @param numOutputChannels The number of channels of sound to be delivered to the
914  stream callback or passed to Pa_WriteStream. It can range from 1 to the value
915  of maxOutputChannels in the PaDeviceInfo record for the default output device.
916  If 0 the stream is opened as an output-only stream.
917 
918  @param sampleFormat The sample format of both the input and output buffers
919  provided to the callback or passed to and from Pa_ReadStream and Pa_WriteStream.
920  sampleFormat may be any of the formats described by the PaSampleFormat
921  enumeration.
922 
923  @param sampleRate Same as Pa_OpenStream parameter of the same name.
924  @param framesPerBuffer Same as Pa_OpenStream parameter of the same name.
925  @param streamCallback Same as Pa_OpenStream parameter of the same name.
926  @param userData Same as Pa_OpenStream parameter of the same name.
927 
928  @return As for Pa_OpenStream
929 
930  @see Pa_OpenStream, PaStreamCallback
931 */
932 PaError Pa_OpenDefaultStream( PaStream** stream,
933                               int numInputChannels,
934                               int numOutputChannels,
935                               PaSampleFormat sampleFormat,
936                               double sampleRate,
937                               unsigned long framesPerBuffer,
938                               PaStreamCallback *streamCallback,
939                               void *userData );
940 
941 
942 /** Closes an audio stream. If the audio stream is active it
943  discards any pending buffers as if Pa_AbortStream() had been called.
944 */
945 PaError Pa_CloseStream( PaStream *stream );
946 
947 
948 /** Functions of type PaStreamFinishedCallback are implemented by PortAudio
949  clients. They can be registered with a stream using the Pa_SetStreamFinishedCallback
950  function. Once registered they are called when the stream becomes inactive
951  (ie once a call to Pa_StopStream() will not block).
952  A stream will become inactive after the stream callback returns non-zero,
953  or when Pa_StopStream or Pa_AbortStream is called. For a stream providing audio
954  output, if the stream callback returns paComplete, or Pa_StopStream() is called,
955  the stream finished callback will not be called until all generated sample data
956  has been played.
957 
958  @param userData The userData parameter supplied to Pa_OpenStream()
959 
960  @see Pa_SetStreamFinishedCallback
961 */
962 typedef void PaStreamFinishedCallback( void *userData );
963 
964 
965 /** Register a stream finished callback function which will be called when the
966  stream becomes inactive. See the description of PaStreamFinishedCallback for
967  further details about when the callback will be called.
968 
969  @param stream a pointer to a PaStream that is in the stopped state - if the
970  stream is not stopped, the stream's finished callback will remain unchanged
971  and an error code will be returned.
972 
973  @param streamFinishedCallback a pointer to a function with the same signature
974  as PaStreamFinishedCallback, that will be called when the stream becomes
975  inactive. Passing NULL for this parameter will un-register a previously
976  registered stream finished callback function.
977 
978  @return on success returns paNoError, otherwise an error code indicating the cause
979  of the error.
980 
981  @see PaStreamFinishedCallback
982 */
983 PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback );
984 
985 
986 /** Commences audio processing.
987 */
988 PaError Pa_StartStream( PaStream *stream );
989 
990 
991 /** Terminates audio processing. It waits until all pending
992  audio buffers have been played before it returns.
993 */
994 PaError Pa_StopStream( PaStream *stream );
995 
996 
997 /** Terminates audio processing immediately without waiting for pending
998  buffers to complete.
999 */
1000 PaError Pa_AbortStream( PaStream *stream );
1001 
1002 
1003 /** Determine whether the stream is stopped.
1004  A stream is considered to be stopped prior to a successful call to
1005  Pa_StartStream and after a successful call to Pa_StopStream or Pa_AbortStream.
1006  If a stream callback returns a value other than paContinue the stream is NOT
1007  considered to be stopped.
1008 
1009  @return Returns one (1) when the stream is stopped, zero (0) when
1010  the stream is running or, a PaErrorCode (which are always negative) if
1011  PortAudio is not initialized or an error is encountered.
1012 
1013  @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive
1014 */
1015 PaError Pa_IsStreamStopped( PaStream *stream );
1016 
1017 
1018 /** Determine whether the stream is active.
1019  A stream is active after a successful call to Pa_StartStream(), until it
1020  becomes inactive either as a result of a call to Pa_StopStream() or
1021  Pa_AbortStream(), or as a result of a return value other than paContinue from
1022  the stream callback. In the latter case, the stream is considered inactive
1023  after the last buffer has finished playing.
1024 
1025  @return Returns one (1) when the stream is active (ie playing or recording
1026  audio), zero (0) when not playing or, a PaErrorCode (which are always negative)
1027  if PortAudio is not initialized or an error is encountered.
1028 
1029  @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamStopped
1030 */
1031 PaError Pa_IsStreamActive( PaStream *stream );
1032 
1033 
1034 
1035 /** A structure containing unchanging information about an open stream.
1036  @see Pa_GetStreamInfo
1037 */
1038 
1039 typedef struct PaStreamInfo
1040 {
1041     /** this is struct version 1 */
1042     int structVersion;
1043 
1044     /** The input latency of the stream in seconds. This value provides the most
1045      accurate estimate of input latency available to the implementation. It may
1046      differ significantly from the suggestedLatency value passed to Pa_OpenStream().
1047      The value of this field will be zero (0.) for output-only streams.
1048      @see PaTime
1049     */
1050     PaTime inputLatency;
1051 
1052     /** The output latency of the stream in seconds. This value provides the most
1053      accurate estimate of output latency available to the implementation. It may
1054      differ significantly from the suggestedLatency value passed to Pa_OpenStream().
1055      The value of this field will be zero (0.) for input-only streams.
1056      @see PaTime
1057     */
1058     PaTime outputLatency;
1059 
1060     /** The sample rate of the stream in Hertz (samples per second). In cases
1061      where the hardware sample rate is inaccurate and PortAudio is aware of it,
1062      the value of this field may be different from the sampleRate parameter
1063      passed to Pa_OpenStream(). If information about the actual hardware sample
1064      rate is not available, this field will have the same value as the sampleRate
1065      parameter passed to Pa_OpenStream().
1066     */
1067     double sampleRate;
1068 
1069 } PaStreamInfo;
1070 
1071 
1072 /** Retrieve a pointer to a PaStreamInfo structure containing information
1073  about the specified stream.
1074  @return A pointer to an immutable PaStreamInfo structure. If the stream
1075  parameter is invalid, or an error is encountered, the function returns NULL.
1076 
1077  @param stream A pointer to an open stream previously created with Pa_OpenStream.
1078 
1079  @note PortAudio manages the memory referenced by the returned pointer,
1080  the client must not manipulate or free the memory. The pointer is only
1081  guaranteed to be valid until the specified stream is closed.
1082 
1083  @see PaStreamInfo
1084 */
1085 const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream );
1086 
1087 
1088 /** Returns the current time in seconds for a stream according to the same clock used
1089  to generate callback PaStreamCallbackTimeInfo timestamps. The time values are
1090  monotonically increasing and have unspecified origin.
1091 
1092  Pa_GetStreamTime returns valid time values for the entire life of the stream,
1093  from when the stream is opened until it is closed. Starting and stopping the stream
1094  does not affect the passage of time returned by Pa_GetStreamTime.
1095 
1096  This time may be used for synchronizing other events to the audio stream, for
1097  example synchronizing audio to MIDI.
1098 
1099  @return The stream's current time in seconds, or 0 if an error occurred.
1100 
1101  @see PaTime, PaStreamCallback, PaStreamCallbackTimeInfo
1102 */
1103 PaTime Pa_GetStreamTime( PaStream *stream );
1104 
1105 
1106 /** Retrieve CPU usage information for the specified stream.
1107  The "CPU Load" is a fraction of total CPU time consumed by a callback stream's
1108  audio processing routines including, but not limited to the client supplied
1109  stream callback. This function does not work with blocking read/write streams.
1110 
1111  This function may be called from the stream callback function or the
1112  application.
1113 
1114  @return
1115  A floating point value, typically between 0.0 and 1.0, where 1.0 indicates
1116  that the stream callback is consuming the maximum number of CPU cycles possible
1117  to maintain real-time operation. A value of 0.5 would imply that PortAudio and
1118  the stream callback was consuming roughly 50% of the available CPU time. The
1119  return value may exceed 1.0. A value of 0.0 will always be returned for a
1120  blocking read/write stream, or if an error occurs.
1121 */
1122 double Pa_GetStreamCpuLoad( PaStream* stream );
1123 
1124 
1125 /** Read samples from an input stream. The function doesn't return until
1126  the entire buffer has been filled - this may involve waiting for the operating
1127  system to supply the data.
1128 
1129  @param stream A pointer to an open stream previously created with Pa_OpenStream.
1130 
1131  @param buffer A pointer to a buffer of sample frames. The buffer contains
1132  samples in the format specified by the inputParameters->sampleFormat field
1133  used to open the stream, and the number of channels specified by
1134  inputParameters->numChannels. If non-interleaved samples were requested using
1135  the paNonInterleaved sample format flag, buffer is a pointer to the first element
1136  of an array of buffer pointers, one non-interleaved buffer for each channel.
1137 
1138  @param frames The number of frames to be read into buffer. This parameter
1139  is not constrained to a specific range, however high performance applications
1140  will want to match this parameter to the framesPerBuffer parameter used
1141  when opening the stream.
1142 
1143  @return On success PaNoError will be returned, or PaInputOverflowed if input
1144  data was discarded by PortAudio after the previous call and before this call.
1145 */
1146 PaError Pa_ReadStream( PaStream* stream,
1147                        void *buffer,
1148                        unsigned long frames );
1149 
1150 
1151 /** Write samples to an output stream. This function doesn't return until the
1152  entire buffer has been written - this may involve waiting for the operating
1153  system to consume the data.
1154 
1155  @param stream A pointer to an open stream previously created with Pa_OpenStream.
1156 
1157  @param buffer A pointer to a buffer of sample frames. The buffer contains
1158  samples in the format specified by the outputParameters->sampleFormat field
1159  used to open the stream, and the number of channels specified by
1160  outputParameters->numChannels. If non-interleaved samples were requested using
1161  the paNonInterleaved sample format flag, buffer is a pointer to the first element
1162  of an array of buffer pointers, one non-interleaved buffer for each channel.
1163 
1164  @param frames The number of frames to be written from buffer. This parameter
1165  is not constrained to a specific range, however high performance applications
1166  will want to match this parameter to the framesPerBuffer parameter used
1167  when opening the stream.
1168 
1169  @return On success PaNoError will be returned, or paOutputUnderflowed if
1170  additional output data was inserted after the previous call and before this
1171  call.
1172 */
1173 PaError Pa_WriteStream( PaStream* stream,
1174                         const void *buffer,
1175                         unsigned long frames );
1176 
1177 
1178 /** Retrieve the number of frames that can be read from the stream without
1179  waiting.
1180 
1181  @return Returns a non-negative value representing the maximum number of frames
1182  that can be read from the stream without blocking or busy waiting or, a
1183  PaErrorCode (which are always negative) if PortAudio is not initialized or an
1184  error is encountered.
1185 */
1186 signed long Pa_GetStreamReadAvailable( PaStream* stream );
1187 
1188 
1189 /** Retrieve the number of frames that can be written to the stream without
1190  waiting.
1191 
1192  @return Returns a non-negative value representing the maximum number of frames
1193  that can be written to the stream without blocking or busy waiting or, a
1194  PaErrorCode (which are always negative) if PortAudio is not initialized or an
1195  error is encountered.
1196 */
1197 signed long Pa_GetStreamWriteAvailable( PaStream* stream );
1198 
1199 
1200 /* Miscellaneous utilities */
1201 
1202 
1203 /** Retrieve the size of a given sample format in bytes.
1204 
1205  @return The size in bytes of a single sample in the specified format,
1206  or paSampleFormatNotSupported if the format is not supported.
1207 */
1208 PaError Pa_GetSampleSize( PaSampleFormat format );
1209 
1210 
1211 /** Put the caller to sleep for at least 'msec' milliseconds. This function is
1212  provided only as a convenience for authors of portable code (such as the tests
1213  and examples in the PortAudio distribution.)
1214 
1215  The function may sleep longer than requested so don't rely on this for accurate
1216  musical timing.
1217 */
1218 void Pa_Sleep( long msec );
1219 
1220 
1221 
1222 #ifdef __cplusplus
1223 }
1224 #endif /* __cplusplus */
1225 #endif /* PORTAUDIO_H */
1226