initial commit
[goodguy/history.git] / cinelerra-5.0 / cinelerra / audioalsa.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  * 
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.
10  * 
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.
15  * 
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
19  * 
20  */
21
22 #include "audiodevice.h"
23 #include "audioalsa.h"
24 #include "bcsignals.h"
25 #include "format.inc"
26 #include "mutex.h"
27 #include "playbackconfig.h"
28 #include "preferences.h"
29 #include "recordconfig.h"
30
31 #include <errno.h>
32
33 #ifdef HAVE_ALSA
34
35 AudioALSA::AudioALSA(AudioDevice *device)
36  : AudioLowLevel(device)
37 {
38         buffer_position = 0;
39         samples_written = 0;
40         timer = new Timer;
41         delay = 0;
42         period_size = 0;
43         timer_lock = new Mutex("AudioALSA::timer_lock");
44         interrupted = 0;
45         dsp_in = 0;
46         dsp_out = 0;
47 }
48
49 AudioALSA::~AudioALSA()
50 {
51         delete timer_lock;
52         delete timer;
53 }
54
55 // leak checking
56 static class alsa_leaks
57 {
58 public:
59 // This is required in the top thread for Alsa to work
60         alsa_leaks() {
61                 ArrayList<char*> *alsa_titles = new ArrayList<char*>;
62                 AudioALSA::list_devices(alsa_titles, 0, MODEPLAY);
63                 alsa_titles->remove_all_objects();
64                 delete alsa_titles;
65         }
66         ~alsa_leaks() { snd_config_update_free_global(); }
67 } alsa_leak;
68
69 void AudioALSA::list_devices(ArrayList<char*> *devices, int pcm_title, int mode)
70 {
71         snd_ctl_t *handle;
72         int card, err, dev;
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;
77
78         devices->set_array_delete();
79
80
81         switch(mode)
82         {
83                 case MODERECORD:
84                         stream = SND_PCM_STREAM_CAPTURE;
85                         break;
86                 case MODEPLAY:
87                         stream = SND_PCM_STREAM_PLAYBACK;
88                         break;
89         }
90
91
92         snd_ctl_card_info_alloca(&info);
93         snd_pcm_info_alloca(&pcminfo);
94
95         card = -1;
96 #define DEFAULT_DEVICE "default"
97         char *result = new char[strlen(DEFAULT_DEVICE) + 1];
98         devices->append(result);
99         strcpy(result, DEFAULT_DEVICE);
100
101         while(snd_card_next(&card) >= 0)
102         {
103                 char name[BCTEXTLEN];
104                 if(card < 0) break;
105                 sprintf(name, "hw:%i", card);
106
107                 if((err = snd_ctl_open(&handle, name, 0)) < 0)
108                 {
109                         printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
110                         continue;
111                 }
112
113                 if((err = snd_ctl_card_info(handle, info)) < 0)
114                 {
115                         printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
116                         snd_ctl_close(handle);
117                         continue;
118                 }
119
120                 dev = -1;
121
122                 while(1)
123                 {
124                         if(snd_ctl_pcm_next_device(handle, &dev) < 0)
125                                 printf("AudioALSA::list_devices: snd_ctl_pcm_next_device\n");
126
127                         if (dev < 0)
128                                 break;
129
130                         snd_pcm_info_set_device(pcminfo, dev);
131                         snd_pcm_info_set_subdevice(pcminfo, 0);
132                         snd_pcm_info_set_stream(pcminfo, stream);
133
134                         if((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) 
135                         {
136                                 if(err != -ENOENT)
137                                         printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
138                                 continue;
139                         }
140
141                         if(pcm_title)
142                         {
143                                 sprintf(string, "plughw:%d,%d", card, dev);
144 //                              strcpy(string, "cards.pcm.front");
145                         }
146                         else
147                         {
148                                 sprintf(string, "%s #%d", 
149                                         snd_ctl_card_info_get_name(info), 
150                                         dev);
151                         }
152
153                         char *result = devices->append(new char[strlen(string) + 1]);
154                         strcpy(result, string);
155                 }
156
157
158
159                 snd_ctl_close(handle);
160         }
161
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
166
167         const char *arg = 0;
168         switch( mode ) {
169                 case MODERECORD:
170                         arg = "source";
171                         break;
172                 case MODEPLAY:
173                         arg = "sink";
174                         break;
175         }
176         FILE *pactl = 0;
177         char line[BCTEXTLEN];
178         if( arg ) {
179                 sprintf(line, "pactl list %ss", arg);
180                 pactl = popen(line,"r");
181         }
182         if( pactl ) {
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 : '_';
194                                 *sp++ = 0;  *id = 0;
195                                 if( !pcm_title )
196                                         devices->append(strcpy(new char[sp-name], name));
197                                 continue;
198                         }
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");
209                         snd_input_t *inp;
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);
214                 }
215                 pclose(pactl);
216         }
217 }
218
219 void AudioALSA::translate_name(char *output, char *input, int mode)
220 {
221         ArrayList<char*> titles;
222         ArrayList<char*> pcm_titles;
223         
224         list_devices(&titles, 0, mode);
225         list_devices(&pcm_titles, 1, mode);
226
227         sprintf(output, "default");     
228         for(int i = 0; i < titles.total; i++)
229         {
230 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
231                 if(!strcasecmp(titles.values[i], input))
232                 {
233                         strcpy(output, pcm_titles.values[i]);
234                         break;
235                 }
236         }
237         
238         titles.remove_all_objects();
239         pcm_titles.remove_all_objects();
240 }
241
242 snd_pcm_format_t AudioALSA::translate_format(int format)
243 {
244         switch(format)
245         {
246         case 8:
247                 return SND_PCM_FORMAT_S8;
248                 break;
249         case 16:
250                 return SND_PCM_FORMAT_S16_LE;
251                 break;
252         case 24:
253                 return SND_PCM_FORMAT_S24_LE;
254                 break;
255         case 32:
256                 return SND_PCM_FORMAT_S32_LE;
257                 break;
258         }
259         return SND_PCM_FORMAT_UNKNOWN;
260 }
261
262 void AudioALSA::set_params(snd_pcm_t *dsp, int mode,
263         int channels, int bits, int samplerate, int samples)
264 {
265         snd_pcm_hw_params_t *params;
266         snd_pcm_sw_params_t *swparams;
267         int err;
268
269         snd_pcm_hw_params_alloca(&params);
270         snd_pcm_sw_params_alloca(&swparams);
271         err = snd_pcm_hw_params_any(dsp, params);
272
273         if (err < 0) 
274         {
275                 printf("AudioALSA::set_params: no PCM configurations available\n");
276                 return;
277         }
278
279         snd_pcm_hw_params_set_access(dsp, 
280                 params,
281                 SND_PCM_ACCESS_RW_INTERLEAVED);
282         snd_pcm_hw_params_set_format(dsp, 
283                 params, 
284                 translate_format(bits));
285         snd_pcm_hw_params_set_channels(dsp, 
286                 params, 
287                 channels);
288         snd_pcm_hw_params_set_rate_near(dsp, 
289                 params, 
290                 (unsigned int*)&samplerate, 
291                 (int*)0);
292
293 // Buffers written must be equal to period_time
294         int buffer_time = 0;
295         int period_time = (int)(1000000 * (double)samples / samplerate);
296         switch( mode ) {
297         case MODERECORD:
298                 buffer_time = 10000000;
299                 break;
300         case MODEPLAY:
301                 buffer_time = 2 * period_time;
302                 break;
303         }
304
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, 
307                 params,
308                 (unsigned int*)&buffer_time, 
309                 (int*)0);
310         snd_pcm_hw_params_set_period_time_near(dsp, 
311                 params,
312                 (unsigned int*)&period_time, 
313                 (int*)0);
314 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
315         err = snd_pcm_hw_params(dsp, params);
316         if(err < 0) {
317                 printf("AudioALSA::set_params: hw_params failed\n");
318                 return;
319         }
320
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);
326
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");
337         }
338
339         device->device_buffer = samples * bits / 8 * channels;
340         period_size /= 2;
341 //printf("AudioALSA::set_params 100 %d %d\n", samples,  device->device_buffer);
342
343 //      snd_pcm_hw_params_free(params);
344 //      snd_pcm_sw_params_free(swparams);
345 }
346
347 int AudioALSA::open_input()
348 {
349         char pcm_name[BCTEXTLEN];
350         snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
351         int open_mode = 0;
352         int err;
353
354         device->in_channels = device->get_ichannels();
355         device->in_bits = device->in_config->alsa_in_bits;
356
357         translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
358 //printf("AudioALSA::open_input %s\n", pcm_name);
359
360         err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
361
362         if(err < 0)
363         {
364                 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
365                 return 1;
366         }
367
368         set_params(dsp_in, MODERECORD,
369                 device->get_ichannels(), 
370                 device->in_config->alsa_in_bits,
371                 device->in_samplerate,
372                 device->in_samples);
373
374         return 0;
375 }
376
377 int AudioALSA::open_output()
378 {
379         char pcm_name[BCTEXTLEN];
380         snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
381         int open_mode = SND_PCM_NONBLOCK;
382         int err;
383
384         device->out_channels = device->get_ochannels();
385         device->out_bits = device->out_config->alsa_out_bits;
386
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);
390
391         err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
392
393         if(err < 0)
394         {
395                 dsp_out = 0;
396                 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
397                 return 1;
398         }
399
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);
405         timer->update();
406         return 0;
407 }
408
409 int AudioALSA::stop_output()
410 {
411 //printf("AudioALSA::stop_output\n");
412         if(!device->out_config->interrupt_workaround)
413         {
414                 if( get_output() )
415                         snd_pcm_drop(get_output());
416         }
417         else
418                 flush_device();
419         return 0;
420 }
421
422 int AudioALSA::close_output()
423 {
424 //printf("AudioALSA::close_output\n");
425         if(device->w && dsp_out) {
426                 stop_output();
427                 snd_pcm_close(dsp_out);
428                 dsp_out = 0;
429         }
430         return 0;
431 }
432
433 int AudioALSA::close_input()
434 {
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);
441                 dsp_in = 0;
442         }
443         return 0;
444 }
445
446 int AudioALSA::close_all()
447 {
448 //printf("AudioALSA::close_all\n");
449         close_input();
450         close_output();
451         buffer_position = 0;
452         samples_written = 0;
453         delay = 0;
454         interrupted = 0;
455         return 0;
456 }
457
458 // Undocumented
459 int64_t AudioALSA::device_position()
460 {
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();
467         return result;
468 }
469
470 int AudioALSA::read_buffer(char *buffer, int size)
471 {
472 //printf("AudioALSA::read_buffer 1\n");
473         int attempts = 0;
474         int done = 0;
475         int frame_size = (device->in_bits / 8) * device->get_ichannels();
476         int result = 0;
477
478         if(!get_input())
479         {
480                 sleep(1);
481                 return 0;
482         }
483
484         while(attempts < 1 && !done)
485         {
486                 snd_pcm_uframes_t frames = size / frame_size;
487                 result = snd_pcm_readi(get_input(), buffer, frames);
488                 if( result < 0)
489                 {
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();
494                         attempts++;
495                 }
496                 else
497                         done = 1;
498 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
499         }
500         return 0;
501 }
502
503 int AudioALSA::write_buffer(char *buffer, int size)
504 {
505 //printf("AudioALSA::write_buffer %d\n",size);
506 // Don't give up and drop the buffer on the first error.
507         int attempts = 0;
508         int done = 0;
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);
512         int count = samples;
513         snd_pcm_sframes_t delay = 0;
514
515         if(!get_output()) return 0;
516         if( buffer_position == 0 )
517                 timer->update();
518
519         AudioThread *audio_out = device->audio_out;
520         while(attempts < 2 && !done && !device->playback_interrupted)
521         {
522 // Buffers written must be equal to period_time
523                 audio_out->Thread::enable_cancel();
524                 int ret = snd_pcm_avail_update(get_output());
525                 if( ret >= period_size ) {
526                         if( ret > count ) ret = count;
527 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
528                         ret = snd_pcm_writei(get_output(),buffer,ret);
529 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
530                 }
531                 else if( ret >= 0 || ret == -EAGAIN ) {
532                         ret = snd_pcm_wait(get_output(),15);
533                         if( ret > 0 ) ret = 0;
534                 }
535                 audio_out->Thread::disable_cancel();
536                 if( ret == 0 ) continue;
537
538                 if( ret > 0 ) {
539                         samples_written += ret;
540                         if( (count-=ret) > 0 ) {
541                                 buffer += ret * sample_size;
542                                 attempts = 0;
543                         }
544                         else
545                                 done = 1;
546                 }
547                 else {
548                         printf("AudioALSA::write_buffer err %d(%s) at sample " _LD "\n",
549                                 ret, snd_strerror(ret), device->current_position());
550                         Timer::delay(50);
551 //                      snd_pcm_resume(get_output());
552                         snd_pcm_recover(get_output(), ret, 1);
553 //                      close_output();  open_output();
554                         attempts++;
555                 }
556         }
557
558         if( !interrupted && device->playback_interrupted )
559         {
560                 interrupted = 1;
561 //printf("AudioALSA::write_buffer interrupted\n");
562                 stop_output();
563         }
564
565         if(done)
566         {
567                 timer_lock->lock("AudioALSA::write_buffer");
568                 snd_pcm_delay(get_output(), &delay);
569                 this->delay = delay;
570                 timer->update();
571                 buffer_position += samples;
572 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
573                 timer_lock->unlock();
574         }
575         return 0;
576 }
577
578 //this delay seems to prevent a problem where the sound system outputs
579 //a lot of silence while waiting for the device drain to happen.
580 int AudioALSA::output_wait()
581 {
582         snd_pcm_sframes_t delay = 0;
583         snd_pcm_delay(get_output(), &delay);
584         if( delay <= 0 ) return 0;
585         int64_t udelay = 1e6 * delay / device->out_samplerate;
586         // don't allow more than 10 seconds
587         if( udelay > 10000000 ) udelay = 10000000;
588         while( udelay > 0 && !device->playback_interrupted ) {
589                 int64_t usecs = udelay;
590                 if( usecs > 100000 ) usecs = 100000;
591                 usleep(usecs);
592                 udelay -= usecs;
593         }
594         if( device->playback_interrupted &&
595             !device->out_config->interrupt_workaround )
596                 snd_pcm_drop(get_output());
597         return 0;
598 }
599
600 int AudioALSA::flush_device()
601 {
602 //printf("AudioALSA::flush_device\n");
603         if(get_output())
604         {
605                 output_wait();
606                 //this causes the output to stutter.
607                 //snd_pcm_nonblock(get_output(), 0);
608                 snd_pcm_drain(get_output());
609                 //snd_pcm_nonblock(get_output(), 1);
610         }
611         return 0;
612 }
613
614 int AudioALSA::interrupt_playback()
615 {
616 //printf("AudioALSA::interrupt_playback *********\n");
617 //      if(get_output()) 
618 //      {
619 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
620 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
621 //              if(!device->out_config->interrupt_workaround)
622 //                      snd_pcm_drop(get_output());
623
624 // Makes sure the current buffer finishes before stopping.
625 //              snd_pcm_drain(get_output());
626
627 // The only way to ensure snd_pcm_writei exits, but
628 // got a lot of crashes when doing this.
629 //              device->Thread::cancel();
630 //      }
631         return 0;
632 }
633
634
635 snd_pcm_t* AudioALSA::get_output()
636 {
637         return dsp_out;
638 }
639
640 snd_pcm_t* AudioALSA::get_input()
641 {
642         return dsp_in;
643 }
644
645 #endif