version update, docs Features5 msg/txt, shuttle tweaks for build
[goodguy/cinelerra.git] / cinelerra-5.1 / 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 "language.h"
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                 alsa_titles->set_array_delete();
63                 AudioALSA::list_devices(alsa_titles, 0, MODEPLAY);
64                 alsa_titles->remove_all_objects();
65                 delete alsa_titles;
66         }
67         ~alsa_leaks() { snd_config_update_free_global(); }
68 } alsa_leak;
69
70 void AudioALSA::list_devices(ArrayList<char*> *names, ArrayList<char*> *pcm_names, int mode)
71 {
72         snd_ctl_t *handle;
73         int card, err, dev;
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;
78
79         switch(mode)
80         {
81                 case MODERECORD:
82                         stream = SND_PCM_STREAM_CAPTURE;
83                         break;
84                 case MODEPLAY:
85                         stream = SND_PCM_STREAM_PLAYBACK;
86                         break;
87         }
88
89
90         snd_ctl_card_info_alloca(&info);
91         snd_pcm_info_alloca(&pcminfo);
92
93         card = -1;
94 #define DEFAULT_DEVICE "default"
95         if( names )
96                 names->append(cstrdup(DEFAULT_DEVICE));
97         if( pcm_names )
98                 pcm_names->append(cstrdup(DEFAULT_DEVICE));
99
100         while(snd_card_next(&card) >= 0) {
101                 char name[BCTEXTLEN];
102                 if(card < 0) break;
103                 sprintf(name, "hw:%i", card);
104
105                 if((err = snd_ctl_open(&handle, name, 0)) < 0) {
106                         printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
107                         continue;
108                 }
109
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);
113                         continue;
114                 }
115
116                 dev = -1;
117
118                 while(1) {
119                         if(snd_ctl_pcm_next_device(handle, &dev) < 0)
120                                 printf("AudioALSA::list_devices: snd_ctl_pcm_next_device\n");
121
122                         if (dev < 0) break;
123
124                         snd_pcm_info_set_device(pcminfo, dev);
125                         snd_pcm_info_set_subdevice(pcminfo, 0);
126                         snd_pcm_info_set_stream(pcminfo, stream);
127
128                         if((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
129                                 if(err != -ENOENT)
130                                         printf("AudioALSA::list_devices card=%i: %s\n", card, snd_strerror(err));
131                                 continue;
132                         }
133
134                         if( pcm_names ) {
135                                 sprintf(string, "plughw:%d,%d", card, dev);
136 //                              strcpy(string, "cards.pcm.front");
137                                 pcm_names->append(cstrdup(string));
138                         }
139                         if( names ) {
140                                 sprintf(string, "%s #%d",
141                                         snd_ctl_card_info_get_name(info), dev);
142                                 names->append(cstrdup(string));
143                         }
144                 }
145
146                 snd_ctl_close(handle);
147         }
148
149 #ifdef HAVE_PACTL
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
154
155         const char *arg = 0;
156         switch( mode ) {
157                 case MODERECORD:
158                         arg = "source";
159                         break;
160                 case MODEPLAY:
161                         arg = "sink";
162                         break;
163         }
164         FILE *pactl = 0;
165         char line[BCTEXTLEN];
166         if( arg ) {
167                 sprintf(line, "LANGUAGE=en_US.UTF-8 pactl list %ss", arg);
168                 pactl = popen(line,"r");
169         }
170         if( pactl ) {
171                 snd_config_update();
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 : '_';
182                                 *sp++ = 0;  *id = 0;
183                                 if( names )
184                                         names->append(cstrdup(name));
185                                 continue;
186                         }
187                         if( sscanf(line, " Name: %s", device) != 1 ) continue;
188                         int len = strlen(pa_name);
189                         if( pcm_names )
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");
197                         snd_input_t *inp;
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);
202                 }
203                 pclose(pactl);
204         }
205 #endif
206 }
207
208 void AudioALSA::translate_name(char *output, char *input, int mode)
209 {
210         ArrayList<char*> titles;
211         titles.set_array_delete();
212
213         ArrayList<char*> pcm_titles;
214         pcm_titles.set_array_delete();
215
216         list_devices(&titles, &pcm_titles, mode);
217
218         sprintf(output, "default");
219         for(int i = 0; i < titles.total; i++)
220         {
221 //printf("AudioALSA::translate_name %s %s\n", titles.values[i], pcm_titles.values[i]);
222                 if(!strcasecmp(titles.values[i], input))
223                 {
224                         strcpy(output, pcm_titles.values[i]);
225                         break;
226                 }
227         }
228
229         titles.remove_all_objects();
230         pcm_titles.remove_all_objects();
231 }
232
233 snd_pcm_format_t AudioALSA::translate_format(int format)
234 {
235         switch(format)
236         {
237         case 8:
238                 return SND_PCM_FORMAT_S8;
239                 break;
240         case 16:
241                 return SND_PCM_FORMAT_S16_LE;
242                 break;
243         case 24:
244                 return SND_PCM_FORMAT_S24_LE;
245                 break;
246         case 32:
247                 return SND_PCM_FORMAT_S32_LE;
248                 break;
249         }
250         return SND_PCM_FORMAT_UNKNOWN;
251 }
252
253 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
254         int channels, int bits, int samplerate, int samples)
255 {
256         snd_pcm_hw_params_t *params;
257         snd_pcm_sw_params_t *swparams;
258         int err;
259
260         snd_pcm_hw_params_alloca(&params);
261         snd_pcm_sw_params_alloca(&swparams);
262         err = snd_pcm_hw_params_any(dsp, params);
263
264         if (err < 0) {
265                 fprintf(stderr, "AudioALSA::set_params: ");
266                 fprintf(stderr, _("no PCM configurations available\n"));
267                 return 1;
268         }
269
270         err=snd_pcm_hw_params_set_access(dsp,
271                 params,
272                 SND_PCM_ACCESS_RW_INTERLEAVED);
273         if(err) {
274                 fprintf(stderr, "AudioALSA::set_params: ");
275                 fprintf(stderr, _("failed to set up interleaved device access.\n"));
276                 return 1;
277         }
278
279         err=snd_pcm_hw_params_set_format(dsp,
280                 params,
281                 translate_format(bits));
282         if(err) {
283                 fprintf(stderr, "AudioALSA::set_params: ");
284                 fprintf(stderr, _("failed to set output format.\n"));
285                 return 1;
286         }
287
288         err=snd_pcm_hw_params_set_channels(dsp,
289                 params,
290                 channels);
291         if(err) {
292                 fprintf(stderr, "AudioALSA::set_params: ");
293                 fprintf(stderr, _("Configured ALSA device does not support %d channel operation.\n"),
294                         channels);
295                 return 1;
296         }
297
298         err=snd_pcm_hw_params_set_rate_near(dsp,
299                 params,
300                 (unsigned int*)&samplerate,
301                 (int*)0);
302         if(err) {
303                 fprintf(stderr, "AudioALSA::set_params: ");
304                 fprintf(stderr, _(" Configured ALSA device does not support %u Hz playback.\n"),
305                         (unsigned int)samplerate);
306                 return 1;
307         }
308
309 // Buffers written must be equal to period_time
310         int buffer_time = 0;
311         int period_time = (int)(1000000 * (double)samples / samplerate);
312         switch( mode ) {
313         case MODERECORD:
314                 buffer_time = 10000000;
315                 break;
316         case MODEPLAY:
317                 buffer_time = 2 * period_time;
318                 break;
319         }
320
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,
323                 params,
324                 (unsigned int*)&buffer_time,
325                 (int*)0);
326         snd_pcm_hw_params_set_period_time_near(dsp,
327                 params,
328                 (unsigned int*)&period_time,
329                 (int*)0);
330 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
331         err = snd_pcm_hw_params(dsp, params);
332         if(err < 0) {
333                 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
334                 return 1;
335         }
336
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);
342
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");
354         }
355
356         device->device_buffer = samples * bits / 8 * channels;
357         period_size /= 2;
358 //printf("AudioALSA::set_params 100 %d %d\n", samples,  device->device_buffer);
359
360 //      snd_pcm_hw_params_free(params);
361 //      snd_pcm_sw_params_free(swparams);
362         return 0;
363 }
364
365 int AudioALSA::open_input()
366 {
367         char pcm_name[BCTEXTLEN];
368         snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
369         int open_mode = 0;
370         int err;
371
372         device->in_channels = device->get_ichannels();
373         device->in_bits = device->in_config->alsa_in_bits;
374
375         translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
376 //printf("AudioALSA::open_input %s\n", pcm_name);
377
378         err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
379
380         if(err < 0) {
381                 dsp_in = 0;
382                 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
383                 return 1;
384         }
385
386         err = set_params(dsp_in, MODERECORD,
387                 device->get_ichannels(),
388                 device->in_config->alsa_in_bits,
389                 device->in_samplerate,
390                 device->in_samples);
391         if(err) {
392                 fprintf(stderr, "AudioALSA::open_input: set_params failed.  Aborting sampling.\n");
393                 close_input();
394                 return 1;
395         }
396
397         return 0;
398 }
399
400 int AudioALSA::open_output()
401 {
402         char pcm_name[BCTEXTLEN];
403         snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
404         int open_mode = SND_PCM_NONBLOCK;
405         int err;
406
407         device->out_channels = device->get_ochannels();
408         device->out_bits = device->out_config->alsa_out_bits;
409
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);
413
414         err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
415
416         if(err < 0)
417         {
418                 dsp_out = 0;
419                 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
420                 return 1;
421         }
422
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);
428         if(err) {
429                 fprintf(stderr, "AudioALSA::open_output: set_params failed.  Aborting playback.\n");
430                 close_output();
431                 return 1;
432         }
433
434         timer->update();
435         return 0;
436 }
437
438 int AudioALSA::stop_output()
439 {
440 //printf("AudioALSA::stop_output\n");
441         if(!device->out_config->interrupt_workaround)
442         {
443                 if( get_output() )
444                         snd_pcm_drop(get_output());
445         }
446         else
447                 flush_device();
448         return 0;
449 }
450
451 int AudioALSA::close_output()
452 {
453 //printf("AudioALSA::close_output\n");
454         if(device->w && dsp_out) {
455                 stop_output();
456                 snd_pcm_close(dsp_out);
457                 dsp_out = 0;
458         }
459         return 0;
460 }
461
462 int AudioALSA::close_input()
463 {
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);
470                 dsp_in = 0;
471         }
472         return 0;
473 }
474
475 int AudioALSA::close_all()
476 {
477 //printf("AudioALSA::close_all\n");
478         close_input();
479         close_output();
480         buffer_position = 0;
481         samples_written = 0;
482         delay = 0;
483         interrupted = 0;
484         return 0;
485 }
486
487 // Undocumented
488 int64_t AudioALSA::device_position()
489 {
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();
496         return result;
497 }
498
499 int AudioALSA::read_buffer(char *buffer, int size)
500 {
501 //printf("AudioALSA::read_buffer 1\n");
502         int attempts = 0;
503         int done = 0;
504         int frame_size = (device->in_bits / 8) * device->get_ichannels();
505         int result = 0;
506
507         if(!get_input())
508         {
509                 sleep(1);
510                 return 0;
511         }
512
513         while(attempts < 1 && !done)
514         {
515                 snd_pcm_uframes_t frames = size / frame_size;
516                 result = snd_pcm_readi(get_input(), buffer, frames);
517                 if( result < 0)
518                 {
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();
523                         attempts++;
524                 }
525                 else
526                         done = 1;
527 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
528         }
529         return 0;
530 }
531
532 int AudioALSA::write_buffer(char *buffer, int size)
533 {
534 //printf("AudioALSA::write_buffer %d\n",size);
535 // Don't give up and drop the buffer on the first error.
536         int attempts = 0;
537         int done = 0;
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);
541         int count = samples;
542         snd_pcm_sframes_t delay = 0;
543
544 // static FILE *debug_fd = 0;
545 // if(!debug_fd)
546 // {
547 //      debug_fd = fopen("/tmp/debug.pcm", "w");
548 // }
549 // fwrite(buffer, size, 1, debug_fd);
550 // fflush(debug_fd);
551
552
553         if(!get_output()) return 0;
554         if( buffer_position == 0 )
555                 timer->update();
556
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;
565 //FILE *alsa_fp = 0;
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);
571                 }
572                 else if( ret >= 0 || ret == -EAGAIN ) {
573                         ret = snd_pcm_wait(get_output(),15);
574                         if( ret > 0 ) ret = 0;
575                 }
576                 audio_out->Thread::disable_cancel();
577                 if( device->playback_interrupted ) break;
578                 if( ret == 0 ) continue;
579
580                 if( ret > 0 ) {
581                         samples_written += ret;
582                         if( (count-=ret) > 0 ) {
583                                 buffer += ret * sample_size;
584                                 attempts = 0;
585                         }
586                         else
587                                 done = 1;
588                 }
589                 else {
590                         printf("AudioALSA::write_buffer err %d(%s) at sample %jd\n",
591                                 ret, snd_strerror(ret), device->current_position());
592                         Timer::delay(50);
593 //                      snd_pcm_resume(get_output());
594                         snd_pcm_recover(get_output(), ret, 1);
595 //                      close_output();  open_output();
596                         attempts++;
597                 }
598         }
599
600         if( !interrupted && device->playback_interrupted )
601         {
602                 interrupted = 1;
603 //printf("AudioALSA::write_buffer interrupted\n");
604                 stop_output();
605         }
606
607         if(done)
608         {
609                 timer_lock->lock("AudioALSA::write_buffer");
610                 snd_pcm_delay(get_output(), &delay);
611                 this->delay = delay;
612                 timer->update();
613                 buffer_position += samples;
614 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
615                 timer_lock->unlock();
616         }
617         return 0;
618 }
619
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()
623 {
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;
633                 usleep(usecs);
634                 udelay -= usecs;
635         }
636         if( device->playback_interrupted &&
637             !device->out_config->interrupt_workaround )
638                 snd_pcm_drop(get_output());
639         return 0;
640 }
641
642 int AudioALSA::flush_device()
643 {
644 //printf("AudioALSA::flush_device\n");
645         if(get_output())
646         {
647                 output_wait();
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);
652         }
653         return 0;
654 }
655
656 int AudioALSA::interrupt_playback()
657 {
658 //printf("AudioALSA::interrupt_playback *********\n");
659 //      if(get_output())
660 //      {
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());
665
666 // Makes sure the current buffer finishes before stopping.
667 //              snd_pcm_drain(get_output());
668
669 // The only way to ensure snd_pcm_writei exits, but
670 // got a lot of crashes when doing this.
671 //              device->Thread::cancel();
672 //      }
673         return 0;
674 }
675
676
677 snd_pcm_t* AudioALSA::get_output()
678 {
679         return dsp_out;
680 }
681
682 snd_pcm_t* AudioALSA::get_input()
683 {
684         return dsp_in;
685 }
686
687 #endif