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"
26 #include "playbackconfig.h"
27 #include "preferences.h"
28 #include "recordconfig.h"
34 AudioALSA::AudioALSA(AudioDevice *device)
35 : AudioLowLevel(device)
42 timer_lock = new Mutex("AudioALSA::timer_lock");
48 AudioALSA::~AudioALSA()
55 static class alsa_leaks
58 // This is required in the top thread for Alsa to work
60 ArrayList<char*> *alsa_titles = new ArrayList<char*>;
61 alsa_titles->set_array_delete();
62 AudioALSA::list_devices(alsa_titles, 0, MODEPLAY);
63 alsa_titles->remove_all_objects();
66 ~alsa_leaks() { snd_config_update_free_global(); }
69 void AudioALSA::list_devices(ArrayList<char*> *devices, int pcm_title, int mode)
73 snd_ctl_card_info_t *info;
74 snd_pcm_info_t *pcminfo;
75 char string[BCTEXTLEN];
76 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
81 stream = SND_PCM_STREAM_CAPTURE;
84 stream = SND_PCM_STREAM_PLAYBACK;
89 snd_ctl_card_info_alloca(&info);
90 snd_pcm_info_alloca(&pcminfo);
93 #define DEFAULT_DEVICE "default"
94 char *result = new char[strlen(DEFAULT_DEVICE) + 1];
95 devices->append(result);
96 strcpy(result, DEFAULT_DEVICE);
98 while(snd_card_next(&card) >= 0)
100 char name[BCTEXTLEN];
102 sprintf(name, "hw:%i", card);
104 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)
112 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
113 snd_ctl_close(handle);
121 if(snd_ctl_pcm_next_device(handle, &dev) < 0)
122 printf("AudioALSA::list_devices: snd_ctl_pcm_next_device\n");
127 snd_pcm_info_set_device(pcminfo, dev);
128 snd_pcm_info_set_subdevice(pcminfo, 0);
129 snd_pcm_info_set_stream(pcminfo, stream);
131 if((err = snd_ctl_pcm_info(handle, pcminfo)) < 0)
134 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
140 sprintf(string, "plughw:%d,%d", card, dev);
141 // strcpy(string, "cards.pcm.front");
145 sprintf(string, "%s #%d",
146 snd_ctl_card_info_get_name(info),
150 char *result = devices->append(new char[strlen(string) + 1]);
151 strcpy(result, string);
156 snd_ctl_close(handle);
160 // attempt to add pulseaudio "monitor" devices
161 // run: pactl list <sources>|<sinks>
162 // scan output for <Source/Sink> #n, Name: <device>
163 // build alsa device config and add to alsa snd_config
175 char line[BCTEXTLEN];
177 sprintf(line, "pactl list %ss", arg);
178 pactl = popen(line,"r");
181 if( pcm_title ) snd_config_update();
182 char name[BCTEXTLEN], pa_name[BCTEXTLEN], device[BCTEXTLEN];
183 name[0] = pa_name[0] = device[0] = 0;
184 int arg_len = strlen(arg);
185 while( fgets(line, sizeof(line), pactl) ) {
186 if( !strncasecmp(line, arg, arg_len) ) {
187 char *sp = name, *id = pa_name;
188 for( char *cp=line; *cp && *cp!='\n'; *sp++=*cp++ )
189 *id++ = (*cp>='A' && *cp<='Z') ||
190 (*cp>='a' && *cp<='z') ||
191 (*cp>='0' && *cp<='9') ? *cp : '_';
194 devices->append(strcpy(new char[sp-name], name));
197 if( !pcm_title ) continue;
198 if( sscanf(line, " Name: %s", device) != 1 ) continue;
199 int len = strlen(pa_name);
200 devices->append(strcpy(new char[len+1], pa_name));
201 char alsa_config[BCTEXTLEN];
202 len = snprintf(alsa_config, sizeof(alsa_config),
203 "pcm.!%s {\n type pulse\n device %s\n}\n"
204 "ctl.!%s {\n type pulse\n device %s\n}\n",
205 pa_name, device, pa_name, device);
206 FILE *fp = fmemopen(alsa_config,len,"r");
208 snd_input_stdio_attach(&inp, fp, 1);
209 snd_config_load(snd_config, inp);
210 name[0] = pa_name[0] = device[0] = 0;
211 snd_input_close(inp);
218 void AudioALSA::translate_name(char *output, char *input, int mode)
220 ArrayList<char*> titles;
221 titles.set_array_delete();
223 ArrayList<char*> pcm_titles;
224 pcm_titles.set_array_delete();
226 list_devices(&titles, 0, mode);
227 list_devices(&pcm_titles, 1, mode);
229 sprintf(output, "default");
230 for(int i = 0; i < titles.total; i++)
232 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
233 if(!strcasecmp(titles.values[i], input))
235 strcpy(output, pcm_titles.values[i]);
240 titles.remove_all_objects();
241 pcm_titles.remove_all_objects();
244 snd_pcm_format_t AudioALSA::translate_format(int format)
249 return SND_PCM_FORMAT_S8;
252 return SND_PCM_FORMAT_S16_LE;
255 return SND_PCM_FORMAT_S24_LE;
258 return SND_PCM_FORMAT_S32_LE;
261 return SND_PCM_FORMAT_UNKNOWN;
264 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
265 int channels, int bits, int samplerate, int samples)
267 snd_pcm_hw_params_t *params;
268 snd_pcm_sw_params_t *swparams;
271 snd_pcm_hw_params_alloca(¶ms);
272 snd_pcm_sw_params_alloca(&swparams);
273 err = snd_pcm_hw_params_any(dsp, params);
276 fprintf(stderr, "AudioALSA::set_params: no PCM configurations available\n");
280 err=snd_pcm_hw_params_set_access(dsp,
282 SND_PCM_ACCESS_RW_INTERLEAVED);
284 fprintf(stderr, "AudioALSA::set_params: failed to set up "
285 "interleaved device access.\n");
289 err=snd_pcm_hw_params_set_format(dsp,
291 translate_format(bits));
293 fprintf(stderr, "AudioALSA::set_params: failed to set output format.\n");
297 err=snd_pcm_hw_params_set_channels(dsp,
301 fprintf(stderr, "AudioALSA::set_params: Configured ALSA device "
302 "does not support %d channel operation.\n",
307 err=snd_pcm_hw_params_set_rate_near(dsp,
309 (unsigned int*)&samplerate,
312 fprintf(stderr, "AudioALSA::set_params: Configured ALSA device "
313 "does not support %u Hz playback.\n",
314 (unsigned int)samplerate);
318 // Buffers written must be equal to period_time
320 int period_time = (int)(1000000 * (double)samples / samplerate);
323 buffer_time = 10000000;
326 buffer_time = 2 * period_time;
330 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
331 snd_pcm_hw_params_set_buffer_time_near(dsp,
333 (unsigned int*)&buffer_time,
335 snd_pcm_hw_params_set_period_time_near(dsp,
337 (unsigned int*)&period_time,
339 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
340 err = snd_pcm_hw_params(dsp, params);
342 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
346 snd_pcm_uframes_t chunk_size = 1024;
347 snd_pcm_uframes_t buffer_size = 262144;
348 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
349 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
350 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
352 snd_pcm_sw_params_current(dsp, swparams);
353 //snd_pcm_uframes_t xfer_align = 1;
354 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
355 //unsigned int sleep_min = 0;
356 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
357 period_size = chunk_size;
358 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
359 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
360 if(snd_pcm_sw_params(dsp, swparams) < 0) {
361 /* we can continue staggering along even if this fails */
362 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
365 device->device_buffer = samples * bits / 8 * channels;
367 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
369 // snd_pcm_hw_params_free(params);
370 // snd_pcm_sw_params_free(swparams);
374 int AudioALSA::open_input()
376 char pcm_name[BCTEXTLEN];
377 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
381 device->in_channels = device->get_ichannels();
382 device->in_bits = device->in_config->alsa_in_bits;
384 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
385 //printf("AudioALSA::open_input %s\n", pcm_name);
387 err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
391 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
395 err = set_params(dsp_in, MODERECORD,
396 device->get_ichannels(),
397 device->in_config->alsa_in_bits,
398 device->in_samplerate,
401 fprintf(stderr, "AudioALSA::open_input: set_params failed. Aborting sampling.\n");
409 int AudioALSA::open_output()
411 char pcm_name[BCTEXTLEN];
412 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
413 int open_mode = SND_PCM_NONBLOCK;
416 device->out_channels = device->get_ochannels();
417 device->out_bits = device->out_config->alsa_out_bits;
419 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
420 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
421 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
423 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
428 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
432 err = set_params(dsp_out, MODEPLAY,
433 device->get_ochannels(),
434 device->out_config->alsa_out_bits,
435 device->out_samplerate,
436 device->out_samples);
438 fprintf(stderr, "AudioALSA::open_output: set_params failed. Aborting playback.\n");
447 int AudioALSA::stop_output()
449 //printf("AudioALSA::stop_output\n");
450 if(!device->out_config->interrupt_workaround)
453 snd_pcm_drop(get_output());
460 int AudioALSA::close_output()
462 //printf("AudioALSA::close_output\n");
463 if(device->w && dsp_out) {
465 snd_pcm_close(dsp_out);
471 int AudioALSA::close_input()
473 //printf("AudioALSA::close_input\n");
474 if(device->r && dsp_in) {
475 // snd_pcm_reset(dsp_in);
476 snd_pcm_drop(dsp_in);
477 snd_pcm_drain(dsp_in);
478 snd_pcm_close(dsp_in);
484 int AudioALSA::close_all()
486 //printf("AudioALSA::close_all\n");
497 int64_t AudioALSA::device_position()
499 timer_lock->lock("AudioALSA::device_position");
500 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
501 int64_t result = buffer_position - delay + delta;
502 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
503 // buffer_position, delta, delay, result);
504 timer_lock->unlock();
508 int AudioALSA::read_buffer(char *buffer, int size)
510 //printf("AudioALSA::read_buffer 1\n");
513 int frame_size = (device->in_bits / 8) * device->get_ichannels();
522 while(attempts < 1 && !done)
524 snd_pcm_uframes_t frames = size / frame_size;
525 result = snd_pcm_readi(get_input(), buffer, frames);
528 printf("AudioALSA::read_buffer overrun at sample %jd\n",
529 device->total_samples_read);
530 // snd_pcm_resume(get_input());
531 close_input(); open_input();
536 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
541 int AudioALSA::write_buffer(char *buffer, int size)
543 //printf("AudioALSA::write_buffer %d\n",size);
544 // Don't give up and drop the buffer on the first error.
547 int sample_size = (device->out_bits / 8) * device->get_ochannels();
548 int samples = size / sample_size;
549 //printf("AudioALSA::write_buffer %d\n",samples);
551 snd_pcm_sframes_t delay = 0;
553 // static FILE *debug_fd = 0;
556 // debug_fd = fopen("/tmp/debug.pcm", "w");
558 // fwrite(buffer, size, 1, debug_fd);
562 if(!get_output()) return 0;
563 if( buffer_position == 0 )
566 AudioThread *audio_out = device->audio_out;
567 while(attempts < 2 && !done && !device->playback_interrupted)
569 // Buffers written must be equal to period_time
570 audio_out->Thread::enable_cancel();
571 int ret = snd_pcm_avail_update(get_output());
572 if( ret >= period_size ) {
573 if( ret > count ) ret = count;
575 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
576 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
577 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
578 ret = snd_pcm_writei(get_output(),buffer,ret);
579 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
581 else if( ret >= 0 || ret == -EAGAIN ) {
582 ret = snd_pcm_wait(get_output(),15);
583 if( ret > 0 ) ret = 0;
585 audio_out->Thread::disable_cancel();
586 if( ret == 0 ) continue;
589 samples_written += ret;
590 if( (count-=ret) > 0 ) {
591 buffer += ret * sample_size;
598 printf("AudioALSA::write_buffer err %d(%s) at sample %jd\n",
599 ret, snd_strerror(ret), device->current_position());
601 // snd_pcm_resume(get_output());
602 snd_pcm_recover(get_output(), ret, 1);
603 // close_output(); open_output();
608 if( !interrupted && device->playback_interrupted )
611 //printf("AudioALSA::write_buffer interrupted\n");
617 timer_lock->lock("AudioALSA::write_buffer");
618 snd_pcm_delay(get_output(), &delay);
621 buffer_position += samples;
622 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
623 timer_lock->unlock();
628 //this delay seems to prevent a problem where the sound system outputs
629 //a lot of silence while waiting for the device drain to happen.
630 int AudioALSA::output_wait()
632 snd_pcm_sframes_t delay = 0;
633 snd_pcm_delay(get_output(), &delay);
634 if( delay <= 0 ) return 0;
635 int64_t udelay = 1e6 * delay / device->out_samplerate;
636 // don't allow more than 10 seconds
637 if( udelay > 10000000 ) udelay = 10000000;
638 while( udelay > 0 && !device->playback_interrupted ) {
639 int64_t usecs = udelay;
640 if( usecs > 100000 ) usecs = 100000;
644 if( device->playback_interrupted &&
645 !device->out_config->interrupt_workaround )
646 snd_pcm_drop(get_output());
650 int AudioALSA::flush_device()
652 //printf("AudioALSA::flush_device\n");
656 //this causes the output to stutter.
657 //snd_pcm_nonblock(get_output(), 0);
658 snd_pcm_drain(get_output());
659 //snd_pcm_nonblock(get_output(), 1);
664 int AudioALSA::interrupt_playback()
666 //printf("AudioALSA::interrupt_playback *********\n");
669 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
670 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
671 // if(!device->out_config->interrupt_workaround)
672 // snd_pcm_drop(get_output());
674 // Makes sure the current buffer finishes before stopping.
675 // snd_pcm_drain(get_output());
677 // The only way to ensure snd_pcm_writei exits, but
678 // got a lot of crashes when doing this.
679 // device->Thread::cancel();
685 snd_pcm_t* AudioALSA::get_output()
690 snd_pcm_t* AudioALSA::get_input()