da8f6786b3a40a505275395d12cd30100d2531f1
[profile/ivi/pulseaudio.git] / src / utils / padsp.c
1 /* $Id$ */
2
3 /***
4   This file is part of polypaudio.
5  
6   polypaudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10  
11   polypaudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public License
17   along with polypaudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #ifdef _FILE_OFFSET_BITS
27 #undef _FILE_OFFSET_BITS
28 #endif
29
30 #ifndef _LARGEFILE64_SOURCE
31 #define _LARGEFILE64_SOURCE 1
32 #endif
33
34 #include <sys/soundcard.h>
35 #include <sys/ioctl.h>
36 #include <pthread.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <dlfcn.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <string.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <signal.h>
46
47 #include <linux/sockios.h>
48
49 #include <polyp/polypaudio.h>
50 #include <polypcore/llist.h>
51 #include <polypcore/gccmacro.h>
52
53 typedef enum {
54     FD_INFO_MIXER,
55     FD_INFO_PLAYBACK
56 } fd_info_type_t;
57
58 typedef struct fd_info fd_info;
59
60 struct fd_info {
61     pthread_mutex_t mutex;
62     int ref;
63     int unusable;
64     
65     fd_info_type_t type;
66     int app_fd, thread_fd;
67
68     pa_sample_spec sample_spec;
69     size_t fragment_size;
70     unsigned n_fragments;
71
72     pa_threaded_mainloop *mainloop;
73     pa_context *context;
74     pa_stream *stream;
75
76     pa_io_event *io_event;
77
78     void *buf;
79
80     int operation_success;
81
82     pa_cvolume volume;
83     uint32_t sink_index;
84     int volume_modify_count;
85     
86     PA_LLIST_FIELDS(fd_info);
87 };
88
89 static int dsp_drain(fd_info *i);
90 static void fd_info_remove_from_list(fd_info *i);
91
92 static pthread_mutex_t fd_infos_mutex = PTHREAD_MUTEX_INITIALIZER;
93 static pthread_mutex_t func_mutex = PTHREAD_MUTEX_INITIALIZER;
94
95 static PA_LLIST_HEAD(fd_info, fd_infos) = NULL;
96
97 static int (*_ioctl)(int, int, void*) = NULL;
98 static int (*_close)(int) = NULL;
99 static int (*_open)(const char *, int, mode_t) = NULL;
100 static FILE* (*_fopen)(const char *path, const char *mode) = NULL;
101 static int (*_open64)(const char *, int, mode_t) = NULL;
102 static FILE* (*_fopen64)(const char *path, const char *mode) = NULL;
103 static int (*_fclose)(FILE *f) = NULL;
104 static int (*_access)(const char *, int) = NULL;
105
106 /* dlsym() violates ISO C, so confide the breakage into this function to
107  * avoid warnings. */
108 typedef void (*fnptr)(void);
109 static inline fnptr dlsym_fn(void *handle, const char *symbol) {
110     return (fnptr) (long) dlsym(handle, symbol);
111 }
112
113 #define LOAD_IOCTL_FUNC() \
114 do { \
115     pthread_mutex_lock(&func_mutex); \
116     if (!_ioctl)  \
117         _ioctl = (int (*)(int, int, void*)) dlsym_fn(RTLD_NEXT, "ioctl"); \
118     pthread_mutex_unlock(&func_mutex); \
119 } while(0)
120
121 #define LOAD_OPEN_FUNC() \
122 do { \
123     pthread_mutex_lock(&func_mutex); \
124     if (!_open) \
125         _open = (int (*)(const char *, int, mode_t)) dlsym_fn(RTLD_NEXT, "open"); \
126     pthread_mutex_unlock(&func_mutex); \
127 } while(0)
128
129 #define LOAD_OPEN64_FUNC() \
130 do { \
131     pthread_mutex_lock(&func_mutex); \
132     if (!_open64) \
133         _open64 = (int (*)(const char *, int, mode_t)) dlsym_fn(RTLD_NEXT, "open64"); \
134     pthread_mutex_unlock(&func_mutex); \
135 } while(0)
136
137 #define LOAD_CLOSE_FUNC() \
138 do { \
139     pthread_mutex_lock(&func_mutex); \
140     if (!_close) \
141         _close = (int (*)(int)) dlsym_fn(RTLD_NEXT, "close"); \
142     pthread_mutex_unlock(&func_mutex); \
143 } while(0)
144
145 #define LOAD_ACCESS_FUNC() \
146 do { \
147     pthread_mutex_lock(&func_mutex); \
148     if (!_access) \
149         _access = (int (*)(const char*, int)) dlsym_fn(RTLD_NEXT, "access"); \
150     pthread_mutex_unlock(&func_mutex); \
151 } while(0)
152
153 #define LOAD_FOPEN_FUNC() \
154 do { \
155     pthread_mutex_lock(&func_mutex); \
156     if (!_fopen) \
157         _fopen = (FILE* (*)(const char *, const char*)) dlsym_fn(RTLD_NEXT, "fopen"); \
158     pthread_mutex_unlock(&func_mutex); \
159 } while(0)
160
161 #define LOAD_FOPEN64_FUNC() \
162 do { \
163     pthread_mutex_lock(&func_mutex); \
164     if (!_fopen64) \
165         _fopen64 = (FILE* (*)(const char *, const char*)) dlsym_fn(RTLD_NEXT, "fopen64"); \
166     pthread_mutex_unlock(&func_mutex); \
167 } while(0)
168
169 #define LOAD_FCLOSE_FUNC() \
170 do { \
171     pthread_mutex_lock(&func_mutex); \
172     if (!_fclose) \
173         _fclose = (int (*)(FILE *)) dlsym_fn(RTLD_NEXT, "fclose"); \
174     pthread_mutex_unlock(&func_mutex); \
175 } while(0)
176
177 #define CONTEXT_CHECK_DEAD_GOTO(i, label) do { \
178 if (!(i)->context || pa_context_get_state((i)->context) != PA_CONTEXT_READY) { \
179     debug(__FILE__": Not connected: %s", (i)->context ? pa_strerror(pa_context_errno((i)->context)) : "NULL"); \
180     goto label; \
181 } \
182 } while(0);
183
184 #define STREAM_CHECK_DEAD_GOTO(i, label) do { \
185 if (!(i)->context || pa_context_get_state((i)->context) != PA_CONTEXT_READY || \
186     !(i)->stream || pa_stream_get_state((i)->stream) != PA_STREAM_READY) { \
187     debug(__FILE__": Not connected: %s", (i)->context ? pa_strerror(pa_context_errno((i)->context)) : "NULL"); \
188     goto label; \
189 } \
190 } while(0);
191
192 static void debug(const char *format, ...) PA_GCC_PRINTF_ATTR(1,2);
193
194 static void debug(const char *format, ...) {
195     va_list ap;
196     if (getenv("PADSP_DEBUG")) {
197         va_start(ap, format);
198         vfprintf(stderr, format, ap);
199         va_end(ap);
200     }
201 }
202
203 static int padsp_disabled(void) {
204     static int *sym;
205     static int sym_resolved = 0;
206
207     /* If the current process has a symbol __padsp_disabled__ we use
208      * it to detect whether we should enable our stuff or not. A
209      * program needs to be compiled with -rdynamic for this to work!
210      * The symbol must be an int containing a three bit bitmask: bit 1
211      * -> disable /dev/dsp emulation, bit 2 -> disable /dev/sndstat
212      * emulation, bit 3 -> disable /dev/mixer emulation. Hence a value
213      * of 7 disables padsp entirely. */
214     
215     pthread_mutex_lock(&func_mutex);
216     if (!sym_resolved) {
217         sym = (int*) dlsym(RTLD_DEFAULT, "__padsp_disabled__");
218         sym_resolved = 1;
219
220     }
221     pthread_mutex_unlock(&func_mutex);
222
223     if (!sym)
224         return 0;
225     
226     return *sym;
227 }
228
229 static int dsp_cloak_enable(void) {
230     if (padsp_disabled() & 1)
231         return 0;
232     
233     if (getenv("PADSP_NO_DSP"))
234         return 0;
235
236     return 1;
237 }
238
239 static int sndstat_cloak_enable(void) {
240     if (padsp_disabled() & 2)
241         return 0;
242
243     if (getenv("PADSP_NO_SNDSTAT"))
244         return 0;
245
246     return 1;
247 }
248
249 static int mixer_cloak_enable(void) {
250     if (padsp_disabled() & 4)
251         return 0;
252
253     if (getenv("PADSP_NO_MIXER"))
254         return 0;
255
256     return 1;
257 }
258 static pthread_key_t recursion_key;
259
260 static void recursion_key_alloc(void) {
261     pthread_key_create(&recursion_key, NULL);
262 }
263
264 static int function_enter(void) {
265     /* Avoid recursive calls */
266     static pthread_once_t recursion_key_once = PTHREAD_ONCE_INIT;
267     pthread_once(&recursion_key_once, recursion_key_alloc);
268     
269     if (pthread_getspecific(recursion_key))
270         return 0;
271
272     pthread_setspecific(recursion_key, (void*) 1);
273     return 1;
274 }
275
276 static void function_exit(void) {
277     pthread_setspecific(recursion_key, NULL);
278 }
279
280 static void fd_info_free(fd_info *i) {
281     assert(i);
282
283     debug(__FILE__": freeing fd info (fd=%i)\n", i->app_fd);
284
285     dsp_drain(i);
286     
287     if (i->mainloop)
288         pa_threaded_mainloop_stop(i->mainloop);
289     
290     if (i->stream) {
291         pa_stream_disconnect(i->stream);
292         pa_stream_unref(i->stream);
293     }
294
295     if (i->context) {
296         pa_context_disconnect(i->context);
297         pa_context_unref(i->context);
298     }
299     
300     if (i->mainloop)
301         pa_threaded_mainloop_free(i->mainloop);
302
303     if (i->app_fd >= 0) {
304         LOAD_CLOSE_FUNC();
305         _close(i->app_fd);
306     }
307
308     if (i->thread_fd >= 0) {
309         LOAD_CLOSE_FUNC();
310         _close(i->thread_fd);
311     }
312
313     free(i->buf);
314
315     pthread_mutex_destroy(&i->mutex);
316     free(i);
317 }
318
319 static fd_info *fd_info_ref(fd_info *i) {
320     assert(i);
321     
322     pthread_mutex_lock(&i->mutex);
323     assert(i->ref >= 1);
324     i->ref++;
325
326 /*     debug(__FILE__": ref++, now %i\n", i->ref); */
327     pthread_mutex_unlock(&i->mutex);
328
329     return i;
330 }
331
332 static void fd_info_unref(fd_info *i) {
333     int r;
334     pthread_mutex_lock(&i->mutex);
335     assert(i->ref >= 1);
336     r = --i->ref;
337 /*     debug(__FILE__": ref--, now %i\n", i->ref); */
338     pthread_mutex_unlock(&i->mutex);
339
340     if (r <= 0)
341         fd_info_free(i);
342 }
343
344 static void context_state_cb(pa_context *c, void *userdata) {
345     fd_info *i = userdata;
346     assert(c);
347
348     switch (pa_context_get_state(c)) {
349         case PA_CONTEXT_READY:
350         case PA_CONTEXT_TERMINATED:
351         case PA_CONTEXT_FAILED:
352             pa_threaded_mainloop_signal(i->mainloop, 0);
353             break;
354
355         case PA_CONTEXT_UNCONNECTED:
356         case PA_CONTEXT_CONNECTING:
357         case PA_CONTEXT_AUTHORIZING:
358         case PA_CONTEXT_SETTING_NAME:
359             break;
360     }
361 }
362
363 static void reset_params(fd_info *i) {
364     assert(i);
365     
366     i->sample_spec.format = PA_SAMPLE_ULAW;
367     i->sample_spec.channels = 1;
368     i->sample_spec.rate = 8000;
369     i->fragment_size = 0;
370     i->n_fragments = 0;
371 }
372
373 static const char *client_name(char *buf, size_t n) {
374     char p[PATH_MAX];
375     const char *e;
376
377     if ((e = getenv("PADSP_CLIENT_NAME")))
378         return e;
379     
380     if (pa_get_binary_name(p, sizeof(p)))
381         snprintf(buf, n, "OSS Emulation[%s]", pa_path_get_filename(p));
382     else
383         snprintf(buf, n, "OSS");
384
385     return buf;
386 }
387
388 static const char *stream_name(void) {
389     const char *e;
390
391     if ((e = getenv("PADSP_STREAM_NAME")))
392         return e;
393
394     return "Audio Stream";
395 }
396
397 static void atfork_prepare(void) {
398     fd_info *i;
399
400     debug(__FILE__": atfork_prepare() enter\n");
401     
402     function_enter();
403
404     pthread_mutex_lock(&fd_infos_mutex);
405
406     for (i = fd_infos; i; i = i->next) {
407         pthread_mutex_lock(&i->mutex);
408         pa_threaded_mainloop_lock(i->mainloop);
409     }
410
411     pthread_mutex_lock(&func_mutex);
412
413     
414     debug(__FILE__": atfork_prepare() exit\n");
415 }
416
417 static void atfork_parent(void) {
418     fd_info *i;
419     
420     debug(__FILE__": atfork_parent() enter\n");
421
422     pthread_mutex_unlock(&func_mutex);
423
424     for (i = fd_infos; i; i = i->next) {
425         pa_threaded_mainloop_unlock(i->mainloop);
426         pthread_mutex_unlock(&i->mutex);
427     }
428
429     pthread_mutex_unlock(&fd_infos_mutex);
430
431     function_exit();
432     
433     debug(__FILE__": atfork_parent() exit\n");
434 }
435
436 static void atfork_child(void) {
437     fd_info *i;
438     
439     debug(__FILE__": atfork_child() enter\n");
440
441     /* We do only the bare minimum to get all fds closed */
442     pthread_mutex_init(&func_mutex, NULL);
443     pthread_mutex_init(&fd_infos_mutex, NULL);
444     
445     for (i = fd_infos; i; i = i->next) {
446         pthread_mutex_init(&i->mutex, NULL);
447
448         if (i->context) {
449             pa_context_disconnect(i->context);
450             pa_context_unref(i->context);
451             i->context = NULL;
452         }
453
454         if (i->stream) {
455             pa_stream_unref(i->stream);
456             i->stream = NULL;
457         }
458
459         if (i->app_fd >= 0) {
460             close(i->app_fd);
461             i->app_fd = -1;
462         }
463
464         if (i->thread_fd >= 0) {
465             close(i->thread_fd);
466             i->thread_fd = -1;
467         }
468
469         i->unusable = 1;
470     }
471
472     function_exit();
473
474     debug(__FILE__": atfork_child() exit\n");
475 }
476
477 static void install_atfork(void) {
478     pthread_atfork(atfork_prepare, atfork_parent, atfork_child);
479 }
480
481 static void stream_success_cb(pa_stream *s, int success, void *userdata) {
482     fd_info *i = userdata;
483
484     assert(s);
485     assert(i);
486
487     i->operation_success = success;
488     pa_threaded_mainloop_signal(i->mainloop, 0);
489 }
490
491 static void context_success_cb(pa_context *c, int success, void *userdata) {
492     fd_info *i = userdata;
493
494     assert(c);
495     assert(i);
496
497     i->operation_success = success;
498     pa_threaded_mainloop_signal(i->mainloop, 0);
499 }
500
501 static fd_info* fd_info_new(fd_info_type_t type, int *_errno) {
502     fd_info *i;
503     int sfds[2] = { -1, -1 };
504     char name[64];
505     static pthread_once_t install_atfork_once = PTHREAD_ONCE_INIT;
506
507     debug(__FILE__": fd_info_new()\n");
508
509     signal(SIGPIPE, SIG_IGN); /* Yes, ugly as hell */
510
511     pthread_once(&install_atfork_once, install_atfork);
512     
513     if (!(i = malloc(sizeof(fd_info)))) {
514         *_errno = ENOMEM;
515         goto fail;
516     }
517
518     i->app_fd = i->thread_fd = -1;
519     i->type = type;
520
521     i->mainloop = NULL;
522     i->context = NULL;
523     i->stream = NULL;
524     i->io_event = NULL;
525     pthread_mutex_init(&i->mutex, NULL);
526     i->ref = 1;
527     i->buf = NULL;
528     i->unusable = 0;
529     pa_cvolume_reset(&i->volume, 2);
530     i->volume_modify_count = 0;
531     i->sink_index = (uint32_t) -1;
532     PA_LLIST_INIT(fd_info, i);
533
534     reset_params(i);
535
536     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sfds) < 0) {
537         *_errno = errno;
538         debug(__FILE__": socket() failed: %s\n", strerror(errno));
539         goto fail;
540     }
541
542     i->app_fd = sfds[0];
543     i->thread_fd = sfds[1];
544
545     if (!(i->mainloop = pa_threaded_mainloop_new())) {
546         *_errno = EIO;
547         debug(__FILE__": pa_threaded_mainloop_new() failed\n");
548         goto fail;
549     }
550
551     if (!(i->context = pa_context_new(pa_threaded_mainloop_get_api(i->mainloop), client_name(name, sizeof(name))))) {
552         *_errno = EIO;
553         debug(__FILE__": pa_context_new() failed\n");
554         goto fail;
555     }
556
557     pa_context_set_state_callback(i->context, context_state_cb, i);
558
559     if (pa_context_connect(i->context, NULL, 0, NULL) < 0) {
560         *_errno = ECONNREFUSED;
561         debug(__FILE__": pa_context_connect() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
562         goto fail;
563     }
564
565     pa_threaded_mainloop_lock(i->mainloop);
566
567     if (pa_threaded_mainloop_start(i->mainloop) < 0) {
568         *_errno = EIO;
569         debug(__FILE__": pa_threaded_mainloop_start() failed\n");
570         goto unlock_and_fail;
571     }
572
573     /* Wait until the context is ready */
574     pa_threaded_mainloop_wait(i->mainloop);
575
576     if (pa_context_get_state(i->context) != PA_CONTEXT_READY) {
577         *_errno = ECONNREFUSED;
578         debug(__FILE__": pa_context_connect() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
579         goto unlock_and_fail;
580     }
581
582     pa_threaded_mainloop_unlock(i->mainloop);
583     return i;
584
585 unlock_and_fail:
586
587     pa_threaded_mainloop_unlock(i->mainloop);
588     
589 fail:
590
591     if (i)
592         fd_info_unref(i);
593     
594     return NULL;
595 }
596
597 static void fd_info_add_to_list(fd_info *i) {
598     assert(i);
599
600     pthread_mutex_lock(&fd_infos_mutex);
601     PA_LLIST_PREPEND(fd_info, fd_infos, i);
602     pthread_mutex_unlock(&fd_infos_mutex);
603
604     fd_info_ref(i);
605 }
606
607 static void fd_info_remove_from_list(fd_info *i) {
608     assert(i);
609
610     pthread_mutex_lock(&fd_infos_mutex);
611     PA_LLIST_REMOVE(fd_info, fd_infos, i);
612     pthread_mutex_unlock(&fd_infos_mutex);
613
614     fd_info_unref(i);
615 }
616
617 static fd_info* fd_info_find(int fd) {
618     fd_info *i;
619
620     pthread_mutex_lock(&fd_infos_mutex);
621     
622     for (i = fd_infos; i; i = i->next)
623         if (i->app_fd == fd && !i->unusable) {
624             fd_info_ref(i);
625             break;
626         }
627
628     pthread_mutex_unlock(&fd_infos_mutex);
629     
630     return i;
631 }
632
633 static void fix_metrics(fd_info *i) {
634     size_t fs;
635     char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
636
637     fs = pa_frame_size(&i->sample_spec);
638     i->fragment_size = (i->fragment_size/fs)*fs;
639
640     /* Number of fragments set? */
641     if (i->n_fragments < 2) {
642         if (i->fragment_size > 0) {
643             i->n_fragments = pa_bytes_per_second(&i->sample_spec) / 2 / i->fragment_size;
644             if (i->n_fragments < 2)
645                 i->n_fragments = 2;
646         } else
647             i->n_fragments = 12;
648     }
649
650     /* Fragment size set? */
651     if (i->fragment_size <= 0) {
652         i->fragment_size = pa_bytes_per_second(&i->sample_spec) / 2 / i->n_fragments;
653         if (i->fragment_size < 1024)
654             i->fragment_size = 1024;
655     }
656
657     debug(__FILE__": sample spec: %s\n", pa_sample_spec_snprint(t, sizeof(t), &i->sample_spec));
658     debug(__FILE__": fixated metrics to %i fragments, %li bytes each.\n", i->n_fragments, (long)i->fragment_size);
659 }
660
661 static void stream_request_cb(pa_stream *s, size_t length, void *userdata) {
662     fd_info *i = userdata;
663     assert(s);
664
665     if (i->io_event) {
666         pa_mainloop_api *api;
667         api = pa_threaded_mainloop_get_api(i->mainloop);
668         api->io_enable(i->io_event, PA_IO_EVENT_INPUT);
669     }
670 }
671
672 static void stream_latency_update_cb(pa_stream *s, void *userdata) {
673     fd_info *i = userdata;
674     assert(s);
675
676     pa_threaded_mainloop_signal(i->mainloop, 0);
677 }
678
679 static void fd_info_shutdown(fd_info *i) {
680     assert(i);
681
682     if (i->io_event) {
683         pa_mainloop_api *api;
684         api = pa_threaded_mainloop_get_api(i->mainloop);
685         api->io_free(i->io_event);
686         i->io_event = NULL;
687     }
688
689     if (i->thread_fd >= 0) {
690         close(i->thread_fd);
691         i->thread_fd = -1;
692     }
693 }
694
695 static int fd_info_copy_data(fd_info *i, int force) {
696     size_t n;
697
698     if (!i->stream)
699         return -1;
700
701     if ((n = pa_stream_writable_size(i->stream)) == (size_t) -1) {
702         debug(__FILE__": pa_stream_writable_size(): %s\n", pa_strerror(pa_context_errno(i->context)));
703         return -1;
704     }
705     
706     while (n >= i->fragment_size || force) {
707         ssize_t r;
708         
709         if (!i->buf) {
710             if (!(i->buf = malloc(i->fragment_size))) {
711                 debug(__FILE__": malloc() failed.\n");
712                 return -1;
713             }
714         }
715     
716         if ((r = read(i->thread_fd, i->buf, i->fragment_size)) <= 0) {
717
718             if (errno == EAGAIN)
719                 break;
720             
721             debug(__FILE__": read(): %s\n", r == 0 ? "EOF" : strerror(errno));
722             return -1;
723         }
724     
725         if (pa_stream_write(i->stream, i->buf, r, free, 0, PA_SEEK_RELATIVE) < 0) {
726             debug(__FILE__": pa_stream_write(): %s\n", pa_strerror(pa_context_errno(i->context)));
727             return -1;
728         }
729
730         i->buf = NULL;
731
732         assert(n >= (size_t) r);
733         n -= r;
734     }
735
736     if (i->io_event) {
737         pa_mainloop_api *api;
738         api = pa_threaded_mainloop_get_api(i->mainloop);
739         api->io_enable(i->io_event, n >= i->fragment_size ? PA_IO_EVENT_INPUT : 0);
740     }
741
742     return 0;
743 }
744
745 static void stream_state_cb(pa_stream *s, void * userdata) {
746     fd_info *i = userdata;
747     assert(s);
748
749     switch (pa_stream_get_state(s)) {
750
751         case PA_STREAM_READY:
752             debug(__FILE__": stream established.\n");
753             break;
754             
755         case PA_STREAM_FAILED:
756             debug(__FILE__": pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
757             fd_info_shutdown(i);
758             break;
759
760         case PA_STREAM_TERMINATED:
761         case PA_STREAM_UNCONNECTED:
762         case PA_STREAM_CREATING:
763             break;
764     }
765 }
766
767 static int create_stream(fd_info *i) {
768     pa_buffer_attr attr;
769     int n;
770     
771     assert(i);
772
773     fix_metrics(i);
774
775     if (!(i->stream = pa_stream_new(i->context, stream_name(), &i->sample_spec, NULL))) {
776         debug(__FILE__": pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
777         goto fail;
778     }
779
780     pa_stream_set_state_callback(i->stream, stream_state_cb, i);
781     pa_stream_set_write_callback(i->stream, stream_request_cb, i);
782     pa_stream_set_latency_update_callback(i->stream, stream_latency_update_cb, i);
783
784     memset(&attr, 0, sizeof(attr));
785     attr.maxlength = i->fragment_size * (i->n_fragments+1);
786     attr.tlength = i->fragment_size * i->n_fragments;
787     attr.prebuf = i->fragment_size;
788     attr.minreq = i->fragment_size;
789     
790     if (pa_stream_connect_playback(i->stream, NULL, &attr, PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE, NULL, NULL) < 0) {
791         debug(__FILE__": pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(i->context)));
792         goto fail;
793     }
794
795     n = i->fragment_size;
796     setsockopt(i->app_fd, SOL_SOCKET, SO_SNDBUF, &n, sizeof(n));
797     n = i->fragment_size;
798     setsockopt(i->thread_fd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n));
799     
800     return 0;
801
802 fail:
803     return -1;
804 }
805
806 static void free_stream(fd_info *i) {
807     assert(i);
808
809     if (i->stream) {
810         pa_stream_disconnect(i->stream);
811         pa_stream_unref(i->stream);
812         i->stream = NULL;
813     }
814 }
815
816 static void io_event_cb(pa_mainloop_api *api, pa_io_event *e, int fd, pa_io_event_flags_t flags, void *userdata) {
817     fd_info *i = userdata;
818
819     pa_threaded_mainloop_signal(i->mainloop, 0);
820     
821     if (flags & PA_IO_EVENT_INPUT) {
822
823         if (!i->stream) {
824             api->io_enable(e, 0);
825
826             if (create_stream(i) < 0)
827                 goto fail;
828
829         } else {
830             if (fd_info_copy_data(i, 0) < 0)
831                 goto fail;
832         }
833         
834     } else if (flags & (PA_IO_EVENT_HANGUP|PA_IO_EVENT_ERROR))
835         goto fail;
836
837     return;
838     
839 fail:
840     /* We can't do anything better than removing the event source */
841     fd_info_shutdown(i);
842 }
843
844 static int dsp_open(int flags, int *_errno) {
845     fd_info *i;
846     pa_mainloop_api *api;
847     int ret;
848     int f;
849
850     if ((flags != O_WRONLY) && (flags != (O_WRONLY|O_NONBLOCK))) {
851         *_errno = EACCES;
852         return -1;
853     }
854     
855     if (!(i = fd_info_new(FD_INFO_PLAYBACK, _errno)))
856         return -1;
857
858     shutdown(i->thread_fd, SHUT_WR);
859     shutdown(i->app_fd, SHUT_RD);
860
861     if ((flags & O_NONBLOCK) == O_NONBLOCK) {
862         if ((f = fcntl(i->app_fd, F_GETFL)) >= 0)
863             fcntl(i->app_fd, F_SETFL, f|O_NONBLOCK);
864     }
865     if ((f = fcntl(i->thread_fd, F_GETFL)) >= 0)
866         fcntl(i->thread_fd, F_SETFL, f|O_NONBLOCK);
867
868     fcntl(i->app_fd, F_SETFD, FD_CLOEXEC);
869     fcntl(i->thread_fd, F_SETFD, FD_CLOEXEC);
870
871     pa_threaded_mainloop_lock(i->mainloop);
872     api = pa_threaded_mainloop_get_api(i->mainloop);
873     if (!(i->io_event = api->io_new(api, i->thread_fd, PA_IO_EVENT_INPUT, io_event_cb, i)))
874         goto fail;
875     
876     pa_threaded_mainloop_unlock(i->mainloop);
877
878     debug(__FILE__": dsp_open() succeeded, fd=%i\n", i->app_fd);
879
880     fd_info_add_to_list(i);
881     ret = i->app_fd;
882     fd_info_unref(i);
883     
884     return ret;
885
886 fail:
887     pa_threaded_mainloop_unlock(i->mainloop);
888
889     if (i)
890         fd_info_unref(i);
891     
892     *_errno = EIO;
893
894     debug(__FILE__": dsp_open() failed\n");
895
896     return -1;
897 }
898
899 static void sink_info_cb(pa_context *context, const pa_sink_info *si, int eol, void *userdata) {
900     fd_info *i = userdata;
901
902     if (!si && eol < 0) {
903         i->operation_success = 0;
904         pa_threaded_mainloop_signal(i->mainloop, 0);
905         return;
906     }
907
908     if (eol)
909         return;
910
911     if (!pa_cvolume_equal(&i->volume, &si->volume))
912         i->volume_modify_count++;
913     
914     i->volume = si->volume;
915     i->sink_index = si->index;
916
917     i->operation_success = 1;
918     pa_threaded_mainloop_signal(i->mainloop, 0);
919 }
920
921 static void subscribe_cb(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) {
922     fd_info *i = userdata;
923     pa_operation *o = NULL;
924
925     if (i->sink_index != idx)
926         return;
927
928     if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) != PA_SUBSCRIPTION_EVENT_CHANGE)
929         return;
930
931     if (!(o = pa_context_get_sink_info_by_index(i->context, i->sink_index, sink_info_cb, i))) {
932         debug(__FILE__": Failed to get sink info: %s", pa_strerror(pa_context_errno(i->context)));
933         return;
934     }
935
936     pa_operation_unref(o);
937 }
938
939 static int mixer_open(int flags, int *_errno) {
940     fd_info *i;
941     pa_operation *o;
942     int ret;
943
944     if (!(i = fd_info_new(FD_INFO_MIXER, _errno))) 
945         return -1;
946     
947     pa_threaded_mainloop_lock(i->mainloop);
948
949     pa_context_set_subscribe_callback(i->context, subscribe_cb, i);
950     
951     if (!(o = pa_context_subscribe(i->context, PA_SUBSCRIPTION_MASK_SINK, context_success_cb, i))) {
952         debug(__FILE__": Failed to subscribe to events: %s", pa_strerror(pa_context_errno(i->context)));
953         *_errno = EIO;
954         goto fail;
955     }
956
957     i->operation_success = 0;
958     while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
959         pa_threaded_mainloop_wait(i->mainloop);
960         CONTEXT_CHECK_DEAD_GOTO(i, fail);
961     }
962
963     if (!i->operation_success) {
964         debug(__FILE__":Failed to subscribe to events: %s", pa_strerror(pa_context_errno(i->context)));
965         *_errno = EIO;
966         goto fail;
967     }
968
969     /* Get sink info */
970
971     pa_operation_unref(o);
972     if (!(o = pa_context_get_sink_info_by_name(i->context, NULL, sink_info_cb, i))) {
973         debug(__FILE__": Failed to get sink info: %s", pa_strerror(pa_context_errno(i->context)));
974         *_errno = EIO;
975         goto fail;
976     }
977
978     i->operation_success = 0;
979     while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
980         pa_threaded_mainloop_wait(i->mainloop);
981         CONTEXT_CHECK_DEAD_GOTO(i, fail);
982     }
983
984     if (!i->operation_success) {
985         debug(__FILE__": Failed to get sink info: %s", pa_strerror(pa_context_errno(i->context)));
986         *_errno = EIO;
987         goto fail;
988     }
989
990     pa_threaded_mainloop_unlock(i->mainloop);
991
992     debug(__FILE__": mixer_open() succeeded, fd=%i\n", i->app_fd);
993
994     fd_info_add_to_list(i);
995     ret = i->app_fd;
996     fd_info_unref(i);
997     
998     return ret;
999
1000 fail:
1001     pa_threaded_mainloop_unlock(i->mainloop);
1002
1003     if (i)
1004         fd_info_unref(i);
1005     
1006     *_errno = EIO;
1007
1008     debug(__FILE__": mixer_open() failed\n");
1009
1010     return -1;
1011 }
1012
1013 static int sndstat_open(int flags, int *_errno) {
1014     static const char sndstat[] =
1015         "Sound Driver:3.8.1a-980706 (Polypaudio Virtual OSS)\n"
1016         "Kernel: POSIX\n"
1017         "Config options: 0\n"
1018         "\n"
1019         "Installed drivers:\n"
1020         "Type 255: Polypaudio Virtual OSS\n"
1021         "\n"
1022         "Card config:\n"
1023         "Polypaudio Virtual OSS\n"
1024         "\n"
1025         "Audio devices:\n"
1026         "0: Polypaudio Virtual OSS\n"
1027         "\n"
1028         "Synth devices: NOT ENABLED IN CONFIG\n"
1029         "\n"
1030         "Midi devices:\n"
1031         "\n"
1032         "Timers:\n"
1033         "\n"
1034         "Mixers:\n"
1035         "0: Polypaudio Virtual OSS\n";
1036
1037     char fn[] = "/tmp/padsp-sndstat-XXXXXX";
1038     mode_t u;
1039     int fd = -1;
1040     int e;
1041
1042     debug(__FILE__": sndstat_open()\n");
1043     
1044     if (flags != O_RDONLY && flags != (O_RDONLY|O_LARGEFILE)) {
1045         *_errno = EACCES;
1046         debug(__FILE__": bad access!\n");
1047         goto fail;
1048     }
1049
1050     u = umask(0077);
1051     fd = mkstemp(fn);
1052     e = errno;
1053     umask(u);
1054
1055     if (fd < 0) {
1056         *_errno = e;
1057         debug(__FILE__": mkstemp() failed: %s\n", strerror(errno));
1058         goto fail;
1059     }
1060
1061     unlink(fn);
1062
1063     if (write(fd, sndstat, sizeof(sndstat) -1) != sizeof(sndstat)-1) {
1064         *_errno = errno;
1065         debug(__FILE__": write() failed: %s\n", strerror(errno));
1066         goto fail;
1067     }
1068
1069     if (lseek(fd, SEEK_SET, 0) < 0) {
1070         *_errno = errno;
1071         debug(__FILE__": lseek() failed: %s\n", strerror(errno));
1072         goto fail;
1073     }
1074
1075     return fd;
1076
1077 fail:
1078     if (fd >= 0)
1079         close(fd);
1080     return -1;
1081 }
1082
1083 int open(const char *filename, int flags, ...) {
1084     va_list args;
1085     mode_t mode = 0;
1086     int r, _errno = 0;
1087
1088     debug(__FILE__": open(%s)\n", filename);
1089
1090     va_start(args, flags);
1091     if (flags & O_CREAT)
1092         mode = va_arg(args, mode_t);
1093     va_end(args);
1094
1095     if (!function_enter()) {
1096         LOAD_OPEN_FUNC();
1097         return _open(filename, flags, mode);
1098     }
1099
1100     if (dsp_cloak_enable() && (strcmp(filename, "/dev/dsp") == 0 || strcmp(filename, "/dev/adsp") == 0)) {
1101         r = dsp_open(flags, &_errno);
1102     } else if (mixer_cloak_enable() && strcmp(filename, "/dev/mixer") == 0) {
1103         r = mixer_open(flags, &_errno);
1104     } else if (sndstat_cloak_enable() && strcmp(filename, "/dev/sndstat") == 0) {
1105         r = sndstat_open(flags, &_errno);
1106     } else {
1107         function_exit();
1108         LOAD_OPEN_FUNC();
1109         return _open(filename, flags, mode);
1110     }
1111
1112     function_exit();
1113     
1114     if (_errno)
1115         errno = _errno;
1116     
1117     return r;
1118 }
1119
1120 static int mixer_ioctl(fd_info *i, unsigned long request, void*argp, int *_errno) {
1121     int ret = -1;
1122     
1123     switch (request) {
1124         case SOUND_MIXER_READ_DEVMASK :
1125             debug(__FILE__": SOUND_MIXER_READ_DEVMASK\n");
1126
1127             *(int*) argp = SOUND_MASK_PCM;
1128             break;
1129
1130         case SOUND_MIXER_READ_RECMASK :
1131             debug(__FILE__": SOUND_MIXER_READ_RECMASK\n");
1132
1133             *(int*) argp = 0;
1134             break;
1135             
1136         case SOUND_MIXER_READ_STEREODEVS:
1137             debug(__FILE__": SOUND_MIXER_READ_STEREODEVS\n");
1138
1139             pa_threaded_mainloop_lock(i->mainloop);
1140             *(int*) argp = i->volume.channels > 1 ? SOUND_MASK_PCM : 0;
1141             pa_threaded_mainloop_unlock(i->mainloop);
1142             
1143             break;
1144
1145         case SOUND_MIXER_READ_RECSRC:
1146             debug(__FILE__": SOUND_MIXER_READ_RECSRC\n");
1147
1148             *(int*) argp = 0;
1149             break;
1150             
1151         case SOUND_MIXER_READ_CAPS:
1152             debug(__FILE__": SOUND_MIXER_READ_CAPS\n");
1153
1154             *(int*) argp = 0;
1155             break;
1156     
1157         case SOUND_MIXER_READ_PCM:
1158             
1159             debug(__FILE__": SOUND_MIXER_READ_PCM\n");
1160             
1161             pa_threaded_mainloop_lock(i->mainloop);
1162
1163             *(int*) argp =
1164                 ((i->volume.values[0]*100/PA_VOLUME_NORM)) |
1165                 ((i->volume.values[i->volume.channels > 1 ? 1 : 0]*100/PA_VOLUME_NORM)  << 8);
1166             
1167             pa_threaded_mainloop_unlock(i->mainloop);
1168             
1169             break;
1170
1171         case SOUND_MIXER_WRITE_PCM: {
1172             pa_cvolume v;
1173             
1174             debug(__FILE__": SOUND_MIXER_WRITE_PCM\n");
1175             
1176             pa_threaded_mainloop_lock(i->mainloop);
1177
1178             v = i->volume;
1179             
1180             i->volume.values[0] = ((*(int*) argp & 0xFF)*PA_VOLUME_NORM)/100;
1181             i->volume.values[1] = ((*(int*) argp >> 8)*PA_VOLUME_NORM)/100;
1182
1183             if (!pa_cvolume_equal(&i->volume, &v)) {
1184                 pa_operation *o;
1185                 
1186                 if (!(o = pa_context_set_sink_volume_by_index(i->context, i->sink_index, &i->volume, NULL, NULL)))
1187                     debug(__FILE__":Failed set volume: %s", pa_strerror(pa_context_errno(i->context)));
1188                 else {
1189
1190                     i->operation_success = 0;
1191                     while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
1192                         CONTEXT_CHECK_DEAD_GOTO(i, exit_loop);
1193                         
1194                         pa_threaded_mainloop_wait(i->mainloop);
1195                     }
1196                 exit_loop:
1197                     
1198                     if (!i->operation_success)
1199                         debug(__FILE__": Failed to set volume: %s\n", pa_strerror(pa_context_errno(i->context)));
1200
1201                     pa_operation_unref(o);
1202                 }
1203                 
1204                 /* We don't wait for completion here */
1205                 i->volume_modify_count++;
1206             }
1207             
1208             pa_threaded_mainloop_unlock(i->mainloop);
1209             
1210             break;
1211         }
1212
1213         case SOUND_MIXER_INFO: {
1214             mixer_info *mi = argp;
1215
1216             memset(mi, 0, sizeof(mixer_info));
1217             strncpy(mi->id, "POLYPAUDIO", sizeof(mi->id));
1218             strncpy(mi->name, "Polypaudio Virtual OSS", sizeof(mi->name));
1219             pa_threaded_mainloop_lock(i->mainloop);
1220             mi->modify_counter = i->volume_modify_count;
1221             pa_threaded_mainloop_unlock(i->mainloop);
1222             break;
1223         }
1224             
1225         default:
1226             debug(__FILE__": unknown ioctl 0x%08lx\n", request);
1227
1228             *_errno = EINVAL;
1229             goto fail;
1230     }
1231
1232     ret = 0;
1233     
1234 fail:
1235     
1236     return ret;
1237 }
1238
1239 static int map_format(int *fmt, pa_sample_spec *ss) {
1240     
1241     switch (*fmt) {
1242         case AFMT_MU_LAW:
1243             ss->format = PA_SAMPLE_ULAW;
1244             break;
1245             
1246         case AFMT_A_LAW:
1247             ss->format = PA_SAMPLE_ALAW;
1248             break;
1249             
1250         case AFMT_S8:
1251             *fmt = AFMT_U8;
1252             /* fall through */
1253         case AFMT_U8:
1254             ss->format = PA_SAMPLE_U8;
1255             break;
1256             
1257         case AFMT_U16_BE:
1258             *fmt = AFMT_S16_BE;
1259             /* fall through */
1260         case AFMT_S16_BE:
1261             ss->format = PA_SAMPLE_S16BE;
1262             break;
1263             
1264         case AFMT_U16_LE:
1265             *fmt = AFMT_S16_LE;
1266             /* fall through */
1267         case AFMT_S16_LE:
1268             ss->format = PA_SAMPLE_S16LE;
1269             break;
1270             
1271         default:
1272             ss->format = PA_SAMPLE_S16NE;
1273             *fmt = AFMT_S16_NE;
1274             break;
1275     }
1276
1277     return 0;
1278 }
1279
1280 static int map_format_back(pa_sample_format_t format) {
1281     switch (format) {
1282         case PA_SAMPLE_S16LE: return AFMT_S16_LE;
1283         case PA_SAMPLE_S16BE: return AFMT_S16_BE;
1284         case PA_SAMPLE_ULAW: return AFMT_MU_LAW;
1285         case PA_SAMPLE_ALAW: return AFMT_A_LAW;
1286         case PA_SAMPLE_U8: return AFMT_U8;
1287         default:
1288             abort();
1289     }
1290 }
1291
1292 static int dsp_flush_socket(fd_info *i) {
1293     int l;
1294         
1295     if (i->thread_fd < 0)
1296         return -1;
1297
1298     if (ioctl(i->thread_fd, SIOCINQ, &l) < 0) {
1299         debug(__FILE__": SIOCINQ: %s\n", strerror(errno));
1300         return -1;
1301     }
1302
1303     while (l > 0) {
1304         char buf[1024];
1305         size_t k;
1306
1307         k = (size_t) l > sizeof(buf) ? sizeof(buf) : (size_t) l;
1308         if (read(i->thread_fd, buf, k) < 0)
1309             debug(__FILE__": read(): %s\n", strerror(errno));
1310         l -= k;
1311     }
1312
1313     return 0;
1314 }
1315
1316 static int dsp_empty_socket(fd_info *i) {
1317     int ret = -1;
1318     
1319     /* Empty the socket */
1320     for (;;) {
1321         int l;
1322         
1323         if (i->thread_fd < 0)
1324             break;
1325         
1326         if (ioctl(i->thread_fd, SIOCINQ, &l) < 0) {
1327             debug(__FILE__": SIOCINQ: %s\n", strerror(errno));
1328             break;
1329         }
1330
1331         if (!l) {
1332             ret = 0;
1333             break;
1334         }
1335         
1336         pa_threaded_mainloop_wait(i->mainloop);
1337     }
1338
1339     return ret;
1340 }
1341
1342 static int dsp_drain(fd_info *i) {
1343     pa_operation *o = NULL;
1344     int r = -1;
1345
1346     if (!i->mainloop)
1347         return 0;
1348     
1349     debug(__FILE__": Draining.\n");
1350
1351     pa_threaded_mainloop_lock(i->mainloop);
1352
1353     if (dsp_empty_socket(i) < 0)
1354         goto fail;
1355     
1356     if (!i->stream)
1357         goto fail;
1358
1359     debug(__FILE__": Really draining.\n");
1360         
1361     if (!(o = pa_stream_drain(i->stream, stream_success_cb, i))) {
1362         debug(__FILE__": pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(i->context)));
1363         goto fail;
1364     }
1365
1366     i->operation_success = 0;
1367     while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
1368         STREAM_CHECK_DEAD_GOTO(i, fail);
1369             
1370         pa_threaded_mainloop_wait(i->mainloop);
1371     }
1372
1373     if (!i->operation_success) {
1374         debug(__FILE__": pa_stream_drain() 2: %s\n", pa_strerror(pa_context_errno(i->context)));
1375         goto fail;
1376     }
1377
1378     r = 0;
1379     
1380 fail:
1381     
1382     if (o)
1383         pa_operation_unref(o);
1384
1385     pa_threaded_mainloop_unlock(i->mainloop);
1386
1387     return 0;
1388 }
1389
1390 static int dsp_trigger(fd_info *i) {
1391     pa_operation *o = NULL;
1392     int r = -1;
1393
1394     if (!i->stream)
1395         return 0;
1396
1397     pa_threaded_mainloop_lock(i->mainloop);
1398
1399     if (dsp_empty_socket(i) < 0)
1400         goto fail;
1401
1402     debug(__FILE__": Triggering.\n");
1403         
1404     if (!(o = pa_stream_trigger(i->stream, stream_success_cb, i))) {
1405         debug(__FILE__": pa_stream_trigger(): %s\n", pa_strerror(pa_context_errno(i->context)));
1406         goto fail;
1407     }
1408
1409     i->operation_success = 0;
1410     while (!pa_operation_get_state(o) != PA_OPERATION_DONE) {
1411         STREAM_CHECK_DEAD_GOTO(i, fail);
1412             
1413         pa_threaded_mainloop_wait(i->mainloop);
1414     }
1415
1416     if (!i->operation_success) {
1417         debug(__FILE__": pa_stream_trigger(): %s\n", pa_strerror(pa_context_errno(i->context)));
1418         goto fail;
1419     }
1420
1421     r = 0;
1422     
1423 fail:
1424     
1425     if (o)
1426         pa_operation_unref(o);
1427
1428     pa_threaded_mainloop_unlock(i->mainloop);
1429
1430     return 0;
1431 }
1432
1433 static int dsp_ioctl(fd_info *i, unsigned long request, void*argp, int *_errno) {
1434     int ret = -1;
1435     
1436     switch (request) {
1437         case SNDCTL_DSP_SETFMT: {
1438             debug(__FILE__": SNDCTL_DSP_SETFMT: %i\n", *(int*) argp);
1439             
1440             pa_threaded_mainloop_lock(i->mainloop);
1441
1442             if (*(int*) argp == AFMT_QUERY)
1443                 *(int*) argp = map_format_back(i->sample_spec.format);
1444             else {
1445                 map_format((int*) argp, &i->sample_spec);
1446                 free_stream(i);
1447             }
1448
1449             pa_threaded_mainloop_unlock(i->mainloop);
1450             break;
1451         }
1452             
1453         case SNDCTL_DSP_SPEED: {
1454             pa_sample_spec ss;
1455             int valid;
1456             char t[256];
1457             
1458             debug(__FILE__": SNDCTL_DSP_SPEED: %i\n", *(int*) argp);
1459
1460             pa_threaded_mainloop_lock(i->mainloop);
1461
1462             ss = i->sample_spec;
1463             ss.rate = *(int*) argp;
1464
1465             if ((valid = pa_sample_spec_valid(&ss))) {
1466                 i->sample_spec = ss;
1467                 free_stream(i);
1468             }
1469             
1470             debug(__FILE__": ss: %s\n", pa_sample_spec_snprint(t, sizeof(t), &i->sample_spec));
1471
1472             pa_threaded_mainloop_unlock(i->mainloop);
1473
1474             if (!valid) {
1475                 *_errno = EINVAL;
1476                 goto fail;
1477             }
1478
1479             break;
1480         }
1481             
1482         case SNDCTL_DSP_STEREO:
1483             debug(__FILE__": SNDCTL_DSP_STEREO: %i\n", *(int*) argp);
1484             
1485             pa_threaded_mainloop_lock(i->mainloop);
1486             
1487             i->sample_spec.channels = *(int*) argp ? 2 : 1;
1488             free_stream(i);
1489             
1490             pa_threaded_mainloop_unlock(i->mainloop);
1491             return 0;
1492
1493         case SNDCTL_DSP_CHANNELS: {
1494             pa_sample_spec ss;
1495             int valid;
1496             
1497             debug(__FILE__": SNDCTL_DSP_CHANNELS: %i\n", *(int*) argp);
1498             
1499             pa_threaded_mainloop_lock(i->mainloop);
1500
1501             ss = i->sample_spec;
1502             ss.channels = *(int*) argp;
1503
1504             if ((valid = pa_sample_spec_valid(&ss))) {
1505                 i->sample_spec = ss;
1506                 free_stream(i);
1507             }
1508             
1509             pa_threaded_mainloop_unlock(i->mainloop);
1510
1511             if (!valid) {
1512                 *_errno = EINVAL;
1513                 goto fail;
1514             }
1515
1516             break;
1517         }
1518
1519         case SNDCTL_DSP_GETBLKSIZE:
1520             debug(__FILE__": SNDCTL_DSP_GETBLKSIZE\n");
1521
1522             pa_threaded_mainloop_lock(i->mainloop);
1523
1524             fix_metrics(i);
1525             *(int*) argp = i->fragment_size;
1526             
1527             pa_threaded_mainloop_unlock(i->mainloop);
1528             
1529             break;
1530
1531         case SNDCTL_DSP_SETFRAGMENT:
1532             debug(__FILE__": SNDCTL_DSP_SETFRAGMENT: 0x%8x\n", *(int*) argp);
1533             
1534             pa_threaded_mainloop_lock(i->mainloop);
1535             
1536             i->fragment_size = 1 << (*(int*) argp);
1537             i->n_fragments = (*(int*) argp) >> 16;
1538             
1539             free_stream(i);
1540             
1541             pa_threaded_mainloop_unlock(i->mainloop);
1542             
1543             break;
1544             
1545         case SNDCTL_DSP_GETCAPS:
1546             debug(__FILE__": SNDCTL_DSP_CAPS\n");
1547             
1548             *(int*)  argp = DSP_CAP_MULTI;
1549             break;
1550
1551         case SNDCTL_DSP_GETODELAY: {
1552             int l;
1553             
1554             debug(__FILE__": SNDCTL_DSP_GETODELAY\n");
1555             
1556             pa_threaded_mainloop_lock(i->mainloop);
1557
1558             *(int*) argp = 0;
1559             
1560             for (;;) {
1561                 pa_usec_t usec;
1562
1563                 STREAM_CHECK_DEAD_GOTO(i, exit_loop);
1564
1565                 if (pa_stream_get_latency(i->stream, &usec, NULL) >= 0) {
1566                     *(int*) argp = pa_usec_to_bytes(usec, &i->sample_spec);
1567                     break;
1568                 }
1569
1570                 if (pa_context_errno(i->context) != PA_ERR_NODATA) {
1571                     debug(__FILE__": pa_stream_get_latency(): %s\n", pa_strerror(pa_context_errno(i->context)));
1572                     break;
1573                 }
1574
1575                 pa_threaded_mainloop_wait(i->mainloop);
1576             }
1577             
1578         exit_loop:
1579             
1580             if (ioctl(i->thread_fd, SIOCINQ, &l) < 0)
1581                 debug(__FILE__": SIOCINQ failed: %s\n", strerror(errno));
1582             else
1583                 *(int*) argp += l;
1584
1585             pa_threaded_mainloop_unlock(i->mainloop);
1586
1587             debug(__FILE__": ODELAY: %i\n", *(int*) argp);
1588
1589             break;
1590         }
1591             
1592         case SNDCTL_DSP_RESET: {
1593             debug(__FILE__": SNDCTL_DSP_RESET\n");
1594             
1595             pa_threaded_mainloop_lock(i->mainloop);
1596
1597             free_stream(i);
1598             dsp_flush_socket(i);
1599             reset_params(i);
1600             
1601             pa_threaded_mainloop_unlock(i->mainloop);
1602             break;
1603         }
1604             
1605         case SNDCTL_DSP_GETFMTS: {
1606             debug(__FILE__": SNDCTL_DSP_GETFMTS\n");
1607             
1608             *(int*) argp = AFMT_MU_LAW|AFMT_A_LAW|AFMT_U8|AFMT_S16_LE|AFMT_S16_BE;
1609             break;
1610         }
1611
1612         case SNDCTL_DSP_POST:
1613             debug(__FILE__": SNDCTL_DSP_POST\n");
1614             
1615             if (dsp_trigger(i) < 0) 
1616                 *_errno = EIO;
1617             break;
1618
1619         case SNDCTL_DSP_SYNC: 
1620             debug(__FILE__": SNDCTL_DSP_SYNC\n");
1621             
1622             if (dsp_drain(i) < 0) 
1623                 *_errno = EIO;
1624
1625             break;
1626
1627         case SNDCTL_DSP_GETOSPACE: {
1628             audio_buf_info *bi = (audio_buf_info*) argp;
1629             int l;
1630             size_t k = 0;
1631
1632             debug(__FILE__": SNDCTL_DSP_GETOSPACE\n");
1633
1634             pa_threaded_mainloop_lock(i->mainloop);
1635
1636             fix_metrics(i);
1637             
1638             if (i->stream) {
1639                 if ((k = pa_stream_writable_size(i->stream)) == (size_t) -1)
1640                     debug(__FILE__": pa_stream_writable_size(): %s\n", pa_strerror(pa_context_errno(i->context)));
1641             } else
1642                 k = i->fragment_size * i->n_fragments;
1643             
1644             if (ioctl(i->thread_fd, SIOCINQ, &l) < 0) {
1645                 debug(__FILE__": SIOCINQ failed: %s\n", strerror(errno));
1646                 l = 0;
1647             }
1648
1649             bi->fragsize = i->fragment_size;
1650             bi->fragstotal = i->n_fragments;
1651             bi->bytes = k > (size_t) l ? k - l : 0;
1652             bi->fragments = bi->bytes / bi->fragsize;
1653
1654             pa_threaded_mainloop_unlock(i->mainloop);
1655
1656             debug(__FILE__": fragsize=%i, fragstotal=%i, bytes=%i, fragments=%i\n", bi->fragsize, bi->fragstotal, bi->bytes, bi->fragments);
1657
1658             break;
1659         }
1660             
1661         default:
1662             debug(__FILE__": unknwon ioctl 0x%08lx\n", request);
1663
1664             *_errno = EINVAL;
1665             goto fail;
1666     }
1667
1668     ret = 0;
1669     
1670 fail:
1671     
1672     return ret;
1673 }
1674
1675 int ioctl(int fd, unsigned long request, ...) {
1676     fd_info *i;
1677     va_list args;
1678     void *argp;
1679     int r, _errno = 0;
1680
1681     debug(__FILE__": ioctl()\n");
1682
1683     va_start(args, request);
1684     argp = va_arg(args, void *);
1685     va_end(args);
1686
1687     if (!function_enter()) {
1688         LOAD_IOCTL_FUNC();
1689         return _ioctl(fd, request, argp);
1690     }
1691
1692     if (!(i = fd_info_find(fd))) {
1693         function_exit();
1694         LOAD_IOCTL_FUNC();
1695         return _ioctl(fd, request, argp);
1696     }
1697
1698     if (i->type == FD_INFO_MIXER)
1699         r = mixer_ioctl(i, request, argp, &_errno);
1700     else
1701         r = dsp_ioctl(i, request, argp, &_errno);
1702     
1703     fd_info_unref(i);
1704
1705     if (_errno)
1706         errno = _errno;
1707
1708     function_exit();
1709     
1710     return r;
1711 }
1712
1713 int close(int fd) {
1714     fd_info *i;
1715
1716     debug(__FILE__": close()\n");
1717
1718     if (!function_enter()) {
1719         LOAD_CLOSE_FUNC();
1720         return _close(fd);
1721     }
1722
1723     if (!(i = fd_info_find(fd))) {
1724         function_exit();
1725         LOAD_CLOSE_FUNC();
1726         return _close(fd);
1727     }
1728
1729     fd_info_remove_from_list(i);
1730     fd_info_unref(i);
1731     
1732     function_exit();
1733
1734     return 0;
1735 }
1736
1737 int access(const char *pathname, int mode) {
1738     debug(__FILE__": access()\n");
1739
1740     if (strcmp(pathname, "/dev/dsp") != 0 &&
1741         strcmp(pathname, "/dev/adsp") != 0 &&
1742         strcmp(pathname, "/dev/sndstat") != 0 &&
1743         strcmp(pathname, "/dev/mixer") != 0) {
1744         LOAD_ACCESS_FUNC();
1745         return _access(pathname, mode);
1746     }
1747
1748     if (mode & (W_OK | X_OK)) {
1749         errno = EACCES;
1750         return -1;
1751     }
1752
1753     return 0;
1754 }
1755
1756 int open64(const char *filename, int flags, ...) {
1757     va_list args;
1758     mode_t mode = 0;
1759
1760     debug(__FILE__": open64(%s)\n", filename);
1761     
1762     va_start(args, flags);
1763     if (flags & O_CREAT)
1764         mode = va_arg(args, mode_t);
1765     va_end(args);
1766
1767     if (strcmp(filename, "/dev/dsp") != 0 &&
1768         strcmp(filename, "/dev/adsp") != 0 &&
1769         strcmp(filename, "/dev/sndstat") != 0 &&
1770         strcmp(filename, "/dev/mixer") != 0) {
1771         LOAD_OPEN64_FUNC();
1772         return _open64(filename, flags, mode);
1773     }
1774
1775     return open(filename, flags, mode);
1776 }
1777
1778 FILE* fopen(const char *filename, const char *mode) {
1779     FILE *f = NULL;
1780     int fd;
1781     mode_t m;
1782     
1783     debug(__FILE__": fopen(%s)\n", filename);
1784
1785     if (strcmp(filename, "/dev/dsp") == 0 ||
1786         strcmp(filename, "/dev/adsp") == 0) {
1787
1788         if (strcmp(mode, "wb") != 0) {
1789             errno = EACCES;
1790             return NULL;
1791         }
1792
1793         m = O_WRONLY;
1794     } else if (strcmp(filename, "/dev/sndstat") == 0) {
1795
1796         if (strcmp(mode, "r") != 0) {
1797             errno = EACCES;
1798             return NULL;
1799         }
1800
1801         m = O_RDONLY;
1802     } else if (strcmp(filename, "/dev/mixer") == 0)
1803         m = O_RDWR;
1804     else {
1805         LOAD_FOPEN_FUNC();
1806         return _fopen(filename, mode);
1807     }
1808
1809     if ((fd = open(filename, m)) < 0)
1810         return NULL;
1811
1812     if (!(f = fdopen(fd, mode))) {
1813         close(fd);
1814         return NULL;
1815     }
1816     
1817     return f;
1818 }
1819
1820 FILE *fopen64(const char *filename, const char *mode) {
1821
1822     debug(__FILE__": fopen64(%s)\n", filename);
1823
1824     if (strcmp(filename, "/dev/dsp") != 0 &&
1825         strcmp(filename, "/dev/adsp") != 0 &&
1826         strcmp(filename, "/dev/sndstat") != 0 &&
1827         strcmp(filename, "/dev/mixer") != 0) {
1828         LOAD_FOPEN64_FUNC();
1829         return _fopen64(filename, mode);
1830     }
1831
1832     return fopen(filename, mode);
1833 }
1834
1835 int fclose(FILE *f) {
1836     fd_info *i;
1837
1838     debug(__FILE__": fclose()\n");
1839
1840     if (!function_enter()) {
1841         LOAD_FCLOSE_FUNC();
1842         return _fclose(f);
1843     }
1844
1845     if (!(i = fd_info_find(fileno(f)))) {
1846         function_exit();
1847         LOAD_FCLOSE_FUNC();
1848         return _fclose(f);
1849     }
1850
1851     fd_info_remove_from_list(i);
1852
1853     /* Dirty trick to avoid that the fd is not freed twice, once by us
1854      * and once by the real fclose() */
1855     i->app_fd = -1;
1856     
1857     fd_info_unref(i);
1858     
1859     function_exit();
1860
1861     LOAD_FCLOSE_FUNC();
1862     return _fclose(f);
1863 }