modify clr btn 16 plugins, add regdmp for sigtraps, rework mask_engine, mask rotate...
[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: return SND_PCM_FORMAT_S8;
238         case 16: return SND_PCM_FORMAT_S16_LE;
239         case 24: return SND_PCM_FORMAT_S24_LE;
240         case 32: return SND_PCM_FORMAT_S32_LE;
241         }
242         return SND_PCM_FORMAT_UNKNOWN;
243 }
244
245 int AudioALSA::set_params(snd_pcm_t *dsp, int mode,
246         int channels, int bits, int samplerate, int samples)
247 {
248         snd_pcm_hw_params_t *params;
249         snd_pcm_sw_params_t *swparams;
250         int err;
251
252         snd_pcm_hw_params_alloca(&params);
253         snd_pcm_sw_params_alloca(&swparams);
254         err = snd_pcm_hw_params_any(dsp, params);
255
256         if (err < 0) {
257                 fprintf(stderr, "AudioALSA::set_params: ");
258                 fprintf(stderr, _("no PCM configurations available\n"));
259                 return 1;
260         }
261
262         err=snd_pcm_hw_params_set_access(dsp,
263                 params,
264                 SND_PCM_ACCESS_RW_INTERLEAVED);
265         if(err) {
266                 fprintf(stderr, "AudioALSA::set_params: ");
267                 fprintf(stderr, _("failed to set up interleaved device access.\n"));
268                 return 1;
269         }
270
271         err=snd_pcm_hw_params_set_format(dsp,
272                 params,
273                 translate_format(bits));
274         if(err) {
275                 fprintf(stderr, "AudioALSA::set_params: ");
276                 fprintf(stderr, _("failed to set output format.\n"));
277                 return 1;
278         }
279
280         err=snd_pcm_hw_params_set_channels(dsp,
281                 params,
282                 channels);
283         if(err) {
284                 fprintf(stderr, "AudioALSA::set_params: ");
285                 fprintf(stderr, _("Configured ALSA device does not support %d channel operation.\n"),
286                         channels);
287                 return 1;
288         }
289
290         err=snd_pcm_hw_params_set_rate_near(dsp,
291                 params,
292                 (unsigned int*)&samplerate,
293                 (int*)0);
294         if(err) {
295                 fprintf(stderr, "AudioALSA::set_params: ");
296                 fprintf(stderr, _(" Configured ALSA device does not support %u Hz playback.\n"),
297                         (unsigned int)samplerate);
298                 return 1;
299         }
300
301 // Buffers written must be equal to period_time
302         int buffer_time = 0;
303         int period_time = (int)(1000000 * (double)samples / samplerate);
304         switch( mode ) {
305         case MODERECORD:
306                 buffer_time = 10000000;
307                 break;
308         case MODEPLAY:
309                 buffer_time = 2 * period_time;
310                 break;
311         }
312
313 //printf("AudioALSA::set_params 1 %d %d %d\n", samples, buffer_time, period_time);
314         snd_pcm_hw_params_set_buffer_time_near(dsp,
315                 params,
316                 (unsigned int*)&buffer_time,
317                 (int*)0);
318         snd_pcm_hw_params_set_period_time_near(dsp,
319                 params,
320                 (unsigned int*)&period_time,
321                 (int*)0);
322 //printf("AudioALSA::set_params 5 %d %d\n", buffer_time, period_time);
323         err = snd_pcm_hw_params(dsp, params);
324         if(err < 0) {
325                 fprintf(stderr, "AudioALSA::set_params: hw_params failed\n");
326                 return 1;
327         }
328
329         snd_pcm_uframes_t chunk_size = 1024;
330         snd_pcm_uframes_t buffer_size = 262144;
331         snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
332         snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
333 //printf("AudioALSA::set_params 10 %d %d\n", chunk_size, buffer_size);
334
335         snd_pcm_sw_params_current(dsp, swparams);
336         //snd_pcm_uframes_t xfer_align = 1;
337         //snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
338         //unsigned int sleep_min = 0;
339         //err = snd_pcm_sw_params_set_sleep_min(dsp, swparams, sleep_min);
340         period_size = chunk_size;
341         err = snd_pcm_sw_params_set_avail_min(dsp, swparams, period_size);
342         //err = snd_pcm_sw_params_set_xfer_align(dsp, swparams, xfer_align);
343         if(snd_pcm_sw_params(dsp, swparams) < 0) {
344                 /* we can continue staggering along even if this fails */
345                 fprintf(stderr, "AudioALSA::set_params: snd_pcm_sw_params failed\n");
346         }
347
348         device->device_buffer = samples * bits / 8 * channels;
349         period_size /= 2;
350 //printf("AudioALSA::set_params 100 %d %d\n", samples,  device->device_buffer);
351
352 //      snd_pcm_hw_params_free(params);
353 //      snd_pcm_sw_params_free(swparams);
354         return 0;
355 }
356
357 int AudioALSA::open_input()
358 {
359         char pcm_name[BCTEXTLEN];
360         snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
361         int open_mode = 0;
362         int err;
363
364         device->in_channels = device->get_ichannels();
365         device->in_bits = device->in_config->alsa_in_bits;
366
367         translate_name(pcm_name, device->in_config->alsa_in_device,MODERECORD);
368 //printf("AudioALSA::open_input %s\n", pcm_name);
369
370         err = snd_pcm_open(&dsp_in, pcm_name, stream, open_mode);
371
372         if(err < 0) {
373                 dsp_in = 0;
374                 printf("AudioALSA::open_input: %s\n", snd_strerror(err));
375                 return 1;
376         }
377
378         err = set_params(dsp_in, MODERECORD,
379                 device->get_ichannels(),
380                 device->in_config->alsa_in_bits,
381                 device->in_samplerate,
382                 device->in_samples);
383         if(err) {
384                 fprintf(stderr, "AudioALSA::open_input: set_params failed.  Aborting sampling.\n");
385                 close_input();
386                 return 1;
387         }
388
389         return 0;
390 }
391
392 int AudioALSA::open_output()
393 {
394         char pcm_name[BCTEXTLEN];
395         snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
396         int open_mode = SND_PCM_NONBLOCK;
397         int err;
398
399         device->out_channels = device->get_ochannels();
400         device->out_bits = device->out_config->alsa_out_bits;
401
402 //printf("AudioALSA::open_output out_device %s\n", device->out_config->alsa_out_device);
403         translate_name(pcm_name, device->out_config->alsa_out_device,MODEPLAY);
404 //printf("AudioALSA::open_output pcm_name %s\n", pcm_name);
405
406         err = snd_pcm_open(&dsp_out, pcm_name, stream, open_mode);
407
408         if(err < 0)
409         {
410                 dsp_out = 0;
411                 printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
412                 return 1;
413         }
414
415         err = set_params(dsp_out, MODEPLAY,
416                 device->get_ochannels(),
417                 device->out_config->alsa_out_bits,
418                 device->out_samplerate,
419                 device->out_samples);
420         if(err) {
421                 fprintf(stderr, "AudioALSA::open_output: set_params failed.  Aborting playback.\n");
422                 close_output();
423                 return 1;
424         }
425
426         timer->update();
427         return 0;
428 }
429
430 int AudioALSA::stop_output()
431 {
432 //printf("AudioALSA::stop_output\n");
433         if(!device->out_config->interrupt_workaround)
434         {
435                 if( get_output() )
436                         snd_pcm_drop(get_output());
437         }
438         else
439                 flush_device();
440         return 0;
441 }
442
443 int AudioALSA::close_output()
444 {
445 //printf("AudioALSA::close_output\n");
446         if(device->w && dsp_out) {
447                 stop_output();
448                 snd_pcm_close(dsp_out);
449                 dsp_out = 0;
450         }
451         return 0;
452 }
453
454 int AudioALSA::close_input()
455 {
456 //printf("AudioALSA::close_input\n");
457         if(device->r && dsp_in) {
458 //              snd_pcm_reset(dsp_in);
459                 snd_pcm_drop(dsp_in);
460                 snd_pcm_drain(dsp_in);
461                 snd_pcm_close(dsp_in);
462                 dsp_in = 0;
463         }
464         return 0;
465 }
466
467 int AudioALSA::close_all()
468 {
469 //printf("AudioALSA::close_all\n");
470         close_input();
471         close_output();
472         buffer_position = 0;
473         samples_written = 0;
474         delay = 0;
475         interrupted = 0;
476         return 0;
477 }
478
479 // Undocumented
480 int64_t AudioALSA::device_position()
481 {
482         timer_lock->lock("AudioALSA::device_position");
483         int64_t delta = timer->get_scaled_difference(device->out_samplerate);
484         int64_t result = buffer_position - delay + delta;
485 //printf("AudioALSA::device_position 1 w=%jd dt=%jd dly=%d pos=%jd\n",
486 // buffer_position, delta, delay, result);
487         timer_lock->unlock();
488         return result;
489 }
490
491 int AudioALSA::read_buffer(char *buffer, int size)
492 {
493 //printf("AudioALSA::read_buffer 1\n");
494         int attempts = 0;
495         int done = 0;
496         int frame_size = (device->in_bits / 8) * device->get_ichannels();
497         int result = 0;
498
499         if(!get_input())
500         {
501                 sleep(1);
502                 return 0;
503         }
504
505         while(attempts < 1 && !done)
506         {
507                 snd_pcm_uframes_t frames = size / frame_size;
508                 result = snd_pcm_readi(get_input(), buffer, frames);
509                 if( result < 0)
510                 {
511                         printf("AudioALSA::read_buffer overrun at sample %jd\n",
512                                 device->total_samples_read);
513 //                      snd_pcm_resume(get_input());
514                         close_input();  open_input();
515                         attempts++;
516                 }
517                 else
518                         done = 1;
519 //printf("AudioALSA::read_buffer %d result=%d done=%d\n", __LINE__, result, done);
520         }
521         return 0;
522 }
523
524 int AudioALSA::write_buffer(char *buffer, int size)
525 {
526 //printf("AudioALSA::write_buffer %d\n",size);
527 // Don't give up and drop the buffer on the first error.
528         int attempts = 0;
529         int done = 0;
530         int sample_size = (device->out_bits / 8) * device->get_ochannels();
531         int samples = size / sample_size;
532 //printf("AudioALSA::write_buffer %d\n",samples);
533         int count = samples;
534         snd_pcm_sframes_t delay = 0;
535
536 // static FILE *debug_fd = 0;
537 // if(!debug_fd)
538 // {
539 //      debug_fd = fopen("/tmp/debug.pcm", "w");
540 // }
541 // fwrite(buffer, size, 1, debug_fd);
542 // fflush(debug_fd);
543
544
545         if(!get_output()) return 0;
546         if( buffer_position == 0 )
547                 timer->update();
548
549         AudioThread *audio_out = device->audio_out;
550         while( count > 0 && attempts < 2 && !done ) {
551                 if( device->playback_interrupted ) break;
552 // Buffers written must be equal to period_time
553                 audio_out->Thread::enable_cancel();
554                 int ret = snd_pcm_avail_update(get_output());
555                 if( ret >= period_size ) {
556                         if( ret > count ) ret = count;
557 //FILE *alsa_fp = 0;
558 //if( !alsa_fp ) alsa_fp = fopen("/tmp/alsa.raw","w");
559 //if( alsa_fp ) fwrite(buffer, sample_size, ret, alsa_fp);
560 //printf("AudioALSA::snd_pcm_writei start %d\n",count);
561                         ret = snd_pcm_writei(get_output(),buffer,ret);
562 //printf("AudioALSA::snd_pcm_writei done %d\n", ret);
563                 }
564                 else if( ret >= 0 || ret == -EAGAIN ) {
565                         ret = snd_pcm_wait(get_output(),15);
566                         if( ret > 0 ) ret = 0;
567                 }
568                 audio_out->Thread::disable_cancel();
569                 if( device->playback_interrupted ) break;
570                 if( ret == 0 ) continue;
571
572                 if( ret > 0 ) {
573                         samples_written += ret;
574                         if( (count-=ret) > 0 ) {
575                                 buffer += ret * sample_size;
576                                 attempts = 0;
577                         }
578                         else
579                                 done = 1;
580                 }
581                 else {
582                         printf("AudioALSA::write_buffer err %d(%s) at sample %jd\n",
583                                 ret, snd_strerror(ret), device->current_position());
584                         Timer::delay(50);
585 //                      snd_pcm_resume(get_output());
586                         snd_pcm_recover(get_output(), ret, 1);
587 //                      close_output();  open_output();
588                         attempts++;
589                 }
590         }
591
592         if( !interrupted && device->playback_interrupted )
593         {
594                 interrupted = 1;
595 //printf("AudioALSA::write_buffer interrupted\n");
596                 stop_output();
597         }
598
599         if(done)
600         {
601                 timer_lock->lock("AudioALSA::write_buffer");
602                 snd_pcm_delay(get_output(), &delay);
603                 this->delay = delay;
604                 timer->update();
605                 buffer_position += samples;
606 //printf("AudioALSA::write_buffer ** wrote %d, delay %d\n",samples,(int)delay);
607                 timer_lock->unlock();
608         }
609         return 0;
610 }
611
612 //this delay seems to prevent a problem where the sound system outputs
613 //a lot of silence while waiting for the device drain to happen.
614 int AudioALSA::output_wait()
615 {
616         snd_pcm_sframes_t delay = 0;
617         snd_pcm_delay(get_output(), &delay);
618         if( delay <= 0 ) return 0;
619         int64_t udelay = 1e6 * delay / device->out_samplerate;
620         // don't allow more than 10 seconds
621         if( udelay > 10000000 ) udelay = 10000000;
622         while( udelay > 0 && !device->playback_interrupted ) {
623                 int64_t usecs = udelay;
624                 if( usecs > 100000 ) usecs = 100000;
625                 usleep(usecs);
626                 udelay -= usecs;
627         }
628         if( device->playback_interrupted &&
629             !device->out_config->interrupt_workaround )
630                 snd_pcm_drop(get_output());
631         return 0;
632 }
633
634 int AudioALSA::flush_device()
635 {
636 //printf("AudioALSA::flush_device\n");
637         if(get_output())
638         {
639                 output_wait();
640                 //this causes the output to stutter.
641                 //snd_pcm_nonblock(get_output(), 0);
642                 snd_pcm_drain(get_output());
643                 //snd_pcm_nonblock(get_output(), 1);
644         }
645         return 0;
646 }
647
648 int AudioALSA::interrupt_playback()
649 {
650 //printf("AudioALSA::interrupt_playback *********\n");
651 //      if(get_output())
652 //      {
653 // Interrupts the playback but may not have caused snd_pcm_writei to exit.
654 // With some soundcards it causes snd_pcm_writei to freeze for a few seconds.
655 //              if(!device->out_config->interrupt_workaround)
656 //                      snd_pcm_drop(get_output());
657
658 // Makes sure the current buffer finishes before stopping.
659 //              snd_pcm_drain(get_output());
660
661 // The only way to ensure snd_pcm_writei exits, but
662 // got a lot of crashes when doing this.
663 //              device->Thread::cancel();
664 //      }
665         return 0;
666 }
667
668
669 snd_pcm_t* AudioALSA::get_output()
670 {
671         return dsp_out;
672 }
673
674 snd_pcm_t* AudioALSA::get_input()
675 {
676         return dsp_in;
677 }
678
679 #endif