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 AudioALSA::list_devices(alsa_titles, 0, MODEPLAY);
62 alsa_titles->remove_all_objects();
65 ~alsa_leaks() { snd_config_update_free_global(); }
68 void AudioALSA::list_devices(ArrayList<char*> *devices, int pcm_title, int mode)
72 snd_ctl_card_info_t *info;
73 snd_pcm_info_t *pcminfo;
74 char string[BCTEXTLEN];
75 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
77 devices->set_array_delete();
83 stream = SND_PCM_STREAM_CAPTURE;
86 stream = SND_PCM_STREAM_PLAYBACK;
91 snd_ctl_card_info_alloca(&info);
92 snd_pcm_info_alloca(&pcminfo);
95 #define DEFAULT_DEVICE "default"
96 char *result = new char[strlen(DEFAULT_DEVICE) + 1];
97 devices->append(result);
98 devices->set_array_delete(); // since we are allocating by new[]
99 strcpy(result, DEFAULT_DEVICE);
101 while(snd_card_next(&card) >= 0)
103 char name[BCTEXTLEN];
105 sprintf(name, "hw:%i", card);
107 if((err = snd_ctl_open(&handle, name, 0)) < 0)
109 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
113 if((err = snd_ctl_card_info(handle, info)) < 0)
115 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
116 snd_ctl_close(handle);
124 if(snd_ctl_pcm_next_device(handle, &dev) < 0)
125 printf("AudioALSA::list_devices: snd_ctl_pcm_next_device\n");
130 snd_pcm_info_set_device(pcminfo, dev);
131 snd_pcm_info_set_subdevice(pcminfo, 0);
132 snd_pcm_info_set_stream(pcminfo, stream);
134 if((err = snd_ctl_pcm_info(handle, pcminfo)) < 0)
137 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
143 sprintf(string, "plughw:%d,%d", card, dev);
144 // strcpy(string, "cards.pcm.front");
148 sprintf(string, "%s #%d",
149 snd_ctl_card_info_get_name(info),
153 char *result = devices->append(new char[strlen(string) + 1]);
154 strcpy(result, string);
159 snd_ctl_close(handle);
162 // attempt to add pulseaudio "monitor" devices
163 // run: pactl list <sources>|<sinks>
164 // scan output for <Source/Sink> #n, Name: <device>
165 // build alsa device config and add to alsa snd_config
177 char line[BCTEXTLEN];
179 sprintf(line, "pactl list %ss", arg);
180 pactl = popen(line,"r");
183 if( pcm_title ) snd_config_update();
184 char name[BCTEXTLEN], pa_name[BCTEXTLEN], device[BCTEXTLEN];
185 name[0] = pa_name[0] = device[0] = 0;
186 int arg_len = strlen(arg);
187 while( fgets(line, sizeof(line), pactl) ) {
188 if( !strncasecmp(line, arg, arg_len) ) {
189 char *sp = name, *id = pa_name;
190 for( char *cp=line; *cp && *cp!='\n'; *sp++=*cp++ )
191 *id++ = (*cp>='A' && *cp<='Z') ||
192 (*cp>='a' && *cp<='z') ||
193 (*cp>='0' && *cp<='9') ? *cp : '_';
196 devices->append(strcpy(new char[sp-name], name));
199 if( !pcm_title ) continue;
200 if( sscanf(line, " Name: %s", device) != 1 ) continue;
201 int len = strlen(pa_name);
202 devices->append(strcpy(new char[len+1], pa_name));
203 char alsa_config[BCTEXTLEN];
204 len = snprintf(alsa_config, sizeof(alsa_config),
205 "pcm.!%s {\n type pulse\n device %s\n}\n"
206 "ctl.!%s {\n type pulse\n device %s\n}\n",
207 pa_name, device, pa_name, device);
208 FILE *fp = fmemopen(alsa_config,len,"r");
210 snd_input_stdio_attach(&inp, fp, 1);
211 snd_config_load(snd_config, inp);
212 name[0] = pa_name[0] = device[0] = 0;
213 snd_input_close(inp);
219 void AudioALSA::translate_name(char *output, char *input, int mode)
221 ArrayList<char*> titles;
222 ArrayList<char*> pcm_titles;
224 list_devices(&titles, 0, mode);
225 list_devices(&pcm_titles, 1, mode);
227 sprintf(output, "default");
228 for(int i = 0; i < titles.total; i++)
230 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
231 if(!strcasecmp(titles.values[i], input))
233 strcpy(output, pcm_titles.values[i]);
238 titles.remove_all_objects();
239 pcm_titles.remove_all_objects();
242 snd_pcm_format_t AudioALSA::translate_format(int format)
247 return SND_PCM_FORMAT_S8;
250 return SND_PCM_FORMAT_S16_LE;
253 return SND_PCM_FORMAT_S24_LE;
256 return SND_PCM_FORMAT_S32_LE;
259 return SND_PCM_FORMAT_UNKNOWN;
262 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
263 int channels, int bits, int samplerate, int samples)
265 snd_pcm_hw_params_t *params;
266 snd_pcm_sw_params_t *swparams;
269 snd_pcm_hw_params_alloca(¶ms);
270 snd_pcm_sw_params_alloca(&swparams);
271 err = snd_pcm_hw_params_any(dsp, params);
274 fprintf(stderr, "AudioALSA::set_params: no PCM configurations available\n");
278 err=snd_pcm_hw_params_set_access(dsp,
280 SND_PCM_ACCESS_RW_INTERLEAVED);
282 fprintf(stderr, "AudioALSA::set_params: failed to set up "
283 "interleaved device access.\n");
287 err=snd_pcm_hw_params_set_format(dsp,
289 translate_format(bits));
291 fprintf(stderr, "AudioALSA::set_params: failed to set output format.\n");
295 err=snd_pcm_hw_params_set_channels(dsp,
299 fprintf(stderr, "AudioALSA::set_params: Configured ALSA device "
300 "does not support %d channel operation.\n",
305 err=snd_pcm_hw_params_set_rate_near(dsp,
307 (unsigned int*)&samplerate,
310 fprintf(stderr, "AudioALSA::set_params: Configured ALSA device "
311 "does not support %u Hz playback.\n",
312 (unsigned int)samplerate);
316 // Buffers written must be equal to period_time
318 int period_time = (int)(1000000 * (double)samples / samplerate);
321 buffer_time = 10000000;
324 buffer_time = 2 * period_time;
328 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
329 snd_pcm_hw_params_set_buffer_time_near(dsp,
331 (unsigned int*)&buffer_time,
333 snd_pcm_hw_params_set_period_time_near(dsp,
335 (unsigned int*)&period_time,
337 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
338 err = snd_pcm_hw_params(dsp, params);
340 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
344 snd_pcm_uframes_t chunk_size = 1024;
345 snd_pcm_uframes_t buffer_size = 262144;
346 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
347 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
348 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
350 snd_pcm_sw_params_current(dsp, swparams);
351 //snd_pcm_uframes_t xfer_align = 1;
352 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
353 //unsigned int sleep_min = 0;
354 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
355 period_size = chunk_size;
356 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
357 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
358 if(snd_pcm_sw_params(dsp, swparams) < 0) {
359 /* we can continue staggering along even if this fails */
360 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
363 device->device_buffer = samples * bits / 8 * channels;
365 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
367 // snd_pcm_hw_params_free(params);
368 // snd_pcm_sw_params_free(swparams);
372 int AudioALSA::open_input()
374 char pcm_name[BCTEXTLEN];
375 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
379 device->in_channels = device->get_ichannels();
380 device->in_bits = device->in_config->alsa_in_bits;
382 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
383 //printf("AudioALSA::open_input %s\n", pcm_name);
385 err = snd_pcm_open(&dsp_in, device->in_config->alsa_in_device, stream, open_mode);
389 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
393 err = set_params(dsp_in, MODERECORD,
394 device->get_ichannels(),
395 device->in_config->alsa_in_bits,
396 device->in_samplerate,
399 fprintf(stderr, "AudioALSA::open_input: set_params failed. Aborting sampling.\n");
407 int AudioALSA::open_output()
409 char pcm_name[BCTEXTLEN];
410 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
411 int open_mode = SND_PCM_NONBLOCK;
414 device->out_channels = device->get_ochannels();
415 device->out_bits = device->out_config->alsa_out_bits;
417 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
418 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
419 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
421 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
426 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
430 set_params(dsp_out, MODEPLAY,
431 device->get_ochannels(),
432 device->out_config->alsa_out_bits,
433 device->out_samplerate,
434 device->out_samples);
436 fprintf(stderr, "AudioALSA::open_output: set_params failed. Aborting playback.\n");
445 int AudioALSA::stop_output()
447 //printf("AudioALSA::stop_output\n");
448 if(!device->out_config->interrupt_workaround)
451 snd_pcm_drop(get_output());
458 int AudioALSA::close_output()
460 //printf("AudioALSA::close_output\n");
461 if(device->w && dsp_out) {
463 snd_pcm_close(dsp_out);
469 int AudioALSA::close_input()
471 //printf("AudioALSA::close_input\n");
472 if(device->r && dsp_in) {
473 // snd_pcm_reset(dsp_in);
474 snd_pcm_drop(dsp_in);
475 snd_pcm_drain(dsp_in);
476 snd_pcm_close(dsp_in);
482 int AudioALSA::close_all()
484 //printf("AudioALSA::close_all\n");
495 int64_t AudioALSA::device_position()
497 timer_lock->lock("AudioALSA::device_position");
498 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
499 int64_t result = buffer_position - delay + delta;
500 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
501 // buffer_position, delta, delay, result);
502 timer_lock->unlock();
506 int AudioALSA::read_buffer(char *buffer, int size)
508 //printf("AudioALSA::read_buffer 1\n");
511 int frame_size = (device->in_bits / 8) * device->get_ichannels();
520 while(attempts < 1 && !done)
522 snd_pcm_uframes_t frames = size / frame_size;
523 result = snd_pcm_readi(get_input(), buffer, frames);
526 printf("AudioALSA::read_buffer overrun at sample %jd\n",
527 device->total_samples_read);
528 // snd_pcm_resume(get_input());
529 close_input(); open_input();
534 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
539 int AudioALSA::write_buffer(char *buffer, int size)
541 //printf("AudioALSA::write_buffer %d\n",size);
542 // Don't give up and drop the buffer on the first error.
545 int sample_size = (device->out_bits / 8) * device->get_ochannels();
546 int samples = size / sample_size;
547 //printf("AudioALSA::write_buffer %d\n",samples);
549 snd_pcm_sframes_t delay = 0;
551 // static FILE *debug_fd = 0;
554 // debug_fd = fopen("/tmp/debug.pcm", "w");
556 // fwrite(buffer, size, 1, debug_fd);
560 if(!get_output()) return 0;
561 if( buffer_position == 0 )
564 AudioThread *audio_out = device->audio_out;
565 while(attempts < 2 && !done && !device->playback_interrupted)
567 // Buffers written must be equal to period_time
568 audio_out->Thread::enable_cancel();
569 int ret = snd_pcm_avail_update(get_output());
570 if( ret >= period_size ) {
571 if( ret > count ) ret = count;
573 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
574 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
575 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
576 ret = snd_pcm_writei(get_output(),buffer,ret);
577 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
579 else if( ret >= 0 || ret == -EAGAIN ) {
580 ret = snd_pcm_wait(get_output(),15);
581 if( ret > 0 ) ret = 0;
583 audio_out->Thread::disable_cancel();
584 if( ret == 0 ) continue;
587 samples_written += ret;
588 if( (count-=ret) > 0 ) {
589 buffer += ret * sample_size;
596 printf("AudioALSA::write_buffer err %d(%s) at sample %jd\n",
597 ret, snd_strerror(ret), device->current_position());
599 // snd_pcm_resume(get_output());
600 snd_pcm_recover(get_output(), ret, 1);
601 // close_output(); open_output();
606 if( !interrupted && device->playback_interrupted )
609 //printf("AudioALSA::write_buffer interrupted\n");
615 timer_lock->lock("AudioALSA::write_buffer");
616 snd_pcm_delay(get_output(), &delay);
619 buffer_position += samples;
620 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
621 timer_lock->unlock();
626 //this delay seems to prevent a problem where the sound system outputs
627 //a lot of silence while waiting for the device drain to happen.
628 int AudioALSA::output_wait()
630 snd_pcm_sframes_t delay = 0;
631 snd_pcm_delay(get_output(), &delay);
632 if( delay <= 0 ) return 0;
633 int64_t udelay = 1e6 * delay / device->out_samplerate;
634 // don't allow more than 10 seconds
635 if( udelay > 10000000 ) udelay = 10000000;
636 while( udelay > 0 && !device->playback_interrupted ) {
637 int64_t usecs = udelay;
638 if( usecs > 100000 ) usecs = 100000;
642 if( device->playback_interrupted &&
643 !device->out_config->interrupt_workaround )
644 snd_pcm_drop(get_output());
648 int AudioALSA::flush_device()
650 //printf("AudioALSA::flush_device\n");
654 //this causes the output to stutter.
655 //snd_pcm_nonblock(get_output(), 0);
656 snd_pcm_drain(get_output());
657 //snd_pcm_nonblock(get_output(), 1);
662 int AudioALSA::interrupt_playback()
664 //printf("AudioALSA::interrupt_playback *********\n");
667 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
668 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
669 // if(!device->out_config->interrupt_workaround)
670 // snd_pcm_drop(get_output());
672 // Makes sure the current buffer finishes before stopping.
673 // snd_pcm_drain(get_output());
675 // The only way to ensure snd_pcm_writei exits, but
676 // got a lot of crashes when doing this.
677 // device->Thread::cancel();
683 snd_pcm_t* AudioALSA::get_output()
688 snd_pcm_t* AudioALSA::get_input()