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)
238 return SND_PCM_FORMAT_S8;
241 return SND_PCM_FORMAT_S16_LE;
244 return SND_PCM_FORMAT_S24_LE;
247 return SND_PCM_FORMAT_S32_LE;
250 return SND_PCM_FORMAT_UNKNOWN;
253 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
254 int channels, int bits, int samplerate, int samples)
256 snd_pcm_hw_params_t *params;
257 snd_pcm_sw_params_t *swparams;
260 snd_pcm_hw_params_alloca(¶ms);
261 snd_pcm_sw_params_alloca(&swparams);
262 err = snd_pcm_hw_params_any(dsp, params);
265 fprintf(stderr, "AudioALSA::set_params: ");
266 fprintf(stderr, _("no PCM configurations available\n"));
270 err=snd_pcm_hw_params_set_access(dsp,
272 SND_PCM_ACCESS_RW_INTERLEAVED);
274 fprintf(stderr, "AudioALSA::set_params: ");
275 fprintf(stderr, _("failed to set up interleaved device access.\n"));
279 err=snd_pcm_hw_params_set_format(dsp,
281 translate_format(bits));
283 fprintf(stderr, "AudioALSA::set_params: ");
284 fprintf(stderr, _("failed to set output format.\n"));
288 err=snd_pcm_hw_params_set_channels(dsp,
292 fprintf(stderr, "AudioALSA::set_params: ");
293 fprintf(stderr, _("Configured ALSA device does not support %d channel operation.\n"),
298 err=snd_pcm_hw_params_set_rate_near(dsp,
300 (unsigned int*)&samplerate,
303 fprintf(stderr, "AudioALSA::set_params: ");
304 fprintf(stderr, _(" Configured ALSA device does not support %u Hz playback.\n"),
305 (unsigned int)samplerate);
309 // Buffers written must be equal to period_time
311 int period_time = (int)(1000000 * (double)samples / samplerate);
314 buffer_time = 10000000;
317 buffer_time = 2 * period_time;
321 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
322 snd_pcm_hw_params_set_buffer_time_near(dsp,
324 (unsigned int*)&buffer_time,
326 snd_pcm_hw_params_set_period_time_near(dsp,
328 (unsigned int*)&period_time,
330 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
331 err = snd_pcm_hw_params(dsp, params);
333 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
337 snd_pcm_uframes_t chunk_size = 1024;
338 snd_pcm_uframes_t buffer_size = 262144;
339 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
340 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
341 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
343 snd_pcm_sw_params_current(dsp, swparams);
344 //snd_pcm_uframes_t xfer_align = 1;
345 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
346 //unsigned int sleep_min = 0;
347 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
348 period_size = chunk_size;
349 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
350 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
351 if(snd_pcm_sw_params(dsp, swparams) < 0) {
352 /* we can continue staggering along even if this fails */
353 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
356 device->device_buffer = samples * bits / 8 * channels;
358 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
360 // snd_pcm_hw_params_free(params);
361 // snd_pcm_sw_params_free(swparams);
365 int AudioALSA::open_input()
367 char pcm_name[BCTEXTLEN];
368 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
372 device->in_channels = device->get_ichannels();
373 device->in_bits = device->in_config->alsa_in_bits;
375 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
376 //printf("AudioALSA::open_input %s\n", pcm_name);
378 err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
382 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
386 err = set_params(dsp_in, MODERECORD,
387 device->get_ichannels(),
388 device->in_config->alsa_in_bits,
389 device->in_samplerate,
392 fprintf(stderr, "AudioALSA::open_input: set_params failed. Aborting sampling.\n");
400 int AudioALSA::open_output()
402 char pcm_name[BCTEXTLEN];
403 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
404 int open_mode = SND_PCM_NONBLOCK;
407 device->out_channels = device->get_ochannels();
408 device->out_bits = device->out_config->alsa_out_bits;
410 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
411 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
412 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
414 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
419 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
423 err = set_params(dsp_out, MODEPLAY,
424 device->get_ochannels(),
425 device->out_config->alsa_out_bits,
426 device->out_samplerate,
427 device->out_samples);
429 fprintf(stderr, "AudioALSA::open_output: set_params failed. Aborting playback.\n");
438 int AudioALSA::stop_output()
440 //printf("AudioALSA::stop_output\n");
441 if(!device->out_config->interrupt_workaround)
444 snd_pcm_drop(get_output());
451 int AudioALSA::close_output()
453 //printf("AudioALSA::close_output\n");
454 if(device->w && dsp_out) {
456 snd_pcm_close(dsp_out);
462 int AudioALSA::close_input()
464 //printf("AudioALSA::close_input\n");
465 if(device->r && dsp_in) {
466 // snd_pcm_reset(dsp_in);
467 snd_pcm_drop(dsp_in);
468 snd_pcm_drain(dsp_in);
469 snd_pcm_close(dsp_in);
475 int AudioALSA::close_all()
477 //printf("AudioALSA::close_all\n");
488 int64_t AudioALSA::device_position()
490 timer_lock->lock("AudioALSA::device_position");
491 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
492 int64_t result = buffer_position - delay + delta;
493 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
494 // buffer_position, delta, delay, result);
495 timer_lock->unlock();
499 int AudioALSA::read_buffer(char *buffer, int size)
501 //printf("AudioALSA::read_buffer 1\n");
504 int frame_size = (device->in_bits / 8) * device->get_ichannels();
513 while(attempts < 1 && !done)
515 snd_pcm_uframes_t frames = size / frame_size;
516 result = snd_pcm_readi(get_input(), buffer, frames);
519 printf("AudioALSA::read_buffer overrun at sample %jd\n",
520 device->total_samples_read);
521 // snd_pcm_resume(get_input());
522 close_input(); open_input();
527 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
532 int AudioALSA::write_buffer(char *buffer, int size)
534 //printf("AudioALSA::write_buffer %d\n",size);
535 // Don't give up and drop the buffer on the first error.
538 int sample_size = (device->out_bits / 8) * device->get_ochannels();
539 int samples = size / sample_size;
540 //printf("AudioALSA::write_buffer %d\n",samples);
542 snd_pcm_sframes_t delay = 0;
544 // static FILE *debug_fd = 0;
547 // debug_fd = fopen("/tmp/debug.pcm", "w");
549 // fwrite(buffer, size, 1, debug_fd);
553 if(!get_output()) return 0;
554 if( buffer_position == 0 )
557 AudioThread *audio_out = device->audio_out;
558 while( count > 0 && attempts < 2 && !done ) {
559 if( device->playback_interrupted ) break;
560 // Buffers written must be equal to period_time
561 audio_out->Thread::enable_cancel();
562 int ret = snd_pcm_avail_update(get_output());
563 if( ret >= period_size ) {
564 if( ret > count ) ret = count;
566 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
567 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
568 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
569 ret = snd_pcm_writei(get_output(),buffer,ret);
570 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
572 else if( ret >= 0 || ret == -EAGAIN ) {
573 ret = snd_pcm_wait(get_output(),15);
574 if( ret > 0 ) ret = 0;
576 audio_out->Thread::disable_cancel();
577 if( device->playback_interrupted ) break;
578 if( ret == 0 ) continue;
581 samples_written += ret;
582 if( (count-=ret) > 0 ) {
583 buffer += ret * sample_size;
590 printf("AudioALSA::write_buffer err %d(%s) at sample %jd\n",
591 ret, snd_strerror(ret), device->current_position());
593 // snd_pcm_resume(get_output());
594 snd_pcm_recover(get_output(), ret, 1);
595 // close_output(); open_output();
600 if( !interrupted && device->playback_interrupted )
603 //printf("AudioALSA::write_buffer interrupted\n");
609 timer_lock->lock("AudioALSA::write_buffer");
610 snd_pcm_delay(get_output(), &delay);
613 buffer_position += samples;
614 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
615 timer_lock->unlock();
620 //this delay seems to prevent a problem where the sound system outputs
621 //a lot of silence while waiting for the device drain to happen.
622 int AudioALSA::output_wait()
624 snd_pcm_sframes_t delay = 0;
625 snd_pcm_delay(get_output(), &delay);
626 if( delay <= 0 ) return 0;
627 int64_t udelay = 1e6 * delay / device->out_samplerate;
628 // don't allow more than 10 seconds
629 if( udelay > 10000000 ) udelay = 10000000;
630 while( udelay > 0 && !device->playback_interrupted ) {
631 int64_t usecs = udelay;
632 if( usecs > 100000 ) usecs = 100000;
636 if( device->playback_interrupted &&
637 !device->out_config->interrupt_workaround )
638 snd_pcm_drop(get_output());
642 int AudioALSA::flush_device()
644 //printf("AudioALSA::flush_device\n");
648 //this causes the output to stutter.
649 //snd_pcm_nonblock(get_output(), 0);
650 snd_pcm_drain(get_output());
651 //snd_pcm_nonblock(get_output(), 1);
656 int AudioALSA::interrupt_playback()
658 //printf("AudioALSA::interrupt_playback *********\n");
661 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
662 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
663 // if(!device->out_config->interrupt_workaround)
664 // snd_pcm_drop(get_output());
666 // Makes sure the current buffer finishes before stopping.
667 // snd_pcm_drain(get_output());
669 // The only way to ensure snd_pcm_writei exits, but
670 // got a lot of crashes when doing this.
671 // device->Thread::cancel();
677 snd_pcm_t* AudioALSA::get_output()
682 snd_pcm_t* AudioALSA::get_input()