PortAudio Implementation

Starting and Stopping Streams

PortAudio is generally executed in two "threads". The foreground thread is the application thread. The background "thread" may be implemented as an actual thread, an interrupt handler, or a callback from a timer thread.

There are three ways that PortAudio can stop a stream. In each case we look at the sequence of events and the messages sent between the two threads. The following variables are contained in the internalPortAudioStream.

int   past_IsActive;     /* Background is still playing. */
int   past_StopSoon;     /* Stop when last buffer done. */
int   past_StopNow;      /* Stop IMMEDIATELY. */

Pa_AbortStream()

This function causes the background thread to terminate as soon as possible and audio I/O to stop abruptly.
 
Foreground Thread Background Thread
sets StopNow
sees StopNow
clears IsActive, stops thread
waits for thread to exit
turns off audio I/O

Pa_StopStream()

This function stops the user callback function from being called and then waits for all audio data written to the output buffer to be played. In a system with very low latency, you may not hear any difference between
 
Foreground Thread Background Thread
sets StopSoon
stops calling user callback
continues until output buffer empty
clears IsActive, stops thread
waits for thread to exit
turns off audio I/O

User callback returns one.

If the user callback returns one then the user callback function will no longer be called. Audio output will continue until all audio data written to the output buffer has been played. Then the audio I/O is stopped, the background thread terminates, and the stream becomes inactive.
 
Foreground Thread Background Thread
callback returns 1
sets StopSoon
stops calling user callback
continues until output buffer empty
clears IsActive, stops thread
waits for thread to exit
turns off audio I/O