4 * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "audiodevice.h"
23 #include "audioalsa.h"
24 #include "bcsignals.h"
27 #include "playbackconfig.h"
28 #include "preferences.h"
29 #include "recordconfig.h"
35 AudioALSA::AudioALSA(AudioDevice *device)
36 : AudioLowLevel(device)
43 timer_lock = new Mutex("AudioALSA::timer_lock");
49 AudioALSA::~AudioALSA()
56 static class alsa_leaks
59 // This is required in the top thread for Alsa to work
61 ArrayList<char*> *alsa_titles = new ArrayList<char*>;
62 alsa_titles->set_array_delete();
63 AudioALSA::list_devices(alsa_titles, 0, MODEPLAY);
64 alsa_titles->remove_all_objects();
67 ~alsa_leaks() { snd_config_update_free_global(); }
70 void AudioALSA::list_devices(ArrayList<char*> *names, ArrayList<char*> *pcm_names, int mode)
74 snd_ctl_card_info_t *info;
75 snd_pcm_info_t *pcminfo;
76 char string[BCTEXTLEN];
77 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
82 stream = SND_PCM_STREAM_CAPTURE;
85 stream = SND_PCM_STREAM_PLAYBACK;
90 snd_ctl_card_info_alloca(&info);
91 snd_pcm_info_alloca(&pcminfo);
94 #define DEFAULT_DEVICE "default"
96 names->append(cstrdup(DEFAULT_DEVICE));
98 pcm_names->append(cstrdup(DEFAULT_DEVICE));
100 while(snd_card_next(&card) >= 0) {
101 char name[BCTEXTLEN];
103 sprintf(name, "hw:%i", card);
105 if((err = snd_ctl_open(&handle, name, 0)) < 0) {
106 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
110 if((err = snd_ctl_card_info(handle, info)) < 0) {
111 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
112 snd_ctl_close(handle);
119 if(snd_ctl_pcm_next_device(handle, &dev) < 0)
120 printf("AudioALSA::list_devices: snd_ctl_pcm_next_device\n");
124 snd_pcm_info_set_device(pcminfo, dev);
125 snd_pcm_info_set_subdevice(pcminfo, 0);
126 snd_pcm_info_set_stream(pcminfo, stream);
128 if((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
130 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
135 sprintf(string, "plughw:%d,%d", card, dev);
136 // strcpy(string, "cards.pcm.front");
137 pcm_names->append(cstrdup(string));
140 sprintf(string, "%s #%d",
141 snd_ctl_card_info_get_name(info), dev);
142 names->append(cstrdup(string));
146 snd_ctl_close(handle);
150 // attempt to add pulseaudio "monitor" devices
151 // run: pactl list <sources>|<sinks>
152 // scan output for <Source/Sink> #n, Name: <device>
153 // build alsa device config and add to alsa snd_config
165 char line[BCTEXTLEN];
167 sprintf(line, "LANGUAGE=en_US.UTF-8 pactl list %ss", arg);
168 pactl = popen(line,"r");
172 char name[BCTEXTLEN], pa_name[BCTEXTLEN], device[BCTEXTLEN];
173 name[0] = pa_name[0] = device[0] = 0;
174 int arg_len = strlen(arg);
175 while( fgets(line, sizeof(line), pactl) ) {
176 if( !strncasecmp(line, arg, arg_len) ) {
177 char *sp = name, *id = pa_name;
178 for( char *cp=line; *cp && *cp!='\n'; *sp++=*cp++ )
179 *id++ = (*cp>='A' && *cp<='Z') ||
180 (*cp>='a' && *cp<='z') ||
181 (*cp>='0' && *cp<='9') ? *cp : '_';
184 names->append(cstrdup(name));
187 if( sscanf(line, " Name: %s", device) != 1 ) continue;
188 int len = strlen(pa_name);
190 pcm_names->append(cstrdup(pa_name));
191 char alsa_config[BCTEXTLEN];
192 len = snprintf(alsa_config, sizeof(alsa_config),
193 "pcm.!%s {\n type pulse\n device %s\n}\n"
194 "ctl.!%s {\n type pulse\n device %s\n}\n",
195 pa_name, device, pa_name, device);
196 FILE *fp = fmemopen(alsa_config,len,"r");
198 snd_input_stdio_attach(&inp, fp, 1);
199 snd_config_load(snd_config, inp);
200 name[0] = pa_name[0] = device[0] = 0;
201 snd_input_close(inp);
208 void AudioALSA::translate_name(char *output, char *input, int mode)
210 ArrayList<char*> titles;
211 titles.set_array_delete();
213 ArrayList<char*> pcm_titles;
214 pcm_titles.set_array_delete();
216 list_devices(&titles, &pcm_titles, mode);
218 sprintf(output, "default");
219 for(int i = 0; i < titles.total; i++)
221 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
222 if(!strcasecmp(titles.values[i], input))
224 strcpy(output, pcm_titles.values[i]);
229 titles.remove_all_objects();
230 pcm_titles.remove_all_objects();
233 snd_pcm_format_t AudioALSA::translate_format(int format)
237 case 8: return SND_PCM_FORMAT_S8;
238 case 16: return SND_PCM_FORMAT_S16_LE;
239 case 24: return SND_PCM_FORMAT_S24_LE;
240 case 32: return SND_PCM_FORMAT_S32_LE;
242 return SND_PCM_FORMAT_UNKNOWN;
245 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
246 int channels, int bits, int samplerate, int samples)
248 snd_pcm_hw_params_t *params;
249 snd_pcm_sw_params_t *swparams;
252 snd_pcm_hw_params_alloca(¶ms);
253 snd_pcm_sw_params_alloca(&swparams);
254 err = snd_pcm_hw_params_any(dsp, params);
257 fprintf(stderr, "AudioALSA::set_params: ");
258 fprintf(stderr, _("no PCM configurations available\n"));
262 err=snd_pcm_hw_params_set_access(dsp,
264 SND_PCM_ACCESS_RW_INTERLEAVED);
266 fprintf(stderr, "AudioALSA::set_params: ");
267 fprintf(stderr, _("failed to set up interleaved device access.\n"));
271 err=snd_pcm_hw_params_set_format(dsp,
273 translate_format(bits));
275 fprintf(stderr, "AudioALSA::set_params: ");
276 fprintf(stderr, _("failed to set output format.\n"));
280 err=snd_pcm_hw_params_set_channels(dsp,
284 fprintf(stderr, "AudioALSA::set_params: ");
285 fprintf(stderr, _("Configured ALSA device does not support %d channel operation.\n"),
290 err=snd_pcm_hw_params_set_rate_near(dsp,
292 (unsigned int*)&samplerate,
295 fprintf(stderr, "AudioALSA::set_params: ");
296 fprintf(stderr, _(" Configured ALSA device does not support %u Hz playback.\n"),
297 (unsigned int)samplerate);
301 // Buffers written must be equal to period_time
303 int period_time = (int)(1000000 * (double)samples / samplerate);
306 buffer_time = 10000000;
309 buffer_time = 2 * period_time;
313 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
314 snd_pcm_hw_params_set_buffer_time_near(dsp,
316 (unsigned int*)&buffer_time,
318 snd_pcm_hw_params_set_period_time_near(dsp,
320 (unsigned int*)&period_time,
322 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
323 err = snd_pcm_hw_params(dsp, params);
325 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
329 snd_pcm_uframes_t chunk_size = 1024;
330 snd_pcm_uframes_t buffer_size = 262144;
331 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
332 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
333 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
335 snd_pcm_sw_params_current(dsp, swparams);
336 //snd_pcm_uframes_t xfer_align = 1;
337 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
338 //unsigned int sleep_min = 0;
339 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
340 period_size = chunk_size;
341 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
342 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
343 if(snd_pcm_sw_params(dsp, swparams) < 0) {
344 /* we can continue staggering along even if this fails */
345 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
348 device->device_buffer = samples * bits / 8 * channels;
350 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
352 // snd_pcm_hw_params_free(params);
353 // snd_pcm_sw_params_free(swparams);
357 int AudioALSA::open_input()
359 char pcm_name[BCTEXTLEN];
360 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
364 device->in_channels = device->get_ichannels();
365 device->in_bits = device->in_config->alsa_in_bits;
367 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
368 //printf("AudioALSA::open_input %s\n", pcm_name);
370 err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
374 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
378 err = set_params(dsp_in, MODERECORD,
379 device->get_ichannels(),
380 device->in_config->alsa_in_bits,
381 device->in_samplerate,
384 fprintf(stderr, "AudioALSA::open_input: set_params failed. Aborting sampling.\n");
392 int AudioALSA::open_output()
394 char pcm_name[BCTEXTLEN];
395 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
396 int open_mode = SND_PCM_NONBLOCK;
399 device->out_channels = device->get_ochannels();
400 device->out_bits = device->out_config->alsa_out_bits;
402 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
403 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
404 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
406 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
411 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
415 err = set_params(dsp_out, MODEPLAY,
416 device->get_ochannels(),
417 device->out_config->alsa_out_bits,
418 device->out_samplerate,
419 device->out_samples);
421 fprintf(stderr, "AudioALSA::open_output: set_params failed. Aborting playback.\n");
430 int AudioALSA::stop_output()
432 //printf("AudioALSA::stop_output\n");
433 if(!device->out_config->interrupt_workaround)
436 snd_pcm_drop(get_output());
443 int AudioALSA::close_output()
445 //printf("AudioALSA::close_output\n");
446 if(device->w && dsp_out) {
448 snd_pcm_close(dsp_out);
454 int AudioALSA::close_input()
456 //printf("AudioALSA::close_input\n");
457 if(device->r && dsp_in) {
458 // snd_pcm_reset(dsp_in);
459 snd_pcm_drop(dsp_in);
460 snd_pcm_drain(dsp_in);
461 snd_pcm_close(dsp_in);
467 int AudioALSA::close_all()
469 //printf("AudioALSA::close_all\n");
480 int64_t AudioALSA::device_position()
482 timer_lock->lock("AudioALSA::device_position");
483 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
484 int64_t result = buffer_position - delay + delta;
485 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
486 // buffer_position, delta, delay, result);
487 timer_lock->unlock();
491 int AudioALSA::read_buffer(char *buffer, int size)
493 //printf("AudioALSA::read_buffer 1\n");
496 int frame_size = (device->in_bits / 8) * device->get_ichannels();
505 while(attempts < 1 && !done)
507 snd_pcm_uframes_t frames = size / frame_size;
508 result = snd_pcm_readi(get_input(), buffer, frames);
511 printf("AudioALSA::read_buffer overrun at sample %jd\n",
512 device->total_samples_read);
513 // snd_pcm_resume(get_input());
514 close_input(); open_input();
519 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
524 int AudioALSA::write_buffer(char *buffer, int size)
526 //printf("AudioALSA::write_buffer %d\n",size);
527 // Don't give up and drop the buffer on the first error.
530 int sample_size = (device->out_bits / 8) * device->get_ochannels();
531 int samples = size / sample_size;
532 //printf("AudioALSA::write_buffer %d\n",samples);
534 snd_pcm_sframes_t delay = 0;
536 // static FILE *debug_fd = 0;
539 // debug_fd = fopen("/tmp/debug.pcm", "w");
541 // fwrite(buffer, size, 1, debug_fd);
545 if(!get_output()) return 0;
546 if( buffer_position == 0 )
549 AudioThread *audio_out = device->audio_out;
550 while( count > 0 && attempts < 2 && !done ) {
551 if( device->playback_interrupted ) break;
552 // Buffers written must be equal to period_time
553 audio_out->Thread::enable_cancel();
554 int ret = snd_pcm_avail_update(get_output());
555 if( ret >= period_size ) {
556 if( ret > count ) ret = count;
558 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
559 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
560 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
561 ret = snd_pcm_writei(get_output(),buffer,ret);
562 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
564 else if( ret >= 0 || ret == -EAGAIN ) {
565 ret = snd_pcm_wait(get_output(),15);
566 if( ret > 0 ) ret = 0;
568 audio_out->Thread::disable_cancel();
569 if( device->playback_interrupted ) break;
570 if( ret == 0 ) continue;
573 samples_written += ret;
574 if( (count-=ret) > 0 ) {
575 buffer += ret * sample_size;
582 printf(_("AudioALSA::write_buffer err %d(%s) at sample %jd\n"),
583 ret, snd_strerror(ret), device->current_position());
585 // snd_pcm_resume(get_output());
586 snd_pcm_recover(get_output(), ret, 1);
587 // close_output(); open_output();
592 if( !interrupted && device->playback_interrupted )
595 //printf("AudioALSA::write_buffer interrupted\n");
601 timer_lock->lock("AudioALSA::write_buffer");
602 snd_pcm_delay(get_output(), &delay);
605 buffer_position += samples;
606 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
607 timer_lock->unlock();
612 //this delay seems to prevent a problem where the sound system outputs
613 //a lot of silence while waiting for the device drain to happen.
614 int AudioALSA::output_wait()
616 snd_pcm_sframes_t delay = 0;
617 snd_pcm_delay(get_output(), &delay);
618 if( delay <= 0 ) return 0;
619 int64_t udelay = 1e6 * delay / device->out_samplerate;
620 // don't allow more than 10 seconds
621 if( udelay > 10000000 ) udelay = 10000000;
622 while( udelay > 0 && !device->playback_interrupted ) {
623 int64_t usecs = udelay;
624 if( usecs > 100000 ) usecs = 100000;
628 if( device->playback_interrupted &&
629 !device->out_config->interrupt_workaround )
630 snd_pcm_drop(get_output());
634 int AudioALSA::flush_device()
636 //printf("AudioALSA::flush_device\n");
640 //this causes the output to stutter.
641 //snd_pcm_nonblock(get_output(), 0);
642 snd_pcm_drain(get_output());
643 //snd_pcm_nonblock(get_output(), 1);
648 int AudioALSA::interrupt_playback()
650 //printf("AudioALSA::interrupt_playback *********\n");
653 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
654 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
655 // if(!device->out_config->interrupt_workaround)
656 // snd_pcm_drop(get_output());
658 // Makes sure the current buffer finishes before stopping.
659 // snd_pcm_drain(get_output());
661 // The only way to ensure snd_pcm_writei exits, but
662 // got a lot of crashes when doing this.
663 // device->Thread::cancel();
669 snd_pcm_t* AudioALSA::get_output()
674 snd_pcm_t* AudioALSA::get_input()