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*> *devices, int pcm_title, 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"
95 char *result = new char[strlen(DEFAULT_DEVICE) + 1];
96 devices->append(result);
97 strcpy(result, DEFAULT_DEVICE);
99 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)
107 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
111 if((err = snd_ctl_card_info(handle, info)) < 0)
113 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
114 snd_ctl_close(handle);
122 if(snd_ctl_pcm_next_device(handle, &dev) < 0)
123 printf("AudioALSA::list_devices: snd_ctl_pcm_next_device\n");
128 snd_pcm_info_set_device(pcminfo, dev);
129 snd_pcm_info_set_subdevice(pcminfo, 0);
130 snd_pcm_info_set_stream(pcminfo, stream);
132 if((err = snd_ctl_pcm_info(handle, pcminfo)) < 0)
135 printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
141 sprintf(string, "plughw:%d,%d", card, dev);
142 // strcpy(string, "cards.pcm.front");
146 sprintf(string, "%s #%d",
147 snd_ctl_card_info_get_name(info),
151 char *result = devices->append(new char[strlen(string) + 1]);
152 strcpy(result, string);
157 snd_ctl_close(handle);
161 // attempt to add pulseaudio "monitor" devices
162 // run: pactl list <sources>|<sinks>
163 // scan output for <Source/Sink> #n, Name: <device>
164 // build alsa device config and add to alsa snd_config
176 char line[BCTEXTLEN];
178 sprintf(line, "pactl list %ss", arg);
179 pactl = popen(line,"r");
182 if( pcm_title ) snd_config_update();
183 char name[BCTEXTLEN], pa_name[BCTEXTLEN], device[BCTEXTLEN];
184 name[0] = pa_name[0] = device[0] = 0;
185 int arg_len = strlen(arg);
186 while( fgets(line, sizeof(line), pactl) ) {
187 if( !strncasecmp(line, arg, arg_len) ) {
188 char *sp = name, *id = pa_name;
189 for( char *cp=line; *cp && *cp!='\n'; *sp++=*cp++ )
190 *id++ = (*cp>='A' && *cp<='Z') ||
191 (*cp>='a' && *cp<='z') ||
192 (*cp>='0' && *cp<='9') ? *cp : '_';
195 devices->append(strcpy(new char[sp-name], name));
198 if( !pcm_title ) continue;
199 if( sscanf(line, " Name: %s", device) != 1 ) continue;
200 int len = strlen(pa_name);
201 devices->append(strcpy(new char[len+1], pa_name));
202 char alsa_config[BCTEXTLEN];
203 len = snprintf(alsa_config, sizeof(alsa_config),
204 "pcm.!%s {\n type pulse\n device %s\n}\n"
205 "ctl.!%s {\n type pulse\n device %s\n}\n",
206 pa_name, device, pa_name, device);
207 FILE *fp = fmemopen(alsa_config,len,"r");
209 snd_input_stdio_attach(&inp, fp, 1);
210 snd_config_load(snd_config, inp);
211 name[0] = pa_name[0] = device[0] = 0;
212 snd_input_close(inp);
219 void AudioALSA::translate_name(char *output, char *input, int mode)
221 ArrayList<char*> titles;
222 titles.set_array_delete();
224 ArrayList<char*> pcm_titles;
225 pcm_titles.set_array_delete();
227 list_devices(&titles, 0, mode);
228 list_devices(&pcm_titles, 1, mode);
230 sprintf(output, "default");
231 for(int i = 0; i < titles.total; i++)
233 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
234 if(!strcasecmp(titles.values[i], input))
236 strcpy(output, pcm_titles.values[i]);
241 titles.remove_all_objects();
242 pcm_titles.remove_all_objects();
245 snd_pcm_format_t AudioALSA::translate_format(int format)
250 return SND_PCM_FORMAT_S8;
253 return SND_PCM_FORMAT_S16_LE;
256 return SND_PCM_FORMAT_S24_LE;
259 return SND_PCM_FORMAT_S32_LE;
262 return SND_PCM_FORMAT_UNKNOWN;
265 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
266 int channels, int bits, int samplerate, int samples)
268 snd_pcm_hw_params_t *params;
269 snd_pcm_sw_params_t *swparams;
272 snd_pcm_hw_params_alloca(¶ms);
273 snd_pcm_sw_params_alloca(&swparams);
274 err = snd_pcm_hw_params_any(dsp, params);
277 fprintf(stderr, "AudioALSA::set_params: ");
278 fprintf(stderr, _("no PCM configurations available\n"));
282 err=snd_pcm_hw_params_set_access(dsp,
284 SND_PCM_ACCESS_RW_INTERLEAVED);
286 fprintf(stderr, "AudioALSA::set_params: ");
287 fprintf(stderr, _("failed to set up interleaved device access.\n"));
291 err=snd_pcm_hw_params_set_format(dsp,
293 translate_format(bits));
295 fprintf(stderr, "AudioALSA::set_params: ");
296 fprintf(stderr, _("failed to set output format.\n"));
300 err=snd_pcm_hw_params_set_channels(dsp,
304 fprintf(stderr, "AudioALSA::set_params: ");
305 fprintf(stderr, _("Configured ALSA device does not support %d channel operation.\n"),
310 err=snd_pcm_hw_params_set_rate_near(dsp,
312 (unsigned int*)&samplerate,
315 fprintf(stderr, "AudioALSA::set_params: ");
316 fprintf(stderr, _(" Configured ALSA device does not support %u Hz playback.\n"),
317 (unsigned int)samplerate);
321 // Buffers written must be equal to period_time
323 int period_time = (int)(1000000 * (double)samples / samplerate);
326 buffer_time = 10000000;
329 buffer_time = 2 * period_time;
333 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
334 snd_pcm_hw_params_set_buffer_time_near(dsp,
336 (unsigned int*)&buffer_time,
338 snd_pcm_hw_params_set_period_time_near(dsp,
340 (unsigned int*)&period_time,
342 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
343 err = snd_pcm_hw_params(dsp, params);
345 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
349 snd_pcm_uframes_t chunk_size = 1024;
350 snd_pcm_uframes_t buffer_size = 262144;
351 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
352 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
353 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
355 snd_pcm_sw_params_current(dsp, swparams);
356 //snd_pcm_uframes_t xfer_align = 1;
357 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
358 //unsigned int sleep_min = 0;
359 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
360 period_size = chunk_size;
361 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
362 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
363 if(snd_pcm_sw_params(dsp, swparams) < 0) {
364 /* we can continue staggering along even if this fails */
365 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
368 device->device_buffer = samples * bits / 8 * channels;
370 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
372 // snd_pcm_hw_params_free(params);
373 // snd_pcm_sw_params_free(swparams);
377 int AudioALSA::open_input()
379 char pcm_name[BCTEXTLEN];
380 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
384 device->in_channels = device->get_ichannels();
385 device->in_bits = device->in_config->alsa_in_bits;
387 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
388 //printf("AudioALSA::open_input %s\n", pcm_name);
390 err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
394 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
398 err = set_params(dsp_in, MODERECORD,
399 device->get_ichannels(),
400 device->in_config->alsa_in_bits,
401 device->in_samplerate,
404 fprintf(stderr, "AudioALSA::open_input: set_params failed. Aborting sampling.\n");
412 int AudioALSA::open_output()
414 char pcm_name[BCTEXTLEN];
415 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
416 int open_mode = SND_PCM_NONBLOCK;
419 device->out_channels = device->get_ochannels();
420 device->out_bits = device->out_config->alsa_out_bits;
422 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
423 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
424 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
426 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
431 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
435 err = set_params(dsp_out, MODEPLAY,
436 device->get_ochannels(),
437 device->out_config->alsa_out_bits,
438 device->out_samplerate,
439 device->out_samples);
441 fprintf(stderr, "AudioALSA::open_output: set_params failed. Aborting playback.\n");
450 int AudioALSA::stop_output()
452 //printf("AudioALSA::stop_output\n");
453 if(!device->out_config->interrupt_workaround)
456 snd_pcm_drop(get_output());
463 int AudioALSA::close_output()
465 //printf("AudioALSA::close_output\n");
466 if(device->w && dsp_out) {
468 snd_pcm_close(dsp_out);
474 int AudioALSA::close_input()
476 //printf("AudioALSA::close_input\n");
477 if(device->r && dsp_in) {
478 // snd_pcm_reset(dsp_in);
479 snd_pcm_drop(dsp_in);
480 snd_pcm_drain(dsp_in);
481 snd_pcm_close(dsp_in);
487 int AudioALSA::close_all()
489 //printf("AudioALSA::close_all\n");
500 int64_t AudioALSA::device_position()
502 timer_lock->lock("AudioALSA::device_position");
503 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
504 int64_t result = buffer_position - delay + delta;
505 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
506 // buffer_position, delta, delay, result);
507 timer_lock->unlock();
511 int AudioALSA::read_buffer(char *buffer, int size)
513 //printf("AudioALSA::read_buffer 1\n");
516 int frame_size = (device->in_bits / 8) * device->get_ichannels();
525 while(attempts < 1 && !done)
527 snd_pcm_uframes_t frames = size / frame_size;
528 result = snd_pcm_readi(get_input(), buffer, frames);
531 printf("AudioALSA::read_buffer overrun at sample %jd\n",
532 device->total_samples_read);
533 // snd_pcm_resume(get_input());
534 close_input(); open_input();
539 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
544 int AudioALSA::write_buffer(char *buffer, int size)
546 //printf("AudioALSA::write_buffer %d\n",size);
547 // Don't give up and drop the buffer on the first error.
550 int sample_size = (device->out_bits / 8) * device->get_ochannels();
551 int samples = size / sample_size;
552 //printf("AudioALSA::write_buffer %d\n",samples);
554 snd_pcm_sframes_t delay = 0;
556 // static FILE *debug_fd = 0;
559 // debug_fd = fopen("/tmp/debug.pcm", "w");
561 // fwrite(buffer, size, 1, debug_fd);
565 if(!get_output()) return 0;
566 if( buffer_position == 0 )
569 AudioThread *audio_out = device->audio_out;
570 while( count > 0 && attempts < 2 && !done ) {
571 if( device->playback_interrupted ) break;
572 // Buffers written must be equal to period_time
573 audio_out->Thread::enable_cancel();
574 int ret = snd_pcm_avail_update(get_output());
575 if( ret >= period_size ) {
576 if( ret > count ) ret = count;
578 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
579 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
580 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
581 ret = snd_pcm_writei(get_output(),buffer,ret);
582 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
584 else if( ret >= 0 || ret == -EAGAIN ) {
585 ret = snd_pcm_wait(get_output(),15);
586 if( ret > 0 ) ret = 0;
588 audio_out->Thread::disable_cancel();
589 if( device->playback_interrupted ) break;
590 if( ret == 0 ) continue;
593 samples_written += ret;
594 if( (count-=ret) > 0 ) {
595 buffer += ret * sample_size;
602 printf("AudioALSA::write_buffer err %d(%s) at sample %jd\n",
603 ret, snd_strerror(ret), device->current_position());
605 // snd_pcm_resume(get_output());
606 snd_pcm_recover(get_output(), ret, 1);
607 // close_output(); open_output();
612 if( !interrupted && device->playback_interrupted )
615 //printf("AudioALSA::write_buffer interrupted\n");
621 timer_lock->lock("AudioALSA::write_buffer");
622 snd_pcm_delay(get_output(), &delay);
625 buffer_position += samples;
626 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
627 timer_lock->unlock();
632 //this delay seems to prevent a problem where the sound system outputs
633 //a lot of silence while waiting for the device drain to happen.
634 int AudioALSA::output_wait()
636 snd_pcm_sframes_t delay = 0;
637 snd_pcm_delay(get_output(), &delay);
638 if( delay <= 0 ) return 0;
639 int64_t udelay = 1e6 * delay / device->out_samplerate;
640 // don't allow more than 10 seconds
641 if( udelay > 10000000 ) udelay = 10000000;
642 while( udelay > 0 && !device->playback_interrupted ) {
643 int64_t usecs = udelay;
644 if( usecs > 100000 ) usecs = 100000;
648 if( device->playback_interrupted &&
649 !device->out_config->interrupt_workaround )
650 snd_pcm_drop(get_output());
654 int AudioALSA::flush_device()
656 //printf("AudioALSA::flush_device\n");
660 //this causes the output to stutter.
661 //snd_pcm_nonblock(get_output(), 0);
662 snd_pcm_drain(get_output());
663 //snd_pcm_nonblock(get_output(), 1);
668 int AudioALSA::interrupt_playback()
670 //printf("AudioALSA::interrupt_playback *********\n");
673 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
674 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
675 // if(!device->out_config->interrupt_workaround)
676 // snd_pcm_drop(get_output());
678 // Makes sure the current buffer finishes before stopping.
679 // snd_pcm_drain(get_output());
681 // The only way to ensure snd_pcm_writei exits, but
682 // got a lot of crashes when doing this.
683 // device->Thread::cancel();
689 snd_pcm_t* AudioALSA::get_output()
694 snd_pcm_t* AudioALSA::get_input()