Debian Codegraph @

addons/audio/alsa.c

raw
1 /* ______ ___ ___
2 * /\ _ \ /\_ \ /\_ \
3 * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
4 * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
5 * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
6 * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
7 * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
8 * /\____/
9 * \_/__/
10 *
11 * ALSA 1.0 sound driver.
12 *
13 * By Thomas Fjellstrom.
14 *
15 * Extensively modified by Elias Pschernig.
16 *
17 * Rewritten for 4.3 sound API by Milan Mimica, with additional
18 * improvements by Chris Robinson. Updated for 4.9 by Ryan Dickie
19 *
20 * See readme.txt for copyright information.
21 */
22
23 #include "allegro5/allegro.h"
24 #include "allegro5/internal/aintern_audio.h"
25
26 #include <alloca.h>
27 #include <alsa/asoundlib.h>
28
29 ALLEGRO_DEBUG_CHANNEL("alsa")
30
31 #define ALSA_CHECK(a) \
32 do { \
33 int err = (a); \
34 if (err < 0) { \
35 ALLEGRO_ERROR("%s: %s\n", snd_strerror(err), #a); \
36 goto Error; \
37 } \
38 } while(0)
39
40
41 static snd_output_t *snd_output = NULL;
42 static char *default_device = "default";
43 static char *alsa_device = NULL;
44 static _AL_LIST* output_device_list;
45
46 // TODO: Setting this to 256 causes (extreme, about than 10 seconds)
47 // lag if the alsa device is really pulseaudio.
48 //
49 // pw: But there are calls later which expect this variable to be set an on
50 // my machine (without PulseAudio) the driver doesn't work properly with
51 // anything lower than 32.
52 #define DEFAULT_PERIOD_SIZE 32
53 #define MIN_PERIOD_SIZE 1
54
55 // This value works well on my RPI3 and Linux machine.
56 #define DEFAULT_BUFFER_SIZE 2048
57
58 static unsigned int get_period_size(void)
59 {
60 const char *val = al_get_config_value(al_get_system_config(),
61 "alsa", "buffer_size");
62 if (val && val[0] != '\0') {
63 int n = atoi(val);
64 if (n < MIN_PERIOD_SIZE)
65 n = MIN_PERIOD_SIZE;
66 return n;
67 }
68
69 return DEFAULT_PERIOD_SIZE;
70 }
71
72 static snd_pcm_uframes_t get_buffer_size(void)
73 {
74 const char *val = al_get_config_value(al_get_system_config(),
75 "alsa", "buffer_size2");
76 if (val && val[0] != '\0') {
77 int n = atoi(val);
78 if (n < 1)
79 n = 1;
80 return n;
81 }
82
83 return DEFAULT_BUFFER_SIZE;
84 }
85
86 typedef struct ALSA_VOICE {
87 unsigned int frame_size; /* in bytes */
88 unsigned int len; /* in frames */
89 snd_pcm_uframes_t frag_len; /* in frames */
90 bool reversed; /* true if playing reversed ATM. */
91
92 volatile bool stop;
93 volatile bool stopped;
94
95 struct pollfd *ufds;
96 int ufds_count;
97
98 ALLEGRO_THREAD *poll_thread;
99
100 snd_pcm_t *pcm_handle;
101 bool mmapped;
102 } ALSA_VOICE;
103
104
105
106 /* initialized output */
107 static int alsa_open(void)
108 {
109 alsa_device = default_device;
110
111 const char *config_device;
112 config_device = al_get_config_value(al_get_system_config(), "alsa", "device");
113 if (config_device && config_device[0] != '\0')
114 alsa_device = strdup(config_device);
115
116 ALSA_CHECK(snd_output_stdio_attach(&snd_output, stdout, 0));
117
118 /* We need to check if alsa is available in this function. */
119 snd_pcm_t *test_pcm_handle;
120 int alsa_err = snd_pcm_open(&test_pcm_handle, alsa_device,
121 SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
122 if (alsa_err < 0) {
123 ALLEGRO_WARN("ALSA is not available on the system.\n");
124 return 1;
125 }
126 else {
127 snd_pcm_close(test_pcm_handle);
128 }
129
130 return 0;
131
132 /* ALSA check is a macro that 'goto' error*/
133 Error:
134 ALLEGRO_ERROR("Error initializing alsa!\n");
135 return 1;
136 }
137
138
139
140 /* The close method should close the device, freeing any resources, and allow
141 other processes to use the device */
142 static void alsa_close(void)
143 {
144 _al_list_destroy(output_device_list);
145
146 if (alsa_device != default_device)
147 al_free(alsa_device);
148
149 alsa_device = NULL;
150
151 snd_output_close(snd_output);
152 snd_config_update_free_global();
153 }
154
155
156 /* Underrun and suspend recovery */
157 static int xrun_recovery(snd_pcm_t *handle, int err)
158 {
159 if (err == -EPIPE) { /* under-run */
160 err = snd_pcm_prepare(handle);
161 if (err < 0) {
162 ALLEGRO_ERROR("Can't recover from underrun, prepare failed: %s\n", snd_strerror(err));
163 }
164 else {
165 ALLEGRO_DEBUG("Recovered from underrun\n");
166 }
167 return 0;
168 }
169 else if (err == -ESTRPIPE) { /* suspend */
170 err = snd_pcm_resume(handle);
171 if (err < 0) {
172 ALLEGRO_ERROR("Can't recover from suspend, resume failed: %s\n", snd_strerror(err));
173 }
174 else {
175 ALLEGRO_DEBUG("Resumed successfully\n");
176 }
177 return 0;
178 }
179 else {
180 ALLEGRO_ERROR("Unknown error code: %d\n", err);
181 ASSERT(0);
182 }
183
184 return err;
185 }
186
187
188 /*
189 * Updates the supplied non-streaming voice.
190 * buf - Returns a pointer to the buffer containing sample data.
191 * bytes - The requested size of the sample data buffer. Returns the actual
192 * size of returned the buffer.
193 * Updates 'stop', 'pos' and 'reversed' fields of the supplied voice to the
194 * future position.
195 * If the voice is played backwards, 'buf' will point to the end of the buffer
196 * and 'bytes' is the size that can be read towards the beginning.
197 */
198 static int alsa_update_nonstream_voice(ALLEGRO_VOICE *voice, void **buf, int *bytes)
199 {
200 ALSA_VOICE *alsa_voice = (ALSA_VOICE*)voice->extra;
201 int bpos = voice->attached_stream->pos * alsa_voice->frame_size;
202 int blen = alsa_voice->len * alsa_voice->frame_size;
203
204 *buf = (char *)voice->attached_stream->spl_data.buffer.ptr + bpos;
205
206 if (!alsa_voice->reversed) {
207 if (bpos + *bytes > blen) {
208 *bytes = blen - bpos;
209 if (voice->attached_stream->loop == ALLEGRO_PLAYMODE_ONCE) {
210 alsa_voice->stop = true;
211 voice->attached_stream->pos = 0;
212 }
213 if (voice->attached_stream->loop == ALLEGRO_PLAYMODE_LOOP) {
214 voice->attached_stream->pos = 0;
215 }
216 else if (voice->attached_stream->loop == ALLEGRO_PLAYMODE_BIDIR) {
217 alsa_voice->reversed = true;
218 voice->attached_stream->pos = alsa_voice->len;
219 }
220 return 1;
221 }
222 else
223 voice->attached_stream->pos += *bytes / alsa_voice->frame_size;
224 }
225 else {
226 if (bpos - *bytes < 0) {
227 *bytes = bpos;
228 /* loop will be ALLEGRO_PLAYMODE_BIDIR, other playing modes that play
229 backwards are not currently supported by the API */
230 /*if (voice->attached_stream->loop != ALLEGRO_PLAYMODE_BIDIR)
231 alsa_voice->stop = true;*/
232
233 voice->attached_stream->pos = 0;
234 alsa_voice->reversed = false;
235 return 1;
236 }
237 else
238 voice->attached_stream->pos -= *bytes / alsa_voice->frame_size;
239 }
240
241 return 0;
242 }
243
244
245 /* Returns true if the voice is ready for more data. */
246 static int alsa_voice_is_ready(ALSA_VOICE *alsa_voice)
247 {
248 unsigned short revents;
249 int err;
250
251 poll(alsa_voice->ufds, alsa_voice->ufds_count, 0);
252 snd_pcm_poll_descriptors_revents(alsa_voice->pcm_handle, alsa_voice->ufds,
253 alsa_voice->ufds_count, &revents);
254
255 if (revents & POLLERR) {
256 if (snd_pcm_state(alsa_voice->pcm_handle) == SND_PCM_STATE_XRUN ||
257 snd_pcm_state(alsa_voice->pcm_handle) == SND_PCM_STATE_SUSPENDED) {
258
259 if (snd_pcm_state(alsa_voice->pcm_handle) == SND_PCM_STATE_XRUN)
260 err = -EPIPE;
261 else
262 err = -ESTRPIPE;
263
264 if (xrun_recovery(alsa_voice->pcm_handle, err) < 0) {
265 ALLEGRO_ERROR("Write error: %s\n", snd_strerror(err));
266 return -POLLERR;
267 }
268 } else {
269 ALLEGRO_ERROR("Wait for poll failed\n");
270 return -POLLERR;
271 }
272 }
273
274 if (revents & POLLOUT)
275 return true;
276
277 return false;
278 }
279
280
281 /* Custom routine which runs in another thread and fills the hardware PCM buffer
282 from the voice buffer. */
283 static void *alsa_update_mmap(ALLEGRO_THREAD *self, void *arg)
284 {
285 ALLEGRO_VOICE *voice = (ALLEGRO_VOICE*)arg;
286 ALSA_VOICE *alsa_voice = (ALSA_VOICE*)voice->extra;
287 snd_pcm_state_t last_state = -1;
288 snd_pcm_state_t state;
289 snd_pcm_uframes_t frames;
290 const snd_pcm_channel_area_t *areas;
291 snd_pcm_uframes_t offset;
292 char *mmap;
293 snd_pcm_sframes_t commitres;
294 int ret;
295
296 ALLEGRO_INFO("ALSA update_mmap thread started\n");
297
298 while (!al_get_thread_should_stop(self)) {
299 if (alsa_voice->stop && !alsa_voice->stopped) {
300 snd_pcm_drop(alsa_voice->pcm_handle);
301 al_lock_mutex(voice->mutex);
302 alsa_voice->stopped = true;
303 al_signal_cond(voice->cond);
304 al_unlock_mutex(voice->mutex);
305 }
306
307 if (!alsa_voice->stop && alsa_voice->stopped) {
308 alsa_voice->stopped = false;
309 }
310
311 if (alsa_voice->stopped) {
312 /* Keep waiting while the voice is supposed to be stopped but present.
313 */
314 al_lock_mutex(voice->mutex);
315 while (alsa_voice->stop && !al_get_thread_should_stop(self)) {
316 al_wait_cond(voice->cond, voice->mutex);
317 }
318 al_unlock_mutex(voice->mutex);
319 continue;
320 }
321
322 state = snd_pcm_state(alsa_voice->pcm_handle);
323 if (state != last_state) {
324 ALLEGRO_DEBUG("state changed to: %s\n", snd_pcm_state_name(state));
325 last_state = state;
326 }
327 if (state == SND_PCM_STATE_SETUP) {
328 int rc = snd_pcm_prepare(alsa_voice->pcm_handle);
329 ALLEGRO_DEBUG("snd_pcm_prepare returned: %d\n", rc);
330 continue;
331 }
332 if (state == SND_PCM_STATE_PREPARED) {
333 int rc = snd_pcm_start(alsa_voice->pcm_handle);
334 ALLEGRO_DEBUG("snd_pcm_start returned: %d\n", rc);
335 }
336
337 ret = alsa_voice_is_ready(alsa_voice);
338 if (ret < 0)
339 break;
340 if (ret == 0) {
341 al_rest(0.005); /* TODO: Why not use an event or condition variable? */
342 continue;
343 }
344
345 snd_pcm_avail_update(alsa_voice->pcm_handle);
346 frames = alsa_voice->frag_len;
347 ret = snd_pcm_mmap_begin(alsa_voice->pcm_handle, &areas, &offset, &frames);
348 if (ret < 0) {
349 if ((ret = xrun_recovery(alsa_voice->pcm_handle, ret)) < 0) {
350 ALLEGRO_ERROR("MMAP begin avail error: %s\n", snd_strerror(ret));
351 }
352 break;
353 }
354
355 if (frames == 0) {
356 al_rest(0.005); /* TODO: Why not use an event or condition variable? */
357 goto commit;
358 }
359
360 /* mmaped driver's memory. Interleaved channels format. */
361 mmap = (char *) areas[0].addr
362 + areas[0].first / 8
363 + offset * areas[0].step / 8;
364
365 /* Read sample data into the buffer. */
366 if (!voice->is_streaming && !alsa_voice->stopped) {
367 void *buf;
368 bool reverse = alsa_voice->reversed;
369 int bytes = frames * alsa_voice->frame_size;
370
371 alsa_update_nonstream_voice(voice, &buf, &bytes);
372 frames = bytes / alsa_voice->frame_size;
373 if (!reverse) {
374 memcpy(mmap, buf, bytes);
375 }
376 else {
377 /* Put a reversed copy in the driver's buffer. */
378 unsigned int i;
379 int fs = alsa_voice->frame_size;
380 for (i = 1; i <= frames; i++)
381 memcpy(mmap + i * fs, (char *) buf - i * fs, fs);
382 }
383 }
384 else if (voice->is_streaming && !alsa_voice->stopped) {
385 /* This should fit. */
386 unsigned int iframes = frames;
387 const void *data = _al_voice_update(voice, voice->mutex, &iframes);
388 frames = iframes;
389 if (data == NULL)
390 goto silence;
391 memcpy(mmap, data, frames * alsa_voice->frame_size);
392 }
393 else {
394 silence:
395 /* If stopped just fill with silence. */
396 al_fill_silence(mmap, frames, voice->depth, voice->chan_conf);
397 }
398
399 commit:
400 commitres = snd_pcm_mmap_commit(alsa_voice->pcm_handle, offset, frames);
401 if (commitres < 0 || (snd_pcm_uframes_t)commitres != frames) {
402 if ((ret = xrun_recovery(alsa_voice->pcm_handle, commitres >= 0 ? -EPIPE : commitres)) < 0) {
403 ALLEGRO_ERROR("MMAP commit error: %s\n", snd_strerror(ret));
404 break;
405 }
406 }
407 }
408
409 ALLEGRO_INFO("ALSA update_mmap thread stopped\n");
410
411 return NULL;
412 }
413
414
415 static void *alsa_update_rw(ALLEGRO_THREAD *self, void *arg)
416 {
417 ALLEGRO_VOICE *voice = (ALLEGRO_VOICE*)arg;
418 ALSA_VOICE *alsa_voice = (ALSA_VOICE*)voice->extra;
419 snd_pcm_state_t last_state = -1;
420 snd_pcm_state_t state;
421 snd_pcm_uframes_t frames;
422 snd_pcm_sframes_t err;
423
424 ALLEGRO_INFO("ALSA update_rw thread started\n");
425
426 while (!al_get_thread_should_stop(self)) {
427 if (alsa_voice->stop && !alsa_voice->stopped) {
428 snd_pcm_drop(alsa_voice->pcm_handle);
429 al_lock_mutex(voice->mutex);
430 alsa_voice->stopped = true;
431 al_signal_cond(voice->cond);
432 al_unlock_mutex(voice->mutex);
433 }
434
435 if (!alsa_voice->stop && alsa_voice->stopped) {
436 alsa_voice->stopped = false;
437 }
438
439 if (alsa_voice->stopped) {
440 /* Keep waiting while the voice is supposed to be stopped but present.
441 */
442 al_lock_mutex(voice->mutex);
443 while (alsa_voice->stop && !al_get_thread_should_stop(self)) {
444 al_wait_cond(voice->cond, voice->mutex);
445 }
446 al_unlock_mutex(voice->mutex);
447 continue;
448 }
449
450 state = snd_pcm_state(alsa_voice->pcm_handle);
451 if (state != last_state) {
452 ALLEGRO_DEBUG("state changed to: %s\n", snd_pcm_state_name(state));
453 last_state = state;
454 }
455 if (state == SND_PCM_STATE_SETUP) {
456 int rc = snd_pcm_prepare(alsa_voice->pcm_handle);
457 ALLEGRO_DEBUG("snd_pcm_prepare returned: %d\n", rc);
458 continue;
459 }
460 if (state == SND_PCM_STATE_PREPARED) {
461 int rc = snd_pcm_start(alsa_voice->pcm_handle);
462 ALLEGRO_DEBUG("snd_pcm_start returned: %d\n", rc);
463 }
464
465 snd_pcm_wait(alsa_voice->pcm_handle, 10);
466 err = snd_pcm_avail_update(alsa_voice->pcm_handle);
467 if (err < 0) {
468 if (err == -EPIPE) {
469 snd_pcm_prepare(alsa_voice->pcm_handle);
470 }
471 else {
472 ALLEGRO_WARN("Alsa r/w thread exited "
473 "with error code %s.\n", snd_strerror(-err));
474 break;
475 }
476 }
477 if (err == 0) {
478 continue;
479 }
480 frames = err;
481 if (frames > alsa_voice->frag_len)
482 frames = alsa_voice->frag_len;
483 /* Write sample data into the buffer. */
484 int bytes = frames * alsa_voice->frame_size;
485 uint8_t data[bytes];
486 void *buf;
487 if (!voice->is_streaming && !alsa_voice->stopped) {
488 ASSERT(!alsa_voice->reversed); // FIXME
489 alsa_update_nonstream_voice(voice, &buf, &bytes);
490 frames = bytes / alsa_voice->frame_size;
491 }
492 else if (voice->is_streaming && !alsa_voice->stopped) {
493 /* This should fit. */
494 unsigned int iframes = frames;
495 buf = (void *)_al_voice_update(voice, voice->mutex, &iframes);
496 if (buf == NULL)
497 goto silence;
498 frames = iframes;
499 }
500 else {
501 silence:
502 /* If stopped just fill with silence. */
503 al_fill_silence(data, frames, voice->depth, voice->chan_conf);
504 buf = data;
505 }
506 err = snd_pcm_writei(alsa_voice->pcm_handle, buf, frames);
507 if (err < 0) {
508 if (err == -EPIPE) {
509 snd_pcm_prepare(alsa_voice->pcm_handle);
510 }
511 }
512 }
513
514 ALLEGRO_INFO("ALSA update_rw thread stopped\n");
515
516 return NULL;
517 }
518
519
520 /* The load_voice method loads a sample into the driver's memory. The voice's
521 'streaming' field will be set to false for these voices, and it's
522 'buffer_size' field will be the total length in bytes of the sample data.
523 The voice's attached stream's looping mode should be honored, and loading
524 must fail if it cannot be. */
525 static int alsa_load_voice(ALLEGRO_VOICE *voice, const void *data)
526 {
527 ALSA_VOICE *ex_data = voice->extra;
528
529 voice->attached_stream->pos = 0;
530 ex_data->len = voice->attached_stream->spl_data.len;
531
532 return 0;
533 (void)data;
534 }
535
536
537
538 /* The unload_voice method unloads a sample previously loaded with load_voice.
539 This method should not be called on a streaming voice. */
540 static void alsa_unload_voice(ALLEGRO_VOICE *voice)
541 {
542 (void)voice;
543 }
544
545
546
547 /* The start_voice should, surprise, start the voice. For streaming voices, it
548 should start polling the device and call _al_voice_update for audio data.
549 For non-streaming voices, it should resume playing from the last set
550 position */
551 static int alsa_start_voice(ALLEGRO_VOICE *voice)
552 {
553 ALSA_VOICE *ex_data = voice->extra;
554
555 /* We already hold voice->mutex. */
556 ex_data->stop = false;
557 al_signal_cond(voice->cond);
558
559 return 0;
560 }
561
562
563
564 /* The stop_voice method should stop playback. For non-streaming voices, it
565 should leave the data loaded, and reset the voice position to 0. */
566 static int alsa_stop_voice(ALLEGRO_VOICE *voice)
567 {
568 ALSA_VOICE *ex_data = voice->extra;
569
570 /* We already hold voice->mutex. */
571 ex_data->stop = true;
572 al_signal_cond(voice->cond);
573
574 if (!voice->is_streaming) {
575 voice->attached_stream->pos = 0;
576 }
577
578 while (!ex_data->stopped) {
579 al_wait_cond(voice->cond, voice->mutex);
580 }
581
582 return 0;
583 }
584
585
586
587 /* The voice_is_playing method should only be called on non-streaming sources,
588 and should return true if the voice is playing */
589 static bool alsa_voice_is_playing(const ALLEGRO_VOICE *voice)
590 {
591 ALSA_VOICE *ex_data = voice->extra;
592 return !ex_data->stopped;
593 }
594
595
596 /* The allocate_voice method should grab a voice from the system, and allocate
597 any data common to streaming and non-streaming sources. */
598 static int alsa_allocate_voice(ALLEGRO_VOICE *voice)
599 {
600 snd_pcm_format_t format;
601 int chan_count;
602 unsigned int req_freq;
603
604 ALSA_VOICE *ex_data = al_calloc(1, sizeof(ALSA_VOICE));
605 if (!ex_data)
606 return 1;
607
608 chan_count = al_get_channel_count(voice->chan_conf);
609 ex_data->frame_size = chan_count * al_get_audio_depth_size(voice->depth);
610 if (!ex_data->frame_size)
611 goto Error;
612
613 ex_data->stop = true;
614 ex_data->stopped = true;
615 ex_data->reversed = false;
616
617 ex_data->frag_len = get_period_size();
618
619 if (voice->depth == ALLEGRO_AUDIO_DEPTH_INT8)
620 format = SND_PCM_FORMAT_S8;
621 else if (voice->depth == ALLEGRO_AUDIO_DEPTH_UINT8)
622 format = SND_PCM_FORMAT_U8;
623 else if (voice->depth == ALLEGRO_AUDIO_DEPTH_INT16)
624 format = SND_PCM_FORMAT_S16;
625 else if (voice->depth == ALLEGRO_AUDIO_DEPTH_UINT16)
626 format = SND_PCM_FORMAT_U16;
627 else if (voice->depth == ALLEGRO_AUDIO_DEPTH_INT24)
628 format = SND_PCM_FORMAT_S24;
629 else if (voice->depth == ALLEGRO_AUDIO_DEPTH_UINT24)
630 format = SND_PCM_FORMAT_U24;
631 else if (voice->depth == ALLEGRO_AUDIO_DEPTH_FLOAT32)
632 format = SND_PCM_FORMAT_FLOAT;
633 else
634 goto Error;
635
636 /* Why is this? And what is this? */
637 if (voice->chan_conf == ALLEGRO_CHANNEL_CONF_3)
638 goto Error;
639
640 req_freq = voice->frequency;
641
642 ALSA_CHECK(snd_pcm_open(&ex_data->pcm_handle, alsa_device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK));
643
644 snd_pcm_hw_params_t *hwparams;
645 snd_pcm_hw_params_alloca(&hwparams);
646
647 ALSA_CHECK(snd_pcm_hw_params_any(ex_data->pcm_handle, hwparams));
648 if (snd_pcm_hw_params_set_access(ex_data->pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED) == 0) {
649 ex_data->mmapped = true;
650 }
651 else {
652 ALSA_CHECK(snd_pcm_hw_params_set_access(ex_data->pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED));
653 ex_data->mmapped = false;
654 }
655 ALSA_CHECK(snd_pcm_hw_params_set_format(ex_data->pcm_handle, hwparams, format));
656 ALSA_CHECK(snd_pcm_hw_params_set_channels(ex_data->pcm_handle, hwparams, chan_count));
657 ALSA_CHECK(snd_pcm_hw_params_set_rate_near(ex_data->pcm_handle, hwparams, &req_freq, NULL));
658 ALSA_CHECK(snd_pcm_hw_params_set_period_size_near(ex_data->pcm_handle, hwparams, &ex_data->frag_len, NULL));
659 snd_pcm_uframes_t buffer_size = get_buffer_size();
660 ALSA_CHECK(snd_pcm_hw_params_set_buffer_size_near(ex_data->pcm_handle, hwparams, &buffer_size));
661 ALSA_CHECK(snd_pcm_hw_params(ex_data->pcm_handle, hwparams));
662
663 if (voice->frequency != req_freq) {
664 ALLEGRO_ERROR("Unsupported rate! Requested %u, got %iu.\n", voice->frequency, req_freq);
665 goto Error;
666 }
667
668 snd_pcm_sw_params_t *swparams;
669 snd_pcm_sw_params_alloca(&swparams);
670
671 ALSA_CHECK(snd_pcm_sw_params_current(ex_data->pcm_handle, swparams));
672 ALSA_CHECK(snd_pcm_sw_params_set_start_threshold(ex_data->pcm_handle, swparams, ex_data->frag_len));
673 ALSA_CHECK(snd_pcm_sw_params_set_avail_min(ex_data->pcm_handle, swparams, ex_data->frag_len));
674 ALSA_CHECK(snd_pcm_sw_params(ex_data->pcm_handle, swparams));
675
676 ex_data->ufds_count = snd_pcm_poll_descriptors_count(ex_data->pcm_handle);
677 ex_data->ufds = al_malloc(sizeof(struct pollfd) * ex_data->ufds_count);
678 ALSA_CHECK(snd_pcm_poll_descriptors(ex_data->pcm_handle, ex_data->ufds, ex_data->ufds_count));
679
680 voice->extra = ex_data;
681
682 if (ex_data->mmapped) {
683 ex_data->poll_thread = al_create_thread(alsa_update_mmap, (void*)voice);
684 }
685 else {
686 ALLEGRO_WARN("Falling back to non-mmapped transfer.\n");
687 snd_pcm_nonblock(ex_data->pcm_handle, 0);
688 ex_data->poll_thread = al_create_thread(alsa_update_rw, (void*)voice);
689 }
690 al_start_thread(ex_data->poll_thread);
691
692 return 0;
693
694 Error:
695 if (ex_data->pcm_handle)
696 snd_pcm_close(ex_data->pcm_handle);
697 al_free(ex_data);
698 voice->extra = NULL;
699 return 1;
700 }
701
702
703
704 /* The deallocate_voice method should free the resources for the given voice,
705 but still retain a hold on the device. The voice should be stopped and
706 unloaded by the time this is called */
707 static void alsa_deallocate_voice(ALLEGRO_VOICE *voice)
708 {
709 ALSA_VOICE *alsa_voice = (ALSA_VOICE*)voice->extra;
710
711 al_lock_mutex(voice->mutex);
712 al_set_thread_should_stop(alsa_voice->poll_thread);
713 al_broadcast_cond(voice->cond);
714 al_unlock_mutex(voice->mutex);
715 al_join_thread(alsa_voice->poll_thread, NULL);
716
717 snd_pcm_drop(alsa_voice->pcm_handle);
718 snd_pcm_close(alsa_voice->pcm_handle);
719
720 al_destroy_thread(alsa_voice->poll_thread);
721 al_free(alsa_voice->ufds);
722 al_free(voice->extra);
723 voice->extra = NULL;
724 }
725
726
727
728 /* The get_voice_position method should return the current sample position of
729 the voice (sample_pos = byte_pos / (depth/8) / channels). This should never
730 be called on a streaming voice. */
731 static unsigned int alsa_get_voice_position(const ALLEGRO_VOICE *voice)
732 {
733 return voice->attached_stream->pos;
734 }
735
736
737
738 /* The set_voice_position method should set the voice's playback position,
739 given the value in samples. This should never be called on a streaming
740 voice. */
741 static int alsa_set_voice_position(ALLEGRO_VOICE *voice, unsigned int val)
742 {
743 voice->attached_stream->pos = val;
744 return 0;
745 }
746
747 typedef struct ALSA_RECORDER_DATA
748 {
749 snd_pcm_t *capture_handle;
750 snd_pcm_hw_params_t *hw_params;
751 } ALSA_RECORDER_DATA;
752
753 static void *alsa_update_recorder(ALLEGRO_THREAD *t, void *thread_data)
754 {
755 ALLEGRO_AUDIO_RECORDER *r = thread_data;
756 ALSA_RECORDER_DATA *alsa = r->extra;
757 ALLEGRO_EVENT user_event;
758 uint8_t *null_buffer;
759 unsigned int fragment_i = 0;
760
761 null_buffer = al_malloc(1024 * r->sample_size);
762 if (!null_buffer) {
763 ALLEGRO_ERROR("Unable to create buffer for draining ALSA.\n");
764 return NULL;
765 }
766
767 while (!al_get_thread_should_stop(t))
768 {
769 al_lock_mutex(r->mutex);
770 if (!r->is_recording) {
771 /* Even if not recording, we still want to read from ALSA.
772 Otherwise it will buffer everything and spit it all out whenever
773 the recording resumes. (XXX: Just copied this from PulseAudio.
774 This current implementation is just a bare minimum effort...)
775 */
776 al_unlock_mutex(r->mutex);
777 snd_pcm_readi(alsa->capture_handle, null_buffer, 1024);
778 }
779 else {
780 ALLEGRO_AUDIO_RECORDER_EVENT *e;
781 snd_pcm_sframes_t count;
782 al_unlock_mutex(r->mutex);
783 if ((count = snd_pcm_readi(alsa->capture_handle, r->fragments[fragment_i], r->samples)) > 0) {
784 user_event.user.type = ALLEGRO_EVENT_AUDIO_RECORDER_FRAGMENT;
785 e = al_get_audio_recorder_event(&user_event);
786 e->buffer = r->fragments[fragment_i];
787 e->samples = count;
788 al_emit_user_event(&r->source, &user_event, NULL);
789
790 if (++fragment_i == r->fragment_count) {
791 fragment_i = 0;
792 }
793 }
794 }
795 }
796
797 al_free(null_buffer);
798 return NULL;
799 }
800
801 static int alsa_allocate_recorder(ALLEGRO_AUDIO_RECORDER *r)
802 {
803 ALSA_RECORDER_DATA *data;
804 unsigned int frequency = r->frequency;
805 snd_pcm_format_t format;
806 const char *device = default_device;
807 const char *config_device;
808 config_device =
809 al_get_config_value(al_get_system_config(), "alsa", "capture_device");
810 if (config_device && config_device[0] != '\0')
811 device = config_device;
812
813 data = al_calloc(1, sizeof(*data));
814
815 if (!data) {
816 goto Error;
817 }
818
819 if (r->depth == ALLEGRO_AUDIO_DEPTH_INT8)
820 format = SND_PCM_FORMAT_S8;
821 else if (r->depth == ALLEGRO_AUDIO_DEPTH_UINT8)
822 format = SND_PCM_FORMAT_U8;
823 else if (r->depth == ALLEGRO_AUDIO_DEPTH_INT16)
824 format = SND_PCM_FORMAT_S16;
825 else if (r->depth == ALLEGRO_AUDIO_DEPTH_UINT16)
826 format = SND_PCM_FORMAT_U16;
827 else if (r->depth == ALLEGRO_AUDIO_DEPTH_INT24)
828 format = SND_PCM_FORMAT_S24;
829 else if (r->depth == ALLEGRO_AUDIO_DEPTH_UINT24)
830 format = SND_PCM_FORMAT_U24;
831 else if (r->depth == ALLEGRO_AUDIO_DEPTH_FLOAT32)
832 format = SND_PCM_FORMAT_FLOAT;
833 else
834 goto Error;
835
836 ALSA_CHECK(snd_pcm_open(&data->capture_handle, device, SND_PCM_STREAM_CAPTURE, 0));
837 ALSA_CHECK(snd_pcm_hw_params_malloc(&data->hw_params));
838 ALSA_CHECK(snd_pcm_hw_params_any(data->capture_handle, data->hw_params));
839 ALSA_CHECK(snd_pcm_hw_params_set_access(data->capture_handle, data->hw_params, SND_PCM_ACCESS_RW_INTERLEAVED));
840 ALSA_CHECK(snd_pcm_hw_params_set_format(data->capture_handle, data->hw_params, format));
841 ALSA_CHECK(snd_pcm_hw_params_set_rate_near(data->capture_handle, data->hw_params, &frequency, 0));
842
843 if (frequency != r->frequency) {
844 ALLEGRO_ERROR("Unsupported rate! Requested %u, got %iu.\n", r->frequency, frequency);
845 goto Error;
846 }
847
848 ALSA_CHECK(snd_pcm_hw_params_set_channels(data->capture_handle, data->hw_params, al_get_channel_count(r->chan_conf)));
849 ALSA_CHECK(snd_pcm_hw_params(data->capture_handle, data->hw_params));
850
851 ALSA_CHECK(snd_pcm_prepare(data->capture_handle));
852
853 r->extra = data;
854 r->thread = al_create_thread(alsa_update_recorder, r);
855
856 return 0;
857
858 Error:
859
860 if (data) {
861 if (data->hw_params) {
862 snd_pcm_hw_params_free(data->hw_params);
863 }
864 if (data->capture_handle) {
865 snd_pcm_close(data->capture_handle);
866 }
867 al_free(data);
868 }
869
870 return 1;
871 }
872
873 static void alsa_deallocate_recorder(ALLEGRO_AUDIO_RECORDER *r)
874 {
875 ALSA_RECORDER_DATA *data = r->extra;
876
877 snd_pcm_hw_params_free(data->hw_params);
878 snd_pcm_close(data->capture_handle);
879 }
880
881 static void _output_device_list_dtor(void* value, void* userdata)
882 {
883 (void)userdata;
884
885 ALLEGRO_AUDIO_DEVICE* device = (ALLEGRO_AUDIO_DEVICE*)value;
886 al_free(device->name);
887 al_free(device->identifier);
888 al_free(device);
889 }
890
891 static _AL_LIST* alsa_get_output_devices(void)
892 {
893 int res;
894 if (!output_device_list) {
895 output_device_list = _al_list_create();
896
897 int rcard = -1;
898 while(snd_card_next(&rcard) == 0) {
899 if (rcard < 0) {
900 ALLEGRO_WARN("snd_card_next returned a bad card %d.\n", rcard);
901 /* Something is really messed up, so bail out. */
902 return output_device_list;
903 }
904
905 snd_ctl_t *handle;
906 char str[64];
907
908 snprintf(str, sizeof str, "hw:%i", rcard);
909 res = snd_ctl_open(&handle, str, 0);
910 if (res < 0) {
911 ALLEGRO_WARN("snd_ctl_open on '%s' failed with code %d.\n", str, res);
912 continue;
913 }
914
915 snd_ctl_card_info_t *card_info;
916 snd_ctl_card_info_alloca(&card_info);
917 res = snd_ctl_card_info(handle, card_info);
918 if (res < 0) {
919 ALLEGRO_WARN("snd_ctl_card_info on '%s' failed with code %d.\n", str, res);
920 continue;
921 }
922
923 const char* card_name = snd_ctl_card_info_get_name(card_info);
924
925 int dev_num = -1;
926
927 while(1) {
928 if (snd_ctl_pcm_next_device(handle, &dev_num) < 0) {
929 break;
930 }
931
932 if (dev_num < 0) {
933 ALLEGRO_WARN("Invalid device number for card %d.\n", rcard);
934 break;
935 }
936
937 void **hints;
938 res = snd_device_name_hint(dev_num, "pcm", &hints);
939 if (res < 0) {
940 ALLEGRO_WARN("snd_device_name_hint for card %d, device %d failed with error code %d\n",
941 rcard, dev_num, res);
942 continue;
943 }
944 char**n = (char**)hints;
945
946 char* identifier = 0;
947 char* name = 0;
948 while(*n != NULL)
949 {
950 identifier = snd_device_name_get_hint(*n, "NAME");
951 name = snd_device_name_get_hint(*n, "DESC");
952
953 char* ioid = snd_device_name_get_hint(*n, "IOID");
954 if (ioid == NULL || strcmp(ioid, "Output") == 0)
955 {
956 free(ioid);
957 break;
958 }
959 free(ioid);
960 n++;
961 }
962
963 if (!identifier || !name) {
964 snd_device_name_free_hint(hints);
965 free(identifier);
966 free(name);
967 ALLEGRO_WARN("Could not find identifier/name for card %d, device %d\n",
968 rcard, dev_num);
969 continue;
970 }
971
972 char* sep_at = strchr(name, '\n');
973 char* actual_name = sep_at ? sep_at + 1 : name;
974
975 /* Two string lengths + space + nul terminator. */
976 int len = strlen(actual_name) + strlen(card_name) + 1 + 1;
977 int identifier_len = strlen(identifier) + 1;
978
979 ALLEGRO_AUDIO_DEVICE* device = (ALLEGRO_AUDIO_DEVICE*)al_malloc(sizeof(ALLEGRO_AUDIO_DEVICE));
980 device->identifier = (char*)al_malloc(identifier_len);
981 device->name = (char*)al_malloc(len);
982
983 snprintf(device->name, len, "%s %s", card_name, actual_name);
984 strcpy(device->identifier, identifier);
985
986 snd_device_name_free_hint(hints);
987 free(identifier);
988 free(name);
989
990 _al_list_push_back_ex(output_device_list, device, _output_device_list_dtor);
991 }
992
993 snd_ctl_close(handle);
994 }
995 }
996
997 return output_device_list;
998 }
999
1000 ALLEGRO_AUDIO_DRIVER _al_kcm_alsa_driver =
1001 {
1002 "ALSA",
1003
1004 alsa_open,
1005 alsa_close,
1006
1007 alsa_allocate_voice,
1008 alsa_deallocate_voice,
1009
1010 alsa_load_voice,
1011 alsa_unload_voice,
1012
1013 alsa_start_voice,
1014 alsa_stop_voice,
1015
1016 alsa_voice_is_playing,
1017
1018 alsa_get_voice_position,
1019 alsa_set_voice_position,
1020
1021 alsa_allocate_recorder,
1022 alsa_deallocate_recorder,
1023
1024 alsa_get_output_devices
1025 };
1026
1027 /* vim: set sts=3 sw=3 et: */