2
audio_portaudio.c: audio output via PortAudio cross-platform audio API
4
copyright 2006 by the mpg123 project - free software under the terms of the LGPL 2.1
5
see COPYING and AUTHORS files in distribution or http://mpg123.de
6
initially written by Nicholas J. Humfrey
22
#define SAMPLE_SIZE (2)
23
#define FRAMES_PER_BUFFER (256)
24
#define FIFO_DURATION (0.5f)
26
static int sdl_initialised=0;
31
/* The audio function callback takes the following parameters:
32
stream: A pointer to the audio buffer to be filled
33
len: The length (in bytes) of the audio buffer
36
audio_callback_sdl(void *udata, Uint8 *stream, int len)
38
/* struct audio_info_struct *ai = udata; */
41
/* Only play if we have data left */
42
if ( sfifo_used( &fifo ) < len ) {
43
warning("Didn't have any audio data for SDL (buffer underflow)");
48
/* Read audio from FIFO to SDL's buffer */
49
read = sfifo_read( &fifo, stream, len );
52
warning2("Error reading from the FIFO (wanted=%u, read=%u).\n", len, read);
57
int audio_open(struct audio_info_struct *ai)
61
if (!sdl_initialised) {
62
if (SDL_Init( SDL_INIT_AUDIO ) ) {
63
error1("Failed to initialise SDL: %s\n", SDL_GetError());
71
/* Open an audio I/O stream. */
72
if (ai->rate > 0 && ai->channels >0 ) {
74
size_t ringbuffer_len;
76
/* L16 uncompressed audio data, using 16-bit signed representation in twos
77
complement notation - system endian-ness. */
78
wanted.format = AUDIO_S16SYS;
79
wanted.samples = 1024; /* Good low-latency value for callback */
80
wanted.callback = audio_callback_sdl;
82
wanted.channels = ai->channels;
83
wanted.freq = ai->rate;
85
/* Open the audio device, forcing the desired format */
86
if ( SDL_OpenAudio(&wanted, NULL) ) {
87
error1("Couldn't open SDL audio: %s\n", SDL_GetError());
92
ringbuffer_len = ai->rate * FIFO_DURATION * SAMPLE_SIZE *ai->channels;
93
debug2( "Allocating %d byte ring-buffer (%f seconds)", ringbuffer_len, (float)FIFO_DURATION);
94
sfifo_init( &fifo, ringbuffer_len );
102
int audio_get_formats(struct audio_info_struct *ai)
104
/* Only implemented Signed 16-bit audio for now */
105
return AUDIO_FORMAT_SIGNED_16;
109
int audio_play_samples(struct audio_info_struct *ai, unsigned char *buf, int len)
112
/* Sleep for half the length of the FIFO */
113
while (sfifo_space( &fifo ) < len ) {
114
usleep( (FIFO_DURATION/2) * 1000000 );
117
/* Bung decoded audio into the FIFO
118
SDL Audio locking probably isn't actually needed
119
as SFIFO claims to be thread safe...
122
sfifo_write( &fifo, buf, len);
126
/* Unpause once the buffer is 50% full */
127
if (sfifo_used(&fifo) > (sfifo_size(&fifo)*0.5) ) SDL_PauseAudio(0);
132
int audio_close(struct audio_info_struct *ai)
136
sfifo_close( &fifo );
141
void audio_queueflush(struct audio_info_struct *ai)
145
sfifo_flush( &fifo );