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 void AudioALSA::translate_name(char *output, char *input, int mode)
152 ArrayList<char*> titles;
153 titles.set_array_delete();
155 ArrayList<char*> pcm_titles;
156 pcm_titles.set_array_delete();
158 list_devices(&titles, &pcm_titles, mode);
160 // attempt to add pulseaudio "monitor" devices
161 add_pulse_devices(mode, &titles, &pcm_titles);
163 sprintf(output, "default");
164 for(int i = 0; i < titles.total; i++)
166 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
167 if(!strcasecmp(titles.values[i], input))
169 strcpy(output, pcm_titles.values[i]);
174 titles.remove_all_objects();
175 pcm_titles.remove_all_objects();
178 snd_pcm_format_t AudioALSA::translate_format(int format)
182 case 8: return SND_PCM_FORMAT_S8;
183 case 16: return SND_PCM_FORMAT_S16_LE;
184 case 24: return SND_PCM_FORMAT_S24_LE;
185 case 32: return SND_PCM_FORMAT_S32_LE;
187 return SND_PCM_FORMAT_UNKNOWN;
190 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
191 int channels, int bits, int samplerate, int samples)
193 snd_pcm_hw_params_t *params;
194 snd_pcm_sw_params_t *swparams;
197 snd_pcm_hw_params_alloca(¶ms);
198 snd_pcm_sw_params_alloca(&swparams);
199 err = snd_pcm_hw_params_any(dsp, params);
202 fprintf(stderr, "AudioALSA::set_params: ");
203 fprintf(stderr, _("no PCM configurations available\n"));
207 err=snd_pcm_hw_params_set_access(dsp,
209 SND_PCM_ACCESS_RW_INTERLEAVED);
211 fprintf(stderr, "AudioALSA::set_params: ");
212 fprintf(stderr, _("failed to set up interleaved device access.\n"));
216 err=snd_pcm_hw_params_set_format(dsp,
218 translate_format(bits));
220 fprintf(stderr, "AudioALSA::set_params: ");
221 fprintf(stderr, _("failed to set output format.\n"));
225 err=snd_pcm_hw_params_set_channels(dsp,
229 fprintf(stderr, "AudioALSA::set_params: ");
230 fprintf(stderr, _("Configured ALSA device does not support %d channel operation.\n"),
235 err=snd_pcm_hw_params_set_rate_near(dsp,
237 (unsigned int*)&samplerate,
240 fprintf(stderr, "AudioALSA::set_params: ");
241 fprintf(stderr, _(" Configured ALSA device does not support %u Hz playback.\n"),
242 (unsigned int)samplerate);
246 // Buffers written must be equal to period_time
248 int period_time = (int)(1000000 * (double)samples / samplerate);
251 buffer_time = 10000000;
254 buffer_time = 2 * period_time;
258 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
259 snd_pcm_hw_params_set_buffer_time_near(dsp,
261 (unsigned int*)&buffer_time,
263 snd_pcm_hw_params_set_period_time_near(dsp,
265 (unsigned int*)&period_time,
267 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
268 err = snd_pcm_hw_params(dsp, params);
270 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
274 snd_pcm_uframes_t chunk_size = 1024;
275 snd_pcm_uframes_t buffer_size = 262144;
276 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
277 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
278 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
280 snd_pcm_sw_params_current(dsp, swparams);
281 //snd_pcm_uframes_t xfer_align = 1;
282 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
283 //unsigned int sleep_min = 0;
284 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
285 period_size = chunk_size;
286 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
287 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
288 if(snd_pcm_sw_params(dsp, swparams) < 0) {
289 /* we can continue staggering along even if this fails */
290 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
293 device->device_buffer = samples * bits / 8 * channels;
295 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
297 // snd_pcm_hw_params_free(params);
298 // snd_pcm_sw_params_free(swparams);
302 int AudioALSA::open_input()
304 char pcm_name[BCTEXTLEN];
305 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
309 device->in_channels = device->get_ichannels();
310 device->in_bits = device->in_config->alsa_in_bits;
312 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
313 //printf("AudioALSA::open_input %s\n", pcm_name);
315 err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
319 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
323 err = set_params(dsp_in, MODERECORD,
324 device->get_ichannels(),
325 device->in_config->alsa_in_bits,
326 device->in_samplerate,
329 fprintf(stderr, "AudioALSA::open_input: set_params failed. Aborting sampling.\n");
337 int AudioALSA::open_output()
339 char pcm_name[BCTEXTLEN];
340 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
341 int open_mode = SND_PCM_NONBLOCK;
344 device->out_channels = device->get_ochannels();
345 device->out_bits = device->out_config->alsa_out_bits;
347 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
348 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
349 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
351 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
356 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
360 err = set_params(dsp_out, MODEPLAY,
361 device->get_ochannels(),
362 device->out_config->alsa_out_bits,
363 device->out_samplerate,
364 device->out_samples);
366 fprintf(stderr, "AudioALSA::open_output: set_params failed. Aborting playback.\n");
375 int AudioALSA::stop_output()
377 //printf("AudioALSA::stop_output\n");
378 if(!device->out_config->interrupt_workaround)
381 snd_pcm_drop(get_output());
388 int AudioALSA::close_output()
390 //printf("AudioALSA::close_output\n");
391 if(device->w && dsp_out) {
393 snd_pcm_close(dsp_out);
399 int AudioALSA::close_input()
401 //printf("AudioALSA::close_input\n");
402 if(device->r && dsp_in) {
403 // snd_pcm_reset(dsp_in);
404 snd_pcm_drop(dsp_in);
405 snd_pcm_drain(dsp_in);
406 snd_pcm_close(dsp_in);
412 int AudioALSA::close_all()
414 //printf("AudioALSA::close_all\n");
425 int64_t AudioALSA::device_position()
427 timer_lock->lock("AudioALSA::device_position");
428 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
429 int64_t result = buffer_position - delay + delta;
430 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
431 // buffer_position, delta, delay, result);
432 timer_lock->unlock();
436 int AudioALSA::read_buffer(char *buffer, int size)
438 //printf("AudioALSA::read_buffer 1\n");
441 int frame_size = (device->in_bits / 8) * device->get_ichannels();
450 while(attempts < 1 && !done)
452 snd_pcm_uframes_t frames = size / frame_size;
453 result = snd_pcm_readi(get_input(), buffer, frames);
456 printf("AudioALSA::read_buffer overrun at sample %jd\n",
457 device->total_samples_read);
458 // snd_pcm_resume(get_input());
459 close_input(); open_input();
464 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
469 int AudioALSA::write_buffer(char *buffer, int size)
471 //printf("AudioALSA::write_buffer %d\n",size);
472 // Don't give up and drop the buffer on the first error.
475 int sample_size = (device->out_bits / 8) * device->get_ochannels();
476 int samples = size / sample_size;
477 //printf("AudioALSA::write_buffer %d\n",samples);
479 snd_pcm_sframes_t delay = 0;
481 // static FILE *debug_fd = 0;
484 // debug_fd = fopen("/tmp/debug.pcm", "w");
486 // fwrite(buffer, size, 1, debug_fd);
490 if(!get_output()) return 0;
491 if( buffer_position == 0 )
494 AudioThread *audio_out = device->audio_out;
495 while( count > 0 && attempts < 2 && !done ) {
496 if( device->playback_interrupted ) break;
497 // Buffers written must be equal to period_time
498 audio_out->Thread::enable_cancel();
499 int ret = snd_pcm_avail_update(get_output());
500 if( ret >= period_size ) {
501 if( ret > count ) ret = count;
503 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
504 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
505 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
506 ret = snd_pcm_writei(get_output(),buffer,ret);
507 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
509 else if( ret >= 0 || ret == -EAGAIN ) {
510 ret = snd_pcm_wait(get_output(),15);
511 if( ret > 0 ) ret = 0;
513 audio_out->Thread::disable_cancel();
514 if( device->playback_interrupted ) break;
515 if( ret == 0 ) continue;
518 samples_written += ret;
519 if( (count-=ret) > 0 ) {
520 buffer += ret * sample_size;
527 printf(_("AudioALSA::write_buffer err %d(%s) at sample %jd\n"),
528 ret, snd_strerror(ret), device->current_position());
530 // snd_pcm_resume(get_output());
531 snd_pcm_recover(get_output(), ret, 1);
532 // close_output(); open_output();
537 if( !interrupted && device->playback_interrupted )
540 //printf("AudioALSA::write_buffer interrupted\n");
546 timer_lock->lock("AudioALSA::write_buffer");
547 snd_pcm_delay(get_output(), &delay);
550 buffer_position += samples;
551 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
552 timer_lock->unlock();
557 //this delay seems to prevent a problem where the sound system outputs
558 //a lot of silence while waiting for the device drain to happen.
559 int AudioALSA::output_wait()
561 snd_pcm_sframes_t delay = 0;
562 snd_pcm_delay(get_output(), &delay);
563 if( delay <= 0 ) return 0;
564 int64_t udelay = 1e6 * delay / device->out_samplerate;
565 // don't allow more than 10 seconds
566 if( udelay > 10000000 ) udelay = 10000000;
567 while( udelay > 0 && !device->playback_interrupted ) {
568 int64_t usecs = udelay;
569 if( usecs > 100000 ) usecs = 100000;
573 if( device->playback_interrupted &&
574 !device->out_config->interrupt_workaround )
575 snd_pcm_drop(get_output());
579 int AudioALSA::flush_device()
581 //printf("AudioALSA::flush_device\n");
585 //this causes the output to stutter.
586 //snd_pcm_nonblock(get_output(), 0);
587 snd_pcm_drain(get_output());
588 //snd_pcm_nonblock(get_output(), 1);
593 int AudioALSA::interrupt_playback()
595 //printf("AudioALSA::interrupt_playback *********\n");
598 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
599 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
600 // if(!device->out_config->interrupt_workaround)
601 // snd_pcm_drop(get_output());
603 // Makes sure the current buffer finishes before stopping.
604 // snd_pcm_drain(get_output());
606 // The only way to ensure snd_pcm_writei exits, but
607 // got a lot of crashes when doing this.
608 // device->Thread::cancel();
614 snd_pcm_t* AudioALSA::get_output()
619 snd_pcm_t* AudioALSA::get_input()
624 void AudioALSA::add_pulse_devices(int mode,
625 ArrayList<char*> *names, ArrayList<char*> *pcm_names)
628 // run: pactl list <sources>|<sinks>
629 // scan output for <Source/Sink> #n, Name: <device>
630 // build alsa device config and add to alsa snd_config
641 char line[BCTEXTLEN];
643 sprintf(line, "LANGUAGE=en_US.UTF-8 pactl list %ss", arg);
644 pactl = popen(line,"r");
648 char name[BCTEXTLEN], pa_name[BCTEXTLEN], device[BCTEXTLEN];
649 name[0] = pa_name[0] = device[0] = 0;
650 int arg_len = strlen(arg);
651 while( fgets(line, sizeof(line), pactl) ) {
652 if( !strncasecmp(line, arg, arg_len) ) {
653 char *sp = name, *id = pa_name;
654 for( char *cp=line; *cp && *cp!='\n'; *sp++=*cp++ )
655 *id++ = (*cp>='A' && *cp<='Z') ||
656 (*cp>='a' && *cp<='z') ||
657 (*cp>='0' && *cp<='9') ? *cp : '_';
660 names->append(cstrdup(name));
663 if( sscanf(line, " Name: %s", device) != 1 ) continue;
664 int len = strlen(pa_name);
666 pcm_names->append(cstrdup(pa_name));
667 char alsa_config[BCTEXTLEN];
668 len = snprintf(alsa_config, sizeof(alsa_config),
669 "pcm.!%s {\n type pulse\n device %s\n}\n"
670 "ctl.!%s {\n type pulse\n device %s\n}\n",
671 pa_name, device, pa_name, device);
672 FILE *fp = fmemopen(alsa_config,len,"r");
674 snd_input_stdio_attach(&inp, fp, 1);
675 snd_config_load(snd_config, inp);
676 name[0] = pa_name[0] = device[0] = 0;
677 snd_input_close(inp);