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 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;
78 devices->set_array_delete();
84 stream = SND_PCM_STREAM_CAPTURE;
87 stream = SND_PCM_STREAM_PLAYBACK;
92 snd_ctl_card_info_alloca(&info);
93 snd_pcm_info_alloca(&pcminfo);
96 #define DEFAULT_DEVICE "default"
97 char *result = new char[strlen(DEFAULT_DEVICE) + 1];
98 devices->append(result);
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 void 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);
275 printf("AudioALSA::set_params: no PCM configurations available\n");
279 snd_pcm_hw_params_set_access(dsp,
281 SND_PCM_ACCESS_RW_INTERLEAVED);
282 snd_pcm_hw_params_set_format(dsp,
284 translate_format(bits));
285 snd_pcm_hw_params_set_channels(dsp,
288 snd_pcm_hw_params_set_rate_near(dsp,
290 (unsigned int*)&samplerate,
293 // Buffers written must be equal to period_time
295 int period_time = (int)(1000000 * (double)samples / samplerate);
298 buffer_time = 10000000;
301 buffer_time = 2 * period_time;
305 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
306 snd_pcm_hw_params_set_buffer_time_near(dsp,
308 (unsigned int*)&buffer_time,
310 snd_pcm_hw_params_set_period_time_near(dsp,
312 (unsigned int*)&period_time,
314 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
315 err = snd_pcm_hw_params(dsp, params);
317 printf("AudioALSA::set_params: hw_params failed\n");
321 snd_pcm_uframes_t chunk_size = 1024;
322 snd_pcm_uframes_t buffer_size = 262144;
323 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
324 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
325 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
327 snd_pcm_sw_params_current(dsp, swparams);
328 //snd_pcm_uframes_t xfer_align = 1;
329 //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
330 //unsigned int sleep_min = 0;
331 //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
332 period_size = chunk_size;
333 err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
334 //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
335 if(snd_pcm_sw_params(dsp, swparams) < 0) {
336 printf("AudioALSA::set_params: snd_pcm_sw_params failed\n");
339 device->device_buffer = samples * bits / 8 * channels;
341 //printf("AudioALSA::set_params 100 %d %d\n", samples, device->device_buffer);
343 // snd_pcm_hw_params_free(params);
344 // snd_pcm_sw_params_free(swparams);
347 int AudioALSA::open_input()
349 char pcm_name[BCTEXTLEN];
350 snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
354 device->in_channels = device->get_ichannels();
355 device->in_bits = device->in_config->alsa_in_bits;
357 translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
358 //printf("AudioALSA::open_input %s\n", pcm_name);
360 err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
364 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
368 set_params(dsp_in, MODERECORD,
369 device->get_ichannels(),
370 device->in_config->alsa_in_bits,
371 device->in_samplerate,
377 int AudioALSA::open_output()
379 char pcm_name[BCTEXTLEN];
380 snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
381 int open_mode = SND_PCM_NONBLOCK;
384 device->out_channels = device->get_ochannels();
385 device->out_bits = device->out_config->alsa_out_bits;
387 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
388 translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
389 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
391 err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
396 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
400 set_params(dsp_out, MODEPLAY,
401 device->get_ochannels(),
402 device->out_config->alsa_out_bits,
403 device->out_samplerate,
404 device->out_samples);
409 int AudioALSA::stop_output()
411 //printf("AudioALSA::stop_output\n");
412 if(!device->out_config->interrupt_workaround)
415 snd_pcm_drop(get_output());
422 int AudioALSA::close_output()
424 //printf("AudioALSA::close_output\n");
425 if(device->w && dsp_out) {
427 snd_pcm_close(dsp_out);
433 int AudioALSA::close_input()
435 //printf("AudioALSA::close_input\n");
436 if(device->r && dsp_in) {
437 // snd_pcm_reset(dsp_in);
438 snd_pcm_drop(dsp_in);
439 snd_pcm_drain(dsp_in);
440 snd_pcm_close(dsp_in);
446 int AudioALSA::close_all()
448 //printf("AudioALSA::close_all\n");
459 int64_t AudioALSA::device_position()
461 timer_lock->lock("AudioALSA::device_position");
462 int64_t delta = timer->get_scaled_difference(device->out_samplerate);
463 int64_t result = buffer_position - delay + delta;
464 //printf("AudioALSA::device_position 1 w=" _LD " dt=" _LD " dly=%d pos=" _LD "\n",
465 // buffer_position, delta, delay, result);
466 timer_lock->unlock();
470 int AudioALSA::read_buffer(char *buffer, int size)
472 //printf("AudioALSA::read_buffer 1\n");
475 int frame_size = (device->in_bits / 8) * device->get_ichannels();
484 while(attempts < 1 && !done)
486 snd_pcm_uframes_t frames = size / frame_size;
487 result = snd_pcm_readi(get_input(), buffer, frames);
490 printf("AudioALSA::read_buffer overrun at sample " _LD "\n",
491 device->total_samples_read);
492 // snd_pcm_resume(get_input());
493 close_input(); open_input();
498 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
503 int AudioALSA::write_buffer(char *buffer, int size)
505 //printf("AudioALSA::write_buffer %d\n",size);
506 // Don't give up and drop the buffer on the first error.
509 int sample_size = (device->out_bits / 8) * device->get_ochannels();
510 int samples = size / sample_size;
511 //printf("AudioALSA::write_buffer %d\n",samples);
513 snd_pcm_sframes_t delay = 0;
515 // static FILE *debug_fd = 0;
518 // debug_fd = fopen("/tmp/debug.pcm", "w");
520 // fwrite(buffer, size, 1, debug_fd);
524 if(!get_output()) return 0;
525 if( buffer_position == 0 )
528 AudioThread *audio_out = device->audio_out;
529 while(attempts < 2 && !done && !device->playback_interrupted)
531 // Buffers written must be equal to period_time
532 audio_out->Thread::enable_cancel();
533 int ret = snd_pcm_avail_update(get_output());
534 if( ret >= period_size ) {
535 if( ret > count ) ret = count;
537 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
538 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
539 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
540 ret = snd_pcm_writei(get_output(),buffer,ret);
541 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
543 else if( ret >= 0 || ret == -EAGAIN ) {
544 ret = snd_pcm_wait(get_output(),15);
545 if( ret > 0 ) ret = 0;
547 audio_out->Thread::disable_cancel();
548 if( ret == 0 ) continue;
551 samples_written += ret;
552 if( (count-=ret) > 0 ) {
553 buffer += ret * sample_size;
560 printf("AudioALSA::write_buffer err %d(%s) at sample " _LD "\n",
561 ret, snd_strerror(ret), device->current_position());
563 // snd_pcm_resume(get_output());
564 snd_pcm_recover(get_output(), ret, 1);
565 // close_output(); open_output();
570 if( !interrupted && device->playback_interrupted )
573 //printf("AudioALSA::write_buffer interrupted\n");
579 timer_lock->lock("AudioALSA::write_buffer");
580 snd_pcm_delay(get_output(), &delay);
583 buffer_position += samples;
584 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
585 timer_lock->unlock();
590 //this delay seems to prevent a problem where the sound system outputs
591 //a lot of silence while waiting for the device drain to happen.
592 int AudioALSA::output_wait()
594 snd_pcm_sframes_t delay = 0;
595 snd_pcm_delay(get_output(), &delay);
596 if( delay <= 0 ) return 0;
597 int64_t udelay = 1e6 * delay / device->out_samplerate;
598 // don't allow more than 10 seconds
599 if( udelay > 10000000 ) udelay = 10000000;
600 while( udelay > 0 && !device->playback_interrupted ) {
601 int64_t usecs = udelay;
602 if( usecs > 100000 ) usecs = 100000;
606 if( device->playback_interrupted &&
607 !device->out_config->interrupt_workaround )
608 snd_pcm_drop(get_output());
612 int AudioALSA::flush_device()
614 //printf("AudioALSA::flush_device\n");
618 //this causes the output to stutter.
619 //snd_pcm_nonblock(get_output(), 0);
620 snd_pcm_drain(get_output());
621 //snd_pcm_nonblock(get_output(), 1);
626 int AudioALSA::interrupt_playback()
628 //printf("AudioALSA::interrupt_playback *********\n");
631 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
632 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
633 // if(!device->out_config->interrupt_workaround)
634 // snd_pcm_drop(get_output());
636 // Makes sure the current buffer finishes before stopping.
637 // snd_pcm_drain(get_output());
639 // The only way to ensure snd_pcm_writei exits, but
640 // got a lot of crashes when doing this.
641 // device->Thread::cancel();
647 snd_pcm_t* AudioALSA::get_output()
652 snd_pcm_t* AudioALSA::get_input()